Lab 4: 1D/2D Box & Grid Layout Geometry Solver with Max-Cap Redistribution
Engineer interlock-safe Qt 6 button groups and touch targets, feedback-free QValidator and QSignalBlocker editors, and drift-free integer box/grid/form layout geometry solvers.
Prerequisites in this module
What ./check.sh verifies
- Builds libcore.a and lab_cli cleanly with -std=c++20 -Wall -Wextra -Werror -pedantic.
- Fix compiler warnings or errors in files/core.cpp.
- Archives core.o into libcore.a and links independent TAP verifier.
- Preserve public declarations in files/core.hpp so tests.cpp links.
step 1/15 · inspect starter files and specification
Build and benchmark a deterministic ISO C++20 1D/2D box-and-grid layout geometry solver that mirrors QLayoutEngine (qGeomCalc) across hidden items, max_px saturation, and zero-drift remainder rounding.
learner@ksa:~/gl-q01/lab-m04ls -lastarter/Makefilestarter/cli.cppstarter/core.cppstarter/core.hpplearner@ksa:~/gl-q01/lab-m04starter: starter/Makefile
learner@ksa:~/gl-q01/lab-m04$ bat starter/Makefile File: starter/Makefile CC_BIN = g++ AR = ar CFLAGS_ALL = -std=c++20 -Wall -Wextra -Werror -pedantic -O2 LDLIBS = all: libcore.a lab_cli libcore.a: core.o $(AR) rcs $@ $^ lab_cli: cli.o libcore.a $(CC_BIN) $(CFLAGS_ALL) cli.o libcore.a $(LDLIBS) -o $@ %.o: %.cpp core.hpp $(CC_BIN) $(CFLAGS_ALL) -c $< -o $@ .PHONY: all clean clean: rm -f core.o cli.o libcore.a lab_clistarter: starter/cli.cpp
learner@ksa:~/gl-q01/lab-m04$ bat starter/cli.cpp File: starter/cli.cpp #include "core.hpp" #include <algorithm> #include <array> #include <cstdint> #include <cstdio> #include <cstring> #include <ctime> #include <vector> static std::uint64_t now_ns() noexcept { timespec ts{}; clock_gettime(CLOCK_MONOTONIC, &ts); return static_cast<std::uint64_t>(ts.tv_sec) * 1000000000ULL + static_cast<std::uint64_t>(ts.tv_nsec); } int main(int argc, char **argv) { const std::vector<hmi::GridCell> cells = { {0, 0, {60, 80, 200, 0, hmi::SizeMode::Fixed, true}, {24, 32, 100, 0, hmi::SizeMode::Fixed, true}}, {0, 1, {80, 100, 900, 0, hmi::SizeMode::Expanding, true}, {24, 32, 100, 0, hmi::SizeMode::Fixed, true}}, {1, 0, {60, 110, 200, 0, hmi::SizeMode::Fixed, true}, {24, 40, 100, 0, hmi::SizeMode::Fixed, true}}, {1, 1, {80, 100, 900, 0, hmi::SizeMode::Expanding, true}, {24, 40, 100, 0, hmi::SizeMode::Fixed, true}}, }; if (argc > 1 && std::strcmp(argv[1], "--bench") == 0) { constexpr int kWarmup = 5; constexpr int kSamples = 40; constexpr int kBatch = 500; std::array<std::uint64_t, kSamples> ns{}; volatile int sink = 0; for (int i = 0; i < kWarmup + kSamples; ++i) { const std::uint64_t t0 = now_ns(); for (int r = 0; r < kBatch; ++r) { auto rects = hmi::solve_grid(800 + (r & 7), 480, 10, 8, 6, 2, 2, {0, 1}, {0, 1}, cells); sink += rects[1].w + rects[3].h; } const std::uint64_t dt = (now_ns() - t0) / kBatch; if (i >= kWarmup) { ns[static_cast<std::size_t>(i - kWarmup)] = dt; } } std::sort(ns.begin(), ns.end()); std::printf("bench_layout_solver_ns: p50=%llu p95=%llu p99=%llu (sink=%d)\n", static_cast<unsigned long long>(ns[20]), static_cast<unsigned long long>(ns[37]), static_cast<unsigned long long>(ns[39]), sink); return 0; } const auto box = hmi::solve_box_axis(322, 10, 10, 0, { {20, 50, 1000, 1, hmi::SizeMode::Expanding, true}, {20, 50, 1000, 1, hmi::SizeMode::Expanding, true}, {20, 50, 1000, 1, hmi::SizeMode::Expanding, true}, }); const auto grid = hmi::solve_grid(430, 100, 10, 10, 10, 2, 2, {0, 1}, {0, 0}, cells); std::printf("box_322px: [%d, %d, %d] right_edge=%d\n", box[0].size, box[1].size, box[2].size, box[2].pos + box[2].size); std::printf("grid_430x100: col0_w=%d col1_x=%d col1_w=%d\n", grid[0].w, grid[1].x, grid[1].w); return (box[2].pos + box[2].size == 312 && grid[0].w == 110 && grid[1].w == 290) ? 0 : 1; }starter: starter/core.cpp
learner@ksa:~/gl-q01/lab-m04$ bat starter/core.cpp File: starter/core.cpp #include "core.hpp" #include <algorithm> namespace hmi { std::vector<Span1D> solve_box_axis(int total_px, int margin_start, int margin_end, int spacing, const std::vector<AxisSpec> &items) { const int n = static_cast<int>(items.size()); std::vector<Span1D> result(static_cast<std::size_t>(n), {0, 0}); std::vector<int> vis; vis.reserve(static_cast<std::size_t>(n)); for (int i = 0; i < n; ++i) { if (items[static_cast<std::size_t>(i)].visible) { vis.push_back(i); } } if (vis.empty()) { return result; } const int gaps = (n - 1) * spacing; const int avail = std::max(0, total_px - margin_start - margin_end - gaps); int current_sum = 0; for (int idx : vis) { const auto &it = items[static_cast<std::size_t>(idx)]; const int eff_max = (it.mode == SizeMode::Fixed) ? it.hint_px : it.max_px; const int eff_min = (it.mode == SizeMode::Fixed) ? it.hint_px : it.min_px; result[static_cast<std::size_t>(idx)].size = std::clamp(it.hint_px, eff_min, eff_max); current_sum += result[static_cast<std::size_t>(idx)].size; } int surplus = avail - current_sum; while (surplus > 0) { std::vector<int> weights(static_cast<std::size_t>(n), 0); int w_sum = 0; for (int idx : vis) { const auto &it = items[static_cast<std::size_t>(idx)]; if (it.mode != SizeMode::Fixed && it.stretch > 0 && result[static_cast<std::size_t>(idx)].size < it.max_px) { weights[static_cast<std::size_t>(idx)] = it.stretch; w_sum += it.stretch; } } if (w_sum == 0) { for (int idx : vis) { const auto &it = items[static_cast<std::size_t>(idx)]; if (it.mode == SizeMode::Expanding && result[static_cast<std::size_t>(idx)].size < it.max_px) { weights[static_cast<std::size_t>(idx)] = 1; w_sum += 1; } } } if (w_sum == 0) { for (int idx : vis) { const auto &it = items[static_cast<std::size_t>(idx)]; if (it.mode == SizeMode::Preferred && result[static_cast<std::size_t>(idx)].size < it.max_px) { weights[static_cast<std::size_t>(idx)] = 1; w_sum += 1; } } } if (w_sum == 0) { break; } int gained = 0; bool capped_any = false; for (int idx : vis) { const int wi = weights[static_cast<std::size_t>(idx)]; if (wi <= 0) { continue; } const int share = (surplus * wi) / w_sum; const int room = items[static_cast<std::size_t>(idx)].max_px - result[static_cast<std::size_t>(idx)].size; if (share >= room) { result[static_cast<std::size_t>(idx)].size += room; gained += room; capped_any = true; } else { result[static_cast<std::size_t>(idx)].size += share; gained += share; } } surplus -= gained; if (false && capped_any) { continue; } for (int idx : vis) { if (surplus <= 0) { break; } if (weights[static_cast<std::size_t>(idx)] > 0 && result[static_cast<std::size_t>(idx)].size < items[static_cast<std::size_t>(idx)].max_px) { surplus = 0; } } break; } if (surplus < 0) { int deficit = -surplus; for (int idx : vis) { if (deficit <= 0) { break; } const auto &it = items[static_cast<std::size_t>(idx)]; if (it.mode == SizeMode::Fixed) { continue; } const int room = result[static_cast<std::size_t>(idx)].size - it.min_px; if (room > 0) { const int cut = std::min(deficit, room); result[static_cast<std::size_t>(idx)].size -= cut; deficit -= cut; } } } int cursor = margin_start; for (int idx : vis) { result[static_cast<std::size_t>(idx)].pos = cursor; cursor += result[static_cast<std::size_t>(idx)].size + spacing; } return result; } std::vector<CellRect> solve_grid(int total_w, int total_h, int margin, int h_spacing, int v_spacing, int rows, int cols, const std::vector<int> &col_stretch, const std::vector<int> &row_stretch, const std::vector<GridCell> &cells) { std::vector<AxisSpec> col_specs(static_cast<std::size_t>(cols), {0, 0, 100000, 0, SizeMode::Preferred, true}); std::vector<AxisSpec> row_specs(static_cast<std::size_t>(rows), {0, 0, 100000, 0, SizeMode::Preferred, true}); for (int c = 0; c < cols; ++c) { if (c < static_cast<int>(col_stretch.size())) { col_specs[static_cast<std::size_t>(c)].stretch = col_stretch[static_cast<std::size_t>(c)]; } } for (int r = 0; r < rows; ++r) { if (r < static_cast<int>(row_stretch.size())) { row_specs[static_cast<std::size_t>(r)].stretch = row_stretch[static_cast<std::size_t>(r)]; } } for (const auto &cell : cells) { if (cell.col >= 0 && cell.col < cols && cell.horiz.visible) { auto &cs = col_specs[static_cast<std::size_t>(cell.col)]; cs.min_px = std::max(cs.min_px, cell.horiz.min_px); cs.hint_px = std::max(cs.hint_px, cell.horiz.hint_px); if (cell.horiz.mode == SizeMode::Expanding) { cs.mode = SizeMode::Expanding; } } if (cell.row >= 0 && cell.row < rows && cell.vert.visible) { auto &rs = row_specs[static_cast<std::size_t>(cell.row)]; rs.min_px = std::max(rs.min_px, cell.vert.min_px); rs.hint_px = std::max(rs.hint_px, cell.vert.hint_px); if (cell.vert.mode == SizeMode::Expanding) { rs.mode = SizeMode::Expanding; } } } const auto x_tracks = solve_box_axis(total_w, margin, margin, h_spacing, col_specs); const auto y_tracks = solve_box_axis(total_h, margin, margin, v_spacing, row_specs); std::vector<CellRect> out(cells.size()); for (std::size_t i = 0; i < cells.size(); ++i) { const auto &c = cells[i]; const auto col_u = static_cast<std::size_t>(c.col); const auto row_u = static_cast<std::size_t>(c.row); out[i] = {x_tracks[col_u].pos, y_tracks[row_u].pos, x_tracks[col_u].size, y_tracks[row_u].size}; } return out; } } // namespace hmistarter: starter/core.hpp
learner@ksa:~/gl-q01/lab-m04$ bat starter/core.hpp File: starter/core.hpp #pragma once #include <vector> namespace hmi { enum class SizeMode { Fixed, Preferred, Expanding }; struct AxisSpec { int min_px = 0; int hint_px = 0; int max_px = 100000; int stretch = 0; SizeMode mode = SizeMode::Preferred; bool visible = true; }; struct Span1D { int pos = 0; int size = 0; }; struct CellRect { int x = 0; int y = 0; int w = 0; int h = 0; }; struct GridCell { int row = 0; int col = 0; AxisSpec horiz; AxisSpec vert; }; std::vector<Span1D> solve_box_axis(int total_px, int margin_start, int margin_end, int spacing, const std::vector<AxisSpec> &items); std::vector<CellRect> solve_grid(int total_w, int total_h, int margin, int h_spacing, int v_spacing, int rows, int cols, const std::vector<int> &col_stretch, const std::vector<int> &row_stretch, const std::vector<GridCell> &cells); } // namespace hmistep 2/15 · 2. learning objectives
- Eliminate 1–2 px right-edge rounding gaps by distributing integer division remainders deterministically across active stretch items.
- Exclude hidden (
visible == false) widgets from both span sums and(N_visible - 1) * spacinggap deductions. - Redistribute surplus pixels iteratively when a stretchable item saturates
max_px, and align multi-row 2Dsolve_gridtracks.
step 3/15 · 3. environment requirements
All automated verification steps run in unprivileged user space on a POSIX Linux host using g++ -std=c++20 -Wall -Wextra -Werror -pedantic and clock_gettime(CLOCK_MONOTONIC). Recorded transcripts in captures.json were generated on x86_64 running kernel 7.0.0-42-generic and prove protocol, state-machine, and memory invariants only. Physical bus timing, DMA cache coherency, and board peripheral behavior require target validation on Linux kernel 6.12 LTS (ARMv7-A Cortex-A7).
step 4/15 · 4. required software and hardware
- Host workstation:
g++(-std=c++20 -Wall -Wextra -Werror -pedantic), GNUmake,ar(binutils), and POSIX/bin/sh. - Target environment (optional hardware step, Section 13):
ARMv7-ACortex-A7HMI panel (800x480RGB LCD or1024x600LVDS) runningLinux kernel6.12 LTS and Qt 6.8QtWidgets, verified across96 DPIand144 DPIfont-scaling profiles.
step 5/15 · 5. complete executable commands
learner@ksa:~/gl-q01/lab-m04$ bat script.sh File: script.sh make -B -C files ./files/lab_cli ./files/lab_cli --bench sh check.shstep 6/15 · 6. annotated source code
files/core.cpp enforces the production invariants that starter/core.cpp breaks:
learner@ksa:~/gl-q01/lab-m04$ bat example.cpp File: example.cpp const int gaps = (static_cast<int>(vis.size()) - 1) * spacing; const int avail = std::max(0, total_px - margin_start - margin_end - gaps); // ... surplus -= gained; if (capped_any && gained > 0) { continue; // Re-run proportional split across remaining uncapped siblings! } for (int idx : vis) { if (surplus <= 0) break; if (weights[static_cast<std::size_t>(idx)] > 0 && result[static_cast<std::size_t>(idx)].size < items[static_cast<std::size_t>(idx)].max_px) { ++result[static_cast<std::size_t>(idx)].size; --surplus; } }starter/core.cpp contains three realistic layout bugs: gaps multiplies (n - 1) * spacing across hidden items, capped_any fails to re-enter the redistribution loop when an item saturates max_px, and modulo remainder pixels are discarded instead of distributed.
step 7/15 · 7. expected output
Passing files/ run (sh check.sh, exit code 0):
learner@ksa:~/gl-q01/lab-m04$ bat listing.txt File: listing.txt TAP version 13 1..5 ok 1 - builds libcore.a and lab_cli cleanly with -std=c++20 -Wall -Wextra -Werror -pedantic ok 2 - archives core.o into libcore.a and links independent TAP verifier ok 3 - distributes proportional stretch weights and 1px modulo remainders with zero cumulative drift ok 4 - excludes hidden items from both pixel allocation and inter-item spacing gap counts ok 5 - redistributes leftover surplus when a stretch item hits max_px and aligns 2D grid tracks # pass 5/5CLI verification output (./files/lab_cli):
learner@ksa:~/gl-q01/lab-m04$ bat listing.txt File: listing.txt box_322px: [101, 101, 100] right_edge=312 grid_430x100: col0_w=110 col1_x=130 col1_w=290Defective starter/ run (exit code 1): emits FAIL: diagnostics on the broken contract assertions.
step 8/15 · 8. explanation of observed behavior
Check 3 divides 152 surplus pixels across three equal stretch = 1 items (50 + 51, 50 + 51, 50 + 50), verifying the right edge lands at exact 312 = 322 - 10. Check 4 hides item 1 inside a 3-item box, confirming only one 8 px gap separates items 0 and 2. Check 5 caps item 0 at 130 px in a 400 px span (routing all 270 px to item 1) and aligns 2D grid columns across unequal label widths (80 vs 110).
step 9/15 · 9. experiment variations
- Near transfer: Add
col_spansupport (col_span == 2) toGridCellso a section header banner spans columns0..1with widthx_tracks[0].size + h_spacing + x_tracks[1].size. - Far transfer: Implement
QFormLayout-style two-column row solving where right-aligned column-0labels lock to the widest label'shint_pxwhile column-1editors expand up tomax_px.
step 10/15 · 10. performance measurements
Recorded host benchmark (./files/lab_cli --bench, CLOCK_MONOTONIC, warmup=5, N=40 batches):
learner@ksa:~/gl-q01/lab-m04$ bat listing.txt File: listing.txt bench_layout_solver_ns: p50=330 p95=340 p99=356 (sink=24468390)The CLOCK_MONOTONIC benchmark measures user-space C++20 2D grid constraint solving (nanoseconds per 2x2 solve in host DRAM). Target frame-time budgets on Cortex-A7 must also include QFontMetrics glyph measurement and QPainter backing-store rasterization.
step 11/15 · 11. troubleshooting
| Symptom | Root cause | Fix |
|---|---|---|
| Check 3 fails with right_edge=310 instead of 312 | Starter code zeroes surplus instead of distributing 1px remainders | Increment uncapped weighted items by 1px while surplus > 0 |
| Check 4 fails with pos2=114 and sizes=[96,0,96] | gaps used total item count n (2 gaps = 16px) instead of vis.size() (1 gap = 8px) | Compute gaps = (static_cast<int>(vis.size()) - 1) * spacing |
| Check 5 fails with [130, 250] instead of [130, 270] | While loop exited after item 0 hit max_px=130 without redistributing remaining 20px | Keep if (capped_any && gained > 0) continue; active before remainder loop |
step 12/15 · 12. guided questions
- Why must max_px saturation run inside a while(surplus > 0) loop rather than a single pass?
- *Hint 1:* Suppose 3 items have stretch 1:1:1 with surplus 300, item 0 caps at +30, and item 1 caps at +110.
- *Hint 2:* Pass 1 caps item 0 (+30), leaving 270 for items 1 and 2 (+135 each), which then triggers item 1's +110 cap on pass 2 so item 2 receives the final +160.
- Why does QSpacerItem avoid the memory and event overhead of an empty QWidget?
- *Hint 1:* Check the inheritance hierarchy of QSpacerItem versus QWidget.
- *Hint 2:* QSpacerItem inherits QLayoutItem directly (not QObject or QWidget), participating in geometry math with zero window-system or event-dispatch state.
step 13/15 · 13. independent challenges
Extend solve_box_axis with proportional shrink priorities (SizeMode::Expanding shrinks faster than Preferred, while Fixed never shrinks below hint_px) and verify across 100 randomized container widths that no item ever violates [eff_min, eff_max].
step 14/15 · 14. solutions and explanations
Filtering visible items first, iterating max_px saturation until only uncapped items remain, and distributing modulo remainder pixels guarantee drift-free 1D and 2D layout geometry.
step 15/15 · run verification and inspect output
Run the verification command and confirm the output matches the expected contract.
learner@ksa:~/gl-q01/lab-m04./files/lab_clilearner@ksa:~/gl-q01/lab-m04box_322px: [101, 101, 100] right_edge=312grid_430x100: col0_w=110 col1_x=130 col1_w=290Progressive hints & solution
hint 1
Compare starter/Makefile against the module lessons. Focus first on: Builds libcore.a and lab_cli cleanly with -std=c++20 -Wall -Wextra -Werror -pedantic.
hint 2
Compile with -std=c11 -Wall -Wextra -Werror, check every system-call return value before touching output buffers, and verify cleanup on error paths.
solution
warning: Reveal the reference solution files? Running ./check.sh against your own attempt first builds stronger retention.
solution: files/Makefile
learner@ksa:~/gl-q01/lab-m04$ bat files/Makefile File: files/Makefile CC_BIN = g++ AR = ar CFLAGS_ALL = -std=c++20 -Wall -Wextra -Werror -pedantic -O2 LDLIBS = all: libcore.a lab_cli libcore.a: core.o $(AR) rcs $@ $^ lab_cli: cli.o libcore.a $(CC_BIN) $(CFLAGS_ALL) cli.o libcore.a $(LDLIBS) -o $@ %.o: %.cpp core.hpp $(CC_BIN) $(CFLAGS_ALL) -c $< -o $@ .PHONY: all clean clean: rm -f core.o cli.o libcore.a lab_clisolution: files/cli.cpp
learner@ksa:~/gl-q01/lab-m04$ bat files/cli.cpp File: files/cli.cpp #include "core.hpp" #include <algorithm> #include <array> #include <cstdint> #include <cstdio> #include <cstring> #include <ctime> #include <vector> static std::uint64_t now_ns() noexcept { timespec ts{}; clock_gettime(CLOCK_MONOTONIC, &ts); return static_cast<std::uint64_t>(ts.tv_sec) * 1000000000ULL + static_cast<std::uint64_t>(ts.tv_nsec); } int main(int argc, char **argv) { const std::vector<hmi::GridCell> cells = { {0, 0, {60, 80, 200, 0, hmi::SizeMode::Fixed, true}, {24, 32, 100, 0, hmi::SizeMode::Fixed, true}}, {0, 1, {80, 100, 900, 0, hmi::SizeMode::Expanding, true}, {24, 32, 100, 0, hmi::SizeMode::Fixed, true}}, {1, 0, {60, 110, 200, 0, hmi::SizeMode::Fixed, true}, {24, 40, 100, 0, hmi::SizeMode::Fixed, true}}, {1, 1, {80, 100, 900, 0, hmi::SizeMode::Expanding, true}, {24, 40, 100, 0, hmi::SizeMode::Fixed, true}}, }; if (argc > 1 && std::strcmp(argv[1], "--bench") == 0) { constexpr int kWarmup = 5; constexpr int kSamples = 40; constexpr int kBatch = 500; std::array<std::uint64_t, kSamples> ns{}; volatile int sink = 0; for (int i = 0; i < kWarmup + kSamples; ++i) { const std::uint64_t t0 = now_ns(); for (int r = 0; r < kBatch; ++r) { auto rects = hmi::solve_grid(800 + (r & 7), 480, 10, 8, 6, 2, 2, {0, 1}, {0, 1}, cells); sink += rects[1].w + rects[3].h; } const std::uint64_t dt = (now_ns() - t0) / kBatch; if (i >= kWarmup) { ns[static_cast<std::size_t>(i - kWarmup)] = dt; } } std::sort(ns.begin(), ns.end()); std::printf("bench_layout_solver_ns: p50=%llu p95=%llu p99=%llu (sink=%d)\n", static_cast<unsigned long long>(ns[20]), static_cast<unsigned long long>(ns[37]), static_cast<unsigned long long>(ns[39]), sink); return 0; } const auto box = hmi::solve_box_axis(322, 10, 10, 0, { {20, 50, 1000, 1, hmi::SizeMode::Expanding, true}, {20, 50, 1000, 1, hmi::SizeMode::Expanding, true}, {20, 50, 1000, 1, hmi::SizeMode::Expanding, true}, }); const auto grid = hmi::solve_grid(430, 100, 10, 10, 10, 2, 2, {0, 1}, {0, 0}, cells); std::printf("box_322px: [%d, %d, %d] right_edge=%d\n", box[0].size, box[1].size, box[2].size, box[2].pos + box[2].size); std::printf("grid_430x100: col0_w=%d col1_x=%d col1_w=%d\n", grid[0].w, grid[1].x, grid[1].w); return (box[2].pos + box[2].size == 312 && grid[0].w == 110 && grid[1].w == 290) ? 0 : 1; }solution: files/core.cpp
learner@ksa:~/gl-q01/lab-m04$ bat files/core.cpp File: files/core.cpp #include "core.hpp" #include <algorithm> namespace hmi { std::vector<Span1D> solve_box_axis(int total_px, int margin_start, int margin_end, int spacing, const std::vector<AxisSpec> &items) { const int n = static_cast<int>(items.size()); std::vector<Span1D> result(static_cast<std::size_t>(n), {0, 0}); std::vector<int> vis; vis.reserve(static_cast<std::size_t>(n)); for (int i = 0; i < n; ++i) { if (items[static_cast<std::size_t>(i)].visible) { vis.push_back(i); } } if (vis.empty()) { return result; } const int gaps = (static_cast<int>(vis.size()) - 1) * spacing; const int avail = std::max(0, total_px - margin_start - margin_end - gaps); int current_sum = 0; for (int idx : vis) { const auto &it = items[static_cast<std::size_t>(idx)]; const int eff_max = (it.mode == SizeMode::Fixed) ? it.hint_px : it.max_px; const int eff_min = (it.mode == SizeMode::Fixed) ? it.hint_px : it.min_px; result[static_cast<std::size_t>(idx)].size = std::clamp(it.hint_px, eff_min, eff_max); current_sum += result[static_cast<std::size_t>(idx)].size; } int surplus = avail - current_sum; while (surplus > 0) { std::vector<int> weights(static_cast<std::size_t>(n), 0); int w_sum = 0; for (int idx : vis) { const auto &it = items[static_cast<std::size_t>(idx)]; if (it.mode != SizeMode::Fixed && it.stretch > 0 && result[static_cast<std::size_t>(idx)].size < it.max_px) { weights[static_cast<std::size_t>(idx)] = it.stretch; w_sum += it.stretch; } } if (w_sum == 0) { for (int idx : vis) { const auto &it = items[static_cast<std::size_t>(idx)]; if (it.mode == SizeMode::Expanding && result[static_cast<std::size_t>(idx)].size < it.max_px) { weights[static_cast<std::size_t>(idx)] = 1; w_sum += 1; } } } if (w_sum == 0) { for (int idx : vis) { const auto &it = items[static_cast<std::size_t>(idx)]; if (it.mode == SizeMode::Preferred && result[static_cast<std::size_t>(idx)].size < it.max_px) { weights[static_cast<std::size_t>(idx)] = 1; w_sum += 1; } } } if (w_sum == 0) { break; } int gained = 0; bool capped_any = false; for (int idx : vis) { const int wi = weights[static_cast<std::size_t>(idx)]; if (wi <= 0) { continue; } const int share = (surplus * wi) / w_sum; const int room = items[static_cast<std::size_t>(idx)].max_px - result[static_cast<std::size_t>(idx)].size; if (share >= room) { result[static_cast<std::size_t>(idx)].size += room; gained += room; capped_any = true; } else { result[static_cast<std::size_t>(idx)].size += share; gained += share; } } surplus -= gained; if (capped_any && gained > 0) { continue; } for (int idx : vis) { if (surplus <= 0) { break; } if (weights[static_cast<std::size_t>(idx)] > 0 && result[static_cast<std::size_t>(idx)].size < items[static_cast<std::size_t>(idx)].max_px) { ++result[static_cast<std::size_t>(idx)].size; --surplus; } } break; } if (surplus < 0) { int deficit = -surplus; for (int idx : vis) { if (deficit <= 0) { break; } const auto &it = items[static_cast<std::size_t>(idx)]; if (it.mode == SizeMode::Fixed) { continue; } const int room = result[static_cast<std::size_t>(idx)].size - it.min_px; if (room > 0) { const int cut = std::min(deficit, room); result[static_cast<std::size_t>(idx)].size -= cut; deficit -= cut; } } } int cursor = margin_start; for (int idx : vis) { result[static_cast<std::size_t>(idx)].pos = cursor; cursor += result[static_cast<std::size_t>(idx)].size + spacing; } return result; } std::vector<CellRect> solve_grid(int total_w, int total_h, int margin, int h_spacing, int v_spacing, int rows, int cols, const std::vector<int> &col_stretch, const std::vector<int> &row_stretch, const std::vector<GridCell> &cells) { std::vector<AxisSpec> col_specs(static_cast<std::size_t>(cols), {0, 0, 100000, 0, SizeMode::Preferred, true}); std::vector<AxisSpec> row_specs(static_cast<std::size_t>(rows), {0, 0, 100000, 0, SizeMode::Preferred, true}); for (int c = 0; c < cols; ++c) { if (c < static_cast<int>(col_stretch.size())) { col_specs[static_cast<std::size_t>(c)].stretch = col_stretch[static_cast<std::size_t>(c)]; } } for (int r = 0; r < rows; ++r) { if (r < static_cast<int>(row_stretch.size())) { row_specs[static_cast<std::size_t>(r)].stretch = row_stretch[static_cast<std::size_t>(r)]; } } for (const auto &cell : cells) { if (cell.col >= 0 && cell.col < cols && cell.horiz.visible) { auto &cs = col_specs[static_cast<std::size_t>(cell.col)]; cs.min_px = std::max(cs.min_px, cell.horiz.min_px); cs.hint_px = std::max(cs.hint_px, cell.horiz.hint_px); if (cell.horiz.mode == SizeMode::Expanding) { cs.mode = SizeMode::Expanding; } } if (cell.row >= 0 && cell.row < rows && cell.vert.visible) { auto &rs = row_specs[static_cast<std::size_t>(cell.row)]; rs.min_px = std::max(rs.min_px, cell.vert.min_px); rs.hint_px = std::max(rs.hint_px, cell.vert.hint_px); if (cell.vert.mode == SizeMode::Expanding) { rs.mode = SizeMode::Expanding; } } } const auto x_tracks = solve_box_axis(total_w, margin, margin, h_spacing, col_specs); const auto y_tracks = solve_box_axis(total_h, margin, margin, v_spacing, row_specs); std::vector<CellRect> out(cells.size()); for (std::size_t i = 0; i < cells.size(); ++i) { const auto &c = cells[i]; const auto col_u = static_cast<std::size_t>(c.col); const auto row_u = static_cast<std::size_t>(c.row); out[i] = {x_tracks[col_u].pos, y_tracks[row_u].pos, x_tracks[col_u].size, y_tracks[row_u].size}; } return out; } } // namespace hmisolution: files/core.hpp
learner@ksa:~/gl-q01/lab-m04$ bat files/core.hpp File: files/core.hpp #pragma once #include <vector> namespace hmi { enum class SizeMode { Fixed, Preferred, Expanding }; struct AxisSpec { int min_px = 0; int hint_px = 0; int max_px = 100000; int stretch = 0; SizeMode mode = SizeMode::Preferred; bool visible = true; }; struct Span1D { int pos = 0; int size = 0; }; struct CellRect { int x = 0; int y = 0; int w = 0; int h = 0; }; struct GridCell { int row = 0; int col = 0; AxisSpec horiz; AxisSpec vert; }; std::vector<Span1D> solve_box_axis(int total_px, int margin_start, int margin_end, int spacing, const std::vector<AxisSpec> &items); std::vector<CellRect> solve_grid(int total_w, int total_h, int margin, int h_spacing, int v_spacing, int rows, int cols, const std::vector<int> &col_stretch, const std::vector<int> &row_stretch, const std::vector<GridCell> &cells); } // namespace hmiRun the check
From labs/lab_m04_box_grid_layout_solver/, run ./check.sh. A complete solution emits TAP version 13 with every test point marked ok and exits 0:
learner@ksa:~/gl-q01/lab-m04./check.shTAP version 131..5ok 1 - builds libcore.a and lab_cli cleanly with -std=c++20 -Wall -Wextra -Werror -pedanticok 2 - archives core.o into libcore.a and links independent TAP verifierok 3 - distributes proportional stretch weights and 1px modulo remainders with zero cumulative driftok 4 - excludes hidden items from both pixel allocation and inter-item spacing gap countsok 5 - redistributes leftover surplus when a stretch item hits max_px and aligns 2D grid tracks# pass 5/5On an incomplete starter tree, ./check.sh exits non-zero and marks the unmet assertion not ok with an indented YAML diagnostic block:
learner@ksa:~/gl-q01/lab-m04./check.shTAP version 131..5ok 1 - builds libcore.a and lab_cli cleanly with -std=c++20 -Wall -Wextra -Werror -pedanticok 2 - archives core.o into libcore.a and links independent TAP verifiernot ok 3 - distributes proportional stretch weights and 1px modulo remainders with zero cumulative driftFAIL: distribute remaining surplus 1px at a time across uncapped weighted items so right edge equals total_px - margin_end --- message: 'got remainder drift: got [100,100,100] end=310' hint: 'distribute remaining surplus 1px at a time across uncapped weighted items so right edge equals total_px - margin_end' ...not ok 4 - excludes hidden items from both pixel allocation and inter-item spacing gap countsFAIL: compute gaps from (vis.size() - 1) * spacing rather than (items.size() - 1) * spacing --- message: 'got hidden gap bug: sizes=[96,0,96] pos2=114' hint: 'compute gaps from (vis.size() - 1) * spacing rather than (items.size() - 1) * spacing' ...not ok 5 - redistributes leftover surplus when a stretch item hits max_px and aligns 2D grid tracksFAIL: continue the while(surplus > 0) redistribution loop whenever capped_any && gained > 0 --- message: 'got max_px redistribution bug: got [130,200] expected [130,270]' hint: 'continue the while(surplus > 0) redistribution loop whenever capped_any && gained > 0' ...# pass 2/5note: How to read TAP diagnostics: 1..N states the total test plan; each ok k confirms a passed check; not ok k pinpoints the failing check alongside message: (what went wrong) and hint: (where to look next) between --- and ....
inspect harness: check.sh
learner@ksa:~/gl-q01/lab-m04$ bat check.sh File: check.sh #!/bin/sh set -u cd "$(dirname "$0")" || exit 1 PASS=0 WORK=$(mktemp -d "${TMPDIR:-/tmp}/ksa_lab.XXXXXX") || exit 1 trap 'rm -rf "$WORK"' EXIT HUP INT TERM cp -R files "$WORK/files" printf 'TAP version 13\n1..5\n' if make -B -C "$WORK/files" >"$WORK/build.log" 2>&1; then printf 'ok 1 - builds libcore.a and lab_cli cleanly with -std=c++20 -Wall -Wextra -Werror -pedantic\n' PASS=$((PASS + 1)) else printf 'not ok 1 - builds libcore.a and lab_cli cleanly with -std=c++20 -Wall -Wextra -Werror -pedantic\n' printf 'FAIL: fix compiler warnings or errors in files/core.cpp\n' fi if [ -f "$WORK/files/libcore.a" ] && g++ -std=c++20 -Wall -Wextra -Werror -pedantic -O2 -I"$WORK/files" tests.cpp "$WORK/files/libcore.a" -o "$WORK/verify" >>"$WORK/build.log" 2>&1; then printf 'ok 2 - archives core.o into libcore.a and links independent TAP verifier\n' PASS=$((PASS + 1)) else printf 'not ok 2 - archives core.o into libcore.a and links independent TAP verifier\n' printf 'FAIL: preserve public declarations in files/core.hpp so tests.cpp links\n' fi if [ -x "$WORK/verify" ] && OUT=$("$WORK/verify" 1 2>&1); then printf 'ok 3 - distributes proportional stretch weights and 1px modulo remainders with zero cumulative drift\n' PASS=$((PASS + 1)) else printf 'not ok 3 - distributes proportional stretch weights and 1px modulo remainders with zero cumulative drift\n' printf 'FAIL: distribute remaining surplus 1px at a time across uncapped weighted items so right edge equals total_px - margin_end\n' printf " ---\n message: 'got %s'\n hint: 'distribute remaining surplus 1px at a time across uncapped weighted items so right edge equals total_px - margin_end'\n ...\n" "${OUT:-build_failed}" fi if [ -x "$WORK/verify" ] && OUT=$("$WORK/verify" 2 2>&1); then printf 'ok 4 - excludes hidden items from both pixel allocation and inter-item spacing gap counts\n' PASS=$((PASS + 1)) else printf 'not ok 4 - excludes hidden items from both pixel allocation and inter-item spacing gap counts\n' printf 'FAIL: compute gaps from (vis.size() - 1) * spacing rather than (items.size() - 1) * spacing\n' printf " ---\n message: 'got %s'\n hint: 'compute gaps from (vis.size() - 1) * spacing rather than (items.size() - 1) * spacing'\n ...\n" "${OUT:-build_failed}" fi if [ -x "$WORK/verify" ] && OUT=$("$WORK/verify" 3 2>&1); then printf 'ok 5 - redistributes leftover surplus when a stretch item hits max_px and aligns 2D grid tracks\n' PASS=$((PASS + 1)) else printf 'not ok 5 - redistributes leftover surplus when a stretch item hits max_px and aligns 2D grid tracks\n' printf 'FAIL: continue the while(surplus > 0) redistribution loop whenever capped_any && gained > 0\n' printf " ---\n message: 'got %s'\n hint: 'continue the while(surplus > 0) redistribution loop whenever capped_any && gained > 0'\n ...\n" "${OUT:-build_failed}" fi printf '# pass %d/5\n' "$PASS" [ "$PASS" -eq 5 ]Definition of done
Verification checklist
status: 0/3 checks verified
Troubleshooting
Compiler fails under -Werror on sign conversion or unused args
Use exact POSIX return types (ssize_t for read()/write(), size_t for byte counts) rather than relaxing flags.
./check.sh reports missing files in files/
Invoke ./check.sh from inside labs/lab_m04_box_grid_layout_solver/ so relative paths to files/ resolve directly.