summaryrefslogtreecommitdiff
path: root/src/Layout.c
blob: e369a82c6b7e3e3a05a32eaa9d4b3c2caa89365e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
/*
 * Copyright 1991 Massachusetts Institute of Technology
 *
 * Permission to use, copy, modify, distribute, and sell this software and its
 * documentation for any purpose is hereby granted without fee, provided that
 * the above copyright notice appear in all copies and that both that
 * copyright notice and this permission notice appear in supporting
 * documentation, and that the name of M.I.T. not be used in advertising or
 * publicity pertaining to distribution of the software without specific,
 * written prior permission.  M.I.T. makes no representations about the
 * suitability of this software for any purpose.  It is provided "as is"
 * without express or implied warranty.
 *
 * M.I.T. DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL M.I.T.
 * BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
 * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 * Author:  Keith Packard, MIT X Consortium
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <X11/IntrinsicP.h>
#include <X11/StringDefs.h>

#include <X11/Xmu/Misc.h>
#include <X11/Xmu/Converters.h>

#ifdef MOTIF
# include <Xm/XmP.h>
#endif

#if defined(LAYOUT)
# include "LayoutP.h"
#else
# include <X11/Xaw3d/LayoutP.h>
#endif

#include <ctype.h>
#include <stdio.h>

#include "LayYY.h"

#undef DEBUG
#ifdef DEBUG
static char *DBUG_currentproc, *DBUG_lastproc;
static int DBUG_level = 0;
# define DBUG_ENTER(s)        \
    {DBUG_lastproc=DBUG_currentproc;DBUG_currentproc=s;\
    fprintf(stderr,"begin: (%d) %s\n",++DBUG_level,s);}
# define DBUG_VOID_RETURN \
    {fprintf(stderr,"end:   (%d) %s\n",DBUG_level--,DBUG_currentproc); \
    DBUG_currentproc=DBUG_lastproc;return;}
# define DBUG_RETURN(f,v) \
    {fprintf(stderr,"return (%d) %s (",DBUG_level--,DBUG_currentproc); \
    fprintf(stderr,(f),(v)); \
    fprintf(stderr,")\n"); DBUG_currentproc=DBUG_lastproc;return (v);}
# define DBUG_PRINT(f,s)        \
    {fprintf(stderr,"       (%d) %s:",DBUG_level, DBUG_currentproc); \
    fprintf(stderr,f,s);fprintf(stderr,"\n");}
#else
# define DBUG_ENTER(s)
# define DBUG_VOID_RETURN return
# define DBUG_PRINT(f,s)
# define DBUG_RETURN(f,v) return(v)
#endif

/*****************************************************************************
 *
 * Full instance record declaration
 *
 ****************************************************************************/

#define offset(field) XtOffsetOf(LayoutRec, layout.field)

static XtResource resources[] = {
    {XtNlayout, XtCLayout, XtRLayout, sizeof (BoxPtr),
	offset(layout), XtRLayout, NULL },
    {XtNdebug, XtCBoolean, XtRBoolean, sizeof(Boolean),
	 offset(debug), XtRImmediate, (XtPointer) FALSE},
};

#undef offset

static void ClassInitialize(void);
static void Initialize(Widget, Widget, ArgList, Cardinal *);
static void Resize(Widget);
static Boolean SetValues(Widget, Widget, Widget, ArgList, Cardinal *);
static XtGeometryResult GeometryManager(Widget, XtWidgetGeometry *, XtWidgetGeometry *);
static void ChangeManaged(Widget);
static void InsertChild(Widget);
static XtGeometryResult QueryGeometry (Widget, XtWidgetGeometry *, XtWidgetGeometry *);
static void GetDesiredSize (Widget);
#ifdef MOTIF
static void Redisplay (Widget, XEvent *, Region);
#endif

static void LayoutLayout (LayoutWidget, Bool);
static void LayoutGetNaturalSize (LayoutWidget, Dimension *, Dimension *);
static void LayoutFreeLayout (BoxPtr);

#ifdef MOTIF
#define SuperClass ((ConstraintWidgetClass)&xmManagerClassRec)
#else
#define SuperClass ((ConstraintWidgetClass)&constraintClassRec)
#endif

LayoutClassRec layoutClassRec = {
   {
/* core class fields */
    /* superclass         */   (WidgetClass) SuperClass,
    /* class name         */   "Layout",
    /* size               */   sizeof(LayoutRec),
    /* class_initialize   */   ClassInitialize,
    /* class_part init    */   NULL,
    /* class_inited       */   FALSE,
    /* initialize         */   Initialize,
    /* initialize_hook    */   NULL,
    /* realize            */   XtInheritRealize,
    /* actions            */   NULL,
    /* num_actions        */   0,
    /* resources          */   resources,
    /* resource_count     */   XtNumber(resources),
    /* xrm_class          */   NULLQUARK,
    /* compress_motion    */   FALSE,
    /* compress_exposure  */   0,
    /* compress_enterleave*/   FALSE,
    /* visible_interest   */   FALSE,
    /* destroy            */   NULL,
    /* resize             */   Resize,
#ifdef MOTIF
    /* expose             */   Redisplay,
#else
    /* expose             */   NULL,
#endif
    /* set_values         */   SetValues,
    /* set_values_hook    */   NULL,
    /* set_values_almost  */   XtInheritSetValuesAlmost,
    /* get_values_hook    */   NULL,
    /* accept_focus       */   NULL,
    /* version            */   XtVersion,
    /* callback_private   */   NULL,
#ifdef MOTIF
    /* tm_table           */   XtInheritTranslations,
#else
    /* tm_table           */   NULL,
#endif
    /* query_geometry	  */   QueryGeometry,
    /* display_accelerator*/   XtInheritDisplayAccelerator,
    /* extension          */   NULL
   }, {
/* composite class fields */
    /* geometry_manager   */   GeometryManager,
    /* change_managed     */   ChangeManaged,
    /* insert_child       */   InsertChild,
    /* delete_child       */   XtInheritDeleteChild,
    /* extension          */   NULL
   }, {
/* constraint class fields */
    /* subresources       */   NULL,
    /* subresource_count  */   0,
    /* constraint_size    */   sizeof(LayoutConstraintsRec),
    /* initialize         */   NULL,
    /* destroy            */   NULL,
    /* set_values         */   NULL,
    /* extension          */   NULL
   },
#ifdef MOTIF
   {
    /* manager class */
    XtInheritTranslations,                /* translations           */
    NULL,                                 /* syn resources          */
    0,                                    /* num syn_resources      */
    NULL,                                 /* get_cont_resources     */
    0,                                    /* num_get_cont_resources */
    XmInheritParentProcess,               /* parent_process       */
    NULL,                                 /* extension              */
   },
#endif
   { /* layout_class fields */
    0
   }
};

WidgetClass layoutWidgetClass = (WidgetClass) &layoutClassRec;

#define ForAllChildren(pw, childP) \
  for ( (childP) = (pw)->composite.children ; \
        (childP) < (pw)->composite.children + (pw)->composite.num_children ; \
        (childP)++ ) if (!XtIsManaged(*childP)) ; else

/************************************************************
 *
 * Semi-public routines.
 *
 ************************************************************/

/*	Function Name: ClassInitialize
 *	Description: The Layout widgets class initialization proc.
 *	Arguments: none.
 *	Returns: none.
 */

/*ARGSUSED*/
static Boolean
CvtStringToLayout (Display *dpy, XrmValue *args, Cardinal *num_args,
                   XrmValue *from, XrmValue *to, XtPointer *converter_data)
{
    static BoxPtr tmp;

    LayYYsetsource ((char *) from->addr);
    if (!to->addr) to->addr = (XtPointer)&tmp;
    LayYYsetdest ((BoxPtr *) to->addr);
    to->size = sizeof (BoxPtr *);
    return  LayYYparse() ? FALSE : TRUE;
}

/*ARGSUSED*/
static void
DisposeLayout (XtAppContext app, XrmValue *to, XtPointer data, XrmValuePtr args,
               Cardinal *num_args)
{
    LayoutFreeLayout (* (LayoutPtr *) to->addr);
}

static void
ClassInitialize(void)
{
    XtSetTypeConverter ( XtRString, XtRLayout, CvtStringToLayout,
		    (XtConvertArgList)NULL, (Cardinal)0, XtCacheNone,
 		    DisposeLayout );
}

#ifdef MOTIF
static void
Redisplay (Widget gw, XEvent *event, Region region)
{
   /*
    * If the Layout widget is visible, redraw gadgets.
    */

    if ( XtIsRealized ( gw ) && gw->core.visible )
    {
        _XmRedisplayGadgets ( gw, event, region );
    }
    /* ChangeManaged(gw);*/
}
#endif

/*ARGSUSED*/
static XtGeometryResult
GeometryManager(Widget child, XtWidgetGeometry *request, XtWidgetGeometry *reply)
{
    LayoutWidget    w = (LayoutWidget) XtParent(child);
    SubInfoPtr	    p = SubInfo(child);
    int		    bw;
    Bool	    changed, bwChanged;

    bw = p->naturalBw;
    changed = FALSE;
    bwChanged = FALSE;
    if (request->request_mode & CWBorderWidth &&
	request->border_width != child->core.border_width)
    {
	p->naturalBw = bw;
	bw = request->border_width;
	changed = TRUE;
	bwChanged = TRUE;
    }
    if (bwChanged || ((request->request_mode & CWWidth) &&
	request->width != child->core.width))
    {
	p->naturalSize[LayoutHorizontal] = request->width + bw * 2;
	changed = TRUE;
    }
    if (bwChanged || ((request->request_mode & CWHeight) &&
	request->height != child->core.height))
    {
	p->naturalSize[LayoutVertical] = request->height + bw * 2;
	changed = TRUE;
    }
    if (changed)
	LayoutLayout (w, TRUE);
    return XtGeometryDone;
}

/* ARGSUSED */
static void
Initialize(Widget request, Widget new, ArgList args, Cardinal *num_args)
{
/*    LayoutWidget w = (LayoutWidget)new; */
}

static void
ChangeManaged(Widget gw)
{
    LayoutWidget	w = (LayoutWidget) gw;
    Widget		*children;

    DBUG_ENTER("changeManaged");

    ForAllChildren (w, children)
	GetDesiredSize (*children);
    LayoutLayout ((LayoutWidget) w, TRUE);
#ifdef MOTIF
    _XmNavigChangeManaged ( gw );
#endif
    DBUG_VOID_RETURN;
}

static void
GetDesiredSize (Widget child)
{
    XtWidgetGeometry	desired;
    SubInfoPtr		p;

    XtQueryGeometry (child, (XtWidgetGeometry *) NULL, &desired);
    p = SubInfo (child);
    p->naturalBw = desired.border_width;
    p->naturalSize[LayoutHorizontal] = desired.width + desired.border_width * 2;
    p->naturalSize[LayoutVertical] = desired.height + desired.border_width * 2;
}

static void
InsertChild (Widget child)
{
    (*SuperClass->composite_class.insert_child) (child);
    GetDesiredSize (child);
}

static void
Resize(Widget gw)
{
    LayoutLayout ((LayoutWidget) gw, FALSE);
}

/* ARGSUSED */
static Boolean
SetValues(Widget gold, Widget greq, Widget gnew, ArgList args, Cardinal *num_args)
{
    LayoutWidget    old = (LayoutWidget) gold,
		    new = (LayoutWidget) gnew;

    if (old->layout.layout != new->layout.layout)
	LayoutLayout (new, TRUE);
    return FALSE;
} /* SetValues */

static XtGeometryResult
QueryGeometry (Widget gw, XtWidgetGeometry *request, XtWidgetGeometry *prefered_return)
{
    LayoutWidget	w = (LayoutWidget) gw;
    XtGeometryResult	result;
    XtWidgetGeometry	prefered_size;

    if (request && !(request->request_mode & (CWWidth|CWHeight)))
	return XtGeometryYes;
    LayoutGetNaturalSize (w, &prefered_size.width, &prefered_size.height);
    prefered_return->request_mode = 0;
    result = XtGeometryYes;
    if (!request) {
	prefered_return->width = prefered_size.width;
	prefered_return->height= prefered_size.height;
	if (prefered_size.width != w->core.width) {
	    prefered_return->request_mode |= CWWidth;
	    result = XtGeometryAlmost;
	}
	if (prefered_size.height != w->core.height) {
	    prefered_return->request_mode |= CWHeight;
	    result = XtGeometryAlmost;
	}
    } else {
    	if (request->request_mode & CWWidth) {
	    if (prefered_size.width > request->width)
	    {
	    	if (prefered_size.width == w->core.width)
		    result = XtGeometryNo;
	    	else if (result != XtGeometryNo) {
		    result = XtGeometryAlmost;
		    prefered_return->request_mode |= CWWidth;
		    prefered_return->width = prefered_size.width;
	    	}
	    }
    	}
    	if (request->request_mode & CWHeight) {
	    if (prefered_size.height > request->height)
	    {
	    	if (prefered_size.height == w->core.height)
		    result = XtGeometryNo;
	    	else if (result != XtGeometryNo) {
		    result = XtGeometryAlmost;
		    prefered_return->request_mode |= CWHeight;
		    prefered_return->height = prefered_size.height;
	    	}
	    }
    	}
    }
    return result;
}

/*
 * Layout section.  Exports LayoutGetNaturalSize and
 * LayoutLayout to above section
 */

static void
PrintGlue (GlueRec g)
{
    if (g.order == 0 || g.value != 1.0)
	(void) printf ("%g", g.value);
    if (g.order > 0)
    {
	(void) printf ("%s", " inf");
	if (g.order > 1)
	    (void) printf (" %d", g.order);
    }
}

static void
PrintDirection (LayoutDirection dir)
{
    switch (dir) {
    case LayoutHorizontal:
	(void) printf ("%s", "horizontal");
	break;
    case LayoutVertical:
	(void) printf ("%s", "vertical");
	break;
    default:
	(void) printf ("Unknown layout direction %d\n", dir);
	break;

    }
}

static void
TabTo(int level)
{
    while (level--)
	(void) printf ("%s", "  ");
}

static void
PrintBox (BoxPtr box, int level)
{
    BoxPtr	child;

    TabTo (level);
    (void) printf ("%s", "< ");
    (void) printf ("%s", " + ");
    PrintGlue (box->params.stretch[LayoutHorizontal]);
    (void) printf ("%s", " - ");
    PrintGlue (box->params.shrink[LayoutHorizontal]);
    (void) printf ("%s", " * ");
    (void) printf ("%s", " + ");
    PrintGlue (box->params.stretch[LayoutVertical]);
    (void) printf ("%s", " - ");
    PrintGlue (box->params.shrink[LayoutVertical]);
    (void) printf ("%s", " >");
    (void) printf (" size: %d x %d", box->size[0], box->size[1]);
    (void) printf (" natural: %d x %d ", box->natural[0], box->natural[1]);
    switch (box->type) {
    case BoxBox:
	PrintDirection (box->u.box.dir);
	(void) printf ("%s\n", "");
	for (child = box->u.box.firstChild; child; child = child->nextSibling)
	    PrintBox (child, level+1);
	break;
    case WidgetBox:
	(void) printf (" %s\n", XrmQuarkToString (box->u.widget.quark));
	break;
    case GlueBox:
	(void) printf ("%s\n", " glue");
	break;
    case VariableBox:
	(void) printf (" variable %s\n", XrmQuarkToString (box->u.variable.quark));
	break;
    }
}

static ExprPtr
LookupVariable (BoxPtr child, XrmQuark quark)
{
    BoxPtr	parent, box;

    DBUG_ENTER("LookupVariable");
    DBUG_PRINT("name = <%s>",XrmQuarkToString(quark));
    DBUG_PRINT("child = %p",child);
    while ((parent = child->parent))
    {
	for (box = parent->u.box.firstChild;
	     box != child;
	     box = box->nextSibling)
	{
	    if (box->type == VariableBox && box->u.variable.quark == quark)
		DBUG_RETURN("%p", box->u.variable.expr);
	}
	child = parent;
    }
    DBUG_RETURN("failure -> %d",0);
}

static double
Evaluate (LayoutWidget l, BoxPtr box, ExprPtr expr, double natural)
{
    double	left, right, down;
    Widget	widget;
    SubInfoPtr	info;

    DBUG_PRINT("Evaluate %d", expr->type);
    switch (expr->type) {
    case Constant:
	return expr->u.constant;
    case Binary:
	left = Evaluate (l, box, expr->u.binary.left, natural);
	right = Evaluate (l, box, expr->u.binary.right, natural);
	switch (expr->u.binary.op) {
        case Plus:
	    return left + right;
	case Minus:
	    return left - right;
	case Times:
	    return left * right;
	case Divide:
	    return left / right;
	case Percent:
	    return right * left / 100.0;
	}
    case Unary:
	down = Evaluate (l, box, expr->u.unary.down, natural);
	switch (expr->u.unary.op) {
	case Percent:
	    return natural * down / 100.0;
	case Minus:
	    return -down;
	case Plus:
	case Times:
	case Divide:
	    break;
	}
    case Width:
	widget = QuarkToWidget (l, expr->u.width);
	if (!widget)
	    return 0;
	info = SubInfo (widget);
	return info->naturalSize[LayoutHorizontal];
    case Height:
	widget = QuarkToWidget (l, expr->u.height);
	if (!widget)
	    return 0;
	info = SubInfo (widget);
	return info->naturalSize[LayoutVertical];
    case Variable:
        {
	/* in the original code there was no nexpr,
	   expr was overwritten by LookupVariable and
	   the expression "expr->u.variable" to obtain the
	   variable name for the errormessage cause a segmentation
	   violation */
	ExprPtr    nexpr;
	nexpr = LookupVariable (box, expr->u.variable);
	if (!nexpr)
	    {
	    char    buf[256];
	    (void) sprintf (buf, "Layout: undefined variable %s\n",
			    XrmQuarkToString (expr->u.variable));
	    XtError (buf);
	    return 0.0;
	    }
	return Evaluate (l, box, nexpr, natural);
	}
    }
    return 0.0;
}

static void
DisposeExpr (ExprPtr expr)
{
    if (!expr)
	return;
    switch (expr->type) {
    case Constant:
	break;
    case Binary:
	DisposeExpr (expr->u.binary.left);
	DisposeExpr (expr->u.binary.right);
	break;
    case Unary:
	DisposeExpr (expr->u.unary.down);
	break;
    case Width:
    case Height:
    case Variable:
	break;
    }
    Dispose (expr);
}

#define CheckGlue(l, box, glue, n) { \
    if (glue.expr) \
	glue.value = Evaluate (l, box, glue.expr, n); \
    if (glue.order == 0 && glue.value == 0) \
	glue.order = -1; \
    else if (glue.order == -1 && glue.value != 0) \
	glue.order = 0; \
}

#define DoStretch(l, box, dir) \
    CheckGlue (l, box, box->params.stretch[dir], (double) box->natural[dir]);

#define DoShrink(l, box, dir) \
    CheckGlue (l, box, box->params.shrink[dir], (double) box->natural[dir])

/* compute the natural sizes of a box */
static void
ComputeNaturalSizes (LayoutWidget l, BoxPtr box, LayoutDirection dir)
{
    BoxPtr	child;
    Widget	w;
    SubInfoPtr	info;
    int		minStretchOrder, minShrinkOrder;
    LayoutDirection thisDir;

    DBUG_ENTER("ComputeNaturalSizes");
    DBUG_PRINT("box->type=%d",box->type);
    switch (box->type) {
    case WidgetBox:
	w = box->u.widget.widget = QuarkToWidget (l, box->u.widget.quark);
	if (!w)
	{
	    box->natural[LayoutHorizontal] = 0;
	    box->natural[LayoutVertical] = 0;
	}
	else
	{
	    info = SubInfo (w);
	    box->natural[LayoutHorizontal] = info->naturalSize[LayoutHorizontal];
	    box->natural[LayoutVertical] = info->naturalSize[LayoutVertical];
	}
	DoStretch (l, box, dir);
	DoShrink (l, box, dir);
	DoStretch (l, box, !dir);
	DoShrink (l, box, !dir);
	break;
    case GlueBox:
	box->natural[dir] = Evaluate (l, box, box->u.glue.expr, 0.0);
	box->natural[!dir] = 0;
	DoStretch (l, box, dir);
	DoShrink (l, box, dir);
	break;
    case BoxBox:
	thisDir = box->u.box.dir;
	box->natural[0] = 0;
	box->natural[1] = 0;
	minStretchOrder = 100000;
	minShrinkOrder = 100000;
	ZeroGlue (box->params.shrink[thisDir]);
	ZeroGlue (box->params.stretch[thisDir]);
	box->params.shrink[!thisDir].order = 100000;
	box->params.stretch[!thisDir].order = 100000;
	for (child = box->u.box.firstChild; child; child = child->nextSibling)
	{
	    ComputeNaturalSizes (l, child, thisDir);
	    /*
	     * along box axis:
	     *  normal size += child normal size
	     *  shrink += child shrink
	     *  stretch += child stretch
	     */
	    box->natural[thisDir] += child->natural[thisDir];
	    AddGlue (box->params.shrink[thisDir],
		     box->params.shrink[thisDir],
		     child->params.shrink[thisDir]);
	    AddGlue (box->params.stretch[thisDir],
		     box->params.stretch[thisDir],
		     child->params.stretch[thisDir]);
	    /*
	     * normal to box axis:
	     *  normal size = maximum child normal size of minimum shrink order
	     *  shrink = difference between normal size and minimum shrink
	     *  stretch = minimum child stretch
	     */
	    if (box->natural[!thisDir] >= child->natural[!thisDir])
	    {
		if (child->params.stretch[!thisDir].order < minShrinkOrder)
		{
		    box->natural[!thisDir] = child->natural[!thisDir];
		    minStretchOrder = child->params.stretch[!thisDir].order;
		    if (child->params.shrink[!thisDir].order < minShrinkOrder)
			minShrinkOrder = child->params.shrink[!thisDir].order;
		}
	    }
	    else
	    {
		if (child->params.shrink[!thisDir].order <= minStretchOrder)
		{
		    box->natural[!thisDir] = child->natural[!thisDir];
		    minShrinkOrder = child->params.shrink[!thisDir].order;
		    if (child->params.stretch[!thisDir].order < minStretchOrder)
			minStretchOrder = child->params.stretch[!thisDir].order;
		}
	    }
	    MinGlue (box->params.stretch[!thisDir],
		     box->params.stretch[!thisDir],
		     child->params.stretch[!thisDir]);
	    MinGlue (box->params.shrink[!thisDir],
		     box->params.shrink[!thisDir],
		     child->params.shrink[!thisDir]);
	}
	if (box->params.shrink[!thisDir].order <= 0)
	{
	    int	    minSize;
	    int	    largestMinSize;

	    largestMinSize = 0;
	    for (child = box->u.box.firstChild; child; child = child->nextSibling)
	    {
		if (child->params.shrink[!thisDir].order <= 0)
		{
		    minSize = child->natural[!thisDir] -
			      child->params.shrink[!thisDir].value;
		    if (minSize > largestMinSize)
			largestMinSize = minSize;
		}
	    }
	    box->params.shrink[!thisDir].value = box->natural[!thisDir] -
						 largestMinSize;
	    if (box->params.shrink[!thisDir].value == 0)
		box->params.shrink[!thisDir].order = -1;
	    else
		box->params.shrink[!thisDir].order = 0;
	}
        break;
    case VariableBox:
        break;
    }
    DBUG_VOID_RETURN;
}

/* given the box's geometry, set the geometry of the pieces */

#define GluePart(a,b,dist)	((a) ? ((int) (((a) * (dist)) / (b) + \
					((dist >= 0) ? 0.5 : -0.5))) : 0)

static Bool
ComputeSizes (BoxPtr box)
{
    LayoutDirection dir;
    BoxPtr	    child;
    GlueRec	    stretch;
    GlueRec	    shrink;
    GlueRec	    totalGlue[2];
    double	    remainingGlue;
    GluePtr	    glue;
    int		    size;
    int		    totalSizes;
    int		    totalChange[2];
    int		    change;
    int		    remainingChange;
    Bool	    shrinking;
    Bool	    happy;
    int		    i;
    int		    maxGlue;

    dir = box->u.box.dir;
    size = box->size[dir];

    stretch = box->params.stretch[dir];
    shrink = box->params.shrink[dir];

    /* pick the correct adjustment parameters based on the change direction */

    totalChange[0] = size - box->natural[dir];

    shrinking = totalChange[0] < 0;

    totalChange[1] = 0;
    totalGlue[1].order = 100000;
    totalGlue[1].value = 0;
    maxGlue = 1;
    if (shrinking)
    {
	totalGlue[0] = shrink;
	/* for first-order infinites, shrink it to zero and then
	 * shrink the zero-orders
	 */
	if (shrink.order == 1) {
	    totalSizes = 0;
	    remainingGlue = 0;
	    for (child = box->u.box.firstChild;
		 child;
		 child = child->nextSibling)
	    {
		switch (child->params.shrink[dir].order) {
		case 0:
		    remainingGlue += child->params.shrink[dir].value;
		    break;
		case 1:
		    totalSizes += child->natural[dir];
		    break;
		}
	    }
	    if (totalSizes < -totalChange[0])
	    {
		totalGlue[1] = shrink;
		totalGlue[0].order = 0;
		totalGlue[0].value = remainingGlue;
		totalChange[1] = -totalSizes;
		totalChange[0] = totalChange[0] - totalChange[1];
		maxGlue = 2;
	    }
	}
	if (totalGlue[0].order <= 0 &&
	    totalChange[0] > totalGlue[0].value)
	{
	    totalChange[0] = totalGlue[0].value;
	}
    }
    else
	totalGlue[0] = stretch;

    /* adjust each box */
    totalSizes = 0;
    remainingGlue = totalGlue[0].value + totalGlue[1].value;
    remainingChange = totalChange[0] + totalChange[1];
    happy = True;
    for (child = box->u.box.firstChild; child; child = child->nextSibling)
    {
        /* never add glue or stretch to a VariableBox! */
        if (child->type == VariableBox) continue;

	if (shrinking)
	    glue = &child->params.shrink[dir];
	else
	    glue = &child->params.stretch[dir];

	child->size[dir] = child->natural[dir];
	for (i = 0; i < maxGlue; i++)
	{
	    if (glue->order == totalGlue[i].order)
	    {
		remainingGlue -= glue->value;
		if (remainingGlue <= 0)
		    change = remainingChange;
		else
		    change = GluePart (glue->value,
				       totalGlue[i].value,
				       totalChange[i]);
		child->size[dir] += change;
		remainingChange -= change;
	    }
	}
	child->size[!dir] = box->size[!dir];
	totalSizes += child->size[dir];
	if (child->type == BoxBox)
	    if (!ComputeSizes (child))
		happy = False;
    }
    return totalSizes == box->size[dir] && happy;
}

static void
SetSizes (BoxPtr box, Position x, Position y)
{
    BoxPtr	child;
    int		width, height;
    int		bw;
    Widget	w;
    SubInfoPtr	info;

    switch (box->type) {
    case WidgetBox:
	w = box->u.widget.widget;
	if (w)
	{
	    info = SubInfo(w);
	    /* info = (SubInfoPtr) w->core.constraints; */
	    width = box->size[LayoutHorizontal];
	    height = box->size[LayoutVertical];
	    bw = info->naturalBw;
	    width -= bw * 2;
	    height -= bw * 2;
	    /* Widgets which grow too small are placed off screen */
	    if (width <= 0 || height <= 0)
	    {
		width = 1;
		height = 1;
		bw = 0;
		x = -1;
		y = -1;
	    }
	    XtConfigureWidget (w, x, y,
			      (Dimension)width, (Dimension)height,
			      (Dimension)bw);
	}
	break;
    case BoxBox:
	for (child = box->u.box.firstChild; child; child = child->nextSibling)
	{
	    SetSizes (child, x, y);
	    if (box->u.box.dir == LayoutHorizontal)
		x += child->size[LayoutHorizontal];
	    else
		y += child->size[LayoutVertical];
	}
	break;
    case GlueBox:
    case VariableBox:
	break;
    }
}

static void
LayoutFreeLayout (BoxPtr box)
{
    BoxPtr  child, next;

    switch (box->type) {
    case BoxBox:
	for (child = box->u.box.firstChild; child; child = next)
	{
	    next = child->nextSibling;
	    LayoutFreeLayout (child);
	}
	break;
    case GlueBox:
	DisposeExpr (box->u.glue.expr);
	break;
    case WidgetBox:
    case VariableBox:
    default:
	break;
    }
    DisposeExpr (box->params.stretch[LayoutHorizontal].expr);
    DisposeExpr (box->params.shrink[LayoutHorizontal].expr);
    DisposeExpr (box->params.stretch[LayoutVertical].expr);
    DisposeExpr (box->params.shrink[LayoutVertical].expr);
    Dispose (box);
}


static void
LayoutGetNaturalSize (LayoutWidget l, Dimension *widthp, Dimension *heightp)
{
    BoxPtr		box;

    DBUG_ENTER("LayoutGetNaturalSize");
    box = l->layout.layout;
    if (box)
    {
	ComputeNaturalSizes (l, box, LayoutHorizontal);
	*widthp = box->natural[LayoutHorizontal];
	*heightp = box->natural[LayoutVertical];
    }
    else
    {
	*widthp = 0;
	*heightp = 0;
    }
    DBUG_VOID_RETURN;
}

static void
LayoutLayout (LayoutWidget l, Bool attemptResize)
{
    BoxPtr		box;
    Dimension		width, height;
    Dimension		prefered_width, prefered_height;

    DBUG_ENTER("LayoutLayout");
    box = l->layout.layout;
    if (!box)
	return;
    LayoutGetNaturalSize (l, &prefered_width, &prefered_height);
    if (l->core.width == 0 || l->core.height == 0)
    {
	l->core.width = prefered_width;
	l->core.height = prefered_height;
    }
    box->size[LayoutHorizontal] = l->core.width;
    box->size[LayoutVertical] = l->core.height;
    if (!ComputeSizes (box) && attemptResize)
    {
	XtMakeResizeRequest ((Widget) l,
			    prefered_width, prefered_height,
			    &width, &height);
	if (width != box->size[LayoutHorizontal] ||
	    height != box->size[LayoutVertical])
	{
	    box->size[LayoutHorizontal] = width;
	    box->size[LayoutVertical] = height;
	    ComputeSizes (box);
	}
    }
    if (l->layout.debug)
    {
	PrintBox (box, 0);
	fflush (stdout);
    }
    SetSizes (box, 0, 0);
    DBUG_VOID_RETURN;
}