gtkgridview.c 42.9 KB
Newer Older
1
/*
Benjamin Otte's avatar
Benjamin Otte committed
2
 * Copyright © 2019 Benjamin Otte
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library. If not, see <http://www.gnu.org/licenses/>.
 *
 * Authors: Benjamin Otte <otte@gnome.org>
 */

#include "config.h"

#include "gtkgridview.h"

24
#include "gtkbitset.h"
25
#include "gtkintl.h"
Benjamin Otte's avatar
Benjamin Otte committed
26
#include "gtklistbaseprivate.h"
Benjamin Otte's avatar
Benjamin Otte committed
27 28
#include "gtklistitemfactory.h"
#include "gtklistitemmanagerprivate.h"
Benjamin Otte's avatar
Benjamin Otte committed
29
#include "gtkmain.h"
30
#include "gtkprivate.h"
31 32
#include "gtksingleselection.h"
#include "gtkwidgetprivate.h"
33
#include "gtkmultiselection.h"
34 35 36 37 38 39 40 41

/* Maximum number of list items created by the gridview.
 * For debugging, you can set this to G_MAXUINT to ensure
 * there's always a list item for every row.
 *
 * We multiply this number with GtkGridView:max-columns so
 * that we can always display at least this many rows.
 */
42
#define GTK_GRID_VIEW_MAX_VISIBLE_ROWS (30)
43

44 45
#define DEFAULT_MAX_COLUMNS (7)

46
/**
Matthias Clasen's avatar
Matthias Clasen committed
47
 * GtkGridView:
48
 *
Matthias Clasen's avatar
Matthias Clasen committed
49
 * `GtkGridView` presents a large dynamic grid of items.
50
 *
Matthias Clasen's avatar
Matthias Clasen committed
51 52 53
 * `GtkGridView` uses its factory to generate one child widget for each
 * visible item and shows them in a grid. The orientation of the grid view
 * determines if the grid reflows vertically or horizontally.
54
 *
Matthias Clasen's avatar
Matthias Clasen committed
55
 * `GtkGridView` allows the user to select items according to the selection
56 57
 * characteristics of the model. For models that allow multiple selected items,
 * it is possible to turn on _rubberband selection_, using
Matthias Clasen's avatar
Matthias Clasen committed
58
 * [property@Gtk.GridView:enable-rubberband].
59
 *
Matthias Clasen's avatar
Matthias Clasen committed
60 61
 * To learn more about the list widget framework, see the
 * [overview](section-list-widget.html).
62
 *
63 64
 * # CSS nodes
 *
Matthias Clasen's avatar
Matthias Clasen committed
65
 * ```
66 67 68 69 70 71 72
 * gridview
 * ├── child
 * │
 * ├── child
 * │
 * ┊
 * ╰── [rubberband]
Matthias Clasen's avatar
Matthias Clasen committed
73
 * ```
74
 *
Matthias Clasen's avatar
Matthias Clasen committed
75
 * `GtkGridView` uses a single CSS node with name gridview. Each child
76 77
 * uses a single CSS node with name child. For rubberband selection,
 * a subnode with name rubberband is used.
78 79 80
 *
 * # Accessibility
 *
Matthias Clasen's avatar
Matthias Clasen committed
81 82
 * `GtkGridView` uses the %GTK_ACCESSIBLE_ROLE_GRID role, and the items
 * use the %GTK_ACCESSIBLE_ROLE_GRID_CELL role.
83 84
 */

Benjamin Otte's avatar
Benjamin Otte committed
85 86 87
typedef struct _Cell Cell;
typedef struct _CellAugment CellAugment;

88 89
struct _GtkGridView
{
Benjamin Otte's avatar
Benjamin Otte committed
90
  GtkListBase parent_instance;
91

Benjamin Otte's avatar
Benjamin Otte committed
92
  GtkListItemManager *item_manager;
93 94
  guint min_columns;
  guint max_columns;
95 96
  /* set in size_allocate */
  guint n_columns;
97
  int unknown_row_height;
98
  double column_width;
99 100
};

Benjamin Otte's avatar
Benjamin Otte committed
101 102 103 104 105
struct _GtkGridViewClass
{
  GtkListBaseClass parent_class;
};

Benjamin Otte's avatar
Benjamin Otte committed
106 107 108
struct _Cell
{
  GtkListItemManagerItem parent;
109
  guint size; /* total, only counting cells in first column */
Benjamin Otte's avatar
Benjamin Otte committed
110 111 112 113 114
};

struct _CellAugment
{
  GtkListItemManagerItemAugment parent;
115
  guint size; /* total, only counting first column */
Benjamin Otte's avatar
Benjamin Otte committed
116 117
};

118 119 120
enum
{
  PROP_0,
Benjamin Otte's avatar
Benjamin Otte committed
121
  PROP_FACTORY,
122 123
  PROP_MAX_COLUMNS,
  PROP_MIN_COLUMNS,
124
  PROP_MODEL,
125
  PROP_SINGLE_CLICK_ACTIVATE,
Matthias Clasen's avatar
Matthias Clasen committed
126
  PROP_ENABLE_RUBBERBAND,
127 128 129 130

  N_PROPS
};

Benjamin Otte's avatar
Benjamin Otte committed
131 132 133 134 135
enum {
  ACTIVATE,
  LAST_SIGNAL
};

136
G_DEFINE_TYPE (GtkGridView, gtk_grid_view, GTK_TYPE_LIST_BASE)
137 138

static GParamSpec *properties[N_PROPS] = { NULL, };
Benjamin Otte's avatar
Benjamin Otte committed
139
static guint signals[LAST_SIGNAL] = { 0 };
140

141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
static void G_GNUC_UNUSED
dump (GtkGridView *self)
{
  Cell *cell;
  guint n_widgets, n_list_rows, n_items;

  n_widgets = 0;
  n_list_rows = 0;
  n_items = 0;
  //g_print ("ANCHOR: %u - %u\n", self->anchor_start, self->anchor_end);
  for (cell = gtk_list_item_manager_get_first (self->item_manager);
       cell;
       cell = gtk_rb_tree_node_get_next (cell))
    {
      if (cell->parent.widget)
        n_widgets++;
      n_list_rows++;
      n_items += cell->parent.n_items;
      g_print ("%6u%6u %5ux%3u %s (%upx)\n",
               cell->parent.n_items, n_items,
               n_items / (self->n_columns ? self->n_columns : self->min_columns),
               n_items % (self->n_columns ? self->n_columns : self->min_columns),
               cell->parent.widget ? " (widget)" : "", cell->size);
    }

  g_print ("  => %u widgets in %u list rows\n", n_widgets, n_list_rows);
}
168

169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
static void
cell_augment (GtkRbTree *tree,
              gpointer   node_augment,
              gpointer   node,
              gpointer   left,
              gpointer   right)
{
  Cell *cell = node;
  CellAugment *aug = node_augment;

  gtk_list_item_manager_augment_node (tree, node_augment, node, left, right);

  aug->size = cell->size;

  if (left)
    {
      CellAugment *left_aug = gtk_rb_tree_get_augment (tree, left);

      aug->size += left_aug->size;
    }

  if (right)
    {
      CellAugment *right_aug = gtk_rb_tree_get_augment (tree, right);

      aug->size += right_aug->size;
    }
}

198 199
/*<private>
 * gtk_grid_view_get_cell_at_y:
Matthias Clasen's avatar
Matthias Clasen committed
200
 * @self: a `GtkGridView`
201 202 203 204 205 206 207 208 209 210 211 212
 * @y: an offset in direction of @self's orientation
 * @position: (out caller-allocates) (optional): stores the position
 *     index of the returned row
 * @offset: (out caller-allocates) (optional): stores the offset
 *     in pixels between y and top of cell.
 * @offset: (out caller-allocates) (optional): stores the height
 *     of the cell
 *
 * Gets the Cell that occupies the leftmost position in the row at offset
 * @y into the primary direction. 
 *
 * If y is larger than the height of all cells, %NULL will be returned.
213
 * In particular that means that for an empty grid, %NULL is returned
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
 * for any value.
 *
 * Returns: (nullable): The first cell at offset y or %NULL if none
 **/
static Cell *
gtk_grid_view_get_cell_at_y (GtkGridView *self,
                             int          y,
                             guint       *position,
                             int         *offset,
                             int         *size)
{
  Cell *cell, *tmp;
  guint pos;

  cell = gtk_list_item_manager_get_root (self->item_manager);
  pos = 0;

  while (cell)
    {
      tmp = gtk_rb_tree_node_get_left (cell);
      if (tmp)
        {
          CellAugment *aug = gtk_list_item_manager_get_item_augment (self->item_manager, tmp);
          if (y < aug->size)
            {
              cell = tmp;
              continue;
            }
          y -= aug->size;
          pos += aug->parent.n_items;
        }

      if (y < cell->size)
        break;
      y -= cell->size;
      pos += cell->parent.n_items;

      cell = gtk_rb_tree_node_get_right (cell);
    }

  if (cell == NULL)
    {
      if (position)
        *position = 0;
      if (offset)
        *offset = 0;
      if (size)
        *size = 0;
      return NULL;
    }

  /* We know have the (range of) cell(s) that contains this offset.
   * Now for the hard part of computing which index this actually is.
   */
  if (offset || position || size)
    {
      guint n_items = cell->parent.n_items;
      guint no_widget_rows, skip;

      /* skip remaining items at end of row */
      if (pos % self->n_columns)
        {
276
          skip = self->n_columns - pos % self->n_columns;
277 278 279 280 281 282 283 284 285 286 287
          if (n_items <= skip)
            {
              g_warning ("ran out of items");
              if (position)
                *position = 0;
              if (offset)
                *offset = 0;
              if (size)
                *size = 0;
              return NULL;
            }
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
          n_items -= skip;
          pos += skip;
        }

      /* Skip all the rows this index doesn't go into */
      no_widget_rows = (n_items - 1) / self->n_columns;
      skip = MIN (y / self->unknown_row_height, no_widget_rows);
      y -= skip * self->unknown_row_height;
      pos += self->n_columns * skip;

      if (position)
        *position = pos;
      if (offset)
        *offset = y;
      if (size)
        {
          if (skip < no_widget_rows)
            *size = self->unknown_row_height;
          else
            *size = cell->size - no_widget_rows * self->unknown_row_height;
        }
    }

  return cell;
}

static gboolean
315 316
gtk_grid_view_get_allocation_along (GtkListBase *base,
                                    guint        pos,
317 318 319
                                    int         *offset,
                                    int         *size)
{
320
  GtkGridView *self = GTK_GRID_VIEW (base);
321 322 323 324 325
  Cell *cell, *tmp;
  int y;

  cell = gtk_list_item_manager_get_root (self->item_manager);
  y = 0;
326
  pos -= pos % self->n_columns;
327 328 329 330 331 332 333

  while (cell)
    {
      tmp = gtk_rb_tree_node_get_left (cell);
      if (tmp)
        {
          CellAugment *aug = gtk_list_item_manager_get_item_augment (self->item_manager, tmp);
334
          if (pos < aug->parent.n_items)
335 336 337 338
            {
              cell = tmp;
              continue;
            }
339
          pos -= aug->parent.n_items;
340 341 342
          y += aug->size;
        }

343
      if (pos < cell->parent.n_items)
344 345
        break;
      y += cell->size;
346
      pos -= cell->parent.n_items;
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368

      cell = gtk_rb_tree_node_get_right (cell);
    }

  if (cell == NULL)
    {
      if (offset)
        *offset = 0;
      if (size)
        *size = 0;
      return FALSE;
    }

  /* We know have the (range of) cell(s) that contains this offset.
   * Now for the hard part of computing which index this actually is.
   */
  if (offset || size)
    {
      guint n_items = cell->parent.n_items;
      guint skip;

      /* skip remaining items at end of row */
369
      if (pos % self->n_columns)
370
        {
371
          skip = pos % self->n_columns;
372
          n_items -= skip;
373
          pos -= skip;
374 375 376
        }

      /* Skip all the rows this index doesn't go into */
377
      skip = pos / self->n_columns;
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
      n_items -= skip * self->n_columns;
      y += skip * self->unknown_row_height;

      if (offset)
        *offset = y;
      if (size)
        {
          if (n_items > self->n_columns)
            *size = self->unknown_row_height;
          else
            *size = cell->size - skip * self->unknown_row_height;
        }
    }

  return TRUE;
}

395 396 397 398 399
static gboolean
gtk_grid_view_get_allocation_across (GtkListBase *base,
                                     guint        pos,
                                     int         *offset,
                                     int         *size)
400
{
401 402
  GtkGridView *self = GTK_GRID_VIEW (base);
  guint start;
403

404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
  pos %= self->n_columns;
  start = ceil (self->column_width * pos);

  if (offset)
    *offset = start;
  if (size)
    *size = ceil (self->column_width * (pos + 1)) - start;

  return TRUE;
}

static gboolean
gtk_grid_view_get_position_from_allocation (GtkListBase           *base,
                                            int                    across,
                                            int                    along,
                                            guint                 *position,
                                            cairo_rectangle_int_t *area)
{
  GtkGridView *self = GTK_GRID_VIEW (base);
  int offset, size;
  guint pos, n_items;

  if (across >= self->column_width * self->n_columns)
    return FALSE;

429
  n_items = gtk_list_base_get_n_items (base);
430 431 432 433 434 435 436 437 438 439
  if (!gtk_grid_view_get_cell_at_y (self,
                                    along,
                                    &pos,
                                    &offset,
                                    &size))
    return FALSE;

  pos += floor (across / self->column_width);

  if (pos >= n_items)
440
    {
441 442 443 444 445 446 447 448 449 450 451 452 453
      /* Ugh, we're in the last row and don't have enough items
       * to fill the row.
       * Do it the hard way then... */
      pos = n_items - 1;
    }

  *position = pos;
  if (area)
    {
      area->x = ceil (self->column_width * (pos % self->n_columns));
      area->width = ceil (self->column_width * (1 + pos % self->n_columns)) - area->x;
      area->y = along - offset;
      area->height = size;
454
    }
455 456

  return TRUE;
457 458
}

459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
static GtkBitset *
gtk_grid_view_get_items_in_rect (GtkListBase        *base,
                                 const GdkRectangle *rect)
{
  GtkGridView *self = GTK_GRID_VIEW (base);
  guint first_row, last_row, first_column, last_column, n_items;
  GtkBitset *result;

  result = gtk_bitset_new_empty ();

  n_items = gtk_list_base_get_n_items (base);
  if (n_items == 0)
    return result;

  first_column = floor (rect->x / self->column_width);
  last_column = floor ((rect->x + rect->width) / self->column_width);
  if (!gtk_grid_view_get_cell_at_y (self, rect->y, &first_row, NULL, NULL))
    first_row = rect->y < 0 ? 0 : n_items - 1;
  if (!gtk_grid_view_get_cell_at_y (self, rect->y + rect->height, &last_row, NULL, NULL))
    last_row = rect->y < 0 ? 0 : n_items - 1;

  gtk_bitset_add_rectangle (result,
                            first_row + first_column,
                            last_column - first_column + 1,
                            (last_row - first_row) / self->n_columns + 1,
                            self->n_columns);

  return result;
}

489 490 491 492
static guint
gtk_grid_view_move_focus_along (GtkListBase *base,
                                guint        pos,
                                int          steps)
Benjamin Otte's avatar
Benjamin Otte committed
493
{
494
  GtkGridView *self = GTK_GRID_VIEW (base);
Benjamin Otte's avatar
Benjamin Otte committed
495

496
  steps *= self->n_columns;
Benjamin Otte's avatar
Benjamin Otte committed
497

498
  if (steps < 0)
Benjamin Otte's avatar
Benjamin Otte committed
499
    {
500 501 502 503 504
      if (pos >= self->n_columns)
        pos -= MIN (pos, -steps);
    }
  else
    {
505
      guint n_items = gtk_list_base_get_n_items (base);
506 507
      if (n_items / self->n_columns > pos / self->n_columns)
        pos += MIN (n_items - pos - 1, steps);
Benjamin Otte's avatar
Benjamin Otte committed
508 509
    }

510 511
  return pos;
}
Benjamin Otte's avatar
Benjamin Otte committed
512

513 514 515 516 517 518 519 520
static guint
gtk_grid_view_move_focus_across (GtkListBase *base,
                                 guint        pos,
                                 int          steps)
{
  if (steps < 0)
    return pos - MIN (pos, -steps);
  else
Benjamin Otte's avatar
Benjamin Otte committed
521
    {
522
      guint n_items = gtk_list_base_get_n_items (base);
523
      pos += MIN (n_items - pos - 1, steps);
Benjamin Otte's avatar
Benjamin Otte committed
524 525
    }

526
  return pos;
Benjamin Otte's avatar
Benjamin Otte committed
527 528
}

529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551
static int
compare_ints (gconstpointer first,
              gconstpointer second)
{
  return *(int *) first - *(int *) second;
}

static int
gtk_grid_view_get_unknown_row_size (GtkGridView *self,
                                    GArray      *heights)
{
  g_return_val_if_fail (heights->len > 0, 0);

  /* return the median and hope rows are generally uniform with few outliers */
  g_array_sort (heights, compare_ints);

  return g_array_index (heights, int, heights->len / 2);
}

static void
gtk_grid_view_measure_column_size (GtkGridView *self,
                                   int         *minimum,
                                   int         *natural)
552
{
553 554 555 556 557 558
  GtkOrientation opposite;
  Cell *cell;
  int min, nat, child_min, child_nat;

  min = 0;
  nat = 0;
559
  opposite = gtk_list_base_get_opposite_orientation (GTK_LIST_BASE (self));
560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602

  for (cell = gtk_list_item_manager_get_first (self->item_manager);
       cell != NULL;
       cell = gtk_rb_tree_node_get_next (cell))
    {
      /* ignore unavailable cells */
      if (cell->parent.widget == NULL)
        continue;

      gtk_widget_measure (cell->parent.widget,
                          opposite, -1,
                          &child_min, &child_nat, NULL, NULL);
      min = MAX (min, child_min);
      nat = MAX (nat, child_nat);
    }

  *minimum = min;
  *natural = nat;
}

static void
gtk_grid_view_measure_across (GtkWidget *widget,
                              int        for_size,
                              int       *minimum,
                              int       *natural)
{
  GtkGridView *self = GTK_GRID_VIEW (widget);

  gtk_grid_view_measure_column_size (self, minimum, natural);

  *minimum *= self->min_columns;
  *natural *= self->max_columns;
}

static guint
gtk_grid_view_compute_n_columns (GtkGridView *self,
                                 guint        for_size,
                                 int          min,
                                 int          nat)
{
  guint n_columns;

  /* rounding down is exactly what we want here, so int division works */
603 604
  if (gtk_list_base_get_scroll_policy (GTK_LIST_BASE (self),
                                       gtk_list_base_get_opposite_orientation (GTK_LIST_BASE (self))) == GTK_SCROLL_MINIMUM)
605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620
    n_columns = for_size / MAX (1, min);
  else
    n_columns = for_size / MAX (1, nat);

  n_columns = CLAMP (n_columns, self->min_columns, self->max_columns);

  return n_columns;
}

static void
gtk_grid_view_measure_list (GtkWidget *widget,
                            int        for_size,
                            int       *minimum,
                            int       *natural)
{
  GtkGridView *self = GTK_GRID_VIEW (widget);
621
  GtkScrollablePolicy scroll_policy;
622 623 624 625 626 627 628
  Cell *cell;
  int height, row_height, child_min, child_nat, column_size, col_min, col_nat;
  gboolean measured;
  GArray *heights;
  guint n_unknown, n_columns;
  guint i;

629
  scroll_policy = gtk_list_base_get_scroll_policy (GTK_LIST_BASE (self), gtk_list_base_get_orientation (GTK_LIST_BASE (self)));
630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648
  heights = g_array_new (FALSE, FALSE, sizeof (int));
  n_unknown = 0;
  height = 0;

  gtk_grid_view_measure_column_size (self, &col_min, &col_nat);
  for_size = MAX (for_size, col_min * (int) self->min_columns);
  n_columns = gtk_grid_view_compute_n_columns (self, for_size, col_min, col_nat);
  column_size = for_size / n_columns;

  i = 0;
  row_height = 0;
  measured = FALSE;
  for (cell = gtk_list_item_manager_get_first (self->item_manager);
       cell != NULL;
       cell = gtk_rb_tree_node_get_next (cell))
    {
      if (cell->parent.widget)
        {
          gtk_widget_measure (cell->parent.widget,
649 650
                              gtk_list_base_get_orientation (GTK_LIST_BASE (self)),
                              column_size,
651
                              &child_min, &child_nat, NULL, NULL);
652
          if (scroll_policy == GTK_SCROLL_MINIMUM)
653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693
            row_height = MAX (row_height, child_min);
          else
            row_height = MAX (row_height, child_nat);
          measured = TRUE;
        }
      
      i += cell->parent.n_items;

      if (i >= n_columns)
        {
          if (measured)
            {
              g_array_append_val (heights, row_height);
              i -= n_columns;
              height += row_height;
              measured = FALSE;
              row_height = 0;
            }
          n_unknown += i / n_columns;
          i %= n_columns;
        }
    }

  if (i > 0)
    {
      if (measured)
        {
          g_array_append_val (heights, row_height);
          height += row_height;
        }
      else
        n_unknown++;
    }

  if (n_unknown)
    height += n_unknown * gtk_grid_view_get_unknown_row_size (self, heights);

  g_array_free (heights, TRUE);

  *minimum = height;
  *natural = height;
694 695 696 697 698 699 700 701 702 703 704 705 706
}

static void
gtk_grid_view_measure (GtkWidget      *widget,
                       GtkOrientation  orientation,
                       int             for_size,
                       int            *minimum,
                       int            *natural,
                       int            *minimum_baseline,
                       int            *natural_baseline)
{
  GtkGridView *self = GTK_GRID_VIEW (widget);

707
  if (orientation == gtk_list_base_get_orientation (GTK_LIST_BASE (self)))
708 709 710
    gtk_grid_view_measure_list (widget, for_size, minimum, natural);
  else
    gtk_grid_view_measure_across (widget, for_size, minimum, natural);
711 712 713
}

static void
714 715
cell_set_size (Cell  *cell,
               guint  size)
716
{
717 718 719 720 721
  if (cell->size == size)
    return;

  cell->size = size;
  gtk_rb_tree_node_mark_dirty (cell);
722 723
}

724 725 726 727 728 729 730 731 732 733 734 735 736
static int
gtk_grid_view_compute_total_height (GtkGridView *self)
{
  Cell *cell;
  CellAugment *aug;

  cell = gtk_list_item_manager_get_root (self->item_manager);
  if (cell == NULL)
    return 0;
  aug = gtk_list_item_manager_get_item_augment (self->item_manager, cell);
  return aug->size;
}

737
static void
738 739 740 741
gtk_grid_view_size_allocate (GtkWidget *widget,
                             int        width,
                             int        height,
                             int        baseline)
742
{
743 744 745
  GtkGridView *self = GTK_GRID_VIEW (widget);
  Cell *cell, *start;
  GArray *heights;
746
  int min_row_height, row_height, col_min, col_nat;
747
  GtkOrientation orientation, opposite_orientation;
748
  GtkScrollablePolicy scroll_policy;
749 750 751 752
  gboolean known;
  int x, y;
  guint i;

753 754 755
  orientation = gtk_list_base_get_orientation (GTK_LIST_BASE (self));
  scroll_policy = gtk_list_base_get_scroll_policy (GTK_LIST_BASE (self), orientation);
  opposite_orientation = OPPOSITE_ORIENTATION (orientation);
756
  min_row_height = ceil ((double) height / GTK_GRID_VIEW_MAX_VISIBLE_ROWS);
757 758 759

  /* step 0: exit early if list is empty */
  if (gtk_list_item_manager_get_root (self->item_manager) == NULL)
760 761
    return;

762 763 764
  /* step 1: determine width of the list */
  gtk_grid_view_measure_column_size (self, &col_min, &col_nat);
  self->n_columns = gtk_grid_view_compute_n_columns (self, 
765
                                                     orientation == GTK_ORIENTATION_VERTICAL ? width : height,
766
                                                     col_min, col_nat);
767
  self->column_width = (orientation == GTK_ORIENTATION_VERTICAL ? width : height) / self->n_columns;
768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785
  self->column_width = MAX (self->column_width, col_min);

  /* step 2: determine height of known rows */
  heights = g_array_new (FALSE, FALSE, sizeof (int));

  i = 0;
  row_height = 0;
  start = NULL;
  for (cell = gtk_list_item_manager_get_first (self->item_manager);
       cell != NULL;
       cell = gtk_rb_tree_node_get_next (cell))
    {
      if (i == 0)
        start = cell;
      
      if (cell->parent.widget)
        {
          int min, nat, size;
786 787
          gtk_widget_measure (cell->parent.widget,
                              gtk_list_base_get_orientation (GTK_LIST_BASE (self)),
788 789
                              self->column_width,
                              &min, &nat, NULL, NULL);
790
          if (scroll_policy == GTK_SCROLL_MINIMUM)
791 792 793
            size = min;
          else
            size = nat;
794
          size = MAX (size, min_row_height);
795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813
          g_array_append_val (heights, size);
          row_height = MAX (row_height, size);
        }
      cell_set_size (cell, 0);
      i += cell->parent.n_items;

      if (i >= self->n_columns)
        {
          i %= self->n_columns;

          cell_set_size (start, start->size + row_height);
          start = cell;
          row_height = 0;
        }
    }
  if (i > 0)
    cell_set_size (start, start->size + row_height);

  /* step 3: determine height of rows with only unknown items */
814
  self->unknown_row_height = gtk_grid_view_get_unknown_row_size (self, heights);
815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832
  g_array_free (heights, TRUE);

  i = 0;
  known = FALSE;
  for (start = cell = gtk_list_item_manager_get_first (self->item_manager);
       cell != NULL;
       cell = gtk_rb_tree_node_get_next (cell))
    {
      if (i == 0)
        start = cell;

      if (cell->parent.widget)
        known = TRUE;

      i += cell->parent.n_items;
      if (i >= self->n_columns)
        {
          if (!known)
833
            cell_set_size (start, start->size + self->unknown_row_height);
834 835 836 837 838 839

          i -= self->n_columns;
          known = FALSE;

          if (i >= self->n_columns)
            {
840
              cell_set_size (cell, cell->size + self->unknown_row_height * (i / self->n_columns));
841 842 843 844 845 846
              i %= self->n_columns;
            }
          start = cell;
        }
    }
  if (i > 0 && !known)
847
    cell_set_size (start, start->size + self->unknown_row_height);
848 849

  /* step 4: update the adjustments */
850 851 852 853 854 855
  gtk_list_base_update_adjustments (GTK_LIST_BASE (self),
                                    self->column_width * self->n_columns,
                                    gtk_grid_view_compute_total_height (self),
                                    gtk_widget_get_size (widget, opposite_orientation),
                                    gtk_widget_get_size (widget, orientation),
                                    &x, &y);
856

857 858 859
  /* step 5: run the size_allocate loop */
  x = -x;
  y = -y;
860 861
  i = 0;
  row_height = 0;
862

863 864 865 866 867 868
  for (cell = gtk_list_item_manager_get_first (self->item_manager);
       cell != NULL;
       cell = gtk_rb_tree_node_get_next (cell))
    {
      if (cell->parent.widget)
        {
869 870
          row_height += cell->size;

871
          gtk_list_base_size_allocate_child (GTK_LIST_BASE (self),
872 873 874 875 876
                                             cell->parent.widget,
                                             x + ceil (self->column_width * i),
                                             y,
                                             ceil (self->column_width * (i + 1)) - ceil (self->column_width * i),
                                             row_height);
877 878 879 880 881 882 883
          i++;
          if (i >= self->n_columns)
            {
              y += row_height;
              i -= self->n_columns;
              row_height = 0;
            }
884 885 886 887
        }
      else
        {
          i += cell->parent.n_items;
888 889
          /* skip remaining row if we didn't start one */
          if (i > cell->parent.n_items && i >= self->n_columns)
890 891 892
            {
              i -= self->n_columns;
              y += row_height;
893 894
              row_height = 0;
            }
895

896 897 898 899 900 901 902 903 904 905 906 907 908
          row_height += cell->size;

          /* skip rows that are completely contained by this cell */
          if (i >= self->n_columns)
            {
              guint unknown_rows, unknown_height;

              unknown_rows = i / self->n_columns;
              unknown_height = unknown_rows * self->unknown_row_height;
              row_height -= unknown_height;
              y += unknown_height;
              i %= self->n_columns;
              g_assert (row_height >= 0);
909 910 911
            }
        }
    }
912 913

  gtk_list_base_allocate_rubberband (GTK_LIST_BASE (widget));
914 915 916 917 918 919 920
}

static void
gtk_grid_view_dispose (GObject *object)
{
  GtkGridView *self = GTK_GRID_VIEW (object);

921
  self->item_manager = NULL;
Benjamin Otte's avatar
Benjamin Otte committed
922

923 924 925 926 927 928 929 930 931 932 933 934 935
  G_OBJECT_CLASS (gtk_grid_view_parent_class)->dispose (object);
}

static void
gtk_grid_view_get_property (GObject    *object,
                            guint       property_id,
                            GValue     *value,
                            GParamSpec *pspec)
{
  GtkGridView *self = GTK_GRID_VIEW (object);

  switch (property_id)
    {
Benjamin Otte's avatar
Benjamin Otte committed
936 937 938 939
    case PROP_FACTORY:
      g_value_set_object (value, gtk_list_item_manager_get_factory (self->item_manager));
      break;

940 941 942 943 944 945 946 947
    case PROP_MAX_COLUMNS:
      g_value_set_uint (value, self->max_columns);
      break;

    case PROP_MIN_COLUMNS:
      g_value_set_uint (value, self->min_columns);
      break;

948
    case PROP_MODEL:
949
      g_value_set_object (value, gtk_list_base_get_model (GTK_LIST_BASE (self)));
950 951
      break;

952 953 954 955
    case PROP_SINGLE_CLICK_ACTIVATE:
      g_value_set_boolean (value, gtk_list_item_manager_get_single_click_activate (self->item_manager));
      break;

Matthias Clasen's avatar
Matthias Clasen committed
956 957 958 959
    case PROP_ENABLE_RUBBERBAND:
      g_value_set_boolean (value, gtk_list_base_get_enable_rubberband (GTK_LIST_BASE (self)));
      break;

960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
      break;
    }
}

static void
gtk_grid_view_set_property (GObject      *object,
                            guint         property_id,
                            const GValue *value,
                            GParamSpec   *pspec)
{
  GtkGridView *self = GTK_GRID_VIEW (object);

  switch (property_id)
    {
Benjamin Otte's avatar
Benjamin Otte committed
976 977 978 979
    case PROP_FACTORY:
      gtk_grid_view_set_factory (self, g_value_get_object (value));
      break;

980 981 982 983 984 985 986
    case PROP_MAX_COLUMNS:
      gtk_grid_view_set_max_columns (self, g_value_get_uint (value));
      break;

    case PROP_MIN_COLUMNS:
      gtk_grid_view_set_min_columns (self, g_value_get_uint (value));
      break;
987
 
988 989 990 991
    case PROP_MODEL:
      gtk_grid_view_set_model (self, g_value_get_object (value));
      break;

992 993 994 995
    case PROP_SINGLE_CLICK_ACTIVATE:
      gtk_grid_view_set_single_click_activate (self, g_value_get_boolean (value));
      break;

Matthias Clasen's avatar
Matthias Clasen committed
996 997 998 999
    case PROP_ENABLE_RUBBERBAND:
      gtk_grid_view_set_enable_rubberband (self, g_value_get_boolean (value));
      break;

1000 1001 1002 1003 1004 1005
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
      break;
    }
}

Benjamin Otte's avatar
Benjamin Otte committed
1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017
static void
gtk_grid_view_activate_item (GtkWidget  *widget,
                             const char *action_name,
                             GVariant   *parameter)
{
  GtkGridView *self = GTK_GRID_VIEW (widget);
  guint pos;

  if (!g_variant_check_format_string (parameter, "u", FALSE))
    return;

  g_variant_get (parameter, "u", &pos);
1018
  if (pos >= gtk_list_base_get_n_items (GTK_LIST_BASE (self)))
Benjamin Otte's avatar
Benjamin Otte committed
1019 1020 1021 1022 1023
    return;

  g_signal_emit (widget, signals[ACTIVATE], 0, pos);
}

1024 1025 1026
static void
gtk_grid_view_class_init (GtkGridViewClass *klass)
{
1027
  GtkListBaseClass *list_base_class = GTK_LIST_BASE_CLASS (klass);
1028 1029
  GtkWidgetClass *widget_class = GTK_WIDGET_CLASS (klass);
  GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
1030

1031
  list_base_class->list_item_name = "child";
1032
  list_base_class->list_item_role = GTK_ACCESSIBLE_ROLE_GRID_CELL;
1033 1034 1035
  list_base_class->list_item_size = sizeof (Cell);
  list_base_class->list_item_augment_size = sizeof (CellAugment);
  list_base_class->list_item_augment_func = cell_augment;
1036 1037
  list_base_class->get_allocation_along = gtk_grid_view_get_allocation_along;
  list_base_class->get_allocation_across = gtk_grid_view_get_allocation_across;
1038
  list_base_class->get_items_in_rect = gtk_grid_view_get_items_in_rect;
1039
  list_base_class->get_position_from_allocation = gtk_grid_view_get_position_from_allocation;
1040 1041
  list_base_class->move_focus_along = gtk_grid_view_move_focus_along;
  list_base_class->move_focus_across = gtk_grid_view_move_focus_across;
1042 1043 1044 1045 1046 1047 1048 1049

  widget_class->measure = gtk_grid_view_measure;
  widget_class->size_allocate = gtk_grid_view_size_allocate;

  gobject_class->dispose = gtk_grid_view_dispose;
  gobject_class->get_property = gtk_grid_view_get_property;
  gobject_class->set_property = gtk_grid_view_set_property;

Benjamin Otte's avatar
Benjamin Otte committed
1050
  /**
Matthias Clasen's avatar
Matthias Clasen committed
1051
   * GtkGridView:factory: (attributes org.gtk.Property.get=gtk_grid_view_get_factory org.gtk.Property.set=gtk_grid_view_set_factory)
Benjamin Otte's avatar
Benjamin Otte committed
1052
   *
Matthias Clasen's avatar
Matthias Clasen committed
1053
   * Factory for populating list items.
Benjamin Otte's avatar
Benjamin Otte committed
1054 1055 1056 1057 1058 1059 1060 1061 1062
   */
  properties[PROP_FACTORY] =
    g_param_spec_object ("factory",
                         P_("Factory"),
                         P_("Factory for populating list items"),
                         GTK_TYPE_LIST_ITEM_FACTORY,
                         G_PARAM_READWRITE | G_PARAM_EXPLICIT_NOTIFY | G_PARAM_STATIC_STRINGS);


1063
  /**
Matthias Clasen's avatar
Matthias Clasen committed
1064
   * GtkGridView:max-columns: (attributes org.gtk.Property.get=gtk_grid_view_get_max_columns org.gtk.Property.set=gtk_grid_view_set_max_columns)
1065
   *
Matthias Clasen's avatar
Matthias Clasen committed
1066
   * Maximum number of columns per row.
1067
   *
Matthias Clasen's avatar
Matthias Clasen committed
1068 1069
   * If this number is smaller than [property@Gtk.GridView:min-columns],
   * that value is used instead.
1070 1071 1072 1073 1074 1075 1076 1077 1078
   */
  properties[PROP_MAX_COLUMNS] =
    g_param_spec_uint ("max-columns",
                       P_("Max columns"),
                       P_("Maximum number of columns per row"),
                       1, G_MAXUINT, DEFAULT_MAX_COLUMNS,
                       G_PARAM_READWRITE | G_PARAM_EXPLICIT_NOTIFY | G_PARAM_STATIC_STRINGS);

  /**
Matthias Clasen's avatar
Matthias Clasen committed
1079
   * GtkGridView:min-columns: (attributes org.gtk.Property.get=gtk_grid_view_get_min_columns org.gtk.Property.set=gtk_grid_view_set_min_columns)
1080
   *
Matthias Clasen's avatar
Matthias Clasen committed
1081
   * Minimum number of columns per row.
1082 1083 1084 1085 1086 1087 1088 1089
   */
  properties[PROP_MIN_COLUMNS] =
    g_param_spec_uint ("min-columns",
                       P_("Min columns"),
                       P_("Minimum number of columns per row"),
                       1, G_MAXUINT, 1,
                       G_PARAM_READWRITE | G_PARAM_EXPLICIT_NOTIFY | G_PARAM_STATIC_STRINGS);

1090
  /**
Matthias Clasen's avatar
Matthias Clasen committed
1091
   * GtkGridView:model: (attributes org.gtk.Property.get=gtk_grid_view_get_model org.gtk.Property.set=gtk_grid_view_set_model)
1092
   *
Matthias Clasen's avatar
Matthias Clasen committed
1093
   * Model for the items displayed.
1094 1095 1096 1097 1098
   */
  properties[PROP_MODEL] =
    g_param_spec_object ("model",
                         P_("Model"),
                         P_("Model for the items displayed"),
1099
                         GTK_TYPE_SELECTION_MODEL,
1100 1101
                         G_PARAM_READWRITE | G_PARAM_EXPLICIT_NOTIFY | G_PARAM_STATIC_STRINGS);

1102
  /**
Matthias Clasen's avatar
Matthias Clasen committed
1103
   * GtkGridView:single-click-activate: (attributes org.gtk.Property.get=gtk_grid_view_get_single_click_activate org.gtk.Property.set=gtk_grid_view_set_single_click_activate)
1104
   *
Matthias Clasen's avatar
Matthias Clasen committed
1105
   * Activate rows on single click and select them on hover.
1106 1107 1108 1109 1110 1111 1112 1113
   */
  properties[PROP_SINGLE_CLICK_ACTIVATE] =
    g_param_spec_boolean ("single-click-activate",
                          P_("Single click activate"),
                          P_("Activate rows on single click"),
                          FALSE,
                          G_PARAM_READWRITE | G_PARAM_EXPLICIT_NOTIFY);

Matthias Clasen's avatar
Matthias Clasen committed
1114
  /**
Matthias Clasen's avatar
Matthias Clasen committed
1115
   * GtkGridView:enable-rubberband: (attributes org.gtk.Property.get=gtk_grid_view_get_enable_rubberband org.gtk.Property.set=gtk_grid_view_set_enable_rubberband)
Matthias Clasen's avatar
Matthias Clasen committed
1116
   *
Matthias Clasen's avatar
Matthias Clasen committed
1117
   * Allow rubberband selection.
Matthias Clasen's avatar
Matthias Clasen committed
1118 1119 1120 1121 1122 1123 1124 1125
   */
  properties[PROP_ENABLE_RUBBERBAND] =
    g_param_spec_boolean ("enable-rubberband",
                          P_("Enable rubberband selection"),
                          P_("Allow selecting items by dragging with the mouse"),
                          FALSE,
                          G_PARAM_READWRITE | G_PARAM_EXPLICIT_NOTIFY);

1126 1127
  g_object_class_install_properties (gobject_class, N_PROPS, properties);

Benjamin Otte's avatar
Benjamin Otte committed
1128 1129
  /**
   * GtkGridView::activate:
Matthias Clasen's avatar
Matthias Clasen committed
1130
   * @self: The `GtkGridView`
Benjamin Otte's avatar
Benjamin Otte committed
1131 1132
   * @position: position of item to activate
   *
Matthias Clasen's avatar
Matthias Clasen committed
1133
   * Emitted when a cell has been activated by the user,
Benjamin Otte's avatar
Benjamin Otte committed
1134 1135 1136
   * usually via activating the GtkGridView|list.activate-item action.
   *
   * This allows for a convenient way to handle activation in a gridview.
Matthias Clasen's avatar
Matthias Clasen committed
1137 1138
   * See [property@Gtk.ListItem:activatable] for details on how to use
   * this signal.
Benjamin Otte's avatar
Benjamin Otte committed
1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156
   */
  signals[ACTIVATE] =
    g_signal_new (I_("activate"),
                  G_TYPE_FROM_CLASS (gobject_class),
                  G_SIGNAL_RUN_LAST,
                  0,
                  NULL, NULL,
                  g_cclosure_marshal_VOID__UINT,
                  G_TYPE_NONE, 1,
                  G_TYPE_UINT);
  g_signal_set_va_marshaller (signals[ACTIVATE],
                              G_TYPE_FROM_CLASS (gobject_class),
                              g_cclosure_marshal_VOID__UINTv);

  /**
   * GtkGridView|list.activate-item:
   * @position: position of item to activate
   *
Matthias Clasen's avatar
Matthias Clasen committed
1157 1158
   * Activates the item given in @position by emitting the
   * [signal@Gtk.GridView::activate] signal.
Benjamin Otte's avatar
Benjamin Otte committed
1159 1160 1161 1162 1163 1164
   */
  gtk_widget_class_install_action (widget_class,
                                   "list.activate-item",
                                   "u",
                                   gtk_grid_view_activate_item);

1165
  gtk_widget_class_set_css_name (widget_class, I_("gridview"));
1166
  gtk_widget_class_set_accessible_role (widget_class, GTK_ACCESSIBLE_ROLE_GRID);
1167 1168 1169 1170 1171
}

static void
gtk_grid_view_init (GtkGridView *self)
{
1172
  self->item_manager = gtk_list_base_get_manager (GTK_LIST_BASE (self));
Benjamin Otte's avatar
Benjamin Otte committed
1173

1174 1175
  self->min_columns = 1;
  self->max_columns = DEFAULT_MAX_COLUMNS;
1176
  self->n_columns = 1;
1177 1178 1179 1180

  gtk_list_base_set_anchor_max_widgets (GTK_LIST_BASE (self),
                                        self->max_columns * GTK_GRID_VIEW_MAX_VISIBLE_ROWS,
                                        self->max_columns);
Timm Bäder's avatar
Timm Bäder committed
1181 1182

  gtk_widget_add_css_class (GTK_WIDGET (self), "view");
1183 1184 1185 1186
}

/**
 * gtk_grid_view_new:
1187 1188
 * @model: (allow-none) (transfer full): the model to use, or %NULL
 * @factory: (allow-none) (transfer full): The factory to populate items with, or %NULL
Benjamin Otte's avatar
Benjamin Otte committed
1189
 *
Matthias Clasen's avatar
Matthias Clasen committed
1190
 * Creates a new `GtkGridView` that uses the given @factory for
Benjamin Otte's avatar
Benjamin Otte committed
1191 1192 1193
 * mapping items to widgets.
 *
 * The function takes ownership of the
1194
 * arguments, so you can write code like
Matthias Clasen's avatar
Matthias Clasen committed
1195 1196 1197
 * ```c
 * grid_view = gtk_grid_view_new (create_model (),
 *   gtk_builder_list_item_factory_new_from_resource ("/resource.ui"));
Benjamin Otte's avatar
Benjamin Otte committed
1198 1199
 * ```
 *
Matthias Clasen's avatar
Matthias Clasen committed
1200 1201
 * Returns: a new `GtkGridView` using the given @model and @factory
 */
Benjamin Otte's avatar
Benjamin Otte committed
1202
GtkWidget *
1203 1204
gtk_grid_view_new (GtkSelectionModel  *model,
                   GtkListItemFactory *factory)
Benjamin Otte's avatar
Benjamin Otte committed
1205 1206 1207
{
  GtkWidget *result;

1208
  g_return_val_if_fail (model == NULL || GTK_IS_SELECTION_MODEL (model), NULL);
1209
  g_return_val_if_fail (factory == NULL || GTK_IS_LIST_ITEM_FACTORY (factory), NULL);
Benjamin Otte's avatar
Benjamin Otte committed
1210 1211

  result = g_object_new (GTK_TYPE_GRID_VIEW,
1212
                         "model", model,
Benjamin Otte's avatar
Benjamin Otte committed
1213 1214 1215
                         "factory", factory,
                         NULL);

1216 1217 1218
  /* consume the references */
  g_clear_object (&model);
  g_clear_object (&factory);
Benjamin Otte's avatar
Benjamin Otte committed
1219