script: Move canvas stuff into dom/canvas folder (#39071)

Move all canvas stuff to canvas folder and 2d canvas to canvas/2d
folder. Webgl and webgpu context remain in respective folders as
outlined in
https://github.com/servo/servo/issues/38901#issuecomment-3243020235

Testing: Just refactor.
Part of https://github.com/servo/servo/issues/38901

---------

Signed-off-by: sagudev <16504129+sagudev@users.noreply.github.com>
This commit is contained in:
Sam 2025-09-02 09:43:10 +02:00 committed by GitHub
parent f4dd2960b8
commit 069ddbfd12
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
17 changed files with 138 additions and 124 deletions

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,108 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use canvas_traits::canvas::{
CanvasGradientStop, FillOrStrokeStyle, LinearGradientStyle, RadialGradientStyle,
};
use dom_struct::dom_struct;
use super::canvas_state::parse_color;
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::CanvasRenderingContext2DBinding::CanvasGradientMethods;
use crate::dom::bindings::error::{Error, ErrorResult};
use crate::dom::bindings::num::Finite;
use crate::dom::bindings::reflector::{Reflector, reflect_dom_object};
use crate::dom::bindings::root::DomRoot;
use crate::dom::bindings::str::DOMString;
use crate::dom::globalscope::GlobalScope;
use crate::script_runtime::CanGc;
// https://html.spec.whatwg.org/multipage/#canvasgradient
#[dom_struct]
pub(crate) struct CanvasGradient {
reflector_: Reflector,
style: CanvasGradientStyle,
#[no_trace]
stops: DomRefCell<Vec<CanvasGradientStop>>,
}
#[derive(Clone, JSTraceable, MallocSizeOf)]
pub(crate) enum CanvasGradientStyle {
Linear(#[no_trace] LinearGradientStyle),
Radial(#[no_trace] RadialGradientStyle),
}
impl CanvasGradient {
fn new_inherited(style: CanvasGradientStyle) -> CanvasGradient {
CanvasGradient {
reflector_: Reflector::new(),
style,
stops: DomRefCell::new(Vec::new()),
}
}
pub(crate) fn new(
global: &GlobalScope,
style: CanvasGradientStyle,
can_gc: CanGc,
) -> DomRoot<CanvasGradient> {
reflect_dom_object(
Box::new(CanvasGradient::new_inherited(style)),
global,
can_gc,
)
}
}
impl CanvasGradientMethods<crate::DomTypeHolder> for CanvasGradient {
// https://html.spec.whatwg.org/multipage/#dom-canvasgradient-addcolorstop
fn AddColorStop(&self, offset: Finite<f64>, color: DOMString) -> ErrorResult {
if *offset < 0f64 || *offset > 1f64 {
return Err(Error::IndexSize);
}
let color = match parse_color(None, &color) {
Ok(color) => color,
Err(_) => return Err(Error::Syntax(None)),
};
self.stops.borrow_mut().push(CanvasGradientStop {
offset: (*offset),
color,
});
Ok(())
}
}
pub(crate) trait ToFillOrStrokeStyle {
fn to_fill_or_stroke_style(self) -> FillOrStrokeStyle;
}
impl ToFillOrStrokeStyle for &CanvasGradient {
fn to_fill_or_stroke_style(self) -> FillOrStrokeStyle {
let gradient_stops = self.stops.borrow().clone();
match self.style {
CanvasGradientStyle::Linear(ref gradient) => {
FillOrStrokeStyle::LinearGradient(LinearGradientStyle::new(
gradient.x0,
gradient.y0,
gradient.x1,
gradient.y1,
gradient_stops,
))
},
CanvasGradientStyle::Radial(ref gradient) => {
FillOrStrokeStyle::RadialGradient(RadialGradientStyle::new(
gradient.x0,
gradient.y0,
gradient.r0,
gradient.x1,
gradient.y1,
gradient.r1,
gradient_stops,
))
},
}
}
}

View file

@ -0,0 +1,121 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use canvas_traits::canvas::{FillOrStrokeStyle, RepetitionStyle, SurfaceStyle};
use dom_struct::dom_struct;
use euclid::default::{Size2D, Transform2D};
use pixels::{IpcSnapshot, Snapshot};
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::CanvasRenderingContext2DBinding::CanvasPatternMethods;
use crate::dom::bindings::codegen::Bindings::DOMMatrixBinding::DOMMatrix2DInit;
use crate::dom::bindings::error::ErrorResult;
use crate::dom::bindings::reflector::{Reflector, reflect_dom_object};
use crate::dom::bindings::root::DomRoot;
use crate::dom::canvasgradient::ToFillOrStrokeStyle;
use crate::dom::dommatrixreadonly::dommatrix2dinit_to_matrix;
use crate::dom::globalscope::GlobalScope;
use crate::script_runtime::CanGc;
/// <https://html.spec.whatwg.org/multipage/#canvaspattern>
#[dom_struct]
pub(crate) struct CanvasPattern {
reflector_: Reflector,
#[no_trace]
surface_data: IpcSnapshot,
#[no_trace]
surface_size: Size2D<u32>,
repeat_x: bool,
repeat_y: bool,
#[no_trace]
transform: DomRefCell<Transform2D<f32>>,
origin_clean: bool,
}
impl CanvasPattern {
fn new_inherited(
surface_data: Snapshot,
surface_size: Size2D<u32>,
repeat: RepetitionStyle,
origin_clean: bool,
) -> CanvasPattern {
let (x, y) = match repeat {
RepetitionStyle::Repeat => (true, true),
RepetitionStyle::RepeatX => (true, false),
RepetitionStyle::RepeatY => (false, true),
RepetitionStyle::NoRepeat => (false, false),
};
CanvasPattern {
reflector_: Reflector::new(),
surface_data: surface_data.as_ipc(),
surface_size,
repeat_x: x,
repeat_y: y,
transform: DomRefCell::new(Transform2D::identity()),
origin_clean,
}
}
pub(crate) fn new(
global: &GlobalScope,
surface_data: Snapshot,
surface_size: Size2D<u32>,
repeat: RepetitionStyle,
origin_clean: bool,
can_gc: CanGc,
) -> DomRoot<CanvasPattern> {
reflect_dom_object(
Box::new(CanvasPattern::new_inherited(
surface_data,
surface_size,
repeat,
origin_clean,
)),
global,
can_gc,
)
}
pub(crate) fn origin_is_clean(&self) -> bool {
self.origin_clean
}
}
impl CanvasPatternMethods<crate::DomTypeHolder> for CanvasPattern {
/// <https://html.spec.whatwg.org/multipage/#dom-canvaspattern-settransform>
fn SetTransform(&self, transform: &DOMMatrix2DInit) -> ErrorResult {
// Step 1. Let matrix be the result of creating a DOMMatrix from the 2D
// dictionary transform.
let matrix = dommatrix2dinit_to_matrix(transform)?;
// Step 2. If one or more of matrix's m11 element, m12 element, m21
// element, m22 element, m41 element, or m42 element are infinite or
// NaN, then return.
if !matrix.m11.is_finite() ||
!matrix.m12.is_finite() ||
!matrix.m21.is_finite() ||
!matrix.m22.is_finite() ||
!matrix.m31.is_finite() ||
!matrix.m32.is_finite()
{
return Ok(());
}
// Step 3. Reset the pattern's transformation matrix to matrix.
*self.transform.borrow_mut() = matrix.cast();
Ok(())
}
}
impl ToFillOrStrokeStyle for &CanvasPattern {
fn to_fill_or_stroke_style(self) -> FillOrStrokeStyle {
FillOrStrokeStyle::Surface(SurfaceStyle::new(
self.surface_data.clone(),
self.surface_size,
self.repeat_x,
self.repeat_y,
*self.transform.borrow(),
))
}
}

View file

@ -0,0 +1,730 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use base::Epoch;
use canvas_traits::canvas::{Canvas2dMsg, CanvasId};
use dom_struct::dom_struct;
use euclid::default::Size2D;
use ipc_channel::ipc;
use pixels::Snapshot;
use script_bindings::inheritance::Castable;
use servo_url::ServoUrl;
use webrender_api::ImageKey;
use super::canvas_state::CanvasState;
use crate::canvas_context::{CanvasContext, CanvasHelpers, LayoutCanvasRenderingContextHelpers};
use crate::dom::bindings::codegen::Bindings::CanvasRenderingContext2DBinding::{
CanvasDirection, CanvasFillRule, CanvasImageSource, CanvasLineCap, CanvasLineJoin,
CanvasRenderingContext2DMethods, CanvasTextAlign, CanvasTextBaseline,
};
use crate::dom::bindings::codegen::Bindings::DOMMatrixBinding::DOMMatrix2DInit;
use crate::dom::bindings::codegen::UnionTypes::{
HTMLCanvasElementOrOffscreenCanvas, StringOrCanvasGradientOrCanvasPattern,
};
use crate::dom::bindings::error::{ErrorResult, Fallible};
use crate::dom::bindings::num::Finite;
use crate::dom::bindings::reflector::{DomGlobal, Reflector, reflect_dom_object};
use crate::dom::bindings::root::{DomRoot, LayoutDom};
use crate::dom::bindings::str::DOMString;
use crate::dom::canvasgradient::CanvasGradient;
use crate::dom::canvaspattern::CanvasPattern;
use crate::dom::dommatrix::DOMMatrix;
use crate::dom::globalscope::GlobalScope;
use crate::dom::html::htmlcanvaselement::HTMLCanvasElement;
use crate::dom::imagedata::ImageData;
use crate::dom::node::{Node, NodeDamage, NodeTraits};
use crate::dom::path2d::Path2D;
use crate::dom::textmetrics::TextMetrics;
use crate::script_runtime::CanGc;
// https://html.spec.whatwg.org/multipage/#canvasrenderingcontext2d
#[dom_struct]
pub(crate) struct CanvasRenderingContext2D {
reflector_: Reflector,
canvas: HTMLCanvasElementOrOffscreenCanvas,
canvas_state: CanvasState,
}
impl CanvasRenderingContext2D {
#[cfg_attr(crown, allow(crown::unrooted_must_root))]
pub(crate) fn new_inherited(
global: &GlobalScope,
canvas: HTMLCanvasElementOrOffscreenCanvas,
size: Size2D<u32>,
) -> Option<CanvasRenderingContext2D> {
let canvas_state =
CanvasState::new(global, Size2D::new(size.width as u64, size.height as u64))?;
Some(CanvasRenderingContext2D {
reflector_: Reflector::new(),
canvas,
canvas_state,
})
}
#[cfg_attr(crown, allow(crown::unrooted_must_root))]
pub(crate) fn new(
global: &GlobalScope,
canvas: &HTMLCanvasElement,
size: Size2D<u32>,
can_gc: CanGc,
) -> Option<DomRoot<CanvasRenderingContext2D>> {
let boxed = Box::new(CanvasRenderingContext2D::new_inherited(
global,
HTMLCanvasElementOrOffscreenCanvas::HTMLCanvasElement(DomRoot::from_ref(canvas)),
size,
)?);
Some(reflect_dom_object(boxed, global, can_gc))
}
// https://html.spec.whatwg.org/multipage/#reset-the-rendering-context-to-its-default-state
fn reset_to_initial_state(&self) {
self.canvas_state.reset_to_initial_state();
}
/// <https://html.spec.whatwg.org/multipage/#concept-canvas-set-bitmap-dimensions>
pub(crate) fn set_canvas_bitmap_dimensions(&self, size: Size2D<u64>) {
self.canvas_state.set_bitmap_dimensions(size);
}
pub(crate) fn take_missing_image_urls(&self) -> Vec<ServoUrl> {
std::mem::take(&mut self.canvas_state.get_missing_image_urls().borrow_mut())
}
pub(crate) fn get_canvas_id(&self) -> CanvasId {
self.canvas_state.get_canvas_id()
}
pub(crate) fn send_canvas_2d_msg(&self, msg: Canvas2dMsg) {
self.canvas_state.send_canvas_2d_msg(msg)
}
}
impl LayoutCanvasRenderingContextHelpers for LayoutDom<'_, CanvasRenderingContext2D> {
fn canvas_data_source(self) -> Option<ImageKey> {
let canvas_state = &self.unsafe_get().canvas_state;
if canvas_state.is_paintable() {
Some(canvas_state.image_key())
} else {
None
}
}
}
impl CanvasContext for CanvasRenderingContext2D {
type ID = CanvasId;
fn context_id(&self) -> Self::ID {
self.canvas_state.get_canvas_id()
}
fn canvas(&self) -> Option<HTMLCanvasElementOrOffscreenCanvas> {
Some(self.canvas.clone())
}
fn update_rendering(&self, canvas_epoch: Epoch) -> bool {
if !self.onscreen() {
return false;
}
self.canvas_state.update_rendering(Some(canvas_epoch))
}
fn resize(&self) {
self.set_canvas_bitmap_dimensions(self.size().cast())
}
fn reset_bitmap(&self) {
self.canvas_state.reset_bitmap()
}
fn get_image_data(&self) -> Option<Snapshot> {
if !self.canvas_state.is_paintable() {
return None;
}
let (sender, receiver) = ipc::channel().unwrap();
self.canvas_state
.send_canvas_2d_msg(Canvas2dMsg::GetImageData(None, sender));
Some(receiver.recv().unwrap().to_owned())
}
fn origin_is_clean(&self) -> bool {
self.canvas_state.origin_is_clean()
}
fn mark_as_dirty(&self) {
if let Some(canvas) = self.canvas.canvas() {
canvas.upcast::<Node>().dirty(NodeDamage::Other);
canvas.owner_document().add_dirty_2d_canvas(self);
}
}
fn image_key(&self) -> Option<ImageKey> {
Some(self.canvas_state.image_key())
}
}
// We add a guard to each of methods by the spec:
// http://www.w3.org/html/wg/drafts/2dcontext/html5_canvas_CR/
//
// > Except where otherwise specified, for the 2D context interface,
// > any method call with a numeric argument whose value is infinite or a NaN value must be ignored.
//
// Restricted values are guarded in glue code. Therefore we need not add a guard.
//
// FIXME: this behavior should might be generated by some annotattions to idl.
impl CanvasRenderingContext2DMethods<crate::DomTypeHolder> for CanvasRenderingContext2D {
// https://html.spec.whatwg.org/multipage/#dom-context-2d-canvas
fn Canvas(&self) -> DomRoot<HTMLCanvasElement> {
match &self.canvas {
HTMLCanvasElementOrOffscreenCanvas::HTMLCanvasElement(canvas) => canvas.clone(),
_ => panic!("Should not be called from offscreen canvas"),
}
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-save
fn Save(&self) {
self.canvas_state.save()
}
#[cfg_attr(crown, allow(crown::unrooted_must_root))]
// https://html.spec.whatwg.org/multipage/#dom-context-2d-restore
fn Restore(&self) {
self.canvas_state.restore()
}
/// <https://html.spec.whatwg.org/multipage/#dom-context-2d-reset>
fn Reset(&self) {
self.canvas_state.reset()
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-scale
fn Scale(&self, x: f64, y: f64) {
self.canvas_state.scale(x, y)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-rotate
fn Rotate(&self, angle: f64) {
self.canvas_state.rotate(angle)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-translate
fn Translate(&self, x: f64, y: f64) {
self.canvas_state.translate(x, y)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-transform
fn Transform(&self, a: f64, b: f64, c: f64, d: f64, e: f64, f: f64) {
self.canvas_state.transform(a, b, c, d, e, f)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-gettransform
fn GetTransform(&self, can_gc: CanGc) -> DomRoot<DOMMatrix> {
self.canvas_state.get_transform(&self.global(), can_gc)
}
/// <https://html.spec.whatwg.org/multipage/#dom-context-2d-settransform>
fn SetTransform(&self, a: f64, b: f64, c: f64, d: f64, e: f64, f: f64) -> ErrorResult {
self.canvas_state.set_transform(a, b, c, d, e, f);
Ok(())
}
/// <https://html.spec.whatwg.org/multipage/#dom-context-2d-settransform-matrix>
fn SetTransform_(&self, transform: &DOMMatrix2DInit) -> ErrorResult {
self.canvas_state.set_transform_(transform)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-resettransform
fn ResetTransform(&self) {
self.canvas_state.reset_transform()
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-globalalpha
fn GlobalAlpha(&self) -> f64 {
self.canvas_state.global_alpha()
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-globalalpha
fn SetGlobalAlpha(&self, alpha: f64) {
self.canvas_state.set_global_alpha(alpha)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-globalcompositeoperation
fn GlobalCompositeOperation(&self) -> DOMString {
self.canvas_state.global_composite_operation()
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-globalcompositeoperation
fn SetGlobalCompositeOperation(&self, op_str: DOMString) {
self.canvas_state.set_global_composite_operation(op_str)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-fillrect
fn FillRect(&self, x: f64, y: f64, width: f64, height: f64) {
self.canvas_state.fill_rect(x, y, width, height);
self.mark_as_dirty();
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-clearrect
fn ClearRect(&self, x: f64, y: f64, width: f64, height: f64) {
self.canvas_state.clear_rect(x, y, width, height);
self.mark_as_dirty();
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-strokerect
fn StrokeRect(&self, x: f64, y: f64, width: f64, height: f64) {
self.canvas_state.stroke_rect(x, y, width, height);
self.mark_as_dirty();
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-beginpath
fn BeginPath(&self) {
self.canvas_state.begin_path()
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-closepath
fn ClosePath(&self) {
self.canvas_state.close_path()
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-fill
fn Fill(&self, fill_rule: CanvasFillRule) {
self.canvas_state.fill(fill_rule);
self.mark_as_dirty();
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-fill
fn Fill_(&self, path: &Path2D, fill_rule: CanvasFillRule) {
self.canvas_state.fill_(path.segments(), fill_rule);
self.mark_as_dirty();
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-stroke
fn Stroke(&self) {
self.canvas_state.stroke();
self.mark_as_dirty();
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-stroke
fn Stroke_(&self, path: &Path2D) {
self.canvas_state.stroke_(path.segments());
self.mark_as_dirty();
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-clip
fn Clip(&self, fill_rule: CanvasFillRule) {
self.canvas_state.clip(fill_rule)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-clip
fn Clip_(&self, path: &Path2D, fill_rule: CanvasFillRule) {
self.canvas_state.clip_(path.segments(), fill_rule)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-ispointinpath
fn IsPointInPath(&self, x: f64, y: f64, fill_rule: CanvasFillRule) -> bool {
self.canvas_state
.is_point_in_path(&self.global(), x, y, fill_rule)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-ispointinpath
fn IsPointInPath_(&self, path: &Path2D, x: f64, y: f64, fill_rule: CanvasFillRule) -> bool {
self.canvas_state
.is_point_in_path_(&self.global(), path.segments(), x, y, fill_rule)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-filltext
fn FillText(&self, text: DOMString, x: f64, y: f64, max_width: Option<f64>) {
self.canvas_state.fill_text(
&self.global(),
self.canvas.canvas().as_deref(),
text,
x,
y,
max_width,
);
self.mark_as_dirty();
}
// https://html.spec.whatwg.org/multipage/#textmetrics
fn MeasureText(&self, text: DOMString, can_gc: CanGc) -> DomRoot<TextMetrics> {
self.canvas_state.measure_text(
&self.global(),
self.canvas.canvas().as_deref(),
text,
can_gc,
)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-font
fn Font(&self) -> DOMString {
self.canvas_state.font()
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-font
fn SetFont(&self, value: DOMString) {
self.canvas_state
.set_font(self.canvas.canvas().as_deref(), value)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-textalign
fn TextAlign(&self) -> CanvasTextAlign {
self.canvas_state.text_align()
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-textalign
fn SetTextAlign(&self, value: CanvasTextAlign) {
self.canvas_state.set_text_align(value)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-textbaseline
fn TextBaseline(&self) -> CanvasTextBaseline {
self.canvas_state.text_baseline()
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-textbaseline
fn SetTextBaseline(&self, value: CanvasTextBaseline) {
self.canvas_state.set_text_baseline(value)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-direction
fn Direction(&self) -> CanvasDirection {
self.canvas_state.direction()
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-direction
fn SetDirection(&self, value: CanvasDirection) {
self.canvas_state.set_direction(value)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-drawimage
fn DrawImage(&self, image: CanvasImageSource, dx: f64, dy: f64) -> ErrorResult {
self.canvas_state
.draw_image(self.canvas.canvas().as_deref(), image, dx, dy)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-drawimage
fn DrawImage_(
&self,
image: CanvasImageSource,
dx: f64,
dy: f64,
dw: f64,
dh: f64,
) -> ErrorResult {
self.canvas_state
.draw_image_(self.canvas.canvas().as_deref(), image, dx, dy, dw, dh)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-drawimage
fn DrawImage__(
&self,
image: CanvasImageSource,
sx: f64,
sy: f64,
sw: f64,
sh: f64,
dx: f64,
dy: f64,
dw: f64,
dh: f64,
) -> ErrorResult {
self.canvas_state.draw_image__(
self.canvas.canvas().as_deref(),
image,
sx,
sy,
sw,
sh,
dx,
dy,
dw,
dh,
)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-moveto
fn MoveTo(&self, x: f64, y: f64) {
self.canvas_state.move_to(x, y)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-lineto
fn LineTo(&self, x: f64, y: f64) {
self.canvas_state.line_to(x, y)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-rect
fn Rect(&self, x: f64, y: f64, width: f64, height: f64) {
self.canvas_state.rect(x, y, width, height)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-quadraticcurveto
fn QuadraticCurveTo(&self, cpx: f64, cpy: f64, x: f64, y: f64) {
self.canvas_state.quadratic_curve_to(cpx, cpy, x, y)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-beziercurveto
fn BezierCurveTo(&self, cp1x: f64, cp1y: f64, cp2x: f64, cp2y: f64, x: f64, y: f64) {
self.canvas_state
.bezier_curve_to(cp1x, cp1y, cp2x, cp2y, x, y)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-arc
fn Arc(&self, x: f64, y: f64, r: f64, start: f64, end: f64, ccw: bool) -> ErrorResult {
self.canvas_state.arc(x, y, r, start, end, ccw)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-arcto
fn ArcTo(&self, cp1x: f64, cp1y: f64, cp2x: f64, cp2y: f64, r: f64) -> ErrorResult {
self.canvas_state.arc_to(cp1x, cp1y, cp2x, cp2y, r)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-ellipse
fn Ellipse(
&self,
x: f64,
y: f64,
rx: f64,
ry: f64,
rotation: f64,
start: f64,
end: f64,
ccw: bool,
) -> ErrorResult {
self.canvas_state
.ellipse(x, y, rx, ry, rotation, start, end, ccw)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-imagesmoothingenabled
fn ImageSmoothingEnabled(&self) -> bool {
self.canvas_state.image_smoothing_enabled()
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-imagesmoothingenabled
fn SetImageSmoothingEnabled(&self, value: bool) {
self.canvas_state.set_image_smoothing_enabled(value)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-strokestyle
fn StrokeStyle(&self) -> StringOrCanvasGradientOrCanvasPattern {
self.canvas_state.stroke_style()
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-strokestyle
fn SetStrokeStyle(&self, value: StringOrCanvasGradientOrCanvasPattern) {
self.canvas_state
.set_stroke_style(self.canvas.canvas().as_deref(), value)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-strokestyle
fn FillStyle(&self) -> StringOrCanvasGradientOrCanvasPattern {
self.canvas_state.fill_style()
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-strokestyle
fn SetFillStyle(&self, value: StringOrCanvasGradientOrCanvasPattern) {
self.canvas_state
.set_fill_style(self.canvas.canvas().as_deref(), value)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-createimagedata
fn CreateImageData(&self, sw: i32, sh: i32, can_gc: CanGc) -> Fallible<DomRoot<ImageData>> {
self.canvas_state
.create_image_data(&self.global(), sw, sh, can_gc)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-createimagedata
fn CreateImageData_(
&self,
imagedata: &ImageData,
can_gc: CanGc,
) -> Fallible<DomRoot<ImageData>> {
self.canvas_state
.create_image_data_(&self.global(), imagedata, can_gc)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-getimagedata
fn GetImageData(
&self,
sx: i32,
sy: i32,
sw: i32,
sh: i32,
can_gc: CanGc,
) -> Fallible<DomRoot<ImageData>> {
self.canvas_state
.get_image_data(self.canvas.size(), &self.global(), sx, sy, sw, sh, can_gc)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-putimagedata
fn PutImageData(&self, imagedata: &ImageData, dx: i32, dy: i32) {
self.canvas_state
.put_image_data(self.canvas.size(), imagedata, dx, dy)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-putimagedata
#[allow(unsafe_code)]
fn PutImageData_(
&self,
imagedata: &ImageData,
dx: i32,
dy: i32,
dirty_x: i32,
dirty_y: i32,
dirty_width: i32,
dirty_height: i32,
) {
self.canvas_state.put_image_data_(
self.canvas.size(),
imagedata,
dx,
dy,
dirty_x,
dirty_y,
dirty_width,
dirty_height,
);
self.mark_as_dirty();
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-createlineargradient
fn CreateLinearGradient(
&self,
x0: Finite<f64>,
y0: Finite<f64>,
x1: Finite<f64>,
y1: Finite<f64>,
can_gc: CanGc,
) -> DomRoot<CanvasGradient> {
self.canvas_state
.create_linear_gradient(&self.global(), x0, y0, x1, y1, can_gc)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-createradialgradient
fn CreateRadialGradient(
&self,
x0: Finite<f64>,
y0: Finite<f64>,
r0: Finite<f64>,
x1: Finite<f64>,
y1: Finite<f64>,
r1: Finite<f64>,
can_gc: CanGc,
) -> Fallible<DomRoot<CanvasGradient>> {
self.canvas_state
.create_radial_gradient(&self.global(), x0, y0, r0, x1, y1, r1, can_gc)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-createpattern
fn CreatePattern(
&self,
image: CanvasImageSource,
repetition: DOMString,
can_gc: CanGc,
) -> Fallible<Option<DomRoot<CanvasPattern>>> {
self.canvas_state
.create_pattern(&self.global(), image, repetition, can_gc)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-linewidth
fn LineWidth(&self) -> f64 {
self.canvas_state.line_width()
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-linewidth
fn SetLineWidth(&self, width: f64) {
self.canvas_state.set_line_width(width)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-linecap
fn LineCap(&self) -> CanvasLineCap {
self.canvas_state.line_cap()
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-linecap
fn SetLineCap(&self, cap: CanvasLineCap) {
self.canvas_state.set_line_cap(cap)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-linejoin
fn LineJoin(&self) -> CanvasLineJoin {
self.canvas_state.line_join()
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-linejoin
fn SetLineJoin(&self, join: CanvasLineJoin) {
self.canvas_state.set_line_join(join)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-miterlimit
fn MiterLimit(&self) -> f64 {
self.canvas_state.miter_limit()
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-miterlimit
fn SetMiterLimit(&self, limit: f64) {
self.canvas_state.set_miter_limit(limit)
}
/// <https://html.spec.whatwg.org/multipage/#dom-context-2d-setlinedash>
fn SetLineDash(&self, segments: Vec<f64>) {
self.canvas_state.set_line_dash(segments);
}
/// <https://html.spec.whatwg.org/multipage/#dom-context-2d-getlinedash>
fn GetLineDash(&self) -> Vec<f64> {
self.canvas_state.line_dash()
}
/// <https://html.spec.whatwg.org/multipage/#dom-context-2d-linedashoffset>
fn LineDashOffset(&self) -> f64 {
self.canvas_state.line_dash_offset()
}
/// <https://html.spec.whatwg.org/multipage/#dom-context-2d-linedashoffset>
fn SetLineDashOffset(&self, offset: f64) {
self.canvas_state.set_line_dash_offset(offset);
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-shadowoffsetx
fn ShadowOffsetX(&self) -> f64 {
self.canvas_state.shadow_offset_x()
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-shadowoffsetx
fn SetShadowOffsetX(&self, value: f64) {
self.canvas_state.set_shadow_offset_x(value)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-shadowoffsety
fn ShadowOffsetY(&self) -> f64 {
self.canvas_state.shadow_offset_y()
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-shadowoffsety
fn SetShadowOffsetY(&self, value: f64) {
self.canvas_state.set_shadow_offset_y(value)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-shadowblur
fn ShadowBlur(&self) -> f64 {
self.canvas_state.shadow_blur()
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-shadowblur
fn SetShadowBlur(&self, value: f64) {
self.canvas_state.set_shadow_blur(value)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-shadowcolor
fn ShadowColor(&self) -> DOMString {
self.canvas_state.shadow_color()
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-shadowcolor
fn SetShadowColor(&self, value: DOMString) {
self.canvas_state
.set_shadow_color(self.canvas.canvas().as_deref(), value)
}
}

View file

@ -0,0 +1,13 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
mod canvas_state;
pub(crate) mod canvasgradient;
pub(crate) mod canvaspattern;
#[allow(dead_code)]
pub(crate) mod canvasrenderingcontext2d;
pub(crate) mod offscreencanvasrenderingcontext2d;
pub(crate) mod paintrenderingcontext2d;
pub(crate) mod path2d;
pub(crate) mod textmetrics;

View file

@ -0,0 +1,613 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::GenericBindings::CanvasRenderingContext2DBinding::CanvasRenderingContext2D_Binding::CanvasRenderingContext2DMethods;
use crate::canvas_context::CanvasContext;
use crate::dom::bindings::codegen::UnionTypes::HTMLCanvasElementOrOffscreenCanvas;
use canvas_traits::canvas::Canvas2dMsg;
use dom_struct::dom_struct;
use pixels::Snapshot;
use crate::dom::bindings::codegen::Bindings::CanvasRenderingContext2DBinding::{
CanvasDirection, CanvasFillRule, CanvasImageSource, CanvasLineCap, CanvasLineJoin,
CanvasTextAlign, CanvasTextBaseline,
};
use crate::dom::bindings::codegen::Bindings::DOMMatrixBinding::DOMMatrix2DInit;
use crate::dom::bindings::codegen::Bindings::OffscreenCanvasRenderingContext2DBinding::OffscreenCanvasRenderingContext2DMethods;
use crate::dom::bindings::codegen::UnionTypes::StringOrCanvasGradientOrCanvasPattern;
use crate::dom::bindings::error::{ErrorResult, Fallible};
use crate::dom::bindings::num::Finite;
use crate::dom::bindings::reflector::reflect_dom_object;
use crate::dom::bindings::root::DomRoot;
use crate::dom::bindings::str::DOMString;
use crate::dom::canvasgradient::CanvasGradient;
use crate::dom::canvaspattern::CanvasPattern;
use crate::dom::dommatrix::DOMMatrix;
use crate::dom::globalscope::GlobalScope;
use crate::dom::imagedata::ImageData;
use crate::dom::offscreencanvas::OffscreenCanvas;
use crate::dom::path2d::Path2D;
use crate::dom::textmetrics::TextMetrics;
use crate::script_runtime::CanGc;
use super::canvasrenderingcontext2d::CanvasRenderingContext2D;
#[dom_struct]
pub(crate) struct OffscreenCanvasRenderingContext2D {
context: CanvasRenderingContext2D,
}
impl OffscreenCanvasRenderingContext2D {
#[cfg_attr(crown, allow(crown::unrooted_must_root))]
fn new_inherited(
global: &GlobalScope,
canvas: &OffscreenCanvas,
) -> Option<OffscreenCanvasRenderingContext2D> {
let size = canvas.get_size().cast();
Some(OffscreenCanvasRenderingContext2D {
context: CanvasRenderingContext2D::new_inherited(
global,
HTMLCanvasElementOrOffscreenCanvas::OffscreenCanvas(DomRoot::from_ref(canvas)),
size,
)?,
})
}
#[cfg_attr(crown, allow(crown::unrooted_must_root))]
pub(crate) fn new(
global: &GlobalScope,
canvas: &OffscreenCanvas,
can_gc: CanGc,
) -> Option<DomRoot<OffscreenCanvasRenderingContext2D>> {
let boxed = Box::new(OffscreenCanvasRenderingContext2D::new_inherited(
global, canvas,
)?);
Some(reflect_dom_object(boxed, global, can_gc))
}
pub(crate) fn send_canvas_2d_msg(&self, msg: Canvas2dMsg) {
self.context.send_canvas_2d_msg(msg)
}
}
impl CanvasContext for OffscreenCanvasRenderingContext2D {
type ID = <CanvasRenderingContext2D as CanvasContext>::ID;
fn context_id(&self) -> Self::ID {
self.context.context_id()
}
fn canvas(&self) -> Option<HTMLCanvasElementOrOffscreenCanvas> {
self.context.canvas()
}
fn resize(&self) {
self.context.resize()
}
fn reset_bitmap(&self) {
self.context.reset_bitmap()
}
fn get_image_data(&self) -> Option<Snapshot> {
self.context.get_image_data()
}
fn origin_is_clean(&self) -> bool {
self.context.origin_is_clean()
}
fn image_key(&self) -> Option<webrender_api::ImageKey> {
None
}
}
impl OffscreenCanvasRenderingContext2DMethods<crate::DomTypeHolder>
for OffscreenCanvasRenderingContext2D
{
// https://html.spec.whatwg.org/multipage/offscreencontext2d-canvas
fn Canvas(&self) -> DomRoot<OffscreenCanvas> {
match self.context.canvas() {
Some(HTMLCanvasElementOrOffscreenCanvas::OffscreenCanvas(canvas)) => canvas,
_ => panic!("Should not be called from onscreen canvas"),
}
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-fillrect
fn FillRect(&self, x: f64, y: f64, width: f64, height: f64) {
self.context.FillRect(x, y, width, height);
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-clearrect
fn ClearRect(&self, x: f64, y: f64, width: f64, height: f64) {
self.context.ClearRect(x, y, width, height);
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-strokerect
fn StrokeRect(&self, x: f64, y: f64, width: f64, height: f64) {
self.context.StrokeRect(x, y, width, height);
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-shadowoffsetx
fn ShadowOffsetX(&self) -> f64 {
self.context.ShadowOffsetX()
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-shadowoffsetx
fn SetShadowOffsetX(&self, value: f64) {
self.context.SetShadowOffsetX(value)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-shadowoffsety
fn ShadowOffsetY(&self) -> f64 {
self.context.ShadowOffsetY()
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-shadowoffsety
fn SetShadowOffsetY(&self, value: f64) {
self.context.SetShadowOffsetY(value)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-shadowblur
fn ShadowBlur(&self) -> f64 {
self.context.ShadowBlur()
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-shadowblur
fn SetShadowBlur(&self, value: f64) {
self.context.SetShadowBlur(value)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-shadowcolor
fn ShadowColor(&self) -> DOMString {
self.context.ShadowColor()
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-shadowcolor
fn SetShadowColor(&self, value: DOMString) {
self.context.SetShadowColor(value)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-strokestyle
fn StrokeStyle(&self) -> StringOrCanvasGradientOrCanvasPattern {
self.context.StrokeStyle()
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-strokestyle
fn SetStrokeStyle(&self, value: StringOrCanvasGradientOrCanvasPattern) {
self.context.SetStrokeStyle(value)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-strokestyle
fn FillStyle(&self) -> StringOrCanvasGradientOrCanvasPattern {
self.context.FillStyle()
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-strokestyle
fn SetFillStyle(&self, value: StringOrCanvasGradientOrCanvasPattern) {
self.context.SetFillStyle(value)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-createlineargradient
fn CreateLinearGradient(
&self,
x0: Finite<f64>,
y0: Finite<f64>,
x1: Finite<f64>,
y1: Finite<f64>,
can_gc: CanGc,
) -> DomRoot<CanvasGradient> {
self.context.CreateLinearGradient(x0, y0, x1, y1, can_gc)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-createradialgradient
fn CreateRadialGradient(
&self,
x0: Finite<f64>,
y0: Finite<f64>,
r0: Finite<f64>,
x1: Finite<f64>,
y1: Finite<f64>,
r1: Finite<f64>,
can_gc: CanGc,
) -> Fallible<DomRoot<CanvasGradient>> {
self.context
.CreateRadialGradient(x0, y0, r0, x1, y1, r1, can_gc)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-createpattern
fn CreatePattern(
&self,
image: CanvasImageSource,
repetition: DOMString,
can_gc: CanGc,
) -> Fallible<Option<DomRoot<CanvasPattern>>> {
self.context.CreatePattern(image, repetition, can_gc)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-save
fn Save(&self) {
self.context.Save()
}
#[cfg_attr(crown, allow(crown::unrooted_must_root))]
// https://html.spec.whatwg.org/multipage/#dom-context-2d-restore
fn Restore(&self) {
self.context.Restore()
}
/// <https://html.spec.whatwg.org/multipage/#dom-context-2d-reset>
fn Reset(&self) {
self.context.Reset()
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-globalalpha
fn GlobalAlpha(&self) -> f64 {
self.context.GlobalAlpha()
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-globalalpha
fn SetGlobalAlpha(&self, alpha: f64) {
self.context.SetGlobalAlpha(alpha)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-globalcompositeoperation
fn GlobalCompositeOperation(&self) -> DOMString {
self.context.GlobalCompositeOperation()
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-globalcompositeoperation
fn SetGlobalCompositeOperation(&self, op_str: DOMString) {
self.context.SetGlobalCompositeOperation(op_str)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-imagesmoothingenabled
fn ImageSmoothingEnabled(&self) -> bool {
self.context.ImageSmoothingEnabled()
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-imagesmoothingenabled
fn SetImageSmoothingEnabled(&self, value: bool) {
self.context.SetImageSmoothingEnabled(value)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-filltext
fn FillText(&self, text: DOMString, x: f64, y: f64, max_width: Option<f64>) {
self.context.FillText(text, x, y, max_width)
}
// https://html.spec.whatwg.org/multipage/#textmetrics
fn MeasureText(&self, text: DOMString, can_gc: CanGc) -> DomRoot<TextMetrics> {
self.context.MeasureText(text, can_gc)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-font
fn Font(&self) -> DOMString {
self.context.Font()
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-font
fn SetFont(&self, value: DOMString) {
self.context.SetFont(value)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-textalign
fn TextAlign(&self) -> CanvasTextAlign {
self.context.TextAlign()
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-textalign
fn SetTextAlign(&self, value: CanvasTextAlign) {
self.context.SetTextAlign(value)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-textbaseline
fn TextBaseline(&self) -> CanvasTextBaseline {
self.context.TextBaseline()
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-textbaseline
fn SetTextBaseline(&self, value: CanvasTextBaseline) {
self.context.SetTextBaseline(value)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-direction
fn Direction(&self) -> CanvasDirection {
self.context.Direction()
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-direction
fn SetDirection(&self, value: CanvasDirection) {
self.context.SetDirection(value)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-linewidth
fn LineWidth(&self) -> f64 {
self.context.LineWidth()
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-linewidth
fn SetLineWidth(&self, width: f64) {
self.context.SetLineWidth(width)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-linecap
fn LineCap(&self) -> CanvasLineCap {
self.context.LineCap()
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-linecap
fn SetLineCap(&self, cap: CanvasLineCap) {
self.context.SetLineCap(cap)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-linejoin
fn LineJoin(&self) -> CanvasLineJoin {
self.context.LineJoin()
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-linejoin
fn SetLineJoin(&self, join: CanvasLineJoin) {
self.context.SetLineJoin(join)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-miterlimit
fn MiterLimit(&self) -> f64 {
self.context.MiterLimit()
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-miterlimit
fn SetMiterLimit(&self, limit: f64) {
self.context.SetMiterLimit(limit)
}
/// <https://html.spec.whatwg.org/multipage/#dom-context-2d-setlinedash>
fn SetLineDash(&self, segments: Vec<f64>) {
self.context.SetLineDash(segments)
}
/// <https://html.spec.whatwg.org/multipage/#dom-context-2d-getlinedash>
fn GetLineDash(&self) -> Vec<f64> {
self.context.GetLineDash()
}
/// <https://html.spec.whatwg.org/multipage/#dom-context-2d-linedashoffset>
fn LineDashOffset(&self) -> f64 {
self.context.LineDashOffset()
}
/// <https://html.spec.whatwg.org/multipage/#dom-context-2d-linedashoffset>
fn SetLineDashOffset(&self, offset: f64) {
self.context.SetLineDashOffset(offset)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-createimagedata
fn CreateImageData(&self, sw: i32, sh: i32, can_gc: CanGc) -> Fallible<DomRoot<ImageData>> {
self.context.CreateImageData(sw, sh, can_gc)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-createimagedata
fn CreateImageData_(
&self,
imagedata: &ImageData,
can_gc: CanGc,
) -> Fallible<DomRoot<ImageData>> {
self.context.CreateImageData_(imagedata, can_gc)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-getimagedata
fn GetImageData(
&self,
sx: i32,
sy: i32,
sw: i32,
sh: i32,
can_gc: CanGc,
) -> Fallible<DomRoot<ImageData>> {
self.context.GetImageData(sx, sy, sw, sh, can_gc)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-putimagedata
fn PutImageData(&self, imagedata: &ImageData, dx: i32, dy: i32) {
self.context.PutImageData(imagedata, dx, dy)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-putimagedata
#[allow(unsafe_code)]
fn PutImageData_(
&self,
imagedata: &ImageData,
dx: i32,
dy: i32,
dirty_x: i32,
dirty_y: i32,
dirty_width: i32,
dirty_height: i32,
) {
self.context.PutImageData_(
imagedata,
dx,
dy,
dirty_x,
dirty_y,
dirty_width,
dirty_height,
)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-drawimage
fn DrawImage(&self, image: CanvasImageSource, dx: f64, dy: f64) -> ErrorResult {
self.context.DrawImage(image, dx, dy)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-drawimage
fn DrawImage_(
&self,
image: CanvasImageSource,
dx: f64,
dy: f64,
dw: f64,
dh: f64,
) -> ErrorResult {
self.context.DrawImage_(image, dx, dy, dw, dh)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-drawimage
fn DrawImage__(
&self,
image: CanvasImageSource,
sx: f64,
sy: f64,
sw: f64,
sh: f64,
dx: f64,
dy: f64,
dw: f64,
dh: f64,
) -> ErrorResult {
self.context
.DrawImage__(image, sx, sy, sw, sh, dx, dy, dw, dh)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-beginpath
fn BeginPath(&self) {
self.context.BeginPath()
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-fill
fn Fill(&self, fill_rule: CanvasFillRule) {
self.context.Fill(fill_rule)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-fill
fn Fill_(&self, path: &Path2D, fill_rule: CanvasFillRule) {
self.context.Fill_(path, fill_rule)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-stroke
fn Stroke(&self) {
self.context.Stroke()
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-stroke
fn Stroke_(&self, path: &Path2D) {
self.context.Stroke_(path)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-clip
fn Clip(&self, fill_rule: CanvasFillRule) {
self.context.Clip(fill_rule)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-clip
fn Clip_(&self, path: &Path2D, fill_rule: CanvasFillRule) {
self.context.Clip_(path, fill_rule)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-ispointinpath
fn IsPointInPath(&self, x: f64, y: f64, fill_rule: CanvasFillRule) -> bool {
self.context.IsPointInPath(x, y, fill_rule)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-ispointinpath
fn IsPointInPath_(&self, path: &Path2D, x: f64, y: f64, fill_rule: CanvasFillRule) -> bool {
self.context.IsPointInPath_(path, x, y, fill_rule)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-scale
fn Scale(&self, x: f64, y: f64) {
self.context.Scale(x, y)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-rotate
fn Rotate(&self, angle: f64) {
self.context.Rotate(angle)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-translate
fn Translate(&self, x: f64, y: f64) {
self.context.Translate(x, y)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-transform
fn Transform(&self, a: f64, b: f64, c: f64, d: f64, e: f64, f: f64) {
self.context.Transform(a, b, c, d, e, f)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-gettransform
fn GetTransform(&self, can_gc: CanGc) -> DomRoot<DOMMatrix> {
self.context.GetTransform(can_gc)
}
/// <https://html.spec.whatwg.org/multipage/#dom-context-2d-settransform>
fn SetTransform(&self, a: f64, b: f64, c: f64, d: f64, e: f64, f: f64) -> ErrorResult {
self.context.SetTransform(a, b, c, d, e, f)
}
/// <https://html.spec.whatwg.org/multipage/#dom-context-2d-settransform-matrix>
fn SetTransform_(&self, transform: &DOMMatrix2DInit) -> ErrorResult {
self.context.SetTransform_(transform)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-resettransform
fn ResetTransform(&self) {
self.context.ResetTransform()
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-closepath
fn ClosePath(&self) {
self.context.ClosePath()
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-moveto
fn MoveTo(&self, x: f64, y: f64) {
self.context.MoveTo(x, y)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-lineto
fn LineTo(&self, x: f64, y: f64) {
self.context.LineTo(x, y)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-rect
fn Rect(&self, x: f64, y: f64, width: f64, height: f64) {
self.context.Rect(x, y, width, height)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-quadraticcurveto
fn QuadraticCurveTo(&self, cpx: f64, cpy: f64, x: f64, y: f64) {
self.context.QuadraticCurveTo(cpx, cpy, x, y)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-beziercurveto
fn BezierCurveTo(&self, cp1x: f64, cp1y: f64, cp2x: f64, cp2y: f64, x: f64, y: f64) {
self.context.BezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-arc
fn Arc(&self, x: f64, y: f64, r: f64, start: f64, end: f64, ccw: bool) -> ErrorResult {
self.context.Arc(x, y, r, start, end, ccw)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-arcto
fn ArcTo(&self, cp1x: f64, cp1y: f64, cp2x: f64, cp2y: f64, r: f64) -> ErrorResult {
self.context.ArcTo(cp1x, cp1y, cp2x, cp2y, r)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-ellipse
fn Ellipse(
&self,
x: f64,
y: f64,
rx: f64,
ry: f64,
rotation: f64,
start: f64,
end: f64,
ccw: bool,
) -> ErrorResult {
self.context
.Ellipse(x, y, rx, ry, rotation, start, end, ccw)
}
}

View file

@ -0,0 +1,505 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use std::cell::Cell;
use dom_struct::dom_struct;
use euclid::{Scale, Size2D};
use script_bindings::reflector::Reflector;
use servo_url::ServoUrl;
use style_traits::CSSPixel;
use webrender_api::ImageKey;
use webrender_api::units::DevicePixel;
use super::canvas_state::CanvasState;
use crate::dom::bindings::codegen::Bindings::CanvasRenderingContext2DBinding::{
CanvasFillRule, CanvasImageSource, CanvasLineCap, CanvasLineJoin,
};
use crate::dom::bindings::codegen::Bindings::DOMMatrixBinding::DOMMatrix2DInit;
use crate::dom::bindings::codegen::Bindings::PaintRenderingContext2DBinding::PaintRenderingContext2DMethods;
use crate::dom::bindings::codegen::UnionTypes::StringOrCanvasGradientOrCanvasPattern;
use crate::dom::bindings::error::{ErrorResult, Fallible};
use crate::dom::bindings::inheritance::Castable;
use crate::dom::bindings::num::Finite;
use crate::dom::bindings::reflector::{DomGlobal as _, reflect_dom_object};
use crate::dom::bindings::root::DomRoot;
use crate::dom::bindings::str::DOMString;
use crate::dom::canvasgradient::CanvasGradient;
use crate::dom::canvaspattern::CanvasPattern;
use crate::dom::dommatrix::DOMMatrix;
use crate::dom::paintworkletglobalscope::PaintWorkletGlobalScope;
use crate::dom::path2d::Path2D;
use crate::script_runtime::CanGc;
#[dom_struct]
pub(crate) struct PaintRenderingContext2D {
reflector_: Reflector,
canvas_state: CanvasState,
#[no_trace]
device_pixel_ratio: Cell<Scale<f32, CSSPixel, DevicePixel>>,
}
impl PaintRenderingContext2D {
#[cfg_attr(crown, allow(crown::unrooted_must_root))]
fn new_inherited(global: &PaintWorkletGlobalScope) -> Option<PaintRenderingContext2D> {
Some(PaintRenderingContext2D {
reflector_: Reflector::new(),
canvas_state: CanvasState::new(global.upcast(), Size2D::zero())?,
device_pixel_ratio: Cell::new(Scale::new(1.0)),
})
}
#[cfg_attr(crown, allow(crown::unrooted_must_root))]
pub(crate) fn new(
global: &PaintWorkletGlobalScope,
can_gc: CanGc,
) -> Option<DomRoot<PaintRenderingContext2D>> {
Some(reflect_dom_object(
Box::new(PaintRenderingContext2D::new_inherited(global)?),
global,
can_gc,
))
}
pub(crate) fn update_rendering(&self) -> bool {
self.canvas_state.update_rendering(None)
}
/// Send update to canvas paint thread and returns [`ImageKey`]
pub(crate) fn image_key(&self) -> ImageKey {
self.canvas_state.image_key()
}
pub(crate) fn take_missing_image_urls(&self) -> Vec<ServoUrl> {
std::mem::take(&mut self.canvas_state.get_missing_image_urls().borrow_mut())
}
pub(crate) fn set_bitmap_dimensions(
&self,
size: Size2D<f32, CSSPixel>,
device_pixel_ratio: Scale<f32, CSSPixel, DevicePixel>,
) {
let size = size * device_pixel_ratio;
self.device_pixel_ratio.set(device_pixel_ratio);
self.canvas_state
.set_bitmap_dimensions(size.to_untyped().to_u64());
self.scale_by_device_pixel_ratio();
}
fn scale_by_device_pixel_ratio(&self) {
let device_pixel_ratio = self.device_pixel_ratio.get().get() as f64;
if device_pixel_ratio != 1.0 {
self.Scale(device_pixel_ratio, device_pixel_ratio);
}
}
}
impl PaintRenderingContext2DMethods<crate::DomTypeHolder> for PaintRenderingContext2D {
// https://html.spec.whatwg.org/multipage/#dom-context-2d-save
fn Save(&self) {
self.canvas_state.save()
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-restore
fn Restore(&self) {
self.canvas_state.restore()
}
/// <https://html.spec.whatwg.org/multipage/#dom-context-2d-reset>
fn Reset(&self) {
self.canvas_state.reset()
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-scale
fn Scale(&self, x: f64, y: f64) {
self.canvas_state.scale(x, y)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-rotate
fn Rotate(&self, angle: f64) {
self.canvas_state.rotate(angle)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-translate
fn Translate(&self, x: f64, y: f64) {
self.canvas_state.translate(x, y)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-transform
fn Transform(&self, a: f64, b: f64, c: f64, d: f64, e: f64, f: f64) {
self.canvas_state.transform(a, b, c, d, e, f)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-gettransform
fn GetTransform(&self, can_gc: CanGc) -> DomRoot<DOMMatrix> {
self.canvas_state.get_transform(&self.global(), can_gc)
}
/// <https://html.spec.whatwg.org/multipage/#dom-context-2d-settransform>
fn SetTransform(&self, a: f64, b: f64, c: f64, d: f64, e: f64, f: f64) -> ErrorResult {
self.canvas_state.set_transform(a, b, c, d, e, f);
self.scale_by_device_pixel_ratio();
Ok(())
}
/// <https://html.spec.whatwg.org/multipage/#dom-context-2d-settransform-matrix>
fn SetTransform_(&self, transform: &DOMMatrix2DInit) -> ErrorResult {
self.canvas_state.set_transform_(transform)?;
self.scale_by_device_pixel_ratio();
Ok(())
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-resettransform
fn ResetTransform(&self) {
self.canvas_state.reset_transform();
self.scale_by_device_pixel_ratio();
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-globalalpha
fn GlobalAlpha(&self) -> f64 {
self.canvas_state.global_alpha()
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-globalalpha
fn SetGlobalAlpha(&self, alpha: f64) {
self.canvas_state.set_global_alpha(alpha)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-globalcompositeoperation
fn GlobalCompositeOperation(&self) -> DOMString {
self.canvas_state.global_composite_operation()
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-globalcompositeoperation
fn SetGlobalCompositeOperation(&self, op_str: DOMString) {
self.canvas_state.set_global_composite_operation(op_str)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-fillrect
fn FillRect(&self, x: f64, y: f64, width: f64, height: f64) {
self.canvas_state.fill_rect(x, y, width, height)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-clearrect
fn ClearRect(&self, x: f64, y: f64, width: f64, height: f64) {
self.canvas_state.clear_rect(x, y, width, height)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-strokerect
fn StrokeRect(&self, x: f64, y: f64, width: f64, height: f64) {
self.canvas_state.stroke_rect(x, y, width, height)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-beginpath
fn BeginPath(&self) {
self.canvas_state.begin_path()
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-closepath
fn ClosePath(&self) {
self.canvas_state.close_path()
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-fill
fn Fill(&self, fill_rule: CanvasFillRule) {
self.canvas_state.fill(fill_rule)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-fill
fn Fill_(&self, path: &Path2D, fill_rule: CanvasFillRule) {
self.canvas_state.fill_(path.segments(), fill_rule)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-stroke
fn Stroke(&self) {
self.canvas_state.stroke()
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-stroke
fn Stroke_(&self, path: &Path2D) {
self.canvas_state.stroke_(path.segments())
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-clip
fn Clip(&self, fill_rule: CanvasFillRule) {
self.canvas_state.clip(fill_rule)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-clip
fn Clip_(&self, path: &Path2D, fill_rule: CanvasFillRule) {
self.canvas_state.clip_(path.segments(), fill_rule)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-ispointinpath
fn IsPointInPath(&self, x: f64, y: f64, fill_rule: CanvasFillRule) -> bool {
self.canvas_state
.is_point_in_path(&self.global(), x, y, fill_rule)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-ispointinpath
fn IsPointInPath_(&self, path: &Path2D, x: f64, y: f64, fill_rule: CanvasFillRule) -> bool {
self.canvas_state
.is_point_in_path_(&self.global(), path.segments(), x, y, fill_rule)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-drawimage
fn DrawImage(&self, image: CanvasImageSource, dx: f64, dy: f64) -> ErrorResult {
self.canvas_state.draw_image(None, image, dx, dy)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-drawimage
fn DrawImage_(
&self,
image: CanvasImageSource,
dx: f64,
dy: f64,
dw: f64,
dh: f64,
) -> ErrorResult {
self.canvas_state.draw_image_(None, image, dx, dy, dw, dh)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-drawimage
fn DrawImage__(
&self,
image: CanvasImageSource,
sx: f64,
sy: f64,
sw: f64,
sh: f64,
dx: f64,
dy: f64,
dw: f64,
dh: f64,
) -> ErrorResult {
self.canvas_state
.draw_image__(None, image, sx, sy, sw, sh, dx, dy, dw, dh)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-moveto
fn MoveTo(&self, x: f64, y: f64) {
self.canvas_state.move_to(x, y)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-lineto
fn LineTo(&self, x: f64, y: f64) {
self.canvas_state.line_to(x, y)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-rect
fn Rect(&self, x: f64, y: f64, width: f64, height: f64) {
self.canvas_state.rect(x, y, width, height)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-quadraticcurveto
fn QuadraticCurveTo(&self, cpx: f64, cpy: f64, x: f64, y: f64) {
self.canvas_state.quadratic_curve_to(cpx, cpy, x, y)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-beziercurveto
fn BezierCurveTo(&self, cp1x: f64, cp1y: f64, cp2x: f64, cp2y: f64, x: f64, y: f64) {
self.canvas_state
.bezier_curve_to(cp1x, cp1y, cp2x, cp2y, x, y)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-arc
fn Arc(&self, x: f64, y: f64, r: f64, start: f64, end: f64, ccw: bool) -> ErrorResult {
self.canvas_state.arc(x, y, r, start, end, ccw)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-arcto
fn ArcTo(&self, cp1x: f64, cp1y: f64, cp2x: f64, cp2y: f64, r: f64) -> ErrorResult {
self.canvas_state.arc_to(cp1x, cp1y, cp2x, cp2y, r)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-ellipse
fn Ellipse(
&self,
x: f64,
y: f64,
rx: f64,
ry: f64,
rotation: f64,
start: f64,
end: f64,
ccw: bool,
) -> ErrorResult {
self.canvas_state
.ellipse(x, y, rx, ry, rotation, start, end, ccw)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-imagesmoothingenabled
fn ImageSmoothingEnabled(&self) -> bool {
self.canvas_state.image_smoothing_enabled()
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-imagesmoothingenabled
fn SetImageSmoothingEnabled(&self, value: bool) {
self.canvas_state.set_image_smoothing_enabled(value)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-strokestyle
fn StrokeStyle(&self) -> StringOrCanvasGradientOrCanvasPattern {
self.canvas_state.stroke_style()
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-strokestyle
fn SetStrokeStyle(&self, value: StringOrCanvasGradientOrCanvasPattern) {
self.canvas_state.set_stroke_style(None, value)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-strokestyle
fn FillStyle(&self) -> StringOrCanvasGradientOrCanvasPattern {
self.canvas_state.fill_style()
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-strokestyle
fn SetFillStyle(&self, value: StringOrCanvasGradientOrCanvasPattern) {
self.canvas_state.set_fill_style(None, value)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-createlineargradient
fn CreateLinearGradient(
&self,
x0: Finite<f64>,
y0: Finite<f64>,
x1: Finite<f64>,
y1: Finite<f64>,
) -> DomRoot<CanvasGradient> {
self.canvas_state
.create_linear_gradient(&self.global(), x0, y0, x1, y1, CanGc::note())
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-createradialgradient
fn CreateRadialGradient(
&self,
x0: Finite<f64>,
y0: Finite<f64>,
r0: Finite<f64>,
x1: Finite<f64>,
y1: Finite<f64>,
r1: Finite<f64>,
) -> Fallible<DomRoot<CanvasGradient>> {
self.canvas_state.create_radial_gradient(
&self.global(),
x0,
y0,
r0,
x1,
y1,
r1,
CanGc::note(),
)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-createpattern
fn CreatePattern(
&self,
image: CanvasImageSource,
repetition: DOMString,
) -> Fallible<Option<DomRoot<CanvasPattern>>> {
self.canvas_state
.create_pattern(&self.global(), image, repetition, CanGc::note())
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-linewidth
fn LineWidth(&self) -> f64 {
self.canvas_state.line_width()
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-linewidth
fn SetLineWidth(&self, width: f64) {
self.canvas_state.set_line_width(width)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-linecap
fn LineCap(&self) -> CanvasLineCap {
self.canvas_state.line_cap()
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-linecap
fn SetLineCap(&self, cap: CanvasLineCap) {
self.canvas_state.set_line_cap(cap)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-linejoin
fn LineJoin(&self) -> CanvasLineJoin {
self.canvas_state.line_join()
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-linejoin
fn SetLineJoin(&self, join: CanvasLineJoin) {
self.canvas_state.set_line_join(join)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-miterlimit
fn MiterLimit(&self) -> f64 {
self.canvas_state.miter_limit()
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-miterlimit
fn SetMiterLimit(&self, limit: f64) {
self.canvas_state.set_miter_limit(limit)
}
/// <https://html.spec.whatwg.org/multipage/#dom-context-2d-setlinedash>
fn SetLineDash(&self, segments: Vec<f64>) {
self.canvas_state.set_line_dash(segments);
}
/// <https://html.spec.whatwg.org/multipage/#dom-context-2d-getlinedash>
fn GetLineDash(&self) -> Vec<f64> {
self.canvas_state.line_dash()
}
/// <https://html.spec.whatwg.org/multipage/#dom-context-2d-linedashoffset>
fn LineDashOffset(&self) -> f64 {
self.canvas_state.line_dash_offset()
}
/// <https://html.spec.whatwg.org/multipage/#dom-context-2d-linedashoffset>
fn SetLineDashOffset(&self, offset: f64) {
self.canvas_state.set_line_dash_offset(offset);
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-shadowoffsetx
fn ShadowOffsetX(&self) -> f64 {
self.canvas_state.shadow_offset_x()
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-shadowoffsetx
fn SetShadowOffsetX(&self, value: f64) {
self.canvas_state.set_shadow_offset_x(value)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-shadowoffsety
fn ShadowOffsetY(&self) -> f64 {
self.canvas_state.shadow_offset_y()
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-shadowoffsety
fn SetShadowOffsetY(&self, value: f64) {
self.canvas_state.set_shadow_offset_y(value)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-shadowblur
fn ShadowBlur(&self) -> f64 {
self.canvas_state.shadow_blur()
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-shadowblur
fn SetShadowBlur(&self, value: f64) {
self.canvas_state.set_shadow_blur(value)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-shadowcolor
fn ShadowColor(&self) -> DOMString {
self.canvas_state.shadow_color()
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-shadowcolor
fn SetShadowColor(&self, value: DOMString) {
self.canvas_state.set_shadow_color(None, value)
}
}

View file

@ -0,0 +1,226 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use std::cell::RefCell;
use canvas_traits::canvas::Path;
use dom_struct::dom_struct;
use js::rust::HandleObject;
use script_bindings::codegen::GenericBindings::DOMMatrixBinding::DOMMatrix2DInit;
use script_bindings::error::ErrorResult;
use script_bindings::str::DOMString;
use crate::dom::bindings::codegen::Bindings::CanvasRenderingContext2DBinding::Path2DMethods;
use crate::dom::bindings::error::{Error, Fallible};
use crate::dom::bindings::reflector::{Reflector, reflect_dom_object_with_proto};
use crate::dom::bindings::root::DomRoot;
use crate::dom::dommatrixreadonly::dommatrix2dinit_to_matrix;
use crate::dom::globalscope::GlobalScope;
use crate::script_runtime::CanGc;
#[dom_struct]
pub(crate) struct Path2D {
reflector_: Reflector,
#[ignore_malloc_size_of = "Defined in kurbo."]
#[no_trace]
path: RefCell<Path>,
}
impl Path2D {
pub(crate) fn new() -> Path2D {
Self {
reflector_: Reflector::new(),
path: RefCell::new(Path::new()),
}
}
pub(crate) fn new_with_path(other: &Path2D) -> Path2D {
Self {
reflector_: Reflector::new(),
path: other.path.clone(),
}
}
pub(crate) fn new_with_str(path: &str) -> Path2D {
Self {
reflector_: Reflector::new(),
path: RefCell::new(Path::from_svg(path)),
}
}
pub(crate) fn segments(&self) -> Path {
self.path.borrow().clone()
}
pub(crate) fn is_path_empty(&self) -> bool {
self.path.borrow().0.is_empty()
}
fn add_path(&self, other: &Path2D, transform: &DOMMatrix2DInit) -> ErrorResult {
// Step 1. If the Path2D object path has no subpaths, then return.
if other.is_path_empty() {
return Ok(());
}
// Step 2 Let matrix be the result of creating a DOMMatrix from the 2D dictionary transform.
let matrix = dommatrix2dinit_to_matrix(transform)?;
// Step 3. If one or more of matrix's m11 element, m12 element, m21
// element, m22 element, m41 element, or m42 element are infinite or
// NaN, then return.
if !matrix.m11.is_finite() ||
!matrix.m12.is_finite() ||
!matrix.m21.is_finite() ||
!matrix.m22.is_finite() ||
!matrix.m31.is_finite() ||
!matrix.m32.is_finite()
{
return Ok(());
}
// Step 4. Create a copy of all the subpaths in path. Let c be this copy.
let mut c = other.segments();
// Step 5. Transform all the coordinates and lines in c by the transform matrix `matrix`.
c.transform(matrix);
let mut path = self.path.borrow_mut();
// Step 6. Let (x, y) be the last point in the last subpath of c
let last_point = path.last_point();
// Step 7. Add all the subpaths in c to a.
path.0.extend(c.0);
// Step 8. Create a new subpath in `a` with (x, y) as the only point in the subpath.
if let Some(last_point) = last_point {
path.move_to(last_point.x, last_point.y);
}
Ok(())
}
}
impl Path2DMethods<crate::DomTypeHolder> for Path2D {
/// <https://html.spec.whatwg.org/multipage/#dom-path2d-addpath>
fn AddPath(&self, other: &Path2D, transform: &DOMMatrix2DInit) -> ErrorResult {
self.add_path(other, transform)
}
/// <https://html.spec.whatwg.org/multipage/#dom-context-2d-closepath>
fn ClosePath(&self) {
self.path.borrow_mut().close_path();
}
/// <https://html.spec.whatwg.org/multipage/#dom-context-2d-moveto>
fn MoveTo(&self, x: f64, y: f64) {
self.path.borrow_mut().move_to(x, y);
}
/// <https://html.spec.whatwg.org/multipage/#dom-context-2d-lineto>
fn LineTo(&self, x: f64, y: f64) {
self.path.borrow_mut().line_to(x, y);
}
/// <https://html.spec.whatwg.org/multipage/#dom-context-2d-quadraticcurveto>
fn QuadraticCurveTo(&self, cpx: f64, cpy: f64, x: f64, y: f64) {
self.path.borrow_mut().quadratic_curve_to(cpx, cpy, x, y);
}
/// <https://html.spec.whatwg.org/multipage/#dom-context-2d-beziercurveto>
fn BezierCurveTo(&self, cp1x: f64, cp1y: f64, cp2x: f64, cp2y: f64, x: f64, y: f64) {
self.path
.borrow_mut()
.bezier_curve_to(cp1x, cp1y, cp2x, cp2y, x, y);
}
/// <https://html.spec.whatwg.org/multipage/#dom-context-2d-arcto>
fn ArcTo(&self, x1: f64, y1: f64, x2: f64, y2: f64, radius: f64) -> Fallible<()> {
self.path
.borrow_mut()
.arc_to(x1, y1, x2, y2, radius)
.map_err(|_| Error::IndexSize)
}
/// <https://html.spec.whatwg.org/multipage/#dom-context-2d-rect>
fn Rect(&self, x: f64, y: f64, w: f64, h: f64) {
self.path.borrow_mut().rect(x, y, w, h);
}
/// <https://html.spec.whatwg.org/multipage/#dom-context-2d-arc>
fn Arc(
&self,
x: f64,
y: f64,
radius: f64,
start_angle: f64,
end_angle: f64,
counterclockwise: bool,
) -> Fallible<()> {
self.path
.borrow_mut()
.arc(x, y, radius, start_angle, end_angle, counterclockwise)
.map_err(|_| Error::IndexSize)
}
/// <https://html.spec.whatwg.org/multipage/#dom-context-2d-ellipse>
fn Ellipse(
&self,
x: f64,
y: f64,
radius_x: f64,
radius_y: f64,
rotation_angle: f64,
start_angle: f64,
end_angle: f64,
counterclockwise: bool,
) -> Fallible<()> {
self.path
.borrow_mut()
.ellipse(
x,
y,
radius_x,
radius_y,
rotation_angle,
start_angle,
end_angle,
counterclockwise,
)
.map_err(|_| Error::IndexSize)
}
/// <https://html.spec.whatwg.org/multipage/#dom-path2d-dev>
fn Constructor(
global: &GlobalScope,
proto: Option<HandleObject>,
can_gc: CanGc,
) -> DomRoot<Path2D> {
reflect_dom_object_with_proto(Box::new(Self::new()), global, proto, can_gc)
}
/// <https://html.spec.whatwg.org/multipage/#dom-path2d-dev>
fn Constructor_(
global: &GlobalScope,
proto: Option<HandleObject>,
can_gc: CanGc,
other: &Path2D,
) -> DomRoot<Path2D> {
reflect_dom_object_with_proto(Box::new(Self::new_with_path(other)), global, proto, can_gc)
}
/// <https://html.spec.whatwg.org/multipage/#dom-path2d-dev>
fn Constructor__(
global: &GlobalScope,
proto: Option<HandleObject>,
can_gc: CanGc,
path_string: DOMString,
) -> DomRoot<Path2D> {
reflect_dom_object_with_proto(
Box::new(Self::new_with_str(path_string.str())),
global,
proto,
can_gc,
)
}
}

View file

@ -0,0 +1,186 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use dom_struct::dom_struct;
use crate::dom::bindings::codegen::Bindings::TextMetricsBinding::TextMetricsMethods;
use crate::dom::bindings::num::Finite;
use crate::dom::bindings::reflector::{Reflector, reflect_dom_object};
use crate::dom::bindings::root::DomRoot;
use crate::dom::globalscope::GlobalScope;
use crate::script_runtime::CanGc;
#[dom_struct]
#[allow(non_snake_case)]
pub(crate) struct TextMetrics {
reflector_: Reflector,
width: Finite<f64>,
actualBoundingBoxLeft: Finite<f64>,
actualBoundingBoxRight: Finite<f64>,
fontBoundingBoxAscent: Finite<f64>,
fontBoundingBoxDescent: Finite<f64>,
actualBoundingBoxAscent: Finite<f64>,
actualBoundingBoxDescent: Finite<f64>,
emHeightAscent: Finite<f64>,
emHeightDescent: Finite<f64>,
hangingBaseline: Finite<f64>,
alphabeticBaseline: Finite<f64>,
ideographicBaseline: Finite<f64>,
}
#[allow(non_snake_case)]
impl TextMetrics {
#[allow(clippy::too_many_arguments)]
fn new_inherited(
width: f64,
actualBoundingBoxLeft: f64,
actualBoundingBoxRight: f64,
fontBoundingBoxAscent: f64,
fontBoundingBoxDescent: f64,
actualBoundingBoxAscent: f64,
actualBoundingBoxDescent: f64,
emHeightAscent: f64,
emHeightDescent: f64,
hangingBaseline: f64,
alphabeticBaseline: f64,
ideographicBaseline: f64,
) -> TextMetrics {
TextMetrics {
reflector_: Reflector::new(),
width: Finite::wrap(width),
actualBoundingBoxLeft: Finite::wrap(actualBoundingBoxLeft),
actualBoundingBoxRight: Finite::wrap(actualBoundingBoxRight),
fontBoundingBoxAscent: Finite::wrap(fontBoundingBoxAscent),
fontBoundingBoxDescent: Finite::wrap(fontBoundingBoxDescent),
actualBoundingBoxAscent: Finite::wrap(actualBoundingBoxAscent),
actualBoundingBoxDescent: Finite::wrap(actualBoundingBoxDescent),
emHeightAscent: Finite::wrap(emHeightAscent),
emHeightDescent: Finite::wrap(emHeightDescent),
hangingBaseline: Finite::wrap(hangingBaseline),
alphabeticBaseline: Finite::wrap(alphabeticBaseline),
ideographicBaseline: Finite::wrap(ideographicBaseline),
}
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn new(
global: &GlobalScope,
width: f64,
actualBoundingBoxLeft: f64,
actualBoundingBoxRight: f64,
fontBoundingBoxAscent: f64,
fontBoundingBoxDescent: f64,
actualBoundingBoxAscent: f64,
actualBoundingBoxDescent: f64,
emHeightAscent: f64,
emHeightDescent: f64,
hangingBaseline: f64,
alphabeticBaseline: f64,
ideographicBaseline: f64,
can_gc: CanGc,
) -> DomRoot<TextMetrics> {
reflect_dom_object(
Box::new(TextMetrics::new_inherited(
width,
actualBoundingBoxLeft,
actualBoundingBoxRight,
fontBoundingBoxAscent,
fontBoundingBoxDescent,
actualBoundingBoxAscent,
actualBoundingBoxDescent,
emHeightAscent,
emHeightDescent,
hangingBaseline,
alphabeticBaseline,
ideographicBaseline,
)),
global,
can_gc,
)
}
pub(crate) fn default(global: &GlobalScope, can_gc: CanGc) -> DomRoot<Self> {
reflect_dom_object(
Box::new(Self {
reflector_: Reflector::new(),
width: Default::default(),
actualBoundingBoxLeft: Default::default(),
actualBoundingBoxRight: Default::default(),
fontBoundingBoxAscent: Default::default(),
fontBoundingBoxDescent: Default::default(),
actualBoundingBoxAscent: Default::default(),
actualBoundingBoxDescent: Default::default(),
emHeightAscent: Default::default(),
emHeightDescent: Default::default(),
hangingBaseline: Default::default(),
alphabeticBaseline: Default::default(),
ideographicBaseline: Default::default(),
}),
global,
can_gc,
)
}
}
impl TextMetricsMethods<crate::DomTypeHolder> for TextMetrics {
/// <https://html.spec.whatwg.org/multipage/#dom-textmetrics-width>
fn Width(&self) -> Finite<f64> {
self.width
}
/// <https://html.spec.whatwg.org/multipage/#dom-textmetrics-actualboundingboxleft>
fn ActualBoundingBoxLeft(&self) -> Finite<f64> {
self.actualBoundingBoxLeft
}
/// <https://html.spec.whatwg.org/multipage/#dom-textmetrics-actualboundingboxright>
fn ActualBoundingBoxRight(&self) -> Finite<f64> {
self.actualBoundingBoxRight
}
/// <https://html.spec.whatwg.org/multipage/#dom-textmetrics-fontboundingboxascent>
fn FontBoundingBoxAscent(&self) -> Finite<f64> {
self.fontBoundingBoxAscent
}
/// <https://html.spec.whatwg.org/multipage/#dom-textmetrics-fontboundingboxascent>
fn FontBoundingBoxDescent(&self) -> Finite<f64> {
self.fontBoundingBoxDescent
}
/// <https://html.spec.whatwg.org/multipage/#dom-textmetrics-actualboundingboxascent>
fn ActualBoundingBoxAscent(&self) -> Finite<f64> {
self.actualBoundingBoxAscent
}
/// <https://html.spec.whatwg.org/multipage/#dom-textmetrics-actualboundingboxdescent>
fn ActualBoundingBoxDescent(&self) -> Finite<f64> {
self.actualBoundingBoxDescent
}
/// <https://html.spec.whatwg.org/multipage/#dom-textmetrics-emheightascent>
fn EmHeightAscent(&self) -> Finite<f64> {
self.emHeightAscent
}
/// <https://html.spec.whatwg.org/multipage/#dom-textmetrics-emheightdescent>
fn EmHeightDescent(&self) -> Finite<f64> {
self.emHeightDescent
}
/// <https://html.spec.whatwg.org/multipage/#dom-textmetrics-hangingbaseline>
fn HangingBaseline(&self) -> Finite<f64> {
self.hangingBaseline
}
/// <https://html.spec.whatwg.org/multipage/#dom-textmetrics-alphabeticbaseline>
fn AlphabeticBaseline(&self) -> Finite<f64> {
self.alphabeticBaseline
}
/// <https://html.spec.whatwg.org/multipage/#dom-textmetrics-ideographicbaseline>
fn IdeographicBaseline(&self) -> Finite<f64> {
self.ideographicBaseline
}
}