]> Pileus Git - ~andy/gtk/blob - gtk/gtksizerequest.c
GtkWidget: add adjust_size_request adjust_size_allocation virtual funcs
[~andy/gtk] / gtk / gtksizerequest.c
1 /* gtksizerequest.c
2  * Copyright (C) 2007-2010 Openismus GmbH
3  *
4  * Authors:
5  *      Mathias Hasselmann <mathias@openismus.com>
6  *      Tristan Van Berkom <tristan.van.berkom@gmail.com>
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Library General Public
10  * License as published by the Free Software Foundation; either
11  * version 2 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Library General Public License for more details.
17  *
18  * You should have received a copy of the GNU Library General Public
19  * License along with this library; if not, write to the
20  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
21  * Boston, MA 02111-1307, USA.
22  */
23
24
25 /**
26  * SECTION:gtksizerequest
27  * @Short_Description: Height-for-width geometry management
28  * @Title: GtkSizeRequest
29  *
30  * The GtkSizeRequest interface is GTK+'s height-for-width (and width-for-height)
31  * geometry management system. Height-for-width means that a widget can
32  * change how much vertical space it needs, depending on the amount
33  * of horizontal space that it is given (and similar for width-for-height).
34  * The most common example is a label that reflows to fill up the available
35  * width, wraps to fewer lines, and therefore needs less height.
36  *
37  * GTK+'s traditional two-pass <link linkend="size-allocation">size-allocation</link>
38  * algorithm does not allow this flexibility. #GtkWidget provides a default
39  * implementation of the #GtkSizeRequest interface for existing widgets,
40  * which always requests the same height, regardless of the available width.
41  *
42  * <refsect2>
43  * <title>Implementing GtkSizeRequest</title>
44  * <para>
45  * Some important things to keep in mind when implementing
46  * the GtkSizeRequest interface and when using it in container
47  * implementations.
48  *
49  * The geometry management system will query a logical hierarchy in
50  * only one orientation at a time. When widgets are initially queried
51  * for their minimum sizes it is generally done in a dual pass
52  * in the direction chosen by the toplevel.
53  *
54  * For instance when queried in the normal height-for-width mode:
55  * First the default minimum and natural width for each widget
56  * in the interface will computed and collectively returned to
57  * the toplevel by way of gtk_size_request_get_width().
58  * Next, the toplevel will use the minimum width to query for the
59  * minimum height contextual to that width using
60  * gtk_size_request_get_height_for_width(), which will also be a
61  * highly recursive operation. This minimum-for-minimum size can be
62  * used to set the minimum size constraint on the toplevel.
63  *
64  * When allocating, each container can use the minimum and natural
65  * sizes reported by their children to allocate natural sizes and
66  * expose as much content as possible with the given allocation.
67  *
68  * That means that the request operation at allocation time will
69  * usually fire again in contexts of different allocated sizes than
70  * the ones originally queried for. #GtkSizeRequest caches a
71  * small number of results to avoid re-querying for the same
72  * allocated size in one allocation cycle.
73  *
74  * A widget that does not actually do height-for-width
75  * or width-for-height size negotiations only has to implement
76  * get_width() and get_height().
77  *
78  * If a widget does move content around to smartly use up the
79  * allocated size, then it must support the request properly in
80  * both orientations; even if the request only makes sense in
81  * one orientation.
82  *
83  * For instance, a GtkLabel that does height-for-width word wrapping
84  * will not expect to have get_height() called because that
85  * call is specific to a width-for-height request, in this case the
86  * label must return the heights contextual to its minimum possible
87  * width. By following this rule any widget that handles height-for-width
88  * or width-for-height requests will always be allocated at least
89  * enough space to fit its own content.
90  * </para>
91  * </refsect2>
92  */
93
94
95 #include <config.h>
96 #include "gtksizerequest.h"
97 #include "gtksizegroup.h"
98 #include "gtkprivate.h"
99 #include "gtkintl.h"
100
101 typedef GtkSizeRequestIface GtkSizeRequestInterface;
102 G_DEFINE_INTERFACE (GtkSizeRequest,
103                     gtk_size_request,
104                     GTK_TYPE_WIDGET);
105
106
107 static void
108 gtk_size_request_default_init (GtkSizeRequestInterface *iface)
109 {
110 }
111
112
113 /* looks for a cached size request for this for_size. If not
114  * found, returns the oldest entry so it can be overwritten
115  *
116  * Note that this caching code was directly derived from
117  * the Clutter toolkit.
118  */
119 static gboolean
120 get_cached_size (gint           for_size,
121                  SizeRequest   *cached_sizes,
122                  SizeRequest  **result)
123 {
124   guint i;
125
126   *result = &cached_sizes[0];
127
128   for (i = 0; i < GTK_SIZE_REQUEST_CACHED_SIZES; i++)
129     {
130       SizeRequest *cs;
131
132       cs = &cached_sizes[i];
133
134       if (cs->age > 0 && cs->for_size == for_size)
135         {
136           *result = cs;
137           return TRUE;
138         }
139       else if (cs->age < (*result)->age)
140         {
141           *result = cs;
142         }
143     }
144
145   return FALSE;
146 }
147
148 static void
149 do_size_request (GtkWidget      *widget,
150                  GtkRequisition *requisition)
151 {
152   /* Now we dont bother caching the deprecated "size-request" returns,
153    * just unconditionally invoke here just in case we run into legacy stuff */
154   gtk_widget_ensure_style (widget);
155   g_signal_emit_by_name (widget, "size-request", requisition);
156 }
157
158 #ifndef G_DISABLE_CHECKS
159 static GQuark recursion_check_quark = 0;
160 #endif /* G_DISABLE_CHECKS */
161
162 static void
163 push_recursion_check (GtkSizeRequest  *request,
164                       GtkSizeGroupMode orientation,
165                       gint             for_size)
166 {
167 #ifndef G_DISABLE_CHECKS
168   const char *previous_method;
169   const char *method;
170
171   if (recursion_check_quark == 0)
172     recursion_check_quark = g_quark_from_static_string ("gtk-size-request-in-progress");
173
174   previous_method = g_object_get_qdata (G_OBJECT (request), recursion_check_quark);
175
176   if (orientation == GTK_SIZE_GROUP_HORIZONTAL)
177     {
178       method = for_size < 0 ? "get_width" : "get_width_for_height";
179     }
180   else
181     {
182       method = for_size < 0 ? "get_height" : "get_height_for_width";
183     }
184
185   if (previous_method != NULL)
186     {
187       g_warning ("%s %p: widget tried to gtk_size_request_%s inside "
188                  " GtkSizeRequest::%s implementation. "
189                  "Should just invoke GTK_SIZE_REQUEST_GET_IFACE(widget)->%s "
190                  "directly rather than using gtk_size_request_%s",
191                  G_OBJECT_TYPE_NAME (request), request,
192                  method, previous_method,
193                  method, method);
194     }
195
196   g_object_set_qdata (G_OBJECT (request), recursion_check_quark, (char*) method);
197 #endif /* G_DISABLE_CHECKS */
198 }
199
200 static void
201 pop_recursion_check (GtkSizeRequest  *request,
202                      GtkSizeGroupMode orientation)
203 {
204 #ifndef G_DISABLE_CHECKS
205   g_object_set_qdata (G_OBJECT (request), recursion_check_quark, NULL);
206 #endif
207 }
208
209 static void
210 compute_size_for_orientation (GtkSizeRequest    *request,
211                               GtkSizeGroupMode   orientation,
212                               gint               for_size,
213                               gint              *minimum_size,
214                               gint              *natural_size)
215 {
216   SizeRequestCache *cache;
217   SizeRequest      *cached_size;
218   GtkWidget        *widget;
219   gboolean          found_in_cache = FALSE;
220   int adjusted_min, adjusted_natural;
221
222   g_return_if_fail (GTK_IS_SIZE_REQUEST (request));
223   g_return_if_fail (minimum_size != NULL || natural_size != NULL);
224
225   widget = GTK_WIDGET (request);
226   cache  = _gtk_widget_peek_request_cache (widget);
227
228   if (orientation == GTK_SIZE_GROUP_HORIZONTAL)
229     {
230       cached_size = &cache->widths[0];
231
232       if (!GTK_WIDGET_WIDTH_REQUEST_NEEDED (request))
233         found_in_cache = get_cached_size (for_size, cache->widths, &cached_size);
234       else
235         {
236           memset (cache->widths, 0, GTK_SIZE_REQUEST_CACHED_SIZES * sizeof (SizeRequest));
237           cache->cached_width_age = 1;
238         }
239     }
240   else
241     {
242       cached_size = &cache->heights[0];
243
244       if (!GTK_WIDGET_HEIGHT_REQUEST_NEEDED (request))
245         found_in_cache = get_cached_size (for_size, cache->heights, &cached_size);
246       else
247         {
248           memset (cache->heights, 0, GTK_SIZE_REQUEST_CACHED_SIZES * sizeof (SizeRequest));
249           cache->cached_height_age = 1;
250         }
251     }
252
253   if (!found_in_cache)
254     {
255       GtkRequisition requisition = { 0, 0 };
256       gint min_size = 0, nat_size = 0;
257       gint group_size, requisition_size;
258
259       /* Unconditional size request runs but is often unhandled. */
260       do_size_request (widget, &requisition);
261
262       push_recursion_check (request, orientation, for_size);
263       if (orientation == GTK_SIZE_GROUP_HORIZONTAL)
264         {
265           requisition_size = requisition.width;
266
267           if (for_size < 0)
268             GTK_SIZE_REQUEST_GET_IFACE (request)->get_width (request, &min_size, &nat_size);
269           else
270             GTK_SIZE_REQUEST_GET_IFACE (request)->get_width_for_height (request, for_size, 
271                                                                         &min_size, &nat_size);
272         }
273       else
274         {
275           requisition_size = requisition.height;
276
277           if (for_size < 0)
278             GTK_SIZE_REQUEST_GET_IFACE (request)->get_height (request, &min_size, &nat_size);
279           else
280             GTK_SIZE_REQUEST_GET_IFACE (request)->get_height_for_width (request, for_size, 
281                                                                         &min_size, &nat_size);
282         }
283       pop_recursion_check (request, orientation);
284
285       if (min_size > nat_size)
286         {
287           g_warning ("%s %p reported min size %d and natural size %d; natural size must be >= min size",
288                      G_OBJECT_TYPE_NAME (request), request, min_size, nat_size);
289         }
290
291       /* Support for dangling "size-request" signal implementations on
292        * legacy widgets
293        */
294       min_size = MAX (min_size, requisition_size);
295       nat_size = MAX (nat_size, requisition_size);
296
297       cached_size->minimum_size = min_size;
298       cached_size->natural_size = nat_size;
299       cached_size->for_size     = for_size;
300
301       if (orientation == GTK_SIZE_GROUP_HORIZONTAL)
302         {
303           cached_size->age = cache->cached_width_age;
304           cache->cached_width_age++;
305
306           GTK_PRIVATE_UNSET_FLAG (request, GTK_WIDTH_REQUEST_NEEDED);
307         }
308       else
309         {
310           cached_size->age = cache->cached_height_age;
311           cache->cached_height_age++;
312
313           GTK_PRIVATE_UNSET_FLAG (request, GTK_HEIGHT_REQUEST_NEEDED);
314         }
315
316       adjusted_min = cached_size->minimum_size;
317       adjusted_natural = cached_size->natural_size;
318       GTK_WIDGET_GET_CLASS (request)->adjust_size_request (GTK_WIDGET (request),
319                                                            orientation == GTK_SIZE_GROUP_HORIZONTAL ?
320                                                            GTK_ORIENTATION_HORIZONTAL :
321                                                            GTK_ORIENTATION_VERTICAL,
322                                                            cached_size->for_size,
323                                                            &adjusted_min,
324                                                            &adjusted_natural);
325
326       if (adjusted_min < cached_size->minimum_size ||
327           adjusted_natural < cached_size->natural_size)
328         {
329           g_warning ("%s %p adjusted size %s min %d natural %d must not decrease below min %d natural %d",
330                      G_OBJECT_TYPE_NAME (request), request,
331                      orientation == GTK_SIZE_GROUP_VERTICAL ? "vertical" : "horizontal",
332                      adjusted_min, adjusted_natural,
333                      cached_size->minimum_size, cached_size->natural_size);
334           /* don't use the adjustment */
335         }
336       else if (adjusted_min > adjusted_natural)
337         {
338           g_warning ("%s %p adjusted size %s min %d natural %d original min %d natural %d has min greater than natural",
339                      G_OBJECT_TYPE_NAME (request), request,
340                      orientation == GTK_SIZE_GROUP_VERTICAL ? "vertical" : "horizontal",
341                      adjusted_min, adjusted_natural,
342                      cached_size->minimum_size, cached_size->natural_size);
343           /* don't use the adjustment */
344         }
345       else
346         {
347           /* adjustment looks good */
348           cached_size->minimum_size = adjusted_min;
349           cached_size->natural_size = adjusted_natural;
350         }
351
352       /* Get size groups to compute the base requisition once one
353        * of the values have been cached, then go ahead and update
354        * the cache with the sizegroup computed value.
355        */
356       group_size =
357         _gtk_size_group_bump_requisition (GTK_WIDGET (request),
358                                           orientation, cached_size->minimum_size);
359
360       cached_size->minimum_size = MAX (cached_size->minimum_size, group_size);
361       cached_size->natural_size = MAX (cached_size->natural_size, group_size);
362     }
363
364   if (minimum_size)
365     *minimum_size = cached_size->minimum_size;
366
367   if (natural_size)
368     *natural_size = cached_size->natural_size;
369
370   g_assert (cached_size->minimum_size <= cached_size->natural_size);
371
372   GTK_NOTE (SIZE_REQUEST,
373             g_print ("[%p] %s\t%s: %d is minimum %d and natural: %d (hit cache: %s)\n",
374                      request, G_OBJECT_TYPE_NAME (request),
375                      orientation == GTK_SIZE_GROUP_HORIZONTAL ?
376                      "width for height" : "height for width" ,
377                      for_size,
378                      cached_size->minimum_size,
379                      cached_size->natural_size,
380                      found_in_cache ? "yes" : "no"));
381
382 }
383
384 /**
385  * gtk_size_request_get_request_mode:
386  * @widget: a #GtkSizeRequest instance
387  *
388  * Gets whether the widget prefers a height-for-width layout
389  * or a width-for-height layout.
390  *
391  * <note><para>#GtkBin widgets generally propagate the preference of
392  * their child, container widgets need to request something either in
393  * context of their children or in context of their allocation
394  * capabilities.</para></note>
395  *
396  * Returns: The #GtkSizeRequestMode preferred by @widget.
397  *
398  * Since: 3.0
399  */
400 GtkSizeRequestMode
401 gtk_size_request_get_request_mode (GtkSizeRequest *widget)
402 {
403   GtkSizeRequestIface *iface;
404
405   g_return_val_if_fail (GTK_IS_SIZE_REQUEST (widget), GTK_SIZE_REQUEST_HEIGHT_FOR_WIDTH);
406
407   iface = GTK_SIZE_REQUEST_GET_IFACE (widget);
408   if (iface->get_request_mode)
409     return iface->get_request_mode (widget);
410
411   /* By default widgets are height-for-width. */
412   return GTK_SIZE_REQUEST_HEIGHT_FOR_WIDTH;
413 }
414
415 /**
416  * gtk_size_request_get_width:
417  * @widget: a #GtkSizeRequest instance
418  * @minimum_width: (out) (allow-none): location to store the minimum width, or %NULL
419  * @natural_width: (out) (allow-none): location to store the natural width, or %NULL
420  *
421  * Retrieves a widget's initial minimum and natural width.
422  *
423  * <note><para>This call is specific to height-for-width
424  * requests.</para></note>
425  *
426  * Since: 3.0
427  */
428 void
429 gtk_size_request_get_width (GtkSizeRequest *widget,
430                             gint           *minimum_width,
431                             gint           *natural_width)
432 {
433   compute_size_for_orientation (widget, GTK_SIZE_GROUP_HORIZONTAL,
434                                 -1, minimum_width, natural_width);
435 }
436
437
438 /**
439  * gtk_size_request_get_height:
440  * @widget: a #GtkSizeRequest instance
441  * @minimum_height: (out) (allow-none): location to store the minimum height, or %NULL
442  * @natural_height: (out) (allow-none): location to store the natural height, or %NULL
443  *
444  * Retrieves a widget's initial minimum and natural height.
445  *
446  * <note><para>This call is specific to width-for-height requests.</para></note>
447  *
448  * Since: 3.0
449  */
450 void
451 gtk_size_request_get_height (GtkSizeRequest *widget,
452                              gint           *minimum_height,
453                              gint           *natural_height)
454 {
455   compute_size_for_orientation (widget, GTK_SIZE_GROUP_VERTICAL,
456                                 -1, minimum_height, natural_height);
457 }
458
459
460
461 /**
462  * gtk_size_request_get_width_for_height:
463  * @widget: a #GtkSizeRequest instance
464  * @height: the height which is available for allocation
465  * @minimum_width: (out) (allow-none): location for storing the minimum width, or %NULL
466  * @natural_width: (out) (allow-none): location for storing the natural width, or %NULL
467  *
468  * Retrieves a widget's minimum and natural width if it would be given
469  * the specified @height.
470  *
471  * Since: 3.0
472  */
473 void
474 gtk_size_request_get_width_for_height (GtkSizeRequest *widget,
475                                        gint            height,
476                                        gint           *minimum_width,
477                                        gint           *natural_width)
478 {
479   compute_size_for_orientation (widget, GTK_SIZE_GROUP_HORIZONTAL,
480                                 height, minimum_width, natural_width);
481 }
482
483 /**
484  * gtk_size_request_get_height_for_width:
485  * @widget: a #GtkSizeRequest instance
486  * @width: the width which is available for allocation
487  * @minimum_height: (out) (allow-none): location for storing the minimum height, or %NULL
488  * @natural_height: (out) (allow-none): location for storing the natural height, or %NULL
489  *
490  * Retrieves a widget's minimum and natural height if it would be given
491  * the specified @width.
492  *
493  * Since: 3.0
494  */
495 void
496 gtk_size_request_get_height_for_width (GtkSizeRequest *widget,
497                                        gint            width,
498                                        gint           *minimum_height,
499                                        gint           *natural_height)
500 {
501   compute_size_for_orientation (widget, GTK_SIZE_GROUP_VERTICAL,
502                                 width, minimum_height, natural_height);
503 }
504
505 /**
506  * gtk_size_request_get_size:
507  * @widget: a #GtkSizeRequest instance
508  * @minimum_size: (out) (allow-none): location for storing the minimum size, or %NULL
509  * @natural_size: (out) (allow-none): location for storing the natural size, or %NULL
510  *
511  * Retrieves the minimum and natural size of a widget taking
512  * into account the widget's preference for height-for-width management.
513  *
514  * This is used to retrieve a suitable size by container widgets which do
515  * not impose any restrictions on the child placement.
516  *
517  * Since: 3.0
518  */
519 void
520 gtk_size_request_get_size (GtkSizeRequest    *widget,
521                            GtkRequisition    *minimum_size,
522                            GtkRequisition    *natural_size)
523 {
524   gint min_width, nat_width;
525   gint min_height, nat_height;
526
527   g_return_if_fail (GTK_IS_SIZE_REQUEST (widget));
528
529   if (gtk_size_request_get_request_mode (widget) == GTK_SIZE_REQUEST_HEIGHT_FOR_WIDTH)
530     {
531       gtk_size_request_get_width (widget, &min_width, &nat_width);
532
533       if (minimum_size)
534         {
535           minimum_size->width = min_width;
536           gtk_size_request_get_height_for_width (widget, min_width,
537                                                  &minimum_size->height, NULL);
538         }
539
540       if (natural_size)
541         {
542           natural_size->width = nat_width;
543           gtk_size_request_get_height_for_width (widget, nat_width,
544                                                  NULL, &natural_size->height);
545         }
546     }
547   else /* GTK_SIZE_REQUEST_WIDTH_FOR_HEIGHT */
548     {
549       gtk_size_request_get_height (widget, &min_height, &nat_height);
550
551       if (minimum_size)
552         {
553           minimum_size->height = min_height;
554           gtk_size_request_get_width_for_height (widget, min_height,
555                                                  &minimum_size->width, NULL);
556         }
557
558       if (natural_size)
559         {
560           natural_size->height = nat_height;
561           gtk_size_request_get_width_for_height (widget, nat_height,
562                                                  NULL, &natural_size->width);
563         }
564     }
565 }
566
567
568 static gint
569 compare_gap (gconstpointer p1,
570              gconstpointer p2,
571              gpointer      data)
572 {
573   GtkRequestedSize *sizes = data;
574   const guint *c1 = p1;
575   const guint *c2 = p2;
576
577   const gint d1 = MAX (sizes[*c1].natural_size -
578                        sizes[*c1].minimum_size,
579                        0);
580   const gint d2 = MAX (sizes[*c2].natural_size -
581                        sizes[*c2].minimum_size,
582                        0);
583
584   gint delta = (d2 - d1);
585
586   if (0 == delta)
587     delta = (*c2 - *c1);
588
589   return delta;
590 }
591
592 /**
593  * gtk_distribute_natural_allocation: 
594  * @extra_space: Extra space to redistribute among children after subtracting
595  *               minimum sizes and any child padding from the overall allocation
596  * @n_requested_sizes: Number of requests to fit into the allocation
597  * @sizes: An array of structs with a client pointer and a minimum/natural size
598  *         in the orientation of the allocation.
599  *
600  * Distributes @extra_space to child @sizes by bringing up smaller
601  * children up to natural size first.
602  *
603  * The remaining space will be added to the @minimum_size member of the
604  * GtkRequestedSize struct. If all sizes reach their natural size then
605  * the remaining space is returned.
606  *
607  * Returns: The remainder of @extra_space after redistributing space
608  * to @sizes.
609  */
610 gint 
611 gtk_distribute_natural_allocation (gint              extra_space,
612                                    guint             n_requested_sizes,
613                                    GtkRequestedSize *sizes)
614 {
615   guint *spreading = g_newa (guint, n_requested_sizes);
616   gint   i;
617
618   g_return_val_if_fail (extra_space >= 0, 0);
619
620   for (i = 0; i < n_requested_sizes; i++)
621     spreading[i] = i;
622
623   /* Distribute the container's extra space c_gap. We want to assign
624    * this space such that the sum of extra space assigned to children
625    * (c^i_gap) is equal to c_cap. The case that there's not enough
626    * space for all children to take their natural size needs some
627    * attention. The goals we want to achieve are:
628    *
629    *   a) Maximize number of children taking their natural size.
630    *   b) The allocated size of children should be a continuous
631    *   function of c_gap.  That is, increasing the container size by
632    *   one pixel should never make drastic changes in the distribution.
633    *   c) If child i takes its natural size and child j doesn't,
634    *   child j should have received at least as much gap as child i.
635    *
636    * The following code distributes the additional space by following
637    * these rules.
638    */
639   
640   /* Sort descending by gap and position. */
641   g_qsort_with_data (spreading,
642                      n_requested_sizes, sizeof (guint),
643                      compare_gap, sizes);
644   
645   /* Distribute available space.
646    * This master piece of a loop was conceived by Behdad Esfahbod.
647    */
648   for (i = n_requested_sizes - 1; extra_space > 0 && i >= 0; --i)
649     {
650       /* Divide remaining space by number of remaining children.
651        * Sort order and reducing remaining space by assigned space
652        * ensures that space is distributed equally.
653        */
654       gint glue = (extra_space + i) / (i + 1);
655       gint gap = sizes[(spreading[i])].natural_size
656         - sizes[(spreading[i])].minimum_size;
657       
658       gint extra = MIN (glue, gap);
659       
660       sizes[spreading[i]].minimum_size += extra;
661       
662       extra_space -= extra;
663     }
664
665   return extra_space;
666 }
667