1 /*
2  * Copyright (C) 2009 Google Inc. All rights reserved.
3  * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions are
7  * met:
8  *
9  *     * Redistributions of source code must retain the above copyright
10  * notice, this list of conditions and the following disclaimer.
11  *     * Redistributions in binary form must reproduce the above
12  * copyright notice, this list of conditions and the following disclaimer
13  * in the documentation and/or other materials provided with the
14  * distribution.
15  *     * Neither the name of Google Inc. nor the names of its
16  * contributors may be used to endorse or promote products derived from
17  * this software without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30  */
31 
32 #ifndef THIRD_PARTY_BLINK_RENDERER_CORE_PAGE_CHROME_CLIENT_IMPL_H_
33 #define THIRD_PARTY_BLINK_RENDERER_CORE_PAGE_CHROME_CLIENT_IMPL_H_
34 
35 #include <memory>
36 
37 #include "cc/input/overscroll_behavior.h"
38 #include "third_party/blink/public/mojom/input/focus_type.mojom-blink-forward.h"
39 #include "third_party/blink/public/web/web_navigation_policy.h"
40 #include "third_party/blink/public/web/web_widget_client.h"
41 #include "third_party/blink/public/web/web_window_features.h"
42 #include "third_party/blink/renderer/core/core_export.h"
43 #include "third_party/blink/renderer/core/page/chrome_client.h"
44 #include "third_party/blink/renderer/platform/graphics/touch_action.h"
45 #include "ui/base/cursor/cursor.h"
46 
47 namespace ui {
48 class Cursor;
49 }
50 
51 namespace blink {
52 
53 class PagePopup;
54 class PagePopupClient;
55 class WebAutofillClient;
56 class WebViewImpl;
57 struct WebRect;
58 
59 // Handles window-level notifications from core on behalf of a WebView.
60 class CORE_EXPORT ChromeClientImpl final : public ChromeClient {
61  public:
62   explicit ChromeClientImpl(WebViewImpl*);
63   ~ChromeClientImpl() override;
64   void Trace(Visitor* visitor) const override;
65 
66   // ChromeClient methods:
67   WebViewImpl* GetWebView() const override;
68   void ChromeDestroyed() override;
69   void SetWindowRect(const IntRect&, LocalFrame&) override;
70   IntRect RootWindowRect(LocalFrame&) override;
71   void FocusPage() override;
72   void DidFocusPage() override;
73   bool CanTakeFocus(mojom::blink::FocusType) override;
74   void TakeFocus(mojom::blink::FocusType) override;
75   void SetKeyboardFocusURL(Element* new_focus_element) override;
76   void BeginLifecycleUpdates(LocalFrame& main_frame) override;
77   void StartDeferringCommits(LocalFrame& main_frame,
78                              base::TimeDelta timeout) override;
79   void StopDeferringCommits(LocalFrame& main_frame,
80                             cc::PaintHoldingCommitTrigger) override;
81   void StartDragging(LocalFrame*,
82                      const WebDragData&,
83                      DragOperationsMask,
84                      const SkBitmap& drag_image,
85                      const gfx::Point& drag_image_offset) override;
86   bool AcceptsLoadDrops() const override;
87   Page* CreateWindowDelegate(LocalFrame*,
88                              const FrameLoadRequest&,
89                              const AtomicString& name,
90                              const WebWindowFeatures&,
91                              network::mojom::blink::WebSandboxFlags,
92                              const FeaturePolicyFeatureState&,
93                              const SessionStorageNamespaceId&,
94                              bool& consumed_user_gesture) override;
95   void Show(const base::UnguessableToken& opener_frame_token,
96             NavigationPolicy navigation_policy,
97             const IntRect& initial_rect,
98             bool user_gesture) override;
99   void DidOverscroll(const gfx::Vector2dF& overscroll_delta,
100                      const gfx::Vector2dF& accumulated_overscroll,
101                      const gfx::PointF& position_in_viewport,
102                      const gfx::Vector2dF& velocity_in_viewport) override;
103   void SetOverscrollBehavior(LocalFrame& main_frame,
104                              const cc::OverscrollBehavior&) override;
105   void InjectGestureScrollEvent(LocalFrame& local_frame,
106                                 WebGestureDevice device,
107                                 const gfx::Vector2dF& delta,
108                                 ScrollGranularity granularity,
109                                 CompositorElementId scrollable_area_element_id,
110                                 WebInputEvent::Type injected_type) override;
111   bool ShouldReportDetailedMessageForSource(LocalFrame&,
112                                             const String&) override;
113   void AddMessageToConsole(LocalFrame*,
114                            mojom::ConsoleMessageSource,
115                            mojom::ConsoleMessageLevel,
116                            const String& message,
117                            unsigned line_number,
118                            const String& source_id,
119                            const String& stack_trace) override;
120   bool CanOpenBeforeUnloadConfirmPanel() override;
121   bool OpenBeforeUnloadConfirmPanelDelegate(LocalFrame*,
122                                             bool is_reload) override;
123   // Used in tests to set a mock value for a before unload confirmation dialog
124   // box. The value is cleared after being read.
125   void SetBeforeUnloadConfirmPanelResultForTesting(bool result_success);
126 
127   void CloseWindowSoon() override;
128   bool OpenJavaScriptAlertDelegate(LocalFrame*, const String&) override;
129   bool OpenJavaScriptConfirmDelegate(LocalFrame*, const String&) override;
130   bool OpenJavaScriptPromptDelegate(LocalFrame*,
131                                     const String& message,
132                                     const String& default_value,
133                                     String& result) override;
134   bool TabsToLinks() override;
135   void InvalidateRect(const IntRect&) override;
136   void ScheduleAnimation(const LocalFrameView*,
137                          base::TimeDelta = base::TimeDelta()) override;
138   IntRect ViewportToScreen(const IntRect&,
139                            const LocalFrameView*) const override;
140   float WindowToViewportScalar(LocalFrame*, const float) const override;
141   ScreenInfo GetScreenInfo(LocalFrame&) const override;
142   void OverrideVisibleRectForMainFrame(LocalFrame& frame,
143                                        IntRect* paint_rect) const override;
144   float InputEventsScaleForEmulation() const override;
145   void ContentsSizeChanged(LocalFrame*, const IntSize&) const override;
146   bool DoubleTapToZoomEnabled() const override;
147   void EnablePreferredSizeChangedMode() override;
148   void ZoomToFindInPageRect(const WebRect& rect_in_root_frame) override;
149   void PageScaleFactorChanged() const override;
150   float ClampPageScaleFactorToLimits(float scale) const override;
151   void MainFrameScrollOffsetChanged(LocalFrame& main_frame) const override;
152   void ResizeAfterLayout() const override;
153   void MainFrameLayoutUpdated() const override;
154   void ShowMouseOverURL(const HitTestResult&) override;
155   void SetToolTip(LocalFrame&, const String&, TextDirection) override;
156   void DispatchViewportPropertiesDidChange(
157       const ViewportDescription&) const override;
158   void PrintDelegate(LocalFrame*) override;
159   ColorChooser* OpenColorChooser(LocalFrame*,
160                                  ColorChooserClient*,
161                                  const Color&) override;
162   DateTimeChooser* OpenDateTimeChooser(
163       LocalFrame* frame,
164       DateTimeChooserClient*,
165       const DateTimeChooserParameters&) override;
166   ExternalDateTimeChooser* GetExternalDateTimeChooserForTesting() override;
167   void OpenFileChooser(LocalFrame*, scoped_refptr<FileChooser>) override;
168   void SetCursor(const ui::Cursor&, LocalFrame*) override;
169   void SetCursorOverridden(bool) override;
170   ui::Cursor LastSetCursorForTesting() const override;
171   void SetEventListenerProperties(LocalFrame*,
172                                   cc::EventListenerClass,
173                                   cc::EventListenerProperties) override;
174   cc::EventListenerProperties EventListenerProperties(
175       LocalFrame*,
176       cc::EventListenerClass) const override;
177   // Informs client about the existence of handlers for scroll events so
178   // appropriate scroll optimizations can be chosen.
179   void SetHasScrollEventHandlers(LocalFrame*, bool has_event_handlers) override;
180   void SetNeedsLowLatencyInput(LocalFrame*, bool needs_low_latency) override;
181   void SetNeedsUnbufferedInputForDebugger(LocalFrame*, bool immediate) override;
182   void RequestUnbufferedInputEvents(LocalFrame*) override;
183   void SetTouchAction(LocalFrame*, TouchAction) override;
184 
185   void AttachRootLayer(scoped_refptr<cc::Layer>,
186                        LocalFrame* local_root) override;
187 
188   void AttachCompositorAnimationTimeline(CompositorAnimationTimeline*,
189                                          LocalFrame*) override;
190   void DetachCompositorAnimationTimeline(CompositorAnimationTimeline*,
191                                          LocalFrame*) override;
192 
193   void EnterFullscreen(LocalFrame&,
194                        const FullscreenOptions*,
195                        FullscreenRequestType) override;
196   void ExitFullscreen(LocalFrame&) override;
197   void FullscreenElementChanged(Element* old_element,
198                                 Element* new_element) override;
199 
200   void AnimateDoubleTapZoom(const gfx::Point& point,
201                             const gfx::Rect& rect) override;
202 
203   void ClearLayerSelection(LocalFrame*) override;
204   void UpdateLayerSelection(LocalFrame*, const cc::LayerSelection&) override;
205 
206   // ChromeClient methods:
207   String AcceptLanguages() override;
208   void SetCursorForPlugin(const ui::Cursor&, LocalFrame*) override;
209   void SetDelegatedInkMetadata(
210       LocalFrame* frame,
211       std::unique_ptr<viz::DelegatedInkMetadata> metadata) override;
212 
213   // ChromeClientImpl:
214   void SetNewWindowNavigationPolicy(WebNavigationPolicy);
215 
216   // FileChooser calls this function to kick pending file chooser
217   // requests.
218   void DidCompleteFileChooser(FileChooser& file_chooser);
219 
220   void AutoscrollStart(const gfx::PointF& viewport_point, LocalFrame*) override;
221   void AutoscrollFling(const gfx::Vector2dF& velocity, LocalFrame*) override;
222   void AutoscrollEnd(LocalFrame*) override;
223 
224   bool HasOpenedPopup() const override;
225   PopupMenu* OpenPopupMenu(LocalFrame&, HTMLSelectElement&) override;
226   PagePopup* OpenPagePopup(PagePopupClient*) override;
227   void ClosePagePopup(PagePopup*) override;
228   DOMWindow* PagePopupWindowForTesting() const override;
229 
230   void SetBrowserControlsState(float top_height,
231                                float bottom_height,
232                                bool shrinks_layout) override;
233   void SetBrowserControlsShownRatio(float top_ratio,
234                                     float bottom_ratio) override;
235 
236   bool ShouldOpenUIElementDuringPageDismissal(
237       LocalFrame&,
238       UIElementType,
239       const String& dialog_message,
240       Document::PageDismissalType) const override;
241 
242   // AutofillClient pass throughs:
243   void DidAssociateFormControlsAfterLoad(LocalFrame*) override;
244   void HandleKeyboardEventOnTextField(HTMLInputElement&,
245                                       KeyboardEvent&) override;
246   void DidChangeValueInTextField(HTMLFormControlElement&) override;
247   void DidEndEditingOnTextField(HTMLInputElement&) override;
248   void OpenTextDataListChooser(HTMLInputElement&) override;
249   void TextFieldDataListChanged(HTMLInputElement&) override;
250   void DidChangeSelectionInSelectControl(HTMLFormControlElement&) override;
251   void SelectFieldOptionsChanged(HTMLFormControlElement&) override;
252   void AjaxSucceeded(LocalFrame*) override;
253 
254   void ShowVirtualKeyboardOnElementFocus(LocalFrame&) override;
255 
256   TransformationMatrix GetDeviceEmulationTransform() const override;
257 
258   void OnMouseDown(Node&) override;
259   void DidUpdateBrowserControls() const override;
260 
261   FloatSize ElasticOverscroll() const override;
262 
263   void RegisterPopupOpeningObserver(PopupOpeningObserver*) override;
264   void UnregisterPopupOpeningObserver(PopupOpeningObserver*) override;
265   void NotifyPopupOpeningObservers() const override;
266 
267   viz::FrameSinkId GetFrameSinkId(LocalFrame*) override;
268 
269   void RequestDecode(LocalFrame*,
270                      const cc::PaintImage&,
271                      base::OnceCallback<void(bool)>) override;
272 
273   void NotifySwapTime(LocalFrame& frame, ReportTimeCallback callback) override;
274 
275   void RequestBeginMainFrameNotExpected(LocalFrame& frame,
276                                         bool request) override;
277 
278   void DidUpdateTextAutosizerPageInfo(
279       const mojom::blink::TextAutosizerPageInfo& page_info) override;
280 
281   int GetLayerTreeId(LocalFrame& frame) override;
282 
283   void DocumentDetached(Document&) override;
284 
285   double UserZoomFactor() const override;
286 
287   void BatterySavingsChanged(LocalFrame& main_frame,
288                              WebBatterySavingsFlags savings) override;
289 
290   void FormElementReset(HTMLFormElement& element) override;
291 
292   void PasswordFieldReset(HTMLInputElement& element) override;
293 
294  private:
IsChromeClientImpl()295   bool IsChromeClientImpl() const override { return true; }
296 
297   void SetCursorInternal(const ui::Cursor&, LocalFrame*);
298 
299   // Returns WebAutofillClient associated with the WebLocalFrame. This takes and
300   // returns nullable.
301   WebAutofillClient* AutofillClientFromFrame(LocalFrame*);
302 
303   WebViewImpl* web_view_;  // Weak pointer.
304   HeapHashSet<WeakMember<PopupOpeningObserver>> popup_opening_observers_;
305   Vector<scoped_refptr<FileChooser>> file_chooser_queue_;
306   ui::Cursor last_set_mouse_cursor_for_testing_;
307   bool cursor_overridden_;
308   Member<ExternalDateTimeChooser> external_date_time_chooser_;
309   bool did_request_non_empty_tool_tip_;
310   base::Optional<bool> before_unload_confirm_panel_result_for_testing_;
311 
312   FRIEND_TEST_ALL_PREFIXES(FileChooserQueueTest, DerefQueuedChooser);
313 };
314 
315 template <>
316 struct DowncastTraits<ChromeClientImpl> {
317   static bool AllowFrom(const ChromeClient& client) {
318     return client.IsChromeClientImpl();
319   }
320 };
321 
322 }  // namespace blink
323 
324 #endif
325