Skip to content
Repos

DevPlaceApp

C++ 15.7 KB490 lines Opens in site

Directory Raw Download

#include "ui/Host.hpp"

#include <algorithm>
#include <cmath>
#include <cstdlib>

#include "core/Log.hpp"
#include "core/UiQueue.hpp"
#include "ui/Palette.hpp"
#include "ui/TextEngine.hpp"
#include "ui/WindowFit.hpp"

namespace dp::ui {

namespace {
constexpr float kTapSlop = 8.0f;
constexpr Uint64 kLongPressMs = 500;
constexpr float kWheelPoints = 48.0f;
}  // namespace

bool Host::init(const HostOptions& options) {
  options_ = options;
  if (!SDL_Init(options.headless ? SDL_INIT_EVENTS : (SDL_INIT_VIDEO | SDL_INIT_EVENTS))) {
    Log::error(std::string("SDL_Init failed: ") + SDL_GetError());
    return false;
  }
  if (!TextEngine::instance().init()) return false;
  if (!options.headless) {
    window_ = SDL_CreateWindow(options.title.c_str(), static_cast<int>(options.initialSize.w),
                               static_cast<int>(options.initialSize.h),
                               SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIGH_PIXEL_DENSITY | SDL_WINDOW_HIDDEN);
    if (!window_) {
      Log::error(std::string("SDL_CreateWindow failed: ") + SDL_GetError());
      return false;
    }
    SDL_SetWindowMinimumSize(window_, static_cast<int>(options.minSize.w), static_cast<int>(options.minSize.h));
    fitToDisplay();
    SDL_ShowWindow(window_);
    renderer_ = SDL_CreateRenderer(window_, nullptr);
    if (!renderer_) {
      Log::error(std::string("SDL_CreateRenderer failed: ") + SDL_GetError());
      return false;
    }
    SDL_SetRenderVSync(renderer_, 1);
    const SDL_SystemTheme theme = SDL_GetSystemTheme();
    systemDark_ = theme != SDL_SYSTEM_THEME_LIGHT;
  }
  layoutCanvas();
  return true;
}

void Host::shutdown() {
  if (texture_) SDL_DestroyTexture(texture_);
  if (renderer_) SDL_DestroyRenderer(renderer_);
  if (window_) SDL_DestroyWindow(window_);
  texture_ = nullptr;
  renderer_ = nullptr;
  window_ = nullptr;
  SDL_Quit();
}

void Host::fitToDisplay() {
  if (!window_ || options_.fitScreenPercent <= 0) return;
  SDL_Rect bounds{};
  if (!SDL_GetDisplayBounds(SDL_GetDisplayForWindow(window_), &bounds) || bounds.w <= 0 || bounds.h <= 0) {
    Log::warn(std::string("fit-screen: display bounds unavailable: ") + SDL_GetError());
    return;
  }
  int fTop = 0, fLeft = 0, fBottom = 0, fRight = 0;
  SDL_GetWindowBordersSize(window_, &fTop, &fLeft, &fBottom, &fRight);  // fails or 0 until the WM reports it
  const WindowFitResult r = WindowFit::fit(options_.initialSize, bounds.x, bounds.y, bounds.w, bounds.h,
                                           options_.fitScreenPercent, fLeft, fTop, fRight, fBottom);
  const int minH = std::min(static_cast<int>(options_.minSize.h), r.maxHeight);
  SDL_SetWindowMinimumSize(window_, static_cast<int>(options_.minSize.w), minH);
  SDL_SetWindowMaximumSize(window_, bounds.w, r.maxHeight);  // hard height cap, width limited to the display
  SDL_SetWindowSize(window_, r.width, r.height);
  SDL_SetWindowPosition(window_, r.x, r.y);
  frameFitted_ = fTop + fBottom > 0;
  fitBounds_ = bounds;
  fitX_ = r.x;
  fitY_ = r.y;
  fitW_ = r.width;
  fitH_ = r.height;
}

// The window manager reports its frame (title bar, borders) after the window is shown. Re-fit once it did,
// so the outer window, not only the client area, stays within the cap. Gives up after a bounded number of frames.
void Host::refitOnceFrameKnown() {
  constexpr int kMaxFitTries = 300;
  constexpr Uint64 kBoundsPollMs = 250;  // display changes by a streaming client may not raise an SDL event
  if (!window_ || options_.fitScreenPercent <= 0) return;
  if (!frameFitted_ && fitTries_ < kMaxFitTries) {
    ++fitTries_;
    fitToDisplay();
    return;
  }
  const Uint64 now = SDL_GetTicks();
  if (now - fitCheckTicks_ < kBoundsPollMs) return;
  fitCheckTicks_ = now;
  if (!fitStartTicks_) fitStartTicks_ = now;
  SDL_Rect b{};
  if (SDL_GetDisplayBounds(SDL_GetDisplayForWindow(window_), &b) &&
      (b.x != fitBounds_.x || b.y != fitBounds_.y || b.w != fitBounds_.w || b.h != fitBounds_.h)) {
    fitToDisplay();
    return;
  }
  // Startup grace: the window manager and the desktop panels may still move or resize the window while the
  // session loads. During a bounded window, correct any drift from the intended centered rect.
  constexpr Uint64 kGraceMs = 15000;
  constexpr int kTolerance = 2;
  if (now - fitStartTicks_ > kGraceMs) return;
  int x = 0, y = 0, w = 0, h = 0;
  SDL_GetWindowPosition(window_, &x, &y);
  SDL_GetWindowSize(window_, &w, &h);
  if (std::abs(x - fitX_) > kTolerance || std::abs(y - fitY_) > kTolerance || std::abs(w - fitW_) > kTolerance ||
      std::abs(h - fitH_) > kTolerance) {
    fitToDisplay();
  }
}

float Host::computeScale() const {
  if (options_.forcedScale > 0) return options_.forcedScale;
  if (window_) {
    const float s = SDL_GetWindowDisplayScale(window_);
    if (s > 0) return s;
  }
  return 1.0f;
}

void Host::layoutCanvas() {
  scale_ = computeScale();
  int pw = static_cast<int>(options_.initialSize.w * scale_), ph = static_cast<int>(options_.initialSize.h * scale_);
  if (window_) SDL_GetWindowSizeInPixels(window_, &pw, &ph);
  if (!window_ && logical_.w > 0) {
    pw = static_cast<int>(std::lround(logical_.w * scale_));
    ph = static_cast<int>(std::lround(logical_.h * scale_));
  }
  canvas_.resize(pw, ph, scale_);
  logical_ = canvas_.logicalSize();
  TextEngine::instance().setScale(scale_);
  if (renderer_) {
    if (texture_) SDL_DestroyTexture(texture_);
    texture_ = SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, pw, ph);
  }
  dirty_ = true;
}

void Host::resizeLogical(Size s) {
  logical_ = s;
  options_.initialSize = s;
  layoutCanvas();
}

void Host::frame(App& app) {
  UiState& ui = UiState::instance();
  ui.now = static_cast<double>(SDL_GetTicks()) / 1000.0;
  ui.animating = false;
  ui.navScrollY = ui.nextNavScrollY;
  ui.nextNavScrollY = 0;
  ui.navScrollSet = false;
  const bool dark = options_.forcedDark >= 0 ? options_.forcedDark == 1 : app.dark(systemDark_);
  Appearance::setDark(dark);
  Env::reset();
  canvas_.resize(canvas_.pixelWidth(), canvas_.pixelHeight(), scale_);
  const Size w = canvas_.logicalSize();
  root_ = app.body(w);
  if (!root_) return;
  if (window_) {
    const std::string t = app.windowTitle();
    if (!t.empty() && t != title_) {
      title_ = t;
      SDL_SetWindowTitle(window_, t.c_str());
    }
  }
  root_->assignIds(0, 0);
  root_->measure(Proposal{w.w, w.h});
  root_->place({0, 0, w.w, w.h});
  canvas_.clear(Palette::bg2());
  root_->draw(canvas_);
  if (renderer_ && texture_) {
    SDL_UpdateTexture(texture_, nullptr, canvas_.pixels(), canvas_.pixelWidth() * 4);
    SDL_RenderTexture(renderer_, texture_, nullptr, nullptr);
    SDL_RenderPresent(renderer_);
  }
  dirty_ = false;
}

void Host::setFocus(View* v) {
  UiState& ui = UiState::instance();
  const std::uint64_t newId = v ? v->id() : 0;
  if (newId == ui.focusedId) return;
  if (root_ && ui.focusedId) {
    if (View* old = root_->findById(ui.focusedId)) old->onFocus(false);
  }
  ui.focusedId = newId;
  if (v) {
    v->onFocus(true);
    if (window_) SDL_StartTextInput(window_);
  } else if (window_) {
    SDL_StopTextInput(window_);
  }
  dirty_ = true;
}

void Host::mouseDown(App&, Point p) {
  if (!root_) return;
  std::vector<View*> path;
  root_->hits(p, path);
  View* press = nullptr;
  View* scroll = nullptr;
  for (View* v : path) {
    if (!press && v->acceptsPress()) press = v;
    if (!scroll && v->scrollable()) scroll = v;
  }
  UiState& ui = UiState::instance();
  pressed_ = true;
  dragging_ = false;
  longFired_ = false;
  pressStart_ = lastPoint_ = p;
  pressTicks_ = SDL_GetTicks();
  velX_ = velY_ = 0;
  pressTargetId_ = press ? press->id() : 0;
  scrollTargetId_ = scroll ? scroll->id() : 0;
  pressTargetIsText_ = press && (press->isTextInput() || press->wantsDrag());
  if (scroll) scroll->fling(0, 0);
  if (pressTargetIsText_) {
    if (press->isTextInput()) setFocus(press);
    else setFocus(nullptr);
    press->onDragBegin(p);
  } else {
    setFocus(nullptr);
  }
  ui.pressedId = pressTargetIsText_ ? 0 : pressTargetId_;
  dirty_ = true;
}

void Host::mouseMove(App&, Point p) {
  if (!root_ || !pressed_) return;
  const float dx = p.x - lastPoint_.x, dy = p.y - lastPoint_.y;
  if (pressTargetIsText_) {
    if (View* t = root_->findById(pressTargetId_)) t->onDragMove(p, {dx, dy});
    lastPoint_ = p;
    dirty_ = true;
    return;
  }
  if (!dragging_) {
    const float dist = std::hypot(p.x - pressStart_.x, p.y - pressStart_.y);
    if (dist < kTapSlop || !scrollTargetId_) return;
    dragging_ = true;
    UiState::instance().pressedId = 0;
    if (View* s = root_->findById(scrollTargetId_)) s->onDragBegin(pressStart_);
  }
  if (View* s = root_->findById(scrollTargetId_)) s->scrollBy(-dx, -dy);
  const Uint64 now = SDL_GetTicks();
  const float dt = std::max(1.0f, static_cast<float>(now - lastMoveTicks_)) / 1000.0f;
  velX_ = velX_ * 0.6f + (-dx / dt) * 0.4f;
  velY_ = velY_ * 0.6f + (-dy / dt) * 0.4f;
  lastMoveTicks_ = now;
  lastPoint_ = p;
  dirty_ = true;
}

void Host::mouseUp(App&, Point p) {
  if (!root_ || !pressed_) return;
  pressed_ = false;
  UiState::instance().pressedId = 0;
  dirty_ = true;
  if (pressTargetIsText_) {
    if (View* t = root_->findById(pressTargetId_)) t->onDragEnd(p);
    return;
  }
  if (dragging_) {
    if (View* s = root_->findById(scrollTargetId_)) {
      s->releaseDrag();
      const bool stale = SDL_GetTicks() - lastMoveTicks_ > 90;
      if (!stale && (std::fabs(velX_) > 120 || std::fabs(velY_) > 120)) s->fling(velX_, velY_);
    }
    dragging_ = false;
    return;
  }
  if (longFired_ || !pressTargetId_) return;
  if (View* t = root_->findById(pressTargetId_)) {
    if (t->bounds().outset(kTapSlop).contains(p)) t->onTap(p);
  }
}

void Host::handleEvent(App& app, const SDL_Event& e) {
  auto toLogical = [&](float x, float y) {
    float fx = 1, fy = 1;
    if (window_) {
      int ww = 0, wh = 0, pw = 0, ph = 0;
      SDL_GetWindowSize(window_, &ww, &wh);
      SDL_GetWindowSizeInPixels(window_, &pw, &ph);
      if (ww > 0 && wh > 0) {
        fx = static_cast<float>(pw) / static_cast<float>(ww);
        fy = static_cast<float>(ph) / static_cast<float>(wh);
      }
    }
    return Point{x * fx / scale_, y * fy / scale_};
  };
  switch (e.type) {
    case SDL_EVENT_WINDOW_RESIZED:
    case SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED:
    case SDL_EVENT_WINDOW_DISPLAY_SCALE_CHANGED:
      layoutCanvas();
      break;
    case SDL_EVENT_DISPLAY_DESKTOP_MODE_CHANGED:
    case SDL_EVENT_DISPLAY_CURRENT_MODE_CHANGED:
    case SDL_EVENT_DISPLAY_USABLE_BOUNDS_CHANGED:
    case SDL_EVENT_DISPLAY_MOVED:
      fitToDisplay();
      break;
    case SDL_EVENT_SYSTEM_THEME_CHANGED:
      systemDark_ = SDL_GetSystemTheme() != SDL_SYSTEM_THEME_LIGHT;
      dirty_ = true;
      break;
    case SDL_EVENT_WINDOW_FOCUS_GAINED:
      app.onForeground();
      dirty_ = true;
      break;
    case SDL_EVENT_MOUSE_BUTTON_DOWN:
      if (e.button.button == SDL_BUTTON_LEFT) mouseDown(app, toLogical(e.button.x, e.button.y));
      break;
    case SDL_EVENT_MOUSE_MOTION:
      mouseMove(app, toLogical(e.motion.x, e.motion.y));
      break;
    case SDL_EVENT_MOUSE_BUTTON_UP:
      if (e.button.button == SDL_BUTTON_LEFT) mouseUp(app, toLogical(e.button.x, e.button.y));
      break;
    case SDL_EVENT_MOUSE_WHEEL: {
      if (!root_) break;
      float mx = 0, my = 0;
      SDL_GetMouseState(&mx, &my);
      const Point p = toLogical(mx, my);
      std::vector<View*> path;
      root_->hits(p, path);
      for (View* v : path) {
        if (v->scrollable() && v->onScrollWheel(-e.wheel.x * kWheelPoints, -e.wheel.y * kWheelPoints)) break;
      }
      dirty_ = true;
      break;
    }
    case SDL_EVENT_KEY_DOWN: {
      UiState& ui = UiState::instance();
      bool handled = false;
      if (ui.focusedId && root_) {
        if (View* f = root_->findById(ui.focusedId)) handled = f->onKey(e.key.key, e.key.mod);
      }
      if (!handled) handled = app.onKeyDown(e.key.key, e.key.mod);
      if (handled) dirty_ = true;
      break;
    }
    case SDL_EVENT_TEXT_INPUT: {
      UiState& ui = UiState::instance();
      if (ui.focusedId && root_) {
        if (View* f = root_->findById(ui.focusedId)) f->onText(e.text.text);
      }
      dirty_ = true;
      break;
    }
    case SDL_EVENT_USER:
      dirty_ = true;
      break;
    default:
      break;
  }
}

int Host::run(App& app) {
  bool running = true;
  frame(app);
  while (running) {
    SDL_Event e;
    const int timeout = UiState::instance().animating ? 8 : 250;
    bool got = SDL_WaitEventTimeout(&e, timeout);
    while (got) {
      if (e.type == SDL_EVENT_QUIT || e.type == SDL_EVENT_WINDOW_CLOSE_REQUESTED) running = false;
      else handleEvent(app, e);
      got = SDL_PollEvent(&e);
    }
    if (UiQueue::instance().drain() > 0) dirty_ = true;
    refitOnceFrameKnown();  // runs every loop pass (at least every 250 ms), also while the UI is idle
    if (pressed_ && !dragging_ && !longFired_ && pressTargetId_ && !pressTargetIsText_ && SDL_GetTicks() - pressTicks_ > kLongPressMs && root_) {
      if (View* t = root_->findById(pressTargetId_)) {
        t->onLongPress(lastPoint_);
        longFired_ = true;
        UiState::instance().pressedId = 0;
        dirty_ = true;
      }
    }
    if (dirty_ || UiState::instance().animating) frame(app);
  }
  return 0;
}

bool Host::capture(App& app, const std::string& pngPath, double maxSeconds, double settleSeconds) {
  const Uint64 start = SDL_GetTicks();
  Uint64 idleSince = 0;
  while (true) {
    UiQueue::instance().drain();
    frame(app);
    const double elapsed = static_cast<double>(SDL_GetTicks() - start) / 1000.0;
    if (app.busy()) idleSince = 0;
    else if (!idleSince) idleSince = SDL_GetTicks();
    const bool settled = idleSince && static_cast<double>(SDL_GetTicks() - idleSince) / 1000.0 >= settleSeconds;
    if (settled || elapsed >= maxSeconds) break;
    SDL_Delay(16);
  }
  UiQueue::instance().drain();
  frame(app);
  return canvas_.savePng(pngPath);
}

void Host::injectTap(App& app, Point p) {
  frame(app);
  mouseDown(app, p);
  mouseUp(app, p);
  UiQueue::instance().drain();
  frame(app);
}

void Host::injectScroll(App& app, Point p, float dy) {
  frame(app);
  std::vector<View*> path;
  if (root_) root_->hits(p, path);
  for (View* v : path) {
    if (v->scrollable() && v->onScrollWheel(0, dy)) break;
  }
  frame(app);
}

void Host::injectText(App& app, const std::string& utf8) {
  frame(app);
  UiState& ui = UiState::instance();
  if (ui.focusedId && root_) {
    if (View* f = root_->findById(ui.focusedId)) f->onText(utf8);
  }
  frame(app);
}

void Host::injectKey(App& app, std::uint32_t key, std::uint16_t mods) {
  frame(app);
  UiState& ui = UiState::instance();
  bool handled = false;
  if (ui.focusedId && root_) {
    if (View* f = root_->findById(ui.focusedId)) handled = f->onKey(key, mods);
  }
  if (!handled) app.onKeyDown(key, mods);
  frame(app);
}

}  // namespace dp::ui

namespace dp::ui {

namespace {
void collect(View* v, std::vector<View*>& out) {
  out.push_back(v);
  for (const ViewPtr& c : v->children()) collect(c.get(), out);
}
}  // namespace

std::optional<Rect> Host::findLabel(const std::string& text, bool contains) {
  if (!root_) return std::nullopt;
  std::vector<View*> all;
  collect(root_.get(), all);
  // Later views are drawn on top (overlays), so search from the end.
  for (auto it = all.rbegin(); it != all.rend(); ++it) {
    const std::string l = (*it)->label();
    if (l.empty()) continue;
    if (l == text || (contains && l.find(text) != std::string::npos)) return (*it)->bounds();
  }
  return std::nullopt;
}

std::vector<std::string> Host::labels() {
  std::vector<std::string> out;
  if (!root_) return out;
  std::vector<View*> all;
  collect(root_.get(), all);
  for (View* v : all) {
    const std::string l = v->label();
    if (!l.empty()) out.push_back(l);
  }
  return out;
}

void Host::injectBack(App& app) { injectKey(app, SDLK_ESCAPE, 0); }

}  // namespace dp::ui
47.1ms