Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(1005)

Side by Side Diff: third_party/WebKit/Source/core/editing/suggestion/TextSuggestionController.cpp

Issue 2931443003: Add support for Android spellcheck menu in Chrome/WebViews (Closed)
Patch Set: Respond to UI + editing feedback Created 3 years, 5 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 // Copyright 2017 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "core/editing/suggestion/TextSuggestionController.h"
6
7 #include "core/editing/EditingUtilities.h"
8 #include "core/editing/Editor.h"
9 #include "core/editing/FrameSelection.h"
10 #include "core/editing/PlainTextRange.h"
11 #include "core/editing/Position.h"
12 #include "core/editing/markers/DocumentMarkerController.h"
13 #include "core/editing/markers/SpellCheckMarker.h"
14 #include "core/editing/spellcheck/SpellChecker.h"
15 #include "core/frame/FrameView.h"
16 #include "core/frame/LocalFrame.h"
17 #include "core/layout/LayoutTheme.h"
18 #include "services/service_manager/public/cpp/interface_provider.h"
19
20 namespace blink {
21
22 namespace {
23
24 bool ShouldDeleteNextCharacter(const Node& marker_text_node,
25 const DocumentMarker& marker) {
26 // If the character immediately following the range to be deleted is a space,
27 // delete it if either of these conditions holds:
28 // - We're deleting at the beginning of the editable text (to avoid ending up
29 // with a space at the beginning)
30 // - The character immediately before the range being deleted is also a space
31 // (to avoid ending up with two adjacent spaces)
32 const EphemeralRange next_character_range =
33 PlainTextRange(marker.EndOffset(), marker.EndOffset() + 1)
34 .CreateRange(*marker_text_node.parentNode());
35 // No character immediately following the range (so it can't be a space)
36 if (next_character_range.IsNull())
37 return false;
38
39 const String next_character_str =
40 PlainText(next_character_range, TextIteratorBehavior::Builder().Build());
41 const UChar next_character = next_character_str[0];
42 // Character immediately following the range is not a space
43 if (next_character != kSpaceCharacter &&
44 next_character != kNoBreakSpaceCharacter)
45 return false;
46
47 // First case: we're deleting at the beginning of the editable text
48 if (marker.StartOffset() == 0)
49 return true;
50
51 const EphemeralRange prev_character_range =
52 PlainTextRange(marker.StartOffset() - 1, marker.StartOffset())
53 .CreateRange(*marker_text_node.parentNode());
54 // Not at beginning, but there's no character immediately before the range
55 // being deleted (so it can't be a space)
56 if (prev_character_range.IsNull())
57 return false;
58
59 const String prev_character_str =
60 PlainText(prev_character_range, TextIteratorBehavior::Builder().Build());
61 // Return true if the character immediately before the range is a space, false
62 // otherwise
63 const UChar prev_character = prev_character_str[0];
64 return prev_character == kSpaceCharacter ||
65 prev_character == kNoBreakSpaceCharacter;
66 }
67
68 EphemeralRangeInFlatTree ComputeRangeSurroundingCaret(
69 const PositionInFlatTree& caret_position) {
70 const Node* const position_node = caret_position.ComputeContainerNode();
71 const bool is_text_node = position_node->IsTextNode();
72 const unsigned position_offset_in_node =
yosin_UTC9 2017/07/21 01:12:23 nit: s/unsigned/int/ Position::ComputeOffsetInCon
73 caret_position.ComputeOffsetInContainerNode();
74
75 // If we're in the interior of a text node, we can avoid calling
76 // PreviousPositionOf/NextPositionOf for better efficiency.
77 if (is_text_node && position_offset_in_node != 0 &&
78 position_offset_in_node !=
79 static_cast<unsigned>(position_node->MaxCharacterOffset())) {
80 return EphemeralRangeInFlatTree(
81 PositionInFlatTree(position_node, position_offset_in_node - 1),
82 PositionInFlatTree(position_node, position_offset_in_node + 1));
83 }
84
85 const PositionInFlatTree& previous_position =
86 PreviousPositionOf(caret_position, PositionMoveType::kGraphemeCluster);
87
88 const PositionInFlatTree& next_position =
89 NextPositionOf(caret_position, PositionMoveType::kGraphemeCluster);
90
91 return EphemeralRangeInFlatTree(
92 previous_position.IsNull() ? caret_position : previous_position,
93 next_position.IsNull() ? caret_position : next_position);
94 }
95
96 } // namespace
97
98 TextSuggestionController::TextSuggestionController(LocalFrame& frame)
99 : is_suggestion_menu_open_(false), frame_(&frame) {}
100
101 void TextSuggestionController::DocumentAttached(Document* document) {
102 DCHECK(document);
103 SetContext(document);
104 }
105
106 bool TextSuggestionController::IsMenuOpen() const {
107 return is_suggestion_menu_open_;
108 }
109
110 void TextSuggestionController::HandlePotentialMisspelledWordTap(
111 const PositionInFlatTree& caret_position) {
112 const EphemeralRangeInFlatTree& range_to_check =
113 ComputeRangeSurroundingCaret(caret_position);
114
115 const std::pair<const Node*, const DocumentMarker*>& node_and_marker =
116 FirstMarkerIntersectingRange(range_to_check,
117 DocumentMarker::MisspellingMarkers());
118 if (!node_and_marker.first)
119 return;
120
121 if (!text_suggestion_host_) {
122 GetFrame().GetInterfaceProvider().GetInterface(
123 mojo::MakeRequest(&text_suggestion_host_));
124 }
125
126 text_suggestion_host_->StartSpellCheckMenuTimer();
127 }
128
129 DEFINE_TRACE(TextSuggestionController) {
130 visitor->Trace(frame_);
131 DocumentShutdownObserver::Trace(visitor);
132 }
133
134 void TextSuggestionController::ApplySpellCheckSuggestion(
135 const String& suggestion) {
136 ReplaceSpellingMarkerTouchingSelectionWithText(suggestion);
137 SuggestionMenuClosed();
138 }
139
140 void TextSuggestionController::DeleteActiveSuggestionRange() {
141 AttemptToDeleteActiveSuggestionRange();
142 SuggestionMenuClosed();
143 }
144
145 void TextSuggestionController::NewWordAddedToDictionary(const String& word) {
146 // Android pops up a dialog to let the user confirm they actually want to add
147 // the word to the dictionary; this method gets called as soon as the dialog
148 // is shown. So the word isn't actually in the dictionary here, even if the
149 // user will end up confirming the dialog, and we shouldn't try to re-run
150 // spellcheck here.
151
152 // Note: this actually matches the behavior in native Android text boxes
153 GetDocument().Markers().RemoveSpellingMarkersUnderWords(
154 Vector<String>({word}));
155 SuggestionMenuClosed();
156 }
157
158 void TextSuggestionController::SpellCheckMenuTimeoutCallback() {
159 const std::pair<const Node*, const DocumentMarker*>& node_and_marker =
160 FirstMarkerTouchingSelection(DocumentMarker::MisspellingMarkers());
161 if (!node_and_marker.first)
162 return;
163
164 const Node* const marker_text_node = node_and_marker.first;
165 const SpellCheckMarker* const marker =
166 ToSpellCheckMarker(node_and_marker.second);
167
168 const EphemeralRange marker_range =
169 EphemeralRange(Position(marker_text_node, marker->StartOffset()),
170 Position(marker_text_node, marker->EndOffset()));
171 const String& misspelled_word = PlainText(marker_range);
172 const String& description = marker->Description();
173
174 is_suggestion_menu_open_ = true;
175 GetFrame().Selection().SetCaretVisible(false);
176 GetDocument().Markers().AddActiveSuggestionMarker(
177 marker_range, SK_ColorTRANSPARENT, StyleableMarker::Thickness::kThin,
178 LayoutTheme::GetTheme().PlatformActiveSpellingMarkerHighlightColor());
179
180 Vector<String> suggestions;
181 description.Split('\n', suggestions);
182
183 Vector<mojom::blink::SpellCheckSuggestionPtr> suggestion_ptrs;
184 for (const String& suggestion : suggestions) {
185 mojom::blink::SpellCheckSuggestionPtr info_ptr(
186 mojom::blink::SpellCheckSuggestion::New());
187 info_ptr->suggestion = suggestion;
188 suggestion_ptrs.push_back(std::move(info_ptr));
189 }
190
191 const IntRect& absolute_bounds = GetFrame().Selection().AbsoluteCaretBounds();
192 const IntRect& viewport_bounds =
193 GetFrame().View()->ContentsToViewport(absolute_bounds);
194
195 text_suggestion_host_->ShowSpellCheckSuggestionMenu(
196 viewport_bounds.X(), viewport_bounds.MaxY(), std::move(misspelled_word),
197 std::move(suggestion_ptrs));
198 }
199
200 void TextSuggestionController::SuggestionMenuClosed() {
201 if (!IsAvailable())
202 return;
203
204 GetDocument().Markers().RemoveMarkersOfTypes(
205 DocumentMarker::kActiveSuggestion);
206 GetFrame().Selection().SetCaretVisible(true);
207 is_suggestion_menu_open_ = false;
208 }
209
210 Document& TextSuggestionController::GetDocument() const {
211 DCHECK(IsAvailable());
212 return *LifecycleContext();
213 }
214
215 bool TextSuggestionController::IsAvailable() const {
216 return LifecycleContext();
217 }
218
219 LocalFrame& TextSuggestionController::GetFrame() const {
220 DCHECK(frame_);
221 return *frame_;
222 }
223
224 std::pair<const Node*, const DocumentMarker*>
225 TextSuggestionController::FirstMarkerIntersectingRange(
226 const EphemeralRangeInFlatTree& range,
227 DocumentMarker::MarkerTypes types) const {
228 const Node* const range_start_container =
229 range.StartPosition().ComputeContainerNode();
230 const unsigned range_start_offset =
yosin_UTC9 2017/07/21 01:12:23 nit: s/unsigned/int/
231 range.StartPosition().ComputeOffsetInContainerNode();
232 const Node* const range_end_container =
233 range.EndPosition().ComputeContainerNode();
234 const unsigned range_end_offset =
yosin_UTC9 2017/07/21 01:12:23 nit: s/unsigned/int/
235 range.EndPosition().ComputeOffsetInContainerNode();
236
237 for (const Node& node : range.Nodes()) {
238 if (!node.IsTextNode())
239 continue;
240
241 const unsigned start_offset =
yosin_UTC9 2017/07/21 01:12:23 nit: s/unsigned/int/
242 node == range_start_container ? range_start_offset : 0;
243 const unsigned end_offset = node == range_end_container
yosin_UTC9 2017/07/21 01:12:23 nit: s/unsigned/int/ CharacterData::MaxCharacterOf
244 ? range_end_offset
245 : node.MaxCharacterOffset();
246
247 const DocumentMarker* const found_marker =
248 GetFrame().GetDocument()->Markers().FirstMarkerIntersectingOffsetRange(
249 ToText(node), start_offset, end_offset, types);
250 if (found_marker)
251 return std::make_pair(&node, found_marker);
252 }
253
254 return {};
255 }
256
257 std::pair<const Node*, const DocumentMarker*>
258 TextSuggestionController::FirstMarkerTouchingSelection(
259 DocumentMarker::MarkerTypes types) const {
260 const VisibleSelectionInFlatTree& selection =
261 GetFrame().Selection().ComputeVisibleSelectionInFlatTree();
262 if (selection.IsNone())
263 return {};
264
265 const EphemeralRangeInFlatTree& range_to_check =
266 selection.IsRange() ? selection.ToNormalizedEphemeralRange()
yosin_UTC9 2017/07/21 01:12:23 Could you use |EphemeralRangeInFlatTree(selection.
267 : ComputeRangeSurroundingCaret(selection.Start());
268
269 return FirstMarkerIntersectingRange(range_to_check, types);
270 }
271
272 void TextSuggestionController::AttemptToDeleteActiveSuggestionRange() {
273 const std::pair<const Node*, const DocumentMarker*>& node_and_marker =
274 FirstMarkerTouchingSelection(DocumentMarker::kActiveSuggestion);
275 if (!node_and_marker.first)
276 return;
277
278 const Node* const marker_text_node = node_and_marker.first;
279 const DocumentMarker* const marker = node_and_marker.second;
280
281 const bool delete_next_char =
282 ShouldDeleteNextCharacter(*marker_text_node, *marker);
283
284 const EphemeralRange range_to_delete = EphemeralRange(
285 Position(marker_text_node, marker->StartOffset()),
286 Position(marker_text_node, marker->EndOffset() + delete_next_char));
287 ReplaceRangeWithText(range_to_delete, "");
288 }
289
290 void TextSuggestionController::ReplaceSpellingMarkerTouchingSelectionWithText(
291 const String& suggestion) {
292 const std::pair<const Node*, const DocumentMarker*>& node_and_marker =
293 FirstMarkerTouchingSelection(DocumentMarker::MisspellingMarkers());
294 if (!node_and_marker.first)
295 return;
296
297 const Node* const marker_text_node = node_and_marker.first;
298 const DocumentMarker* const marker = node_and_marker.second;
299
300 const EphemeralRange range_to_replace(
301 Position(marker_text_node, marker->StartOffset()),
302 Position(marker_text_node, marker->EndOffset()));
303 ReplaceRangeWithText(range_to_replace, suggestion);
304 }
305
306 void TextSuggestionController::ReplaceRangeWithText(const EphemeralRange& range,
307 const String& replacement) {
308 GetFrame().Selection().SetSelection(
309 SelectionInDOMTree::Builder().SetBaseAndExtent(range).Build());
310
311 // Dispatch 'beforeinput'.
312 Element* const target = GetFrame().GetEditor().FindEventTargetFromSelection();
313 DataTransfer* const data_transfer = DataTransfer::Create(
314 DataTransfer::DataTransferType::kInsertReplacementText,
315 DataTransferAccessPolicy::kDataTransferReadable,
316 DataObject::CreateFromString(replacement));
317
318 const bool is_canceled =
319 DispatchBeforeInputDataTransfer(
320 target, InputEvent::InputType::kInsertReplacementText,
321 data_transfer) != DispatchEventResult::kNotCanceled;
322
323 // 'beforeinput' event handler may destroy target frame.
324 if (!IsAvailable())
325 return;
326
327 // TODO(editing-dev): The use of updateStyleAndLayoutIgnorePendingStylesheets
328 // needs to be audited. See http://crbug.com/590369 for more details.
329 GetFrame().GetDocument()->UpdateStyleAndLayoutIgnorePendingStylesheets();
330
331 if (is_canceled)
332 return;
333 GetFrame().GetEditor().ReplaceSelectionWithText(
334 replacement, false, false, InputEvent::InputType::kInsertReplacementText);
335 }
336
337 } // namespace blink
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698