Skip to content
Repos

DevPlaceApp

C++ 19.6 KB525 lines Opens in site

Directory Raw Download

#include "ui/TextInput.hpp"

#include <SDL3/SDL.h>

#include <algorithm>
#include <cmath>

#include "spec/EditLimits.hpp"
#include "ui/Palette.hpp"
#include "ui/TextEngine.hpp"

namespace dp::ui {

std::string Clipboard::get() {
  char* t = SDL_GetClipboardText();
  std::string out = t ? t : "";
  SDL_free(t);
  if (out.size() > kMaxBytes) out.resize(kMaxBytes);
  return out;
}
void Clipboard::set(const std::string& utf8) { SDL_SetClipboardText(utf8.c_str()); }

namespace {

constexpr const char* kBullet = "\xE2\x80\xA2";

std::size_t cpLen(unsigned char c) {
  if (c < 0x80) return 1;
  if ((c >> 5) == 0x6) return 2;
  if ((c >> 4) == 0xE) return 3;
  if ((c >> 3) == 0x1E) return 4;
  return 1;
}

int prevCp(const std::string& s, int pos) {
  if (pos <= 0) return 0;
  --pos;
  while (pos > 0 && (static_cast<unsigned char>(s[static_cast<std::size_t>(pos)]) & 0xC0) == 0x80) --pos;
  return pos;
}
int nextCp(const std::string& s, int pos) {
  if (pos >= static_cast<int>(s.size())) return static_cast<int>(s.size());
  return std::min(static_cast<int>(s.size()), pos + static_cast<int>(cpLen(static_cast<unsigned char>(s[static_cast<std::size_t>(pos)]))));
}
bool isWordChar(const std::string& s, int pos) {
  const unsigned char c = static_cast<unsigned char>(s[static_cast<std::size_t>(pos)]);
  return c >= 0x80 || std::isalnum(c) || c == '_';
}
int wordLeft(const std::string& s, int pos) {
  while (pos > 0 && !isWordChar(s, prevCp(s, pos))) pos = prevCp(s, pos);
  while (pos > 0 && isWordChar(s, prevCp(s, pos))) pos = prevCp(s, pos);
  return pos;
}
int wordRight(const std::string& s, int pos) {
  const int n = static_cast<int>(s.size());
  while (pos < n && !isWordChar(s, pos)) pos = nextCp(s, pos);
  while (pos < n && isWordChar(s, pos)) pos = nextCp(s, pos);
  return pos;
}

struct EditLine {
  int start = 0;  // byte offsets into the display string
  int end = 0;
  float width = 0;
};

class EditView : public View {
 public:
  EditView(Binding binding, TextInputOptions o, bool multiline)
      : binding_(std::move(binding)), opts_(std::move(o)), multiline_(multiline) {
    text_ = binding_.get ? binding_.get() : std::string();
    if (opts_.handle) {
      opts_.handle->binding = &binding_;
    }
  }
  bool acceptsPress() const override { return !opts_.disabled; }
  std::string label() const override { return opts_.secure ? opts_.placeholder : (text_.empty() ? opts_.placeholder : text_); }
  bool isTextInput() const override { return true; }
  bool scrollable() const override { return false; }

  void assignIds(std::uint64_t parent, std::uint64_t index) override {
    View::assignIds(parent, index);
    if (opts_.handle) opts_.handle->id = id_;
  }

  void hits(Point p, std::vector<View*>& out) override {
    if (frame_.contains(p)) out.push_back(this);
  }

  // ---- layout ----
  FontSpec font() const { return opts_.font.value_or(Env::cur().font.value_or(FontSpec::body())); }

  std::string display() const {
    if (!opts_.secure) return text_;
    std::string d;
    for (std::size_t i = 0; i < text_.size(); i += cpLen(static_cast<unsigned char>(text_[i]))) d += kBullet;
    return d;
  }
  int toDisplayOffset(int byteOffset) const {
    if (!opts_.secure) return byteOffset;
    int count = 0;
    for (int i = 0; i < byteOffset && i < static_cast<int>(text_.size());) {
      i += static_cast<int>(cpLen(static_cast<unsigned char>(text_[static_cast<std::size_t>(i)])));
      ++count;
    }
    return count * 3;
  }

  float cpWidth(const FontSpec& f, const std::string& s, int pos, int len) const {
    return TextEngine::instance().width(f, s.substr(static_cast<std::size_t>(pos), static_cast<std::size_t>(len)));
  }

  std::vector<EditLine> layoutLines(const std::string& d, float wrapWidth) const {
    const FontSpec f = font();
    std::vector<EditLine> lines;
    int start = 0;
    const int n = static_cast<int>(d.size());
    float w = 0;
    int i = 0;
    int lastBreak = -1;
    float widthAtBreak = 0;
    while (i < n) {
      if (d[static_cast<std::size_t>(i)] == '\n') {
        lines.push_back({start, i, w});
        i += 1;
        start = i;
        w = 0;
        lastBreak = -1;
        continue;
      }
      const int len = static_cast<int>(cpLen(static_cast<unsigned char>(d[static_cast<std::size_t>(i)])));
      const float cw = cpWidth(f, d, i, len);
      if (multiline_ && w + cw > wrapWidth && i > start) {
        if (lastBreak > start) {
          lines.push_back({start, lastBreak, widthAtBreak});
          start = lastBreak;
          // recompute width of the remainder
          w = 0;
          for (int k = start; k < i;) {
            const int l2 = static_cast<int>(cpLen(static_cast<unsigned char>(d[static_cast<std::size_t>(k)])));
            w += cpWidth(f, d, k, l2);
            k += l2;
          }
        } else {
          lines.push_back({start, i, w});
          start = i;
          w = 0;
        }
        lastBreak = -1;
      }
      w += cw;
      i += len;
      if (d[static_cast<std::size_t>(i - len)] == ' ') {
        lastBreak = i;
        widthAtBreak = w;
      }
    }
    lines.push_back({start, n, w});
    return lines;
  }

  float lineHeight() const { return font().lineHeight(); }

 protected:
  Size compute(const Proposal& p) override {
    const float lh = lineHeight();
    const float width = p.w ? (*p.w >= kInf / 2 ? 200.0f : *p.w) : 200.0f;
    if (!multiline_) return {width, lh};
    const auto lines = layoutLines(display(), std::max(10.0f, width));
    const int count = std::clamp(static_cast<int>(lines.size()), opts_.minLines, opts_.maxLines);
    return {width, lh * static_cast<float>(count)};
  }

 public:
  void place(const Rect& r) override {
    frame_ = r;
    lines_ = layoutLines(display(), r.w);
    clampScroll();
  }

  // ---- state ----
  Slot& slot() const { return UiState::instance().slot(id_); }
  bool focused() const { return UiState::instance().focusedId == id_; }
  int caret() const { return std::clamp(slot().caret, 0, static_cast<int>(text_.size())); }

  // Byte offset (in the real text) -> display offset is monotone; we keep caret/anchor in real offsets.
  Point caretPoint(int realOffset) const {
    const std::string d = display();
    const int off = toDisplayOffset(realOffset);
    const FontSpec f = font();
    for (std::size_t li = 0; li < lines_.size(); ++li) {
      const EditLine& l = lines_[li];
      const bool last = li + 1 == lines_.size();
      if (off >= l.start && (off < l.end || (off == l.end && (last || d[static_cast<std::size_t>(std::min<int>(off, static_cast<int>(d.size()) - 1))] == '\n' || true)))) {
        if (off == l.end && !last && lines_[li + 1].start == off && d[static_cast<std::size_t>(off - 1 < 0 ? 0 : off - 1)] != '\n') {
          // soft wrap boundary: caret belongs to the start of the next line
          continue;
        }
        return {cpWidth(f, d, l.start, off - l.start), static_cast<float>(li) * lineHeight()};
      }
    }
    return {0, 0};
  }

  void clampScroll() {
    Slot& s = slot();
    const float contentH = static_cast<float>(lines_.size()) * lineHeight();
    s.scrollY = std::clamp(s.scrollY, 0.0f, std::max(0.0f, contentH - frame_.h));
    if (!multiline_) {
      const float contentW = lines_.empty() ? 0 : lines_[0].width;
      s.scrollX = std::clamp(s.scrollX, 0.0f, std::max(0.0f, contentW - frame_.w + 2));
    } else {
      s.scrollX = 0;
    }
  }

  void ensureCaretVisible() {
    Slot& s = slot();
    const Point cp = caretPoint(caret());
    if (multiline_) {
      if (cp.y < s.scrollY) s.scrollY = cp.y;
      if (cp.y + lineHeight() > s.scrollY + frame_.h) s.scrollY = cp.y + lineHeight() - frame_.h;
    } else {
      if (cp.x < s.scrollX) s.scrollX = cp.x;
      if (cp.x > s.scrollX + frame_.w - 2) s.scrollX = cp.x - frame_.w + 2;
    }
  }

  int offsetAt(Point p) const {
    const std::string d = display();
    const FontSpec f = font();
    const Slot& s = slot();
    if (lines_.empty()) return 0;
    int li = multiline_ ? static_cast<int>(std::floor((p.y - frame_.y + s.scrollY) / lineHeight())) : 0;
    li = std::clamp(li, 0, static_cast<int>(lines_.size()) - 1);
    const EditLine& l = lines_[static_cast<std::size_t>(li)];
    const float x = p.x - frame_.x + s.scrollX;
    int pos = l.start;
    float acc = 0;
    while (pos < l.end) {
      const int len = static_cast<int>(cpLen(static_cast<unsigned char>(d[static_cast<std::size_t>(pos)])));
      const float cw = cpWidth(f, d, pos, len);
      if (x < acc + cw / 2) break;
      acc += cw;
      pos += len;
    }
    // display offset -> real offset
    if (!opts_.secure) return pos;
    return std::min(static_cast<int>(text_.size()), pos / 3 * 1) == 0 ? 0 : realFromDisplay(pos);
  }
  int realFromDisplay(int dispOffset) const {
    int count = dispOffset / 3, i = 0;
    while (count > 0 && i < static_cast<int>(text_.size())) {
      i += static_cast<int>(cpLen(static_cast<unsigned char>(text_[static_cast<std::size_t>(i)])));
      --count;
    }
    return i;
  }

  // ---- editing ----
  void commit(const std::string& next, int newCaret) {
    if (next.size() > (opts_.maxChars ? opts_.maxChars : spec::EditLimits::kMaxEditBytes)) return;
    text_ = next;
    Slot& s = slot();
    s.caret = s.anchor = std::clamp(newCaret, 0, static_cast<int>(text_.size()));
    s.stamp = UiState::instance().now;
    if (binding_.set) binding_.set(text_);
    if (opts_.onChange) opts_.onChange(text_);
    if (opts_.onCaretChange) opts_.onCaretChange(s.caret);
    lines_ = layoutLines(display(), frame_.w);
    ensureCaretVisible();
  }
  // Slots outlive the text (a send clears the draft), so every offset is clamped to the current text.
  std::pair<int, int> selection() const {
    Slot& s = slot();
    const int n = static_cast<int>(text_.size());
    const int c = std::clamp(s.caret, 0, n), a = std::clamp(s.anchor, 0, n);
    return {std::min(c, a), std::max(c, a)};
  }
  bool hasSelection() const { auto sel = selection(); return sel.first != sel.second; }
  std::string selectedText() const { auto [a, b] = selection(); return text_.substr(static_cast<std::size_t>(a), static_cast<std::size_t>(b - a)); }
  void replaceSelection(const std::string& with) {
    auto [a, b] = selection();
    std::string next = text_.substr(0, static_cast<std::size_t>(a)) + with + text_.substr(static_cast<std::size_t>(b));
    commit(next, a + static_cast<int>(with.size()));
  }
  void moveCaret(int pos, bool extend) {
    Slot& s = slot();
    s.caret = std::clamp(pos, 0, static_cast<int>(text_.size()));
    if (!extend) s.anchor = s.caret;
    s.stamp = UiState::instance().now;
    if (opts_.onCaretChange) opts_.onCaretChange(s.caret);
    ensureCaretVisible();
  }
  int verticalMove(int dir) const {
    const Point cp = caretPoint(caret());
    const FontSpec f = font();
    const int li = static_cast<int>(cp.y / lineHeight()) + dir;
    if (li < 0) return 0;
    if (li >= static_cast<int>(lines_.size())) return static_cast<int>(text_.size());
    const std::string d = display();
    const EditLine& l = lines_[static_cast<std::size_t>(li)];
    int pos = l.start;
    float acc = 0;
    while (pos < l.end) {
      const int len = static_cast<int>(cpLen(static_cast<unsigned char>(d[static_cast<std::size_t>(pos)])));
      const float cw = cpWidth(f, d, pos, len);
      if (cp.x < acc + cw / 2) break;
      acc += cw;
      pos += len;
    }
    return opts_.secure ? realFromDisplay(pos) : pos;
  }

  void onFocus(bool f) override {
    if (f) {
      Slot& s = slot();
      s.stamp = UiState::instance().now;
      s.caret = std::clamp(s.caret, 0, static_cast<int>(text_.size()));
    }
  }

  void onDragBegin(Point p) override {
    Slot& s = slot();
    const int pos = offsetAt(p);
    const double now = UiState::instance().now;
    if (now - lastClick_ < 0.35 && std::abs(pos - lastClickPos_) < 3) {
      s.anchor = wordLeft(text_, std::min(pos + 1, static_cast<int>(text_.size())));
      s.caret = wordRight(text_, s.anchor);
    } else {
      s.caret = s.anchor = pos;
    }
    lastClick_ = now;
    lastClickPos_ = pos;
    s.stamp = now;
  }
  void onDragMove(Point p, Point) override {
    Slot& s = slot();
    s.caret = offsetAt(p);
    s.stamp = UiState::instance().now;
    ensureCaretVisible();
  }
  void onTap(Point) override {}

  void onText(const std::string& utf8) override {
    if (opts_.disabled) return;
    std::string clean;
    for (char c : utf8) if (c != '\r' && (multiline_ || c != '\n')) clean.push_back(c);
    if (!clean.empty()) replaceSelection(clean);
  }

  bool onKey(std::uint32_t key, std::uint16_t mods) override {
    if (opts_.disabled) return false;
    const bool ctrl = (mods & SDL_KMOD_CTRL) || (mods & SDL_KMOD_GUI);
    const bool shift = mods & SDL_KMOD_SHIFT;
    const int caretPos = caret();
    switch (key) {
      case SDLK_BACKSPACE:
        if (hasSelection()) replaceSelection("");
        else if (caretPos > 0) {
          const int from = ctrl ? wordLeft(text_, caretPos) : prevCp(text_, caretPos);
          commit(text_.substr(0, static_cast<std::size_t>(from)) + text_.substr(static_cast<std::size_t>(caretPos)), from);
        }
        return true;
      case SDLK_DELETE:
        if (hasSelection()) replaceSelection("");
        else if (caretPos < static_cast<int>(text_.size())) {
          const int to = ctrl ? wordRight(text_, caretPos) : nextCp(text_, caretPos);
          commit(text_.substr(0, static_cast<std::size_t>(caretPos)) + text_.substr(static_cast<std::size_t>(to)), caretPos);
        }
        return true;
      case SDLK_LEFT:
        if (hasSelection() && !shift) moveCaret(selection().first, false);
        else moveCaret(ctrl ? wordLeft(text_, caretPos) : prevCp(text_, caretPos), shift);
        return true;
      case SDLK_RIGHT:
        if (hasSelection() && !shift) moveCaret(selection().second, false);
        else moveCaret(ctrl ? wordRight(text_, caretPos) : nextCp(text_, caretPos), shift);
        return true;
      case SDLK_UP:
        if (multiline_) { moveCaret(verticalMove(-1), shift); return true; }
        return false;
      case SDLK_DOWN:
        if (multiline_) { moveCaret(verticalMove(1), shift); return true; }
        return false;
      case SDLK_HOME: {
        if (ctrl || !multiline_) { moveCaret(0, shift); return true; }
        const Point cp = caretPoint(caretPos);
        const int li = static_cast<int>(cp.y / lineHeight());
        moveCaret(opts_.secure ? realFromDisplay(lines_[static_cast<std::size_t>(li)].start) : lines_[static_cast<std::size_t>(li)].start, shift);
        return true;
      }
      case SDLK_END: {
        if (ctrl || !multiline_) { moveCaret(static_cast<int>(text_.size()), shift); return true; }
        const Point cp = caretPoint(caretPos);
        const int li = static_cast<int>(cp.y / lineHeight());
        moveCaret(opts_.secure ? realFromDisplay(lines_[static_cast<std::size_t>(li)].end) : lines_[static_cast<std::size_t>(li)].end, shift);
        return true;
      }
      case SDLK_RETURN:
      case SDLK_KP_ENTER:
        if (multiline_) {
          replaceSelection("\n");
        } else if (opts_.onSubmit) {
          opts_.onSubmit();
        }
        return true;
      case SDLK_A:
        if (ctrl) { Slot& s = slot(); s.anchor = 0; s.caret = static_cast<int>(text_.size()); return true; }
        return false;
      case SDLK_C:
        if (ctrl) { if (hasSelection() && !opts_.secure) Clipboard::set(selectedText()); return true; }
        return false;
      case SDLK_X:
        if (ctrl) {
          if (hasSelection() && !opts_.secure) { Clipboard::set(selectedText()); replaceSelection(""); }
          return true;
        }
        return false;
      case SDLK_V:
        if (ctrl) { onText(Clipboard::get()); return true; }
        return false;
      default:
        return false;
    }
  }

  void draw(Canvas& c) override {
    const FontSpec f = font();
    const bool isFocused = focused();
    const std::string d = display();
    c.pushClip(frame_);
    Slot& s = slot();
    const float lh = lineHeight();
    auto& engine = TextEngine::instance();
    if (text_.empty()) {
      if (!opts_.placeholder.empty()) {
        BitmapPtr bmp = engine.render(f, Palette::fg2().opacity(0.6f), opts_.placeholder);
        if (bmp) {
          const float top = frame_.y + (lh - (engine.ascent(f) + engine.descent(f))) / 2;
          c.blitText(*bmp, frame_.x, top);
        }
      }
    } else {
      const Color col = Env::cur().foreground.value_or(Palette::fg1());
      if (isFocused && hasSelection()) {
        auto [a, b] = selection();
        const int da = toDisplayOffset(a), db = toDisplayOffset(b);
        for (std::size_t li = 0; li < lines_.size(); ++li) {
          const EditLine& l = lines_[li];
          const int s0 = std::max(da, l.start), s1 = std::min(db, l.end);
          if (s1 <= s0 && !(db > l.end && da <= l.end && l.end == l.start)) continue;
          const float x0 = cpWidth(f, d, l.start, std::max(0, s0 - l.start));
          const float x1 = cpWidth(f, d, l.start, std::max(0, s1 - l.start)) + (db > l.end ? 4.0f : 0.0f);
          c.fillRect({frame_.x + x0 - s.scrollX, frame_.y + static_cast<float>(li) * lh - s.scrollY, std::max(2.0f, x1 - x0), lh}, Palette::accent(), 0.3f);
        }
      }
      for (std::size_t li = 0; li < lines_.size(); ++li) {
        const EditLine& l = lines_[li];
        const float y = frame_.y + static_cast<float>(li) * lh - s.scrollY;
        if (y + lh < frame_.y || y > frame_.bottom()) continue;
        if (l.end <= l.start) continue;
        std::string lineText = d.substr(static_cast<std::size_t>(l.start), static_cast<std::size_t>(l.end - l.start));
        while (!lineText.empty() && lineText.back() == ' ' && li + 1 < lines_.size()) lineText.pop_back();
        if (lineText.empty()) continue;
        BitmapPtr bmp = engine.render(f, col, lineText);
        if (bmp) {
          const float top = y + (lh - (engine.ascent(f) + engine.descent(f))) / 2;
          c.blitText(*bmp, frame_.x - s.scrollX, top);
        }
      }
    }
    if (isFocused) {
      UiState::instance().animating = true;
      const double phase = std::fmod(UiState::instance().now - s.stamp, 1.0);
      if (phase < 0.6 && !hasSelection()) {
        const Point cp = caretPoint(caret());
        c.fillRect({frame_.x + cp.x - s.scrollX, frame_.y + cp.y - s.scrollY + 1, 1.5f, lh - 2}, Palette::accent());
      }
    }
    c.popClip();
  }

 private:
  Binding binding_;
  TextInputOptions opts_;
  bool multiline_;
  std::string text_;
  std::vector<EditLine> lines_;
  double lastClick_ = -10;
  int lastClickPos_ = -100;
};

}  // namespace

int TextInputHandle::caret() const { return UiState::instance().slot(id).caret; }
void TextInputHandle::setCaret(int byteOffset) {
  Slot& s = UiState::instance().slot(id);
  s.caret = s.anchor = std::max(0, byteOffset);
  s.stamp = UiState::instance().now;
}
void TextInputHandle::focus() {
  UiState::instance().focusedId = id;
  UiState::instance().slot(id).stamp = UiState::instance().now;
}
bool TextInputHandle::focused() const { return UiState::instance().focusedId == id && id != 0; }
void TextInputHandle::insertAtCaret(const std::string& utf8) {
  if (!binding || !binding->get || !binding->set) return;
  Slot& s = UiState::instance().slot(id);
  std::string t = binding->get();
  const int a = std::clamp(std::min(s.caret, s.anchor), 0, static_cast<int>(t.size()));
  const int b = std::clamp(std::max(s.caret, s.anchor), 0, static_cast<int>(t.size()));
  t = t.substr(0, static_cast<std::size_t>(a)) + utf8 + t.substr(static_cast<std::size_t>(b));
  binding->set(t);
  s.caret = s.anchor = a + static_cast<int>(utf8.size());
}

ViewPtr TextField(Binding text, TextInputOptions options) {
  return std::make_shared<EditView>(std::move(text), std::move(options), false);
}
ViewPtr TextEditor(Binding text, TextInputOptions options) {
  return std::make_shared<EditView>(std::move(text), std::move(options), true);
}

}  // namespace dp::ui
45.7ms