]> Pileus Git - ~andy/gtk/blob - gtk/gtksizerequest.c
Fixed possible segmentation fault while freeing size request caches.
[~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 #include <config.h>
25
26 #include "gtksizerequest.h"
27
28 #include "gtkdebug.h"
29 #include "gtkintl.h"
30 #include "gtkprivate.h"
31 #include "gtksizegroup-private.h"
32 #include "gtkwidgetprivate.h"
33
34
35 #ifndef G_DISABLE_CHECKS
36 static GQuark recursion_check_quark = 0;
37 #endif /* G_DISABLE_CHECKS */
38
39 static void
40 push_recursion_check (GtkWidget       *widget,
41                       GtkSizeGroupMode orientation,
42                       gint             for_size)
43 {
44 #ifndef G_DISABLE_CHECKS
45   const char *previous_method;
46   const char *method;
47
48   if (recursion_check_quark == 0)
49     recursion_check_quark = g_quark_from_static_string ("gtk-size-request-in-progress");
50
51   previous_method = g_object_get_qdata (G_OBJECT (widget), recursion_check_quark);
52
53   if (orientation == GTK_SIZE_GROUP_HORIZONTAL)
54     {
55       method = for_size < 0 ? "get_width" : "get_width_for_height";
56     }
57   else
58     {
59       method = for_size < 0 ? "get_height" : "get_height_for_width";
60     }
61
62   if (previous_method != NULL)
63     {
64       g_warning ("%s %p: widget tried to gtk_widget_%s inside "
65                  " GtkWidget     ::%s implementation. "
66                  "Should just invoke GTK_WIDGET_GET_CLASS(widget)->%s "
67                  "directly rather than using gtk_widget_%s",
68                  G_OBJECT_TYPE_NAME (widget), widget,
69                  method, previous_method,
70                  method, method);
71     }
72
73   g_object_set_qdata (G_OBJECT (widget), recursion_check_quark, (char*) method);
74 #endif /* G_DISABLE_CHECKS */
75 }
76
77 static void
78 pop_recursion_check (GtkWidget       *widget,
79                      GtkSizeGroupMode orientation)
80 {
81 #ifndef G_DISABLE_CHECKS
82   g_object_set_qdata (G_OBJECT (widget), recursion_check_quark, NULL);
83 #endif
84 }
85
86
87 static void
88 clear_cache (SizeRequestCache   *cache,
89              GtkSizeGroupMode    orientation)
90 {
91   SizeRequest **sizes;
92   gint          i;
93
94   if (orientation == GTK_SIZE_GROUP_HORIZONTAL)
95     {
96       sizes = cache->widths;
97
98       cache->widths            = NULL;
99       cache->cached_widths     = 0;
100       cache->last_cached_width = 0;
101       cache->cached_base_width = FALSE;
102     }
103   else
104     {
105       sizes = cache->heights;
106
107       cache->heights            = NULL;
108       cache->cached_heights     = 0;
109       cache->last_cached_height = 0; 
110       cache->cached_base_height = FALSE;
111    }
112
113   if (sizes)
114     {
115       for (i = 0; i < GTK_SIZE_REQUEST_CACHED_SIZES && sizes[i] != NULL; i++)
116         g_slice_free (SizeRequest, sizes[i]);
117       
118       g_slice_free1 (sizeof (SizeRequest *) * GTK_SIZE_REQUEST_CACHED_SIZES, sizes);
119     }
120 }
121
122 void
123 _gtk_widget_free_cached_sizes (GtkWidget *widget)
124 {
125   SizeRequestCache   *cache;
126
127   cache = _gtk_widget_peek_request_cache (widget);
128
129   clear_cache (cache, GTK_SIZE_GROUP_HORIZONTAL);
130   clear_cache (cache, GTK_SIZE_GROUP_VERTICAL);
131 }
132
133 /* This function checks if 'request_needed' flag is present
134  * and resets the cache state if a request is needed for
135  * a given orientation.
136  */
137 static SizeRequestCache *
138 init_cache (GtkWidget        *widget)
139 {
140   SizeRequestCache *cache;
141
142   cache = _gtk_widget_peek_request_cache (widget);
143
144   if (_gtk_widget_get_width_request_needed (widget))
145     clear_cache (cache, GTK_SIZE_GROUP_HORIZONTAL);
146   else if (_gtk_widget_get_height_request_needed (widget))
147     clear_cache (cache, GTK_SIZE_GROUP_VERTICAL);
148
149   return cache;
150 }
151
152 /* looks for a cached size request for this for_size. If not
153  * found, returns the oldest entry so it can be overwritten
154  *
155  * Note that this caching code was originally derived from
156  * the Clutter toolkit but has evolved for other GTK+ requirements.
157  */
158 static gboolean
159 get_cached_size (GtkWidget         *widget,
160                  GtkSizeGroupMode   orientation,
161                  gint               for_size,
162                  CachedSize       **result)
163 {
164   SizeRequestCache  *cache;
165   SizeRequest      **cached_sizes;
166   guint              i, n_sizes;
167
168   cache = init_cache (widget);
169
170   if (for_size < 0)
171     {
172       if (orientation == GTK_SIZE_GROUP_HORIZONTAL)
173         {
174           *result = &cache->cached_width;
175           return cache->cached_base_width;
176         }
177       else
178         {
179           *result = &cache->cached_height;
180           return cache->cached_base_height;
181         }
182     }
183
184   if (orientation == GTK_SIZE_GROUP_HORIZONTAL)
185     {
186       cached_sizes = cache->widths;
187       n_sizes      = cache->cached_widths;
188     }
189   else
190     {
191       cached_sizes = cache->heights;
192       n_sizes      = cache->cached_heights;
193     }
194
195   /* Search for an already cached size */
196   for (i = 0; i < n_sizes; i++)
197     {
198       if (cached_sizes[i]->lower_for_size <= for_size &&
199           cached_sizes[i]->upper_for_size >= for_size)
200         {
201           *result = &cached_sizes[i]->cached_size;
202           return TRUE;
203         }
204     }
205
206   return FALSE;
207 }
208
209 static void
210 commit_cached_size (GtkWidget         *widget,
211                     GtkSizeGroupMode   orientation,
212                     gint               for_size,
213                     gint               minimum_size,
214                     gint               natural_size)
215 {
216   SizeRequestCache  *cache;
217   SizeRequest      **cached_sizes;
218   guint              i, n_sizes;
219
220   cache = _gtk_widget_peek_request_cache (widget);
221
222   /* First handle caching of the base requests */
223   if (for_size < 0)
224     {
225       if (orientation == GTK_SIZE_GROUP_HORIZONTAL)
226         {
227           cache->cached_width.minimum_size = minimum_size;
228           cache->cached_width.natural_size = natural_size;
229           cache->cached_base_width = TRUE;
230         }
231       else
232         {
233           cache->cached_height.minimum_size = minimum_size;
234           cache->cached_height.natural_size = natural_size;
235           cache->cached_base_height = TRUE;
236         }
237       return;
238     }
239
240   /* Check if the minimum_size and natural_size is already
241    * in the cache and if this result can be used to extend
242    * that cache entry 
243    */
244   if (orientation == GTK_SIZE_GROUP_HORIZONTAL)
245     {
246       cached_sizes = cache->widths;
247       n_sizes = cache->cached_widths;
248     }
249   else
250     {
251       cached_sizes = cache->heights;
252       n_sizes = cache->cached_heights;
253     }
254
255   for (i = 0; i < n_sizes; i++)
256     {
257       if (cached_sizes[i]->cached_size.minimum_size == minimum_size &&
258           cached_sizes[i]->cached_size.natural_size == natural_size)
259         {
260           cached_sizes[i]->lower_for_size = MIN (cached_sizes[i]->lower_for_size, for_size);
261           cached_sizes[i]->upper_for_size = MAX (cached_sizes[i]->upper_for_size, for_size);
262           return;
263         }
264     }
265
266   /* If not found, pull a new size from the cache, the returned size cache
267    * will immediately be used to cache the new computed size so we go ahead
268    * and increment the last_cached_width/height right away */
269   if (orientation == GTK_SIZE_GROUP_HORIZONTAL)
270     {
271       if (cache->cached_widths < GTK_SIZE_REQUEST_CACHED_SIZES)
272         {
273           cache->cached_widths++;
274           cache->last_cached_width = cache->cached_widths - 1;
275         }
276       else
277         {
278           if (++cache->last_cached_width == GTK_SIZE_REQUEST_CACHED_SIZES)
279             cache->last_cached_width = 0;
280         }
281
282       if (!cache->widths)
283         cache->widths = g_slice_alloc0 (sizeof (SizeRequest *) * GTK_SIZE_REQUEST_CACHED_SIZES);
284
285       if (!cache->widths[cache->last_cached_width])
286         cache->widths[cache->last_cached_width] = g_slice_new (SizeRequest);
287
288       cache->widths[cache->last_cached_width]->lower_for_size = for_size;
289       cache->widths[cache->last_cached_width]->upper_for_size = for_size;
290       cache->widths[cache->last_cached_width]->cached_size.minimum_size = minimum_size;
291       cache->widths[cache->last_cached_width]->cached_size.natural_size = natural_size;
292     }
293   else /* GTK_SIZE_GROUP_VERTICAL */
294     {
295       if (cache->cached_heights < GTK_SIZE_REQUEST_CACHED_SIZES)
296         {
297           cache->cached_heights++;
298           cache->last_cached_height = cache->cached_heights - 1;
299         }
300       else
301         {
302           if (++cache->last_cached_height == GTK_SIZE_REQUEST_CACHED_SIZES)
303             cache->last_cached_height = 0;
304         }
305
306       if (!cache->heights)
307         cache->heights = g_slice_alloc0 (sizeof (SizeRequest *) * GTK_SIZE_REQUEST_CACHED_SIZES);
308
309       if (!cache->heights[cache->last_cached_height])
310         cache->heights[cache->last_cached_height] = g_slice_new (SizeRequest);
311
312       cache->heights[cache->last_cached_height]->lower_for_size = for_size;
313       cache->heights[cache->last_cached_height]->upper_for_size = for_size;
314       cache->heights[cache->last_cached_height]->cached_size.minimum_size = minimum_size;
315       cache->heights[cache->last_cached_height]->cached_size.natural_size = natural_size;
316     }
317 }
318
319 /* This is the main function that checks for a cached size and
320  * possibly queries the widget class to compute the size if it's
321  * not cached. If the for_size here is -1, then get_preferred_width()
322  * or get_preferred_height() will be used.
323  */
324 static void
325 compute_size_for_orientation (GtkWidget         *widget,
326                               GtkSizeGroupMode   orientation,
327                               gint               for_size,
328                               gint              *minimum_size,
329                               gint              *natural_size)
330 {
331   CachedSize       *cached_size;
332   gboolean          found_in_cache = FALSE;
333   gint              min_size = 0;
334   gint              nat_size = 0;
335
336   found_in_cache = get_cached_size (widget, orientation, for_size, &cached_size);
337
338   if (!found_in_cache)
339     {
340       gint adjusted_min, adjusted_natural, adjusted_for_size = for_size;
341
342       if (orientation == GTK_SIZE_GROUP_HORIZONTAL)
343         {
344           if (for_size < 0)
345             {
346               push_recursion_check (widget, orientation, for_size);
347               GTK_WIDGET_GET_CLASS (widget)->get_preferred_width (widget, &min_size, &nat_size);
348               pop_recursion_check (widget, orientation);
349             }
350           else
351             {
352               gint ignored_position = 0;
353               gint minimum_height;
354               gint natural_height;
355
356               /* Pull the base natural height from the cache as it's needed to adjust
357                * the proposed 'for_size' */
358               gtk_widget_get_preferred_height (widget, &minimum_height, &natural_height);
359
360               /* convert for_size to unadjusted height (for_size is a proposed allocation) */
361               GTK_WIDGET_GET_CLASS (widget)->adjust_size_allocation (widget,
362                                                                      GTK_ORIENTATION_VERTICAL,
363                                                                      &minimum_height,
364                                                                      &natural_height,
365                                                                      &ignored_position,
366                                                                      &adjusted_for_size);
367
368               push_recursion_check (widget, orientation, for_size);
369               GTK_WIDGET_GET_CLASS (widget)->get_preferred_width_for_height (widget, 
370                                                                              MAX (adjusted_for_size, minimum_height),
371                                                                              &min_size, &nat_size);
372               pop_recursion_check (widget, orientation);
373             }
374         }
375       else
376         {
377           if (for_size < 0)
378             {
379               push_recursion_check (widget, orientation, for_size);
380               GTK_WIDGET_GET_CLASS (widget)->get_preferred_height (widget, &min_size, &nat_size);
381               pop_recursion_check (widget, orientation);
382             }
383           else
384             {
385               gint ignored_position = 0;
386               gint minimum_width;
387               gint natural_width;
388
389               /* Pull the base natural width from the cache as it's needed to adjust
390                * the proposed 'for_size' */
391               gtk_widget_get_preferred_width (widget, &minimum_width, &natural_width);
392
393               /* convert for_size to unadjusted width (for_size is a proposed allocation) */
394               GTK_WIDGET_GET_CLASS (widget)->adjust_size_allocation (widget,
395                                                                      GTK_ORIENTATION_HORIZONTAL,
396                                                                      &minimum_width,
397                                                                      &natural_width,
398                                                                      &ignored_position,
399                                                                      &adjusted_for_size);
400
401               push_recursion_check (widget, orientation, for_size);
402               GTK_WIDGET_GET_CLASS (widget)->get_preferred_height_for_width (widget, 
403                                                                              MAX (adjusted_for_size, minimum_width),
404                                                                              &min_size, &nat_size);
405               pop_recursion_check (widget, orientation);
406             }
407         }
408
409       if (min_size > nat_size)
410         {
411           g_warning ("%s %p reported min size %d and natural size %d; natural size must be >= min size",
412                      G_OBJECT_TYPE_NAME (widget), widget, min_size, nat_size);
413         }
414
415       if (orientation == GTK_SIZE_GROUP_HORIZONTAL)
416           _gtk_widget_set_width_request_needed (widget, FALSE);
417       else
418           _gtk_widget_set_height_request_needed (widget, FALSE);
419
420       adjusted_min     = min_size;
421       adjusted_natural = nat_size;
422       GTK_WIDGET_GET_CLASS (widget)->adjust_size_request (widget,
423                                                           orientation == GTK_SIZE_GROUP_HORIZONTAL ?
424                                                           GTK_ORIENTATION_HORIZONTAL :
425                                                           GTK_ORIENTATION_VERTICAL,
426                                                           &adjusted_min,
427                                                           &adjusted_natural);
428
429       if (adjusted_min < min_size ||
430           adjusted_natural < nat_size)
431         {
432           g_warning ("%s %p adjusted size %s min %d natural %d must not decrease below min %d natural %d",
433                      G_OBJECT_TYPE_NAME (widget), widget,
434                      orientation == GTK_SIZE_GROUP_VERTICAL ? "vertical" : "horizontal",
435                      adjusted_min, adjusted_natural,
436                      min_size, nat_size);
437           /* don't use the adjustment */
438         }
439       else if (adjusted_min > adjusted_natural)
440         {
441           g_warning ("%s %p adjusted size %s min %d natural %d original min %d natural %d has min greater than natural",
442                      G_OBJECT_TYPE_NAME (widget), widget,
443                      orientation == GTK_SIZE_GROUP_VERTICAL ? "vertical" : "horizontal",
444                      adjusted_min, adjusted_natural,
445                      min_size, nat_size);
446           /* don't use the adjustment */
447         }
448       else
449         {
450           /* adjustment looks good */
451           min_size = adjusted_min;
452           nat_size = adjusted_natural;
453         }
454
455       /* Update size-groups with our request and update our cached requests
456        * with the size-group values in a single pass.
457        */
458       _gtk_size_group_bump_requisition (widget,
459                                         orientation,
460                                         &min_size,
461                                         &nat_size);
462
463       commit_cached_size (widget, orientation, for_size, min_size, nat_size);
464     }
465   else
466     {
467       min_size = cached_size->minimum_size;
468       nat_size = cached_size->natural_size;
469     }
470
471   if (minimum_size)
472     *minimum_size = min_size;
473
474   if (natural_size)
475     *natural_size = nat_size;
476
477   g_assert (min_size <= nat_size);
478
479   GTK_NOTE (SIZE_REQUEST,
480             g_print ("[%p] %s\t%s: %d is minimum %d and natural: %d (hit cache: %s)\n",
481                      widget, G_OBJECT_TYPE_NAME (widget),
482                      orientation == GTK_SIZE_GROUP_HORIZONTAL ?
483                      "width for height" : "height for width" ,
484                      for_size, min_size, nat_size,
485                      found_in_cache ? "yes" : "no"));
486
487 }
488
489 /**
490  * gtk_widget_get_request_mode:
491  * @widget: a #GtkWidget instance
492  *
493  * Gets whether the widget prefers a height-for-width layout
494  * or a width-for-height layout.
495  *
496  * <note><para>#GtkBin widgets generally propagate the preference of
497  * their child, container widgets need to request something either in
498  * context of their children or in context of their allocation
499  * capabilities.</para></note>
500  *
501  * Returns: The #GtkSizeRequestMode preferred by @widget.
502  *
503  * Since: 3.0
504  */
505 GtkSizeRequestMode
506 gtk_widget_get_request_mode (GtkWidget *widget)
507 {
508   g_return_val_if_fail (GTK_IS_WIDGET (widget), GTK_SIZE_REQUEST_HEIGHT_FOR_WIDTH);
509
510   return GTK_WIDGET_GET_CLASS (widget)->get_request_mode (widget);
511 }
512
513 /**
514  * gtk_widget_get_preferred_width:
515  * @widget: a #GtkWidget instance
516  * @minimum_width: (out) (allow-none): location to store the minimum width, or %NULL
517  * @natural_width: (out) (allow-none): location to store the natural width, or %NULL
518  *
519  * Retrieves a widget's initial minimum and natural width.
520  *
521  * <note><para>This call is specific to height-for-width
522  * requests.</para></note>
523  *
524  * The returned request will be modified by the
525  * GtkWidgetClass::adjust_size_request virtual method and by any
526  * #GtkSizeGroup<!-- -->s that have been applied. That is, the returned request
527  * is the one that should be used for layout, not necessarily the one
528  * returned by the widget itself.
529  *
530  * Since: 3.0
531  */
532 void
533 gtk_widget_get_preferred_width (GtkWidget *widget,
534                                 gint      *minimum_width,
535                                 gint      *natural_width)
536 {
537   g_return_if_fail (GTK_IS_WIDGET (widget));
538   g_return_if_fail (minimum_width != NULL || natural_width != NULL);
539
540   compute_size_for_orientation (widget, GTK_SIZE_GROUP_HORIZONTAL,
541                                 -1, minimum_width, natural_width);
542 }
543
544
545 /**
546  * gtk_widget_get_preferred_height:
547  * @widget: a #GtkWidget instance
548  * @minimum_height: (out) (allow-none): location to store the minimum height, or %NULL
549  * @natural_height: (out) (allow-none): location to store the natural height, or %NULL
550  *
551  * Retrieves a widget's initial minimum and natural height.
552  *
553  * <note><para>This call is specific to width-for-height requests.</para></note>
554  *
555  * The returned request will be modified by the
556  * GtkWidgetClass::adjust_size_request virtual method and by any
557  * #GtkSizeGroup<!-- -->s that have been applied. That is, the returned request
558  * is the one that should be used for layout, not necessarily the one
559  * returned by the widget itself.
560  *
561  * Since: 3.0
562  */
563 void
564 gtk_widget_get_preferred_height (GtkWidget *widget,
565                                  gint      *minimum_height,
566                                  gint      *natural_height)
567 {
568   g_return_if_fail (GTK_IS_WIDGET (widget));
569   g_return_if_fail (minimum_height != NULL || natural_height != NULL);
570
571   compute_size_for_orientation (widget, GTK_SIZE_GROUP_VERTICAL,
572                                 -1, minimum_height, natural_height);
573 }
574
575
576
577 /**
578  * gtk_widget_get_preferred_width_for_height:
579  * @widget: a #GtkWidget instance
580  * @height: the height which is available for allocation
581  * @minimum_width: (out) (allow-none): location for storing the minimum width, or %NULL
582  * @natural_width: (out) (allow-none): location for storing the natural width, or %NULL
583  *
584  * Retrieves a widget's minimum and natural width if it would be given
585  * the specified @height.
586  *
587  * The returned request will be modified by the
588  * GtkWidgetClass::adjust_size_request virtual method and by any
589  * #GtkSizeGroup<!-- -->s that have been applied. That is, the returned request
590  * is the one that should be used for layout, not necessarily the one
591  * returned by the widget itself.
592  *
593  * Since: 3.0
594  */
595 void
596 gtk_widget_get_preferred_width_for_height (GtkWidget *widget,
597                                            gint       height,
598                                            gint      *minimum_width,
599                                            gint      *natural_width)
600 {
601   g_return_if_fail (GTK_IS_WIDGET (widget));
602   g_return_if_fail (minimum_width != NULL || natural_width != NULL);
603   g_return_if_fail (height >= 0);
604
605   if (GTK_WIDGET_GET_CLASS (widget)->get_request_mode (widget) == GTK_SIZE_REQUEST_CONSTANT_SIZE)
606     compute_size_for_orientation (widget, GTK_SIZE_GROUP_HORIZONTAL,
607                                   -1, minimum_width, natural_width);
608   else
609     compute_size_for_orientation (widget, GTK_SIZE_GROUP_HORIZONTAL,
610                                   height, minimum_width, natural_width);
611 }
612
613 /**
614  * gtk_widget_get_preferred_height_for_width:
615  * @widget: a #GtkWidget instance
616  * @width: the width which is available for allocation
617  * @minimum_height: (out) (allow-none): location for storing the minimum height, or %NULL
618  * @natural_height: (out) (allow-none): location for storing the natural height, or %NULL
619  *
620  * Retrieves a widget's minimum and natural height if it would be given
621  * the specified @width.
622  *
623  * The returned request will be modified by the
624  * GtkWidgetClass::adjust_size_request virtual method and by any
625  * #GtkSizeGroup<!-- -->s that have been applied. That is, the returned request
626  * is the one that should be used for layout, not necessarily the one
627  * returned by the widget itself.
628  *
629  * Since: 3.0
630  */
631 void
632 gtk_widget_get_preferred_height_for_width (GtkWidget *widget,
633                                            gint       width,
634                                            gint      *minimum_height,
635                                            gint      *natural_height)
636 {
637   g_return_if_fail (GTK_IS_WIDGET (widget));
638   g_return_if_fail (minimum_height != NULL || natural_height != NULL);
639   g_return_if_fail (width >= 0);
640
641   if (GTK_WIDGET_GET_CLASS (widget)->get_request_mode (widget) == GTK_SIZE_REQUEST_CONSTANT_SIZE)
642     compute_size_for_orientation (widget, GTK_SIZE_GROUP_VERTICAL,
643                                   -1, minimum_height, natural_height);
644   else
645     compute_size_for_orientation (widget, GTK_SIZE_GROUP_VERTICAL,
646                                   width, minimum_height, natural_height);
647 }
648
649 /**
650  * gtk_widget_get_preferred_size:
651  * @widget: a #GtkWidget instance
652  * @minimum_size: (out) (allow-none): location for storing the minimum size, or %NULL
653  * @natural_size: (out) (allow-none): location for storing the natural size, or %NULL
654  *
655  * Retrieves the minimum and natural size of a widget, taking
656  * into account the widget's preference for height-for-width management.
657  *
658  * This is used to retrieve a suitable size by container widgets which do
659  * not impose any restrictions on the child placement. It can be used
660  * to deduce toplevel window and menu sizes as well as child widgets in
661  * free-form containers such as GtkLayout.
662  *
663  * <note><para>Handle with care. Note that the natural height of a height-for-width
664  * widget will generally be a smaller size than the minimum height, since the required
665  * height for the natural width is generally smaller than the required height for
666  * the minimum width.</para></note>
667  *
668  * Since: 3.0
669  */
670 void
671 gtk_widget_get_preferred_size (GtkWidget      *widget,
672                                GtkRequisition *minimum_size,
673                                GtkRequisition *natural_size)
674 {
675   gint min_width, nat_width;
676   gint min_height, nat_height;
677
678   g_return_if_fail (GTK_IS_WIDGET (widget));
679
680   if (gtk_widget_get_request_mode (widget) == GTK_SIZE_REQUEST_HEIGHT_FOR_WIDTH)
681     {
682       gtk_widget_get_preferred_width (widget, &min_width, &nat_width);
683
684       if (minimum_size)
685         {
686           minimum_size->width = min_width;
687           gtk_widget_get_preferred_height_for_width (widget, min_width,
688                                                      &minimum_size->height, NULL);
689         }
690
691       if (natural_size)
692         {
693           natural_size->width = nat_width;
694           gtk_widget_get_preferred_height_for_width (widget, nat_width,
695                                                      NULL, &natural_size->height);
696         }
697     }
698   else /* GTK_SIZE_REQUEST_WIDTH_FOR_HEIGHT or CONSTANT_SIZE */
699     {
700       gtk_widget_get_preferred_height (widget, &min_height, &nat_height);
701
702       if (minimum_size)
703         {
704           minimum_size->height = min_height;
705           gtk_widget_get_preferred_width_for_height (widget, min_height,
706                                                      &minimum_size->width, NULL);
707         }
708
709       if (natural_size)
710         {
711           natural_size->height = nat_height;
712           gtk_widget_get_preferred_width_for_height (widget, nat_height,
713                                                      NULL, &natural_size->width);
714         }
715     }
716 }
717
718
719 static gint
720 compare_gap (gconstpointer p1,
721              gconstpointer p2,
722              gpointer      data)
723 {
724   GtkRequestedSize *sizes = data;
725   const guint *c1 = p1;
726   const guint *c2 = p2;
727
728   const gint d1 = MAX (sizes[*c1].natural_size -
729                        sizes[*c1].minimum_size,
730                        0);
731   const gint d2 = MAX (sizes[*c2].natural_size -
732                        sizes[*c2].minimum_size,
733                        0);
734
735   gint delta = (d2 - d1);
736
737   if (0 == delta)
738     delta = (*c2 - *c1);
739
740   return delta;
741 }
742
743 /**
744  * gtk_distribute_natural_allocation:
745  * @extra_space: Extra space to redistribute among children after subtracting
746  *               minimum sizes and any child padding from the overall allocation
747  * @n_requested_sizes: Number of requests to fit into the allocation
748  * @sizes: An array of structs with a client pointer and a minimum/natural size
749  *         in the orientation of the allocation.
750  *
751  * Distributes @extra_space to child @sizes by bringing smaller
752  * children up to natural size first.
753  *
754  * The remaining space will be added to the @minimum_size member of the
755  * GtkRequestedSize struct. If all sizes reach their natural size then
756  * the remaining space is returned.
757  *
758  * Returns: The remainder of @extra_space after redistributing space
759  * to @sizes.
760  */
761 gint
762 gtk_distribute_natural_allocation (gint              extra_space,
763                                    guint             n_requested_sizes,
764                                    GtkRequestedSize *sizes)
765 {
766   guint *spreading;
767   gint   i;
768
769   g_return_val_if_fail (extra_space >= 0, 0);
770
771   spreading = g_newa (guint, n_requested_sizes);
772
773   for (i = 0; i < n_requested_sizes; i++)
774     spreading[i] = i;
775
776   /* Distribute the container's extra space c_gap. We want to assign
777    * this space such that the sum of extra space assigned to children
778    * (c^i_gap) is equal to c_cap. The case that there's not enough
779    * space for all children to take their natural size needs some
780    * attention. The goals we want to achieve are:
781    *
782    *   a) Maximize number of children taking their natural size.
783    *   b) The allocated size of children should be a continuous
784    *   function of c_gap.  That is, increasing the container size by
785    *   one pixel should never make drastic changes in the distribution.
786    *   c) If child i takes its natural size and child j doesn't,
787    *   child j should have received at least as much gap as child i.
788    *
789    * The following code distributes the additional space by following
790    * these rules.
791    */
792
793   /* Sort descending by gap and position. */
794   g_qsort_with_data (spreading,
795                      n_requested_sizes, sizeof (guint),
796                      compare_gap, sizes);
797
798   /* Distribute available space.
799    * This master piece of a loop was conceived by Behdad Esfahbod.
800    */
801   for (i = n_requested_sizes - 1; extra_space > 0 && i >= 0; --i)
802     {
803       /* Divide remaining space by number of remaining children.
804        * Sort order and reducing remaining space by assigned space
805        * ensures that space is distributed equally.
806        */
807       gint glue = (extra_space + i) / (i + 1);
808       gint gap = sizes[(spreading[i])].natural_size
809         - sizes[(spreading[i])].minimum_size;
810
811       gint extra = MIN (glue, gap);
812
813       sizes[spreading[i]].minimum_size += extra;
814
815       extra_space -= extra;
816     }
817
818   return extra_space;
819 }