# Layout management

Abigail Adams, wife of John Adams, in a letter to John Thaxter (1778-09-29)

If we do not lay out ourselves in the service of mankind, whom should we serve?

## Introduction

Layout management in Clutter controls how an actor and children "inside" that actor are sized and positioned. More specifically, layouts are managed by associating a parent with a ClutterLayoutManager; the parent is usually either a composite ClutterActor (composed of several ClutterActors) or a ClutterContainer (containing child ClutterActors). The ClutterLayoutManager then manages:

1. The size requisition (determination of the desired height and width) of the parent.

2. The allocation (size and position) assigned to each composed or child ClutterActor.

To make this more concrete, imagine you have a sheet of paper and some coloured squares to place on it. Someone stands next to you telling you how big the piece of paper should be, how big the squares should be, and where to put each square on the piece of paper.

The sheet of paper is analogous to the container or composite actor; the squares are analogous to the child ClutterActors; and the person giving you instructions is analogous to the layout manager.

The following sections give an overview of how layout management works in Clutter.

### Using layouts

Although Clutter provides plenty of flexibility in how you can use layout management, the simplest way to get started is to use the built-in ClutterBox class with one of the provided ClutterLayoutManager implementations.

The pattern for doing this is:

- Create an instance of one of the ClutterLayoutManager implementations (see the following section).

- Configure the layout manager's default policies (e.g. how actors are aligned by default, whether to pack actors horizontally or vertically, spacing between actors in the layout).

- Create a ClutterBox, setting its layout manager to the one you just created.

- Pack actors into the ClutterBox, setting layout properties (if required) as each is added.

- Modify layout properties of child actors using `clutter_layout_manager_child_set()` (if required).

Individual recipes in this section give more examples of how to make use of the different layout manager implementations.

It is not possible to use a layout manager with an arbitrary ClutterContainer: you must use a ClutterActor subclass which can delegate its layout to a layout manager (either use ClutterBox or write your own).

### Types of layout manager

Clutter provides a range of layout managers suitable for different use cases:

- ClutterFixedLayout arranges actors at fixed positions on the stage. No alignment options are available, so you have to manually compute and manage the coordinates (or use ClutterConstraints) which will align actors how you want them.

- ClutterBinLayout arranges actors in a depth-ordered stack on top of each other, aligned to the container. This is useful for arranging actors inside composites (e.g. creating a button widget from a ClutterTexture with a ClutterText on top of it).

- ClutterBoxLayout arranges actors in a single horizontal row or vertical column. This type of layout is common in UI elements like toolbars and menus.

- ClutterFlowLayout arranges actors in reflowing columns and rows. If the container's allocation changes, the child actors are rearranged to fit inside its new allocation. This can be useful for arranging actors where you're not sure how many there might be; or where new ones are going to be added into the UI, perhaps displacing others. An example might be a photo viewer or an RSS feed display.

### Layout properties

How actors are sized and positioned inside a container associated with a layout manager depends on two things:

1. #### Properties which apply to all actors added to the layout

   There will be one setting at the layout level which can't be overridden per actor. This includes properties like spacing between rows and columns, whether the layout is homogenous (each actor gets the same allocation), etc.

2. #### Properties for each actor added to the layout

   These are properties of the relationship between the layout, the container associated with the layout, and the children of the container. Each layout/container/actor combination can have different settings for each of these properties.

Each layout manager implementation supports a subset of the following layout properties; different managers may have different names or functions for setting them, but the functionality remains the same. Individual recipes give more details about which properties can be set for each layout manager implementation.

- #### Alignment

  How an actor aligns to the container's axes, e.g. aligned to the container's left, right, or center. For some layouts (like ClutterBinLayout) alignment is also used to set expand and fill properties.

- #### Horizontal/vertical orientation

  Whether actors are arranged in a horizontal row or vertical column.

- #### Homogenous rows and columns

  Grid-like layouts (e.g. ClutterFlowLayout) can be configured to have uniform rows and/or columns, expanding to fit the largest actor they contain.

- #### Row height and column width

  Grid-like layouts arranged in rows and columns can be configured with maximum and minimum row height and column width.

- #### Row and column spacing

  Grid-like layouts enable you to define a space (in pixels) between rows and columns.

- #### Expand

  Some layouts can be configured to minimize their size request to fit the actors they contain (expand is FALSE); or to increase the allocation of actors they contain so that all available space in the layout is used (expand is TRUE). In the latter case, you'd also need to set a size for the container associated with the layout, otherwise the container will just fit itself to the actors inside it.

- #### Fill

  This property only has an effect when expand is on. The fill setting controls whether actors are resized to fill their allocation (fill is TRUE); or if the space around the actor is increased (fill is FALSE).

- #### Pack at start/end

  This controls whether actors at prepended or appended to the layout.

  - If the orientation is vertical, prepended actors are added to the top of the layout and appended actors to the bottom.

  - If the orientation is horizontal, prepended actors are added at the left of the layout and appended actors on the right.

#### Setting layout properties

Layout properties can be set in one or more of the following ways (depending on the type of property and the layout manager):

1. By setting a default value for the property on the layout manager (e.g. using `clutter_bin_layout_set_alignment()`, `clutter_box_layout_set_expand()`). Any actor added to the layout gets this value for the property, unless it is overridden for that actor.

2. When adding an actor to a ClutterBox container using `clutter_box_pack()`, you can set properties on the actor which you're adding.

3. When adding an actor to a layout you can use a function which enables setting properties simultaneously (e.g. `clutter_box_layout_pack()`, `clutter_bin_layout_add()`).

4. By using `clutter_layout_manager_child_set()` on the child of a layout.

### Not using layout managers

It is perfectly possible to arrange ClutterActors without using layout managers; however, you may have to do more of your own calculations about actor sizes and positions.

There are two (not mutually-exclusive) approaches you can take to do this, described below.

#### Manual positioning and alignment

This basically means using the ClutterActor bounding box mechanism (see the ClutterActor documentation for details) to set actor sizes and positions. This is the approach you will see in a lot of older Clutter code (written before layout managers were available).

This approach is simplest where the UI is relatively static and is composed of a few known actors. It will work in larger, more complex scenarios, but in those sorts of cases it is better to make use of layout managers and constraints (see below) instead.

#### Using ClutterConstraint

Constraints provide mechanisms for:

- Aligning actors with each other (ClutterAlignConstraint). For example, you can align the top, bottom or center of one actor with the top, bottom or center of another (on the `y` axis). Similarly, you can align one actor to another on the `x` axis.

- Binding properties of one actor to those of another. For example, you could ensure that two actors always remain the same width; or you could specify that two actors always have the same `x` coordinate. In both these cases and others, you can specify that the properties should be the same, or the same +/- some offset.

ClutterConstraints can be used in combination with some layout managers, but you need to be careful that constraints don't fight with the layout manager policies. Unpredictable results could ensue.

## Stacking actors on top of each other

### Problem

You want to lay out several actors so that they are in layers on top of each other (e.g. to create a button widget composed from a rectangle with text on top of it).

### Solution

The most flexible approach is to use a ClutterBinLayout associated with a ClutterBox:

    /* define some colors */
    const ClutterColor background_color = { 0xaa, 0x99, 0x00, 0xff };
    const ClutterColor text_color = { 0xff, 0xff, 0xff, 0xff };

    ClutterLayoutManager *layout;
    ClutterActor *box;
    ClutterActor *background;
    ClutterActor *text;

    /*
     * create a layout, setting the default x and y alignment;
     * actors fill the whole allocation of the layout's container
     * by default
     */
    layout = clutter_bin_layout_new (CLUTTER_BIN_ALIGNMENT_FILL,
                                     CLUTTER_BIN_ALIGNMENT_FILL);

    /* create the box whose children the layout will manage */
    box = clutter_box_new (layout);

    /*
     * fill doesn't have much effect here
     * unless the container has height and/or width
     */
    clutter_actor_set_size (box, 100, 30);

    /*
     * background for the button; could equally be a texture
     * with an image loaded into it or any other ClutterActor
     */
    background = clutter_rectangle_new_with_color (&background_color);

    /*
     * add the background to the container;
     * as it should use the default alignment, it can be added
     * direct to the container, rather than via the layout
     */
    clutter_container_add_actor (CLUTTER_CONTAINER (box), background);

    /* text for the button */
    text = clutter_text_new_full ("Sans 15px", "Click me", &text_color);

    /*
     * the text requires a different alignment from the background
     * (centered on the box)
     * so we add it via the layout so the default
     * alignment can be overridden
     */
    clutter_bin_layout_add (CLUTTER_BIN_LAYOUT (layout),
                            text,
                            CLUTTER_BIN_ALIGNMENT_CENTER,
                            CLUTTER_BIN_ALIGNMENT_CENTER);

    /*
     * ensure the actors are arranged in the correct depth order;
     * in this case, the text is on top
     * (NB this is not strictly necesary here as text is added after
     * background)
     */
    clutter_actor_raise_top (text);

### Discussion

This section covers some other aspects of using a ClutterBinLayout.

#### Setting and changing alignment

Alignment is the only layout property available for ClutterBinLayout. Each actor can have a different setting for its alignment in one or both of the `x` or `y` axes. However, as shown in the solution above, alignment can also be used to expand an actor to fill the container (`CLUTTER_BIN_ALIGNMENT_FILL`) in one or both axes.

Setting alignment does not have any effect if the container is the same size as all of the actors inside it: in this case, every alignment produces the same layout. But if the container associated with the layout is larger than the actor being aligned, alignment will have an effect; see this section for more details.

Changing an actor's alignment after it has been added to a ClutterBinLayout may make the actor "jump" (without animation) to a new position and/or change its size. The exception is changing from some other alignment to `CLUTTER_BIN_ALIGNMENT_FIXED`: in this case, the actor will retain the position and size it had before its alignment was fixed.

#### Size requisitioning

A container with a ClutterBinLayout will by default request the width of the widest actor in it, and the height of the tallest. If you add actors smaller than those dimensions, they will be aligned inside the container according to the layout's policies. Here's an example where a ClutterBinLayout requests a size to encompass the tallest (light grey rectangle) and widest (dark grey rectangle) actors inside it, with other actors aligned within those bounds:

Size requisition in a ClutterBinLayout

The screenshot also shows the 9 possible combinations of start, center and end alignments on the `x` and `y` axes. See the sample code for more details.

The white space is the stage visible behind the ClutterBox holding the coloured rectangles. Notice that the layout is the width of the widest actor within it and the height of the tallest.

You can also manually set a size on the container associated with a layout to override the automatically-computed size requisition.

#### Depth ordering

Another important consideration is the depth ordering of actors inside a ClutterBinLayout. By default, the depth ordering mirrors the order in which actors are added to the layout: the earlier an actor is added, the lower down in the depth order it is. If this isn't what you want, you can fix the depth ordering using `clutter_actor_raise()`, `clutter_actor_lower()` and their relatives.

#### Other ways to stack actors

ClutterBinLayout makes it simple to lay out large numbers of actors in a stack and align them to the container; see the example below which shows layering of many actors on top of each other.

However, if you have a small number of actors and you need some simple alignment, an alternative is to use manual positioning inside a ClutterFixedLayout (or even a ClutterGroup), possibly combined with ClutterConstraints to align actors with each other and bind their widths and heights together. See this section for more details.

### Full examples

#### ClutterBinLayout, with actors in 9 combinations of start, center and end alignment combinations

      a code sample should be here... but isn't

#### Layering multiple textures on top of each other inside a ClutterBinLayout

      a code sample should be here... but isn't

## Binding the size of one actor to the size of another

### Problem

You want one actor (the "target") to automatically change its width or height (or both) when the size of another actor (the "source") changes.

Example use cases:

- Making an actor adjust itself to the size of the stage (particularly when the stage is resizable).

- Putting one actor on top of another and keeping their sizes in sync.

### Solution

Create a ClutterBindConstraint bound to the width and/or height of one actor (the "source"). Add that constraint to an actor (the "target") whose size should follow the size of the source.

This short example shows how to create and add a constraint; `source` and `target` can be any two ClutterActors:

    ClutterConstraint *width_constraint;

    /* create a constraint which binds a target actor's width to 100px less than
     * the width of the source actor (use CLUTTER_BIND_HEIGHT to create a
     * constraint based on an actor's height)
     *
     * the third argument is a positive or negative offset from the actor's
     * dimension, in pixels; this is added to the height or width of the source
     * actor before the constraint is applied to the target actor
     */
    width_constraint = clutter_bind_constraint_new (source, CLUTTER_BIND_WIDTH, -100);

    /* add the constraint to an actor */
    clutter_actor_add_constraint (target, width_constraint);

Below is a full example, showing how to incorporate a constraint into a Clutter application.

#### Constraining the size of a texture to the size of the stage using ClutterBindConstraint

      a code sample should be here... but isn't

The texture in this example is 100px smaller than the stage, leaving a border of visible stage around the texture; and the texture has a tiled image on it. The tiling changes as the texture changes size. Also note that two ClutterAlignConstraints are added to center the actor on the stage.

The result looks like this:

A texture bound to the height and width of the stage using ClutterBindConstraint

### Discussion

Sizing constraints are a good solution in these cases:

- Where you can't use a layout manager. For example, you can't apply a layout manager to the stage directly; so if you want to control the size of an actor based on the size of the stage (as in the example above), constraints are a good substitute for a layout manager .

- Where the layout of a UI is fairly simple (perhaps up to half a dozen actors) and fairly static. An example might be something like a text editor, where the arrangement of the UI (menu bar, toolbar, editing panel, footer) changes infrequently. Of course, it is possible to arrange top-level components using constraints, but still use layout managers inside individual components (e.g. a flow layout manager to manage buttons in the toolbar).

- Where you have an actor whose size can change erratically, but you still want to be able to track its size to control another actor's size. An example might be an application like a drawing program, where a user can create their own actors: you might want the user to be able to describe loose, custom constraints between actors like "keep these actors at the same width", then allow those actors to be moved around and resized in a free-form way as a group. In this situation, a layout manager is too rigid and not appropriate; but adding ClutterConstraints to actors in response to user actions could work well.

  The sample code in the appendix is the kind of thing you might include in a drawing program: you can resize a texture with a key press (`+` to increase size, `-` to decrease), and click on the actor to select/deselect it (a semi-transparent overlay is toggled on the texture). The size of the overlay is bound and aligned to the texture, so that it covers and slightly overlaps the texture regardless of its size.

You can bind an actor to a single dimension (just height or depth) of another actor: you don't have to bind both height and width. Also, you don't have to bind both dimensions of the target to the same source: for example, you could bind the target's height to one source (actor A) and its width to another source (actor B).

A ClutterBindConstraint can also be used to constrain a target actor's position on the `x` and `y` axes to the position of a source actor. This is covered in another recipe.

#### Another way to bind actors' sizes together

There is another way to control the size of a target actor, based on the size of a source: you can create a handler for the `allocation-changed` signal of the source, emitted when its size and/or position changes. This signal includes all the data about the source's new allocation (height, width, x and y coordindates), which the handler function can then use to resize the target.

Alternatively, if you're only interested in a change to width or height, you can create a handler for the `notify::width` or `notify::height` signal (respectively), and modify the target's width/height in the handler.

This approach may be useful if you need a type of control over alignment and size which is not possible using constraints alone (e.g. one actor's size should be a proportion of another's). See the code in this section for an example where the size of one actor is dynamically set to 10% more than the size of another.

This recipe explains more about monitoring changes to an actor's size.

### Full examples

#### Creating an automatically-resizing overlay for a texture using ClutterBindConstraint

      a code sample should be here... but isn't

#### Using the `allocation-changed` signal of one actor to trigger proportional size changes in another

      a code sample should be here... but isn't