]> Pileus Git - ~andy/gtk/blob - gtk/gtksizerequest.c
Move GtkSizeRequest into GtkWidget
[~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: GtkWidget     
29  *
30  * The GtkWidget      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 #GtkWidget      interface for existing widgets,
40  * which always requests the same height, regardless of the available width.
41  *
42  * <refsect2>
43  * <title>Implementing GtkWidget     </title>
44  * <para>
45  * Some important things to keep in mind when implementing
46  * the GtkWidget      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_widget_get_preferred_width().
58  * Next, the toplevel will use the minimum width to query for the
59  * minimum height contextual to that width using
60  * gtk_widget_get_preferred_height_for_width(), which will also
61  * be a highly recursive operation. This minimum-for-minimum size can
62  * be 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. #GtkWidget      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  *
91  * Often a widget needs to get its own request during size request or
92  * allocation, for example when computing height it may need to also
93  * compute width, or when deciding how to use an allocation the widget may
94  * need to know its natural size. In these cases, the widget should be
95  * careful to call its virtual methods directly, like this:
96  * <example>
97  *   <title>Widget calling its own size request method.</title>
98  *   <programlisting>
99  * GTK_SIZE_REQUEST_GET_IFACE(widget)-&gt;get_width(GTK_SIZE_REQUEST(widget), &min, &natural);
100  *   </programlisting>
101  * </example>
102  *
103  * It will not work to use the wrapper functions, such as
104  * gtk_size_request_get_width(), inside your own size request
105  * implementation. These return a request adjusted by #GtkSizeGroup
106  * and by the GtkWidgetClass::adjust_size_request virtual method. If a
107  * widget used the wrappers inside its virtual method implementations,
108  * then the adjustments (such as widget margins) would be applied
109  * twice. GTK+ therefore does not allow this and will warn if you try
110  * to do it.
111  *
112  * Of course if you are getting the size request for
113  * <emphasis>another</emphasis> widget, such as a child of a
114  * container, you <emphasis>must</emphasis> use the wrapper APIs;
115  * otherwise, you would not properly consider widget margins,
116  * #GtkSizeGroup, and so forth.
117  * </para>
118  * </refsect2>
119  */
120
121
122 #include <config.h>
123 #include "gtksizerequest.h"
124 #include "gtksizegroup.h"
125 #include "gtkprivate.h"
126 #include "gtkintl.h"
127
128 /* looks for a cached size request for this for_size. If not
129  * found, returns the oldest entry so it can be overwritten
130  *
131  * Note that this caching code was directly derived from
132  * the Clutter toolkit.
133  */
134 static gboolean
135 get_cached_size (SizeRequestCache  *cache,
136                  GtkSizeGroupMode   orientation,
137                  gint               for_size,
138                  SizeRequest      **result)
139 {
140   guint i, n_sizes;
141   SizeRequest  *cached_sizes;
142
143   if (orientation == GTK_SIZE_GROUP_HORIZONTAL)
144     {
145       cached_sizes = cache->widths;
146       n_sizes = cache->cached_widths;
147     }
148   else
149     {
150       cached_sizes = cache->heights;
151       n_sizes = cache->cached_widths;
152     }
153
154   /* Search for an already cached size */
155   for (i = 0; i < n_sizes; i++)
156     {
157       if (cached_sizes[i].for_size == for_size)
158         {
159           *result = &cached_sizes[i];
160           return TRUE;
161         }
162     }
163
164   /* If not found, pull a new size from the cache, the returned size cache
165    * will immediately be used to cache the new computed size so we go ahead
166    * and increment the last_cached_width/height right away */
167   if (orientation == GTK_SIZE_GROUP_HORIZONTAL)
168     {
169       if (cache->cached_widths < GTK_SIZE_REQUEST_CACHED_SIZES)
170         {
171           cache->cached_widths++;
172           cache->last_cached_width = cache->cached_widths - 1;
173         }
174       else
175         {
176           if (++cache->last_cached_width == GTK_SIZE_REQUEST_CACHED_SIZES)
177             cache->last_cached_width = 0;
178         }
179
180       *result = &cache->widths[cache->last_cached_width];
181     }
182   else /* GTK_SIZE_GROUP_VERTICAL */
183     {
184       if (cache->cached_heights < GTK_SIZE_REQUEST_CACHED_SIZES)
185         {
186           cache->cached_heights++;
187           cache->last_cached_height = cache->cached_heights - 1;
188         }
189       else
190         {
191           if (++cache->last_cached_height == GTK_SIZE_REQUEST_CACHED_SIZES)
192             cache->last_cached_height = 0;
193         }
194
195       *result = &cache->heights[cache->last_cached_height];
196     }
197
198   return FALSE;
199 }
200
201 static void
202 do_size_request (GtkWidget      *widget,
203                  GtkRequisition *requisition)
204 {
205   /* Now we dont bother caching the deprecated "size-request" returns,
206    * just unconditionally invoke here just in case we run into legacy stuff */
207   gtk_widget_ensure_style (widget);
208   g_signal_emit_by_name (widget, "size-request", requisition);
209 }
210
211 #ifndef G_DISABLE_CHECKS
212 static GQuark recursion_check_quark = 0;
213 #endif /* G_DISABLE_CHECKS */
214
215 static void
216 push_recursion_check (GtkWidget       *request,
217                       GtkSizeGroupMode orientation,
218                       gint             for_size)
219 {
220 #ifndef G_DISABLE_CHECKS
221   const char *previous_method;
222   const char *method;
223
224   if (recursion_check_quark == 0)
225     recursion_check_quark = g_quark_from_static_string ("gtk-size-request-in-progress");
226
227   previous_method = g_object_get_qdata (G_OBJECT (request), recursion_check_quark);
228
229   if (orientation == GTK_SIZE_GROUP_HORIZONTAL)
230     {
231       method = for_size < 0 ? "get_width" : "get_width_for_height";
232     }
233   else
234     {
235       method = for_size < 0 ? "get_height" : "get_height_for_width";
236     }
237
238   if (previous_method != NULL)
239     {
240       g_warning ("%s %p: widget tried to gtk_widget_%s inside "
241                  " GtkWidget     ::%s implementation. "
242                  "Should just invoke GTK_WIDGET_GET_CLASS(widget)->%s "
243                  "directly rather than using gtk_widget_%s",
244                  G_OBJECT_TYPE_NAME (request), request,
245                  method, previous_method,
246                  method, method);
247     }
248
249   g_object_set_qdata (G_OBJECT (request), recursion_check_quark, (char*) method);
250 #endif /* G_DISABLE_CHECKS */
251 }
252
253 static void
254 pop_recursion_check (GtkWidget       *request,
255                      GtkSizeGroupMode orientation)
256 {
257 #ifndef G_DISABLE_CHECKS
258   g_object_set_qdata (G_OBJECT (request), recursion_check_quark, NULL);
259 #endif
260 }
261
262 static void
263 compute_size_for_orientation (GtkWidget         *request,
264                               GtkSizeGroupMode   orientation,
265                               gint               for_size,
266                               gint              *minimum_size,
267                               gint              *natural_size)
268 {
269   SizeRequestCache *cache;
270   SizeRequest      *cached_size;
271   GtkWidget        *widget;
272   gboolean          found_in_cache = FALSE;
273   int adjusted_min, adjusted_natural;
274
275   g_return_if_fail (GTK_IS_WIDGET (request));
276   g_return_if_fail (minimum_size != NULL || natural_size != NULL);
277
278   widget = GTK_WIDGET (request);
279   cache  = _gtk_widget_peek_request_cache (widget);
280
281   if (orientation == GTK_SIZE_GROUP_HORIZONTAL)
282     {
283       cached_size = &cache->widths[0];
284
285       if (!GTK_WIDGET_WIDTH_REQUEST_NEEDED (request))
286         found_in_cache = get_cached_size (cache, orientation, for_size, &cached_size);
287       else
288         {
289           memset (cache->widths, 0, GTK_SIZE_REQUEST_CACHED_SIZES * sizeof (SizeRequest));
290           cache->cached_widths = 1;
291           cache->last_cached_width = 0;
292         }
293     }
294   else
295     {
296       cached_size = &cache->heights[0];
297
298       if (!GTK_WIDGET_HEIGHT_REQUEST_NEEDED (request))
299         found_in_cache = get_cached_size (cache, orientation, for_size, &cached_size);
300       else
301         {
302           memset (cache->heights, 0, GTK_SIZE_REQUEST_CACHED_SIZES * sizeof (SizeRequest));
303           cache->cached_heights = 1;
304           cache->last_cached_height = 0;
305         }
306     }
307
308   if (!found_in_cache)
309     {
310       GtkRequisition requisition = { 0, 0 };
311       gint min_size = 0, nat_size = 0;
312       gint requisition_size;
313
314       /* Unconditional size request runs but is often unhandled. */
315       do_size_request (widget, &requisition);
316
317       push_recursion_check (request, orientation, for_size);
318       if (orientation == GTK_SIZE_GROUP_HORIZONTAL)
319         {
320           requisition_size = requisition.width;
321
322           if (for_size < 0)
323             GTK_WIDGET_GET_CLASS (request)->get_preferred_width (request, &min_size, &nat_size);
324           else
325             GTK_WIDGET_GET_CLASS (request)->get_preferred_width_for_height (request, for_size, 
326                                                                                   &min_size, &nat_size);
327         }
328       else
329         {
330           requisition_size = requisition.height;
331
332           if (for_size < 0)
333             GTK_WIDGET_GET_CLASS (request)->get_preferred_height (request, &min_size, &nat_size);
334           else
335             GTK_WIDGET_GET_CLASS (request)->get_preferred_height_for_width (request, for_size, 
336                                                                                   &min_size, &nat_size);
337         }
338       pop_recursion_check (request, orientation);
339
340       if (min_size > nat_size)
341         {
342           g_warning ("%s %p reported min size %d and natural size %d; natural size must be >= min size",
343                      G_OBJECT_TYPE_NAME (request), request, min_size, nat_size);
344         }
345
346       /* Support for dangling "size-request" signal implementations on
347        * legacy widgets
348        */
349       min_size = MAX (min_size, requisition_size);
350       nat_size = MAX (nat_size, requisition_size);
351
352       cached_size->minimum_size = min_size;
353       cached_size->natural_size = nat_size;
354       cached_size->for_size     = for_size;
355
356       if (orientation == GTK_SIZE_GROUP_HORIZONTAL)
357         GTK_PRIVATE_UNSET_FLAG (request, GTK_WIDTH_REQUEST_NEEDED);
358       else
359         GTK_PRIVATE_UNSET_FLAG (request, GTK_HEIGHT_REQUEST_NEEDED);
360
361       adjusted_min = cached_size->minimum_size;
362       adjusted_natural = cached_size->natural_size;
363       GTK_WIDGET_GET_CLASS (request)->adjust_size_request (GTK_WIDGET (request),
364                                                            orientation == GTK_SIZE_GROUP_HORIZONTAL ?
365                                                            GTK_ORIENTATION_HORIZONTAL :
366                                                            GTK_ORIENTATION_VERTICAL,
367                                                            cached_size->for_size,
368                                                            &adjusted_min,
369                                                            &adjusted_natural);
370
371       if (adjusted_min < cached_size->minimum_size ||
372           adjusted_natural < cached_size->natural_size)
373         {
374           g_warning ("%s %p adjusted size %s min %d natural %d must not decrease below min %d natural %d",
375                      G_OBJECT_TYPE_NAME (request), request,
376                      orientation == GTK_SIZE_GROUP_VERTICAL ? "vertical" : "horizontal",
377                      adjusted_min, adjusted_natural,
378                      cached_size->minimum_size, cached_size->natural_size);
379           /* don't use the adjustment */
380         }
381       else if (adjusted_min > adjusted_natural)
382         {
383           g_warning ("%s %p adjusted size %s min %d natural %d original min %d natural %d has min greater than natural",
384                      G_OBJECT_TYPE_NAME (request), request,
385                      orientation == GTK_SIZE_GROUP_VERTICAL ? "vertical" : "horizontal",
386                      adjusted_min, adjusted_natural,
387                      cached_size->minimum_size, cached_size->natural_size);
388           /* don't use the adjustment */
389         }
390       else
391         {
392           /* adjustment looks good */
393           cached_size->minimum_size = adjusted_min;
394           cached_size->natural_size = adjusted_natural;
395         }
396
397       /* Update size-groups with our request and update our cached requests 
398        * with the size-group values in a single pass.
399        */
400       _gtk_size_group_bump_requisition (GTK_WIDGET (request),
401                                         orientation, 
402                                         &cached_size->minimum_size,
403                                         &cached_size->natural_size);
404     }
405
406   if (minimum_size)
407     *minimum_size = cached_size->minimum_size;
408
409   if (natural_size)
410     *natural_size = cached_size->natural_size;
411
412   g_assert (cached_size->minimum_size <= cached_size->natural_size);
413
414   GTK_NOTE (SIZE_REQUEST,
415             g_print ("[%p] %s\t%s: %d is minimum %d and natural: %d (hit cache: %s)\n",
416                      request, G_OBJECT_TYPE_NAME (request),
417                      orientation == GTK_SIZE_GROUP_HORIZONTAL ?
418                      "width for height" : "height for width" ,
419                      for_size,
420                      cached_size->minimum_size,
421                      cached_size->natural_size,
422                      found_in_cache ? "yes" : "no"));
423
424 }
425
426 /**
427  * gtk_widget_get_preferred:
428  * @widget: a #GtkWidget instance
429  *
430  * Gets whether the widget prefers a height-for-width layout
431  * or a width-for-height layout.
432  *
433  * <note><para>#GtkBin widgets generally propagate the preference of
434  * their child, container widgets need to request something either in
435  * context of their children or in context of their allocation
436  * capabilities.</para></note>
437  *
438  * Returns: The #GtkSizeRequestMode preferred by @widget.
439  *
440  * Since: 3.0
441  */
442 GtkSizeRequestMode
443 gtk_widget_get_request_mode (GtkWidget *widget)
444 {
445   GtkWidgetClass *klass;
446
447   g_return_val_if_fail (GTK_IS_WIDGET (widget), GTK_SIZE_REQUEST_HEIGHT_FOR_WIDTH);
448
449   klass = GTK_WIDGET_GET_CLASS (widget);
450   if (klass->get_request_mode)
451     return klass->get_request_mode (widget);
452
453   /* By default widgets are height-for-width. */
454   return GTK_SIZE_REQUEST_HEIGHT_FOR_WIDTH;
455 }
456
457 /**
458  * gtk_widget_get_preferred_width:
459  * @widget: a #GtkWidget instance
460  * @minimum_width: (out) (allow-none): location to store the minimum width, or %NULL
461  * @natural_width: (out) (allow-none): location to store the natural width, or %NULL
462  *
463  * Retrieves a widget's initial minimum and natural width.
464  *
465  * <note><para>This call is specific to height-for-width
466  * requests.</para></note>
467  *
468  * The returned request will be modified by the
469  * GtkWidgetClass::adjust_size_request virtual method and by any
470  * #GtkSizeGroup that have been applied. That is, the returned request
471  * is the one that should be used for layout, not necessarily the one
472  * returned by the widget itself.
473  *
474  * Since: 3.0
475  */
476 void
477 gtk_widget_get_preferred_width (GtkWidget *widget,
478                                 gint      *minimum_width,
479                                 gint      *natural_width)
480 {
481   compute_size_for_orientation (widget, GTK_SIZE_GROUP_HORIZONTAL,
482                                 -1, minimum_width, natural_width);
483 }
484
485
486 /**
487  * gtk_widget_get_preferred_height:
488  * @widget: a #GtkWidget instance
489  * @minimum_height: (out) (allow-none): location to store the minimum height, or %NULL
490  * @natural_height: (out) (allow-none): location to store the natural height, or %NULL
491  *
492  * Retrieves a widget's initial minimum and natural height.
493  *
494  * <note><para>This call is specific to width-for-height requests.</para></note>
495  *
496  * The returned request will be modified by the
497  * GtkWidgetClass::adjust_size_request virtual method and by any
498  * #GtkSizeGroup that have been applied. That is, the returned request
499  * is the one that should be used for layout, not necessarily the one
500  * returned by the widget itself.
501  *
502  * Since: 3.0
503  */
504 void
505 gtk_widget_get_preferred_height (GtkWidget *widget,
506                                  gint      *minimum_height,
507                                  gint      *natural_height)
508 {
509   compute_size_for_orientation (widget, GTK_SIZE_GROUP_VERTICAL,
510                                 -1, minimum_height, natural_height);
511 }
512
513
514
515 /**
516  * gtk_widget_get_preferred_width_for_height:
517  * @widget: a #GtkWidget instance
518  * @height: the height which is available for allocation
519  * @minimum_width: (out) (allow-none): location for storing the minimum width, or %NULL
520  * @natural_width: (out) (allow-none): location for storing the natural width, or %NULL
521  *
522  * Retrieves a widget's minimum and natural width if it would be given
523  * the specified @height.
524  *
525  * The returned request will be modified by the
526  * GtkWidgetClass::adjust_size_request virtual method and by any
527  * #GtkSizeGroup that have been applied. That is, the returned request
528  * is the one that should be used for layout, not necessarily the one
529  * returned by the widget itself.
530  *
531  * Since: 3.0
532  */
533 void
534 gtk_widget_get_preferred_width_for_height (GtkWidget *widget,
535                                            gint       height,
536                                            gint      *minimum_width,
537                                            gint      *natural_width)
538 {
539   compute_size_for_orientation (widget, GTK_SIZE_GROUP_HORIZONTAL,
540                                 height, minimum_width, natural_width);
541 }
542
543 /**
544  * gtk_widget_get_preferred_height_for_width:
545  * @widget: a #GtkWidget instance
546  * @width: the width which is available for allocation
547  * @minimum_height: (out) (allow-none): location for storing the minimum height, or %NULL
548  * @natural_height: (out) (allow-none): location for storing the natural height, or %NULL
549  *
550  * Retrieves a widget's minimum and natural height if it would be given
551  * the specified @width.
552  *
553  * The returned request will be modified by the
554  * GtkWidgetClass::adjust_size_request virtual method and by any
555  * #GtkSizeGroup that have been applied. That is, the returned request
556  * is the one that should be used for layout, not necessarily the one
557  * returned by the widget itself.
558  *
559  * Since: 3.0
560  */
561 void
562 gtk_widget_get_preferred_height_for_width (GtkWidget *widget,
563                                            gint       width,
564                                            gint      *minimum_height,
565                                            gint      *natural_height)
566 {
567   compute_size_for_orientation (widget, GTK_SIZE_GROUP_VERTICAL,
568                                 width, minimum_height, natural_height);
569 }
570
571 /**
572  * gtk_widget_get_preferred_size:
573  * @widget: a #GtkWidget instance
574  * @minimum_size: (out) (allow-none): location for storing the minimum size, or %NULL
575  * @natural_size: (out) (allow-none): location for storing the natural size, or %NULL
576  *
577  * Retrieves the minimum and natural size of a widget taking
578  * into account the widget's preference for height-for-width management.
579  *
580  * This is used to retrieve a suitable size by container widgets which do
581  * not impose any restrictions on the child placement.
582  *
583  * Since: 3.0
584  */
585 void
586 gtk_widget_get_preferred_size (GtkWidget      *widget,
587                                GtkRequisition *minimum_size,
588                                GtkRequisition *natural_size)
589 {
590   gint min_width, nat_width;
591   gint min_height, nat_height;
592
593   g_return_if_fail (GTK_IS_WIDGET (widget));
594
595   if (gtk_widget_get_request_mode (widget) == GTK_SIZE_REQUEST_HEIGHT_FOR_WIDTH)
596     {
597       gtk_widget_get_preferred_width (widget, &min_width, &nat_width);
598
599       if (minimum_size)
600         {
601           minimum_size->width = min_width;
602           gtk_widget_get_preferred_height_for_width (widget, min_width,
603                                                      &minimum_size->height, NULL);
604         }
605
606       if (natural_size)
607         {
608           natural_size->width = nat_width;
609           gtk_widget_get_preferred_height_for_width (widget, nat_width,
610                                                      NULL, &natural_size->height);
611         }
612     }
613   else /* GTK_SIZE_REQUEST_WIDTH_FOR_HEIGHT */
614     {
615       gtk_widget_get_preferred_height (widget, &min_height, &nat_height);
616
617       if (minimum_size)
618         {
619           minimum_size->height = min_height;
620           gtk_widget_get_preferred_width_for_height (widget, min_height,
621                                                      &minimum_size->width, NULL);
622         }
623
624       if (natural_size)
625         {
626           natural_size->height = nat_height;
627           gtk_widget_get_preferred_width_for_height (widget, nat_height,
628                                                      NULL, &natural_size->width);
629         }
630     }
631 }
632
633
634 static gint
635 compare_gap (gconstpointer p1,
636              gconstpointer p2,
637              gpointer      data)
638 {
639   GtkRequestedSize *sizes = data;
640   const guint *c1 = p1;
641   const guint *c2 = p2;
642
643   const gint d1 = MAX (sizes[*c1].natural_size -
644                        sizes[*c1].minimum_size,
645                        0);
646   const gint d2 = MAX (sizes[*c2].natural_size -
647                        sizes[*c2].minimum_size,
648                        0);
649
650   gint delta = (d2 - d1);
651
652   if (0 == delta)
653     delta = (*c2 - *c1);
654
655   return delta;
656 }
657
658 /**
659  * gtk_distribute_natural_allocation: 
660  * @extra_space: Extra space to redistribute among children after subtracting
661  *               minimum sizes and any child padding from the overall allocation
662  * @n_requested_sizes: Number of requests to fit into the allocation
663  * @sizes: An array of structs with a client pointer and a minimum/natural size
664  *         in the orientation of the allocation.
665  *
666  * Distributes @extra_space to child @sizes by bringing up smaller
667  * children up to natural size first.
668  *
669  * The remaining space will be added to the @minimum_size member of the
670  * GtkRequestedSize struct. If all sizes reach their natural size then
671  * the remaining space is returned.
672  *
673  * Returns: The remainder of @extra_space after redistributing space
674  * to @sizes.
675  */
676 gint 
677 gtk_distribute_natural_allocation (gint              extra_space,
678                                    guint             n_requested_sizes,
679                                    GtkRequestedSize *sizes)
680 {
681   guint *spreading;
682   gint   i;
683
684   g_return_val_if_fail (extra_space >= 0, 0);
685
686   spreading = g_newa (guint, n_requested_sizes);
687
688   for (i = 0; i < n_requested_sizes; i++)
689     spreading[i] = i;
690
691   /* Distribute the container's extra space c_gap. We want to assign
692    * this space such that the sum of extra space assigned to children
693    * (c^i_gap) is equal to c_cap. The case that there's not enough
694    * space for all children to take their natural size needs some
695    * attention. The goals we want to achieve are:
696    *
697    *   a) Maximize number of children taking their natural size.
698    *   b) The allocated size of children should be a continuous
699    *   function of c_gap.  That is, increasing the container size by
700    *   one pixel should never make drastic changes in the distribution.
701    *   c) If child i takes its natural size and child j doesn't,
702    *   child j should have received at least as much gap as child i.
703    *
704    * The following code distributes the additional space by following
705    * these rules.
706    */
707   
708   /* Sort descending by gap and position. */
709   g_qsort_with_data (spreading,
710                      n_requested_sizes, sizeof (guint),
711                      compare_gap, sizes);
712   
713   /* Distribute available space.
714    * This master piece of a loop was conceived by Behdad Esfahbod.
715    */
716   for (i = n_requested_sizes - 1; extra_space > 0 && i >= 0; --i)
717     {
718       /* Divide remaining space by number of remaining children.
719        * Sort order and reducing remaining space by assigned space
720        * ensures that space is distributed equally.
721        */
722       gint glue = (extra_space + i) / (i + 1);
723       gint gap = sizes[(spreading[i])].natural_size
724         - sizes[(spreading[i])].minimum_size;
725       
726       gint extra = MIN (glue, gap);
727       
728       sizes[spreading[i]].minimum_size += extra;
729       
730       extra_space -= extra;
731     }
732
733   return extra_space;
734 }
735