webrender/
render_api.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5#![deny(missing_docs)]
6
7use api::precise_time_ns;
8use std::cell::Cell;
9use std::fmt;
10use std::marker::PhantomData;
11use std::path::PathBuf;
12use std::sync::Arc;
13use std::u32;
14use api::{HitTestFlags, MinimapData, SnapshotImageKey};
15use crate::api::channel::{Sender, single_msg_channel, unbounded_channel};
16use crate::api::{BuiltDisplayList, IdNamespace, ExternalScrollId, Parameter, BoolParameter};
17use crate::api::{FontKey, FontInstanceKey, NativeFontHandle};
18use crate::api::{BlobImageData, BlobImageKey, ImageData, ImageDescriptor, ImageKey, Epoch, QualitySettings};
19use crate::api::{BlobImageParams, BlobImageRequest, BlobImageResult, AsyncBlobImageRasterizer, BlobImageHandler};
20use crate::api::{DocumentId, PipelineId, PropertyBindingId, PropertyBindingKey, ExternalEvent};
21use crate::api::{HitTestResult, HitTesterRequest, ApiHitTester, PropertyValue, DynamicProperties};
22use crate::api::{SampledScrollOffset, TileSize, NotificationRequest, DebugFlags};
23use crate::api::{GlyphDimensionRequest, GlyphIndexRequest, GlyphIndex, GlyphDimensions};
24use crate::api::{FontInstanceOptions, FontInstancePlatformOptions, FontVariation, RenderReasons};
25use crate::api::DEFAULT_TILE_SIZE;
26use crate::api::units::*;
27use crate::api_resources::ApiResources;
28use glyph_rasterizer::SharedFontResources;
29use crate::scene_builder_thread::{SceneBuilderRequest, SceneBuilderResult};
30use crate::intern::InterningMemoryReport;
31use crate::profiler::{self, TransactionProfile};
32
33#[repr(C)]
34#[derive(Clone, Copy, Debug)]
35#[cfg_attr(any(feature = "serde"), derive(Deserialize, Serialize))]
36struct ResourceId(pub u32);
37
38/// Update of a persistent resource in WebRender.
39///
40/// ResourceUpdate changes keep theirs effect across display list changes.
41#[derive(Clone)]
42#[cfg_attr(any(feature = "serde"), derive(Deserialize, Serialize))]
43pub enum ResourceUpdate {
44    /// See `AddImage`.
45    AddImage(AddImage),
46    /// See `UpdateImage`.
47    UpdateImage(UpdateImage),
48    /// Delete an existing image resource.
49    ///
50    /// It is invalid to continue referring to the image key in any display list
51    /// in the transaction that contains the `DeleteImage` message and subsequent
52    /// transactions.
53    DeleteImage(ImageKey),
54    /// See `AddBlobImage`.
55    AddBlobImage(AddBlobImage),
56    /// See `UpdateBlobImage`.
57    UpdateBlobImage(UpdateBlobImage),
58    /// Delete existing blob image resource.
59    DeleteBlobImage(BlobImageKey),
60    /// See `AddBlobImage::visible_area`.
61    SetBlobImageVisibleArea(BlobImageKey, DeviceIntRect),
62    /// See `AddSnapshotImage`.
63    AddSnapshotImage(AddSnapshotImage),
64    /// See `AddSnapshotImage`.
65    DeleteSnapshotImage(SnapshotImageKey),
66    /// See `AddFont`.
67    AddFont(AddFont),
68    /// Deletes an already existing font resource.
69    ///
70    /// It is invalid to continue referring to the font key in any display list
71    /// in the transaction that contains the `DeleteImage` message and subsequent
72    /// transactions.
73    DeleteFont(FontKey),
74    /// See `AddFontInstance`.
75    AddFontInstance(AddFontInstance),
76    /// Deletes an already existing font instance resource.
77    ///
78    /// It is invalid to continue referring to the font instance in any display
79    /// list in the transaction that contains the `DeleteImage` message and
80    /// subsequent transactions.
81    DeleteFontInstance(FontInstanceKey),
82}
83
84impl fmt::Debug for ResourceUpdate {
85    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
86        match self {
87            ResourceUpdate::AddImage(ref i) => f.write_fmt(format_args!(
88                "ResourceUpdate::AddImage size({:?})",
89                &i.descriptor.size
90            )),
91            ResourceUpdate::UpdateImage(ref i) => f.write_fmt(format_args!(
92                "ResourceUpdate::UpdateImage size({:?})",
93                &i.descriptor.size
94            )),
95            ResourceUpdate::AddBlobImage(ref i) => f.write_fmt(format_args!(
96                "ResourceUFpdate::AddBlobImage size({:?})",
97                &i.descriptor.size
98            )),
99            ResourceUpdate::UpdateBlobImage(i) => f.write_fmt(format_args!(
100                "ResourceUpdate::UpdateBlobImage size({:?})",
101                &i.descriptor.size
102            )),
103            ResourceUpdate::DeleteImage(..) => f.write_str("ResourceUpdate::DeleteImage"),
104            ResourceUpdate::DeleteBlobImage(..) => f.write_str("ResourceUpdate::DeleteBlobImage"),
105            ResourceUpdate::SetBlobImageVisibleArea(..) => f.write_str("ResourceUpdate::SetBlobImageVisibleArea"),
106            ResourceUpdate::AddSnapshotImage(..) => f.write_str("ResourceUpdate::AddSnapshotImage"),
107            ResourceUpdate::DeleteSnapshotImage(..) => f.write_str("ResourceUpdate::DeleteSnapshotImage"),
108            ResourceUpdate::AddFont(..) => f.write_str("ResourceUpdate::AddFont"),
109            ResourceUpdate::DeleteFont(..) => f.write_str("ResourceUpdate::DeleteFont"),
110            ResourceUpdate::AddFontInstance(..) => f.write_str("ResourceUpdate::AddFontInstance"),
111            ResourceUpdate::DeleteFontInstance(..) => f.write_str("ResourceUpdate::DeleteFontInstance"),
112        }
113    }
114}
115
116/// Whether to generate a frame, and if so, an id that allows tracking this
117/// transaction through the various frame stages.
118#[derive(Clone, Debug)]
119pub enum GenerateFrame {
120    /// Generate a frame if something changed.
121    Yes {
122        /// An id that allows tracking the frame transaction through the various
123        /// frame stages. Specified by the caller of generate_frame().
124        id: u64,
125        /// If false, (a subset of) the frame will be rendered, but nothing will
126        /// be presented on the window.
127        present: bool,
128    },
129    /// Don't generate a frame even if something has changed.
130    No,
131}
132
133impl GenerateFrame {
134    ///
135    pub fn as_bool(&self) -> bool {
136        match self {
137            GenerateFrame::Yes { .. } => true,
138            GenerateFrame::No => false,
139        }
140    }
141
142    /// If false, a frame may be (partially) generated but it will not be
143    /// presented to the window.
144    pub fn present(&self) -> bool {
145        match self {
146            GenerateFrame::Yes { present, .. } => *present,
147            GenerateFrame::No => false,
148        }
149    }
150
151    /// Return the frame ID, if a frame is generated.
152    pub fn id(&self) -> Option<u64> {
153        match self {
154            GenerateFrame::Yes { id, .. } => Some(*id),
155            GenerateFrame::No => None,
156        }
157    }
158}
159
160/// A Transaction is a group of commands to apply atomically to a document.
161///
162/// This mechanism ensures that:
163///  - no other message can be interleaved between two commands that need to be applied together.
164///  - no redundant work is performed if two commands in the same transaction cause the scene or
165///    the frame to be rebuilt.
166pub struct Transaction {
167    /// Operations affecting the scene (applied before scene building).
168    scene_ops: Vec<SceneMsg>,
169    /// Operations affecting the generation of frames (applied after scene building).
170    frame_ops: Vec<FrameMsg>,
171
172    notifications: Vec<NotificationRequest>,
173
174    /// Persistent resource updates to apply as part of this transaction.
175    pub resource_updates: Vec<ResourceUpdate>,
176
177    /// True if the transaction needs the scene building thread's attention.
178    /// False for things that can skip the scene builder, like APZ changes and
179    /// async images.
180    ///
181    /// Before this `Transaction` is converted to a `TransactionMsg`, we look
182    /// over its contents and set this if we're doing anything the scene builder
183    /// needs to know about, so this is only a default.
184    use_scene_builder_thread: bool,
185
186    /// Whether to generate a frame, and if so, an id that allows tracking this
187    /// transaction through the various frame stages. Specified by the caller of
188    /// generate_frame().
189    generate_frame: GenerateFrame,
190
191    /// Time when this transaction was constructed.
192    creation_time: u64,
193
194    /// Set to true in order to force re-rendering even if WebRender can't internally
195    /// detect that something has changed.
196    pub invalidate_rendered_frame: bool,
197
198    low_priority: bool,
199
200    ///
201    pub render_reasons: RenderReasons,
202}
203
204impl Transaction {
205    /// Constructor.
206    pub fn new() -> Self {
207        Transaction {
208            scene_ops: Vec::new(),
209            frame_ops: Vec::new(),
210            resource_updates: Vec::new(),
211            notifications: Vec::new(),
212            use_scene_builder_thread: true,
213            generate_frame: GenerateFrame::No,
214            creation_time: precise_time_ns(),
215            invalidate_rendered_frame: false,
216            low_priority: false,
217            render_reasons: RenderReasons::empty(),
218        }
219    }
220
221    /// Marks this transaction to allow it to skip going through the scene builder
222    /// thread.
223    ///
224    /// This is useful to avoid jank in transaction associated with animated
225    /// property updates, panning and zooming.
226    ///
227    /// Note that transactions that skip the scene builder thread can race ahead of
228    /// transactions that don't skip it.
229    pub fn skip_scene_builder(&mut self) {
230        self.use_scene_builder_thread = false;
231    }
232
233    /// Marks this transaction to enforce going through the scene builder thread.
234    pub fn use_scene_builder_thread(&mut self) {
235        self.use_scene_builder_thread = true;
236    }
237
238    /// Returns true if the transaction has no effect.
239    pub fn is_empty(&self) -> bool {
240        !self.generate_frame.as_bool() &&
241            !self.invalidate_rendered_frame &&
242            self.scene_ops.is_empty() &&
243            self.frame_ops.is_empty() &&
244            self.resource_updates.is_empty() &&
245            self.notifications.is_empty()
246    }
247
248    /// Update a pipeline's epoch.
249    pub fn update_epoch(&mut self, pipeline_id: PipelineId, epoch: Epoch) {
250        // We track epochs before and after scene building.
251        // This one will be applied to the pending scene right away:
252        self.scene_ops.push(SceneMsg::UpdateEpoch(pipeline_id, epoch));
253        // And this one will be applied to the currently built scene at the end
254        // of the transaction (potentially long after the scene_ops one).
255        self.frame_ops.push(FrameMsg::UpdateEpoch(pipeline_id, epoch));
256        // We could avoid the duplication here by storing the epoch updates in a
257        // separate array and let the render backend schedule the updates at the
258        // proper times, but it wouldn't make things simpler.
259    }
260
261    /// Sets the root pipeline.
262    ///
263    /// # Examples
264    ///
265    /// ```
266    /// # use webrender::api::{PipelineId};
267    /// # use webrender::api::units::{DeviceIntSize};
268    /// # use webrender::render_api::{RenderApiSender, Transaction};
269    /// # fn example() {
270    /// let pipeline_id = PipelineId(0, 0);
271    /// let mut txn = Transaction::new();
272    /// txn.set_root_pipeline(pipeline_id);
273    /// # }
274    /// ```
275    pub fn set_root_pipeline(&mut self, pipeline_id: PipelineId) {
276        self.scene_ops.push(SceneMsg::SetRootPipeline(pipeline_id));
277    }
278
279    /// Removes data associated with a pipeline from the internal data structures.
280    /// If the specified `pipeline_id` is for the root pipeline, the root pipeline
281    /// is reset back to `None`.
282    pub fn remove_pipeline(&mut self, pipeline_id: PipelineId) {
283        self.scene_ops.push(SceneMsg::RemovePipeline(pipeline_id));
284    }
285
286    /// Supplies a new frame to WebRender.
287    ///
288    /// Non-blocking, it notifies a worker process which processes the display list.
289    ///
290    /// Note: Scrolling doesn't require an own Frame.
291    ///
292    /// Arguments:
293    ///
294    /// * `epoch`: The unique Frame ID, monotonically increasing.
295    /// * `pipeline_id`: The ID of the pipeline that is supplying this display list.
296    /// * `display_list`: The root Display list used in this frame.
297    pub fn set_display_list(
298        &mut self,
299        epoch: Epoch,
300        (pipeline_id, mut display_list): (PipelineId, BuiltDisplayList),
301    ) {
302        display_list.set_send_time_ns(precise_time_ns());
303        self.scene_ops.push(
304            SceneMsg::SetDisplayList {
305                display_list,
306                epoch,
307                pipeline_id,
308            }
309        );
310    }
311
312    /// Add a set of persistent resource updates to apply as part of this transaction.
313    pub fn update_resources(&mut self, mut resources: Vec<ResourceUpdate>) {
314        self.resource_updates.append(&mut resources);
315    }
316
317    // Note: Gecko uses this to get notified when a transaction that contains
318    // potentially long blob rasterization or scene build is ready to be rendered.
319    // so that the tab-switching integration can react adequately when tab
320    // switching takes too long. For this use case when matters is that the
321    // notification doesn't fire before scene building and blob rasterization.
322
323    /// Trigger a notification at a certain stage of the rendering pipeline.
324    ///
325    /// Not that notification requests are skipped during serialization, so is is
326    /// best to use them for synchronization purposes and not for things that could
327    /// affect the WebRender's state.
328    pub fn notify(&mut self, event: NotificationRequest) {
329        self.notifications.push(event);
330    }
331
332    /// Setup the output region in the framebuffer for a given document.
333    pub fn set_document_view(
334        &mut self,
335        device_rect: DeviceIntRect,
336    ) {
337        window_size_sanity_check(device_rect.size());
338        self.scene_ops.push(
339            SceneMsg::SetDocumentView {
340                device_rect,
341            },
342        );
343    }
344
345    /// Set multiple scroll offsets with generations to the node identified by
346    /// the given external scroll id, the scroll offsets are relative to the
347    /// pre-scrolled offset for the scrolling layer.
348    pub fn set_scroll_offsets(
349        &mut self,
350        id: ExternalScrollId,
351        sampled_scroll_offsets: Vec<SampledScrollOffset>,
352    ) {
353        self.frame_ops.push(FrameMsg::SetScrollOffsets(id, sampled_scroll_offsets));
354    }
355
356    /// Set the current quality / performance settings for this document.
357    pub fn set_quality_settings(&mut self, settings: QualitySettings) {
358        self.scene_ops.push(SceneMsg::SetQualitySettings { settings });
359    }
360
361    ///
362    pub fn set_is_transform_async_zooming(&mut self, is_zooming: bool, animation_id: PropertyBindingId) {
363        self.frame_ops.push(FrameMsg::SetIsTransformAsyncZooming(is_zooming, animation_id));
364    }
365
366    /// Specify data for APZ minimap debug overlay to be composited
367    pub fn set_minimap_data(&mut self, id: ExternalScrollId, minimap_data: MinimapData) {
368      self.frame_ops.push(FrameMsg::SetMinimapData(id, minimap_data));
369    }
370
371    /// Generate a new frame. When it's done and a RenderNotifier has been set
372    /// in `webrender::Renderer`, [new_frame_ready()][notifier] gets called.
373    /// Note that the notifier is called even if the frame generation was a
374    /// no-op; the arguments passed to `new_frame_ready` will provide information
375    /// as to when happened.
376    ///
377    /// [notifier]: trait.RenderNotifier.html#tymethod.new_frame_ready
378    pub fn generate_frame(&mut self, id: u64, present: bool, reasons: RenderReasons) {
379        self.generate_frame = GenerateFrame::Yes{ id, present };
380        self.render_reasons |= reasons;
381    }
382
383    /// Invalidate rendered frame. It ensure that frame will be rendered during
384    /// next frame generation. WebRender could skip frame rendering if there
385    /// is no update.
386    /// But there are cases that needs to force rendering.
387    ///  - Content of image is updated by reusing same ExternalImageId.
388    ///  - Platform requests it if pixels become stale (like wakeup from standby).
389    pub fn invalidate_rendered_frame(&mut self, reasons: RenderReasons) {
390        self.invalidate_rendered_frame = true;
391        self.render_reasons |= reasons
392    }
393
394    /// Reset the list of animated property bindings that should be used to resolve
395    /// bindings in the current display list.
396    pub fn reset_dynamic_properties(&mut self) {
397        self.frame_ops.push(FrameMsg::ResetDynamicProperties);
398    }
399
400    /// Add to the list of animated property bindings that should be used to resolve
401    /// bindings in the current display list.
402    pub fn append_dynamic_properties(&mut self, properties: DynamicProperties) {
403        self.frame_ops.push(FrameMsg::AppendDynamicProperties(properties));
404    }
405
406    /// Add to the list of animated property bindings that should be used to
407    /// resolve bindings in the current display list. This is a convenience method
408    /// so the caller doesn't have to figure out all the dynamic properties before
409    /// setting them on the transaction but can do them incrementally.
410    pub fn append_dynamic_transform_properties(&mut self, transforms: Vec<PropertyValue<LayoutTransform>>) {
411        self.frame_ops.push(FrameMsg::AppendDynamicTransformProperties(transforms));
412    }
413
414    /// Consumes this object and just returns the frame ops.
415    pub fn get_frame_ops(self) -> Vec<FrameMsg> {
416        self.frame_ops
417    }
418
419    fn finalize(self, document_id: DocumentId) -> Box<TransactionMsg> {
420        Box::new(TransactionMsg {
421            document_id,
422            scene_ops: self.scene_ops,
423            frame_ops: self.frame_ops,
424            resource_updates: self.resource_updates,
425            notifications: self.notifications,
426            use_scene_builder_thread: self.use_scene_builder_thread,
427            generate_frame: self.generate_frame,
428            creation_time: Some(self.creation_time),
429            invalidate_rendered_frame: self.invalidate_rendered_frame,
430            low_priority: self.low_priority,
431            blob_rasterizer: None,
432            blob_requests: Vec::new(),
433            rasterized_blobs: Vec::new(),
434            profile: TransactionProfile::new(),
435            render_reasons: self.render_reasons,
436        })
437    }
438
439    /// See `ResourceUpdate::AddImage`.
440    pub fn add_image(
441        &mut self,
442        key: ImageKey,
443        descriptor: ImageDescriptor,
444        data: ImageData,
445        tiling: Option<TileSize>,
446    ) {
447        self.resource_updates.push(ResourceUpdate::AddImage(AddImage {
448            key,
449            descriptor,
450            data,
451            tiling,
452        }));
453    }
454
455    /// See `ResourceUpdate::UpdateImage`.
456    pub fn update_image(
457        &mut self,
458        key: ImageKey,
459        descriptor: ImageDescriptor,
460        data: ImageData,
461        dirty_rect: &ImageDirtyRect,
462    ) {
463        self.resource_updates.push(ResourceUpdate::UpdateImage(UpdateImage {
464            key,
465            descriptor,
466            data,
467            dirty_rect: *dirty_rect,
468        }));
469    }
470
471    /// See `ResourceUpdate::DeleteImage`.
472    pub fn delete_image(&mut self, key: ImageKey) {
473        self.resource_updates.push(ResourceUpdate::DeleteImage(key));
474    }
475
476    /// See `ResourceUpdate::AddBlobImage`.
477    pub fn add_blob_image(
478        &mut self,
479        key: BlobImageKey,
480        descriptor: ImageDescriptor,
481        data: Arc<BlobImageData>,
482        visible_rect: DeviceIntRect,
483        tile_size: Option<TileSize>,
484    ) {
485        self.resource_updates.push(
486            ResourceUpdate::AddBlobImage(AddBlobImage {
487                key,
488                descriptor,
489                data,
490                visible_rect,
491                tile_size: tile_size.unwrap_or(DEFAULT_TILE_SIZE),
492            })
493        );
494    }
495
496    /// See `ResourceUpdate::UpdateBlobImage`.
497    pub fn update_blob_image(
498        &mut self,
499        key: BlobImageKey,
500        descriptor: ImageDescriptor,
501        data: Arc<BlobImageData>,
502        visible_rect: DeviceIntRect,
503        dirty_rect: &BlobDirtyRect,
504    ) {
505        self.resource_updates.push(
506            ResourceUpdate::UpdateBlobImage(UpdateBlobImage {
507                key,
508                descriptor,
509                data,
510                visible_rect,
511                dirty_rect: *dirty_rect,
512            })
513        );
514    }
515
516    /// See `ResourceUpdate::DeleteBlobImage`.
517    pub fn delete_blob_image(&mut self, key: BlobImageKey) {
518        self.resource_updates.push(ResourceUpdate::DeleteBlobImage(key));
519    }
520
521    /// See `ResourceUpdate::SetBlobImageVisibleArea`.
522    pub fn set_blob_image_visible_area(&mut self, key: BlobImageKey, area: DeviceIntRect) {
523        self.resource_updates.push(ResourceUpdate::SetBlobImageVisibleArea(key, area));
524    }
525
526    /// See `ResourceUpdate::AddSnapshotImage`.
527    pub fn add_snapshot_image(
528        &mut self,
529        key: SnapshotImageKey,
530    ) {
531        self.resource_updates.push(
532            ResourceUpdate::AddSnapshotImage(AddSnapshotImage { key })
533        );
534    }
535
536    /// See `ResourceUpdate::DeleteSnapshotImage`.
537    pub fn delete_snapshot_image(&mut self, key: SnapshotImageKey) {
538        self.resource_updates.push(ResourceUpdate::DeleteSnapshotImage(key));
539    }
540
541    /// See `ResourceUpdate::AddFont`.
542    pub fn add_raw_font(&mut self, key: FontKey, bytes: Vec<u8>, index: u32) {
543        self.resource_updates
544            .push(ResourceUpdate::AddFont(AddFont::Raw(key, Arc::new(bytes), index)));
545    }
546
547    /// See `ResourceUpdate::AddFont`.
548    pub fn add_native_font(&mut self, key: FontKey, native_handle: NativeFontHandle) {
549        self.resource_updates
550            .push(ResourceUpdate::AddFont(AddFont::Native(key, native_handle)));
551    }
552
553    /// See `ResourceUpdate::DeleteFont`.
554    pub fn delete_font(&mut self, key: FontKey) {
555        self.resource_updates.push(ResourceUpdate::DeleteFont(key));
556    }
557
558    /// See `ResourceUpdate::AddFontInstance`.
559    pub fn add_font_instance(
560        &mut self,
561        key: FontInstanceKey,
562        font_key: FontKey,
563        glyph_size: f32,
564        options: Option<FontInstanceOptions>,
565        platform_options: Option<FontInstancePlatformOptions>,
566        variations: Vec<FontVariation>,
567    ) {
568        self.resource_updates
569            .push(ResourceUpdate::AddFontInstance(AddFontInstance {
570                key,
571                font_key,
572                glyph_size,
573                options,
574                platform_options,
575                variations,
576            }));
577    }
578
579    /// See `ResourceUpdate::DeleteFontInstance`.
580    pub fn delete_font_instance(&mut self, key: FontInstanceKey) {
581        self.resource_updates.push(ResourceUpdate::DeleteFontInstance(key));
582    }
583
584    /// A hint that this transaction can be processed at a lower priority. High-
585    /// priority transactions can jump ahead of regular-priority transactions,
586    /// but both high- and regular-priority transactions are processed in order
587    /// relative to other transactions of the same priority.
588    pub fn set_low_priority(&mut self, low_priority: bool) {
589        self.low_priority = low_priority;
590    }
591
592    /// Returns whether this transaction is marked as low priority.
593    pub fn is_low_priority(&self) -> bool {
594        self.low_priority
595    }
596}
597
598///
599pub struct DocumentTransaction {
600    ///
601    pub document_id: DocumentId,
602    ///
603    pub transaction: Transaction,
604}
605
606/// Represents a transaction in the format sent through the channel.
607pub struct TransactionMsg {
608    ///
609    pub document_id: DocumentId,
610    /// Changes that require re-building the scene.
611    pub scene_ops: Vec<SceneMsg>,
612    /// Changes to animated properties that do not require re-building the scene.
613    pub frame_ops: Vec<FrameMsg>,
614    /// Updates to resources that persist across display lists.
615    pub resource_updates: Vec<ResourceUpdate>,
616    /// Whether to trigger frame building and rendering if something has changed.
617    pub generate_frame: GenerateFrame,
618    /// Creation time of this transaction.
619    pub creation_time: Option<u64>,
620    /// Whether to force frame building and rendering even if no changes are internally
621    /// observed.
622    pub invalidate_rendered_frame: bool,
623    /// Whether to enforce that this transaction go through the scene builder.
624    pub use_scene_builder_thread: bool,
625    ///
626    pub low_priority: bool,
627
628    /// Handlers to notify at certain points of the pipeline.
629    pub notifications: Vec<NotificationRequest>,
630    ///
631    pub blob_rasterizer: Option<Box<dyn AsyncBlobImageRasterizer>>,
632    ///
633    pub blob_requests: Vec<BlobImageParams>,
634    ///
635    pub rasterized_blobs: Vec<(BlobImageRequest, BlobImageResult)>,
636    /// Collect various data along the rendering pipeline to display it in the embedded profiler.
637    pub profile: TransactionProfile,
638    /// Keep track of who asks rendering to happen.
639    pub render_reasons: RenderReasons,
640}
641
642impl fmt::Debug for TransactionMsg {
643    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
644        writeln!(f, "threaded={}, genframe={:?}, invalidate={}, low_priority={}",
645                        self.use_scene_builder_thread,
646                        self.generate_frame,
647                        self.invalidate_rendered_frame,
648                        self.low_priority,
649                    ).unwrap();
650        for scene_op in &self.scene_ops {
651            writeln!(f, "\t\t{:?}", scene_op).unwrap();
652        }
653
654        for frame_op in &self.frame_ops {
655            writeln!(f, "\t\t{:?}", frame_op).unwrap();
656        }
657
658        for resource_update in &self.resource_updates {
659            writeln!(f, "\t\t{:?}", resource_update).unwrap();
660        }
661        Ok(())
662    }
663}
664
665impl TransactionMsg {
666    /// Returns true if this transaction has no effect.
667    pub fn is_empty(&self) -> bool {
668        !self.generate_frame.as_bool() &&
669            !self.invalidate_rendered_frame &&
670            self.scene_ops.is_empty() &&
671            self.frame_ops.is_empty() &&
672            self.resource_updates.is_empty() &&
673            self.notifications.is_empty()
674    }
675}
676
677/// Creates an image resource with provided parameters.
678///
679/// Must be matched with a `DeleteImage` at some point to prevent memory leaks.
680#[derive(Clone)]
681#[cfg_attr(any(feature = "serde"), derive(Deserialize, Serialize))]
682pub struct AddImage {
683    /// A key to identify the image resource.
684    pub key: ImageKey,
685    /// Properties of the image.
686    pub descriptor: ImageDescriptor,
687    /// The pixels of the image.
688    pub data: ImageData,
689    /// An optional tiling scheme to apply when storing the image's data
690    /// on the GPU. Applies to both width and heights of the tiles.
691    ///
692    /// Note that WebRender may internally chose to tile large images
693    /// even if this member is set to `None`.
694    pub tiling: Option<TileSize>,
695}
696
697/// Updates an already existing image resource.
698#[derive(Clone)]
699#[cfg_attr(any(feature = "serde"), derive(Deserialize, Serialize))]
700pub struct UpdateImage {
701    /// The key identfying the image resource to update.
702    pub key: ImageKey,
703    /// Properties of the image.
704    pub descriptor: ImageDescriptor,
705    /// The pixels of the image.
706    pub data: ImageData,
707    /// An optional dirty rect that lets WebRender optimize the amount of
708    /// data to transfer to the GPU.
709    ///
710    /// The data provided must still represent the entire image.
711    pub dirty_rect: ImageDirtyRect,
712}
713
714/// Creates a blob-image resource with provided parameters.
715///
716/// Must be matched with a `DeleteImage` at some point to prevent memory leaks.
717#[derive(Clone)]
718#[cfg_attr(any(feature = "serde"), derive(Deserialize, Serialize))]
719pub struct AddBlobImage {
720    /// A key to identify the blob-image resource.
721    pub key: BlobImageKey,
722    /// Properties of the image.
723    pub descriptor: ImageDescriptor,
724    /// The blob-image's serialized commands.
725    pub data: Arc<BlobImageData>,
726    /// The portion of the plane in the blob-image's internal coordinate
727    /// system that is stretched to fill the image display item.
728    ///
729    /// Unlike regular images, blob images are not limited in size. The
730    /// top-left corner of their internal coordinate system is also not
731    /// necessary at (0, 0).
732    /// This means that blob images can be updated to insert/remove content
733    /// in any direction to support panning and zooming.
734    pub visible_rect: DeviceIntRect,
735    /// The blob image's tile size to apply when rasterizing the blob-image
736    /// and when storing its rasterized data on the GPU.
737    /// Applies to both width and heights of the tiles.
738    ///
739    /// All blob images are tiled.
740    pub tile_size: TileSize,
741}
742
743/// Updates an already existing blob-image resource.
744#[derive(Clone)]
745#[cfg_attr(any(feature = "serde"), derive(Deserialize, Serialize))]
746pub struct UpdateBlobImage {
747    /// The key identfying the blob-image resource to update.
748    pub key: BlobImageKey,
749    /// Properties of the image.
750    pub descriptor: ImageDescriptor,
751    /// The blob-image's serialized commands.
752    pub data: Arc<BlobImageData>,
753    /// See `AddBlobImage::visible_rect`.
754    pub visible_rect: DeviceIntRect,
755    /// An optional dirty rect that lets WebRender optimize the amount of
756    /// data to to rasterize and transfer to the GPU.
757    pub dirty_rect: BlobDirtyRect,
758}
759
760/// Creates a snapshot image resource.
761///
762/// Must be matched with a `DeleteSnapshotImage` at some point to prevent memory leaks.
763#[derive(Clone)]
764#[cfg_attr(any(feature = "serde"), derive(Deserialize, Serialize))]
765pub struct AddSnapshotImage {
766    /// The key identfying the snapshot resource.
767    pub key: SnapshotImageKey,
768}
769
770/// Creates a font resource.
771///
772/// Must be matched with a corresponding `ResourceUpdate::DeleteFont` at some point to prevent
773/// memory leaks.
774#[derive(Clone)]
775#[cfg_attr(any(feature = "serde"), derive(Deserialize, Serialize))]
776pub enum AddFont {
777    ///
778    Raw(FontKey, Arc<Vec<u8>>, u32),
779    ///
780    Native(FontKey, NativeFontHandle),
781}
782
783/// Creates a font instance resource.
784///
785/// Must be matched with a corresponding `DeleteFontInstance` at some point
786/// to prevent memory leaks.
787#[derive(Clone)]
788#[cfg_attr(any(feature = "serde"), derive(Deserialize, Serialize))]
789pub struct AddFontInstance {
790    /// A key to identify the font instance.
791    pub key: FontInstanceKey,
792    /// The font resource's key.
793    pub font_key: FontKey,
794    /// Glyph size in app units.
795    pub glyph_size: f32,
796    ///
797    pub options: Option<FontInstanceOptions>,
798    ///
799    pub platform_options: Option<FontInstancePlatformOptions>,
800    ///
801    pub variations: Vec<FontVariation>,
802}
803
804/// Frame messages affect building the scene.
805pub enum SceneMsg {
806    ///
807    UpdateEpoch(PipelineId, Epoch),
808    ///
809    SetRootPipeline(PipelineId),
810    ///
811    RemovePipeline(PipelineId),
812    ///
813    SetDisplayList {
814        ///
815        display_list: BuiltDisplayList,
816        ///
817        epoch: Epoch,
818        ///
819        pipeline_id: PipelineId,
820    },
821    ///
822    SetDocumentView {
823        ///
824        device_rect: DeviceIntRect,
825    },
826    /// Set the current quality / performance configuration for this document.
827    SetQualitySettings {
828        /// The set of available quality / performance config values.
829        settings: QualitySettings,
830    },
831}
832
833/// Frame messages affect frame generation (applied after building the scene).
834pub enum FrameMsg {
835    ///
836    UpdateEpoch(PipelineId, Epoch),
837    ///
838    HitTest(Option<PipelineId>, WorldPoint, HitTestFlags, Sender<HitTestResult>),
839    ///
840    RequestHitTester(Sender<Arc<dyn ApiHitTester>>),
841    ///
842    SetScrollOffsets(ExternalScrollId, Vec<SampledScrollOffset>),
843    ///
844    ResetDynamicProperties,
845    ///
846    AppendDynamicProperties(DynamicProperties),
847    ///
848    AppendDynamicTransformProperties(Vec<PropertyValue<LayoutTransform>>),
849    ///
850    SetIsTransformAsyncZooming(bool, PropertyBindingId),
851    ///
852    SetMinimapData(ExternalScrollId, MinimapData)
853}
854
855impl fmt::Debug for SceneMsg {
856    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
857        f.write_str(match *self {
858            SceneMsg::UpdateEpoch(..) => "SceneMsg::UpdateEpoch",
859            SceneMsg::SetDisplayList { .. } => "SceneMsg::SetDisplayList",
860            SceneMsg::RemovePipeline(..) => "SceneMsg::RemovePipeline",
861            SceneMsg::SetDocumentView { .. } => "SceneMsg::SetDocumentView",
862            SceneMsg::SetRootPipeline(..) => "SceneMsg::SetRootPipeline",
863            SceneMsg::SetQualitySettings { .. } => "SceneMsg::SetQualitySettings",
864        })
865    }
866}
867
868impl fmt::Debug for FrameMsg {
869    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
870        f.write_str(match *self {
871            FrameMsg::UpdateEpoch(..) => "FrameMsg::UpdateEpoch",
872            FrameMsg::HitTest(..) => "FrameMsg::HitTest",
873            FrameMsg::RequestHitTester(..) => "FrameMsg::RequestHitTester",
874            FrameMsg::SetScrollOffsets(..) => "FrameMsg::SetScrollOffsets",
875            FrameMsg::ResetDynamicProperties => "FrameMsg::ResetDynamicProperties",
876            FrameMsg::AppendDynamicProperties(..) => "FrameMsg::AppendDynamicProperties",
877            FrameMsg::AppendDynamicTransformProperties(..) => "FrameMsg::AppendDynamicTransformProperties",
878            FrameMsg::SetIsTransformAsyncZooming(..) => "FrameMsg::SetIsTransformAsyncZooming",
879            FrameMsg::SetMinimapData(..) => "FrameMsg::SetMinimapData",
880        })
881    }
882}
883
884bitflags!{
885    /// Bit flags for WR stages to store in a capture.
886    // Note: capturing `FRAME` without `SCENE` is not currently supported.
887    #[derive(Debug, Copy, PartialEq, Eq, Clone, PartialOrd, Ord, Hash)]
888    pub struct CaptureBits: u8 {
889        ///
890        const SCENE = 0x1;
891        ///
892        const FRAME = 0x2;
893        ///
894        const TILE_CACHE = 0x4;
895        ///
896        const EXTERNAL_RESOURCES = 0x8;
897    }
898}
899
900bitflags!{
901    /// Mask for clearing caches in debug commands.
902    #[derive(Debug, Copy, PartialEq, Eq, Clone, PartialOrd, Ord, Hash)]
903    pub struct ClearCache: u8 {
904        ///
905        const IMAGES = 0b1;
906        ///
907        const GLYPHS = 0b10;
908        ///
909        const GLYPH_DIMENSIONS = 0b100;
910        ///
911        const RENDER_TASKS = 0b1000;
912        ///
913        const TEXTURE_CACHE = 0b10000;
914        /// Clear render target pool
915        const RENDER_TARGETS = 0b100000;
916    }
917}
918
919/// Information about a loaded capture of each document
920/// that is returned by `RenderBackend`.
921#[derive(Clone, Debug)]
922pub struct CapturedDocument {
923    ///
924    pub document_id: DocumentId,
925    ///
926    pub root_pipeline_id: Option<PipelineId>,
927}
928
929/// Update of the state of built-in debugging facilities.
930#[derive(Clone)]
931pub enum DebugCommand {
932    /// Sets the provided debug flags.
933    SetFlags(DebugFlags),
934    /// Save a capture of all the documents state.
935    SaveCapture(PathBuf, CaptureBits),
936    /// Load a capture of all the documents state.
937    LoadCapture(PathBuf, Option<(u32, u32)>, Sender<CapturedDocument>),
938    /// Start capturing a sequence of scene/frame changes.
939    StartCaptureSequence(PathBuf, CaptureBits),
940    /// Stop capturing a sequence of scene/frame changes.
941    StopCaptureSequence,
942    /// Clear cached resources, forcing them to be re-uploaded from templates.
943    ClearCaches(ClearCache),
944    /// Enable/disable native compositor usage
945    EnableNativeCompositor(bool),
946    /// Sets the maximum amount of existing batches to visit before creating a new one.
947    SetBatchingLookback(u32),
948    /// Invalidate GPU cache, forcing the update from the CPU mirror.
949    InvalidateGpuCache,
950    /// Causes the scene builder to pause for a given amount of milliseconds each time it
951    /// processes a transaction.
952    SimulateLongSceneBuild(u32),
953    /// Set an override tile size to use for picture caches
954    SetPictureTileSize(Option<DeviceIntSize>),
955    /// Set an override for max off-screen surface size
956    SetMaximumSurfaceSize(Option<usize>),
957}
958
959/// Message sent by the `RenderApi` to the render backend thread.
960pub enum ApiMsg {
961    /// Adds a new document namespace.
962    CloneApi(Sender<IdNamespace>),
963    /// Adds a new document namespace.
964    CloneApiByClient(IdNamespace),
965    /// Adds a new document with given initial size.
966    AddDocument(DocumentId, DeviceIntSize),
967    /// A message targeted at a particular document.
968    UpdateDocuments(Vec<Box<TransactionMsg>>),
969    /// Flush from the caches anything that isn't necessary, to free some memory.
970    MemoryPressure,
971    /// Collects a memory report.
972    ReportMemory(Sender<Box<MemoryReport>>),
973    /// Change debugging options.
974    DebugCommand(DebugCommand),
975    /// Message from the scene builder thread.
976    SceneBuilderResult(SceneBuilderResult),
977}
978
979impl fmt::Debug for ApiMsg {
980    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
981        f.write_str(match *self {
982            ApiMsg::CloneApi(..) => "ApiMsg::CloneApi",
983            ApiMsg::CloneApiByClient(..) => "ApiMsg::CloneApiByClient",
984            ApiMsg::AddDocument(..) => "ApiMsg::AddDocument",
985            ApiMsg::UpdateDocuments(..) => "ApiMsg::UpdateDocuments",
986            ApiMsg::MemoryPressure => "ApiMsg::MemoryPressure",
987            ApiMsg::ReportMemory(..) => "ApiMsg::ReportMemory",
988            ApiMsg::DebugCommand(..) => "ApiMsg::DebugCommand",
989            ApiMsg::SceneBuilderResult(..) => "ApiMsg::SceneBuilderResult",
990        })
991    }
992}
993
994/// Allows the API to communicate with WebRender.
995///
996/// This object is created along with the `Renderer` and it's main use from a
997/// user perspective is to create one or several `RenderApi` objects.
998pub struct RenderApiSender {
999    api_sender: Sender<ApiMsg>,
1000    scene_sender: Sender<SceneBuilderRequest>,
1001    low_priority_scene_sender: Sender<SceneBuilderRequest>,
1002    blob_image_handler: Option<Box<dyn BlobImageHandler>>,
1003    fonts: SharedFontResources,
1004}
1005
1006impl RenderApiSender {
1007    /// Used internally by the `Renderer`.
1008    pub fn new(
1009        api_sender: Sender<ApiMsg>,
1010        scene_sender: Sender<SceneBuilderRequest>,
1011        low_priority_scene_sender: Sender<SceneBuilderRequest>,
1012        blob_image_handler: Option<Box<dyn BlobImageHandler>>,
1013        fonts: SharedFontResources,
1014    ) -> Self {
1015        RenderApiSender {
1016            api_sender,
1017            scene_sender,
1018            low_priority_scene_sender,
1019            blob_image_handler,
1020            fonts,
1021        }
1022    }
1023
1024    /// Creates a new resource API object with a dedicated namespace.
1025    pub fn create_api(&self) -> RenderApi {
1026        let (sync_tx, sync_rx) = single_msg_channel();
1027        let msg = ApiMsg::CloneApi(sync_tx);
1028        self.api_sender.send(msg).expect("Failed to send CloneApi message");
1029        let namespace_id = sync_rx.recv().expect("Failed to receive CloneApi reply");
1030        RenderApi {
1031            api_sender: self.api_sender.clone(),
1032            scene_sender: self.scene_sender.clone(),
1033            low_priority_scene_sender: self.low_priority_scene_sender.clone(),
1034            namespace_id,
1035            next_id: Cell::new(ResourceId(0)),
1036            resources: ApiResources::new(
1037                self.blob_image_handler.as_ref().map(|handler| handler.create_similar()),
1038                self.fonts.clone(),
1039            ),
1040        }
1041    }
1042
1043    /// Creates a new resource API object with a dedicated namespace.
1044    /// Namespace id is allocated by client.
1045    ///
1046    /// The function could be used only when WebRenderOptions::namespace_alloc_by_client is true.
1047    /// When the option is true, create_api() could not be used to prevent namespace id conflict.
1048    pub fn create_api_by_client(&self, namespace_id: IdNamespace) -> RenderApi {
1049        let msg = ApiMsg::CloneApiByClient(namespace_id);
1050        self.api_sender.send(msg).expect("Failed to send CloneApiByClient message");
1051        RenderApi {
1052            api_sender: self.api_sender.clone(),
1053            scene_sender: self.scene_sender.clone(),
1054            low_priority_scene_sender: self.low_priority_scene_sender.clone(),
1055            namespace_id,
1056            next_id: Cell::new(ResourceId(0)),
1057            resources: ApiResources::new(
1058                self.blob_image_handler.as_ref().map(|handler| handler.create_similar()),
1059                self.fonts.clone(),
1060            ),
1061        }
1062    }
1063}
1064
1065/// The main entry point to interact with WebRender.
1066pub struct RenderApi {
1067    api_sender: Sender<ApiMsg>,
1068    scene_sender: Sender<SceneBuilderRequest>,
1069    low_priority_scene_sender: Sender<SceneBuilderRequest>,
1070    namespace_id: IdNamespace,
1071    next_id: Cell<ResourceId>,
1072    resources: ApiResources,
1073}
1074
1075impl RenderApi {
1076    /// Returns the namespace ID used by this API object.
1077    pub fn get_namespace_id(&self) -> IdNamespace {
1078        self.namespace_id
1079    }
1080
1081    ///
1082    pub fn create_sender(&self) -> RenderApiSender {
1083        RenderApiSender::new(
1084            self.api_sender.clone(),
1085            self.scene_sender.clone(),
1086            self.low_priority_scene_sender.clone(),
1087            self.resources.blob_image_handler.as_ref().map(|handler| handler.create_similar()),
1088            self.resources.get_fonts(),
1089        )
1090    }
1091
1092    /// Add a document to the WebRender instance.
1093    ///
1094    /// Instances can manage one or several documents (using the same render backend thread).
1095    /// Each document will internally correspond to a single scene, and scenes are made of
1096    /// one or several pipelines.
1097    pub fn add_document(&self, initial_size: DeviceIntSize) -> DocumentId {
1098        let new_id = self.next_unique_id();
1099        self.add_document_with_id(initial_size, new_id)
1100    }
1101
1102    /// See `add_document`
1103    pub fn add_document_with_id(&self,
1104                                initial_size: DeviceIntSize,
1105                                id: u32) -> DocumentId {
1106        window_size_sanity_check(initial_size);
1107
1108        let document_id = DocumentId::new(self.namespace_id, id);
1109
1110        // We send this message to both the render backend and the scene builder instead of having
1111        // the scene builder thread forward it to the render backend as we do elswhere. This is because
1112        // some transactions can skip the scene builder thread and we want to avoid them arriving before
1113        // the render backend knows about the existence of the corresponding document id.
1114        // It may not be necessary, though.
1115        self.api_sender.send(
1116            ApiMsg::AddDocument(document_id, initial_size)
1117        ).unwrap();
1118        self.scene_sender.send(
1119            SceneBuilderRequest::AddDocument(document_id, initial_size)
1120        ).unwrap();
1121
1122        document_id
1123    }
1124
1125    /// Delete a document.
1126    pub fn delete_document(&self, document_id: DocumentId) {
1127        self.low_priority_scene_sender.send(
1128            SceneBuilderRequest::DeleteDocument(document_id)
1129        ).unwrap();
1130    }
1131
1132    /// Generate a new font key
1133    pub fn generate_font_key(&self) -> FontKey {
1134        let new_id = self.next_unique_id();
1135        FontKey::new(self.namespace_id, new_id)
1136    }
1137
1138    /// Generate a new font instance key
1139    pub fn generate_font_instance_key(&self) -> FontInstanceKey {
1140        let new_id = self.next_unique_id();
1141        FontInstanceKey::new(self.namespace_id, new_id)
1142    }
1143
1144    /// Gets the dimensions for the supplied glyph keys
1145    ///
1146    /// Note: Internally, the internal texture cache doesn't store
1147    /// 'empty' textures (height or width = 0)
1148    /// This means that glyph dimensions e.g. for spaces (' ') will mostly be None.
1149    pub fn get_glyph_dimensions(
1150        &self,
1151        key: FontInstanceKey,
1152        glyph_indices: Vec<GlyphIndex>,
1153    ) -> Vec<Option<GlyphDimensions>> {
1154        let (sender, rx) = single_msg_channel();
1155        let msg = SceneBuilderRequest::GetGlyphDimensions(GlyphDimensionRequest {
1156            key,
1157            glyph_indices,
1158            sender
1159        });
1160        self.low_priority_scene_sender.send(msg).unwrap();
1161        rx.recv().unwrap()
1162    }
1163
1164    /// Gets the glyph indices for the supplied string. These
1165    /// can be used to construct GlyphKeys.
1166    pub fn get_glyph_indices(&self, key: FontKey, text: &str) -> Vec<Option<u32>> {
1167        let (sender, rx) = single_msg_channel();
1168        let msg = SceneBuilderRequest::GetGlyphIndices(GlyphIndexRequest {
1169            key,
1170            text: text.to_string(),
1171            sender,
1172        });
1173        self.low_priority_scene_sender.send(msg).unwrap();
1174        rx.recv().unwrap()
1175    }
1176
1177    /// Creates an `ImageKey`.
1178    pub fn generate_image_key(&self) -> ImageKey {
1179        let new_id = self.next_unique_id();
1180        ImageKey::new(self.namespace_id, new_id)
1181    }
1182
1183    /// Creates a `BlobImageKey`.
1184    pub fn generate_blob_image_key(&self) -> BlobImageKey {
1185        BlobImageKey(self.generate_image_key())
1186    }
1187
1188    /// A Gecko-specific notification mechanism to get some code executed on the
1189    /// `Renderer`'s thread, mostly replaced by `NotificationHandler`. You should
1190    /// probably use the latter instead.
1191    pub fn send_external_event(&self, evt: ExternalEvent) {
1192        let msg = SceneBuilderRequest::ExternalEvent(evt);
1193        self.low_priority_scene_sender.send(msg).unwrap();
1194    }
1195
1196    /// Notify WebRender that now is a good time to flush caches and release
1197    /// as much memory as possible.
1198    pub fn notify_memory_pressure(&self) {
1199        self.api_sender.send(ApiMsg::MemoryPressure).unwrap();
1200    }
1201
1202    /// Synchronously requests memory report.
1203    pub fn report_memory(&self, _ops: malloc_size_of::MallocSizeOfOps) -> MemoryReport {
1204        let (tx, rx) = single_msg_channel();
1205        self.api_sender.send(ApiMsg::ReportMemory(tx)).unwrap();
1206        *rx.recv().unwrap()
1207    }
1208
1209    /// Update debugging flags.
1210    pub fn set_debug_flags(&mut self, flags: DebugFlags) {
1211        self.resources.set_debug_flags(flags);
1212        let cmd = DebugCommand::SetFlags(flags);
1213        self.api_sender.send(ApiMsg::DebugCommand(cmd)).unwrap();
1214        self.scene_sender.send(SceneBuilderRequest ::SetFlags(flags)).unwrap();
1215        self.low_priority_scene_sender.send(SceneBuilderRequest ::SetFlags(flags)).unwrap();
1216    }
1217
1218    /// Stop RenderBackend's task until shut down
1219    pub fn stop_render_backend(&self) {
1220        self.low_priority_scene_sender.send(SceneBuilderRequest::StopRenderBackend).unwrap();
1221    }
1222
1223    /// Shut the WebRender instance down.
1224    pub fn shut_down(&self, synchronously: bool) {
1225        if synchronously {
1226            let (tx, rx) = single_msg_channel();
1227            self.low_priority_scene_sender.send(SceneBuilderRequest::ShutDown(Some(tx))).unwrap();
1228            rx.recv().unwrap();
1229        } else {
1230            self.low_priority_scene_sender.send(SceneBuilderRequest::ShutDown(None)).unwrap();
1231        }
1232    }
1233
1234    /// Create a new unique key that can be used for
1235    /// animated property bindings.
1236    pub fn generate_property_binding_key<T: Copy>(&self) -> PropertyBindingKey<T> {
1237        let new_id = self.next_unique_id();
1238        PropertyBindingKey {
1239            id: PropertyBindingId {
1240                namespace: self.namespace_id,
1241                uid: new_id,
1242            },
1243            _phantom: PhantomData,
1244        }
1245    }
1246
1247    #[inline]
1248    fn next_unique_id(&self) -> u32 {
1249        let ResourceId(id) = self.next_id.get();
1250        self.next_id.set(ResourceId(id + 1));
1251        id
1252    }
1253
1254    // For use in Wrench only
1255    #[doc(hidden)]
1256    pub fn send_message(&self, msg: ApiMsg) {
1257        self.api_sender.send(msg).unwrap();
1258    }
1259
1260    /// Creates a transaction message from a single frame message.
1261    fn frame_message(&self, msg: FrameMsg, document_id: DocumentId) -> Box<TransactionMsg> {
1262        Box::new(TransactionMsg {
1263            document_id,
1264            scene_ops: Vec::new(),
1265            frame_ops: vec![msg],
1266            resource_updates: Vec::new(),
1267            notifications: Vec::new(),
1268            generate_frame: GenerateFrame::No,
1269            creation_time: None,
1270            invalidate_rendered_frame: false,
1271            use_scene_builder_thread: false,
1272            low_priority: false,
1273            blob_rasterizer: None,
1274            blob_requests: Vec::new(),
1275            rasterized_blobs: Vec::new(),
1276            profile: TransactionProfile::new(),
1277            render_reasons: RenderReasons::empty(),
1278        })
1279    }
1280
1281    /// A helper method to send document messages.
1282    fn send_frame_msg(&self, document_id: DocumentId, msg: FrameMsg) {
1283        // This assertion fails on Servo use-cases, because it creates different
1284        // `RenderApi` instances for layout and compositor.
1285        //assert_eq!(document_id.0, self.namespace_id);
1286        self.api_sender
1287            .send(ApiMsg::UpdateDocuments(vec![self.frame_message(msg, document_id)]))
1288            .unwrap()
1289    }
1290
1291    /// Send a transaction to WebRender.
1292    pub fn send_transaction(&mut self, document_id: DocumentId, transaction: Transaction) {
1293        let mut transaction = transaction.finalize(document_id);
1294
1295        self.resources.update(&mut transaction);
1296
1297        if transaction.generate_frame.as_bool() {
1298            transaction.profile.start_time(profiler::API_SEND_TIME);
1299            transaction.profile.start_time(profiler::TOTAL_FRAME_CPU_TIME);
1300        }
1301
1302        if transaction.use_scene_builder_thread {
1303            let sender = if transaction.low_priority {
1304                &mut self.low_priority_scene_sender
1305            } else {
1306                &mut self.scene_sender
1307            };
1308
1309            sender.send(SceneBuilderRequest::Transactions(vec![transaction]))
1310                .expect("send by scene sender failed");
1311        } else {
1312            self.api_sender.send(ApiMsg::UpdateDocuments(vec![transaction]))
1313                .expect("send by api sender failed");
1314        }
1315    }
1316
1317    /// Does a hit test on display items in the specified document, at the given
1318    /// point. If a pipeline_id is specified, it is used to further restrict the
1319    /// hit results so that only items inside that pipeline are matched. The vector
1320    /// of hit results will contain all display items that match, ordered from
1321    /// front to back.
1322    pub fn hit_test(&self,
1323        document_id: DocumentId,
1324        pipeline_id: Option<PipelineId>,
1325        point: WorldPoint,
1326        flags: HitTestFlags,
1327    ) -> HitTestResult {
1328        let (tx, rx) = single_msg_channel();
1329
1330        self.send_frame_msg(
1331            document_id,
1332            FrameMsg::HitTest(pipeline_id, point, flags, tx)
1333        );
1334        rx.recv().unwrap()
1335    }
1336
1337    /// Synchronously request an object that can perform fast hit testing queries.
1338    pub fn request_hit_tester(&self, document_id: DocumentId) -> HitTesterRequest {
1339        let (tx, rx) = single_msg_channel();
1340        self.send_frame_msg(
1341            document_id,
1342            FrameMsg::RequestHitTester(tx)
1343        );
1344
1345        HitTesterRequest { rx }
1346    }
1347
1348    // Some internal scheduling magic that leaked into the API.
1349    // Buckle up and see APZUpdater.cpp for more info about what this is about.
1350    #[doc(hidden)]
1351    pub fn wake_scene_builder(&self) {
1352        self.scene_sender.send(SceneBuilderRequest::WakeUp).unwrap();
1353    }
1354
1355    /// Block until a round-trip to the scene builder thread has completed. This
1356    /// ensures that any transactions (including ones deferred to the scene
1357    /// builder thread) have been processed.
1358    pub fn flush_scene_builder(&self) {
1359        let (tx, rx) = single_msg_channel();
1360        self.low_priority_scene_sender.send(SceneBuilderRequest::Flush(tx)).unwrap();
1361        rx.recv().unwrap(); // Block until done.
1362    }
1363
1364    /// Save a capture of the current frame state for debugging.
1365    pub fn save_capture(&self, path: PathBuf, bits: CaptureBits) {
1366        let msg = ApiMsg::DebugCommand(DebugCommand::SaveCapture(path, bits));
1367        self.send_message(msg);
1368    }
1369
1370    /// Load a capture of the current frame state for debugging.
1371    pub fn load_capture(&self, path: PathBuf, ids: Option<(u32, u32)>) -> Vec<CapturedDocument> {
1372        // First flush the scene builder otherwise async scenes might clobber
1373        // the capture we are about to load.
1374        self.flush_scene_builder();
1375
1376        let (tx, rx) = unbounded_channel();
1377        let msg = ApiMsg::DebugCommand(DebugCommand::LoadCapture(path, ids, tx));
1378        self.send_message(msg);
1379
1380        let mut documents = Vec::new();
1381        while let Ok(captured_doc) = rx.recv() {
1382            documents.push(captured_doc);
1383        }
1384        documents
1385    }
1386
1387    /// Start capturing a sequence of frames.
1388    pub fn start_capture_sequence(&self, path: PathBuf, bits: CaptureBits) {
1389        let msg = ApiMsg::DebugCommand(DebugCommand::StartCaptureSequence(path, bits));
1390        self.send_message(msg);
1391    }
1392
1393    /// Stop capturing sequences of frames.
1394    pub fn stop_capture_sequence(&self) {
1395        let msg = ApiMsg::DebugCommand(DebugCommand::StopCaptureSequence);
1396        self.send_message(msg);
1397    }
1398
1399    /// Update the state of builtin debugging facilities.
1400    pub fn send_debug_cmd(&self, cmd: DebugCommand) {
1401        let msg = ApiMsg::DebugCommand(cmd);
1402        self.send_message(msg);
1403    }
1404
1405    /// Update a instance-global parameter.
1406    pub fn set_parameter(&mut self, parameter: Parameter) {
1407        if let Parameter::Bool(BoolParameter::Multithreading, enabled) = parameter {
1408            self.resources.enable_multithreading(enabled);
1409        }
1410
1411        let _ = self.low_priority_scene_sender.send(
1412            SceneBuilderRequest::SetParameter(parameter)
1413        );
1414    }
1415}
1416
1417impl Drop for RenderApi {
1418    fn drop(&mut self) {
1419        let msg = SceneBuilderRequest::ClearNamespace(self.namespace_id);
1420        let _ = self.low_priority_scene_sender.send(msg);
1421    }
1422}
1423
1424
1425fn window_size_sanity_check(size: DeviceIntSize) {
1426    // Anything bigger than this will crash later when attempting to create
1427    // a render task.
1428    use crate::api::MAX_RENDER_TASK_SIZE;
1429    if size.width > MAX_RENDER_TASK_SIZE || size.height > MAX_RENDER_TASK_SIZE {
1430        panic!("Attempting to create a {}x{} window/document", size.width, size.height);
1431    }
1432}
1433
1434/// Collection of heap sizes, in bytes.
1435/// cbindgen:derive-eq=false
1436/// cbindgen:derive-ostream=false
1437#[repr(C)]
1438#[allow(missing_docs)]
1439#[derive(AddAssign, Clone, Debug, Default)]
1440pub struct MemoryReport {
1441    //
1442    // CPU Memory.
1443    //
1444    pub clip_stores: usize,
1445    pub gpu_cache_metadata: usize,
1446    pub gpu_cache_cpu_mirror: usize,
1447    pub hit_testers: usize,
1448    pub fonts: usize,
1449    pub weak_fonts: usize,
1450    pub images: usize,
1451    pub rasterized_blobs: usize,
1452    pub shader_cache: usize,
1453    pub interning: InterningMemoryReport,
1454    pub display_list: usize,
1455    pub upload_staging_memory: usize,
1456    pub swgl: usize,
1457    pub frame_allocator: usize,
1458    pub render_tasks: usize,
1459
1460    //
1461    // GPU memory.
1462    //
1463    pub gpu_cache_textures: usize,
1464    pub vertex_data_textures: usize,
1465    pub render_target_textures: usize,
1466    pub picture_tile_textures: usize,
1467    pub atlas_textures: usize,
1468    pub standalone_textures: usize,
1469    pub texture_cache_structures: usize,
1470    pub depth_target_textures: usize,
1471    pub texture_upload_pbos: usize,
1472    pub swap_chain: usize,
1473    pub render_texture_hosts: usize,
1474    pub upload_staging_textures: usize,
1475}