/*
 * Copyright 2026 Phosh.mobi e.V.
 *
 * SPDX-License-Identifier: GPL-3.0-or-later
 *
 * Author: Guido Günther <agx@sigxcpu.org>
 */

#include "livi-margin-layout.h"
#include "livi-window.h"


struct _LiviMarginLayout {
  GtkLayoutManager parent;
};

G_DEFINE_TYPE (LiviMarginLayout, livi_margin_layout, GTK_TYPE_LAYOUT_MANAGER)


static void
livi_margin_layout_measure (GtkLayoutManager *manager,
                            GtkWidget        *widget,
                            GtkOrientation    orientation,
                            int               for_size,
                            int              *min,
                            int              *nat,
                            int              *min_baseline,
                            int              *nat_baseline)
{
  GtkWidget *child = gtk_widget_get_first_child (widget);

  if (!child)
    return;

  gtk_widget_measure (child, orientation, for_size,
                      min, nat,
                      min_baseline, nat_baseline);
}


static void
livi_margin_layout_allocate (GtkLayoutManager *manager,
                             GtkWidget        *widget,
                             int               width,
                             int               height,
                             int               baseline)
{
  GtkWidget *child = gtk_widget_get_first_child (widget);
  GtkRoot *root;
  uint margin_left = 0, margin_right = 0;

  if (!child)
    return;

  root = gtk_widget_get_root (widget);
  if (root) {
    gboolean fullscreen = gtk_window_is_fullscreen (GTK_WINDOW (root));

    if (fullscreen)
      livi_window_get_cutout_margins (LIVI_WINDOW (root), &margin_left, &margin_right);
  }

  gtk_widget_allocate (child,
                       width - margin_left - margin_right,
                       height,
                       baseline,
                       gsk_transform_translate (NULL,
                                                &GRAPHENE_POINT_INIT (margin_left, 0)));
}


static void
livi_margin_layout_class_init (LiviMarginLayoutClass *klass)
{
  GtkLayoutManagerClass *layout_manager_class = GTK_LAYOUT_MANAGER_CLASS (klass);

  layout_manager_class->measure  = livi_margin_layout_measure;
  layout_manager_class->allocate = livi_margin_layout_allocate;
}


static void
livi_margin_layout_init (LiviMarginLayout *self)
{
}


GtkLayoutManager *
livi_margin_layout_new (void)
{
  return g_object_new (LIVI_TYPE_MARGIN_LAYOUT, NULL);
}
