SkPlainTextEditor: from experimental to modules
Change-Id: I8896283ee3a57af926a43f6647e27059d52dd7a8
Reviewed-on: https://skia-review.googlesource.com/c/skia/+/237146
Reviewed-by: Hal Canary <halcanary@google.com>
Commit-Queue: Hal Canary <halcanary@google.com>
diff --git a/modules/skplaintexteditor/BUILD.gn b/modules/skplaintexteditor/BUILD.gn
new file mode 100644
index 0000000..1442477
--- /dev/null
+++ b/modules/skplaintexteditor/BUILD.gn
@@ -0,0 +1,69 @@
+# Copyright 2019 Google LLC.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+
+import("../../gn/skia.gni")
+
+if (skia_use_icu && skia_use_harfbuzz) {
+ source_set("editor_lib") {
+ include_dirs = [ "../.." ]
+ public = [
+ "include/editor.h",
+ "include/stringslice.h",
+ "include/stringview.h",
+ ]
+ sources = [
+ "src/editor.cpp",
+ "src/stringslice.cpp",
+ ]
+ public_deps = [
+ "../..:skia",
+ ]
+ deps = [
+ ":shape",
+ ]
+ }
+
+ source_set("shape") {
+ include_dirs = [ "../.." ]
+ public = [
+ "src/shape.h",
+ ]
+ sources = [
+ "src/shape.cpp",
+ ]
+ public_deps = [
+ "../..:skia",
+ ]
+ deps = [
+ ":word_boundaries",
+ "../../modules/skshaper",
+ ]
+ }
+
+ source_set("word_boundaries") {
+ include_dirs = [ "../.." ]
+ public = [
+ "src/word_boundaries.h",
+ ]
+ sources = [
+ "src/word_boundaries.cpp",
+ ]
+ deps = [
+ "../../third_party/icu",
+ ]
+ }
+
+ source_set("editor_app") {
+ testonly = true
+ sources = [
+ "app/editor_application.cpp",
+ ]
+ public_deps = [
+ "../..:sk_app",
+ ]
+ deps = [
+ ":editor_lib",
+ ]
+ }
+}
diff --git a/modules/skplaintexteditor/README.md b/modules/skplaintexteditor/README.md
new file mode 100644
index 0000000..f07d958
--- /dev/null
+++ b/modules/skplaintexteditor/README.md
@@ -0,0 +1,42 @@
+# Editor #
+
+This is an experimental Editor layer that abstracts out SkShaper text layeout
+for easy embedding into an application. The Editor layer is agnostic about the
+operating system.
+
+ +--------------------------------+
+ |Application |
+ +-+----+-------------------------+
+ | |
+ | |
+ | +-v-------------------------+
+ | |Editor |
+ | +-+----+--------------------+
+ | | |
+ | | |
+ | | +-v--------------------+
+ | | |SkShaper |
+ | | +-+--------+-----------+
+ | | | |
+ | | | |
+ +-v----v----v--+ +-v-----------+
+ |Skia | |HarfBuzz, ICU|
+ +--------------+ +-------------+
+
+The Application layer must interact with the:
+
+ * Windowing system
+ * File system
+ * Clipboard
+ * Keyboard/mouse input.
+
+Try it out:
+
+ tools/git-sync-deps
+ bin/gn gen out/default
+ ninja -C out/default editor
+
+ out/default/editor resources/text/english.txt
+
+ cat resources/text/*.txt > example.txt
+ out/default/editor example.txt
diff --git a/modules/skplaintexteditor/app/editor_application.cpp b/modules/skplaintexteditor/app/editor_application.cpp
new file mode 100644
index 0000000..3a49d55
--- /dev/null
+++ b/modules/skplaintexteditor/app/editor_application.cpp
@@ -0,0 +1,409 @@
+// Copyright 2019 Google LLC.
+// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
+
+// Proof of principle of a text editor written with Skia & SkShaper.
+// https://bugs.skia.org/9020
+
+#include "include/core/SkCanvas.h"
+#include "include/core/SkSurface.h"
+#include "include/core/SkTime.h"
+
+#include "tools/ModifierKey.h"
+#include "tools/sk_app/Application.h"
+#include "tools/sk_app/Window.h"
+
+#include "modules/skplaintexteditor/include/editor.h"
+
+#include "third_party/icu/SkLoadICU.h"
+
+#include <fstream>
+#include <memory>
+
+using SkPlainTextEditor::Editor;
+using SkPlainTextEditor::StringView;
+
+#ifdef SK_EDITOR_DEBUG_OUT
+static const char* key_name(sk_app::Window::Key k) {
+ switch (k) {
+ #define M(X) case sk_app::Window::Key::k ## X: return #X
+ M(NONE); M(LeftSoftKey); M(RightSoftKey); M(Home); M(Back); M(Send); M(End); M(0); M(1);
+ M(2); M(3); M(4); M(5); M(6); M(7); M(8); M(9); M(Star); M(Hash); M(Up); M(Down); M(Left);
+ M(Right); M(Tab); M(PageUp); M(PageDown); M(Delete); M(Escape); M(Shift); M(Ctrl);
+ M(Option); M(A); M(C); M(V); M(X); M(Y); M(Z); M(OK); M(VolUp); M(VolDown); M(Power);
+ M(Camera);
+ #undef M
+ default: return "?";
+ }
+}
+
+static SkString modifiers_desc(ModifierKey m) {
+ SkString s;
+ #define M(X) if (m & ModifierKey::k ## X ##) { s.append(" {" #X "}"); }
+ M(Shift) M(Control) M(Option) M(Command) M(FirstPress)
+ #undef M
+ return s;
+}
+
+static void debug_on_char(SkUnichar c, ModifierKey modifiers) {
+ SkString m = modifiers_desc(modifiers);
+ if ((unsigned)c < 0x100) {
+ SkDebugf("char: %c (0x%02X)%s\n", (char)(c & 0xFF), (unsigned)c, m.c_str());
+ } else {
+ SkDebugf("char: 0x%08X%s\n", (unsigned)c, m.c_str());
+ }
+}
+
+static void debug_on_key(sk_app::Window::Key key, InputState, ModifierKey modi) {
+ SkDebugf("key: %s%s\n", key_name(key), modifiers_desc(modi).c_str());
+}
+#endif // SK_EDITOR_DEBUG_OUT
+
+static Editor::Movement convert(sk_app::Window::Key key) {
+ switch (key) {
+ case sk_app::Window::Key::kLeft: return Editor::Movement::kLeft;
+ case sk_app::Window::Key::kRight: return Editor::Movement::kRight;
+ case sk_app::Window::Key::kUp: return Editor::Movement::kUp;
+ case sk_app::Window::Key::kDown: return Editor::Movement::kDown;
+ case sk_app::Window::Key::kHome: return Editor::Movement::kHome;
+ case sk_app::Window::Key::kEnd: return Editor::Movement::kEnd;
+ default: return Editor::Movement::kNowhere;
+ }
+}
+namespace {
+
+struct Timer {
+ double fTime;
+ const char* fDesc;
+ Timer(const char* desc = "") : fTime(SkTime::GetNSecs()), fDesc(desc) {}
+ ~Timer() { SkDebugf("%s: %5d μs\n", fDesc, (int)((SkTime::GetNSecs() - fTime) * 1e-3)); }
+};
+
+struct EditorLayer : public sk_app::Window::Layer {
+ SkString fPath;
+ sk_app::Window* fParent = nullptr;
+ // TODO(halcanary): implement a cross-platform clipboard interface.
+ std::vector<char> fClipboard;
+ Editor fEditor;
+ Editor::TextPosition fTextPos{0, 0};
+ Editor::TextPosition fMarkPos;
+ int fPos = 0; // window pixel position in file
+ int fWidth = 0; // window width
+ int fHeight = 0; // window height
+ int fMargin = 10;
+ bool fShiftDown = false;
+ bool fBlink = false;
+ bool fMouseDown = false;
+
+ void loadFile(const char* path) {
+ if (sk_sp<SkData> data = SkData::MakeFromFileName(path)) {
+ fPath = path;
+ fEditor.insert(Editor::TextPosition{0, 0},
+ (const char*)data->data(), data->size());
+ } else {
+ fPath = "output.txt";
+ }
+ }
+
+ void onPaint(SkSurface* surface) override {
+ SkCanvas* canvas = surface->getCanvas();
+ SkAutoCanvasRestore acr(canvas, true);
+ canvas->clipRect({0, 0, (float)fWidth, (float)fHeight});
+ canvas->translate(fMargin, (float)(fMargin - fPos));
+ Editor::PaintOpts options;
+ options.fCursor = fTextPos;
+ options.fCursorColor = {1, 0, 0, fBlink ? 0.0f : 1.0f};
+ options.fBackgroundColor = SkColor4f{0.8f, 0.8f, 0.8f, 1};
+ options.fCursorColor = {1, 0, 0, fBlink ? 0.0f : 1.0f};
+ if (fMarkPos != Editor::TextPosition()) {
+ options.fSelectionBegin = fMarkPos;
+ options.fSelectionEnd = fTextPos;
+ }
+ #ifdef SK_EDITOR_DEBUG_OUT
+ {
+ Timer timer("shaping");
+ fEditor.paint(nullptr, options);
+ }
+ Timer timer("painting");
+ #endif // SK_EDITOR_DEBUG_OUT
+ fEditor.paint(canvas, options);
+ }
+
+ void onResize(int width, int height) override {
+ if (SkISize{fWidth, fHeight} != SkISize{width, height}) {
+ fHeight = height;
+ if (width != fWidth) {
+ fWidth = width;
+ fEditor.setWidth(fWidth - 2 * fMargin);
+ }
+ this->inval();
+ }
+ }
+
+ void onAttach(sk_app::Window* w) override { fParent = w; }
+
+ bool scroll(int delta) {
+ int maxPos = std::max(0, fEditor.getHeight() + 2 * fMargin - fHeight / 2);
+ int newpos = std::max(0, std::min(fPos + delta, maxPos));
+ if (newpos != fPos) {
+ fPos = newpos;
+ this->inval();
+ }
+ return true;
+ }
+
+ void inval() { if (fParent) { fParent->inval(); } }
+
+ bool onMouseWheel(float delta, ModifierKey) override {
+ this->scroll(-(int)(delta * fEditor.font().getSpacing()));
+ return true;
+ }
+
+ bool onMouse(int x, int y, InputState state, ModifierKey modifiers) override {
+ bool mouseDown = InputState::kDown == state;
+ if (mouseDown) {
+ fMouseDown = true;
+ } else if (InputState::kUp == state) {
+ fMouseDown = false;
+ }
+ bool shiftOrDrag = skstd::Any(modifiers & ModifierKey::kShift) || !mouseDown;
+ if (fMouseDown) {
+ return this->move(fEditor.getPosition({x - fMargin, y + fPos - fMargin}), shiftOrDrag);
+ }
+ return false;
+ }
+
+ bool onChar(SkUnichar c, ModifierKey modi) override {
+ using skstd::Any;
+ modi &= ~ModifierKey::kFirstPress;
+ if (!Any(modi & (ModifierKey::kControl |
+ ModifierKey::kOption |
+ ModifierKey::kCommand))) {
+ if (((unsigned)c < 0x7F && (unsigned)c >= 0x20) || c == '\n') {
+ char ch = (char)c;
+ fEditor.insert(fTextPos, &ch, 1);
+ #ifdef SK_EDITOR_DEBUG_OUT
+ SkDebugf("insert: %X'%c'\n", (unsigned)c, ch);
+ #endif // SK_EDITOR_DEBUG_OUT
+ return this->moveCursor(Editor::Movement::kRight);
+ }
+ }
+ static constexpr ModifierKey kCommandOrControl = ModifierKey::kCommand |
+ ModifierKey::kControl;
+ if (Any(modi & kCommandOrControl) && !Any(modi & ~kCommandOrControl)) {
+ switch (c) {
+ case 'p':
+ for (StringView str : fEditor.text()) {
+ SkDebugf(">> '%.*s'\n", str.size, str.data);
+ }
+ return true;
+ case 's':
+ {
+ std::ofstream out(fPath.c_str());
+ size_t count = fEditor.lineCount();
+ for (size_t i = 0; i < count; ++i) {
+ if (i != 0) {
+ out << '\n';
+ }
+ StringView str = fEditor.line(i);
+ out.write(str.data, str.size);
+ }
+ }
+ return true;
+ case 'c':
+ if (fMarkPos != Editor::TextPosition()) {
+ fClipboard.resize(fEditor.copy(fMarkPos, fTextPos, nullptr));
+ fEditor.copy(fMarkPos, fTextPos, fClipboard.data());
+ return true;
+ }
+ return false;
+ case 'x':
+ if (fMarkPos != Editor::TextPosition()) {
+ fClipboard.resize(fEditor.copy(fMarkPos, fTextPos, nullptr));
+ fEditor.copy(fMarkPos, fTextPos, fClipboard.data());
+ (void)this->move(fEditor.remove(fMarkPos, fTextPos), false);
+ this->inval();
+ return true;
+ }
+ return false;
+ case 'v':
+ if (fClipboard.size()) {
+ fEditor.insert(fTextPos, fClipboard.data(), fClipboard.size());
+ this->inval();
+ return true;
+ }
+ return false;
+ case '=':
+ case '+':
+ {
+ float s = fEditor.font().getSize() + 1;
+ fEditor.setFont(fEditor.font().makeWithSize(s));
+ }
+ return true;
+ case '-':
+ case '_':
+ {
+ float s = fEditor.font().getSize() - 1;
+ if (s > 0) {
+ fEditor.setFont(fEditor.font().makeWithSize(s));
+ }
+ }
+ }
+ }
+ #ifdef SK_EDITOR_DEBUG_OUT
+ debug_on_char(c, modifiers);
+ #endif // SK_EDITOR_DEBUG_OUT
+ return false;
+ }
+
+ bool moveCursor(Editor::Movement m, bool shift = false) {
+ return this->move(fEditor.move(m, fTextPos), shift);
+ }
+
+ bool move(Editor::TextPosition pos, bool shift) {
+ if (pos == fTextPos || pos == Editor::TextPosition()) {
+ if (!shift) {
+ fMarkPos = Editor::TextPosition();
+ }
+ return false;
+ }
+ if (shift != fShiftDown) {
+ fMarkPos = shift ? fTextPos : Editor::TextPosition();
+ fShiftDown = shift;
+ }
+ fTextPos = pos;
+
+ // scroll if needed.
+ SkIRect cursor = fEditor.getLocation(fTextPos).roundOut();
+ if (fPos < cursor.bottom() - fHeight + 2 * fMargin) {
+ fPos = cursor.bottom() - fHeight + 2 * fMargin;
+ } else if (cursor.top() < fPos) {
+ fPos = cursor.top();
+ }
+ this->inval();
+ return true;
+ }
+
+ bool onKey(sk_app::Window::Key key,
+ InputState state,
+ ModifierKey modifiers) override {
+ if (state != InputState::kDown) {
+ return false; // ignore keyup
+ }
+ // ignore other modifiers.
+ using skstd::Any;
+ ModifierKey ctrlAltCmd = modifiers & (ModifierKey::kControl |
+ ModifierKey::kOption |
+ ModifierKey::kCommand);
+ bool shift = Any(modifiers & (ModifierKey::kShift));
+ if (!Any(ctrlAltCmd)) {
+ // no modifiers
+ switch (key) {
+ case sk_app::Window::Key::kPageDown:
+ return this->scroll(fHeight * 4 / 5);
+ case sk_app::Window::Key::kPageUp:
+ return this->scroll(-fHeight * 4 / 5);
+ case sk_app::Window::Key::kLeft:
+ case sk_app::Window::Key::kRight:
+ case sk_app::Window::Key::kUp:
+ case sk_app::Window::Key::kDown:
+ case sk_app::Window::Key::kHome:
+ case sk_app::Window::Key::kEnd:
+ return this->moveCursor(convert(key), shift);
+ case sk_app::Window::Key::kDelete:
+ if (fMarkPos != Editor::TextPosition()) {
+ (void)this->move(fEditor.remove(fMarkPos, fTextPos), false);
+ } else {
+ auto pos = fEditor.move(Editor::Movement::kRight, fTextPos);
+ (void)this->move(fEditor.remove(fTextPos, pos), false);
+ }
+ this->inval();
+ return true;
+ case sk_app::Window::Key::kBack:
+ if (fMarkPos != Editor::TextPosition()) {
+ (void)this->move(fEditor.remove(fMarkPos, fTextPos), false);
+ } else {
+ auto pos = fEditor.move(Editor::Movement::kLeft, fTextPos);
+ (void)this->move(fEditor.remove(fTextPos, pos), false);
+ }
+ this->inval();
+ return true;
+ case sk_app::Window::Key::kOK:
+ return this->onChar('\n', modifiers);
+ default:
+ break;
+ }
+ } else if (skstd::Any(ctrlAltCmd & (ModifierKey::kControl | ModifierKey::kCommand))) {
+ switch (key) {
+ case sk_app::Window::Key::kLeft:
+ return this->moveCursor(Editor::Movement::kWordLeft, shift);
+ case sk_app::Window::Key::kRight:
+ return this->moveCursor(Editor::Movement::kWordRight, shift);
+ default:
+ break;
+ }
+ }
+ #ifdef SK_EDITOR_DEBUG_OUT
+ debug_on_key(key, state, modifiers);
+ #endif // SK_EDITOR_DEBUG_OUT
+ return false;
+ }
+};
+
+static constexpr float kFontSize = 18;
+// static constexpr char kTypefaceName[] = "monospace";
+static constexpr char kTypefaceName[] = "sans-serif";
+static constexpr SkFontStyle::Weight kFontWeight = SkFontStyle::kNormal_Weight;
+static constexpr SkFontStyle::Width kFontWidth = SkFontStyle::kNormal_Width;
+static constexpr SkFontStyle::Slant kFontSlant = SkFontStyle::kUpright_Slant;
+
+//static constexpr sk_app::Window::BackendType kBackendType = sk_app::Window::kRaster_BackendType;
+static constexpr sk_app::Window::BackendType kBackendType = sk_app::Window::kNativeGL_BackendType;
+
+struct EditorApplication : public sk_app::Application {
+ std::unique_ptr<sk_app::Window> fWindow;
+ EditorLayer fLayer;
+ double fNextTime = -DBL_MAX;
+
+ EditorApplication(std::unique_ptr<sk_app::Window> win) : fWindow(std::move(win)) {}
+
+ bool init(const char* path) {
+ fWindow->attach(kBackendType);
+
+ fLayer.fEditor.setFont(SkFont(SkTypeface::MakeFromName(kTypefaceName,
+ SkFontStyle(kFontWeight, kFontWidth, kFontSlant)), kFontSize));
+ fLayer.loadFile(path);
+
+ fWindow->pushLayer(&fLayer);
+ fWindow->setTitle(SkStringPrintf("Editor: \"%s\"", fLayer.fPath.c_str()).c_str());
+ fLayer.onResize(fWindow->width(), fWindow->height());
+ fLayer.fEditor.paint(nullptr, Editor::PaintOpts());
+
+ fWindow->show();
+ return true;
+ }
+ ~EditorApplication() override { fWindow->detach(); }
+
+ void onIdle() override {
+ double now = SkTime::GetNSecs();
+ if (now >= fNextTime) {
+ constexpr double kHalfPeriodNanoSeconds = 0.5 * 1e9;
+ fNextTime = now + kHalfPeriodNanoSeconds;
+ fLayer.fBlink = !fLayer.fBlink;
+ fWindow->inval();
+ }
+ }
+};
+} // namespace
+
+sk_app::Application* sk_app::Application::Create(int argc, char** argv, void* dat) {
+ if (!SkLoadICU()) {
+ SK_ABORT("SkLoadICU failed.");
+ }
+ std::unique_ptr<sk_app::Window> win(sk_app::Window::CreateNativeWindow(dat));
+ if (!win) {
+ SK_ABORT("CreateNativeWindow failed.");
+ }
+ std::unique_ptr<EditorApplication> app(new EditorApplication(std::move(win)));
+ (void)app->init(argc > 1 ? argv[1] : nullptr);
+ return app.release();
+}
diff --git a/modules/skplaintexteditor/include/editor.h b/modules/skplaintexteditor/include/editor.h
new file mode 100644
index 0000000..b87d536
--- /dev/null
+++ b/modules/skplaintexteditor/include/editor.h
@@ -0,0 +1,142 @@
+// Copyright 2019 Google LLC.
+// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
+#ifndef editor_DEFINED
+#define editor_DEFINED
+
+#include "modules/skplaintexteditor/include/stringslice.h"
+#include "modules/skplaintexteditor/include/stringview.h"
+
+#include "include/core/SkColor.h"
+#include "include/core/SkFont.h"
+#include "include/core/SkString.h"
+#include "include/core/SkTextBlob.h"
+
+#include <climits>
+#include <cstdint>
+#include <utility>
+#include <vector>
+
+class SkCanvas;
+class SkShaper;
+
+namespace SkPlainTextEditor {
+
+class Editor {
+ struct TextLine;
+public:
+ // total height in canvas display units.
+ int getHeight() const { return fHeight; }
+
+ // set display width in canvas display units
+ void setWidth(int w); // may force re-shape
+
+ // get/set current font (used for shaping and displaying text)
+ const SkFont& font() const { return fFont; }
+ void setFont(SkFont font);
+
+ struct Text {
+ const std::vector<TextLine>& fLines;
+ struct Iterator {
+ std::vector<TextLine>::const_iterator fPtr;
+ StringView operator*() { return fPtr->fText.view(); }
+ void operator++() { ++fPtr; }
+ bool operator!=(const Iterator& other) const { return fPtr != other.fPtr; }
+ };
+ Iterator begin() const { return Iterator{fLines.begin()}; }
+ Iterator end() const { return Iterator{fLines.end()}; }
+ };
+ // Loop over all the lines of text. The lines are not '\0'- or '\n'-terminated.
+ // For example, to dump the entire file to standard output:
+ // for (SkPlainTextEditor::StringView str : editor.text()) {
+ // std::cout.write(str.data, str.size) << '\n';
+ // }
+ Text text() const { return Text{fLines}; }
+
+ // get size of line in canvas display units.
+ int lineHeight(size_t index) const { return fLines[index].fHeight; }
+
+ struct TextPosition {
+ size_t fTextByteIndex = SIZE_MAX; // index into UTF-8 representation of line.
+ size_t fParagraphIndex = SIZE_MAX; // logical line, based on hard newline characters.
+ };
+ enum class Movement {
+ kNowhere,
+ kLeft,
+ kUp,
+ kRight,
+ kDown,
+ kHome,
+ kEnd,
+ kWordLeft,
+ kWordRight,
+ };
+ TextPosition move(Editor::Movement move, Editor::TextPosition pos) const;
+ TextPosition getPosition(SkIPoint);
+ SkRect getLocation(TextPosition);
+ // insert into current text.
+ TextPosition insert(TextPosition, const char* utf8Text, size_t byteLen);
+ // remove text between two positions
+ TextPosition remove(TextPosition, TextPosition);
+
+ // If dst is nullptr, returns size of given selection.
+ // Otherwise, fill dst with a copy of the selection, and return the amount copied.
+ size_t copy(TextPosition pos1, TextPosition pos2, char* dst = nullptr) const;
+ size_t lineCount() const { return fLines.size(); }
+ StringView line(size_t i) const {
+ return i < fLines.size() ? fLines[i].fText.view() : StringView{nullptr, 0};
+ }
+
+ struct PaintOpts {
+ SkColor4f fBackgroundColor = {1, 1, 1, 1};
+ SkColor4f fForegroundColor = {0, 0, 0, 1};
+ // TODO: maybe have multiple selections and cursors, each with separate colors.
+ SkColor4f fSelectionColor = {0.729f, 0.827f, 0.988f, 1};
+ SkColor4f fCursorColor = {1, 0, 0, 1};
+ TextPosition fSelectionBegin;
+ TextPosition fSelectionEnd;
+ TextPosition fCursor;
+ };
+ void paint(SkCanvas* canvas, PaintOpts);
+
+private:
+ // TODO: rename this to TextParagraph. fLines to fParas.
+ struct TextLine {
+ StringSlice fText;
+ sk_sp<const SkTextBlob> fBlob;
+ std::vector<SkRect> fCursorPos;
+ std::vector<size_t> fLineEndOffsets;
+ std::vector<bool> fWordBoundaries;
+ SkIPoint fOrigin = {0, 0};
+ int fHeight = 0;
+ bool fShaped = false;
+
+ TextLine(StringSlice t) : fText(std::move(t)) {}
+ TextLine() {}
+ };
+ std::vector<TextLine> fLines;
+ int fWidth = 0;
+ int fHeight = 0;
+ SkFont fFont;
+ bool fNeedsReshape = false;
+ const char* fLocale = "en"; // TODO: make this setable
+
+ void markDirty(TextLine*);
+ void reshapeAll();
+};
+} // namespace SkPlainTextEditor
+
+static inline bool operator==(const SkPlainTextEditor::Editor::TextPosition& u,
+ const SkPlainTextEditor::Editor::TextPosition& v) {
+ return u.fParagraphIndex == v.fParagraphIndex && u.fTextByteIndex == v.fTextByteIndex;
+}
+static inline bool operator!=(const SkPlainTextEditor::Editor::TextPosition& u,
+ const SkPlainTextEditor::Editor::TextPosition& v) { return !(u == v); }
+
+static inline bool operator<(const SkPlainTextEditor::Editor::TextPosition& u,
+ const SkPlainTextEditor::Editor::TextPosition& v) {
+ return u.fParagraphIndex < v.fParagraphIndex ||
+ (u.fParagraphIndex == v.fParagraphIndex && u.fTextByteIndex < v.fTextByteIndex);
+}
+
+
+#endif // editor_DEFINED
diff --git a/modules/skplaintexteditor/include/stringslice.h b/modules/skplaintexteditor/include/stringslice.h
new file mode 100644
index 0000000..00619af
--- /dev/null
+++ b/modules/skplaintexteditor/include/stringslice.h
@@ -0,0 +1,46 @@
+// Copyright 2019 Google LLC.
+// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
+#ifndef stringslice_DEFINED
+#define stringslice_DEFINED
+
+#include "modules/skplaintexteditor/include/stringview.h"
+
+#include <memory>
+#include <cstddef>
+
+namespace SkPlainTextEditor {
+// A lightweight modifiable string class.
+class StringSlice {
+public:
+ StringSlice() = default;
+ StringSlice(const char* s, std::size_t l) { this->insert(0, s, l); }
+ StringSlice(StringSlice&&);
+ StringSlice(const StringSlice& that) : StringSlice(that.begin(), that.size()) {}
+ ~StringSlice() = default;
+ StringSlice& operator=(StringSlice&&);
+ StringSlice& operator=(const StringSlice&);
+
+ // access:
+ // Does not have a c_str method; is *not* NUL-terminated.
+ const char* begin() const { return fPtr.get(); }
+ const char* end() const { return fPtr ? fPtr.get() + fLength : nullptr; }
+ std::size_t size() const { return fLength; }
+ SkPlainTextEditor::StringView view() const { return {fPtr.get(), fLength}; }
+
+ // mutation:
+ void insert(std::size_t offset, const char* text, std::size_t length);
+ void remove(std::size_t offset, std::size_t length);
+
+ // modify capacity only:
+ void reserve(std::size_t size) { if (size > fCapacity) { this->realloc(size); } }
+ void shrink() { this->realloc(fLength); }
+
+private:
+ struct FreeWrapper { void operator()(void*); };
+ std::unique_ptr<char[], FreeWrapper> fPtr;
+ std::size_t fLength = 0;
+ std::size_t fCapacity = 0;
+ void realloc(std::size_t);
+};
+} // namespace SkPlainTextEditor;
+#endif // stringslice_DEFINED
diff --git a/modules/skplaintexteditor/include/stringview.h b/modules/skplaintexteditor/include/stringview.h
new file mode 100644
index 0000000..a9effa5
--- /dev/null
+++ b/modules/skplaintexteditor/include/stringview.h
@@ -0,0 +1,19 @@
+// Copyright 2019 Google LLC.
+// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
+#ifndef stringview_DEFINED
+#define stringview_DEFINED
+
+#include <cstddef>
+
+namespace SkPlainTextEditor {
+
+template <typename T>
+struct Span {
+ T* data;
+ std::size_t size;
+};
+
+using StringView = Span<const char>;
+
+}
+#endif // stringview_DEFINED
diff --git a/modules/skplaintexteditor/src/editor.cpp b/modules/skplaintexteditor/src/editor.cpp
new file mode 100644
index 0000000..4b66d80
--- /dev/null
+++ b/modules/skplaintexteditor/src/editor.cpp
@@ -0,0 +1,512 @@
+// Copyright 2019 Google LLC.
+// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
+
+#include "modules/skplaintexteditor/include/editor.h"
+
+#include "include/core/SkCanvas.h"
+#include "include/core/SkExecutor.h"
+#include "include/core/SkPath.h"
+#include "src/utils/SkUTF.h"
+
+#include "modules/skplaintexteditor/src/shape.h"
+
+#include <algorithm>
+
+using namespace SkPlainTextEditor;
+
+static inline SkRect offset(SkRect r, SkIPoint p) {
+ return r.makeOffset((float)p.x(), (float)p.y());
+}
+
+static constexpr SkRect kUnsetRect{-FLT_MAX, -FLT_MAX, -FLT_MAX, -FLT_MAX};
+
+static bool valid_utf8(const char* ptr, size_t size) { return SkUTF::CountUTF8(ptr, size) >= 0; }
+
+// Kind of like Python's readlines(), but without any allocation.
+// Calls f() on each line.
+// F is [](const char*, size_t) -> void
+template <typename F>
+static void readlines(const void* data, size_t size, F f) {
+ const char* start = (const char*)data;
+ const char* end = start + size;
+ const char* ptr = start;
+ while (ptr < end) {
+ while (*ptr++ != '\n' && ptr < end) {}
+ size_t len = ptr - start;
+ SkASSERT(len > 0);
+ f(start, len);
+ start = ptr;
+ }
+}
+
+static const StringSlice remove_newline(const char* str, size_t len) {
+ return SkASSERT((str != nullptr) || (len == 0)),
+ StringSlice(str, (len > 0 && str[len - 1] == '\n') ? len - 1 : len);
+}
+
+void Editor::markDirty(TextLine* line) {
+ line->fBlob = nullptr;
+ line->fShaped = false;
+ line->fWordBoundaries = std::vector<bool>();
+}
+
+void Editor::setFont(SkFont font) {
+ if (font != fFont) {
+ fFont = std::move(font);
+ fNeedsReshape = true;
+ for (auto& l : fLines) { this->markDirty(&l); }
+ }
+}
+
+void Editor::setWidth(int w) {
+ if (fWidth != w) {
+ fWidth = w;
+ fNeedsReshape = true;
+ for (auto& l : fLines) { this->markDirty(&l); }
+ }
+}
+static SkPoint to_point(SkIPoint p) { return {(float)p.x(), (float)p.y()}; }
+
+Editor::TextPosition Editor::getPosition(SkIPoint xy) {
+ Editor::TextPosition approximatePosition;
+ this->reshapeAll();
+ for (size_t j = 0; j < fLines.size(); ++j) {
+ const TextLine& line = fLines[j];
+ SkIRect lineRect = {0,
+ line.fOrigin.y(),
+ fWidth,
+ j + 1 < fLines.size() ? fLines[j + 1].fOrigin.y() : INT_MAX};
+ if (const SkTextBlob* b = line.fBlob.get()) {
+ SkIRect r = b->bounds().roundOut();
+ r.offset(line.fOrigin);
+ lineRect.join(r);
+ }
+ if (!lineRect.contains(xy.x(), xy.y())) {
+ continue;
+ }
+ SkPoint pt = to_point(xy - line.fOrigin);
+ const std::vector<SkRect>& pos = line.fCursorPos;
+ for (size_t i = 0; i < pos.size(); ++i) {
+ if (pos[i] != kUnsetRect && pos[i].contains(pt.x(), pt.y())) {
+ return Editor::TextPosition{i, j};
+ }
+ }
+ approximatePosition = {xy.x() <= line.fOrigin.x() ? 0 : line.fText.size(), j};
+ }
+ return approximatePosition;
+}
+
+static inline bool is_utf8_continuation(char v) {
+ return ((unsigned char)v & 0b11000000) ==
+ 0b10000000;
+}
+
+static const char* next_utf8(const char* p, const char* end) {
+ if (p < end) {
+ do {
+ ++p;
+ } while (p < end && is_utf8_continuation(*p));
+ }
+ return p;
+}
+
+static const char* align_utf8(const char* p, const char* begin) {
+ while (p > begin && is_utf8_continuation(*p)) {
+ --p;
+ }
+ return p;
+}
+
+static const char* prev_utf8(const char* p, const char* begin) {
+ return p > begin ? align_utf8(p - 1, begin) : begin;
+}
+
+SkRect Editor::getLocation(Editor::TextPosition cursor) {
+ this->reshapeAll();
+ cursor = this->move(Editor::Movement::kNowhere, cursor);
+ if (fLines.size() > 0) {
+ const TextLine& cLine = fLines[cursor.fParagraphIndex];
+ SkRect pos = {0, 0, 0, 0};
+ if (cursor.fTextByteIndex < cLine.fCursorPos.size()) {
+ pos = cLine.fCursorPos[cursor.fTextByteIndex];
+ }
+ pos.fRight = pos.fLeft + 1;
+ pos.fLeft -= 1;
+ return offset(pos, cLine.fOrigin);
+ }
+ return SkRect{0, 0, 0, 0};
+}
+
+static size_t count_char(const StringSlice& string, char value) {
+ size_t count = 0;
+ for (char c : string) { if (c == value) { ++count; } }
+ return count;
+}
+
+Editor::TextPosition Editor::insert(TextPosition pos, const char* utf8Text, size_t byteLen) {
+ if (!valid_utf8(utf8Text, byteLen) || 0 == byteLen) {
+ return pos;
+ }
+ pos = this->move(Editor::Movement::kNowhere, pos);
+ fNeedsReshape = true;
+ if (pos.fParagraphIndex < fLines.size()) {
+ fLines[pos.fParagraphIndex].fText.insert(pos.fTextByteIndex, utf8Text, byteLen);
+ this->markDirty(&fLines[pos.fParagraphIndex]);
+ } else {
+ SkASSERT(pos.fParagraphIndex == fLines.size());
+ SkASSERT(pos.fTextByteIndex == 0);
+ fLines.push_back(Editor::TextLine(StringSlice(utf8Text, byteLen)));
+ }
+ pos = Editor::TextPosition{pos.fTextByteIndex + byteLen, pos.fParagraphIndex};
+ size_t newlinecount = count_char(fLines[pos.fParagraphIndex].fText, '\n');
+ if (newlinecount > 0) {
+ StringSlice src = std::move(fLines[pos.fParagraphIndex].fText);
+ std::vector<TextLine>::const_iterator next = fLines.begin() + pos.fParagraphIndex + 1;
+ fLines.insert(next, newlinecount, TextLine());
+ TextLine* line = &fLines[pos.fParagraphIndex];
+ readlines(src.begin(), src.size(), [&line](const char* str, size_t l) {
+ (line++)->fText = remove_newline(str, l);
+ });
+ }
+ return pos;
+}
+
+Editor::TextPosition Editor::remove(TextPosition pos1, TextPosition pos2) {
+ pos1 = this->move(Editor::Movement::kNowhere, pos1);
+ pos2 = this->move(Editor::Movement::kNowhere, pos2);
+ auto cmp = [](const Editor::TextPosition& u, const Editor::TextPosition& v) { return u < v; };
+ Editor::TextPosition start = std::min(pos1, pos2, cmp);
+ Editor::TextPosition end = std::max(pos1, pos2, cmp);
+ if (start == end || start.fParagraphIndex == fLines.size()) {
+ return start;
+ }
+ fNeedsReshape = true;
+ if (start.fParagraphIndex == end.fParagraphIndex) {
+ SkASSERT(end.fTextByteIndex > start.fTextByteIndex);
+ fLines[start.fParagraphIndex].fText.remove(
+ start.fTextByteIndex, end.fTextByteIndex - start.fTextByteIndex);
+ this->markDirty(&fLines[start.fParagraphIndex]);
+ } else {
+ SkASSERT(end.fParagraphIndex < fLines.size());
+ auto& line = fLines[start.fParagraphIndex];
+ line.fText.remove(start.fTextByteIndex,
+ line.fText.size() - start.fTextByteIndex);
+ line.fText.insert(start.fTextByteIndex,
+ fLines[end.fParagraphIndex].fText.begin() + end.fTextByteIndex,
+ fLines[end.fParagraphIndex].fText.size() - end.fTextByteIndex);
+ this->markDirty(&line);
+ fLines.erase(fLines.begin() + start.fParagraphIndex + 1,
+ fLines.begin() + end.fParagraphIndex + 1);
+ }
+ return start;
+}
+
+static void append(char** dst, size_t* count, const char* src, size_t n) {
+ if (*dst) {
+ ::memcpy(*dst, src, n);
+ *dst += n;
+ }
+ *count += n;
+}
+
+size_t Editor::copy(TextPosition pos1, TextPosition pos2, char* dst) const {
+ size_t size = 0;
+ pos1 = this->move(Editor::Movement::kNowhere, pos1);
+ pos2 = this->move(Editor::Movement::kNowhere, pos2);
+ auto cmp = [](const Editor::TextPosition& u, const Editor::TextPosition& v) { return u < v; };
+ Editor::TextPosition start = std::min(pos1, pos2, cmp);
+ Editor::TextPosition end = std::max(pos1, pos2, cmp);
+ if (start == end || start.fParagraphIndex == fLines.size()) {
+ return size;
+ }
+ if (start.fParagraphIndex == end.fParagraphIndex) {
+ SkASSERT(end.fTextByteIndex > start.fTextByteIndex);
+ auto& str = fLines[start.fParagraphIndex].fText;
+ append(&dst, &size, str.begin() + start.fTextByteIndex,
+ end.fTextByteIndex - start.fTextByteIndex);
+ return size;
+ }
+ SkASSERT(end.fParagraphIndex < fLines.size());
+ const std::vector<TextLine>::const_iterator firstP = fLines.begin() + start.fParagraphIndex;
+ const std::vector<TextLine>::const_iterator lastP = fLines.begin() + end.fParagraphIndex;
+ const auto& first = firstP->fText;
+ const auto& last = lastP->fText;
+
+ append(&dst, &size, first.begin() + start.fTextByteIndex, first.size() - start.fTextByteIndex);
+ for (auto line = firstP + 1; line < lastP; ++line) {
+ append(&dst, &size, "\n", 1);
+ append(&dst, &size, line->fText.begin(), line->fText.size());
+ }
+ append(&dst, &size, "\n", 1);
+ append(&dst, &size, last.begin(), end.fTextByteIndex);
+ return size;
+}
+
+static inline const char* begin(const StringSlice& s) { return s.begin(); }
+
+static inline const char* end(const StringSlice& s) { return s.end(); }
+
+static size_t align_column(const StringSlice& str, size_t p) {
+ if (p >= str.size()) {
+ return str.size();
+ }
+ return align_utf8(begin(str) + p, begin(str)) - begin(str);
+}
+
+// returns smallest i such that list[i] > value. value > list[i-1]
+// Use a binary search since list is monotonic
+template <typename T>
+static size_t find_first_larger(const std::vector<T>& list, T value) {
+ return (size_t)(std::upper_bound(list.begin(), list.end(), value) - list.begin());
+}
+
+static size_t find_closest_x(const std::vector<SkRect>& bounds, float x, size_t b, size_t e) {
+ if (b >= e) {
+ return b;
+ }
+ SkASSERT(e <= bounds.size());
+ size_t best_index = b;
+ float best_diff = ::fabsf(bounds[best_index].x() - x);
+ for (size_t i = b + 1; i < e; ++i) {
+ float d = ::fabsf(bounds[i].x() - x);
+ if (d < best_diff) {
+ best_diff = d;
+ best_index = i;
+ }
+ }
+ return best_index;
+}
+
+Editor::TextPosition Editor::move(Editor::Movement move, Editor::TextPosition pos) const {
+ if (fLines.empty()) {
+ return {0, 0};
+ }
+ // First thing: fix possible bad input values.
+ if (pos.fParagraphIndex >= fLines.size()) {
+ pos.fParagraphIndex = fLines.size() - 1;
+ pos.fTextByteIndex = fLines[pos.fParagraphIndex].fText.size();
+ } else {
+ pos.fTextByteIndex = align_column(fLines[pos.fParagraphIndex].fText, pos.fTextByteIndex);
+ }
+
+ SkASSERT(pos.fParagraphIndex < fLines.size());
+ SkASSERT(pos.fTextByteIndex <= fLines[pos.fParagraphIndex].fText.size());
+
+ SkASSERT(pos.fTextByteIndex == fLines[pos.fParagraphIndex].fText.size() ||
+ !is_utf8_continuation(fLines[pos.fParagraphIndex].fText.begin()[pos.fTextByteIndex]));
+
+ switch (move) {
+ case Editor::Movement::kNowhere:
+ break;
+ case Editor::Movement::kLeft:
+ if (0 == pos.fTextByteIndex) {
+ if (pos.fParagraphIndex > 0) {
+ --pos.fParagraphIndex;
+ pos.fTextByteIndex = fLines[pos.fParagraphIndex].fText.size();
+ }
+ } else {
+ const auto& str = fLines[pos.fParagraphIndex].fText;
+ pos.fTextByteIndex =
+ prev_utf8(begin(str) + pos.fTextByteIndex, begin(str)) - begin(str);
+ }
+ break;
+ case Editor::Movement::kRight:
+ if (fLines[pos.fParagraphIndex].fText.size() == pos.fTextByteIndex) {
+ if (pos.fParagraphIndex + 1 < fLines.size()) {
+ ++pos.fParagraphIndex;
+ pos.fTextByteIndex = 0;
+ }
+ } else {
+ const auto& str = fLines[pos.fParagraphIndex].fText;
+ pos.fTextByteIndex =
+ next_utf8(begin(str) + pos.fTextByteIndex, end(str)) - begin(str);
+ }
+ break;
+ case Editor::Movement::kHome:
+ {
+ const std::vector<size_t>& list = fLines[pos.fParagraphIndex].fLineEndOffsets;
+ size_t f = find_first_larger(list, pos.fTextByteIndex);
+ pos.fTextByteIndex = f > 0 ? list[f - 1] : 0;
+ }
+ break;
+ case Editor::Movement::kEnd:
+ {
+ const std::vector<size_t>& list = fLines[pos.fParagraphIndex].fLineEndOffsets;
+ size_t f = find_first_larger(list, pos.fTextByteIndex);
+ if (f < list.size()) {
+ pos.fTextByteIndex = list[f] > 0 ? list[f] - 1 : 0;
+ } else {
+ pos.fTextByteIndex = fLines[pos.fParagraphIndex].fText.size();
+ }
+ }
+ break;
+ case Editor::Movement::kUp:
+ {
+ SkASSERT(pos.fTextByteIndex < fLines[pos.fParagraphIndex].fCursorPos.size());
+ float x = fLines[pos.fParagraphIndex].fCursorPos[pos.fTextByteIndex].left();
+ const std::vector<size_t>& list = fLines[pos.fParagraphIndex].fLineEndOffsets;
+ size_t f = find_first_larger(list, pos.fTextByteIndex);
+ // list[f] > value. value > list[f-1]
+ if (f > 0) {
+ // not the first line in paragraph.
+ pos.fTextByteIndex = find_closest_x(fLines[pos.fParagraphIndex].fCursorPos, x,
+ (f == 1) ? 0 : list[f - 2],
+ list[f - 1]);
+ } else if (pos.fParagraphIndex > 0) {
+ --pos.fParagraphIndex;
+ const auto& newLine = fLines[pos.fParagraphIndex];
+ size_t r = newLine.fLineEndOffsets.size();
+ if (r > 0) {
+ pos.fTextByteIndex = find_closest_x(newLine.fCursorPos, x,
+ newLine.fLineEndOffsets[r - 1],
+ newLine.fCursorPos.size());
+ } else {
+ pos.fTextByteIndex = find_closest_x(newLine.fCursorPos, x, 0,
+ newLine.fCursorPos.size());
+ }
+ }
+ pos.fTextByteIndex =
+ align_column(fLines[pos.fParagraphIndex].fText, pos.fTextByteIndex);
+ }
+ break;
+ case Editor::Movement::kDown:
+ {
+ const std::vector<size_t>& list = fLines[pos.fParagraphIndex].fLineEndOffsets;
+ float x = fLines[pos.fParagraphIndex].fCursorPos[pos.fTextByteIndex].left();
+
+ size_t f = find_first_larger(list, pos.fTextByteIndex);
+ if (f < list.size()) {
+ const auto& bounds = fLines[pos.fParagraphIndex].fCursorPos;
+ pos.fTextByteIndex = find_closest_x(bounds, x, list[f],
+ f + 1 < list.size() ? list[f + 1]
+ : bounds.size());
+ } else if (pos.fParagraphIndex + 1 < fLines.size()) {
+ ++pos.fParagraphIndex;
+ const auto& bounds = fLines[pos.fParagraphIndex].fCursorPos;
+ const std::vector<size_t>& l2 = fLines[pos.fParagraphIndex].fLineEndOffsets;
+ pos.fTextByteIndex = find_closest_x(bounds, x, 0,
+ l2.size() > 0 ? l2[0] : bounds.size());
+ } else {
+ pos.fTextByteIndex = fLines[pos.fParagraphIndex].fText.size();
+ }
+ pos.fTextByteIndex =
+ align_column(fLines[pos.fParagraphIndex].fText, pos.fTextByteIndex);
+ }
+ break;
+ case Editor::Movement::kWordLeft:
+ {
+ if (pos.fTextByteIndex == 0) {
+ pos = this->move(Editor::Movement::kLeft, pos);
+ break;
+ }
+ const std::vector<bool>& words = fLines[pos.fParagraphIndex].fWordBoundaries;
+ SkASSERT(words.size() == fLines[pos.fParagraphIndex].fText.size());
+ do {
+ --pos.fTextByteIndex;
+ } while (pos.fTextByteIndex > 0 && !words[pos.fTextByteIndex]);
+ }
+ break;
+ case Editor::Movement::kWordRight:
+ {
+ const StringSlice& text = fLines[pos.fParagraphIndex].fText;
+ if (pos.fTextByteIndex == text.size()) {
+ pos = this->move(Editor::Movement::kRight, pos);
+ break;
+ }
+ const std::vector<bool>& words = fLines[pos.fParagraphIndex].fWordBoundaries;
+ SkASSERT(words.size() == text.size());
+ do {
+ ++pos.fTextByteIndex;
+ } while (pos.fTextByteIndex < text.size() && !words[pos.fTextByteIndex]);
+ }
+ break;
+
+ }
+ return pos;
+}
+
+void Editor::paint(SkCanvas* c, PaintOpts options) {
+ this->reshapeAll();
+ if (!c) {
+ return;
+ }
+
+ c->drawPaint(SkPaint(options.fBackgroundColor));
+
+ SkPaint selection = SkPaint(options.fSelectionColor);
+ auto cmp = [](const Editor::TextPosition& u, const Editor::TextPosition& v) { return u < v; };
+ for (TextPosition pos = std::min(options.fSelectionBegin, options.fSelectionEnd, cmp),
+ end = std::max(options.fSelectionBegin, options.fSelectionEnd, cmp);
+ pos < end;
+ pos = this->move(Editor::Movement::kRight, pos))
+ {
+ SkASSERT(pos.fParagraphIndex < fLines.size());
+ const TextLine& l = fLines[pos.fParagraphIndex];
+ c->drawRect(offset(l.fCursorPos[pos.fTextByteIndex], l.fOrigin), selection);
+ }
+
+ if (fLines.size() > 0) {
+ c->drawRect(Editor::getLocation(options.fCursor), SkPaint(options.fCursorColor));
+ }
+
+ SkPaint foreground = SkPaint(options.fForegroundColor);
+ for (const TextLine& line : fLines) {
+ if (line.fBlob) {
+ c->drawTextBlob(line.fBlob.get(), line.fOrigin.x(), line.fOrigin.y(), foreground);
+ }
+ }
+}
+
+void Editor::reshapeAll() {
+ if (fNeedsReshape) {
+ if (fLines.empty()) {
+ fLines.push_back(TextLine());
+ }
+ float shape_width = (float)(fWidth);
+ #ifdef SK_EDITOR_GO_FAST
+ SkSemaphore semaphore;
+ std::unique_ptr<SkExecutor> executor = SkExecutor::MakeFIFOThreadPool(100);
+ int jobCount = 0;
+ for (TextLine& line : fLines) {
+ if (!line.fShaped) {
+ executor->add([&]() {
+ ShapeResult result = Shape(line.fText.begin(), line.fText.size(),
+ fFont, fLocale, shape_width);
+ line.fBlob = std::move(result.blob);
+ line.fLineEndOffsets = std::move(result.lineBreakOffsets);
+ line.fCursorPos = std::move(result.glyphBounds);
+ line.fWordBoundaries = std::move(result.wordBreaks);
+ line.fHeight = result.verticalAdvance;
+ line.fShaped = true;
+ semaphore.signal();
+ }
+ ++jobCount;
+ });
+ }
+ while (jobCount-- > 0) { semaphore.wait(); }
+ #else
+ int i = 0;
+ for (TextLine& line : fLines) {
+ if (!line.fShaped) {
+ ShapeResult result = Shape(line.fText.begin(), line.fText.size(),
+ fFont, fLocale, shape_width);
+ line.fBlob = std::move(result.blob);
+ line.fLineEndOffsets = std::move(result.lineBreakOffsets);
+ line.fCursorPos = std::move(result.glyphBounds);
+ line.fWordBoundaries = std::move(result.wordBreaks);
+ line.fHeight = result.verticalAdvance;
+ line.fShaped = true;
+ }
+ ++i;
+ }
+ #endif
+ int y = 0;
+ for (TextLine& line : fLines) {
+ line.fOrigin = {0, y};
+ y += line.fHeight;
+ }
+ fHeight = y;
+ fNeedsReshape = false;
+ }
+}
+
diff --git a/modules/skplaintexteditor/src/shape.cpp b/modules/skplaintexteditor/src/shape.cpp
new file mode 100644
index 0000000..9acba0d
--- /dev/null
+++ b/modules/skplaintexteditor/src/shape.cpp
@@ -0,0 +1,294 @@
+// Copyright 2019 Google LLC.
+// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
+
+#include "modules/skplaintexteditor/src/shape.h"
+
+#include "include/core/SkFont.h"
+#include "include/core/SkFontMetrics.h"
+#include "include/core/SkPoint.h"
+#include "include/core/SkRefCnt.h"
+#include "include/core/SkScalar.h"
+#include "include/core/SkString.h"
+#include "include/core/SkTextBlob.h"
+#include "include/core/SkTypes.h"
+#include "include/private/SkTFitsIn.h"
+#include "modules/skplaintexteditor/src/word_boundaries.h"
+#include "modules/skshaper/include/SkShaper.h"
+#include "src/core/SkTextBlobPriv.h"
+#include "src/utils/SkUTF.h"
+
+#include <limits.h>
+#include <string.h>
+
+
+using namespace SkPlainTextEditor;
+
+namespace {
+class RunHandler final : public SkShaper::RunHandler {
+public:
+ RunHandler(const char* utf8Text, size_t) : fUtf8Text(utf8Text) {}
+ using RunCallback = void (*)(void* context,
+ const char* utf8Text,
+ size_t utf8TextBytes,
+ size_t glyphCount,
+ const SkGlyphID* glyphs,
+ const SkPoint* positions,
+ const uint32_t* clusters,
+ const SkFont& font);
+ void setRunCallback(RunCallback f, void* context) {
+ fCallbackContext = context;
+ fCallbackFunction = f;
+ }
+
+ sk_sp<SkTextBlob> makeBlob();
+ SkPoint endPoint() const { return fOffset; }
+ SkPoint finalPosition() const { return fCurrentPosition; }
+
+ void beginLine() override;
+ void runInfo(const RunInfo&) override;
+ void commitRunInfo() override;
+ SkShaper::RunHandler::Buffer runBuffer(const RunInfo&) override;
+ void commitRunBuffer(const RunInfo&) override;
+ void commitLine() override;
+
+ const std::vector<size_t>& lineEndOffsets() const { return fLineEndOffsets; }
+
+ SkRect finalRect(const SkFont& font) const {
+ if (0 == fMaxRunAscent || 0 == fMaxRunDescent) {
+ SkFontMetrics metrics;
+ font.getMetrics(&metrics);
+ return {fCurrentPosition.x(),
+ fCurrentPosition.y(),
+ fCurrentPosition.x() + font.getSize(),
+ fCurrentPosition.y() + metrics.fDescent - metrics.fAscent};
+ } else {
+ return {fCurrentPosition.x(),
+ fCurrentPosition.y() + fMaxRunAscent,
+ fCurrentPosition.x() + font.getSize(),
+ fCurrentPosition.y() + fMaxRunDescent};
+ }
+ }
+
+
+private:
+ SkTextBlobBuilder fBuilder;
+ std::vector<size_t> fLineEndOffsets;
+ const SkGlyphID* fCurrentGlyphs = nullptr;
+ const SkPoint* fCurrentPoints = nullptr;
+ void* fCallbackContext = nullptr;
+ RunCallback fCallbackFunction = nullptr;
+ char const * const fUtf8Text;
+ size_t fTextOffset = 0;
+ uint32_t* fClusters = nullptr;
+ int fClusterOffset = 0;
+ int fGlyphCount = 0;
+ SkScalar fMaxRunAscent = 0;
+ SkScalar fMaxRunDescent = 0;
+ SkScalar fMaxRunLeading = 0;
+ SkPoint fCurrentPosition = {0, 0};
+ SkPoint fOffset = {0, 0};
+};
+} // namespace
+
+void RunHandler::beginLine() {
+ fCurrentPosition = fOffset;
+ fMaxRunAscent = 0;
+ fMaxRunDescent = 0;
+ fMaxRunLeading = 0;
+}
+
+void RunHandler::runInfo(const SkShaper::RunHandler::RunInfo& info) {
+ SkFontMetrics metrics;
+ info.fFont.getMetrics(&metrics);
+ fMaxRunAscent = SkTMin(fMaxRunAscent, metrics.fAscent);
+ fMaxRunDescent = SkTMax(fMaxRunDescent, metrics.fDescent);
+ fMaxRunLeading = SkTMax(fMaxRunLeading, metrics.fLeading);
+}
+
+void RunHandler::commitRunInfo() {
+ fCurrentPosition.fY -= fMaxRunAscent;
+}
+
+SkShaper::RunHandler::Buffer RunHandler::runBuffer(const RunInfo& info) {
+ int glyphCount = SkTFitsIn<int>(info.glyphCount) ? info.glyphCount : INT_MAX;
+ int utf8RangeSize = SkTFitsIn<int>(info.utf8Range.size()) ? info.utf8Range.size() : INT_MAX;
+
+ const auto& runBuffer = SkTextBlobBuilderPriv::AllocRunTextPos(&fBuilder, info.fFont, glyphCount,
+ utf8RangeSize, SkString());
+ fCurrentGlyphs = runBuffer.glyphs;
+ fCurrentPoints = runBuffer.points();
+
+ if (runBuffer.utf8text && fUtf8Text) {
+ memcpy(runBuffer.utf8text, fUtf8Text + info.utf8Range.begin(), utf8RangeSize);
+ }
+ fClusters = runBuffer.clusters;
+ fGlyphCount = glyphCount;
+ fClusterOffset = info.utf8Range.begin();
+
+ return {runBuffer.glyphs,
+ runBuffer.points(),
+ nullptr,
+ runBuffer.clusters,
+ fCurrentPosition};
+}
+
+void RunHandler::commitRunBuffer(const RunInfo& info) {
+ // for (size_t i = 0; i < info.glyphCount; ++i) {
+ // SkASSERT(fClusters[i] >= info.utf8Range.begin());
+ // // this fails for khmer example.
+ // SkASSERT(fClusters[i] < info.utf8Range.end());
+ // }
+ if (fCallbackFunction) {
+ fCallbackFunction(fCallbackContext,
+ fUtf8Text,
+ info.utf8Range.end(),
+ info.glyphCount,
+ fCurrentGlyphs,
+ fCurrentPoints,
+ fClusters,
+ info.fFont);
+ }
+ SkASSERT(0 <= fClusterOffset);
+ for (int i = 0; i < fGlyphCount; ++i) {
+ SkASSERT(fClusters[i] >= (unsigned)fClusterOffset);
+ fClusters[i] -= fClusterOffset;
+ }
+ fCurrentPosition += info.fAdvance;
+ fTextOffset = SkTMax(fTextOffset, info.utf8Range.end());
+}
+
+void RunHandler::commitLine() {
+ if (fLineEndOffsets.empty() || fTextOffset > fLineEndOffsets.back()) {
+ // Ensure that fLineEndOffsets is monotonic.
+ fLineEndOffsets.push_back(fTextOffset);
+ }
+ fOffset += { 0, fMaxRunDescent + fMaxRunLeading - fMaxRunAscent };
+}
+
+sk_sp<SkTextBlob> RunHandler::makeBlob() {
+ return fBuilder.make();
+}
+
+static SkRect selection_box(const SkFontMetrics& metrics,
+ float advance,
+ SkPoint pos) {
+ if (fabsf(advance) < 1.0f) {
+ advance = copysignf(1.0f, advance);
+ }
+ return SkRect{pos.x(),
+ pos.y() + metrics.fAscent,
+ pos.x() + advance,
+ pos.y() + metrics.fDescent}.makeSorted();
+}
+
+static void set_character_bounds(void* context,
+ const char* utf8Text,
+ size_t utf8TextBytes,
+ size_t glyphCount,
+ const SkGlyphID* glyphs,
+ const SkPoint* positions,
+ const uint32_t* clusters,
+ const SkFont& font)
+{
+ SkASSERT(context);
+ SkASSERT(glyphCount > 0);
+ SkRect* cursors = (SkRect*)context;
+
+ SkFontMetrics metrics;
+ font.getMetrics(&metrics);
+ std::unique_ptr<float[]> advances(new float[glyphCount]);
+ font.getWidths(glyphs, glyphCount, advances.get());
+
+ // Loop over each cluster in this run.
+ size_t clusterStart = 0;
+ for (size_t glyphIndex = 0; glyphIndex < glyphCount; ++glyphIndex) {
+ if (glyphIndex + 1 < glyphCount // more glyphs
+ && clusters[glyphIndex] == clusters[glyphIndex + 1]) {
+ continue; // multi-glyph cluster
+ }
+ unsigned textBegin = clusters[glyphIndex];
+ unsigned textEnd = utf8TextBytes;
+ for (size_t i = 0; i < glyphCount; ++i) {
+ if (clusters[i] >= textEnd) {
+ textEnd = clusters[i] + 1;
+ }
+ }
+ for (size_t i = 0; i < glyphCount; ++i) {
+ if (clusters[i] > textBegin && clusters[i] < textEnd) {
+ textEnd = clusters[i];
+ if (textEnd == textBegin + 1) { break; }
+ }
+ }
+ SkASSERT(glyphIndex + 1 > clusterStart);
+ unsigned clusterGlyphCount = glyphIndex + 1 - clusterStart;
+ const SkPoint* clusterGlyphPositions = &positions[clusterStart];
+ const float* clusterAdvances = &advances[clusterStart];
+ clusterStart = glyphIndex + 1; // for next loop
+
+ SkRect clusterBox = selection_box(metrics, clusterAdvances[0], clusterGlyphPositions[0]);
+ for (unsigned i = 1; i < clusterGlyphCount; ++i) { // multiple glyphs
+ clusterBox.join(selection_box(metrics, clusterAdvances[i], clusterGlyphPositions[i]));
+ }
+ if (textBegin + 1 == textEnd) { // single byte, fast path.
+ cursors[textBegin] = clusterBox;
+ continue;
+ }
+ int textCount = textEnd - textBegin;
+ int codePointCount = SkUTF::CountUTF8(utf8Text + textBegin, textCount);
+ if (codePointCount == 1) { // single codepoint, fast path.
+ cursors[textBegin] = clusterBox;
+ continue;
+ }
+
+ float width = clusterBox.width() / codePointCount;
+ SkASSERT(width > 0);
+ const char* ptr = utf8Text + textBegin;
+ const char* end = utf8Text + textEnd;
+ float x = clusterBox.left();
+ while (ptr < end) { // for each codepoint in cluster
+ const char* nextPtr = ptr;
+ SkUTF::NextUTF8(&nextPtr, end);
+ int firstIndex = ptr - utf8Text;
+ float nextX = x + width;
+ cursors[firstIndex] = SkRect{x, clusterBox.top(), nextX, clusterBox.bottom()};
+ x = nextX;
+ ptr = nextPtr;
+ }
+ }
+}
+
+ShapeResult SkPlainTextEditor::Shape(const char* utf8Text,
+ size_t textByteLen,
+ const SkFont& font,
+ const char* locale,
+ float width)
+{
+ ShapeResult result;
+ if (SkUTF::CountUTF8(utf8Text, textByteLen) < 0) {
+ utf8Text = nullptr;
+ textByteLen = 0;
+ }
+ std::unique_ptr<SkShaper> shaper = SkShaper::Make();
+ float height = font.getSpacing();
+ RunHandler runHandler(utf8Text, textByteLen);
+ if (textByteLen) {
+ result.glyphBounds.resize(textByteLen);
+ for (SkRect& c : result.glyphBounds) {
+ c = SkRect{-FLT_MAX, -FLT_MAX, -FLT_MAX, -FLT_MAX};
+ }
+ runHandler.setRunCallback(set_character_bounds, result.glyphBounds.data());
+ // TODO: make use of locale in shaping.
+ shaper->shape(utf8Text, textByteLen, font, true, width, &runHandler);
+ if (runHandler.lineEndOffsets().size() > 1) {
+ result.lineBreakOffsets = runHandler.lineEndOffsets();
+ SkASSERT(result.lineBreakOffsets.size() > 0);
+ result.lineBreakOffsets.pop_back();
+ }
+ height = std::max(height, runHandler.endPoint().y());
+ result.blob = runHandler.makeBlob();
+ }
+ result.glyphBounds.push_back(runHandler.finalRect(font));
+ result.verticalAdvance = (int)ceilf(height);
+ result.wordBreaks = GetUtf8WordBoundaries(utf8Text, textByteLen, locale);
+ return result;
+}
diff --git a/modules/skplaintexteditor/src/shape.h b/modules/skplaintexteditor/src/shape.h
new file mode 100644
index 0000000..c5585eb
--- /dev/null
+++ b/modules/skplaintexteditor/src/shape.h
@@ -0,0 +1,26 @@
+// Copyright 2019 Google LLC.
+// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
+
+#include "include/core/SkFont.h"
+#include "include/core/SkTextBlob.h"
+
+#include <cstddef>
+#include <vector>
+
+namespace SkPlainTextEditor {
+
+struct ShapeResult {
+ sk_sp<SkTextBlob> blob;
+ std::vector<std::size_t> lineBreakOffsets;
+ std::vector<SkRect> glyphBounds;
+ std::vector<bool> wordBreaks;
+ int verticalAdvance;
+};
+
+ShapeResult Shape(const char* ut8text,
+ size_t textByteLen,
+ const SkFont& font,
+ const char* locale,
+ float width);
+
+}
diff --git a/modules/skplaintexteditor/src/stringslice.cpp b/modules/skplaintexteditor/src/stringslice.cpp
new file mode 100644
index 0000000..3f7da00
--- /dev/null
+++ b/modules/skplaintexteditor/src/stringslice.cpp
@@ -0,0 +1,82 @@
+// Copyright 2019 Google LLC.
+// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
+
+#include "modules/skplaintexteditor/include/stringslice.h"
+
+#include <algorithm>
+#include <cassert>
+#include <cstdlib>
+#include <cstring>
+
+using namespace SkPlainTextEditor;
+
+void StringSlice::FreeWrapper::operator()(void* t) { std::free(t); }
+
+StringSlice::StringSlice(StringSlice&& that)
+ : fPtr(std::move(that.fPtr))
+ , fLength(that.fLength)
+ , fCapacity(that.fCapacity)
+{
+ that.fLength = 0;
+ that.fCapacity = 0;
+}
+
+StringSlice& StringSlice::operator=(StringSlice&& that) {
+ if (this != &that) {
+ this->~StringSlice();
+ new (this)StringSlice(std::move(that));
+ }
+ return *this;
+}
+
+StringSlice& StringSlice::operator=(const StringSlice& that) {
+ if (this != &that) {
+ fLength = 0;
+ if (that.size() > 0) {
+ this->insert(0, that.begin(), that.size());
+ }
+ }
+ return *this;
+}
+
+void StringSlice::insert(std::size_t offset, const char* text, std::size_t length) {
+ if (length) {
+ offset = std::min(fLength, offset);
+ this->reserve(fLength + length);
+ char* s = fPtr.get();
+ assert(s);
+ if (offset != fLength) {
+ std::memmove(s + offset + length, s + offset, fLength - offset);
+ }
+ if (text) {
+ std::memcpy(s + offset, text, length);
+ } else {
+ std::memset(s + offset, 0, length);
+ }
+ fLength += length;
+ }
+}
+
+void StringSlice::remove(std::size_t offset, std::size_t length) {
+ if (length && offset < fLength) {
+ length = std::min(length, fLength - offset);
+ assert(length > 0);
+ assert(length + offset <= fLength);
+ if (length + offset < fLength) {
+ char* s = fPtr.get();
+ assert(s);
+ std::memmove(s + offset, s + offset + length, fLength - (length + offset));
+ }
+ fLength -= length;
+ }
+}
+
+void StringSlice::realloc(std::size_t size) {
+ // round up to multiple of (1 << kBits) bytes
+ static constexpr unsigned kBits = 4;
+ fCapacity = size ? (((size - 1) >> kBits) + 1) << kBits : 0;
+ assert(fCapacity % (1u << kBits) == 0);
+ assert(fCapacity >= size);
+ fPtr.reset((char*)std::realloc(fPtr.release(), fCapacity));
+ assert(fCapacity >= fLength);
+}
diff --git a/modules/skplaintexteditor/src/word_boundaries.cpp b/modules/skplaintexteditor/src/word_boundaries.cpp
new file mode 100644
index 0000000..17c8cd3
--- /dev/null
+++ b/modules/skplaintexteditor/src/word_boundaries.cpp
@@ -0,0 +1,50 @@
+// Copyright 2019 Google LLC.
+// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
+
+#include "modules/skplaintexteditor/src/word_boundaries.h"
+
+#include <unicode/brkiter.h>
+#include <unicode/unistr.h>
+
+#include <memory>
+
+std::vector<bool> GetUtf8WordBoundaries(const char* begin, size_t byteCount, const char* locale) {
+ static constexpr UBreakIteratorType kIteratorType = UBRK_WORD;
+ struct UTextCloser {
+ void operator()(UText* p) { (void)utext_close(p); }
+ };
+ struct UBreakCloser {
+ void operator()(UBreakIterator* p) { (void)ubrk_close(p); }
+ };
+
+ std::vector<bool> result;
+ if (0 == byteCount) {
+ return result;
+ }
+ result.resize(byteCount);
+
+ UText utf8UText = UTEXT_INITIALIZER;
+ UErrorCode errorCode = U_ZERO_ERROR;
+ (void)utext_openUTF8(&utf8UText, begin, byteCount, &errorCode);
+ std::unique_ptr<UText, UTextCloser> autoclose1(&utf8UText);
+ if (U_FAILURE(errorCode)) {
+ return result;
+ }
+ UBreakIterator* iter = ubrk_open(kIteratorType, locale, nullptr, 0, &errorCode);
+ std::unique_ptr<UBreakIterator, UBreakCloser> autoclose2(iter);
+ if (U_FAILURE(errorCode)) {
+ return result;
+ }
+ ubrk_setUText(iter, &utf8UText, &errorCode);
+ if (U_FAILURE(errorCode)) {
+ return result;
+ }
+ int pos = ubrk_first(iter);
+ while (pos != icu::BreakIterator::DONE) {
+ if ((unsigned)pos < (unsigned)byteCount) {
+ result[pos] = true;
+ }
+ pos = ubrk_next(iter);
+ }
+ return result;
+}
diff --git a/modules/skplaintexteditor/src/word_boundaries.h b/modules/skplaintexteditor/src/word_boundaries.h
new file mode 100644
index 0000000..b6541df
--- /dev/null
+++ b/modules/skplaintexteditor/src/word_boundaries.h
@@ -0,0 +1,12 @@
+// Copyright 2019 Google LLC.
+// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
+#ifndef word_boundaries_DEFINED
+#define word_boundaries_DEFINED
+
+#include <cstddef>
+#include <vector>
+
+// TODO: Decide if this functionality should be moved into SkShaper as an extra utility.
+std::vector<bool> GetUtf8WordBoundaries(const char* begin, std::size_t byteLen, const char* locale);
+
+#endif // word_boundaries_DEFINED