chiark / gitweb /
draw_thick_line: Bound thickness by 1.0 below
[sgt-puzzles.git] / devel.but
index 815fc1c410d49bf777bae807be369e663938f9f8..e59b2a265ce8c8cd3c04f680b883bc8ef5c9c621 100644 (file)
--- a/devel.but
+++ b/devel.but
@@ -32,7 +32,7 @@ Puzzle Collection (henceforth referred to simply as \q{Puzzles}),
 for use by anyone attempting to implement a new puzzle or port to a
 new platform.
 
-This guide is believed correct as of r6140. Hopefully it will be
+This guide is believed correct as of r6190. Hopefully it will be
 updated along with the code in future, but if not, I've at least
 left this version number in here so you can figure out what's
 changed by tracking commit comments from there onwards.
@@ -170,8 +170,8 @@ other miscellaneous functions. All of these are documented in
 
 There are a number of function call interfaces within Puzzles, and
 this guide will discuss each one in a chapter of its own. After
-that, there will be a section about how to design new games, with
-some general design thoughts and tips.
+that, \k{writing} discusses how to design new games, with some
+general design thoughts and tips.
 
 \C{backend} Interface to the back end
 
@@ -193,7 +193,9 @@ end module builds a different puzzle.
 \b On platforms such as MacOS X and PalmOS, which build all the
 puzzles into a single monolithic binary, the game structure in each
 back end must have a different name, and there's a helper module
-\c{list.c} which contains a complete list of those game structures.
+\c{list.c} (constructed automatically by the same Perl script that
+builds the \cw{Makefile}s) which contains a complete list of those
+game structures.
 
 On the latter type of platform, source files may assume that the
 preprocessor symbol \c{COMBINED} has been defined. Thus, the usual
@@ -389,8 +391,9 @@ with the default values, and returns a pointer to it.
 
 \c int (*fetch_preset)(int i, char **name, game_params **params);
 
-This function is used to populate the \q{Type} menu, which provides
-a list of conveniently accessible preset parameters for most games.
+This function is one of the two APIs a back end can provide to
+populate the \q{Type} menu, which provides a list of conveniently
+accessible preset parameters for most games.
 
 The function is called with \c{i} equal to the index of the preset
 required (numbering from zero). It returns \cw{FALSE} if that preset
@@ -404,9 +407,36 @@ returns \cw{TRUE}.
 If the game does not wish to support any presets at all, this
 function is permitted to return \cw{FALSE} always.
 
+If the game wants to return presets in the form of a hierarchical menu
+instead of a flat list (and, indeed, even if it doesn't), then it may
+set this function pointer to \cw{NULL}, and instead fill in the
+alternative function pointer \cw{preset_menu}
+(\k{backend-preset-menu}).
+
+\S{backend-preset-menu} \cw{preset_menu()}
+
+\c struct preset_menu *(*preset_menu)(void);
+
+This function is the more flexible of the two APIs by which a back end
+can define a collection of preset game parameters.
+
+This function simply returns a complete menu hierarchy, in the form of
+a \c{struct preset_menu} (see \k{midend-get-presets}) and further
+submenus (if it wishes) dangling off it. There are utility functions
+described in \k{utils-presets} to make it easy for the back end to
+construct this menu.
+
+If the game has no need to return a hierarchy of menus, it may instead
+opt to implement the \cw{fetch_preset()} function (see
+\k{backend-fetch-preset}).
+
+The game need not fill in the \c{id} fields in the preset menu
+structures. The mid-end will do that after it receives the structure
+from the game, and before passing it on to the front end.
+
 \S{backend-encode-params} \cw{encode_params()}
 
-\c char *(*encode_params)(game_params *params, int full);
+\c char *(*encode_params)(const game_params *params, int full);
 
 The job of this function is to take a \c{game_params}, and encode it
 in a string form for use in game IDs. The return value must be a
@@ -443,7 +473,7 @@ difficulty, since to describe a puzzle once generated it's
 sufficient to give the grid dimensions and the location and contents
 of the clue squares. (Indeed, one might very easily type in a puzzle
 out of a newspaper without \e{knowing} what its difficulty level is
-in Solo's terminology.) Therefore. Solo's \cw{encode_params()} only
+in Solo's terminology.) Therefore, Solo's \cw{encode_params()} only
 encodes the difficulty level if \c{full} is set.
 
 \S{backend-decode-params} \cw{decode_params()}
@@ -491,7 +521,7 @@ allocations contained within it.
 
 \S{backend-dup-params} \cw{dup_params()}
 
-\c game_params *(*dup_params)(game_params *params);
+\c game_params *(*dup_params)(const game_params *params);
 
 This function allocates a new \c{game_params} structure and
 initialises it with an exact copy of the information in the one
@@ -509,12 +539,17 @@ and \k{backend-custom-params} for more details.
 
 \S{backend-configure} \cw{configure()}
 
-\c config_item *(*configure)(game_params *params);
+\c config_item *(*configure)(const game_params *params);
 
 This function is called when the user requests a dialog box for
 custom parameter configuration. It returns a newly allocated array
 of \cw{config_item} structures, describing the GUI elements required
-in the dialog box. The 
+in the dialog box. The array should have one more element than the
+number of controls, since it is terminated with a \cw{C_END} marker
+(see below). Each array element describes the control together with
+its initial value; the front end will modify the value fields and
+return the updated array to \cw{custom_params()} (see
+\k{backend-custom-params}).
 
 The \cw{config_item} structure contains the following elements:
 
@@ -579,7 +614,7 @@ function is never called and need not do anything at all.
 
 \S{backend-custom-params} \cw{custom_params()}
 
-\c game_params *(*custom_params)(config_item *cfg);
+\c game_params *(*custom_params)(const config_item *cfg);
 
 This function is the counterpart to \cw{configure()}
 (\k{backend-configure}). It receives as input an array of
@@ -604,7 +639,7 @@ function is never called and need not do anything at all.
 
 \S{backend-validate-params} \cw{validate_params()}
 
-\c char *(*validate_params)(game_params *params, int full);
+\c char *(*validate_params)(const game_params *params, int full);
 
 This function takes a \c{game_params} structure as input, and checks
 that the parameters described in it fall within sensible limits. (At
@@ -648,7 +683,7 @@ a descriptive-format game ID.
 
 \S{backend-new-desc} \cw{new_desc()}
 
-\c char *(*new_desc)(game_params *params, random_state *rs,
+\c char *(*new_desc)(const game_params *params, random_state *rs,
 \c                   char **aux, int interactive);
 
 This function is where all the really hard work gets done. This is
@@ -689,7 +724,7 @@ again in the game description.
 
 \S{backend-validate-desc} \cw{validate_desc()}
 
-\c char *(*validate_desc)(game_params *params, char *desc);
+\c char *(*validate_desc)(const game_params *params, const char *desc);
 
 This function is given a game description, and its job is to
 validate that it describes a puzzle which makes sense.
@@ -713,8 +748,8 @@ non-dynamically-allocated C string containing an error message.
 
 \S{backend-new-game} \cw{new_game()}
 
-\c game_state *(*new_game)(midend_data *me, game_params *params,
-\c                         char *desc);
+\c game_state *(*new_game)(midend *me, const game_params *params,
+\c                         const char *desc);
 
 This function takes a game description as input, together with its
 accompanying \c{game_params}, and constructs a \c{game_state}
@@ -742,7 +777,7 @@ game states and it had to go in one section or the other.)
 
 \S{backend-dup-game} \cw{dup_game()}
 
-\c game_state *(*dup_game)(game_state *state);
+\c game_state *(*dup_game)(const game_state *state);
 
 This function allocates a new \c{game_state} structure and
 initialises it with an exact copy of the information in the one
@@ -759,7 +794,7 @@ allocations contained within it.
 
 \S{backend-new-ui} \cw{new_ui()}
 
-\c game_ui *(*new_ui)(game_state *state);
+\c game_ui *(*new_ui)(const game_state *state);
 
 This function allocates and returns a new \c{game_ui} structure for
 playing a particular puzzle. It is passed a pointer to the initial
@@ -775,7 +810,7 @@ allocations contained within it.
 
 \S{backend-encode-ui} \cw{encode_ui()}
 
-\c char *(*encode_ui)(game_ui *ui);
+\c char *(*encode_ui)(const game_ui *ui);
 
 This function encodes any \e{important} data in a \c{game_ui}
 structure in string form. It is only called when saving a
@@ -786,7 +821,7 @@ important enough to save. The location of the keyboard-controlled
 cursor, for example, can be reset to a default position on reloading
 the game without impacting the user experience. If the user should
 somehow manage to save a game while a mouse drag was in progress,
-then discarding that mouse drag would be an outright \e{feature},
+then discarding that mouse drag would be an outright \e{feature}.
 
 A typical thing that \e{would} be worth encoding in this function is
 the Mines death counter: it's in the \c{game_ui} rather than the
@@ -799,7 +834,7 @@ source.)
 
 \S{backend-decode-ui} \cw{decode_ui()}
 
-\c void (*decode_ui)(game_ui *ui, char *encoding);
+\c void (*decode_ui)(game_ui *ui, const char *encoding);
 
 This function parses a string previously output by \cw{encode_ui()},
 and writes the decoded data back into the provided \c{game_ui}
@@ -807,8 +842,8 @@ structure.
 
 \S{backend-changed-state} \cw{changed_state()}
 
-\c void (*changed_state)(game_ui *ui, game_state *oldstate,
-\c                       game_state *newstate);
+\c void (*changed_state)(game_ui *ui, const game_state *oldstate,
+\c                       const game_state *newstate);
 
 This function is called by the mid-end whenever the current game
 state changes, for any reason. Those reasons include:
@@ -833,12 +868,12 @@ invalid when the game state changes; thus, Same Game's
 \cw{changed_state()} function clears the current selection whenever
 it is called.
 
-Any call to \cw{changed_state()} can be sure that there will be a
-subsequent call to \cw{anim_length()} and \cw{flash_length()}. So
-\cw{changed_state()} can set up data in the \c{game_ui} which will
-be read by \cw{anim_length()} and \cw{flash_length()}, and not have
-to worry about those functions being called without the data having
-been uninitialised.
+When \cw{anim_length()} or \cw{flash_length()} are called, you can
+be sure that there has been a previous call to \cw{changed_state()}.
+So \cw{changed_state()} can set up data in the \c{game_ui} which will
+be read by \cw{anim_length()} and \cw{flash_length()}, and those
+functions will not have to worry about being called without the data
+having been initialised.
 
 \H{backend-moves} Making moves
 
@@ -848,8 +883,8 @@ producing new \c{game_state}s.
 
 \S{backend-interpret-move} \cw{interpret_move()}
 
-\c char *(*interpret_move)(game_state *state, game_ui *ui,
-\c                         game_drawstate *ds,
+\c char *(*interpret_move)(const game_state *state, game_ui *ui,
+\c                         const game_drawstate *ds,
 \c                         int x, int y, int button);
 
 This function receives user input and processes it. Its input
@@ -861,6 +896,11 @@ indicating an arrow or function key or a mouse event; when
 coordinates of the mouse pointer relative to the top left of the
 puzzle's drawing area.
 
+(The pointer to the \c{game_drawstate} is marked \c{const}, because
+\c{interpret_move} should not write to it. The normal use of that
+pointer will be to read the game's tile size parameter in order to
+divide mouse coordinates by it.)
+
 \cw{interpret_move()} may return in three different ways:
 
 \b Returning \cw{NULL} indicates that no action whatsoever occurred
@@ -963,7 +1003,7 @@ any input value.
 
 \S{backend-execute-move} \cw{execute_move()}
 
-\c game_state *(*execute_move)(game_state *state, char *move);
+\c game_state *(*execute_move)(const game_state *state, char *move);
 
 This function takes an input \c{game_state} and a move string as
 output from \cw{interpret_move()}. It returns a newly allocated
@@ -987,8 +1027,8 @@ not even offer the \q{Solve} menu option.
 
 \S{backend-solve} \cw{solve()}
 
-\c char *(*solve)(game_state *orig, game_state *curr,
-\c                char *aux, char **error);
+\c char *(*solve)(const game_state *orig, const game_state *curr,
+\c                const char *aux, char **error);
 
 This function is called when the user selects the \q{Solve} option
 from the menu.
@@ -1008,9 +1048,11 @@ it may return \cw{NULL}. If it does this, it must also set
 \q{Solution not known for this puzzle}); that error message is not
 expected to be dynamically allocated.
 
-If this function \e{does} produce a solution, it returns a move
-string suitable for feeding to \cw{execute_move()}
-(\k{backend-execute-move}).
+If this function \e{does} produce a solution, it returns a move string
+suitable for feeding to \cw{execute_move()}
+(\k{backend-execute-move}). Like a (non-empty) string returned from
+\cw{interpret_move()}, the returned string should be dynamically
+allocated.
 
 \H{backend-drawing} Drawing the game graphics
 
@@ -1019,7 +1061,8 @@ drawing.
 
 \S{backend-new-drawstate} \cw{new_drawstate()}
 
-\c game_drawstate *(*new_drawstate)(game_state *state);
+\c game_drawstate *(*new_drawstate)(drawing *dr,
+\c                                  const game_state *state);
 
 This function allocates and returns a new \c{game_drawstate}
 structure for drawing a particular puzzle. It is passed a pointer to
@@ -1032,13 +1075,22 @@ requests a forced redraw. For games like Pattern, in which initial
 game states are much simpler than general ones, this might be
 important to keep in mind.
 
+The parameter \c{dr} is a drawing object (see \k{drawing}) which the
+function might need to use to allocate blitters. (However, this
+isn't recommended; it's usually more sensible to wait to allocate a
+blitter until \cw{set_size()} is called, because that way you can
+tailor it to the scale at which the puzzle is being drawn.)
+
 \S{backend-free-drawstate} \cw{free_drawstate()}
 
-\c void (*free_drawstate)(game_drawstate *ds);
+\c void (*free_drawstate)(drawing *dr, game_drawstate *ds);
 
 This function frees a \c{game_drawstate} structure, and any
 subsidiary allocations contained within it.
 
+The parameter \c{dr} is a drawing object (see \k{drawing}), which
+might be required if you are freeing a blitter.
+
 \S{backend-preferred-tilesize} \c{preferred_tilesize}
 
 \c int preferred_tilesize;
@@ -1060,7 +1112,7 @@ requesting a resize if that ever gets implemented).
 
 \S{backend-compute-size} \cw{compute_size()}
 
-\c void (*compute_size)(game_params *params, int tilesize,
+\c void (*compute_size)(const game_params *params, int tilesize,
 \c                      int *x, int *y);
 
 This function is passed a \c{game_params} structure and a tile size.
@@ -1070,8 +1122,8 @@ at that tile size.
 
 \S{backend-set-size} \cw{set_size()}
 
-\c void (*set_size)(game_drawstate *ds, game_params *params,
-\c                  int tilesize);
+\c void (*set_size)(drawing *dr, game_drawstate *ds,
+\c                  const game_params *params, int tilesize);
 
 This function is responsible for setting up a \c{game_drawstate} to
 draw at a given tile size. Typically this will simply involve
@@ -1080,9 +1132,17 @@ field inside the draw state; for some more complex games it might
 also involve setting up other dimension fields, or possibly
 allocating a blitter (see \k{drawing-blitter}).
 
+The parameter \c{dr} is a drawing object (see \k{drawing}), which is
+required if a blitter needs to be allocated.
+
+Back ends may assume (and may enforce by assertion) that this
+function will be called at most once for any \c{game_drawstate}. If
+a puzzle needs to be redrawn at a different size, the mid-end will
+create a fresh drawstate.
+
 \S{backend-colours} \cw{colours()}
 
-\c float *(*colours)(frontend *fe, game_state *state, int *ncolours);
+\c float *(*colours)(frontend *fe, int *ncolours);
 
 This function is responsible for telling the front end what colours
 the puzzle will need to draw itself.
@@ -1093,27 +1153,27 @@ array of three times that many \c{float}s, containing the red, green
 and blue components of each colour respectively as numbers in the
 range [0,1].
 
-It is passed a sample \c{game_state} in case it needs one, although
-currently no puzzle does need this. (In fact, colours are not
-reallocated when the game parameters change or a new game is
-started, so you can't reliably use this \c{game_state} to allocate a
-different number of colours depending on the game. It is probably
-actually a mistake to rely on this parameter at all. I ought to
-either remove it or fix it; probably the former.)
-
-The final parameter passed to this function is a front end handle.
-The only thing it is permitted to do with this handle is to call the
-front-end function called \cw{frontend_default_colour()} (see
-\k{frontend-default-colour}). This allows \cw{colours()} to take
-local configuration into account when deciding on its own colour
-allocations. Most games use the front end's default colour as their
-background, apart from a few which depend on drawing relief
-highlights so they adjust the background colour if it's too light
-for highlights to show up against it.
+The second parameter passed to this function is a front end handle.
+The only things it is permitted to do with this handle are to call
+the front-end function called \cw{frontend_default_colour()} (see
+\k{frontend-default-colour}) or the utility function called
+\cw{game_mkhighlight()} (see \k{utils-game-mkhighlight}). (The
+latter is a wrapper on the former, so front end implementors only
+need to provide \cw{frontend_default_colour()}.) This allows
+\cw{colours()} to take local configuration into account when
+deciding on its own colour allocations. Most games use the front
+end's default colour as their background, apart from a few which
+depend on drawing relief highlights so they adjust the background
+colour if it's too light for highlights to show up against it.
+
+Note that the colours returned from this function are for
+\e{drawing}, not for printing. Printing has an entirely different
+colour allocation policy.
 
 \S{backend-anim-length} \cw{anim_length()}
 
-\c float (*anim_length)(game_state *oldstate, game_state *newstate,
+\c float (*anim_length)(const game_state *oldstate,
+\c                      const game_state *newstate,
 \c                      int dir, game_ui *ui);
 
 This function is called when a move is made, undone or redone. It is
@@ -1137,8 +1197,7 @@ State changes as a result of a Restart operation are never animated;
 the mid-end will handle them internally and never consult this
 function at all. State changes as a result of Solve operations are
 also not animated by default, although you can change this for a
-particular game by setting a flag in \c{mouse_priorities}
-(\k{backend-mouse-priorities}).
+particular game by setting a flag in \c{flags} (\k{backend-flags}).
 
 The function is also passed a pointer to the local \c{game_ui}. It
 may refer to information in here to help with its decision (see
@@ -1158,7 +1217,8 @@ state.
 
 \S{backend-flash-length} \cw{flash_length()}
 
-\c float (*flash_length)(game_state *oldstate, game_state *newstate,
+\c float (*flash_length)(const game_state *oldstate,
+\c                       const game_state *newstate,
 \c                       int dir, game_ui *ui);
 
 This function is called when a move is completed. (\q{Completed}
@@ -1202,19 +1262,49 @@ a mine from the colour it uses when you complete the game. In order
 to achieve this, its \cw{flash_length()} function has to store a
 flag in the \c{game_ui} to indicate which flash type is required.)
 
+\S{backend-status} \cw{status()}
+
+\c int (*status)(const game_state *state);
+
+This function returns a status value indicating whether the current
+game is still in play, or has been won, or has been conclusively lost.
+The mid-end uses this to implement \cw{midend_status()}
+(\k{midend-status}).
+
+The return value should be +1 if the game has been successfully
+solved. If the game has been lost in a situation where further play is
+unlikely, the return value should be -1. If neither is true (so play
+is still ongoing), return zero.
+
+Front ends may wish to use a non-zero status as a cue to proactively
+offer the option of starting a new game. Therefore, back ends should
+not return -1 if the game has been \e{technically} lost but undoing
+and continuing is still a realistic possibility.
+
+(For instance, games with hidden information such as Guess or Mines
+might well return a non-zero status whenever they reveal the solution,
+whether or not the player guessed it correctly, on the grounds that a
+player would be unlikely to hide the solution and continue playing
+after the answer was spoiled. On the other hand, games where you can
+merely get into a dead end such as Same Game or Inertia might choose
+to return 0 in that situation, on the grounds that the player would
+quite likely press Undo and carry on playing.)
+
 \S{backend-redraw} \cw{redraw()}
 
-\c void (*redraw)(frontend *fe, game_drawstate *ds,
-\c                game_state *oldstate, game_state *newstate, int dir,
-\c                game_ui *ui, float anim_time, float flash_time);
+\c void (*redraw)(drawing *dr, game_drawstate *ds,
+\c                const game_state *oldstate,
+\c                const game_state *newstate,
+\c                int dir, const game_ui *ui,
+\c                float anim_time, float flash_time);
 
 This function is responsible for actually drawing the contents of
 the game window, and for redrawing every time the game state or the
 \c{game_ui} changes.
 
-The parameter \c{fe} is a front end handle which may be passed to
-the drawing API functions (see \k{drawing} for documentation of the
-drawing API). This function may not save \c{fe} and use it
+The parameter \c{dr} is a drawing object which may be passed to the
+drawing API functions (see \k{drawing} for documentation of the
+drawing API). This function may not save \c{dr} and use it
 elsewhere; it must only use it for calling back to the drawing API
 functions within its own lifetime.
 
@@ -1242,32 +1332,166 @@ never subsequently altered, it is often simplest to arrange this by
 having a special \q{first time} flag in the draw state, and
 resetting it after the first redraw.
 
+When this function (or any subfunction) calls the drawing API, it is
+expected to pass colour indices which were previously defined by the
+\cw{colours()} function.
+
+\H{backend-printing} Printing functions
+
+This section discusses the back end functions that deal with
+printing puzzles out on paper.
+
+\S{backend-can-print} \c{can_print}
+
+\c int can_print;
+
+This flag is set to \cw{TRUE} if the puzzle is capable of printing
+itself on paper. (This makes sense for some puzzles, such as Solo,
+which can be filled in with a pencil. Other puzzles, such as
+Twiddle, inherently involve moving things around and so would not
+make sense to print.)
+
+If this flag is \cw{FALSE}, then the functions \cw{print_size()}
+and \cw{print()} will never be called.
+
+\S{backend-can-print-in-colour} \c{can_print_in_colour}
+
+\c int can_print_in_colour;
+
+This flag is set to \cw{TRUE} if the puzzle is capable of printing
+itself differently when colour is available. For example, Map can
+actually print coloured regions in different \e{colours} rather than
+resorting to cross-hatching.
+
+If the \c{can_print} flag is \cw{FALSE}, then this flag will be
+ignored.
+
+\S{backend-print-size} \cw{print_size()}
+
+\c void (*print_size)(const game_params *params, float *x, float *y);
+
+This function is passed a \c{game_params} structure and a tile size.
+It returns, in \c{*x} and \c{*y}, the preferred size in
+\e{millimetres} of that puzzle if it were to be printed out on paper.
+
+If the \c{can_print} flag is \cw{FALSE}, this function will never be
+called.
+
+\S{backend-print} \cw{print()}
+
+\c void (*print)(drawing *dr, const game_state *state, int tilesize);
+
+This function is called when a puzzle is to be printed out on paper.
+It should use the drawing API functions (see \k{drawing}) to print
+itself.
+
+This function is separate from \cw{redraw()} because it is often
+very different:
+
+\b The printing function may not depend on pixel accuracy, since
+printer resolution is variable. Draw as if your canvas had infinite
+resolution.
+
+\b The printing function sometimes needs to display things in a
+completely different style. Net, for example, is very different as
+an on-screen puzzle and as a printed one.
+
+\b The printing function is often much simpler since it has no need
+to deal with repeated partial redraws.
+
+However, there's no reason the printing and redraw functions can't
+share some code if they want to.
+
+When this function (or any subfunction) calls the drawing API, the
+colour indices it passes should be colours which have been allocated
+by the \cw{print_*_colour()} functions within this execution of
+\cw{print()}. This is very different from the fixed small number of
+colours used in \cw{redraw()}, because printers do not have a
+limitation on the total number of colours that may be used. Some
+puzzles' printing functions might wish to allocate only one \q{ink}
+colour and use it for all drawing; others might wish to allocate
+\e{more} colours than are used on screen.
+
+One possible colour policy worth mentioning specifically is that a
+puzzle's printing function might want to allocate the \e{same}
+colour indices as are used by the redraw function, so that code
+shared between drawing and printing does not have to keep switching
+its colour indices. In order to do this, the simplest thing is to
+make use of the fact that colour indices returned from
+\cw{print_*_colour()} are guaranteed to be in increasing order from
+zero. So if you have declared an \c{enum} defining three colours
+\cw{COL_BACKGROUND}, \cw{COL_THIS} and \cw{COL_THAT}, you might then
+write
+
+\c int c;
+\c c = print_mono_colour(dr, 1); assert(c == COL_BACKGROUND);
+\c c = print_mono_colour(dr, 0); assert(c == COL_THIS);
+\c c = print_mono_colour(dr, 0); assert(c == COL_THAT);
+
+If the \c{can_print} flag is \cw{FALSE}, this function will never be
+called.
+
 \H{backend-misc} Miscellaneous
 
-\S{backend-can-format-as-text} \c{can_format_as_text}
+\S{backend-can-format-as-text-ever} \c{can_format_as_text_ever}
 
-\c int can_format_as_text;
+\c int can_format_as_text_ever;
 
 This boolean field is \cw{TRUE} if the game supports formatting a
 game state as ASCII text (typically ASCII art) for copying to the
 clipboard and pasting into other applications. If it is \cw{FALSE},
 front ends will not offer the \q{Copy} command at all.
 
-If this field is \cw{FALSE}, the function \cw{text_format()}
-(\k{backend-text-format}) is not expected to do anything at all.
+If this field is \cw{TRUE}, the game does not necessarily have to
+support text formatting for \e{all} games: e.g. a game which can be
+played on a square grid or a triangular one might only support copy
+and paste for the former, because triangular grids in ASCII art are
+just too difficult.
+
+If this field is \cw{FALSE}, the functions
+\cw{can_format_as_text_now()} (\k{backend-can-format-as-text-now})
+and \cw{text_format()} (\k{backend-text-format}) are never called.
+
+\S{backend-can-format-as-text-now} \c{can_format_as_text_now()}
+
+\c int (*can_format_as_text_now)(const game_params *params);
+
+This function is passed a \c{game_params} and returns a boolean,
+which is \cw{TRUE} if the game can support ASCII text output for
+this particular game type. If it returns \cw{FALSE}, front ends will
+grey out or otherwise disable the \q{Copy} command.
+
+Games may enable and disable the copy-and-paste function for
+different game \e{parameters}, but are currently constrained to
+return the same answer from this function for all game \e{states}
+sharing the same parameters. In other words, the \q{Copy} function
+may enable or disable itself when the player changes game preset,
+but will never change during play of a single game or when another
+game of exactly the same type is generated.
+
+This function should not take into account aspects of the game
+parameters which are not encoded by \cw{encode_params()}
+(\k{backend-encode-params}) when the \c{full} parameter is set to
+\cw{FALSE}. Such parameters will not necessarily match up between a
+call to this function and a subsequent call to \cw{text_format()}
+itself. (For instance, game \e{difficulty} should not affect whether
+the game can be copied to the clipboard. Only the actual visible
+\e{shape} of the game can affect that.)
 
 \S{backend-text-format} \cw{text_format()}
 
-\c char *(*text_format)(game_state *state);
+\c char *(*text_format)(const game_state *state);
 
 This function is passed a \c{game_state}, and returns a newly
 allocated C string containing an ASCII representation of that game
 state. It is used to implement the \q{Copy} operation in many front
 ends.
 
-This function should only be called if the back end field
-\c{can_format_as_text} (\k{backend-can-format-as-text}) is
-\cw{TRUE}.
+This function will only ever be called if the back end field
+\c{can_format_as_text_ever} (\k{backend-can-format-as-text-ever}) is
+\cw{TRUE} \e{and} the function \cw{can_format_as_text_now()}
+(\k{backend-can-format-as-text-now}) has returned \cw{TRUE} for the
+currently selected game parameters.
 
 The returned string may contain line endings (and will probably want
 to), using the normal C internal \cq{\\n} convention. For
@@ -1277,18 +1501,14 @@ them internally. (There are currently no puzzles which have a
 one-line ASCII representation, so there's no precedent yet for
 whether that should come with a newline or not.)
 
-\S{backend-wants-statusbar} \cw{wants_statusbar()}
+\S{backend-wants-statusbar} \cw{wants_statusbar}
 
-\c int (*wants_statusbar)(void);
+\c int wants_statusbar;
 
-This function returns \cw{TRUE} if the puzzle has a use for a
+This boolean field is set to \cw{TRUE} if the puzzle has a use for a
 textual status line (to display score, completion status, currently
 active tiles, etc).
 
-(This should probably be a static boolean field rather than a
-function. I don't remember why I did it this way. I probably ought
-to change it.)
-
 \S{backend-is-timed} \c{is_timed}
 
 \c int is_timed;
@@ -1301,7 +1521,7 @@ called and need not do anything.
 
 \S{backend-timing-state} \cw{timing_state()}
 
-\c int (*timing_state)(game_state *state, game_ui *ui);
+\c int (*timing_state)(const game_state *state, game_ui *ui);
 
 This function is passed the current \c{game_state} and the local
 \c{game_ui}; it returns \cw{TRUE} if the game timer should currently
@@ -1313,17 +1533,17 @@ the game was first completed (by setting a flag in
 freeze the timer thereafter so that the user can undo back through
 their solution process without altering their time.
 
-\S{backend-mouse-priorities} \c{mouse_priorities}
+\S{backend-flags} \c{flags}
 
-\c int mouse_priorities;
+\c int flags;
 
-This field is badly named. It is in fact a generic flags word. It
-consists of the bitwise OR of the following flags:
+This field contains miscellaneous per-backend flags. It consists of
+the bitwise OR of some combination of the following:
 
 \dt \cw{BUTTON_BEATS(x,y)}
 
-\dd Given any \cw{x} and \cw{y} from the set (\cw{LEFT_BUTTON},
-\cw{MIDDLE_BUTTON}, \cw{RIGHT_BUTTON}), this macro evaluates to a
+\dd Given any \cw{x} and \cw{y} from the set \{\cw{LEFT_BUTTON},
+\cw{MIDDLE_BUTTON}, \cw{RIGHT_BUTTON}\}, this macro evaluates to a
 bit flag which indicates that when buttons \cw{x} and \cw{y} are
 both pressed simultaneously, the mid-end should consider \cw{x} to
 have priority. (In the absence of any such flags, the mid-end will
@@ -1339,6 +1559,26 @@ mid-end doesn't even bother calling \cw{anim_length()}
 each game. On the rare occasion that animated solve moves are
 actually required, you can set this flag.
 
+\dt \cw{REQUIRE_RBUTTON}
+
+\dd This flag indicates that the puzzle cannot be usefully played
+without the use of mouse buttons other than the left one. On some
+PDA platforms, this flag is used by the front end to enable
+right-button emulation through an appropriate gesture. Note that a
+puzzle is not required to set this just because it \e{uses} the
+right button, but only if its use of the right button is critical to
+playing the game. (Slant, for example, uses the right button to
+cycle through the three square states in the opposite order from the
+left button, and hence can manage fine without it.)
+
+\dt \cw{REQUIRE_NUMPAD}
+
+\dd This flag indicates that the puzzle cannot be usefully played
+without the use of number-key input. On some PDA platforms it causes
+an emulated number pad to appear on the screen. Similarly to
+\cw{REQUIRE_RBUTTON}, a puzzle need not specify this simply if its
+use of the number keys is not critical.
+
 \H{backend-initiative} Things a back end may do on its own initiative
 
 This section describes a couple of things that a back end may choose
@@ -1350,11 +1590,11 @@ otherwise be obvious.
 If a back end needs random numbers at some point during normal play,
 it can create a fresh \c{random_state} by first calling
 \c{get_random_seed} (\k{frontend-get-random-seed}) and then passing
-the returned seed data to \cw{random_init()}.
+the returned seed data to \cw{random_new()}.
 
 This is likely not to be what you want. If a puzzle needs randomness
 in the middle of play, it's likely to be more sensible to store some
-sort of random state within the \e{game_state}, so that the random
+sort of random state within the \c{game_state}, so that the random
 numbers are tied to the particular game state and hence the player
 can't simply keep undoing their move until they get numbers they
 like better.
@@ -1370,7 +1610,7 @@ in getting different random numbers.
 In response to a move, a back end is (reluctantly) permitted to call
 \cw{midend_supersede_game_desc()}:
 
-\c void midend_supersede_game_desc(midend_data *me,
+\c void midend_supersede_game_desc(midend *me,
 \c                                 char *desc, char *privdesc);
 
 When the user selects \q{New Game}, the mid-end calls
@@ -1404,31 +1644,62 @@ should use it if they're not Mines; if you think you need to use it,
 think again repeatedly in the hope of finding a better way to do
 whatever it was you needed to do.
 
-\C{drawing} The drawing API: front-end functions called from the
-back end
+\C{drawing} The drawing API
 
 The back end function \cw{redraw()} (\k{backend-redraw}) is required
-to draw the puzzle's graphics on the window's drawing area. To do
-this portably, it is provided with a drawing API allowing it to talk
-directly to the front end. In this chapter I document that API, both
-for the benefit of back end authors trying to use it and for front
-end authors trying to implement it.
-
-All of the drawing functions take a pointer to a \c{frontend}
-structure, which is passed in to \cw{redraw()}.
-
-The puzzle window is indexed by pixel coordinates, with the top left
-pixel defined as \cw{(0,0)} and the bottom right pixel
-\cw{(w-1,h-1)}, where \c{w} and \c{h} are the width and height
+to draw the puzzle's graphics on the window's drawing area, or on
+paper if the puzzle is printable. To do this portably, it is
+provided with a drawing API allowing it to talk directly to the
+front end. In this chapter I document that API, both for the benefit
+of back end authors trying to use it and for front end authors
+trying to implement it.
+
+The drawing API as seen by the back end is a collection of global
+functions, each of which takes a pointer to a \c{drawing} structure
+(a \q{drawing object}). These objects are supplied as parameters to
+the back end's \cw{redraw()} and \cw{print()} functions.
+
+In fact these global functions are not implemented directly by the
+front end; instead, they are implemented centrally in \c{drawing.c}
+and form a small piece of middleware. The drawing API as supplied by
+the front end is a structure containing a set of function pointers,
+plus a \cq{void *} handle which is passed to each of those
+functions. This enables a single front end to switch between
+multiple implementations of the drawing API if necessary. For
+example, the Windows API supplies a printing mechanism integrated
+into the same GDI which deals with drawing in windows, and therefore
+the same API implementation can handle both drawing and printing;
+but on Unix, the most common way for applications to print is by
+producing PostScript output directly, and although it would be
+\e{possible} to write a single (say) \cw{draw_rect()} function which
+checked a global flag to decide whether to do GTK drawing operations
+or output PostScript to a file, it's much nicer to have two separate
+functions and switch between them as appropriate.
+
+When drawing, the puzzle window is indexed by pixel coordinates,
+with the top left pixel defined as \cw{(0,0)} and the bottom right
+pixel \cw{(w-1,h-1)}, where \c{w} and \c{h} are the width and height
 values returned by the back end function \cw{compute_size()}
 (\k{backend-compute-size}).
 
-\e{Puzzles may assume that the surface they draw on is persistent}.
-It is the responsibility of every front end to preserve the puzzle's
-window contents in the face of GUI window expose issues and similar.
-It is not permissible to request the back end redraw any part of a
-window that it has already drawn, unless something has actually
-changed as a result of making moves in the puzzle.
+When printing, the puzzle's print area is indexed in exactly the
+same way (with an arbitrary tile size provided by the printing
+module \c{printing.c}), to facilitate sharing of code between the
+drawing and printing routines. However, when printing, puzzles may
+no longer assume that the coordinate unit has any relationship to a
+pixel; the printer's actual resolution might very well not even be
+known at print time, so the coordinate unit might be smaller or
+larger than a pixel. Puzzles' print functions should restrict
+themselves to drawing geometric shapes rather than fiddly pixel
+manipulation.
+
+\e{Puzzles' redraw functions may assume that the surface they draw
+on is persistent}. It is the responsibility of every front end to
+preserve the puzzle's window contents in the face of GUI window
+expose issues and similar. It is not permissible to request that the
+back end redraw any part of a window that it has already drawn,
+unless something has actually changed as a result of making moves in
+the puzzle.
 
 Most front ends accomplish this by having the drawing routines draw
 on a stored bitmap rather than directly on the window, and copying
@@ -1438,9 +1709,55 @@ end does any drawing it informs the front end of which parts of the
 window it has accessed, and hence which parts need repainting. This
 is done by calling \cw{draw_update()} (\k{drawing-draw-update}).
 
-\H{drawing-draw-rect} \cw{draw_rect()}
-
-\c void draw_rect(frontend *fe, int x, int y, int w, int h,
+Persistence of old drawing is convenient. However, a puzzle should
+be very careful about how it updates its drawing area. The problem
+is that some front ends do anti-aliased drawing: rather than simply
+choosing between leaving each pixel untouched or painting it a
+specified colour, an antialiased drawing function will \e{blend} the
+original and new colours in pixels at a figure's boundary according
+to the proportion of the pixel occupied by the figure (probably
+modified by some heuristic fudge factors). All of this produces a
+smoother appearance for curves and diagonal lines.
+
+An unfortunate effect of drawing an anti-aliased figure repeatedly
+is that the pixels around the figure's boundary come steadily more
+saturated with \q{ink} and the boundary appears to \q{spread out}.
+Worse, redrawing a figure in a different colour won't fully paint
+over the old boundary pixels, so the end result is a rather ugly
+smudge.
+
+A good strategy to avoid unpleasant anti-aliasing artifacts is to
+identify a number of rectangular areas which need to be redrawn,
+clear them to the background colour, and then redraw their contents
+from scratch, being careful all the while not to stray beyond the
+boundaries of the original rectangles. The \cw{clip()} function
+(\k{drawing-clip}) comes in very handy here. Games based on a square
+grid can often do this fairly easily. Other games may need to be
+somewhat more careful. For example, Loopy's redraw function first
+identifies portions of the display which need to be updated. Then,
+if the changes are fairly well localised, it clears and redraws a
+rectangle containing each changed area. Otherwise, it gives up and
+redraws the entire grid from scratch.
+
+It is possible to avoid clearing to background and redrawing from
+scratch if one is very careful about which drawing functions one
+uses: if a function is documented as not anti-aliasing under some
+circumstances, you can rely on each pixel in a drawing either being
+left entirely alone or being set to the requested colour, with no
+blending being performed.
+
+In the following sections I first discuss the drawing API as seen by
+the back end, and then the \e{almost} identical function-pointer
+form seen by the front end.
+
+\H{drawing-backend} Drawing API as seen by the back end
+
+This section documents the back-end drawing API, in the form of
+functions which take a \c{drawing} object as an argument.
+
+\S{drawing-draw-rect} \cw{draw_rect()}
+
+\c void draw_rect(drawing *dr, int x, int y, int w, int h,
 \c                int colour);
 
 Draws a filled rectangle in the puzzle window.
@@ -1462,9 +1779,11 @@ Unlike many of the other drawing functions, this function is
 guaranteed to be pixel-perfect: the rectangle will be sharply
 defined and not anti-aliased or anything like that.
 
-\H{drawing-draw-rect-outline} \cw{draw_rect_outline()}
+This function may be used for both drawing and printing.
+
+\S{drawing-draw-rect-outline} \cw{draw_rect_outline()}
 
-\c void draw_rect_outline(frontend *fe, int x, int y, int w, int h,
+\c void draw_rect_outline(drawing *dr, int x, int y, int w, int h,
 \c                        int colour);
 
 Draws an outline rectangle in the puzzle window.
@@ -1481,11 +1800,13 @@ the back end function \cw{colours()} (\k{backend-colours}).
 From a back end perspective, this function may be considered to be
 part of the drawing API. However, front ends are not required to
 implement it, since it is actually implemented centrally (in
-\cw{misc.c}) as a wrapper on four calls to \cw{draw_line()}.
+\cw{misc.c}) as a wrapper on \cw{draw_polygon()}.
 
-\H{drawing-draw-line} \cw{draw_line()}
+This function may be used for both drawing and printing.
 
-\c void draw_line(frontend *fe, int x1, int y1, int x2, int y2,
+\S{drawing-draw-line} \cw{draw_line()}
+
+\c void draw_line(drawing *dr, int x1, int y1, int x2, int y2,
 \c                int colour);
 
 Draws a straight line in the puzzle window.
@@ -1499,12 +1820,15 @@ the back end function \cw{colours()} (\k{backend-colours}).
 
 Some platforms may perform anti-aliasing on this function.
 Therefore, do not assume that you can erase a line by drawing the
-same line over it in the background colour; anti-aliasing might
-lead to perceptible ghost artefacts around the vanished line.
+same line over it in the background colour; anti-aliasing might lead
+to perceptible ghost artefacts around the vanished line. Horizontal
+and vertical lines, however, are pixel-perfect and not anti-aliased.
+
+This function may be used for both drawing and printing.
 
-\H{drawing-draw-polygon} \cw{draw_polygon()}
+\S{drawing-draw-polygon} \cw{draw_polygon()}
 
-\c void draw_polygon(frontend *fe, int *coords, int npoints,
+\c void draw_polygon(drawing *dr, int *coords, int npoints,
 \c                   int fillcolour, int outlinecolour);
 
 Draws an outlined or filled polygon in the puzzle window.
@@ -1535,11 +1859,14 @@ same polygon over it in the background colour. Also, be prepared for
 the polygon to extend a pixel beyond its obvious bounding box as a
 result of this; if you really need it not to do this to avoid
 interfering with other delicate graphics, you should probably use
-\cw{clip()} (\k{drawing-clip}).
+\cw{clip()} (\k{drawing-clip}). You can rely on horizontal and
+vertical lines not being anti-aliased.
+
+This function may be used for both drawing and printing.
 
-\H{drawing-draw-circle} \cw{draw_circle()}
+\S{drawing-draw-circle} \cw{draw_circle()}
 
-\c void draw_circle(frontend *fe, int cx, int cy, int radius,
+\c void draw_circle(drawing *dr, int cx, int cy, int radius,
 \c                  int fillcolour, int outlinecolour);
 
 Draws an outlined or filled circle in the puzzle window.
@@ -1573,9 +1900,40 @@ result of this; if you really need it not to do this to avoid
 interfering with other delicate graphics, you should probably use
 \cw{clip()} (\k{drawing-clip}).
 
-\H{drawing-draw-text} \cw{draw_text()}
+This function may be used for both drawing and printing.
+
+\S{drawing-draw-thick-line} \cw{draw_thick_line()}
+
+\c void draw_thick_line(drawing *dr, float thickness,
+\c                      float x1, float y1, float x2, float y2,
+\c                      int colour)
+
+Draws a line in the puzzle window, giving control over the line's
+thickness.
 
-\c void draw_text(frontend *fe, int x, int y, int fonttype,
+\c{x1} and \c{y1} give the coordinates of one end of the line.
+\c{x2} and \c{y2} give the coordinates of the other end.
+\c{thickness} gives the thickness of the line, in pixels.
+
+Note that the coordinates and thickness are floating-point: the
+continuous coordinate system is in effect here. It's important to
+be able to address points with better-than-pixel precision in this
+case, because one can't otherwise properly express the endpoints of
+lines with both odd and even thicknesses.
+
+Some platforms may perform anti-aliasing on this function. The
+precise pixels affected by a thick-line drawing operation may vary
+between platforms, and no particular guarantees are provided.
+Indeed, even horizontal or vertical lines may be anti-aliased.
+
+This function may be used for both drawing and printing.
+
+If the xpecified thickness is less than 1.0, 1.0 is used.
+This ensures that thin lines are visible even at small scales.
+
+\S{drawing-draw-text} \cw{draw_text()}
+
+\c void draw_text(drawing *dr, int x, int y, int fonttype,
 \c                int fontsize, int align, int colour, char *text);
 
 Draws text in the puzzle window.
@@ -1624,9 +1982,59 @@ internal dimension such as the cap-height.
 \c{colour} is an integer index into the colours array returned by
 the back end function \cw{colours()} (\k{backend-colours}).
 
-\H{drawing-clip} \cw{clip()}
+This function may be used for both drawing and printing.
+
+The character set used to encode the text passed to this function is
+specified \e{by the drawing object}, although it must be a superset
+of ASCII. If a puzzle wants to display text that is not contained in
+ASCII, it should use the \cw{text_fallback()} function
+(\k{drawing-text-fallback}) to query the drawing object for an
+appropriate representation of the characters it wants.
+
+\S{drawing-text-fallback} \cw{text_fallback()}
+
+\c char *text_fallback(drawing *dr, const char *const *strings,
+\c                     int nstrings);
 
-\c void clip(frontend *fe, int x, int y, int w, int h);
+This function is used to request a translation of UTF-8 text into
+whatever character encoding is expected by the drawing object's
+implementation of \cw{draw_text()}.
+
+The input is a list of strings encoded in UTF-8: \cw{nstrings} gives
+the number of strings in the list, and \cw{strings[0]},
+\cw{strings[1]}, ..., \cw{strings[nstrings-1]} are the strings
+themselves.
+
+The returned string (which is dynamically allocated and must be
+freed when finished with) is derived from the first string in the
+list that the drawing object expects to be able to display reliably;
+it will consist of that string translated into the character set
+expected by \cw{draw_text()}.
+
+Drawing implementations are not required to handle anything outside
+ASCII, but are permitted to assume that \e{some} string will be
+successfully translated. So every call to this function must include
+a string somewhere in the list (presumably the last element) which
+consists of nothing but ASCII, to be used by any front end which
+cannot handle anything else.
+
+For example, if a puzzle wished to display a string including a
+multiplication sign (U+00D7 in Unicode, represented by the bytes C3
+97 in UTF-8), it might do something like this:
+
+\c static const char *const times_signs[] = { "\xC3\x97", "x" };
+\c char *times_sign = text_fallback(dr, times_signs, 2);
+\c sprintf(buffer, "%d%s%d", width, times_sign, height);
+\c draw_text(dr, x, y, font, size, align, colour, buffer);
+\c sfree(buffer);
+
+which would draw a string with a times sign in the middle on
+platforms that support it, and fall back to a simple ASCII \cq{x}
+where there was no alternative.
+
+\S{drawing-clip} \cw{clip()}
+
+\c void clip(drawing *dr, int x, int y, int w, int h);
 
 Establishes a clipping rectangle in the puzzle window.
 
@@ -1639,24 +2047,30 @@ inclusive. (These are exactly the same semantics as
 
 After this call, no drawing operation will affect anything outside
 the specified rectangle. The effect can be reversed by calling
-\cw{unclip()} (\k{drawing-unclip}).
+\cw{unclip()} (\k{drawing-unclip}). The clipping rectangle is
+pixel-perfect: pixels within the rectangle are affected as usual by
+drawing functions; pixels outside are completely untouched.
 
 Back ends should not assume that a clipping rectangle will be
 automatically cleared up by the front end if it's left lying around;
 that might work on current front ends, but shouldn't be relied upon.
 Always explicitly call \cw{unclip()}.
 
-\H{drawing-unclip} \cw{unclip()}
+This function may be used for both drawing and printing.
 
-\c void unclip(frontend *fe);
+\S{drawing-unclip} \cw{unclip()}
+
+\c void unclip(drawing *dr);
 
 Reverts the effect of a previous call to \cw{clip()}. After this
 call, all drawing operations will be able to affect the entire
 puzzle window again.
 
-\H{drawing-draw-update} \cw{draw_update()}
+This function may be used for both drawing and printing.
+
+\S{drawing-draw-update} \cw{draw_update()}
 
-\c void draw_update(frontend *fe, int x, int y, int w, int h);
+\c void draw_update(drawing *dr, int x, int y, int w, int h);
 
 Informs the front end that a rectangular portion of the puzzle
 window has been drawn on and needs to be updated.
@@ -1674,34 +2088,35 @@ not become immediately visible, and may then appear at an
 unpredictable subsequent time such as the next time the window is
 covered and re-exposed.
 
-\H{drawing-status-bar} \cw{status_bar()}
+This function is only important when drawing. It may be called when
+printing as well, but doing so is not compulsory, and has no effect.
+(So if you have a shared piece of code between the drawing and
+printing routines, that code may safely call \cw{draw_update()}.)
 
-\c void status_bar(frontend *fe, char *text);
+\S{drawing-status-bar} \cw{status_bar()}
 
-Sets the text in the game's status bar to \c{text}.
+\c void status_bar(drawing *dr, char *text);
+
+Sets the text in the game's status bar to \c{text}. The text is copied
+from the supplied buffer, so the caller is free to deallocate or
+modify the buffer after use.
 
 (This function is not exactly a \e{drawing} function, but it shares
 with the drawing API the property that it may only be called from
 within the back end redraw function, so this is as good a place as
 any to document it.)
 
-Front ends implementing this function should not use the provided
-text directly; they should call \cw{midend_rewrite_statusbar()}
-(\k{midend-rewrite-statusbar}) to process it first.
+The supplied text is filtered through the mid-end for optional
+rewriting before being passed on to the front end; the mid-end will
+prepend the current game time if the game is timed (and may in
+future perform other rewriting if it seems like a good idea).
 
-In a game which has a timer, this function is likely to be called
-every time the timer goes off, i.e. many times a second. It is
-therefore likely to be common that this function is called with
-precisely the same text as the last time it was called. Front ends
-may well wish to detect this common case and avoid bothering to do
-anything. If they do, however, they \e{must} perform this check on
-the value \e{returned} from \cw{midend_rewrite_statusbar()}, rather
-than the value passed in to it (because the mid-end will frequently
-update the status-bar timer without the back end's intervention).
+This function is for drawing only; it must never be called during
+printing.
 
-\H{drawing-blitter} Blitter functions
+\S{drawing-blitter} Blitter functions
 
-This section describes a group of related function which save and
+This section describes a group of related functions which save and
 restore a section of the puzzle window. This is most commonly used
 to implement user interfaces involving dragging a puzzle element
 around the window: at the end of each call to \cw{redraw()}, if an
@@ -1713,9 +2128,12 @@ restore the background.
 The front end defines an opaque type called a \c{blitter}, which is
 capable of storing a rectangular area of a specified size.
 
-\S{drawing-blitter-new} \cw{blitter_new()}
+Blitter functions are for drawing only; they must never be called
+during printing.
+
+\S2{drawing-blitter-new} \cw{blitter_new()}
 
-\c blitter *blitter_new(int w, int h);
+\c blitter *blitter_new(drawing *dr, int w, int h);
 
 Creates a new blitter object which stores a rectangle of size \c{w}
 by \c{h} pixels. Returns a pointer to the blitter object.
@@ -1725,9 +2143,9 @@ time to create them is in the \cw{set_size()} function
 (\k{backend-set-size}), since it is at this point that you first
 know how big a rectangle they will need to save.
 
-\S{drawing-blitter-free} \cw{blitter_free()}
+\S2{drawing-blitter-free} \cw{blitter_free()}
 
-\c void blitter_free(blitter *bl);
+\c void blitter_free(drawing *dr, blitter *bl);
 
 Disposes of a blitter object. Best called in \cw{free_drawstate()}.
 (However, check that the blitter object is not \cw{NULL} before
@@ -1735,9 +2153,9 @@ attempting to free it; it is possible that a draw state might be
 created and freed without ever having \cw{set_size()} called on it
 in between.)
 
-\S{drawing-blitter-save} \cw{blitter_save()}
+\S2{drawing-blitter-save} \cw{blitter_save()}
 
-\c void blitter_save(frontend *fe, blitter *bl, int x, int y);
+\c void blitter_save(drawing *dr, blitter *bl, int x, int y);
 
 This is a true drawing API function, in that it may only be called
 from within the game redraw routine. It saves a rectangular portion
@@ -1752,9 +2170,9 @@ and \c{y} are out of range. (The right thing probably means saving
 whatever part of the blitter rectangle overlaps with the visible
 area of the puzzle window.)
 
-\S{drawing-blitter-load} \cw{blitter_load()}
+\S2{drawing-blitter-load} \cw{blitter_load()}
 
-\c void blitter_load(frontend *fe, blitter *bl, int x, int y);
+\c void blitter_load(drawing *dr, blitter *bl, int x, int y);
 
 This is a true drawing API function, in that it may only be called
 from within the game redraw routine. It restores a rectangular
@@ -1782,42 +2200,515 @@ saved bitmap which were not visible at save time are undefined. If
 the blitter is restored to a different position so as to make those
 parts visible, the effect on the drawing area is undefined.
 
-\H{drawing-midend} Additional functions only called by the mid-end
+\S{print-mono-colour} \cw{print_mono_colour()}
+
+\c int print_mono_colour(drawing *dr, int grey);
+
+This function allocates a colour index for a simple monochrome
+colour during printing.
+
+\c{grey} must be 0 or 1. If \c{grey} is 0, the colour returned is
+black; if \c{grey} is 1, the colour is white.
+
+\S{print-grey-colour} \cw{print_grey_colour()}
+
+\c int print_grey_colour(drawing *dr, float grey);
+
+This function allocates a colour index for a grey-scale colour
+during printing.
+
+\c{grey} may be any number between 0 (black) and 1 (white); for
+example, 0.5 indicates a medium grey.
 
-The two functions documented in this section are part of the drawing
-API as seen by a front end, but are not needed by the back end. The
-mid-end calls these functions before and after calling the back end
-redraw function.
+The chosen colour will be rendered to the limits of the printer's
+halftoning capability.
 
-\S{drawing-start-draw} \cw{start_draw()}
+\S{print-hatched-colour} \cw{print_hatched_colour()}
 
-\c void start_draw(frontend *fe);
+\c int print_hatched_colour(drawing *dr, int hatch);
 
-This function is called before any drawing takes place. It allows
-the front end to initialise any temporary data required to draw
-with, such as device contexts.
+This function allocates a colour index which does not represent a
+literal \e{colour}. Instead, regions shaded in this colour will be
+hatched with parallel lines. The \c{hatch} parameter defines what
+type of hatching should be used in place of this colour:
 
-\S{drawing-end-draw} \cw{end_draw()}
+\dt \cw{HATCH_SLASH}
 
-\c void end_draw(frontend *fe);
+\dd This colour will be hatched by lines slanting to the right at 45
+degrees. 
+
+\dt \cw{HATCH_BACKSLASH}
+
+\dd This colour will be hatched by lines slanting to the left at 45
+degrees.
+
+\dt \cw{HATCH_HORIZ}
+
+\dd This colour will be hatched by horizontal lines.
+
+\dt \cw{HATCH_VERT}
+
+\dd This colour will be hatched by vertical lines.
+
+\dt \cw{HATCH_PLUS}
+
+\dd This colour will be hatched by criss-crossing horizontal and
+vertical lines.
+
+\dt \cw{HATCH_X}
+
+\dd This colour will be hatched by criss-crossing diagonal lines.
+
+Colours defined to use hatching may not be used for drawing lines or
+text; they may only be used for filling areas. That is, they may be
+used as the \c{fillcolour} parameter to \cw{draw_circle()} and
+\cw{draw_polygon()}, and as the colour parameter to
+\cw{draw_rect()}, but may not be used as the \c{outlinecolour}
+parameter to \cw{draw_circle()} or \cw{draw_polygon()}, or with
+\cw{draw_line()} or \cw{draw_text()}.
+
+\S{print-rgb-mono-colour} \cw{print_rgb_mono_colour()}
+
+\c int print_rgb_mono_colour(drawing *dr, float r, float g,
+\c                           float b, float grey);
+
+This function allocates a colour index for a fully specified RGB
+colour during printing.
+
+\c{r}, \c{g} and \c{b} may each be anywhere in the range from 0 to 1.
+
+If printing in black and white only, these values will be ignored,
+and either pure black or pure white will be used instead, according
+to the \q{grey} parameter. (The fallback colour is the same as the
+one which would be allocated by \cw{print_mono_colour(grey)}.)
+
+\S{print-rgb-grey-colour} \cw{print_rgb_grey_colour()}
+
+\c int print_rgb_grey_colour(drawing *dr, float r, float g,
+\c                           float b, float grey);
+
+This function allocates a colour index for a fully specified RGB
+colour during printing.
+
+\c{r}, \c{g} and \c{b} may each be anywhere in the range from 0 to 1.
+
+If printing in black and white only, these values will be ignored,
+and a shade of grey given by the \c{grey} parameter will be used
+instead. (The fallback colour is the same as the one which would be
+allocated by \cw{print_grey_colour(grey)}.)
+
+\S{print-rgb-hatched-colour} \cw{print_rgb_hatched_colour()}
+
+\c int print_rgb_hatched_colour(drawing *dr, float r, float g,
+\c                              float b, float hatched);
+
+This function allocates a colour index for a fully specified RGB
+colour during printing.
+
+\c{r}, \c{g} and \c{b} may each be anywhere in the range from 0 to 1.
+
+If printing in black and white only, these values will be ignored,
+and a form of cross-hatching given by the \c{hatch} parameter will
+be used instead; see \k{print-hatched-colour} for the possible
+values of this parameter. (The fallback colour is the same as the
+one which would be allocated by \cw{print_hatched_colour(hatch)}.)
+
+\S{print-line-width} \cw{print_line_width()}
+
+\c void print_line_width(drawing *dr, int width);
+
+This function is called to set the thickness of lines drawn during
+printing. It is meaningless in drawing: all lines drawn by
+\cw{draw_line()}, \cw{draw_circle} and \cw{draw_polygon()} are one
+pixel in thickness. However, in printing there is no clear
+definition of a pixel and so line widths must be explicitly
+specified.
+
+The line width is specified in the usual coordinate system. Note,
+however, that it is a hint only: the central printing system may
+choose to vary line thicknesses at user request or due to printer
+capabilities.
+
+\S{print-line-dotted} \cw{print_line_dotted()}
+
+\c void print_line_dotted(drawing *dr, int dotted);
+
+This function is called to toggle the drawing of dotted lines during
+printing. It is not supported during drawing.
+
+The parameter \cq{dotted} is a boolean; \cw{TRUE} means that future
+lines drawn by \cw{draw_line()}, \cw{draw_circle} and
+\cw{draw_polygon()} will be dotted, and \cw{FALSE} means that they
+will be solid.
+
+Some front ends may impose restrictions on the width of dotted
+lines. Asking for a dotted line via this front end will override any
+line width request if the front end requires it.
+
+\H{drawing-frontend} The drawing API as implemented by the front end
+
+This section describes the drawing API in the function-pointer form
+in which it is implemented by a front end.
+
+(It isn't only platform-specific front ends which implement this
+API; the platform-independent module \c{ps.c} also provides an
+implementation of it which outputs PostScript. Thus, any platform
+which wants to do PS printing can do so with minimum fuss.)
+
+The following entries all describe function pointer fields in a
+structure called \c{drawing_api}. Each of the functions takes a
+\cq{void *} context pointer, which it should internally cast back to
+a more useful type. Thus, a drawing \e{object} (\c{drawing *)}
+suitable for passing to the back end redraw or printing functions
+is constructed by passing a \c{drawing_api} and a \cq{void *} to the
+function \cw{drawing_new()} (see \k{drawing-new}).
+
+\S{drawingapi-draw-text} \cw{draw_text()}
+
+\c void (*draw_text)(void *handle, int x, int y, int fonttype,
+\c                   int fontsize, int align, int colour, char *text);
+
+This function behaves exactly like the back end \cw{draw_text()}
+function; see \k{drawing-draw-text}.
+
+\S{drawingapi-draw-rect} \cw{draw_rect()}
+
+\c void (*draw_rect)(void *handle, int x, int y, int w, int h,
+\c                   int colour);
+
+This function behaves exactly like the back end \cw{draw_rect()}
+function; see \k{drawing-draw-rect}.
+
+\S{drawingapi-draw-line} \cw{draw_line()}
+
+\c void (*draw_line)(void *handle, int x1, int y1, int x2, int y2,
+\c                   int colour);
+
+This function behaves exactly like the back end \cw{draw_line()}
+function; see \k{drawing-draw-line}.
+
+\S{drawingapi-draw-polygon} \cw{draw_polygon()}
+
+\c void (*draw_polygon)(void *handle, int *coords, int npoints,
+\c                      int fillcolour, int outlinecolour);
+
+This function behaves exactly like the back end \cw{draw_polygon()}
+function; see \k{drawing-draw-polygon}.
+
+\S{drawingapi-draw-circle} \cw{draw_circle()}
+
+\c void (*draw_circle)(void *handle, int cx, int cy, int radius,
+\c                     int fillcolour, int outlinecolour);
+
+This function behaves exactly like the back end \cw{draw_circle()}
+function; see \k{drawing-draw-circle}.
+
+\S{drawingapi-draw-thick-line} \cw{draw_thick_line()}
+
+\c void draw_thick_line(drawing *dr, float thickness,
+\c                      float x1, float y1, float x2, float y2,
+\c                      int colour)
+
+This function behaves exactly like the back end
+\cw{draw_thick_line()} function; see \k{drawing-draw-thick-line}.
+
+An implementation of this API which doesn't provide high-quality
+rendering of thick lines is permitted to define this function
+pointer to be \cw{NULL}. The middleware in \cw{drawing.c} will notice
+and provide a low-quality alternative using \cw{draw_polygon()}.
+
+\S{drawingapi-draw-update} \cw{draw_update()}
+
+\c void (*draw_update)(void *handle, int x, int y, int w, int h);
+
+This function behaves exactly like the back end \cw{draw_update()}
+function; see \k{drawing-draw-update}.
+
+An implementation of this API which only supports printing is
+permitted to define this function pointer to be \cw{NULL} rather
+than bothering to define an empty function. The middleware in
+\cw{drawing.c} will notice and avoid calling it.
+
+\S{drawingapi-clip} \cw{clip()}
+
+\c void (*clip)(void *handle, int x, int y, int w, int h);
+
+This function behaves exactly like the back end \cw{clip()}
+function; see \k{drawing-clip}.
+
+\S{drawingapi-unclip} \cw{unclip()}
+
+\c void (*unclip)(void *handle);
+
+This function behaves exactly like the back end \cw{unclip()}
+function; see \k{drawing-unclip}.
+
+\S{drawingapi-start-draw} \cw{start_draw()}
+
+\c void (*start_draw)(void *handle);
+
+This function is called at the start of drawing. It allows the front
+end to initialise any temporary data required to draw with, such as
+device contexts.
+
+Implementations of this API which do not provide drawing services
+may define this function pointer to be \cw{NULL}; it will never be
+called unless drawing is attempted.
+
+\S{drawingapi-end-draw} \cw{end_draw()}
+
+\c void (*end_draw)(void *handle);
 
 This function is called at the end of drawing. It allows the front
 end to do cleanup tasks such as deallocating device contexts and
 scheduling appropriate GUI redraw events.
 
-\H{frontend-default-colour} \cw{frontend_default_colour()}
+Implementations of this API which do not provide drawing services
+may define this function pointer to be \cw{NULL}; it will never be
+called unless drawing is attempted.
 
-\c void frontend_default_colour(frontend *fe, float *output);
+\S{drawingapi-status-bar} \cw{status_bar()}
 
-This function expects to be passed a pointer to an array of three
-\cw{float}s. It returns the platform's local preferred background
-colour in those three floats, as red, green and blue values (in that
-order) ranging from \cw{0.0} to \cw{1.0}.
+\c void (*status_bar)(void *handle, char *text);
 
-This function should only ever be called by the back end function
-\cw{colours()} (\k{backend-colours}). (Thus, it isn't a drawing API
-function as such, but it's a front end function of interest to
-puzzle implementors so it's probably best in this section.)
+This function behaves exactly like the back end \cw{status_bar()}
+function; see \k{drawing-status-bar}.
+
+Front ends implementing this function need not worry about it being
+called repeatedly with the same text; the middleware code in
+\cw{status_bar()} will take care of this.
+
+Implementations of this API which do not provide drawing services
+may define this function pointer to be \cw{NULL}; it will never be
+called unless drawing is attempted.
+
+\S{drawingapi-blitter-new} \cw{blitter_new()}
+
+\c blitter *(*blitter_new)(void *handle, int w, int h);
+
+This function behaves exactly like the back end \cw{blitter_new()}
+function; see \k{drawing-blitter-new}.
+
+Implementations of this API which do not provide drawing services
+may define this function pointer to be \cw{NULL}; it will never be
+called unless drawing is attempted.
+
+\S{drawingapi-blitter-free} \cw{blitter_free()}
+
+\c void (*blitter_free)(void *handle, blitter *bl);
+
+This function behaves exactly like the back end \cw{blitter_free()}
+function; see \k{drawing-blitter-free}.
+
+Implementations of this API which do not provide drawing services
+may define this function pointer to be \cw{NULL}; it will never be
+called unless drawing is attempted.
+
+\S{drawingapi-blitter-save} \cw{blitter_save()}
+
+\c void (*blitter_save)(void *handle, blitter *bl, int x, int y);
+
+This function behaves exactly like the back end \cw{blitter_save()}
+function; see \k{drawing-blitter-save}.
+
+Implementations of this API which do not provide drawing services
+may define this function pointer to be \cw{NULL}; it will never be
+called unless drawing is attempted.
+
+\S{drawingapi-blitter-load} \cw{blitter_load()}
+
+\c void (*blitter_load)(void *handle, blitter *bl, int x, int y);
+
+This function behaves exactly like the back end \cw{blitter_load()}
+function; see \k{drawing-blitter-load}.
+
+Implementations of this API which do not provide drawing services
+may define this function pointer to be \cw{NULL}; it will never be
+called unless drawing is attempted.
+
+\S{drawingapi-begin-doc} \cw{begin_doc()}
+
+\c void (*begin_doc)(void *handle, int pages);
+
+This function is called at the beginning of a printing run. It gives
+the front end an opportunity to initialise any required printing
+subsystem. It also provides the number of pages in advance.
+
+Implementations of this API which do not provide printing services
+may define this function pointer to be \cw{NULL}; it will never be
+called unless printing is attempted.
+
+\S{drawingapi-begin-page} \cw{begin_page()}
+
+\c void (*begin_page)(void *handle, int number);
+
+This function is called during printing, at the beginning of each
+page. It gives the page number (numbered from 1 rather than 0, so
+suitable for use in user-visible contexts).
+
+Implementations of this API which do not provide printing services
+may define this function pointer to be \cw{NULL}; it will never be
+called unless printing is attempted.
+
+\S{drawingapi-begin-puzzle} \cw{begin_puzzle()}
+
+\c void (*begin_puzzle)(void *handle, float xm, float xc,
+\c                      float ym, float yc, int pw, int ph, float wmm);
+
+This function is called during printing, just before printing a
+single puzzle on a page. It specifies the size and location of the
+puzzle on the page.
+
+\c{xm} and \c{xc} specify the horizontal position of the puzzle on
+the page, as a linear function of the page width. The front end is
+expected to multiply the page width by \c{xm}, add \c{xc} (measured
+in millimetres), and use the resulting x-coordinate as the left edge
+of the puzzle.
+
+Similarly, \c{ym} and \c{yc} specify the vertical position of the
+puzzle as a function of the page height: the page height times
+\c{ym}, plus \c{yc} millimetres, equals the desired distance from
+the top of the page to the top of the puzzle.
+
+(This unwieldy mechanism is required because not all printing
+systems can communicate the page size back to the software. The
+PostScript back end, for example, writes out PS which determines the
+page size at print time by means of calling \cq{clippath}, and
+centres the puzzles within that. Thus, exactly the same PS file
+works on A4 or on US Letter paper without needing local
+configuration, which simplifies matters.)
+
+\cw{pw} and \cw{ph} give the size of the puzzle in drawing API
+coordinates. The printing system will subsequently call the puzzle's
+own print function, which will in turn call drawing API functions in
+the expectation that an area \cw{pw} by \cw{ph} units is available
+to draw the puzzle on.
+
+Finally, \cw{wmm} gives the desired width of the puzzle in
+millimetres. (The aspect ratio is expected to be preserved, so if
+the desired puzzle height is also needed then it can be computed as
+\cw{wmm*ph/pw}.)
+
+Implementations of this API which do not provide printing services
+may define this function pointer to be \cw{NULL}; it will never be
+called unless printing is attempted.
+
+\S{drawingapi-end-puzzle} \cw{end_puzzle()}
+
+\c void (*end_puzzle)(void *handle);
+
+This function is called after the printing of a specific puzzle is
+complete.
+
+Implementations of this API which do not provide printing services
+may define this function pointer to be \cw{NULL}; it will never be
+called unless printing is attempted.
+
+\S{drawingapi-end-page} \cw{end_page()}
+
+\c void (*end_page)(void *handle, int number);
+
+This function is called after the printing of a page is finished.
+
+Implementations of this API which do not provide printing services
+may define this function pointer to be \cw{NULL}; it will never be
+called unless printing is attempted.
+
+\S{drawingapi-end-doc} \cw{end_doc()}
+
+\c void (*end_doc)(void *handle);
+
+This function is called after the printing of the entire document is
+finished. This is the moment to close files, send things to the
+print spooler, or whatever the local convention is.
+
+Implementations of this API which do not provide printing services
+may define this function pointer to be \cw{NULL}; it will never be
+called unless printing is attempted.
+
+\S{drawingapi-line-width} \cw{line_width()}
+
+\c void (*line_width)(void *handle, float width);
+
+This function is called to set the line thickness, during printing
+only. Note that the width is a \cw{float} here, where it was an
+\cw{int} as seen by the back end. This is because \cw{drawing.c} may
+have scaled it on the way past.
+
+However, the width is still specified in the same coordinate system
+as the rest of the drawing.
+
+Implementations of this API which do not provide printing services
+may define this function pointer to be \cw{NULL}; it will never be
+called unless printing is attempted.
+
+\S{drawingapi-text-fallback} \cw{text_fallback()}
+
+\c char *(*text_fallback)(void *handle, const char *const *strings,
+\c                        int nstrings);
+
+This function behaves exactly like the back end \cw{text_fallback()}
+function; see \k{drawing-text-fallback}.
+
+Implementations of this API which do not support any characters
+outside ASCII may define this function pointer to be \cw{NULL}, in
+which case the central code in \cw{drawing.c} will provide a default
+implementation.
+
+\H{drawingapi-frontend} The drawing API as called by the front end
+
+There are a small number of functions provided in \cw{drawing.c}
+which the front end needs to \e{call}, rather than helping to
+implement. They are described in this section.
+
+\S{drawing-new} \cw{drawing_new()}
+
+\c drawing *drawing_new(const drawing_api *api, midend *me,
+\c                      void *handle);
+
+This function creates a drawing object. It is passed a
+\c{drawing_api}, which is a structure containing nothing but
+function pointers; and also a \cq{void *} handle. The handle is
+passed back to each function pointer when it is called.
+
+The \c{midend} parameter is used for rewriting the status bar
+contents: \cw{status_bar()} (see \k{drawing-status-bar}) has to call
+a function in the mid-end which might rewrite the status bar text.
+If the drawing object is to be used only for printing, or if the
+game is known not to call \cw{status_bar()}, this parameter may be
+\cw{NULL}.
+
+\S{drawing-free} \cw{drawing_free()}
+
+\c void drawing_free(drawing *dr);
+
+This function frees a drawing object. Note that the \cq{void *}
+handle is not freed; if that needs cleaning up it must be done by
+the front end.
+
+\S{drawing-print-get-colour} \cw{print_get_colour()}
+
+\c void print_get_colour(drawing *dr, int colour, int printincolour,
+\c                       int *hatch, float *r, float *g, float *b)
+
+This function is called by the implementations of the drawing API
+functions when they are called in a printing context. It takes a
+colour index as input, and returns the description of the colour as
+requested by the back end.
+
+\c{printincolour} is \cw{TRUE} iff the implementation is printing in
+colour. This will alter the results returned if the colour in
+question was specified with a black-and-white fallback value.
+
+If the colour should be rendered by hatching, \c{*hatch} is filled
+with the type of hatching desired. See \k{print-grey-colour} for
+details of the values this integer can take.
+
+If the colour should be rendered as solid colour, \c{*hatch} is
+given a negative value, and \c{*r}, \c{*g} and \c{*b} are filled
+with the RGB values of the desired colour (if printing in colour),
+or all filled with the grey-scale value (if printing in black and
+white).
 
 \C{midend} The API provided by the mid-end
 
@@ -1828,24 +2719,29 @@ platform. If you're only interested in writing new puzzles, you can
 safely skip this chapter.
 
 All the persistent state in the mid-end is encapsulated within a
-\c{midend_data} structure, to facilitate having multiple mid-ends in
-any port which supports multiple puzzle windows open simultaneously.
-Each \c{midend_data} is intended to handle the contents of a single
+\c{midend} structure, to facilitate having multiple mid-ends in any
+port which supports multiple puzzle windows open simultaneously.
+Each \c{midend} is intended to handle the contents of a single
 puzzle window.
 
 \H{midend-new} \cw{midend_new()}
 
-\c midend_data *midend_new(frontend *fe, const game *ourgame);
+\c midend *midend_new(frontend *fe, const game *ourgame,
+\c                    const drawing_api *drapi, void *drhandle)
 
 Allocates and returns a new mid-end structure.
 
 The \c{fe} argument is stored in the mid-end. It will be used when
 calling back to functions such as \cw{activate_timer()}
-(\k{frontend-activate-timer}), and will be passed on to back end
-functions such as \cw{colours()} (\k{backend-colours}) and
-\cw{redraw()} (\k{backend-redraw}). The latter, of course, means
-that the front end can expect to receive this pointer in calls to
-the entire drawing API (\k{drawing}).
+(\k{frontend-activate-timer}), and will be passed on to the back end
+function \cw{colours()} (\k{backend-colours}).
+
+The parameters \c{drapi} and \c{drhandle} are passed to
+\cw{drawing_new()} (\k{drawing-new}) to construct a drawing object
+which will be passed to the back end function \cw{redraw()}
+(\k{backend-redraw}). Hence, all drawing-related function pointers
+defined in \c{drapi} can expect to be called with \c{drhandle} as
+their first argument.
 
 The \c{ourgame} argument points to a container structure describing
 a game back end. The mid-end thus created will only be capable of
@@ -1857,13 +2753,20 @@ without closing the window...)
 
 \H{midend-free} \cw{midend_free()}
 
-\c void midend_free(midend_data *me);
+\c void midend_free(midend *me);
 
 Frees a mid-end structure and all its associated data.
 
+\H{midend-tilesize} \cw{midend_tilesize()}
+
+\c int midend_tilesize(midend *me);
+
+Returns the \cq{tilesize} parameter being used to display the
+current puzzle (\k{backend-preferred-tilesize}).
+
 \H{midend-set-params} \cw{midend_set_params()}
 
-\c void midend_set_params(midend_data *me, game_params *params);
+\c void midend_set_params(midend *me, game_params *params);
 
 Sets the current game parameters for a mid-end. Subsequent games
 generated by \cw{midend_new_game()} (\k{midend-new-game}) will use
@@ -1871,13 +2774,23 @@ these parameters until further notice.
 
 The usual way in which the front end will have an actual
 \c{game_params} structure to pass to this function is if it had
-previously got it from \cw{midend_fetch_preset()}
-(\k{midend-fetch-preset}). Thus, this function is usually called in
+previously got it from \cw{midend_get_presets()}
+(\k{midend-get-presets}). Thus, this function is usually called in
 response to the user making a selection from the presets menu.
 
+\H{midend-get-params} \cw{midend_get_params()}
+
+\c game_params *midend_get_params(midend *me);
+
+Returns the current game parameters stored in this mid-end.
+
+The returned value is dynamically allocated, and should be freed
+when finished with by passing it to the game's own
+\cw{free_params()} function (see \k{backend-free-params}).
+
 \H{midend-size} \cw{midend_size()}
 
-\c void midend_size(midend_data *me, int *x, int *y, int expand);
+\c void midend_size(midend *me, int *x, int *y, int user_size);
 
 Tells the mid-end to figure out its window size.
 
@@ -1892,18 +2805,27 @@ course up to the front end to adjust this for any additional window
 furniture such as menu bars and window borders, if necessary. The
 status bar is also not included in this size.)
 
-If \c{expand} is set to \cw{FALSE}, then the game's tile size will
-never go over its preferred one. This is the recommended approach
-when opening a new window at default size: the game will use its
-preferred size unless it has to use a smaller one to fit on the
-screen.
-
-If \c{expand} is set to \cw{TRUE}, the mid-end will pick a tile size
-which approximates the input size \e{as closely as possible}, and
-will go over the game's preferred tile size if necessary to achieve
-this. Use this option if you want your front end to support dynamic
-resizing of the puzzle window with automatic scaling of the puzzle
-to fit.
+Use \c{user_size} to indicate whether \c{*x} and \c{*y} are a
+requested size, or just a maximum size.
+
+If \c{user_size} is set to \cw{TRUE}, the mid-end will treat the
+input size as a request, and will pick a tile size which
+approximates it \e{as closely as possible}, going over the game's
+preferred tile size if necessary to achieve this. The mid-end will
+also use the resulting tile size as its preferred one until further
+notice, on the assumption that this size was explicitly requested
+by the user. Use this option if you want your front end to support
+dynamic resizing of the puzzle window with automatic scaling of the
+puzzle to fit.
+
+If \c{user_size} is set to \cw{FALSE}, then the game's tile size
+will never go over its preferred one, although it may go under in
+order to fit within the maximum bounds specified by \c{*x} and
+\c{*y}. This is the recommended approach when opening a new window
+at default size: the game will use its preferred size unless it has
+to use a smaller one to fit on the screen. If the tile size is
+shrunk for this reason, the change will not persist; if a smaller
+grid is subsequently chosen, the tile size will recover.
 
 The mid-end will try as hard as it can to return a size which is
 less than or equal to the input size, in both dimensions. In extreme
@@ -1923,11 +2845,30 @@ creatively.
 If your platform has no limit on window size (or if you're planning
 to use scroll bars for large puzzles), you can pass dimensions of
 \cw{INT_MAX} as input to this function. You should probably not do
-that \e{and} set the \c{expand} flag, though!
+that \e{and} set the \c{user_size} flag, though!
+
+The midend relies on the frontend calling \cw{midend_new_game()}
+(\k{midend-new-game}) before calling \cw{midend_size()}.
+
+\H{midend-reset-tilesize} \cw{midend_reset_tilesize()}
+
+\c void midend_reset_tilesize(midend *me);
+
+This function resets the midend's preferred tile size to that of the
+standard puzzle.
+
+As discussed in \k{midend-size}, puzzle resizes are typically
+'sticky', in that once the user has dragged the puzzle to a different
+window size, the resulting tile size will be remembered and used when
+the puzzle configuration changes. If you \e{don't} want that, e.g. if
+you want to provide a command to explicitly reset the puzzle size back
+to its default, then you can call this just before calling
+\cw{midend_size()} (which, in turn, you would probably call with
+\c{user_size} set to \cw{FALSE}).
 
 \H{midend-new-game} \cw{midend_new_game()}
 
-\c void midend_new_game(midend_data *me);
+\c void midend_new_game(midend *me);
 
 Causes the mid-end to begin a new game. Normally the game will be a
 new randomly generated puzzle. However, if you have previously
@@ -1953,7 +2894,7 @@ a fresh one already. It would work, but it's usually excessive.)
 
 \H{midend-restart-game} \cw{midend_restart_game()}
 
-\c void midend_restart_game(midend_data *me);
+\c void midend_restart_game(midend *me);
 
 This function causes the current game to be restarted. This is done
 by placing a new copy of the original game state on the end of the
@@ -1961,33 +2902,36 @@ undo list (so that an accidental restart can be undone).
 
 This function automatically causes a redraw, i.e. the front end can
 expect its drawing API to be called from \e{within} a call to this
-function.
+function. Some back ends require that \cw{midend_size()}
+(\k{midend-size}) is called before \cw{midend_restart_game()}.
 
 \H{midend-force-redraw} \cw{midend_force_redraw()}
 
-\c void midend_force_redraw(midend_data *me);
+\c void midend_force_redraw(midend *me);
 
 Forces a complete redraw of the puzzle window, by means of
 discarding the current \c{game_drawstate} and creating a new one
 from scratch before calling the game's \cw{redraw()} function.
 
 The front end can expect its drawing API to be called from within a
-call to this function.
+call to this function. Some back ends require that \cw{midend_size()}
+(\k{midend-size}) is called before \cw{midend_force_redraw()}.
 
 \H{midend-redraw} \cw{midend_redraw()}
 
-\c void midend_redraw(midend_data *me);
+\c void midend_redraw(midend *me);
 
 Causes a partial redraw of the puzzle window, by means of simply
 calling the game's \cw{redraw()} function. (That is, the only things
 redrawn will be things that have changed since the last redraw.)
 
 The front end can expect its drawing API to be called from within a
-call to this function.
+call to this function. Some back ends require that \cw{midend_size()}
+(\k{midend-size}) is called before \cw{midend_redraw()}.
 
 \H{midend-process-key} \cw{midend_process_key()}
 
-\c int midend_process_key(midend_data *me, int x, int y, int button);
+\c int midend_process_key(midend *me, int x, int y, int button);
 
 The front end calls this function to report a mouse or keyboard
 event. The parameters \c{x}, \c{y} and \c{button} are almost
@@ -2020,9 +2964,14 @@ Calling this function is very likely to result in calls back to the
 front end's drawing API and/or \cw{activate_timer()}
 (\k{frontend-activate-timer}).
 
+The return value from \cw{midend_process_key()} is non-zero, unless
+the effect of the keypress was to request termination of the
+program. A front end should shut down the puzzle in response to a
+zero return.
+
 \H{midend-colours} \cw{midend_colours()}
 
-\c float *midend_colours(midend_data *me, int *ncolours);
+\c float *midend_colours(midend *me, int *ncolours);
 
 Returns an array of the colours required by the game, in exactly the
 same format as that returned by the back end function \cw{colours()}
@@ -2035,7 +2984,7 @@ more full and formal in future.)
 
 \H{midend-timer} \cw{midend_timer()}
 
-\c void midend_timer(midend_data *me, float tplus);
+\c void midend_timer(midend *me, float tplus);
 
 If the mid-end has called \cw{activate_timer()}
 (\k{frontend-activate-timer}) to request regular callbacks for
@@ -2048,38 +2997,81 @@ One of the major purposes of timing in the mid-end is to perform
 move animation. Therefore, calling this function is very likely to
 result in calls back to the front end's drawing API.
 
-\H{midend-num-presets} \cw{midend_num_presets()}
+\H{midend-get-presets} \cw{midend_get_presets()}
 
-\c int midend_num_presets(midend_data *me);
+\c struct preset_menu *midend_get_presets(midend *me, int *id_limit);
 
-Returns the number of game parameter presets supplied by this game.
-Front ends should use this function and \cw{midend_fetch_preset()}
-to configure their presets menu rather than calling the back end
-directly, since the mid-end adds standard customisation facilities.
-(At the time of writing, those customisation facilities are
-implemented hackily by means of environment variables, but it's not
-impossible that they may become more full and formal in future.)
+Returns a data structure describing this game's collection of preset
+game parameters, organised into a hierarchical structure of menus and
+submenus.
 
-\H{midend-fetch-preset} \cw{midend_fetch_preset()}
+The return value is a pointer to a data structure containing the
+following fields (among others, which are not intended for front end
+use):
 
-\c void midend_fetch_preset(midend_data *me, int n,
-\c                          char **name, game_params **params);
+\c struct preset_menu {
+\c     int n_entries;
+\c     struct preset_menu_entry *entries;
+\c     /* and other things */
+\e     iiiiiiiiiiiiiiiiiiiiii
+\c };
 
-Returns one of the preset game parameter structures for the game. On
-input \c{n} must be a non-negative integer and less than the value
-returned from \cw{midend_num_presets()}. On output, \c{*name} is set
-to an ASCII string suitable for entering in the game's presets menu,
-and \c{*params} is set to the corresponding \c{game_params}
-structure.
+Those fields describe the intended contents of one particular menu in
+the hierarchy. \cq{entries} points to an array of \cq{n_entries}
+items, each of which is a structure containing the following fields:
+
+\c struct preset_menu_entry {
+\c     char *title;
+\c     game_params *params;
+\c     struct preset_menu *submenu;
+\c     int id;
+\c };
+
+Of these fields, \cq{title} and \cq{id} are present in every entry,
+giving (respectively) the textual name of the menu item and an integer
+identifier for it. The integer id will correspond to the one returned
+by \c{midend_which_preset} (\k{midend-which-preset}), when that preset
+is the one selected.
+
+The other two fields are mutually exclusive. Each \c{struct
+preset_menu_entry} will have one of those fields \cw{NULL} and the
+other one non-null. If the menu item is an actual preset, then
+\cq{params} will point to the set of game parameters that go with the
+name; if it's a submenu, then \cq{submenu} instead will be non-null,
+and will point at a subsidiary \c{struct preset_menu}.
+
+The complete hierarchy of these structures is owned by the mid-end,
+and will be freed when the mid-end is freed. The front end should not
+attempt to free any of it.
+
+The integer identifiers will be allocated densely from 0 upwards, so
+that it's reasonable for the front end to allocate an array which uses
+them as indices, if it needs to store information per preset menu
+item. For this purpose, the front end may pass the second parameter
+\cq{id_limit} to \cw{midend_get_presets} as the address of an \c{int}
+variable, into which \cw{midend_get_presets} will write an integer one
+larger than the largest id number actually used (i.e. the number of
+elements the front end would need in the array).
 
-Both of the two output values are dynamically allocated, but they
-are owned by the mid-end structure: the front end should not ever
-free them directly, because they will be freed automatically during
-\cw{midend_free()}.
+Submenu-type entries also have integer identifiers.
+
+\H{midend-which-preset} \cw{midend_which_preset()}
+
+\c int midend_which_preset(midend *me);
+
+Returns the numeric index of the preset game parameter structure
+which matches the current game parameters, or a negative number if
+no preset matches. Front ends could use this to maintain a tick
+beside one of the items in the menu (or tick the \q{Custom} option
+if the return value is less than zero).
+
+The returned index value (if non-negative) will match the \c{id} field
+of the corresponding \cw{struct preset_menu_entry} returned by
+\c{midend_get_presets()} (\k{midend-get-presets}).
 
 \H{midend-wants-statusbar} \cw{midend_wants_statusbar()}
 
-\c int midend_wants_statusbar(midend_data *me);
+\c int midend_wants_statusbar(midend *me);
 
 This function returns \cw{TRUE} if the puzzle has a use for a
 textual status line (to display score, completion status, currently
@@ -2090,7 +3082,7 @@ the back end.
 
 \H{midend-get-config} \cw{midend_get_config()}
 
-\c config_item *midend_get_config(midend_data *me, int which,
+\c config_item *midend_get_config(midend *me, int which,
 \c                                char **wintitle);
 
 Returns a dialog box description for user configuration.
@@ -2137,7 +3129,7 @@ will probably need to pass it to \cw{midend_set_config}.)
 
 \H{midend-set-config} \cw{midend_set_config()}
 
-\c char *midend_set_config(midend_data *me, int which,
+\c char *midend_set_config(midend *me, int which,
 \c                         config_item *cfg);
 
 Passes the mid-end the results of a configuration dialog box.
@@ -2159,7 +3151,7 @@ using \cw{midend_size()} and eventually perform a refresh using
 
 \H{midend-game-id} \cw{midend_game_id()}
 
-\c char *midend_game_id(midend_data *me, char *id);
+\c char *midend_game_id(midend *me, char *id);
 
 Passes the mid-end a string game ID (of any of the valid forms
 \cq{params}, \cq{params:description} or \cq{params#seed}) which the
@@ -2178,16 +3170,46 @@ requested. The front end should therefore call
 using \cw{midend_size()} and eventually case a refresh using
 \cw{midend_redraw()}.
 
+\H{midend-get-game-id} \cw{midend_get_game_id()}
+
+\c char *midend_get_game_id(midend *me)
+
+Returns a descriptive game ID (i.e. one in the form
+\cq{params:description}) describing the game currently active in the
+mid-end. The returned string is dynamically allocated.
+
+\H{midend-get-random-seed} \cw{midend_get_random_seed()}
+
+\c char *midend_get_random_seed(midend *me)
+
+Returns a random game ID (i.e. one in the form \cq{params#seedstring})
+describing the game currently active in the mid-end, if there is one.
+If the game was created by entering a description, no random seed will
+currently exist and this function will return \cw{NULL}.
+
+The returned string, if it is non-\cw{NULL}, is dynamically allocated.
+
+\H{midend-can-format-as-text-now} \cw{midend_can_format_as_text_now()}
+
+\c int midend_can_format_as_text_now(midend *me);
+
+Returns \cw{TRUE} if the game code is capable of formatting puzzles
+of the currently selected game type as ASCII.
+
+If this returns \cw{FALSE}, then \cw{midend_text_format()}
+(\k{midend-text-format}) will return \cw{NULL}.
+
 \H{midend-text-format} \cw{midend_text_format()}
 
-\c char *midend_text_format(midend_data *me);
+\c char *midend_text_format(midend *me);
 
 Formats the current game's current state as ASCII text suitable for
 copying to the clipboard. The returned string is dynamically
 allocated.
 
-You should not call this function if the game's
-\c{can_format_as_text} flag is \cw{FALSE}.
+If the game's \c{can_format_as_text_ever} flag is \cw{FALSE}, or if
+its \cw{can_format_as_text_now()} function returns \cw{FALSE}, then
+this function will return \cw{NULL}.
 
 If the returned string contains multiple lines (which is likely), it
 will use the normal C line ending convention (\cw{\\n} only). On
@@ -2197,7 +3219,7 @@ conversion.
 
 \H{midend-solve} \cw{midend_solve()}
 
-\c char *midend_solve(midend_data *me);
+\c char *midend_solve(midend *me);
 
 Requests the mid-end to perform a Solve operation.
 
@@ -2207,37 +3229,44 @@ user.
 
 The front end can expect its drawing API and/or
 \cw{activate_timer()} to be called from within a call to this
-function.
+function.  Some back ends require that \cw{midend_size()}
+(\k{midend-size}) is called before \cw{midend_solve()}.
+
+\H{midend-status} \cw{midend_status()}
+
+\c int midend_status(midend *me);
+
+This function returns +1 if the midend is currently displaying a game
+in a solved state, -1 if the game is in a permanently lost state, or 0
+otherwise. This function just calls the back end's \cw{status()}
+function. Front ends may wish to use this as a cue to proactively
+offer the option of starting a new game.
 
-\H{midend-rewrite-statusbar} \cw{midend_rewrite_statusbar()}
-
-\c char *midend_rewrite_statusbar(midend_data *me, char *text);
-
-The front end should call this function from within
-\cw{status_bar()} (\k{drawing-status-bar}). It should be passed the
-string that was passed by the back end to \cw{status_bar()}; it will
-return a dynamically allocated string adjusted by the mid-end.
-(Specifically, adjusted to include the timer if the game is a timed
-one.) The returned value should be placed in the actual status bar
-in place of the input value.
-
-(This is a nasty piece of architecture; I apologise for it. It would
-seem a lot more pleasant to have the back end pass its status bar
-text to the mid-end, which in turn would rewrite it and pass it on
-to the front end, so that each front end needed to do nothing
-strange. The main reason why I haven't done this is because it means
-the back end redraw function would need to be passed a mid-end
-pointer \e{as well} as a front end pointer, which seemed like an
-excessive proliferation of opaque handles. The only way to avoid
-that proliferation would be to have all the drawing API functions
-also gatewayed through the mid-end, and that seemed like an
-excessive proliferation of wrapper functions. The current setup
-isn't nice, but it has minimal impact and I'm unconvinced that any
-of the other options are an improvement.)
+(See \k{backend-status} for more detail about the back end's
+\cw{status()} function and discussion of what should count as which
+status code.)
+
+\H{midend-can-undo} \cw{midend_can_undo()}
+
+\c int midend_can_undo(midend *me);
+
+Returns \cw{TRUE} if the midend is currently in a state where the undo
+operation is meaningful (i.e. at least one position exists on the undo
+chain before the present one). Front ends may wish to use this to
+visually activate and deactivate an undo button.
+
+\H{midend-can-redo} \cw{midend_can_redo()}
+
+\c int midend_can_redo(midend *me);
+
+Returns \cw{TRUE} if the midend is currently in a state where the redo
+operation is meaningful (i.e. at least one position exists on the redo
+chain after the present one). Front ends may wish to use this to
+visually activate and deactivate a redo button.
 
 \H{midend-serialise} \cw{midend_serialise()}
 
-\c void midend_serialise(midend_data *me,
+\c void midend_serialise(midend *me,
 \c                       void (*write)(void *ctx, void *buf, int len),
 \c                       void *wctx);
 
@@ -2262,7 +3291,7 @@ output string.
 
 \H{midend-deserialise} \cw{midend_deserialise()}
 
-\c char *midend_deserialise(midend_data *me,
+\c char *midend_deserialise(midend *me,
 \c                          int (*read)(void *ctx, void *buf, int len),
 \c                          void *rctx);
 
@@ -2292,12 +3321,63 @@ re-think the window size using \cw{midend_size()}, and probably
 cause a refresh using \cw{midend_redraw()}.
 
 Because each mid-end is tied to a specific game back end, this
-function will fail if you attempt to read in a save file generated
-by a different game from the one configured in this mid-end, even if
-your application is a monolithic one containing all the puzzles. (It
-would be pretty easy to write a function which would look at a save
-file and determine which game it was for; any front end implementor
-who needs such a function can probably be accommodated.)
+function will fail if you attempt to read in a save file generated by
+a different game from the one configured in this mid-end, even if your
+application is a monolithic one containing all the puzzles. See
+\k{identify-game} for a helper function which will allow you to
+identify a save file before you instantiate your mid-end in the first
+place.
+
+\H{identify-game} \cw{identify_game()}
+
+\c char *identify_game(char **name,
+\c                     int (*read)(void *ctx, void *buf, int len),
+\c                     void *rctx);
+
+This function examines a serialised midend stream, of the same kind
+used by \cw{midend_serialise()} and \cw{midend_deserialise()}, and
+returns the \cw{name} field of the game back end from which it was
+saved.
+
+You might want this if your front end was a monolithic one containing
+all the puzzles, and you wanted to be able to load an arbitrary save
+file and automatically switch to the right game. Probably your next
+step would be to iterate through \cw{gamelist} (\k{frontend-backend})
+looking for a game structure whose \cw{name} field matched the
+returned string, and give an error if you didn't find one.
+
+On success, the return value of this function is \cw{NULL}, and the
+game name string is written into \cw{*name}. The caller should free
+that string after using it.
+
+On failure, \cw{*name} is \cw{NULL}, and the return value is an error
+message (which does not need freeing at all).
+
+(This isn't strictly speaking a midend function, since it doesn't
+accept or return a pointer to a midend. You'd probably call it just
+\e{before} deciding what kind of midend you wanted to instantiate.)
+
+\H{midend-request-id-changes} \cw{midend_request_id_changes()}
+
+\c void midend_request_id_changes(midend *me,
+\c                                void (*notify)(void *), void *ctx);
+
+This function is called by the front end to request notification by
+the mid-end when the current game IDs (either descriptive or
+random-seed) change. This can occur as a result of keypresses ('n' for
+New Game, for example) or when a puzzle supersedes its game
+description (see \k{backend-supersede}). After this function is
+called, any change of the game ids will cause the mid-end to call
+\cw{notify(ctx)} after the change.
+
+This is for use by puzzles which want to present the game description
+to the user constantly (e.g. as an HTML hyperlink) instead of only
+showing it when the user explicitly requests it.
+
+This is a function I anticipate few front ends needing to implement,
+so I make it a callback rather than a static function in order to
+relieve most front ends of the need to provide an empty
+implementation.
 
 \H{frontend-backend} Direct reference to the back end structure by
 the front end
@@ -2316,8 +3396,8 @@ mid-end because there didn't seem much point in doing so:
 \b fetching the \c{name} field to use in window titles and similar
 
 \b reading the \c{can_configure}, \c{can_solve} and
-\c{can_format_as_text} fields to decide whether to add those items
-to the menu bar or equivalent
+\c{can_format_as_text_ever} fields to decide whether to add those
+items to the menu bar or equivalent
 
 \b reading the \c{winhelp_topic} field (Windows only)
 
@@ -2350,9 +3430,10 @@ base), then there will be two global variables defined:
 \c extern const int gamecount;
 
 \c{gamelist} will be an array of \c{gamecount} game structures,
-declared in the source module \c{list.c}. The application should
-search that array for the game it wants, probably by reaching into
-each game structure and looking at its \c{name} field.
+declared in the automatically constructed source module \c{list.c}.
+The application should search that array for the game it wants,
+probably by reaching into each game structure and looking at its
+\c{name} field.
 
 }
 
@@ -2409,6 +3490,20 @@ variadic function in the style of \cw{printf()}, and is expected to
 show the formatted error message to the user any way it can and then
 terminate the application. It must not return.
 
+\H{frontend-default-colour} \cw{frontend_default_colour()}
+
+\c void frontend_default_colour(frontend *fe, float *output);
+
+This function expects to be passed a pointer to an array of three
+\cw{float}s. It returns the platform's local preferred background
+colour in those three floats, as red, green and blue values (in that
+order) ranging from \cw{0.0} to \cw{1.0}.
+
+This function should only ever be called by the back end function
+\cw{colours()} (\k{backend-colours}). (Thus, it isn't a
+\e{midend}-to-frontend function as such, but there didn't seem to be
+anywhere else particularly good to put it. Sorry.)
+
 \C{utils} Utility APIs
 
 This chapter documents a variety of utility APIs provided for the
@@ -2428,9 +3523,9 @@ generator has an \e{explicit} state object called a
 \c{random_state}. One of these is managed by each mid-end, for
 example, and passed to the back end to generate a game with.
 
-\S{utils-random-init} \cw{random_init()}
+\S{utils-random-init} \cw{random_new()}
 
-\c random_state *random_init(char *seed, int len);
+\c random_state *random_new(char *seed, int len);
 
 Allocates, initialises and returns a new \c{random_state}. The input
 data is used as the seed for the random number stream (i.e. using
@@ -2439,6 +3534,17 @@ the same seed at a later time will generate the same stream).
 The seed data can be any data at all; there is no requirement to use
 printable ASCII, or NUL-terminated strings, or anything like that.
 
+\S{utils-random-copy} \cw{random_copy()}
+
+\c random_state *random_copy(random_state *tocopy);
+
+Allocates a new \c{random_state}, copies the contents of another
+\c{random_state} into it, and returns the new state.  If exactly the
+same sequence of functions is subseqently called on both the copy and
+the original, the results will be identical.  This may be useful for
+speculatively performing some operation using a given random state,
+and later replaying that operation precisely.
+
 \S{utils-random-free} \cw{random_free()}
 
 \c void random_free(random_state *state);
@@ -2493,6 +3599,63 @@ single element (typically measured using \c{sizeof}). \c{rs} is a
 \c{random_state} used to generate all the random numbers for the
 shuffling process.
 
+\H{utils-presets} Presets menu management
+
+The function \c{midend_get_presets()} (\k{midend-get-presets}) returns
+a data structure describing a menu hierarchy. Back ends can also
+choose to provide such a structure to the mid-end, if they want to
+group their presets hierarchically. To make this easy, there are a few
+utility functions to construct preset menu structures, and also one
+intended for front-end use.
+
+\S{utils-preset-menu-new} \cw{preset_menu_new()}
+
+\c struct preset_menu *preset_menu_new(void);
+
+Allocates a new \c{struct preset_menu}, and initialises it to hold no
+menu items.
+
+\S{utils-preset-menu-add_submenu} \cw{preset_menu_add_submenu()}
+
+\c struct preset_menu *preset_menu_add_submenu
+\c     (struct preset_menu *parent, char *title);
+
+Adds a new submenu to the end of an existing preset menu, and returns
+a pointer to a newly allocated \c{struct preset_menu} describing the
+submenu.
+
+The string parameter \cq{title} must be dynamically allocated by the
+caller. The preset-menu structure will take ownership of it, so the
+caller must not free it.
+
+\S{utils-preset-menu-add-preset} \cw{preset_menu_add_preset()}
+
+\c void preset_menu_add_preset
+\c     (struct preset_menu *menu, char *title, game_params *params);
+
+Adds a preset game configuration to the end of a preset menu.
+
+Both the string parameter \cq{title} and the game parameter structure
+\cq{params} itself must be dynamically allocated by the caller. The
+preset-menu structure will take ownership of it, so the caller must
+not free it.
+
+\S{utils-preset-menu-lookup-by-id} \cw{preset_menu_lookup_by_id()}
+
+\c game_params *preset_menu_lookup_by_id
+\c     (struct preset_menu *menu, int id);
+
+Given a numeric index, searches recursively through a preset menu
+hierarchy to find the corresponding menu entry, and returns a pointer
+to its existing \c{game_params} structure.
+
+This function is intended for front end use (but front ends need not
+use it if they prefer to do things another way). If a front end finds
+it inconvenient to store anything more than a numeric index alongside
+each menu item, then this function provides an easy way for the front
+end to get back the actual game parameters corresponding to a menu
+item that the user has selected.
+
 \H{utils-alloc} Memory allocation
 
 Puzzles has some central wrappers on the standard memory allocation
@@ -2522,7 +3685,7 @@ versa!).
 \S{utils-snewn} \cw{snewn()}
 
 \c var = snewn(n, type);
-\e iii            iiii
+\e iii         i  iiii
 
 This macro is the array form of \cw{snew()}. It takes two arguments;
 the first is a number, and the second is a type name. It allocates
@@ -2906,10 +4069,10 @@ sensibly fit anywhere else.
 \S{utils-truefalse} \cw{TRUE} and \cw{FALSE}
 
 The main Puzzles header file defines the macros \cw{TRUE} and
-\cw{FALSE}, which are used throughout the code in place of 0 and 1
-to indicate that the values are in a boolean context. For code base
-consistency, I'd prefer it if submissions of new code followed this
-convention as well.
+\cw{FALSE}, which are used throughout the code in place of 1 and 0
+(respectively) to indicate that the values are in a boolean context.
+For code base consistency, I'd prefer it if submissions of new code
+followed this convention as well.
 
 \S{utils-maxmin} \cw{max()} and \cw{min()}
 
@@ -3120,6 +4283,11 @@ compile it conveniently. \e{Do not edit the Makefiles}: they are
 created automatically by the script \c{mkfiles.pl}, from the file
 called \c{Recipe}. Edit \c{Recipe}, and then re-run \c{mkfiles.pl}.
 
+Also, don't forget to add your puzzle to \c{list.c}: if you don't,
+then it will still run fine on platforms which build each puzzle
+separately, but Mac OS X and other monolithic platforms will not
+include your new puzzle in their single binary.
+
 Once your source file is building, you can move on to the fun bit.
 
 \S{writing-generation} Puzzle generation
@@ -3272,19 +4440,22 @@ is next to a three}, which can depend on the values of up to 32 of
 the 56 squares in the default setting!), so this tweaking strategy
 would be rather less likely to work well.
 
-A more specialised strategy is that used in Solo. Solo has the
-unusual property that the clues (information provided at the
-beginning of the puzzle) and the solution (information the user is
-required to fill in) are inherently interchangeable; therefore a
-simple generation technique is to leave the decision of which
-numbers are clues until the last minute. Solo works by first
-generating a random \e{filled} grid, and then gradually removing
-numbers for as long as the solver reports that it's still soluble.
-Unlike the methods described above, this technique \e{cannot} fail
-\dash once you've got a filled grid, nothing can stop you from being
-able to convert it into a viable puzzle. However, it wouldn't even
-be meaningful to apply this technique to (say) Pattern, in which the
-clues and the solution occupy completely different spaces.
+A more specialised strategy is that used in Solo and Slant. These
+puzzles have the property that they derive their difficulty from not
+presenting all the available clues. (In Solo's case, if all the
+possible clues were provided then the puzzle would already be
+solved; in Slant it would still require user action to fill in the
+lines, but it would present no challenge at all). Therefore, a
+simple generation technique is to leave the decision of which clues
+to provide until the last minute. In other words, first generate a
+random \e{filled} grid with all possible clues present, and then
+gradually remove clues for as long as the solver reports that it's
+still soluble. Unlike the methods described above, this technique
+\e{cannot} fail \dash once you've got a filled grid, nothing can
+stop you from being able to convert it into a viable puzzle.
+However, it wouldn't even be meaningful to apply this technique to
+(say) Pattern, in which clues can never be left out, so the only way
+to affect the set of clues is by altering the solution.
 
 (Unfortunately, Solo is complicated by the need to provide puzzles
 at varying difficulty levels. It's easy enough to generate a puzzle
@@ -3354,13 +4525,13 @@ notice that a puzzle is soluble), and it can fail to generate a
 puzzle at all, provided it doesn't do either so often as to become
 slow.
 
-One last piece of advice: for grid-based puzzles when writing and
+One last piece of advice: for grid-based puzzles, when writing and
 testing your generation algorithm, it's almost always a good idea
 \e{not} to test it initially on a grid that's square (i.e.
-\cw{w==h}), because that way you won't notice if you mistakenly
-write \c{w} instead of \c{h} or vice versa somewhere in the code.
-Use a rectangular grid for testing, and any size of grid will be
-likely to work after that.
+\cw{w==h}), because if the grid is square then you won't notice if
+you mistakenly write \c{h} instead of \c{w} (or vice versa)
+somewhere in the code. Use a rectangular grid for testing, and any
+size of grid will be likely to work after that.
 
 \S{writing-textformats} Designing textual description formats
 
@@ -3406,7 +4577,7 @@ make it difficult to find the cursor in order to do anything with
 it, and would introduce the potential for synchronisation bugs in
 which you ended up with two cursors or none. The obviously sensible
 way to store a cursor in the \c{game_ui} is to have fields directly
-encodings the cursor's coordinates.
+encoding the cursor's coordinates.
 
 However, it is a mistake to assume that the same logic applies to
 the \c{game_drawstate}. If you replicate the cursor position fields
@@ -3425,7 +4596,7 @@ Then the main redraw loop will look something like this
 \c         if (x == ui->cursor_x && y == ui->cursor_y)
 \c             value |= CURSOR;
 \c         if (ds->symbol_at_position[y][x] != value) {
-\c             symbol_drawing_subroutine(fe, ds, x, y, value);
+\c             symbol_drawing_subroutine(dr, ds, x, y, value);
 \c             ds->symbol_at_position[y][x] = value;
 \c         }
 \c     }
@@ -3490,9 +4661,7 @@ piece of saved background needs to be.
 
 \b In the game's \cw{set_size()} function, once you know the size of
 the object you'll be dragging around the display and hence the
-required size of the blitter, actually allocate the blitter (making
-sure to free a previous one if present \dash it's possible that
-\cw{set_size()} might be called twice on the same draw state).
+required size of the blitter, actually allocate the blitter.
 
 \b In \cw{free_drawstate()}, free the blitter if it's not \cw{NULL}.
 
@@ -3727,3 +4896,5 @@ that the redraw and the animations (if any) work properly. Failing
 to animate undo properly seems to be a common error.
 
 Other than that, just use your common sense.
+
+\versionid Simon Tatham's Portable Puzzle Collection, version 20161228.7cae89f