Debian Codegraph @

modules/skottie/utils/TextEditor.cpp

raw
1 /*
2 * Copyright 2022 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8 #include "modules/skottie/utils/TextEditor.h"
9
10 #include "include/core/SkCanvas.h"
11 #include "include/core/SkColor.h"
12 #include "include/core/SkM44.h"
13 #include "include/core/SkMatrix.h"
14 #include "include/core/SkPaint.h"
15 #include "include/core/SkPath.h"
16 #include "include/core/SkPathBuilder.h"
17 #include "include/core/SkPoint.h"
18 #include "include/core/SkRefCnt.h"
19 #include "include/core/SkSpan.h"
20 #include "include/core/SkString.h"
21 #include "src/base/SkUTF.h"
22 #include "tools/skui/InputState.h"
23
24 #include <algorithm>
25 #include <limits>
26 #include <utility>
27
28 namespace skottie_utils {
29
30 namespace {
31
32 SkPath make_cursor_path() {
33 // Normalized values, relative to text/font size.
34 constexpr float kWidth = 0.2f,
35 kHeight = 0.75f;
36
37 SkPathBuilder p;
38
39 p.moveTo(0, 0);
40 p.lineTo(kWidth , 0);
41 p.moveTo(kWidth/2, 0);
42 p.lineTo(kWidth/2, kHeight);
43 p.moveTo(0 , kHeight);
44 p.lineTo(kWidth , kHeight);
45
46 return p.detach();
47 }
48
49 size_t next_utf8(const SkString& str, size_t index) {
50 SkASSERT(index < str.size());
51
52 const char* utf8_ptr = str.c_str() + index;
53
54 if (SkUTF::NextUTF8(&utf8_ptr, str.c_str() + str.size()) < 0){
55 // Invalid UTF sequence.
56 return index;
57 }
58
59 return utf8_ptr - str.c_str();
60 }
61
62 size_t prev_utf8(const SkString& str, size_t index) {
63 SkASSERT(index > 0);
64
65 // Find the previous utf8 index by probing the preceding 4 offsets. Utf8 leading bytes are
66 // always distinct from continuation bytes, so only one of these probes will succeed.
67 for (unsigned i = 1; i <= SkUTF::kMaxBytesInUTF8Sequence && i <= index; ++i) {
68 const char* utf8_ptr = str.c_str() + index - i;
69 if (SkUTF::NextUTF8(&utf8_ptr, str.c_str() + str.size()) >= 0) {
70 return index - i;
71 }
72 }
73
74 // Invalid UTF sequence.
75 return index;
76 }
77
78 } // namespace
79
80 TextEditor::TextEditor(
81 std::unique_ptr<skottie::TextPropertyHandle>&& prop,
82 std::vector<std::unique_ptr<skottie::TextPropertyHandle>>&& deps)
83 : fTextProp(std::move(prop))
84 , fDependentProps(std::move(deps))
85 , fCursorPath(make_cursor_path())
86 , fCursorBounds(fCursorPath.computeTightBounds())
87 {}
88
89 TextEditor::~TextEditor() = default;
90
91 void TextEditor::toggleEnabled() {
92 fEnabled = !fEnabled;
93
94 auto txt = fTextProp->get();
95 txt.fDecorator = fEnabled ? sk_ref_sp(this) : nullptr;
96 fTextProp->set(txt);
97
98 if (fEnabled) {
99 // Always reset the cursor position to the end.
100 fCursorIndex = txt.fText.size();
101 }
102
103 fTimeBase = std::chrono::steady_clock::now();
104 }
105
106 void TextEditor::setEnabled(bool enabled) {
107 if (enabled != fEnabled) {
108 this->toggleEnabled();
109 }
110 }
111
112 std::tuple<size_t, size_t> TextEditor::currentSelection() const {
113 // Selection can be inverted.
114 return std::make_tuple(std::min(std::get<0>(fSelection), std::get<1>(fSelection)),
115 std::max(std::get<0>(fSelection), std::get<1>(fSelection)));
116 }
117
118 size_t TextEditor::closestGlyph(const SkPoint& pt) const {
119 float min_distance = std::numeric_limits<float>::max();
120 size_t min_index = 0;
121
122 for (size_t i = 0; i < fGlyphData.size(); ++i) {
123 const auto dist = (fGlyphData[i].fDevBounds.center() - pt).length();
124 if (dist < min_distance) {
125 min_distance = dist;
126 min_index = i;
127 }
128 }
129
130 return min_index;
131 }
132
133 void TextEditor::drawCursor(SkCanvas* canvas, const TextInfo& tinfo) const {
134 constexpr double kCursorHz = 2;
135 const auto now_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
136 std::chrono::steady_clock::now() - fTimeBase).count();
137 const long cycle = static_cast<long>(static_cast<double>(now_ms) * 0.001 * kCursorHz);
138 if (cycle & 1) {
139 // blink
140 return;
141 }
142
143 auto txt_prop = fTextProp->get();
144
145 const auto glyph_index = [&]() -> size_t {
146 if (!fCursorIndex) {
147 return 0;
148 }
149
150 const auto prev_index = prev_utf8(txt_prop.fText, fCursorIndex);
151 for (size_t i = 0; i < tinfo.fGlyphs.size(); ++i) {
152 if (tinfo.fGlyphs[i].fCluster >= prev_index) {
153 return i;
154 }
155 }
156
157 return tinfo.fGlyphs.size() - 1;
158 }();
159
160 // Cursor index mapping:
161 // 0 -> before the first char
162 // 1 -> after the first char
163 // 2 -> after the second char
164 // ...
165 // The cursor is bottom-aligned to the baseline (y = 0), and horizontally centered to the right
166 // of the glyph advance.
167 const auto cscale = txt_prop.fTextSize * tinfo.fScale,
168 cxpos = (fCursorIndex ? tinfo.fGlyphs[glyph_index].fAdvance : 0)
169 - fCursorBounds.width() * cscale * 0.5f,
170 cypos = - fCursorBounds.height() * cscale;
171 const auto cpath = fCursorPath.makeTransform(SkMatrix::Translate(cxpos, cypos) *
172 SkMatrix::Scale(cscale, cscale));
173
174 // We stroke the cursor twice, with different colors, to ensure reasonable contrast
175 // regardless of background.
176 // The default inner stroke width is .5px for a font size of 10, and scales proportionally.
177 // The outer stroke width is slightly larger.
178 const auto inner_width = cscale * fCursorWeight * 0.05f,
179 outer_width = inner_width * 3 / 2;
180
181 SkPaint p;
182 p.setAntiAlias(true);
183 p.setStyle(SkPaint::kStroke_Style);
184 p.setStrokeCap(SkPaint::kRound_Cap);
185
186 SkAutoCanvasRestore acr(canvas, true);
187 canvas->concat(tinfo.fGlyphs[glyph_index].fMatrix);
188
189 p.setColor(SK_ColorWHITE);
190 p.setStrokeWidth(outer_width);
191 canvas->drawPath(cpath, p);
192 p.setColor(SK_ColorBLACK);
193 p.setStrokeWidth(inner_width);
194 canvas->drawPath(cpath, p);
195 }
196
197 void TextEditor::updateDeps(const SkString& txt) {
198 for (const auto& dep : fDependentProps) {
199 auto txt_prop = dep->get();
200 txt_prop.fText = txt;
201 dep->set(txt_prop);
202 }
203 }
204
205 void TextEditor::insertChar(SkUnichar c) {
206 auto txt = fTextProp->get();
207 const auto initial_size = txt.fText.size();
208
209 txt.fText.insertUnichar(fCursorIndex, c);
210 fCursorIndex += txt.fText.size() - initial_size;
211
212 fTextProp->set(txt);
213 this->updateDeps(txt.fText);
214 }
215
216 void TextEditor::deleteChars(size_t offset, size_t count) {
217 auto txt = fTextProp->get();
218
219 txt.fText.remove(offset, count);
220 fTextProp->set(txt);
221 this->updateDeps(txt.fText);
222
223 fCursorIndex = offset;
224 }
225
226 bool TextEditor::deleteSelection() {
227 const auto [glyph_sel_start, glyph_sel_end] = this->currentSelection();
228 if (glyph_sel_start == glyph_sel_end) {
229 return false;
230 }
231
232 const auto utf8_sel_start = fGlyphData[glyph_sel_start].fCluster,
233 utf8_sel_end = fGlyphData[glyph_sel_end ].fCluster;
234 SkASSERT(utf8_sel_start < utf8_sel_end);
235
236 this->deleteChars(utf8_sel_start, utf8_sel_end - utf8_sel_start);
237
238 fSelection = {0,0};
239
240 return true;
241 }
242
243 void TextEditor::onDecorate(SkCanvas* canvas, const TextInfo& tinfo) {
244 const auto [sel_start, sel_end] = this->currentSelection();
245
246 fGlyphData.clear();
247
248 for (size_t i = 0; i < tinfo.fGlyphs.size(); ++i) {
249 const auto& ginfo = tinfo.fGlyphs[i];
250
251 SkAutoCanvasRestore acr(canvas, true);
252 canvas->concat(ginfo.fMatrix);
253
254 // Stash some glyph info, for later use.
255 fGlyphData.push_back({
256 canvas->getLocalToDevice().asM33().mapRect(ginfo.fBounds),
257 ginfo.fCluster
258 });
259
260 if (i < sel_start || i >= sel_end) {
261 continue;
262 }
263
264 static constexpr SkColor4f kSelectionColor{0, 0, 1, 0.4f};
265 canvas->drawRect(ginfo.fBounds, SkPaint(kSelectionColor));
266 }
267
268 // Only draw the cursor when there's no active selection.
269 if (sel_start == sel_end) {
270 this->drawCursor(canvas, tinfo);
271 }
272 }
273
274 bool TextEditor::onMouseInput(SkScalar x, SkScalar y, skui::InputState state,
275 skui::ModifierKey) {
276 if (!fEnabled || fGlyphData.empty()) {
277 return false;
278 }
279
280 switch (state) {
281 case skui::InputState::kDown: {
282 fMouseDown = true;
283
284 const auto closest = this->closestGlyph({x, y});
285 fSelection = {closest, closest};
286 } break;
287 case skui::InputState::kUp:
288 fMouseDown = false;
289 break;
290 case skui::InputState::kMove:
291 if (fMouseDown) {
292 const auto closest = this->closestGlyph({x, y});
293 std::get<1>(fSelection) = closest < std::get<0>(fSelection)
294 ? closest
295 : closest + 1;
296 }
297 break;
298 default:
299 break;
300 }
301
302 return true;
303 }
304
305 bool TextEditor::onCharInput(SkUnichar c) {
306 if (!fEnabled || fGlyphData.empty()) {
307 return false;
308 }
309
310 const auto& txt_str = fTextProp->get().fText;
311
312 // Natural editor bindings are currently intercepted by Viewer, so we use these instead.
313 switch (c) {
314 case '|': // commit changes and exit editing mode
315 this->toggleEnabled();
316 break;
317 case ']': { // move right
318 if (fCursorIndex < txt_str.size()) {
319 fCursorIndex = next_utf8(txt_str, fCursorIndex);
320 }
321 } break;
322 case '[': // move left
323 if (fCursorIndex > 0) {
324 fCursorIndex = prev_utf8(txt_str, fCursorIndex);
325 }
326 break;
327 case '\\': { // delete
328 if (!this->deleteSelection() && fCursorIndex > 0) {
329 // Delete preceding char.
330 const auto del_index = prev_utf8(txt_str, fCursorIndex),
331 del_count = fCursorIndex - del_index;
332
333 this->deleteChars(del_index, del_count);
334 }
335 } break;
336 default:
337 // Delete any selection on insert.
338 this->deleteSelection();
339 this->insertChar(c);
340 break;
341 }
342
343 // Reset the cursor blink timer on input.
344 fTimeBase = std::chrono::steady_clock::now();
345
346 return true;
347 }
348
349 } // namespace skottie_utils