summaryrefslogtreecommitdiff
path: root/chromium/third_party/blink/renderer/core/page/chrome_client.cc
blob: 4b42770e1650670839fcabeaf7f8dd66fc5a228a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
/*
 * Copyright (C) 2006, 2007, 2009, 2011 Apple Inc. All rights reserved.
 * Copyright (C) 2008, 2010 Nokia Corporation and/or its subsidiary(-ies)
 * Copyright (C) 2012, Samsung Electronics. All rights reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

#include "third_party/blink/renderer/core/page/chrome_client.h"

#include <algorithm>

#include "third_party/blink/public/common/widget/screen_info.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/public/platform/web_prescient_networking.h"
#include "third_party/blink/renderer/core/core_initializer.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/element.h"
#include "third_party/blink/renderer/core/frame/frame_console.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/inspector/console_message.h"
#include "third_party/blink/renderer/core/layout/hit_test_result.h"
#include "third_party/blink/renderer/core/page/frame_tree.h"
#include "third_party/blink/renderer/core/page/page.h"
#include "third_party/blink/renderer/core/page/scoped_page_pauser.h"
#include "third_party/blink/renderer/core/probe/core_probes.h"
#include "third_party/blink/renderer/platform/geometry/int_rect.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"

namespace blink {

void ChromeClient::Trace(Visitor* visitor) const {
  visitor->Trace(last_mouse_over_node_);
}

void ChromeClient::InstallSupplements(LocalFrame& frame) {
  CoreInitializer::GetInstance().InstallSupplements(frame);
}

IntRect ChromeClient::CalculateWindowRectWithAdjustment(
    const IntRect& pending_rect,
    LocalFrame& frame,
    LocalFrame& requesting_frame) {
  IntRect screen(GetScreenInfo(frame).available_rect);
  IntRect window = pending_rect;

  IntSize minimum_size = MinimumWindowSize();
  IntSize size_for_constraining_move = minimum_size;
  // Let size 0 pass through, since that indicates default size, not minimum
  // size.
  if (window.Width()) {
    int width = std::max(minimum_size.Width(), window.Width());
    // If the Window Placement experiment is enabled, the window could be placed
    // on another screen, and so it should not be limited by the current screen.
    // This relies on the embedder clamping bounds to the target screen for now.
    // TODO(http://crbug.com/897300): Implement multi-screen clamping in Blink.
    if (!RuntimeEnabledFeatures::WindowPlacementEnabled(
            requesting_frame.DomWindow())) {
      width = std::min(width, screen.Width());
    }
    window.SetWidth(width);
    size_for_constraining_move.SetWidth(window.Width());
  }
  if (window.Height()) {
    int height = std::max(minimum_size.Height(), window.Height());
    // If the Window Placement experiment is enabled, the window could be placed
    // on another screen, and so it should not be limited by the current screen.
    // This relies on the embedder clamping bounds to the target screen for now.
    // TODO(http://crbug.com/897300): Implement multi-screen clamping in Blink.
    if (!RuntimeEnabledFeatures::WindowPlacementEnabled(
            requesting_frame.DomWindow())) {
      height = std::min(height, screen.Height());
    }
    window.SetHeight(height);
    size_for_constraining_move.SetHeight(window.Height());
  }

  // If the Window Placement experiment is enabled, the window could be placed
  // on another screen, and so it should not be limited by the current screen.
  // This relies on the embedder clamping bounds to the target screen for now.
  // TODO(http://crbug.com/897300): Implement multi-screen clamping in Blink.
  if (!RuntimeEnabledFeatures::WindowPlacementEnabled(
          requesting_frame.DomWindow())) {
    // Constrain the window position within the valid screen area.
    window.SetX(
        std::max(screen.X(),
                 std::min(window.X(),
                          screen.MaxX() - size_for_constraining_move.Width())));
    window.SetY(std::max(
        screen.Y(),
        std::min(window.Y(),
                 screen.MaxY() - size_for_constraining_move.Height())));
  }

  // Coarsely measure whether coordinates may be requesting another screen.
  if (!screen.Contains(window)) {
    UseCounter::Count(frame.DomWindow(),
                      WebFeature::kDOMWindowSetWindowRectCrossScreen);
  }

  return window;
}

void ChromeClient::SetWindowRectWithAdjustment(const IntRect& pending_rect,
                                               LocalFrame& frame) {
  IntRect rect = CalculateWindowRectWithAdjustment(pending_rect, frame, frame);
  SetWindowRect(rect, frame);
}

bool ChromeClient::CanOpenUIElementIfDuringPageDismissal(
    Frame& main_frame,
    UIElementType ui_element_type,
    const String& message) {
  for (Frame* frame = &main_frame; frame;
       frame = frame->Tree().TraverseNext()) {
    auto* local_frame = DynamicTo<LocalFrame>(frame);
    if (!local_frame)
      continue;
    Document::PageDismissalType dismissal =
        local_frame->GetDocument()->PageDismissalEventBeingDispatched();
    if (dismissal != Document::kNoDismissal) {
      return ShouldOpenUIElementDuringPageDismissal(
          *local_frame, ui_element_type, message, dismissal);
    }
  }
  return true;
}

Page* ChromeClient::CreateWindow(
    LocalFrame* frame,
    const FrameLoadRequest& r,
    const AtomicString& frame_name,
    const WebWindowFeatures& features,
    network::mojom::blink::WebSandboxFlags sandbox_flags,
    const FeaturePolicyFeatureState& opener_feature_state,
    const SessionStorageNamespaceId& session_storage_namespace_id,
    bool& consumed_user_gesture) {
  if (!CanOpenUIElementIfDuringPageDismissal(
          frame->Tree().Top(), UIElementType::kPopup, g_empty_string)) {
    return nullptr;
  }

  return CreateWindowDelegate(
      frame, r, frame_name, features, sandbox_flags, opener_feature_state,
      session_storage_namespace_id, consumed_user_gesture);
}

template <typename Delegate>
static bool OpenJavaScriptDialog(LocalFrame* frame,
                                 const String& message,
                                 const Delegate& delegate) {
  // Suspend pages in case the client method runs a new event loop that would
  // otherwise cause the load to continue while we're in the middle of
  // executing JavaScript.
  ScopedPagePauser pauser;
  probe::WillRunJavaScriptDialog(frame);
  bool result = delegate();
  probe::DidRunJavaScriptDialog(frame);
  return result;
}

bool ChromeClient::OpenBeforeUnloadConfirmPanel(const String& message,
                                                LocalFrame* frame,
                                                bool is_reload) {
  DCHECK(frame);
  return OpenJavaScriptDialog(frame, message, [this, frame, is_reload]() {
    return OpenBeforeUnloadConfirmPanelDelegate(frame, is_reload);
  });
}

bool ChromeClient::OpenJavaScriptAlert(LocalFrame* frame,
                                       const String& message) {
  DCHECK(frame);
  if (!CanOpenUIElementIfDuringPageDismissal(
          frame->Tree().Top(), UIElementType::kAlertDialog, message)) {
    return false;
  }
  return OpenJavaScriptDialog(frame, message, [this, frame, &message]() {
    return OpenJavaScriptAlertDelegate(frame, message);
  });
}

bool ChromeClient::OpenJavaScriptConfirm(LocalFrame* frame,
                                         const String& message) {
  DCHECK(frame);
  if (!CanOpenUIElementIfDuringPageDismissal(
          frame->Tree().Top(), UIElementType::kConfirmDialog, message)) {
    return false;
  }
  return OpenJavaScriptDialog(frame, message, [this, frame, &message]() {
    return OpenJavaScriptConfirmDelegate(frame, message);
  });
}

bool ChromeClient::OpenJavaScriptPrompt(LocalFrame* frame,
                                        const String& prompt,
                                        const String& default_value,
                                        String& result) {
  DCHECK(frame);
  if (!CanOpenUIElementIfDuringPageDismissal(
          frame->Tree().Top(), UIElementType::kPromptDialog, prompt)) {
    return false;
  }
  return OpenJavaScriptDialog(
      frame, prompt, [this, frame, &prompt, &default_value, &result]() {
        return OpenJavaScriptPromptDelegate(frame, prompt, default_value,
                                            result);
      });
}

void ChromeClient::MouseDidMoveOverElement(LocalFrame& frame,
                                           const HitTestLocation& location,
                                           const HitTestResult& result) {
  if (!result.GetScrollbar() && result.InnerNode() &&
      result.InnerNode()->GetDocument().IsDNSPrefetchEnabled()) {
    WebPrescientNetworking* web_prescient_networking =
        frame.PrescientNetworking();
    if (web_prescient_networking) {
      web_prescient_networking->PrefetchDNS(result.AbsoluteLinkURL().Host());
    }
  }

  ShowMouseOverURL(result);

  if (result.GetScrollbar())
    ClearToolTip(frame);
  else
    SetToolTip(frame, location, result);
}

void ChromeClient::SetToolTip(LocalFrame& frame,
                              const HitTestLocation& location,
                              const HitTestResult& result) {
  // First priority is a tooltip for element with "title" attribute.
  TextDirection tool_tip_direction;
  String tool_tip = result.Title(tool_tip_direction);

  // Lastly, some elements provide default tooltip strings.  e.g. <input
  // type="file" multiple> shows a tooltip for the selected filenames.
  if (tool_tip.IsNull()) {
    if (auto* element = DynamicTo<Element>(result.InnerNode())) {
      tool_tip = element->DefaultToolTip();

      // FIXME: We should obtain text direction of tooltip from
      // ChromeClient or platform. As of October 2011, all client
      // implementations don't use text direction information for
      // ChromeClient::setToolTip. We'll work on tooltip text
      // direction during bidi cleanup in form inputs.
      tool_tip_direction = TextDirection::kLtr;
    }
  }

  if (last_tool_tip_point_ == location.Point() &&
      last_tool_tip_text_ == tool_tip)
    return;

  // If a tooltip was displayed earlier, and mouse cursor moves over
  // a different node with the same tooltip text, make sure the previous
  // tooltip is unset, so that it does not get stuck positioned relative
  // to the previous node).
  // The ::setToolTip overload, which is be called down the road,
  // ensures a new tooltip to be displayed with the new context.
  if (result.InnerNodeOrImageMapImage() != last_mouse_over_node_ &&
      !last_tool_tip_text_.IsEmpty() && tool_tip == last_tool_tip_text_)
    ClearToolTip(frame);

  last_tool_tip_point_ = location.Point();
  last_tool_tip_text_ = tool_tip;
  last_mouse_over_node_ = result.InnerNodeOrImageMapImage();
  current_tool_tip_text_for_test_ = last_tool_tip_text_;
  SetToolTip(frame, tool_tip, tool_tip_direction);
}

void ChromeClient::ClearToolTip(LocalFrame& frame) {
  current_tool_tip_text_for_test_ = String();
  // Do not check last_tool_tip_* and do not update them intentionally.
  // We don't want to show tooltips with same content after clearToolTip().
  SetToolTip(frame, String(), TextDirection::kLtr);
}

bool ChromeClient::Print(LocalFrame* frame) {
  if (!CanOpenUIElementIfDuringPageDismissal(*frame->GetPage()->MainFrame(),
                                             UIElementType::kPrintDialog,
                                             g_empty_string)) {
    return false;
  }

  if (frame->DomWindow()->IsSandboxed(
          network::mojom::blink::WebSandboxFlags::kModals)) {
    UseCounter::Count(frame->DomWindow(),
                      WebFeature::kDialogInSandboxedContext);
    frame->Console().AddMessage(MakeGarbageCollected<ConsoleMessage>(
        mojom::ConsoleMessageSource::kSecurity,
        mojom::ConsoleMessageLevel::kError,
        "Ignored call to 'print()'. The document is sandboxed, and the "
        "'allow-modals' keyword is not set."));
    return false;
  }

  // Suspend pages in case the client method runs a new event loop that would
  // otherwise cause the load to continue while we're in the middle of
  // executing JavaScript.
  // TODO(crbug.com/956832): Remove this when it is safe to do so.
  ScopedPagePauser pauser;

  PrintDelegate(frame);
  return true;
}

}  // namespace blink