File: render_widget_host_view_tvos_uiview.mm

package info (click to toggle)
chromium 139.0.7258.127-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 6,122,156 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (345 lines) | stat: -rw-r--r-- 12,057 bytes parent folder | download | duplicates (3)
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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
// Copyright 2025 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/browser/renderer_host/render_widget_host_view_tvos_uiview.h"

#include "base/strings/sys_string_conversions.h"
#include "components/input/native_web_keyboard_event.h"
#include "third_party/blink/public/common/input/web_input_event.h"
#include "third_party/blink/public/common/input/web_keyboard_event.h"
#include "ui/base/ime/mojom/ime_types.mojom-shared.h"
#include "ui/events/base_event_utils.h"
#include "ui/events/keycodes/dom/dom_code.h"
#include "ui/events/keycodes/dom/dom_key.h"
#include "ui/events/keycodes/keyboard_codes.h"

static void* kObservingContext = &kObservingContext;

namespace {

UIKeyboardType keyboardTypeForInputType(ui::TextInputType inputType) {
  // TODO(crbug.com/411452047): Implement textFieldShouldEndEditing to detect
  // invalid contents in the text field. When texts are inserted via a H/W
  // connected keyboard, it's still possible to insert invalid contents.
  switch (inputType) {
    case ui::TextInputType::TEXT_INPUT_TYPE_SEARCH:
      return UIKeyboardTypeWebSearch;
    case ui::TextInputType::TEXT_INPUT_TYPE_EMAIL:
      return UIKeyboardTypeEmailAddress;
    case ui::TextInputType::TEXT_INPUT_TYPE_NUMBER:
      return UIKeyboardTypeNumberPad;
    case ui::TextInputType::TEXT_INPUT_TYPE_TELEPHONE:
      return UIKeyboardTypePhonePad;
    case ui::TextInputType::TEXT_INPUT_TYPE_URL:
      return UIKeyboardTypeURL;
    default:
      return UIKeyboardTypeASCIICapable;
  }
}

}  // namespace

@implementation RenderWidgetUIView

#pragma mark - Public

- (instancetype)initWithWidget:
    (base::WeakPtr<content::RenderWidgetHostViewIOS>)view {
  self = [self init];
  if (self) {
    _view = view;
    self.autoresizingMask =
        UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

    UITapGestureRecognizer* tapGesture =
        [[UITapGestureRecognizer alloc] initWithTarget:self
                                                action:@selector(tapGesture:)];
    [self addGestureRecognizer:tapGesture];

    UISwipeGestureRecognizer* swipeLeftGesture =
        [[UISwipeGestureRecognizer alloc]
            initWithTarget:self
                    action:@selector(swipeGesture:)];
    swipeLeftGesture.direction = UISwipeGestureRecognizerDirectionLeft;
    [self addGestureRecognizer:swipeLeftGesture];

    UISwipeGestureRecognizer* swipeRightGesture =
        [[UISwipeGestureRecognizer alloc]
            initWithTarget:self
                    action:@selector(swipeGesture:)];
    swipeRightGesture.direction = UISwipeGestureRecognizerDirectionRight;
    [self addGestureRecognizer:swipeRightGesture];

    UISwipeGestureRecognizer* swipeUpGesture = [[UISwipeGestureRecognizer alloc]
        initWithTarget:self
                action:@selector(swipeGesture:)];
    swipeUpGesture.direction = UISwipeGestureRecognizerDirectionUp;
    [self addGestureRecognizer:swipeUpGesture];

    UISwipeGestureRecognizer* swipeDownGesture =
        [[UISwipeGestureRecognizer alloc]
            initWithTarget:self
                    action:@selector(swipeGesture:)];
    swipeDownGesture.direction = UISwipeGestureRecognizerDirectionDown;
    [self addGestureRecognizer:swipeDownGesture];
  }
  return self;
}

// Contrary to iOS, on tvOS the on-screen keyboard takes the entire screen, so
// instead of showing it when an input element is focused, we require a tap to
// do it.
- (void)onUpdateTextInputState:(const ui::mojom::TextInputState&)state
                    withBounds:(CGRect)bounds {
  // Check for the visibility request and policy if VK APIs are enabled.
  if (state.vk_policy == ui::mojom::VirtualKeyboardPolicy::MANUAL) {
    // policy is manual.
    if (state.last_vk_visibility_request ==
        ui::mojom::VirtualKeyboardVisibilityRequest::SHOW) {
      [self showKeyboard:state];
    } else if (state.last_vk_visibility_request ==
               ui::mojom::VirtualKeyboardVisibilityRequest::HIDE) {
      [self hideAndDeleteKeyboard];
    }
  } else {
    bool hide = state.always_hide_ime ||
                state.mode == ui::TextInputMode::TEXT_INPUT_MODE_NONE ||
                state.type == ui::TextInputType::TEXT_INPUT_TYPE_NONE;
    if (hide) {
      [self hideAndDeleteKeyboard];
    } else if (state.show_ime_if_needed) {
      [self showKeyboard:state];
    }
  }
}

- (void)updateView:(UIScrollView*)view {
  [view addSubview:self];
  view.scrollEnabled = NO;
  // Remove all existing gestureRecognizers since the header might be reused.
  for (UIGestureRecognizer* recognizer in view.gestureRecognizers) {
    [view removeGestureRecognizer:recognizer];
  }
  [view addObserver:self
         forKeyPath:NSStringFromSelector(@selector(contentInset))
            options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld
            context:kObservingContext];
}

- (void)removeView {
  UIScrollView* view = (UIScrollView*)[self superview];
  [view removeObserver:self
            forKeyPath:NSStringFromSelector(@selector(contentInset))];
  [self removeFromSuperview];
}

#pragma mark - Private

- (void)tapGesture:(UIGestureRecognizer*)gestureRecognizer {
  if ([gestureRecognizer state] != UIGestureRecognizerStateEnded) {
    return;
  }

  const ui::mojom::TextInputState* state = [self editState];
  if (state && state->mode != ui::TextInputMode::TEXT_INPUT_MODE_NONE &&
      state->type != ui::TextInputType::TEXT_INPUT_TYPE_NONE) {
    [self showKeyboard:*state];
    return;
  }

  blink::WebKeyboardEvent event(blink::WebInputEvent::Type::kKeyDown,
                                blink::WebInputEvent::kNoModifiers,
                                ui::EventTimeForNow());
  event.native_key_code = UIKeyboardHIDUsageKeyboardReturnOrEnter;
  event.dom_code = static_cast<int>(ui::DomCode::ENTER);
  event.dom_key = ui::DomKey::ENTER;
  event.windows_key_code = ui::VKEY_RETURN;

  // Copied from components/input/web_input_event_builders_mac.mm's
  // WebKeyboardEventBuilder::Build().
  // This is necessary due to way some HTML elements process keyboard activation
  // (e.g. blink::HTMLElement::HandleKeyboardActivation()).
  event.text[0] = '\r';
  event.unmodified_text[0] = '\r';

  _view->SendKeyEvent(
      input::NativeWebKeyboardEvent(event, _view->GetNativeView()));

  // We also need to send a keyup event so that e.g. checkboxes are properly
  // activated/deactivated with the keyboard.
  event.SetType(blink::WebInputEvent::Type::kKeyUp);
  event.SetTimeStamp(ui::EventTimeForNow());
  _view->SendKeyEvent(
      input::NativeWebKeyboardEvent(event, _view->GetNativeView()));
}

- (void)swipeGesture:(UISwipeGestureRecognizer*)gestureRecognizer {
  if ([gestureRecognizer state] != UIGestureRecognizerStateEnded) {
    return;
  }

  const UISwipeGestureRecognizerDirection direction =
      gestureRecognizer.direction;

  blink::WebKeyboardEvent event(blink::WebInputEvent::Type::kKeyDown,
                                blink::WebInputEvent::kNoModifiers,
                                ui::EventTimeForNow());

  switch (direction) {
    case UISwipeGestureRecognizerDirectionLeft:
      event.native_key_code = UIKeyboardHIDUsageKeyboardLeftArrow;
      event.dom_code = static_cast<int>(ui::DomCode::ARROW_LEFT);
      event.dom_key = ui::DomKey::ARROW_LEFT;
      event.windows_key_code = ui::VKEY_LEFT;
      break;
    case UISwipeGestureRecognizerDirectionRight:
      event.native_key_code = UIKeyboardHIDUsageKeyboardRightArrow;
      event.dom_code = static_cast<int>(ui::DomCode::ARROW_RIGHT);
      event.dom_key = ui::DomKey::ARROW_RIGHT;
      event.windows_key_code = ui::VKEY_RIGHT;
      break;
    case UISwipeGestureRecognizerDirectionUp:
      event.native_key_code = UIKeyboardHIDUsageKeyboardUpArrow;
      event.dom_code = static_cast<int>(ui::DomCode::ARROW_UP);
      event.dom_key = ui::DomKey::ARROW_UP;
      event.windows_key_code = ui::VKEY_UP;
      break;
    case UISwipeGestureRecognizerDirectionDown:
      event.native_key_code = UIKeyboardHIDUsageKeyboardDownArrow;
      event.dom_code = static_cast<int>(ui::DomCode::ARROW_DOWN);
      event.dom_key = ui::DomKey::ARROW_DOWN;
      event.windows_key_code = ui::VKEY_DOWN;
      break;
  }

  _view->SendKeyEvent(
      input::NativeWebKeyboardEvent(event, _view->GetNativeView()));
}

- (void)showKeyboard:(const ui::mojom::TextInputState&)state {
  if (_textFieldForAllTextInput) {
    return;
  }

  _textFieldForAllTextInput = [[UITextField alloc] init];
  _textFieldForAllTextInput.delegate = self;
  _textFieldForAllTextInput.keyboardType = keyboardTypeForInputType(state.type);
  if (state.value.has_value()) {
    _textFieldForAllTextInput.text =
        base::SysUTF16ToNSString(state.value.value());
  }
  if (state.type == ui::TextInputType::TEXT_INPUT_TYPE_PASSWORD) {
    _textFieldForAllTextInput.secureTextEntry = YES;
    // state.value.value() contains "\u2022" characters instead of actual text,
    // so it makes more sense to just start with an empty field to avoid the
    // case of a bogus value being set and used if the user just presses "done"
    // on the on-screen keyboard.
    _textFieldForAllTextInput.text = nil;
  }

  [self addSubview:_textFieldForAllTextInput];
  [_textFieldForAllTextInput becomeFirstResponder];
}

- (void)hideAndDeleteKeyboard {
  [_textFieldForAllTextInput removeFromSuperview];
  _textFieldForAllTextInput = nil;
}

- (const ui::mojom::TextInputState*)editState {
  if (!_view || !_view->GetTextInputManager()) {
    return nil;
  }
  return _view->GetTextInputManager()->GetTextInputState();
}

#pragma mark - CALayerFrameSinkProvider

- (ui::CALayerFrameSink*)frameSink {
  return _view.get();
}

#pragma mark - NSObject

- (void)observeValueForKeyPath:(NSString*)keyPath
                      ofObject:(id)object
                        change:(NSDictionary*)change
                       context:(void*)context {
  CHECK(_view);
  if (context == kObservingContext) {
    _view->ContentInsetChanged();
  } else {
    [super observeValueForKeyPath:keyPath
                         ofObject:object
                           change:change
                          context:context];
  }
}

#pragma mark - UIResponder

- (BOOL)canBecomeFirstResponder {
  return YES;
}

- (BOOL)isFirstResponder {
  return
      [super isFirstResponder] || [_textFieldForAllTextInput isFirstResponder];
}

- (BOOL)becomeFirstResponder {
  CHECK(_view);
  const BOOL result = [super becomeFirstResponder];
  const BOOL keyboard_is_hidden =
      !_textFieldForAllTextInput || [_textFieldForAllTextInput isHidden];
  if (keyboard_is_hidden &&
      (result || _view->CanBecomeFirstResponderForTesting())) {
    _view->OnFirstResponderChanged();
  }
  return result;
}

- (BOOL)resignFirstResponder {
  const BOOL result = [super resignFirstResponder];
  const BOOL keyboard_is_hidden =
      !_textFieldForAllTextInput || [_textFieldForAllTextInput isHidden];
  if (_view && keyboard_is_hidden &&
      (result || _view->CanResignFirstResponderForTesting())) {
    _view->OnFirstResponderChanged();
  }
  return result;
}

#pragma mark - UITextFieldDelegate

- (void)textFieldDidEndEditing:(UITextField*)textField
                        reason:(UITextFieldDidEndEditingReason)reason {
  CHECK_EQ(textField, _textFieldForAllTextInput);
  if (reason == UITextFieldDidEndEditingReasonCommitted) {
    const ui::mojom::TextInputState* state = [self editState];
    const gfx::Range range = state ? gfx::Range(0, state->selection.GetMax())
                                   : gfx::Range::InvalidRange();
    _view->ImeCommitText(base::SysNSStringToUTF16(textField.text), range, 0);
  }

  [self hideAndDeleteKeyboard];
}

#pragma mark - UIView

- (BOOL)canBecomeFocused {
  return YES;
}

- (void)layoutSubviews {
  CHECK(_view);
  [super layoutSubviews];
  _view->UpdateScreenInfo();

  // TODO(dtapuska): This isn't correct, we need to figure out when the window
  // gains/loses focus.
  _view->SetActive(true);
}

@end