Skip to content
Repos

DevPlaceApp

C++ 1.7 KB39 lines Opens in site

Directory Raw Download

#pragma once
// Spec: SPEC.md UX-HOST-02. Pure sizing math for a window that must stay within a percentage of the screen
// height and sit in the middle of the screen. No SDL calls, so it is unit tested.
#include <algorithm>

#include "spec/AppSpec.hpp"
#include "ui/Geometry.hpp"

namespace dp::ui {

struct WindowFitResult {
  int width = 0, height = 0;  // window size in screen units
  int x = 0, y = 0;           // top-left, centered on the display
  int maxHeight = 0;          // hard cap to hand to the window system
};

class WindowFit {
 public:
  static int clampPercent(int percent) {
    return std::clamp(percent, spec::AppSpec::kFitPercentMin, spec::AppSpec::kFitPercentMax);
  }

  // `desired` is the client size the app wants. The cap and the centering apply to the OUTER window, so the
  // frame the window manager draws (title bar, borders) is passed in and subtracted from the client area.
  static WindowFitResult fit(Size desired, int displayX, int displayY, int displayW, int displayH, int percent,
                             int frameLeft = 0, int frameTop = 0, int frameRight = 0, int frameBottom = 0) {
    WindowFitResult r;
    const int outerMax = std::max(1, displayH * clampPercent(percent) / 100);
    r.maxHeight = std::max(1, outerMax - frameTop - frameBottom);
    r.height = std::min(static_cast<int>(desired.h), r.maxHeight);
    r.width = std::max(1, std::min(static_cast<int>(desired.w), displayW - frameLeft - frameRight));
    const int outerW = r.width + frameLeft + frameRight, outerH = r.height + frameTop + frameBottom;
    r.x = displayX + (displayW - outerW) / 2 + frameLeft;
    r.y = displayY + (displayH - outerH) / 2 + frameTop;
    return r;
  }
};

}  // namespace dp::ui
37.9ms