1 /*
2  * Copyright (C) 2009 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
14  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
17  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24  */
25 
26 #ifndef THIRD_PARTY_BLINK_RENDERER_CORE_HTML_CANVAS_CANVAS_RENDERING_CONTEXT_H_
27 #define THIRD_PARTY_BLINK_RENDERER_CORE_HTML_CANVAS_CANVAS_RENDERING_CONTEXT_H_
28 
29 #include "base/macros.h"
30 #include "third_party/blink/renderer/core/core_export.h"
31 #include "third_party/blink/renderer/core/html/canvas/canvas_context_creation_attributes_core.h"
32 #include "third_party/blink/renderer/core/html/canvas/html_canvas_element.h"
33 #include "third_party/blink/renderer/core/layout/hit_test_canvas_result.h"
34 #include "third_party/blink/renderer/core/offscreencanvas/offscreen_canvas.h"
35 #include "third_party/blink/renderer/platform/graphics/canvas_color_params.h"
36 #include "third_party/blink/renderer/platform/graphics/color_behavior.h"
37 #include "third_party/blink/renderer/platform/scheduler/public/thread.h"
38 #include "third_party/skia/include/core/SkColorSpace.h"
39 #include "third_party/skia/include/core/SkData.h"
40 #include "third_party/skia/include/core/SkImageInfo.h"
41 
42 namespace blink {
43 
44 class CanvasImageSource;
45 class HTMLCanvasElement;
46 class ImageBitmap;
47 
48 constexpr const char* kSRGBCanvasColorSpaceName = "srgb";
49 constexpr const char* kLinearRGBCanvasColorSpaceName = "linear-rgb";
50 constexpr const char* kRec2020CanvasColorSpaceName = "rec2020";
51 constexpr const char* kP3CanvasColorSpaceName = "p3";
52 
53 constexpr const char* kRGBA8CanvasPixelFormatName = "uint8";
54 constexpr const char* kBGRA8CanvasPixelFormatName = "uint8";
55 constexpr const char* kF16CanvasPixelFormatName = "float16";
56 
57 class CORE_EXPORT CanvasRenderingContext : public ScriptWrappable,
58                                            public Thread::TaskObserver {
59   USING_PRE_FINALIZER(CanvasRenderingContext, Dispose);
60 
61  public:
62   ~CanvasRenderingContext() override = default;
63 
64   // A Canvas can either be "2D" or "webgl" but never both. Requesting a context
65   // with a type different from an existing will destroy the latter.
66   enum ContextType {
67     // Do not change assigned numbers of existing items: add new features to the
68     // end of the list.
69     kContext2D = 0,
70     kContextExperimentalWebgl = 2,
71     kContextWebgl = 3,
72     kContextWebgl2 = 4,
73     kContextImageBitmap = 5,
74     kContextXRPresent = 6,
75     kContextWebgl2Compute = 7,
76     kContextGPUPresent = 8,
77     kContextTypeUnknown = 9,
78     kMaxValue = kContextTypeUnknown,
79   };
80 
81   static ContextType ContextTypeFromId(const String& id);
82   static ContextType ResolveContextTypeAliases(ContextType);
83 
Host()84   CanvasRenderingContextHost* Host() const { return host_; }
85 
86   WTF::String ColorSpaceAsString() const;
87   WTF::String PixelFormatAsString() const;
88 
ColorParams()89   const CanvasColorParams& ColorParams() const { return color_params_; }
90 
91   virtual scoped_refptr<StaticBitmapImage> GetImage(AccelerationHint) = 0;
92   virtual ContextType GetContextType() const = 0;
93   virtual bool IsComposited() const = 0;
94   virtual bool IsAccelerated() const = 0;
IsOriginTopLeft()95   virtual bool IsOriginTopLeft() const {
96     // Canvas contexts have the origin of coordinates on the top left corner.
97     // Accelerated resources (e.g. GPU textures) have their origin of
98     // coordinates in the upper left corner.
99     return !IsAccelerated();
100   }
ShouldAntialias()101   virtual bool ShouldAntialias() const { return false; }
102   // Indicates whether the entire tab is backgrounded. Passing false
103   // to this method may cause some canvas context implementations to
104   // aggressively discard resources, which is not desired for canvases
105   // which are being rendered to, just not being displayed in the
106   // page.
107   virtual void SetIsInHiddenPage(bool) = 0;
108   // Indicates whether the canvas is being displayed in the page;
109   // i.e., doesn't have display:none, and is visible. The initial
110   // value for all context types is assumed to be false; this will be
111   // called when the context is first displayed.
112   virtual void SetIsBeingDisplayed(bool) = 0;
isContextLost()113   virtual bool isContextLost() const { return true; }
114   // TODO(fserb): remove SetCanvasGetContextResult.
SetCanvasGetContextResult(RenderingContext &)115   virtual void SetCanvasGetContextResult(RenderingContext&) { NOTREACHED(); }
SetOffscreenCanvasGetContextResult(OffscreenRenderingContext &)116   virtual void SetOffscreenCanvasGetContextResult(OffscreenRenderingContext&) {
117     NOTREACHED();
118   }
119   virtual bool IsPaintable() const = 0;
120   virtual void DidDraw(const SkIRect& dirty_rect);
121   virtual void DidDraw();
122 
123   // Return true if the content is updated.
PaintRenderingResultsToCanvas(SourceDrawingBuffer)124   virtual bool PaintRenderingResultsToCanvas(SourceDrawingBuffer) {
125     return false;
126   }
127 
CcLayer()128   virtual cc::Layer* CcLayer() const { return nullptr; }
129 
130   enum LostContextMode {
131     kNotLostContext,
132 
133     // Lost context occurred at the graphics system level.
134     kRealLostContext,
135 
136     // Lost context provoked by WEBGL_lose_context.
137     kWebGLLoseContextLostContext,
138 
139     // Lost context occurred due to internal implementation reasons.
140     kSyntheticLostContext,
141   };
LoseContext(LostContextMode)142   virtual void LoseContext(LostContextMode) {}
143 
144   // This method gets called at the end of script tasks that modified
145   // the contents of the canvas (called didDraw). It marks the completion
146   // of a presentable frame.
FinalizeFrame()147   virtual void FinalizeFrame() {}
148 
149   // Thread::TaskObserver implementation
150   void DidProcessTask(const base::PendingTask&) override;
WillProcessTask(const base::PendingTask &,bool)151   void WillProcessTask(const base::PendingTask&, bool) final {}
152 
153   // Canvas2D-specific interface
Is2d()154   virtual bool Is2d() const { return false; }
RestoreCanvasMatrixClipStack(cc::PaintCanvas *)155   virtual void RestoreCanvasMatrixClipStack(cc::PaintCanvas*) const {}
Reset()156   virtual void Reset() {}
ClearRect(double x,double y,double width,double height)157   virtual void ClearRect(double x, double y, double width, double height) {}
DidSetSurfaceSize()158   virtual void DidSetSurfaceSize() {}
SetShouldAntialias(bool)159   virtual void SetShouldAntialias(bool) {}
HitRegionsCount()160   virtual unsigned HitRegionsCount() const { return 0; }
setFont(const String &)161   virtual void setFont(const String&) {}
StyleDidChange(const ComputedStyle * old_style,const ComputedStyle & new_style)162   virtual void StyleDidChange(const ComputedStyle* old_style,
163                               const ComputedStyle& new_style) {}
GetControlAndIdIfHitRegionExists(const PhysicalOffset & location)164   virtual HitTestCanvasResult* GetControlAndIdIfHitRegionExists(
165       const PhysicalOffset& location) {
166     NOTREACHED();
167     return MakeGarbageCollected<HitTestCanvasResult>(String(), nullptr);
168   }
GetIdFromControl(const Element * element)169   virtual String GetIdFromControl(const Element* element) { return String(); }
ResetUsageTracking()170   virtual void ResetUsageTracking() {}
171 
172   // WebGL-specific interface
Is3d()173   virtual bool Is3d() const { return false; }
UsingSwapChain()174   virtual bool UsingSwapChain() const { return false; }
SetFilterQuality(SkFilterQuality)175   virtual void SetFilterQuality(SkFilterQuality) { NOTREACHED(); }
Reshape(int width,int height)176   virtual void Reshape(int width, int height) { NOTREACHED(); }
MarkLayerComposited()177   virtual void MarkLayerComposited() { NOTREACHED(); }
PaintRenderingResultsToDataArray(SourceDrawingBuffer)178   virtual sk_sp<SkData> PaintRenderingResultsToDataArray(SourceDrawingBuffer) {
179     NOTREACHED();
180     return nullptr;
181   }
ExternallyAllocatedBufferCountPerPixel()182   virtual int ExternallyAllocatedBufferCountPerPixel() {
183     NOTREACHED();
184     return 0;
185   }
DrawingBufferSize()186   virtual IntSize DrawingBufferSize() const {
187     NOTREACHED();
188     return IntSize(0, 0);
189   }
190 
191   // OffscreenCanvas-specific methods
PushFrame()192   virtual bool PushFrame() { return false; }
TransferToImageBitmap(ScriptState *)193   virtual ImageBitmap* TransferToImageBitmap(ScriptState*) { return nullptr; }
194 
195   bool WouldTaintOrigin(CanvasImageSource*);
196   void DidMoveToNewDocument(Document*);
197 
DetachHost()198   void DetachHost() { host_ = nullptr; }
199 
CreationAttributes()200   const CanvasContextCreationAttributesCore& CreationAttributes() const {
201     return creation_attributes_;
202   }
203 
204   void Trace(Visitor*) override;
205   virtual void Stop() = 0;
206 
207  protected:
208   CanvasRenderingContext(CanvasRenderingContextHost*,
209                          const CanvasContextCreationAttributesCore&);
210 
211  private:
212   void Dispose();
213 
214   Member<CanvasRenderingContextHost> host_;
215   CanvasColorParams color_params_;
216   CanvasContextCreationAttributesCore creation_attributes_;
217 
218   void StartListeningForDidProcessTask();
219   void StopListeningForDidProcessTask();
220   bool listening_for_did_process_task_ = false;
221 
222   DISALLOW_COPY_AND_ASSIGN(CanvasRenderingContext);
223 };
224 
225 }  // namespace blink
226 
227 #endif
228