Skip to content
Repos

DevPlaceApp

C++ 10.3 KB255 lines Opens in site

Directory Raw Download

#include "screens/components/SelectableTextPopover.hpp"

#include <algorithm>
#include <cmath>
#include <memory>

#include "screens/components/AccessibleLabel.hpp"
#include "spec/ComposeSpec.hpp"
#include "ui/Modifiers.hpp"
#include "ui/Overlays.hpp"
#include "ui/Palette.hpp"
#include "ui/TextEngine.hpp"
#include "ui/TextInput.hpp"

namespace dp {

using namespace ui;
using spec::ComposeSpec;

namespace {

bool isSpace(unsigned char c) { return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f' || c == '\v'; }

int prevBoundary(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 nextBoundary(const std::string& s, int pos) {
  const int n = static_cast<int>(s.size());
  if (pos >= n) return n;
  ++pos;
  while (pos < n && (static_cast<unsigned char>(s[static_cast<std::size_t>(pos)]) & 0xC0) == 0x80) ++pos;
  return pos;
}

struct WrappedLine {
  int start = 0;
  int end = 0;
};

// Greedy word wrap on code point widths (same approach as the editor).
std::vector<WrappedLine> wrapLines(const std::string& text, const FontSpec& font, float width) {
  auto& engine = TextEngine::instance();
  std::vector<WrappedLine> lines;
  const int n = static_cast<int>(text.size());
  int start = 0, i = 0, lastBreak = -1;
  float w = 0;
  while (i < n) {
    if (text[static_cast<std::size_t>(i)] == '\n') {
      lines.push_back({start, i});
      start = ++i;
      w = 0;
      lastBreak = -1;
      continue;
    }
    const int next = nextBoundary(text, i);
    const float cw = engine.width(font, text.substr(static_cast<std::size_t>(i), static_cast<std::size_t>(next - i)));
    if (w + cw > width && i > start) {
      const int cut = lastBreak > start ? lastBreak : i;
      lines.push_back({start, cut});
      start = cut;
      w = engine.width(font, text.substr(static_cast<std::size_t>(start), static_cast<std::size_t>(i - start)));
      lastBreak = -1;
    }
    w += cw;
    if (text[static_cast<std::size_t>(i)] == ' ') lastBreak = next;
    i = next;
  }
  lines.push_back({start, n});
  return lines;
}

// Read-only text with mouse selection; selection state is shared with the footer buttons.
class SelectableRawTextView : public View {
 public:
  SelectableRawTextView(std::shared_ptr<TextSelection> selection, float width)
      : selection_(std::move(selection)), font_(FontSpec::body()), lines_(wrapLines(selection_->text(), font_, width)) {}

  bool acceptsPress() const override { return true; }
  bool wantsDrag() const override { return true; }
  void hits(Point p, std::vector<View*>& out) override {
    if (frame_.contains(p)) out.push_back(this);
  }
  float contentHeight() const { return static_cast<float>(lines_.size()) * font_.lineHeight(); }

  void onDragBegin(Point p) override {
    const int pos = offsetAt(p);
    const double now = UiState::instance().now;
    if (now - lastClick_ < 0.35 && std::abs(pos - lastPos_) < 3) {
      selectWord(pos);
    } else {
      selection_->anchor = selection_->caret = pos;
    }
    lastClick_ = now;
    lastPos_ = pos;
  }
  void onDragMove(Point p, Point) override { selection_->caret = offsetAt(p); }

 protected:
  Size compute(const Proposal& p) override { return {p.w ? *p.w : 0.0f, contentHeight()}; }

 public:
  void draw(Canvas& c) override {
    auto& engine = TextEngine::instance();
    const float lh = font_.lineHeight();
    const std::string& text = selection_->text();
    const int a = std::min(selection_->anchor, selection_->caret), b = std::max(selection_->anchor, selection_->caret);
    for (std::size_t li = 0; li < lines_.size(); ++li) {
      const WrappedLine& l = lines_[li];
      const float y = frame_.y + static_cast<float>(li) * lh;
      if (y + lh < frame_.y || y > frame_.bottom()) continue;
      const int s0 = std::max(a, l.start), s1 = std::min(b, l.end);
      if (s1 > s0) {
        const float x0 = engine.width(font_, text.substr(static_cast<std::size_t>(l.start), static_cast<std::size_t>(s0 - l.start)));
        const float x1 = engine.width(font_, text.substr(static_cast<std::size_t>(l.start), static_cast<std::size_t>(s1 - l.start)));
        c.fillRect({frame_.x + x0, y, std::max(2.0f, x1 - x0), lh}, Palette::accent(), 0.3f);
      }
      if (l.end > l.start) {
        BitmapPtr bmp = engine.render(font_, Palette::fg1(), text.substr(static_cast<std::size_t>(l.start), static_cast<std::size_t>(l.end - l.start)));
        if (bmp) c.blitText(*bmp, frame_.x, y + (lh - (engine.ascent(font_) + engine.descent(font_))) / 2);
      }
    }
  }

 private:
  int offsetAt(Point p) const {
    auto& engine = TextEngine::instance();
    const float lh = font_.lineHeight();
    const int li = std::clamp(static_cast<int>(std::floor((p.y - frame_.y) / lh)), 0, static_cast<int>(lines_.size()) - 1);
    const WrappedLine& l = lines_[static_cast<std::size_t>(li)];
    const std::string& text = selection_->text();
    float acc = 0;
    int pos = l.start;
    while (pos < l.end) {
      const int next = nextBoundary(text, pos);
      const float cw = engine.width(font_, text.substr(static_cast<std::size_t>(pos), static_cast<std::size_t>(next - pos)));
      if (p.x - frame_.x < acc + cw / 2) break;
      acc += cw;
      pos = next;
    }
    return pos;
  }
  void selectWord(int pos) {
    const std::string& t = selection_->text();
    int a = std::min(pos, static_cast<int>(t.size())), b = a;
    while (a > 0 && !isSpace(static_cast<unsigned char>(t[static_cast<std::size_t>(prevBoundary(t, a))]))) a = prevBoundary(t, a);
    while (b < static_cast<int>(t.size()) && !isSpace(static_cast<unsigned char>(t[static_cast<std::size_t>(b)]))) b = nextBoundary(t, b);
    selection_->anchor = a;
    selection_->caret = b;
  }

  std::shared_ptr<TextSelection> selection_;
  FontSpec font_;
  std::vector<WrappedLine> lines_;
  double lastClick_ = -10;
  int lastPos_ = -100;
};

ViewPtr iconButton(const std::string& symbol, const std::string& label, std::function<void()> action) {
  return WithAccessibleLabel(Button(Icon(symbol, ComposeSpec::kPopoverIconSize)->foreground(Palette::fg2()), std::move(action),
                                    ButtonStyles::plain()), label);
}

// Wrapper that opens the popover on a long press.
class LongPressPopoverView : public WrapperView {
 public:
  LongPressPopoverView(ViewPtr content, std::string text, QuoteComposer quote)
      : WrapperView(std::move(content)), text_(std::move(text)), quote_(std::move(quote)) {}
  bool acceptsPress() const override { return true; }
  void onLongPress(Point) override { present(); }
  void hits(Point p, std::vector<View*>& out) override {
    if (!frame_.contains(p)) return;
    WrapperView::hits(p, out);
    out.push_back(this);
  }

 private:
  void present() {
    std::string raw = text_;
    if (raw.size() > ComposeSpec::kPopoverMaxChars) raw.resize(ComposeSpec::kPopoverMaxChars);
    auto selection = std::make_shared<TextSelection>(raw);
    const FontSpec body = FontSpec::body();
    const float maxText = ComposeSpec::kPopoverMaxWidth;
    float ideal = 0;
    for (const WrappedLine& l : wrapLines(raw, body, 1.0e6f)) {
      ideal = std::max(ideal, TextEngine::instance().width(body, raw.substr(static_cast<std::size_t>(l.start), static_cast<std::size_t>(l.end - l.start))));
    }
    const float textW = std::clamp(ideal + 1, ComposeSpec::kPopoverMinTextWidth, maxText);
    const float fitted = static_cast<float>(wrapLines(raw, body, textW).size()) * body.lineHeight();
    const float textH = std::min(fitted, ComposeSpec::kPopoverMaxHeight);
    const float footerH = FontSpec::footnote().lineHeight() + 8;
    const float pad = ComposeSpec::kPopoverPadding;
    const Size size{textW + 2 * pad, textH + ComposeSpec::kPopoverGap + footerH + 2 * pad};
    QuoteComposer quote = quote_;
    const bool scrolls = fitted > textH;
    Overlays::instance().popover(frame_, size, [selection, quote, textW, textH, scrolls] {
      ViewPtr textView = std::make_shared<SelectableRawTextView>(selection, textW);
      ViewPtr body = scrolls ? ScrollView(textView)->frame(textW, textH) : textView->frame(textW, textH);
      std::vector<ViewPtr> left{iconButton("selection.pin.in.out", ComposeSpec::kLabelFirstWord, [selection] { selection->selectFirstWord(); }),
                                iconButton("textformat.characters.arrow.left.and.right", ComposeSpec::kLabelSelectAll, [selection] { selection->selectAll(); })};
      std::vector<ViewPtr> right{iconButton("document.on.clipboard", ComposeSpec::kLabelCopy, [selection] {
        Clipboard::set(selection->selectedText());
        Overlays::instance().dismissTop();
      })};
      if (quote.active) {
        right.push_back(iconButton("text.quote", ComposeSpec::kLabelQuote, [selection, quote] {
          if (quote.insert) {
            quote.insert(std::string(ComposeSpec::kQuotePrefix) + selection->selectedText() + ComposeSpec::kQuoteSuffix);
          }
          Overlays::instance().dismissTop();
        }));
      }
      ViewPtr footer = HStack({HStack(left, ComposeSpec::kPopoverIconGap), Spacer(), HStack(right, ComposeSpec::kPopoverIconGap)}, 8)
                           ->font(FontSpec::footnote())->foreground(Palette::fg2());
      return VStack({body, footer}, ComposeSpec::kPopoverGap, HAlign::Leading)->padding(ComposeSpec::kPopoverPadding);
    });
  }

  std::string text_;
  QuoteComposer quote_;
};

}  // namespace

std::string TextSelection::selectedText() const {
  const int a = std::clamp(std::min(anchor, caret), 0, static_cast<int>(text_.size()));
  const int b = std::clamp(std::max(anchor, caret), 0, static_cast<int>(text_.size()));
  if (a == b) return text_;
  return text_.substr(static_cast<std::size_t>(a), static_cast<std::size_t>(b - a));
}

void TextSelection::selectAll() {
  anchor = 0;
  caret = static_cast<int>(text_.size());
}

void TextSelection::selectFirstWord() {
  const int n = static_cast<int>(text_.size());
  int start = 0;
  while (start < n && isSpace(static_cast<unsigned char>(text_[static_cast<std::size_t>(start)]))) ++start;
  if (start >= n) return;
  int end = start;
  while (end < n && !isSpace(static_cast<unsigned char>(text_[static_cast<std::size_t>(end)]))) ++end;
  anchor = start;
  caret = end;
}

ViewPtr SelectableTextPopover(ViewPtr content, std::string text, QuoteComposer quote) {
  return std::make_shared<LongPressPopoverView>(std::move(content), std::move(text), std::move(quote));
}

}  // namespace dp
45.1ms