]> Pileus Git - ~andy/gtk/blob - gtk/gtksizerequest.c
Completely removed requisition cache from GtkWidget instance structure.
[~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 /* With GtkSizeRequest, a widget may be requested
102  * its width for 2 or maximum 3 heights in one resize
103  */
104 #define N_CACHED_SIZES 3
105
106 typedef struct
107 {
108   guint  age;
109   gint   for_size;
110   gint   minimum_size;
111   gint   natural_size;
112 } SizeRequest;
113
114 typedef struct {
115   SizeRequest widths[N_CACHED_SIZES];
116   SizeRequest heights[N_CACHED_SIZES];
117   guint8      cached_width_age;
118   guint8      cached_height_age;
119 } SizeRequestCache;
120
121 static GQuark quark_cache = 0;
122
123
124 typedef GtkSizeRequestIface GtkSizeRequestInterface;
125 G_DEFINE_INTERFACE_WITH_CODE (GtkSizeRequest,
126                               gtk_size_request,
127                               GTK_TYPE_WIDGET,
128                               quark_cache = g_quark_from_static_string ("gtk-size-request-cache"));
129
130
131 static void
132 gtk_size_request_default_init (GtkSizeRequestInterface *iface)
133 {
134 }
135
136
137 /* looks for a cached size request for this for_size. If not
138  * found, returns the oldest entry so it can be overwritten
139  *
140  * Note that this caching code was directly derived from
141  * the Clutter toolkit.
142  */
143 static gboolean
144 get_cached_size (gint           for_size,
145                  SizeRequest   *cached_sizes,
146                  SizeRequest  **result)
147 {
148   guint i;
149
150   *result = &cached_sizes[0];
151
152   for (i = 0; i < N_CACHED_SIZES; i++)
153     {
154       SizeRequest *cs;
155
156       cs = &cached_sizes[i];
157
158       if (cs->age > 0 && cs->for_size == for_size)
159         {
160           *result = cs;
161           return TRUE;
162         }
163       else if (cs->age < (*result)->age)
164         {
165           *result = cs;
166         }
167     }
168
169   return FALSE;
170 }
171
172 static void
173 destroy_cache (SizeRequestCache *cache)
174 {
175   g_slice_free (SizeRequestCache, cache);
176 }
177
178 static SizeRequestCache *
179 get_cache (GtkSizeRequest *widget,
180            gboolean        create)
181 {
182   SizeRequestCache *cache;
183
184   cache = g_object_get_qdata (G_OBJECT (widget), quark_cache);
185   if (!cache && create)
186     {
187       cache = g_slice_new0 (SizeRequestCache);
188
189       cache->cached_width_age  = 1;
190       cache->cached_height_age = 1;
191
192       g_object_set_qdata_full (G_OBJECT (widget), quark_cache, cache,
193                                (GDestroyNotify)destroy_cache);
194     }
195
196   return cache;
197 }
198
199 static void
200 do_size_request (GtkWidget      *widget,
201                  GtkRequisition *requisition)
202 {
203   /* Now we dont bother caching the deprecated "size-request" returns,
204    * just unconditionally invoke here just in case we run into legacy stuff */
205   gtk_widget_ensure_style (widget);
206   g_signal_emit_by_name (widget, "size-request", requisition);
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
221   g_return_if_fail (GTK_IS_SIZE_REQUEST (request));
222   g_return_if_fail (minimum_size != NULL || natural_size != NULL);
223
224   widget = GTK_WIDGET (request);
225   cache  = get_cache (request, TRUE);
226
227   if (orientation == GTK_SIZE_GROUP_HORIZONTAL)
228     {
229       cached_size = &cache->widths[0];
230
231       if (!GTK_WIDGET_WIDTH_REQUEST_NEEDED (request))
232         found_in_cache = get_cached_size (for_size, cache->widths, &cached_size);
233       else
234         {
235           memset (cache->widths, 0, N_CACHED_SIZES * sizeof (SizeRequest));
236           cache->cached_width_age = 1;
237         }
238     }
239   else
240     {
241       cached_size = &cache->heights[0];
242
243       if (!GTK_WIDGET_HEIGHT_REQUEST_NEEDED (request))
244         found_in_cache = get_cached_size (for_size, cache->heights, &cached_size);
245       else
246         {
247           memset (cache->heights, 0, N_CACHED_SIZES * sizeof (SizeRequest));
248           cache->cached_height_age = 1;
249         }
250     }
251
252   if (!found_in_cache)
253     {
254       GtkRequisition requisition = { 0, 0 };
255       gint min_size = 0, nat_size = 0;
256       gint group_size, requisition_size;
257
258       /* Unconditional size request runs but is often unhandled. */
259       do_size_request (widget, &requisition);
260
261       if (orientation == GTK_SIZE_GROUP_HORIZONTAL)
262         {
263           requisition_size = requisition.width;
264
265           if (for_size < 0)
266             GTK_SIZE_REQUEST_GET_IFACE (request)->get_width (request, &min_size, &nat_size);
267           else
268             GTK_SIZE_REQUEST_GET_IFACE (request)->get_width_for_height (request, for_size, 
269                                                                         &min_size, &nat_size);
270         }
271       else
272         {
273           requisition_size = requisition.height;
274
275           if (for_size < 0)
276             GTK_SIZE_REQUEST_GET_IFACE (request)->get_height (request, &min_size, &nat_size);
277           else
278             GTK_SIZE_REQUEST_GET_IFACE (request)->get_height_for_width (request, for_size, 
279                                                                         &min_size, &nat_size);
280         }
281
282       if (min_size > nat_size)
283         {
284           g_warning ("%s %p reported min size %d and natural size %d; natural size must be >= min size",
285                      G_OBJECT_TYPE_NAME (request), request, min_size, nat_size);
286         }
287
288       /* Support for dangling "size-request" signal implementations on
289        * legacy widgets
290        */
291       min_size = MAX (min_size, requisition_size);
292       nat_size = MAX (nat_size, requisition_size);
293
294       cached_size->minimum_size = min_size;
295       cached_size->natural_size = nat_size;
296       cached_size->for_size     = for_size;
297
298       if (orientation == GTK_SIZE_GROUP_HORIZONTAL)
299         {
300           cached_size->age = cache->cached_width_age;
301           cache->cached_width_age++;
302
303           GTK_PRIVATE_UNSET_FLAG (request, GTK_WIDTH_REQUEST_NEEDED);
304         }
305       else
306         {
307           cached_size->age = cache->cached_height_age;
308           cache->cached_height_age++;
309
310           GTK_PRIVATE_UNSET_FLAG (request, GTK_HEIGHT_REQUEST_NEEDED);
311         }
312
313       /* Get size groups to compute the base requisition once one
314        * of the values have been cached, then go ahead and update
315        * the cache with the sizegroup computed value.
316        *
317        * Note this is also where values from gtk_widget_set_size_request()
318        * are considered.
319        */
320       group_size =
321         _gtk_size_group_bump_requisition (GTK_WIDGET (request),
322                                           orientation, cached_size->minimum_size);
323
324       cached_size->minimum_size = MAX (cached_size->minimum_size, group_size);
325       cached_size->natural_size = MAX (cached_size->natural_size, group_size);
326     }
327
328   if (minimum_size)
329     *minimum_size = cached_size->minimum_size;
330
331   if (natural_size)
332     *natural_size = cached_size->natural_size;
333
334   g_assert (cached_size->minimum_size <= cached_size->natural_size);
335
336   GTK_NOTE (SIZE_REQUEST,
337             g_print ("[%p] %s\t%s: %d is minimum %d and natural: %d (hit cache: %s)\n",
338                      request, G_OBJECT_TYPE_NAME (request),
339                      orientation == GTK_SIZE_GROUP_HORIZONTAL ?
340                      "width for height" : "height for width" ,
341                      for_size,
342                      cached_size->minimum_size,
343                      cached_size->natural_size,
344                      found_in_cache ? "yes" : "no"));
345
346 }
347
348 /**
349  * gtk_size_request_get_request_mode:
350  * @widget: a #GtkSizeRequest instance
351  *
352  * Gets whether the widget prefers a height-for-width layout
353  * or a width-for-height layout.
354  *
355  * <note><para>#GtkBin widgets generally propagate the preference of
356  * their child, container widgets need to request something either in
357  * context of their children or in context of their allocation
358  * capabilities.</para></note>
359  *
360  * Returns: The #GtkSizeRequestMode preferred by @widget.
361  *
362  * Since: 3.0
363  */
364 GtkSizeRequestMode
365 gtk_size_request_get_request_mode (GtkSizeRequest *widget)
366 {
367   GtkSizeRequestIface *iface;
368
369   g_return_val_if_fail (GTK_IS_SIZE_REQUEST (widget), GTK_SIZE_REQUEST_HEIGHT_FOR_WIDTH);
370
371   iface = GTK_SIZE_REQUEST_GET_IFACE (widget);
372   if (iface->get_request_mode)
373     return iface->get_request_mode (widget);
374
375   /* By default widgets are height-for-width. */
376   return GTK_SIZE_REQUEST_HEIGHT_FOR_WIDTH;
377 }
378
379 /**
380  * gtk_size_request_get_width:
381  * @widget: a #GtkSizeRequest instance
382  * @minimum_width: (out) (allow-none): location to store the minimum width, or %NULL
383  * @natural_width: (out) (allow-none): location to store the natural width, or %NULL
384  *
385  * Retrieves a widget's initial minimum and natural width.
386  *
387  * <note><para>This call is specific to height-for-width
388  * requests.</para></note>
389  *
390  * Since: 3.0
391  */
392 void
393 gtk_size_request_get_width (GtkSizeRequest *widget,
394                             gint           *minimum_width,
395                             gint           *natural_width)
396 {
397   compute_size_for_orientation (widget, GTK_SIZE_GROUP_HORIZONTAL,
398                                 -1, minimum_width, natural_width);
399 }
400
401
402 /**
403  * gtk_size_request_get_height:
404  * @widget: a #GtkSizeRequest instance
405  * @minimum_height: (out) (allow-none): location to store the minimum height, or %NULL
406  * @natural_height: (out) (allow-none): location to store the natural height, or %NULL
407  *
408  * Retrieves a widget's initial minimum and natural height.
409  *
410  * <note><para>This call is specific to width-for-height requests.</para></note>
411  *
412  * Since: 3.0
413  */
414 void
415 gtk_size_request_get_height (GtkSizeRequest *widget,
416                              gint           *minimum_height,
417                              gint           *natural_height)
418 {
419   compute_size_for_orientation (widget, GTK_SIZE_GROUP_VERTICAL,
420                                 -1, minimum_height, natural_height);
421 }
422
423
424
425 /**
426  * gtk_size_request_get_width_for_height:
427  * @widget: a #GtkSizeRequest instance
428  * @height: the height which is available for allocation
429  * @minimum_width: (out) (allow-none): location for storing the minimum width, or %NULL
430  * @natural_width: (out) (allow-none): location for storing the natural width, or %NULL
431  *
432  * Retrieves a widget's minimum and natural width if it would be given
433  * the specified @height.
434  *
435  * Since: 3.0
436  */
437 void
438 gtk_size_request_get_width_for_height (GtkSizeRequest *widget,
439                                        gint            height,
440                                        gint           *minimum_width,
441                                        gint           *natural_width)
442 {
443   compute_size_for_orientation (widget, GTK_SIZE_GROUP_HORIZONTAL,
444                                 height, minimum_width, natural_width);
445 }
446
447 /**
448  * gtk_size_request_get_height_for_width:
449  * @widget: a #GtkSizeRequest instance
450  * @width: the width which is available for allocation
451  * @minimum_height: (out) (allow-none): location for storing the minimum height, or %NULL
452  * @natural_height: (out) (allow-none): location for storing the natural height, or %NULL
453  *
454  * Retrieves a widget's minimum and natural height if it would be given
455  * the specified @width.
456  *
457  * Since: 3.0
458  */
459 void
460 gtk_size_request_get_height_for_width (GtkSizeRequest *widget,
461                                        gint            width,
462                                        gint           *minimum_height,
463                                        gint           *natural_height)
464 {
465   compute_size_for_orientation (widget, GTK_SIZE_GROUP_VERTICAL,
466                                 width, minimum_height, natural_height);
467 }
468
469 /**
470  * gtk_size_request_get_size:
471  * @widget: a #GtkSizeRequest instance
472  * @minimum_size: (out) (allow-none): location for storing the minimum size, or %NULL
473  * @natural_size: (out) (allow-none): location for storing the natural size, or %NULL
474  *
475  * Retrieves the minimum and natural size of a widget taking
476  * into account the widget's preference for height-for-width management.
477  *
478  * This is used to retrieve a suitable size by container widgets which do
479  * not impose any restrictions on the child placement.
480  *
481  * Since: 3.0
482  */
483 void
484 gtk_size_request_get_size (GtkSizeRequest    *widget,
485                            GtkRequisition    *minimum_size,
486                            GtkRequisition    *natural_size)
487 {
488   gint min_width, nat_width;
489   gint min_height, nat_height;
490
491   g_return_if_fail (GTK_IS_SIZE_REQUEST (widget));
492
493   if (gtk_size_request_get_request_mode (widget) == GTK_SIZE_REQUEST_HEIGHT_FOR_WIDTH)
494     {
495       gtk_size_request_get_width (widget, &min_width, &nat_width);
496
497       if (minimum_size)
498         {
499           minimum_size->width = min_width;
500           gtk_size_request_get_height_for_width (widget, min_width,
501                                                  &minimum_size->height, NULL);
502         }
503
504       if (natural_size)
505         {
506           natural_size->width = nat_width;
507           gtk_size_request_get_height_for_width (widget, nat_width,
508                                                  NULL, &natural_size->height);
509         }
510     }
511   else /* GTK_SIZE_REQUEST_WIDTH_FOR_HEIGHT */
512     {
513       gtk_size_request_get_height (widget, &min_height, &nat_height);
514
515       if (minimum_size)
516         {
517           minimum_size->height = min_height;
518           gtk_size_request_get_width_for_height (widget, min_height,
519                                                  &minimum_size->width, NULL);
520         }
521
522       if (natural_size)
523         {
524           natural_size->height = nat_height;
525           gtk_size_request_get_width_for_height (widget, nat_height,
526                                                  NULL, &natural_size->width);
527         }
528     }
529 }
530
531
532 static gint
533 compare_gap (gconstpointer p1,
534              gconstpointer p2,
535              gpointer      data)
536 {
537   GtkRequestedSize *sizes = data;
538   const guint *c1 = p1;
539   const guint *c2 = p2;
540
541   const gint d1 = MAX (sizes[*c1].natural_size -
542                        sizes[*c1].minimum_size,
543                        0);
544   const gint d2 = MAX (sizes[*c2].natural_size -
545                        sizes[*c2].minimum_size,
546                        0);
547
548   gint delta = (d2 - d1);
549
550   if (0 == delta)
551     delta = (*c2 - *c1);
552
553   return delta;
554 }
555
556 /**
557  * gtk_distribute_natural_allocation: 
558  * @extra_space: Extra space to redistribute among children after subtracting
559  *               minimum sizes and any child padding from the overall allocation
560  * @n_requested_sizes: Number of requests to fit into the allocation
561  * @sizes: An array of structs with a client pointer and a minimum/natural size
562  *         in the orientation of the allocation.
563  *
564  * Distributes @extra_space to child @sizes by bringing up smaller
565  * children up to natural size first.
566  *
567  * The remaining space will be added to the @minimum_size member of the
568  * GtkRequestedSize struct. If all sizes reach their natural size then
569  * the remaining space is returned.
570  *
571  * Returns: The remainder of @extra_space after redistributing space
572  * to @sizes.
573  */
574 gint 
575 gtk_distribute_natural_allocation (gint              extra_space,
576                                    guint             n_requested_sizes,
577                                    GtkRequestedSize *sizes)
578 {
579   guint *spreading = g_newa (guint, n_requested_sizes);
580   gint   i;
581
582   g_return_val_if_fail (extra_space >= 0, 0);
583
584   for (i = 0; i < n_requested_sizes; i++)
585     spreading[i] = i;
586
587   /* Distribute the container's extra space c_gap. We want to assign
588    * this space such that the sum of extra space assigned to children
589    * (c^i_gap) is equal to c_cap. The case that there's not enough
590    * space for all children to take their natural size needs some
591    * attention. The goals we want to achieve are:
592    *
593    *   a) Maximize number of children taking their natural size.
594    *   b) The allocated size of children should be a continuous
595    *   function of c_gap.  That is, increasing the container size by
596    *   one pixel should never make drastic changes in the distribution.
597    *   c) If child i takes its natural size and child j doesn't,
598    *   child j should have received at least as much gap as child i.
599    *
600    * The following code distributes the additional space by following
601    * these rules.
602    */
603   
604   /* Sort descending by gap and position. */
605   g_qsort_with_data (spreading,
606                      n_requested_sizes, sizeof (guint),
607                      compare_gap, sizes);
608   
609   /* Distribute available space.
610    * This master piece of a loop was conceived by Behdad Esfahbod.
611    */
612   for (i = n_requested_sizes - 1; extra_space > 0 && i >= 0; --i)
613     {
614       /* Divide remaining space by number of remaining children.
615        * Sort order and reducing remaining space by assigned space
616        * ensures that space is distributed equally.
617        */
618       gint glue = (extra_space + i) / (i + 1);
619       gint gap = sizes[(spreading[i])].natural_size
620         - sizes[(spreading[i])].minimum_size;
621       
622       gint extra = MIN (glue, gap);
623       
624       sizes[spreading[i]].minimum_size += extra;
625       
626       extra_space -= extra;
627     }
628
629   return extra_space;
630 }
631