midend.c 96 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208
  1. /*
  2. * midend.c: general middle fragment sitting between the
  3. * platform-specific front end and game-specific back end.
  4. * Maintains a move list, takes care of Undo and Redo commands, and
  5. * processes standard keystrokes for undo/redo/new/quit.
  6. */
  7. #include <stdio.h>
  8. #include <string.h>
  9. #include <assert.h>
  10. #include <stdlib.h>
  11. #include <ctype.h>
  12. #include "puzzles.h"
  13. enum { DEF_PARAMS, DEF_SEED, DEF_DESC }; /* for midend_game_id_int */
  14. enum { NEWGAME, MOVE, SOLVE, RESTART };/* for midend_state_entry.movetype */
  15. #define special(type) ( (type) != MOVE )
  16. struct midend_state_entry {
  17. game_state *state;
  18. char *movestr;
  19. int movetype;
  20. };
  21. struct midend_serialise_buf {
  22. char *buf;
  23. int len, size;
  24. };
  25. struct midend_serialise_buf_read_ctx {
  26. struct midend_serialise_buf *ser;
  27. int len, pos;
  28. };
  29. struct midend {
  30. frontend *frontend;
  31. random_state *random;
  32. const game *ourgame;
  33. struct preset_menu *preset_menu;
  34. char **encoded_presets; /* for midend_which_preset to check against */
  35. int n_encoded_presets;
  36. /*
  37. * `desc' and `privdesc' deserve a comment.
  38. *
  39. * `desc' is the game description as presented to the user when
  40. * they ask for Game -> Specific. `privdesc', if non-NULL, is a
  41. * different game description used to reconstruct the initial
  42. * game_state when de-serialising. If privdesc is NULL, `desc'
  43. * is used for both.
  44. *
  45. * For almost all games, `privdesc' is NULL and never used. The
  46. * exception (as usual) is Mines: the initial game state has no
  47. * squares open at all, but after the first click `desc' is
  48. * rewritten to describe a game state with an initial click and
  49. * thus a bunch of squares open. If we used that desc to
  50. * serialise and deserialise, then the initial game state after
  51. * deserialisation would look unlike the initial game state
  52. * beforehand, and worse still execute_move() might fail on the
  53. * attempted first click. So `privdesc' is also used in this
  54. * case, to provide a game description describing the same
  55. * fixed mine layout _but_ no initial click. (These game IDs
  56. * may also be typed directly into Mines if you like.)
  57. */
  58. char *desc, *privdesc, *seedstr;
  59. char *aux_info;
  60. enum { GOT_SEED, GOT_DESC, GOT_NOTHING } genmode;
  61. int nstates, statesize, statepos;
  62. struct midend_state_entry *states;
  63. struct midend_serialise_buf newgame_undo, newgame_redo;
  64. bool newgame_can_store_undo;
  65. game_params *params, *curparams;
  66. game_drawstate *drawstate;
  67. bool first_draw;
  68. game_ui *ui;
  69. game_state *oldstate;
  70. float anim_time, anim_pos;
  71. float flash_time, flash_pos;
  72. int dir;
  73. bool timing;
  74. float elapsed;
  75. char *laststatus;
  76. drawing *drawing;
  77. int pressed_mouse_button;
  78. struct midend_serialise_buf be_prefs;
  79. int preferred_tilesize, preferred_tilesize_dpr, tilesize;
  80. int winwidth, winheight;
  81. void (*game_id_change_notify_function)(void *);
  82. void *game_id_change_notify_ctx;
  83. bool one_key_shortcuts;
  84. };
  85. #define ensure(me) do { \
  86. if ((me)->nstates >= (me)->statesize) { \
  87. (me)->statesize = (me)->nstates + 128; \
  88. (me)->states = sresize((me)->states, (me)->statesize, \
  89. struct midend_state_entry); \
  90. } \
  91. } while (0)
  92. /*
  93. * Structure storing all the decoded data from reading a serialised
  94. * game. We keep it in one of these while we check its sanity, and
  95. * only once we're completely satisfied do we install it all in the
  96. * midend structure proper.
  97. */
  98. struct deserialise_data {
  99. char *seed, *parstr, *desc, *privdesc;
  100. char *auxinfo, *uistr, *cparstr;
  101. float elapsed;
  102. game_params *params, *cparams;
  103. game_ui *ui;
  104. struct midend_state_entry *states;
  105. int nstates, statepos;
  106. };
  107. /*
  108. * Forward references.
  109. */
  110. static const char *midend_deserialise_internal(
  111. midend *me, bool (*read)(void *ctx, void *buf, int len), void *rctx,
  112. const char *(*check)(void *ctx, midend *, const struct deserialise_data *),
  113. void *cctx);
  114. static void midend_serialise_prefs(
  115. midend *me, game_ui *ui,
  116. void (*write)(void *ctx, const void *buf, int len), void *wctx);
  117. static const char *midend_deserialise_prefs(
  118. midend *me, game_ui *ui,
  119. bool (*read)(void *ctx, void *buf, int len), void *rctx);
  120. static config_item *midend_get_prefs(midend *me, game_ui *ui);
  121. static void midend_set_prefs(midend *me, game_ui *ui, config_item *all_prefs);
  122. static void midend_apply_prefs(midend *me, game_ui *ui);
  123. void midend_reset_tilesize(midend *me)
  124. {
  125. me->preferred_tilesize = me->ourgame->preferred_tilesize;
  126. me->preferred_tilesize_dpr = 1.0;
  127. {
  128. /*
  129. * Allow an environment-based override for the default tile
  130. * size by defining a variable along the lines of
  131. * `NET_TILESIZE=15'.
  132. *
  133. * XXX How should this interact with DPR?
  134. */
  135. char buf[80], *e;
  136. int j, k, ts;
  137. sprintf(buf, "%s_TILESIZE", me->ourgame->name);
  138. for (j = k = 0; buf[j]; j++)
  139. if (!isspace((unsigned char)buf[j]))
  140. buf[k++] = toupper((unsigned char)buf[j]);
  141. buf[k] = '\0';
  142. if ((e = getenv(buf)) != NULL && sscanf(e, "%d", &ts) == 1 && ts > 0)
  143. me->preferred_tilesize = ts;
  144. }
  145. }
  146. midend *midend_new(frontend *fe, const game *ourgame,
  147. const drawing_api *drapi, void *drhandle)
  148. {
  149. midend *me = snew(midend);
  150. void *randseed;
  151. int randseedsize;
  152. get_random_seed(&randseed, &randseedsize);
  153. me->frontend = fe;
  154. me->ourgame = ourgame;
  155. me->random = random_new(randseed, randseedsize);
  156. me->nstates = me->statesize = me->statepos = 0;
  157. me->states = NULL;
  158. me->newgame_undo.buf = NULL;
  159. me->newgame_undo.size = me->newgame_undo.len = 0;
  160. me->newgame_redo.buf = NULL;
  161. me->newgame_redo.size = me->newgame_redo.len = 0;
  162. me->newgame_can_store_undo = false;
  163. me->params = ourgame->default_params();
  164. me->game_id_change_notify_function = NULL;
  165. me->game_id_change_notify_ctx = NULL;
  166. me->encoded_presets = NULL;
  167. me->n_encoded_presets = 0;
  168. /*
  169. * Allow environment-based changing of the default settings by
  170. * defining a variable along the lines of `NET_DEFAULT=25x25w'
  171. * in which the value is an encoded parameter string.
  172. */
  173. {
  174. char buf[80], *e;
  175. int j, k;
  176. sprintf(buf, "%s_DEFAULT", me->ourgame->name);
  177. for (j = k = 0; buf[j]; j++)
  178. if (!isspace((unsigned char)buf[j]))
  179. buf[k++] = toupper((unsigned char)buf[j]);
  180. buf[k] = '\0';
  181. if ((e = getenv(buf)) != NULL)
  182. me->ourgame->decode_params(me->params, e);
  183. }
  184. me->curparams = NULL;
  185. me->desc = me->privdesc = NULL;
  186. me->seedstr = NULL;
  187. me->aux_info = NULL;
  188. me->genmode = GOT_NOTHING;
  189. me->drawstate = NULL;
  190. me->first_draw = true;
  191. me->oldstate = NULL;
  192. me->preset_menu = NULL;
  193. me->anim_time = me->anim_pos = 0.0F;
  194. me->flash_time = me->flash_pos = 0.0F;
  195. me->dir = 0;
  196. me->ui = NULL;
  197. me->pressed_mouse_button = 0;
  198. me->laststatus = NULL;
  199. me->timing = false;
  200. me->elapsed = 0.0F;
  201. me->tilesize = me->winwidth = me->winheight = 0;
  202. if (drapi)
  203. me->drawing = drawing_new(drapi, me, drhandle);
  204. else
  205. me->drawing = NULL;
  206. me->be_prefs.buf = NULL;
  207. me->be_prefs.size = me->be_prefs.len = 0;
  208. me->one_key_shortcuts = true;
  209. midend_reset_tilesize(me);
  210. sfree(randseed);
  211. return me;
  212. }
  213. const game *midend_which_game(midend *me)
  214. {
  215. return me->ourgame;
  216. }
  217. static void midend_purge_states(midend *me)
  218. {
  219. while (me->nstates > me->statepos) {
  220. me->ourgame->free_game(me->states[--me->nstates].state);
  221. if (me->states[me->nstates].movestr)
  222. sfree(me->states[me->nstates].movestr);
  223. }
  224. me->newgame_redo.len = 0;
  225. }
  226. static void midend_free_game(midend *me)
  227. {
  228. while (me->nstates > 0) {
  229. me->nstates--;
  230. me->ourgame->free_game(me->states[me->nstates].state);
  231. sfree(me->states[me->nstates].movestr);
  232. }
  233. if (me->drawstate)
  234. me->ourgame->free_drawstate(me->drawing, me->drawstate);
  235. }
  236. static void midend_free_preset_menu(midend *me, struct preset_menu *menu)
  237. {
  238. if (menu) {
  239. int i;
  240. for (i = 0; i < menu->n_entries; i++) {
  241. sfree(menu->entries[i].title);
  242. if (menu->entries[i].params)
  243. me->ourgame->free_params(menu->entries[i].params);
  244. midend_free_preset_menu(me, menu->entries[i].submenu);
  245. }
  246. sfree(menu->entries);
  247. sfree(menu);
  248. }
  249. }
  250. void midend_free(midend *me)
  251. {
  252. int i;
  253. midend_free_game(me);
  254. for (i = 0; i < me->n_encoded_presets; i++)
  255. sfree(me->encoded_presets[i]);
  256. sfree(me->encoded_presets);
  257. if (me->drawing)
  258. drawing_free(me->drawing);
  259. random_free(me->random);
  260. sfree(me->newgame_undo.buf);
  261. sfree(me->newgame_redo.buf);
  262. sfree(me->states);
  263. sfree(me->desc);
  264. sfree(me->privdesc);
  265. sfree(me->seedstr);
  266. sfree(me->aux_info);
  267. sfree(me->be_prefs.buf);
  268. me->ourgame->free_params(me->params);
  269. midend_free_preset_menu(me, me->preset_menu);
  270. if (me->ui)
  271. me->ourgame->free_ui(me->ui);
  272. if (me->curparams)
  273. me->ourgame->free_params(me->curparams);
  274. sfree(me->laststatus);
  275. sfree(me);
  276. }
  277. static void midend_size_new_drawstate(midend *me)
  278. {
  279. /*
  280. * Don't even bother, if we haven't worked out our tile size
  281. * anyway yet.
  282. */
  283. if (me->tilesize > 0) {
  284. me->ourgame->compute_size(me->params, me->tilesize, me->ui,
  285. &me->winwidth, &me->winheight);
  286. me->ourgame->set_size(me->drawing, me->drawstate,
  287. me->params, me->tilesize);
  288. }
  289. }
  290. /*
  291. * There is no one correct way to convert tilesizes between device
  292. * pixel ratios, because there's only a loosely-defined relationship
  293. * between tilesize and the actual size of a puzzle. We define this
  294. * function as the canonical conversion function so everything in the
  295. * midend will be consistent.
  296. */
  297. static int convert_tilesize(midend *me, int old_tilesize,
  298. double old_dpr, double new_dpr)
  299. {
  300. int x, y, rx, ry, min, max;
  301. game_params *defaults;
  302. if (new_dpr == old_dpr)
  303. return old_tilesize;
  304. defaults = me->ourgame->default_params();
  305. me->ourgame->compute_size(defaults, old_tilesize, me->ui, &x, &y);
  306. x *= new_dpr / old_dpr;
  307. y *= new_dpr / old_dpr;
  308. min = max = 1;
  309. do {
  310. max *= 2;
  311. me->ourgame->compute_size(defaults, max, me->ui, &rx, &ry);
  312. } while (rx <= x && ry <= y);
  313. while (max - min > 1) {
  314. int mid = (max + min) / 2;
  315. me->ourgame->compute_size(defaults, mid, me->ui, &rx, &ry);
  316. if (rx <= x && ry <= y)
  317. min = mid;
  318. else
  319. max = mid;
  320. }
  321. me->ourgame->free_params(defaults);
  322. return min;
  323. }
  324. void midend_size(midend *me, int *x, int *y, bool user_size,
  325. double device_pixel_ratio)
  326. {
  327. int min, max;
  328. int rx, ry;
  329. /*
  330. * We can't set the size on the same drawstate twice. So if
  331. * we've already sized one drawstate, we must throw it away and
  332. * create a new one.
  333. */
  334. if (me->drawstate && me->tilesize > 0) {
  335. me->ourgame->free_drawstate(me->drawing, me->drawstate);
  336. me->drawstate = me->ourgame->new_drawstate(me->drawing,
  337. me->states[0].state);
  338. me->first_draw = true;
  339. }
  340. /*
  341. * Find the tile size that best fits within the given space. If
  342. * `user_size' is true, we must actually find the _largest_ such
  343. * tile size, in order to get as close to the user's explicit
  344. * request as possible; otherwise, we bound above at the game's
  345. * preferred tile size, so that the game gets what it wants
  346. * provided that this doesn't break the constraint from the
  347. * front-end (which is likely to be a screen size or similar).
  348. */
  349. if (user_size) {
  350. max = 1;
  351. do {
  352. max *= 2;
  353. me->ourgame->compute_size(me->params, max, me->ui, &rx, &ry);
  354. } while (rx <= *x && ry <= *y);
  355. } else
  356. max = convert_tilesize(me, me->preferred_tilesize,
  357. me->preferred_tilesize_dpr,
  358. device_pixel_ratio) + 1;
  359. min = 1;
  360. /*
  361. * Now binary-search between min and max. We're looking for a
  362. * boundary rather than a value: the point at which tile sizes
  363. * stop fitting within the given dimensions. Thus, we stop when
  364. * max and min differ by exactly 1.
  365. */
  366. while (max - min > 1) {
  367. int mid = (max + min) / 2;
  368. me->ourgame->compute_size(me->params, mid, me->ui, &rx, &ry);
  369. if (rx <= *x && ry <= *y)
  370. min = mid;
  371. else
  372. max = mid;
  373. }
  374. /*
  375. * Now `min' is a valid size, and `max' isn't. So use `min'.
  376. */
  377. me->tilesize = min;
  378. if (user_size) {
  379. /* If the user requested a change in size, make it permanent. */
  380. me->preferred_tilesize = me->tilesize;
  381. me->preferred_tilesize_dpr = device_pixel_ratio;
  382. }
  383. midend_size_new_drawstate(me);
  384. *x = me->winwidth;
  385. *y = me->winheight;
  386. }
  387. int midend_tilesize(midend *me) { return me->tilesize; }
  388. void midend_set_params(midend *me, game_params *params)
  389. {
  390. me->ourgame->free_params(me->params);
  391. me->params = me->ourgame->dup_params(params);
  392. }
  393. game_params *midend_get_params(midend *me)
  394. {
  395. return me->ourgame->dup_params(me->params);
  396. }
  397. static char *encode_params(midend *me, const game_params *params, bool full)
  398. {
  399. char *encoded = me->ourgame->encode_params(params, full);
  400. int i;
  401. /* Assert that the params consist of printable ASCII containing
  402. * neither '#' nor ':'. */
  403. for (i = 0; encoded[i]; i++)
  404. assert(encoded[i] >= 32 && encoded[i] < 127 &&
  405. encoded[i] != '#' && encoded[i] != ':');
  406. return encoded;
  407. }
  408. static void assert_printable_ascii(char const *s)
  409. {
  410. /* Assert that s is entirely printable ASCII, and hence safe for
  411. * writing in a save file. */
  412. int i;
  413. for (i = 0; s[i]; i++)
  414. assert(s[i] >= 32 && s[i] < 127);
  415. }
  416. static void midend_set_timer(midend *me)
  417. {
  418. me->timing = (me->ourgame->is_timed &&
  419. me->ourgame->timing_state(me->states[me->statepos-1].state,
  420. me->ui));
  421. if (me->timing || me->flash_time || me->anim_time)
  422. activate_timer(me->frontend);
  423. else
  424. deactivate_timer(me->frontend);
  425. }
  426. void midend_force_redraw(midend *me)
  427. {
  428. if (me->drawstate)
  429. me->ourgame->free_drawstate(me->drawing, me->drawstate);
  430. me->drawstate = me->ourgame->new_drawstate(me->drawing,
  431. me->states[0].state);
  432. me->first_draw = true;
  433. midend_size_new_drawstate(me);
  434. midend_redraw(me);
  435. }
  436. static void midend_serialise_buf_write(void *ctx, const void *buf, int len)
  437. {
  438. struct midend_serialise_buf *ser = (struct midend_serialise_buf *)ctx;
  439. int new_len;
  440. assert(len < INT_MAX - ser->len);
  441. new_len = ser->len + len;
  442. if (new_len > ser->size) {
  443. ser->size = new_len + new_len / 4 + 1024;
  444. ser->buf = sresize(ser->buf, ser->size, char);
  445. }
  446. memcpy(ser->buf + ser->len, buf, len);
  447. ser->len = new_len;
  448. }
  449. static bool midend_serialise_buf_read(void *ctx, void *buf, int len)
  450. {
  451. struct midend_serialise_buf_read_ctx *const rctx = ctx;
  452. if (len > rctx->len - rctx->pos)
  453. return false;
  454. memcpy(buf, rctx->ser->buf + rctx->pos, len);
  455. rctx->pos += len;
  456. return true;
  457. }
  458. void midend_new_game(midend *me)
  459. {
  460. me->newgame_undo.len = 0;
  461. if (me->newgame_can_store_undo) {
  462. /*
  463. * Serialise the whole of the game that we're about to
  464. * supersede, so that the 'New Game' action can be undone
  465. * later.
  466. *
  467. * We omit this in various situations, such as if there
  468. * _isn't_ a current game (not even a starting position)
  469. * because this is the initial call to midend_new_game when
  470. * the midend is first set up, or if the midend state has
  471. * already begun to be overwritten by midend_set_config. In
  472. * those situations, we want to avoid writing out any
  473. * serialisation, because they will be either invalid, or
  474. * worse, valid but wrong.
  475. */
  476. midend_purge_states(me);
  477. midend_serialise(me, midend_serialise_buf_write, &me->newgame_undo);
  478. }
  479. midend_stop_anim(me);
  480. midend_free_game(me);
  481. assert(me->nstates == 0);
  482. if (me->genmode == GOT_DESC) {
  483. me->genmode = GOT_NOTHING;
  484. } else {
  485. random_state *rs;
  486. if (me->genmode == GOT_SEED) {
  487. me->genmode = GOT_NOTHING;
  488. } else {
  489. /*
  490. * Generate a new random seed. 15 digits comes to about
  491. * 48 bits, which should be more than enough.
  492. *
  493. * I'll avoid putting a leading zero on the number,
  494. * just in case it confuses anybody who thinks it's
  495. * processed as an integer rather than a string.
  496. */
  497. char newseed[16];
  498. int i;
  499. newseed[15] = '\0';
  500. newseed[0] = '1' + (char)random_upto(me->random, 9);
  501. for (i = 1; i < 15; i++)
  502. newseed[i] = '0' + (char)random_upto(me->random, 10);
  503. sfree(me->seedstr);
  504. me->seedstr = dupstr(newseed);
  505. if (me->curparams)
  506. me->ourgame->free_params(me->curparams);
  507. me->curparams = me->ourgame->dup_params(me->params);
  508. }
  509. sfree(me->desc);
  510. sfree(me->privdesc);
  511. sfree(me->aux_info);
  512. me->aux_info = NULL;
  513. rs = random_new(me->seedstr, strlen(me->seedstr));
  514. /*
  515. * If this midend has been instantiated without providing a
  516. * drawing API, it is non-interactive. This means that it's
  517. * being used for bulk game generation, and hence we should
  518. * pass the non-interactive flag to new_desc.
  519. */
  520. me->desc = me->ourgame->new_desc(me->curparams, rs,
  521. &me->aux_info, (me->drawing != NULL));
  522. assert_printable_ascii(me->desc);
  523. me->privdesc = NULL;
  524. random_free(rs);
  525. }
  526. ensure(me);
  527. /*
  528. * It might seem a bit odd that we're using me->params to
  529. * create the initial game state, rather than me->curparams
  530. * which is better tailored to this specific game and which we
  531. * always know.
  532. *
  533. * It's supposed to be an invariant in the midend that
  534. * me->params and me->curparams differ in no aspect that is
  535. * important after generation (i.e. after new_desc()). By
  536. * deliberately passing the _less_ specific of these two
  537. * parameter sets, we provoke play-time misbehaviour in the
  538. * case where a game has failed to encode a play-time parameter
  539. * in the non-full version of encode_params().
  540. */
  541. me->states[me->nstates].state =
  542. me->ourgame->new_game(me, me->params, me->desc);
  543. /*
  544. * As part of our commitment to self-testing, test the aux
  545. * string to make sure nothing ghastly went wrong.
  546. */
  547. if (me->ourgame->can_solve && me->aux_info) {
  548. game_state *s;
  549. const char *msg;
  550. char *movestr;
  551. msg = NULL;
  552. movestr = me->ourgame->solve(me->states[0].state,
  553. me->states[0].state,
  554. me->aux_info, &msg);
  555. assert(movestr && !msg);
  556. s = me->ourgame->execute_move(me->states[0].state, movestr);
  557. assert(s);
  558. me->ourgame->free_game(s);
  559. sfree(movestr);
  560. }
  561. me->states[me->nstates].movestr = NULL;
  562. me->states[me->nstates].movetype = NEWGAME;
  563. me->nstates++;
  564. me->statepos = 1;
  565. me->drawstate = me->ourgame->new_drawstate(me->drawing,
  566. me->states[0].state);
  567. me->first_draw = true;
  568. midend_size_new_drawstate(me);
  569. me->elapsed = 0.0F;
  570. me->flash_pos = me->flash_time = 0.0F;
  571. me->anim_pos = me->anim_time = 0.0F;
  572. if (me->ui)
  573. me->ourgame->free_ui(me->ui);
  574. me->ui = me->ourgame->new_ui(me->states[0].state);
  575. midend_apply_prefs(me, me->ui);
  576. midend_set_timer(me);
  577. me->pressed_mouse_button = 0;
  578. if (me->game_id_change_notify_function)
  579. me->game_id_change_notify_function(me->game_id_change_notify_ctx);
  580. me->newgame_can_store_undo = true;
  581. }
  582. const char *midend_load_prefs(
  583. midend *me, bool (*read)(void *ctx, void *buf, int len), void *rctx)
  584. {
  585. const char *err = midend_deserialise_prefs(me, NULL, read, rctx);
  586. return err;
  587. }
  588. void midend_save_prefs(midend *me,
  589. void (*write)(void *ctx, const void *buf, int len),
  590. void *wctx)
  591. {
  592. midend_serialise_prefs(me, NULL, write, wctx);
  593. }
  594. bool midend_can_undo(midend *me)
  595. {
  596. return (me->statepos > 1 || me->newgame_undo.len);
  597. }
  598. bool midend_can_redo(midend *me)
  599. {
  600. return (me->statepos < me->nstates || me->newgame_redo.len);
  601. }
  602. struct newgame_undo_deserialise_check_ctx {
  603. bool refused;
  604. };
  605. static const char *newgame_undo_deserialise_check(
  606. void *vctx, midend *me, const struct deserialise_data *data)
  607. {
  608. struct newgame_undo_deserialise_check_ctx *ctx =
  609. (struct newgame_undo_deserialise_check_ctx *)vctx;
  610. char *old, *new;
  611. /*
  612. * Undoing a New Game operation is only permitted if it doesn't
  613. * change the game parameters. The point of having the ability at
  614. * all is to recover from the momentary finger error of having hit
  615. * the 'n' key (perhaps in place of some other nearby key), or hit
  616. * the New Game menu item by mistake when aiming for the adjacent
  617. * Restart; in both those situations, the game params are the same
  618. * before and after the new-game operation.
  619. *
  620. * In principle, we could generalise this so that _any_ call to
  621. * midend_new_game could be undone, but that would need all front
  622. * ends to be alert to the possibility that any keystroke passed
  623. * to midend_process_key might (if it turns out to have been one
  624. * of the synonyms for undo, which the frontend doesn't
  625. * necessarily check for) have various knock-on effects like
  626. * needing to select a different preset in the game type menu, or
  627. * even resizing the window. At least for the moment, it's easier
  628. * not to do that, and to simply disallow any newgame-undo that is
  629. * disruptive in either of those ways.
  630. *
  631. * We check both params and cparams, to be as safe as possible.
  632. */
  633. old = encode_params(me, me->params, true);
  634. new = encode_params(me, data->params, true);
  635. if (strcmp(old, new)) {
  636. /* Set a flag to distinguish this deserialise failure
  637. * from one due to faulty decoding */
  638. ctx->refused = true;
  639. return "Undoing this new-game operation would change params";
  640. }
  641. old = encode_params(me, me->curparams, true);
  642. new = encode_params(me, data->cparams, true);
  643. if (strcmp(old, new)) {
  644. ctx->refused = true;
  645. return "Undoing this new-game operation would change params";
  646. }
  647. /*
  648. * Otherwise, fine, go ahead.
  649. */
  650. return NULL;
  651. }
  652. static bool midend_undo(midend *me)
  653. {
  654. const char *deserialise_error;
  655. if (me->statepos > 1) {
  656. if (me->ui)
  657. me->ourgame->changed_state(me->ui,
  658. me->states[me->statepos-1].state,
  659. me->states[me->statepos-2].state);
  660. me->statepos--;
  661. me->dir = -1;
  662. return true;
  663. } else if (me->newgame_undo.len) {
  664. struct midend_serialise_buf_read_ctx rctx;
  665. struct newgame_undo_deserialise_check_ctx cctx;
  666. struct midend_serialise_buf serbuf;
  667. /*
  668. * Serialise the current game so that you can later redo past
  669. * this undo. Once we're committed to the undo actually
  670. * happening, we'll copy this data into place.
  671. */
  672. serbuf.buf = NULL;
  673. serbuf.len = serbuf.size = 0;
  674. midend_serialise(me, midend_serialise_buf_write, &serbuf);
  675. rctx.ser = &me->newgame_undo;
  676. rctx.len = me->newgame_undo.len; /* copy for reentrancy safety */
  677. rctx.pos = 0;
  678. cctx.refused = false;
  679. deserialise_error = midend_deserialise_internal(
  680. me, midend_serialise_buf_read, &rctx,
  681. newgame_undo_deserialise_check, &cctx);
  682. if (cctx.refused) {
  683. /*
  684. * Our post-deserialisation check shows that we can't use
  685. * this saved game after all. (deserialise_error will
  686. * contain the dummy error message generated by our check
  687. * function, which we ignore.)
  688. */
  689. sfree(serbuf.buf);
  690. return false;
  691. } else {
  692. /*
  693. * There should never be any _other_ deserialisation
  694. * error, because this serialised data has been held in
  695. * our memory since it was created, and hasn't had any
  696. * opportunity to be corrupted on disk, accidentally
  697. * replaced by the wrong file, etc., by user error.
  698. */
  699. assert(!deserialise_error);
  700. /*
  701. * Clear the old newgame_undo serialisation, so that we
  702. * don't try to undo past the beginning of the game we've
  703. * just gone back to and end up at the front of it again.
  704. */
  705. me->newgame_undo.len = 0;
  706. /*
  707. * Copy the serialisation of the game we've just left into
  708. * the midend so that we can redo back into it later.
  709. */
  710. me->newgame_redo.len = 0;
  711. midend_serialise_buf_write(&me->newgame_redo,
  712. serbuf.buf, serbuf.len);
  713. sfree(serbuf.buf);
  714. return true;
  715. }
  716. } else
  717. return false;
  718. }
  719. static bool midend_redo(midend *me)
  720. {
  721. const char *deserialise_error;
  722. if (me->statepos < me->nstates) {
  723. if (me->ui)
  724. me->ourgame->changed_state(me->ui,
  725. me->states[me->statepos-1].state,
  726. me->states[me->statepos].state);
  727. me->statepos++;
  728. me->dir = +1;
  729. return true;
  730. } else if (me->newgame_redo.len) {
  731. struct midend_serialise_buf_read_ctx rctx;
  732. struct newgame_undo_deserialise_check_ctx cctx;
  733. struct midend_serialise_buf serbuf;
  734. /*
  735. * Serialise the current game so that you can later undo past
  736. * this redo. Once we're committed to the undo actually
  737. * happening, we'll copy this data into place.
  738. */
  739. serbuf.buf = NULL;
  740. serbuf.len = serbuf.size = 0;
  741. midend_serialise(me, midend_serialise_buf_write, &serbuf);
  742. rctx.ser = &me->newgame_redo;
  743. rctx.len = me->newgame_redo.len; /* copy for reentrancy safety */
  744. rctx.pos = 0;
  745. cctx.refused = false;
  746. deserialise_error = midend_deserialise_internal(
  747. me, midend_serialise_buf_read, &rctx,
  748. newgame_undo_deserialise_check, &cctx);
  749. if (cctx.refused) {
  750. /*
  751. * Our post-deserialisation check shows that we can't use
  752. * this saved game after all. (deserialise_error will
  753. * contain the dummy error message generated by our check
  754. * function, which we ignore.)
  755. */
  756. sfree(serbuf.buf);
  757. return false;
  758. } else {
  759. /*
  760. * There should never be any _other_ deserialisation
  761. * error, because this serialised data has been held in
  762. * our memory since it was created, and hasn't had any
  763. * opportunity to be corrupted on disk, accidentally
  764. * replaced by the wrong file, etc., by user error.
  765. */
  766. assert(!deserialise_error);
  767. /*
  768. * Clear the old newgame_redo serialisation, so that we
  769. * don't try to redo past the end of the game we've just
  770. * come into and end up at the back of it again.
  771. */
  772. me->newgame_redo.len = 0;
  773. /*
  774. * Copy the serialisation of the game we've just left into
  775. * the midend so that we can undo back into it later.
  776. */
  777. me->newgame_undo.len = 0;
  778. midend_serialise_buf_write(&me->newgame_undo,
  779. serbuf.buf, serbuf.len);
  780. sfree(serbuf.buf);
  781. return true;
  782. }
  783. } else
  784. return false;
  785. }
  786. static void midend_finish_move(midend *me)
  787. {
  788. float flashtime;
  789. /*
  790. * We do not flash if the later of the two states is special.
  791. * This covers both forward Solve moves and backward (undone)
  792. * Restart moves.
  793. */
  794. if ((me->oldstate || me->statepos > 1) &&
  795. ((me->dir > 0 && !special(me->states[me->statepos-1].movetype)) ||
  796. (me->dir < 0 && me->statepos < me->nstates &&
  797. !special(me->states[me->statepos].movetype)))) {
  798. flashtime = me->ourgame->flash_length(me->oldstate ? me->oldstate :
  799. me->states[me->statepos-2].state,
  800. me->states[me->statepos-1].state,
  801. me->oldstate ? me->dir : +1,
  802. me->ui);
  803. if (flashtime > 0) {
  804. me->flash_pos = 0.0F;
  805. me->flash_time = flashtime;
  806. }
  807. }
  808. if (me->oldstate)
  809. me->ourgame->free_game(me->oldstate);
  810. me->oldstate = NULL;
  811. me->anim_pos = me->anim_time = 0;
  812. me->dir = 0;
  813. midend_set_timer(me);
  814. }
  815. void midend_stop_anim(midend *me)
  816. {
  817. if (me->oldstate || me->anim_time != 0) {
  818. midend_finish_move(me);
  819. midend_redraw(me);
  820. }
  821. }
  822. void midend_restart_game(midend *me)
  823. {
  824. game_state *s;
  825. assert(me->statepos >= 1);
  826. if (me->statepos == 1)
  827. return; /* no point doing anything at all! */
  828. /*
  829. * During restart, we reconstruct the game from the (public)
  830. * game description rather than from states[0], because that
  831. * way Mines gets slightly more sensible behaviour (restart
  832. * goes to _after_ the first click so you don't have to
  833. * remember where you clicked).
  834. */
  835. s = me->ourgame->new_game(me, me->params, me->desc);
  836. /*
  837. * Now enter the restarted state as the next move.
  838. */
  839. midend_stop_anim(me);
  840. midend_purge_states(me);
  841. ensure(me);
  842. me->states[me->nstates].state = s;
  843. me->states[me->nstates].movestr = dupstr(me->desc);
  844. me->states[me->nstates].movetype = RESTART;
  845. me->statepos = ++me->nstates;
  846. if (me->ui)
  847. me->ourgame->changed_state(me->ui,
  848. me->states[me->statepos-2].state,
  849. me->states[me->statepos-1].state);
  850. me->flash_pos = me->flash_time = 0.0F;
  851. midend_finish_move(me);
  852. midend_redraw(me);
  853. midend_set_timer(me);
  854. }
  855. static int midend_really_process_key(midend *me, int x, int y, int button)
  856. {
  857. game_state *oldstate =
  858. me->ourgame->dup_game(me->states[me->statepos - 1].state);
  859. int type = MOVE;
  860. bool gottype = false;
  861. int ret = PKR_NO_EFFECT;
  862. float anim_time;
  863. game_state *s;
  864. char *movestr = NULL;
  865. if (!IS_UI_FAKE_KEY(button)) {
  866. movestr = me->ourgame->interpret_move(
  867. me->states[me->statepos-1].state,
  868. me->ui, me->drawstate, x, y, button);
  869. }
  870. if (movestr == NULL || movestr == MOVE_UNUSED) {
  871. if ((me->one_key_shortcuts && (button == 'n' || button == 'N')) ||
  872. button == '\x0E' || button == UI_NEWGAME) {
  873. midend_new_game(me);
  874. midend_redraw(me);
  875. ret = PKR_SOME_EFFECT;
  876. goto done; /* never animate */
  877. } else if ((me->one_key_shortcuts && (button=='u' || button=='U')) ||
  878. button == '*' || button == '\x1A' || button == '\x1F' ||
  879. button == UI_UNDO) {
  880. midend_stop_anim(me);
  881. type = me->states[me->statepos-1].movetype;
  882. gottype = true;
  883. if (!midend_undo(me))
  884. goto done;
  885. ret = PKR_SOME_EFFECT;
  886. } else if ((me->one_key_shortcuts && (button=='r' || button=='R')) ||
  887. button == '#' || button == '\x12' || button == '\x19' ||
  888. button == UI_REDO) {
  889. midend_stop_anim(me);
  890. if (!midend_redo(me))
  891. goto done;
  892. ret = PKR_SOME_EFFECT;
  893. } else if ((button == '\x13' || button == UI_SOLVE) &&
  894. me->ourgame->can_solve) {
  895. ret = PKR_SOME_EFFECT;
  896. if (midend_solve(me))
  897. goto done;
  898. } else if ((me->one_key_shortcuts && (button=='q' || button=='Q')) ||
  899. button == '\x11' || button == UI_QUIT) {
  900. ret = PKR_QUIT;
  901. goto done;
  902. } else {
  903. ret = PKR_UNUSED;
  904. goto done;
  905. }
  906. } else if (movestr == MOVE_NO_EFFECT) {
  907. ret = PKR_NO_EFFECT;
  908. goto done;
  909. } else {
  910. ret = PKR_SOME_EFFECT;
  911. if (movestr == MOVE_UI_UPDATE)
  912. s = me->states[me->statepos-1].state;
  913. else {
  914. assert_printable_ascii(movestr);
  915. s = me->ourgame->execute_move(me->states[me->statepos-1].state,
  916. movestr);
  917. assert(s != NULL);
  918. }
  919. if (s == me->states[me->statepos-1].state) {
  920. /*
  921. * make_move() is allowed to return its input state to
  922. * indicate that although no move has been made, the UI
  923. * state has been updated and a redraw is called for.
  924. */
  925. midend_redraw(me);
  926. midend_set_timer(me);
  927. goto done;
  928. } else if (s) {
  929. midend_stop_anim(me);
  930. midend_purge_states(me);
  931. ensure(me);
  932. assert(movestr != NULL);
  933. me->states[me->nstates].state = s;
  934. me->states[me->nstates].movestr = movestr;
  935. me->states[me->nstates].movetype = MOVE;
  936. me->statepos = ++me->nstates;
  937. me->dir = +1;
  938. if (me->ui)
  939. me->ourgame->changed_state(me->ui,
  940. me->states[me->statepos-2].state,
  941. me->states[me->statepos-1].state);
  942. } else {
  943. goto done;
  944. }
  945. }
  946. if (!gottype)
  947. type = me->states[me->statepos-1].movetype;
  948. /*
  949. * See if this move requires an animation.
  950. */
  951. if (special(type) && !(type == SOLVE &&
  952. (me->ourgame->flags & SOLVE_ANIMATES))) {
  953. anim_time = 0;
  954. } else {
  955. anim_time = me->ourgame->anim_length(oldstate,
  956. me->states[me->statepos-1].state,
  957. me->dir, me->ui);
  958. }
  959. me->oldstate = oldstate; oldstate = NULL;
  960. if (anim_time > 0) {
  961. me->anim_time = anim_time;
  962. } else {
  963. me->anim_time = 0.0;
  964. midend_finish_move(me);
  965. }
  966. me->anim_pos = 0.0;
  967. midend_redraw(me);
  968. midend_set_timer(me);
  969. done:
  970. if (oldstate) me->ourgame->free_game(oldstate);
  971. return ret;
  972. }
  973. int midend_process_key(midend *me, int x, int y, int button)
  974. {
  975. int ret = PKR_UNUSED, ret2;
  976. /*
  977. * Harmonise mouse drag and release messages.
  978. *
  979. * Some front ends might accidentally switch from sending, say,
  980. * RIGHT_DRAG messages to sending LEFT_DRAG, half way through a
  981. * drag. (This can happen on the Mac, for example, since
  982. * RIGHT_DRAG is usually done using Command+drag, and if the
  983. * user accidentally releases Command half way through the drag
  984. * then there will be trouble.)
  985. *
  986. * It would be an O(number of front ends) annoyance to fix this
  987. * in the front ends, but an O(number of back ends) annoyance
  988. * to have each game capable of dealing with it. Therefore, we
  989. * fix it _here_ in the common midend code so that it only has
  990. * to be done once.
  991. *
  992. * The possible ways in which things can go screwy in the front
  993. * end are:
  994. *
  995. * - in a system containing multiple physical buttons button
  996. * presses can inadvertently overlap. We can see ABab (caps
  997. * meaning button-down and lowercase meaning button-up) when
  998. * the user had semantically intended AaBb.
  999. *
  1000. * - in a system where one button is simulated by means of a
  1001. * modifier key and another button, buttons can mutate
  1002. * between press and release (possibly during drag). So we
  1003. * can see Ab instead of Aa.
  1004. *
  1005. * Definite requirements are:
  1006. *
  1007. * - button _presses_ must never be invented or destroyed. If
  1008. * the user presses two buttons in succession, the button
  1009. * presses must be transferred to the backend unchanged. So
  1010. * if we see AaBb , that's fine; if we see ABab (the button
  1011. * presses inadvertently overlapped) we must somehow
  1012. * `correct' it to AaBb.
  1013. *
  1014. * - every mouse action must end up looking like a press, zero
  1015. * or more drags, then a release. This allows back ends to
  1016. * make the _assumption_ that incoming mouse data will be
  1017. * sane in this regard, and not worry about the details.
  1018. *
  1019. * So my policy will be:
  1020. *
  1021. * - treat any button-up as a button-up for the currently
  1022. * pressed button, or ignore it if there is no currently
  1023. * pressed button.
  1024. *
  1025. * - treat any drag as a drag for the currently pressed
  1026. * button, or ignore it if there is no currently pressed
  1027. * button.
  1028. *
  1029. * - if we see a button-down while another button is currently
  1030. * pressed, invent a button-up for the first one and then
  1031. * pass the button-down through as before.
  1032. *
  1033. * 2005-05-31: An addendum to the above. Some games might want
  1034. * a `priority order' among buttons, such that if one button is
  1035. * pressed while another is down then a fixed one of the
  1036. * buttons takes priority no matter what order they're pressed
  1037. * in. Mines, in particular, wants to treat a left+right click
  1038. * like a left click for the benefit of users of other
  1039. * implementations. So the last of the above points is modified
  1040. * in the presence of an (optional) button priority order.
  1041. *
  1042. * A further addition: we translate certain keyboard presses to
  1043. * cursor key 'select' buttons, so that a) frontends don't have
  1044. * to translate these themselves (like they do for CURSOR_UP etc),
  1045. * and b) individual games don't have to hard-code button presses
  1046. * of '\n' etc for keyboard-based cursors. The choice of buttons
  1047. * here could eventually be controlled by a runtime configuration
  1048. * option.
  1049. *
  1050. * We also handle converting MOD_CTRL|'a' etc into '\x01' etc,
  1051. * specially recognising Ctrl+Shift+Z, and stripping modifier
  1052. * flags off keys that aren't meant to have them.
  1053. */
  1054. if (IS_MOUSE_DRAG(button) || IS_MOUSE_RELEASE(button)) {
  1055. if (me->pressed_mouse_button) {
  1056. if (IS_MOUSE_DRAG(button)) {
  1057. button = me->pressed_mouse_button +
  1058. (LEFT_DRAG - LEFT_BUTTON);
  1059. } else {
  1060. button = me->pressed_mouse_button +
  1061. (LEFT_RELEASE - LEFT_BUTTON);
  1062. }
  1063. } else
  1064. return ret; /* ignore it */
  1065. } else if (IS_MOUSE_DOWN(button) && me->pressed_mouse_button) {
  1066. /*
  1067. * If the new button has lower priority than the old one,
  1068. * don't bother doing this.
  1069. */
  1070. if (me->ourgame->flags &
  1071. BUTTON_BEATS(me->pressed_mouse_button, button))
  1072. return ret; /* just ignore it */
  1073. /*
  1074. * Fabricate a button-up for the previously pressed button.
  1075. */
  1076. ret2 = midend_really_process_key
  1077. (me, x, y, (me->pressed_mouse_button +
  1078. (LEFT_RELEASE - LEFT_BUTTON)));
  1079. ret = min(ret, ret2);
  1080. }
  1081. /* Canonicalise CTRL+ASCII. */
  1082. if ((button & MOD_CTRL) &&
  1083. (button & ~MOD_MASK) >= 0x40 && (button & ~MOD_MASK) < 0x80)
  1084. button = button & (0x1f | (MOD_MASK & ~MOD_CTRL));
  1085. /* Special handling to make CTRL+SHFT+Z into REDO. */
  1086. if ((button & (~MOD_MASK | MOD_SHFT)) == (MOD_SHFT | '\x1A'))
  1087. button = UI_REDO;
  1088. /* interpret_move() expects CTRL and SHFT only on cursor keys. */
  1089. if (!IS_CURSOR_MOVE(button & ~MOD_MASK)) {
  1090. /* reject CTRL+anything odd */
  1091. if ((button & MOD_CTRL) && (button & ~MOD_MASK) >= 0x20)
  1092. return PKR_UNUSED;
  1093. /* otherwise strip them */
  1094. button &= ~(MOD_CTRL | MOD_SHFT);
  1095. }
  1096. /* interpret_move() expects NUM_KEYPAD only on numbers. */
  1097. if ((button & ~MOD_MASK) < '0' || (button & ~MOD_MASK) > '9')
  1098. button &= ~MOD_NUM_KEYPAD;
  1099. /*
  1100. * Translate keyboard presses to cursor selection.
  1101. */
  1102. if (button == '\n' || button == '\r')
  1103. button = CURSOR_SELECT;
  1104. if (button == ' ')
  1105. button = CURSOR_SELECT2;
  1106. /*
  1107. * Normalise both backspace characters (8 and 127) to \b. Easier
  1108. * to do this once, here, than to require all front ends to
  1109. * carefully generate the same one - now each front end can
  1110. * generate whichever is easiest.
  1111. */
  1112. if (button == '\177')
  1113. button = '\b';
  1114. /*
  1115. * Now send on the event we originally received.
  1116. */
  1117. ret2 = midend_really_process_key(me, x, y, button);
  1118. ret = min(ret, ret2);
  1119. /*
  1120. * And update the currently pressed button.
  1121. */
  1122. if (IS_MOUSE_RELEASE(button))
  1123. me->pressed_mouse_button = 0;
  1124. else if (IS_MOUSE_DOWN(button))
  1125. me->pressed_mouse_button = button;
  1126. return ret;
  1127. }
  1128. key_label *midend_request_keys(midend *me, int *n)
  1129. {
  1130. key_label *keys = NULL;
  1131. int nkeys = 0, i;
  1132. if(me->ourgame->request_keys)
  1133. {
  1134. keys = me->ourgame->request_keys(midend_get_params(me), &nkeys);
  1135. for(i = 0; i < nkeys; ++i)
  1136. {
  1137. if(!keys[i].label)
  1138. keys[i].label = button2label(keys[i].button);
  1139. }
  1140. }
  1141. if(n)
  1142. *n = nkeys;
  1143. return keys;
  1144. }
  1145. /* Return a good label to show next to a key right now. */
  1146. const char *midend_current_key_label(midend *me, int button)
  1147. {
  1148. assert(IS_CURSOR_SELECT(button));
  1149. if (!me->ourgame->current_key_label) return "";
  1150. return me->ourgame->current_key_label(
  1151. me->ui, me->states[me->statepos-1].state, button);
  1152. }
  1153. void midend_redraw(midend *me)
  1154. {
  1155. assert(me->drawing);
  1156. if (me->statepos > 0 && me->drawstate) {
  1157. bool first_draw = me->first_draw;
  1158. me->first_draw = false;
  1159. start_draw(me->drawing);
  1160. if (first_draw) {
  1161. /*
  1162. * The initial contents of the window are not guaranteed
  1163. * by the front end. But we also don't want to require
  1164. * every single game to go to the effort of clearing the
  1165. * window on setup. So we centralise here the operation of
  1166. * covering the whole window with colour 0 (assumed to be
  1167. * the puzzle's background colour) the first time we do a
  1168. * redraw operation with a new drawstate.
  1169. */
  1170. draw_rect(me->drawing, 0, 0, me->winwidth, me->winheight, 0);
  1171. }
  1172. if (me->oldstate && me->anim_time > 0 &&
  1173. me->anim_pos < me->anim_time) {
  1174. assert(me->dir != 0);
  1175. me->ourgame->redraw(me->drawing, me->drawstate, me->oldstate,
  1176. me->states[me->statepos-1].state, me->dir,
  1177. me->ui, me->anim_pos, me->flash_pos);
  1178. } else {
  1179. me->ourgame->redraw(me->drawing, me->drawstate, NULL,
  1180. me->states[me->statepos-1].state, +1 /*shrug*/,
  1181. me->ui, 0.0, me->flash_pos);
  1182. }
  1183. if (first_draw) {
  1184. /*
  1185. * Call a big draw_update on the whole window, in case the
  1186. * game backend didn't.
  1187. */
  1188. draw_update(me->drawing, 0, 0, me->winwidth, me->winheight);
  1189. }
  1190. end_draw(me->drawing);
  1191. }
  1192. }
  1193. /*
  1194. * Nasty hacky function used to implement the --redo option in
  1195. * gtk.c. Only used for generating the puzzles' icons.
  1196. */
  1197. void midend_freeze_timer(midend *me, float tprop)
  1198. {
  1199. me->anim_pos = me->anim_time * tprop;
  1200. midend_redraw(me);
  1201. deactivate_timer(me->frontend);
  1202. }
  1203. void midend_timer(midend *me, float tplus)
  1204. {
  1205. bool need_redraw = (me->anim_time > 0 || me->flash_time > 0);
  1206. me->anim_pos += tplus;
  1207. if (me->anim_pos >= me->anim_time ||
  1208. me->anim_time == 0 || !me->oldstate) {
  1209. if (me->anim_time > 0)
  1210. midend_finish_move(me);
  1211. }
  1212. me->flash_pos += tplus;
  1213. if (me->flash_pos >= me->flash_time || me->flash_time == 0) {
  1214. me->flash_pos = me->flash_time = 0;
  1215. }
  1216. if (need_redraw)
  1217. midend_redraw(me);
  1218. if (me->timing) {
  1219. float oldelapsed = me->elapsed;
  1220. me->elapsed += tplus;
  1221. if ((int)oldelapsed != (int)me->elapsed)
  1222. status_bar(me->drawing, me->laststatus ? me->laststatus : "");
  1223. }
  1224. midend_set_timer(me);
  1225. }
  1226. float *midend_colours(midend *me, int *ncolours)
  1227. {
  1228. float *ret;
  1229. ret = me->ourgame->colours(me->frontend, ncolours);
  1230. assert(*ncolours >= 1);
  1231. {
  1232. int i;
  1233. /*
  1234. * Allow environment-based overrides for the standard
  1235. * colours by defining variables along the lines of
  1236. * `NET_COLOUR_4=6000c0'.
  1237. */
  1238. for (i = 0; i < *ncolours; i++) {
  1239. char buf[80], *e;
  1240. unsigned int r, g, b;
  1241. int j, k;
  1242. sprintf(buf, "%s_COLOUR_%d", me->ourgame->name, i);
  1243. for (j = k = 0; buf[j]; j++)
  1244. if (!isspace((unsigned char)buf[j]))
  1245. buf[k++] = toupper((unsigned char)buf[j]);
  1246. buf[k] = '\0';
  1247. if ((e = getenv(buf)) != NULL &&
  1248. sscanf(e, "%2x%2x%2x", &r, &g, &b) == 3) {
  1249. ret[i*3 + 0] = r / 255.0F;
  1250. ret[i*3 + 1] = g / 255.0F;
  1251. ret[i*3 + 2] = b / 255.0F;
  1252. }
  1253. assert(0.0F <= ret[i*3 + 0] && ret[i*3 + 0] <= 1.0F);
  1254. assert(0.0F <= ret[i*3 + 1] && ret[i*3 + 1] <= 1.0F);
  1255. assert(0.0F <= ret[i*3 + 2] && ret[i*3 + 2] <= 1.0F);
  1256. }
  1257. }
  1258. return ret;
  1259. }
  1260. struct preset_menu *preset_menu_new(void)
  1261. {
  1262. struct preset_menu *menu = snew(struct preset_menu);
  1263. menu->n_entries = 0;
  1264. menu->entries_size = 0;
  1265. menu->entries = NULL;
  1266. return menu;
  1267. }
  1268. static struct preset_menu_entry *preset_menu_add(struct preset_menu *menu,
  1269. char *title)
  1270. {
  1271. struct preset_menu_entry *toret;
  1272. if (menu->n_entries >= menu->entries_size) {
  1273. menu->entries_size = menu->n_entries * 5 / 4 + 10;
  1274. menu->entries = sresize(menu->entries, menu->entries_size,
  1275. struct preset_menu_entry);
  1276. }
  1277. toret = &menu->entries[menu->n_entries++];
  1278. toret->title = title;
  1279. toret->params = NULL;
  1280. toret->submenu = NULL;
  1281. return toret;
  1282. }
  1283. struct preset_menu *preset_menu_add_submenu(struct preset_menu *parent,
  1284. char *title)
  1285. {
  1286. struct preset_menu_entry *entry = preset_menu_add(parent, title);
  1287. entry->submenu = preset_menu_new();
  1288. return entry->submenu;
  1289. }
  1290. void preset_menu_add_preset(struct preset_menu *parent,
  1291. char *title, game_params *params)
  1292. {
  1293. struct preset_menu_entry *entry = preset_menu_add(parent, title);
  1294. entry->params = params;
  1295. }
  1296. game_params *preset_menu_lookup_by_id(struct preset_menu *menu, int id)
  1297. {
  1298. int i;
  1299. game_params *retd;
  1300. for (i = 0; i < menu->n_entries; i++) {
  1301. if (id == menu->entries[i].id)
  1302. return menu->entries[i].params;
  1303. if (menu->entries[i].submenu &&
  1304. (retd = preset_menu_lookup_by_id(
  1305. menu->entries[i].submenu, id)) != NULL)
  1306. return retd;
  1307. }
  1308. return NULL;
  1309. }
  1310. static char *preset_menu_add_from_user_env(
  1311. midend *me, struct preset_menu *menu, char *p, bool top_level)
  1312. {
  1313. while (*p) {
  1314. char *name, *val;
  1315. game_params *preset;
  1316. name = p;
  1317. while (*p && *p != ':') p++;
  1318. if (*p) *p++ = '\0';
  1319. val = p;
  1320. while (*p && *p != ':') p++;
  1321. if (*p) *p++ = '\0';
  1322. if (!strcmp(val, "#")) {
  1323. /*
  1324. * Special case: either open a new submenu with the given
  1325. * title, or terminate the current submenu.
  1326. */
  1327. if (*name) {
  1328. struct preset_menu *submenu =
  1329. preset_menu_add_submenu(menu, dupstr(name));
  1330. p = preset_menu_add_from_user_env(me, submenu, p, false);
  1331. } else {
  1332. /*
  1333. * If we get a 'close submenu' indication at the top
  1334. * level, there's not much we can do but quietly
  1335. * ignore it.
  1336. */
  1337. if (!top_level)
  1338. return p;
  1339. }
  1340. continue;
  1341. }
  1342. preset = me->ourgame->default_params();
  1343. me->ourgame->decode_params(preset, val);
  1344. if (me->ourgame->validate_params(preset, true)) {
  1345. /* Drop this one from the list. */
  1346. me->ourgame->free_params(preset);
  1347. continue;
  1348. }
  1349. preset_menu_add_preset(menu, dupstr(name), preset);
  1350. }
  1351. return p;
  1352. }
  1353. static void preset_menu_alloc_ids(midend *me, struct preset_menu *menu)
  1354. {
  1355. int i;
  1356. for (i = 0; i < menu->n_entries; i++)
  1357. menu->entries[i].id = me->n_encoded_presets++;
  1358. for (i = 0; i < menu->n_entries; i++)
  1359. if (menu->entries[i].submenu)
  1360. preset_menu_alloc_ids(me, menu->entries[i].submenu);
  1361. }
  1362. static void preset_menu_encode_params(midend *me, struct preset_menu *menu)
  1363. {
  1364. int i;
  1365. for (i = 0; i < menu->n_entries; i++) {
  1366. if (menu->entries[i].params) {
  1367. me->encoded_presets[menu->entries[i].id] =
  1368. encode_params(me, menu->entries[i].params, true);
  1369. } else {
  1370. preset_menu_encode_params(me, menu->entries[i].submenu);
  1371. }
  1372. }
  1373. }
  1374. struct preset_menu *midend_get_presets(midend *me, int *id_limit)
  1375. {
  1376. int i;
  1377. if (me->preset_menu)
  1378. return me->preset_menu;
  1379. #if 0
  1380. /* Expect the game to implement exactly one of the two preset APIs */
  1381. assert(me->ourgame->fetch_preset || me->ourgame->preset_menu);
  1382. assert(!(me->ourgame->fetch_preset && me->ourgame->preset_menu));
  1383. #endif
  1384. if (me->ourgame->fetch_preset) {
  1385. char *name;
  1386. game_params *preset;
  1387. /* Simple one-level menu */
  1388. assert(!me->ourgame->preset_menu);
  1389. me->preset_menu = preset_menu_new();
  1390. for (i = 0; me->ourgame->fetch_preset(i, &name, &preset); i++)
  1391. preset_menu_add_preset(me->preset_menu, name, preset);
  1392. } else {
  1393. /* Hierarchical menu provided by the game backend */
  1394. me->preset_menu = me->ourgame->preset_menu();
  1395. }
  1396. {
  1397. /*
  1398. * Allow user extensions to the preset list by defining an
  1399. * environment variable <gamename>_PRESETS whose value is a
  1400. * colon-separated list of items, alternating between textual
  1401. * titles in the menu and encoded parameter strings. For
  1402. * example, "SOLO_PRESETS=2x3 Advanced:2x3da" would define
  1403. * just one additional preset for Solo.
  1404. */
  1405. char buf[80], *e;
  1406. int j, k;
  1407. sprintf(buf, "%s_PRESETS", me->ourgame->name);
  1408. for (j = k = 0; buf[j]; j++)
  1409. if (!isspace((unsigned char)buf[j]))
  1410. buf[k++] = toupper((unsigned char)buf[j]);
  1411. buf[k] = '\0';
  1412. if ((e = getenv(buf)) != NULL) {
  1413. e = dupstr(e);
  1414. preset_menu_add_from_user_env(me, me->preset_menu, e, true);
  1415. sfree(e);
  1416. }
  1417. }
  1418. /*
  1419. * Finalise the menu: allocate an integer id to each entry, and
  1420. * store string encodings of the presets' parameters in
  1421. * me->encoded_presets.
  1422. */
  1423. me->n_encoded_presets = 0;
  1424. preset_menu_alloc_ids(me, me->preset_menu);
  1425. me->encoded_presets = snewn(me->n_encoded_presets, char *);
  1426. for (i = 0; i < me->n_encoded_presets; i++)
  1427. me->encoded_presets[i] = NULL;
  1428. preset_menu_encode_params(me, me->preset_menu);
  1429. if (id_limit)
  1430. *id_limit = me->n_encoded_presets;
  1431. return me->preset_menu;
  1432. }
  1433. int midend_which_preset(midend *me)
  1434. {
  1435. char *encoding = encode_params(me, me->params, true);
  1436. int i, ret;
  1437. ret = -1;
  1438. for (i = 0; i < me->n_encoded_presets; i++)
  1439. if (me->encoded_presets[i] &&
  1440. !strcmp(encoding, me->encoded_presets[i])) {
  1441. ret = i;
  1442. break;
  1443. }
  1444. sfree(encoding);
  1445. return ret;
  1446. }
  1447. bool midend_wants_statusbar(midend *me)
  1448. {
  1449. return me->ourgame->wants_statusbar;
  1450. }
  1451. void midend_request_id_changes(midend *me, void (*notify)(void *), void *ctx)
  1452. {
  1453. me->game_id_change_notify_function = notify;
  1454. me->game_id_change_notify_ctx = ctx;
  1455. }
  1456. bool midend_get_cursor_location(midend *me,
  1457. int *x_out, int *y_out,
  1458. int *w_out, int *h_out)
  1459. {
  1460. int x, y, w, h;
  1461. x = y = -1;
  1462. w = h = 1;
  1463. if(me->ourgame->get_cursor_location)
  1464. me->ourgame->get_cursor_location(me->ui,
  1465. me->drawstate,
  1466. me->states[me->statepos-1].state,
  1467. me->params,
  1468. &x, &y, &w, &h);
  1469. if(x == -1 && y == -1)
  1470. return false;
  1471. if(x_out)
  1472. *x_out = x;
  1473. if(y_out)
  1474. *y_out = y;
  1475. if(w_out)
  1476. *w_out = w;
  1477. if(h_out)
  1478. *h_out = h;
  1479. return true;
  1480. }
  1481. void midend_supersede_game_desc(midend *me, const char *desc,
  1482. const char *privdesc)
  1483. {
  1484. /* Assert that the descriptions consists only of printable ASCII. */
  1485. assert_printable_ascii(desc);
  1486. if (privdesc)
  1487. assert_printable_ascii(privdesc);
  1488. sfree(me->desc);
  1489. sfree(me->privdesc);
  1490. me->desc = dupstr(desc);
  1491. me->privdesc = privdesc ? dupstr(privdesc) : NULL;
  1492. if (me->game_id_change_notify_function)
  1493. me->game_id_change_notify_function(me->game_id_change_notify_ctx);
  1494. }
  1495. config_item *midend_get_config(midend *me, int which, char **wintitle)
  1496. {
  1497. char *titlebuf, *parstr;
  1498. const char *rest;
  1499. config_item *ret;
  1500. char sep;
  1501. assert(wintitle);
  1502. titlebuf = snewn(40 + strlen(me->ourgame->name), char);
  1503. switch (which) {
  1504. case CFG_SETTINGS:
  1505. sprintf(titlebuf, "%s configuration", me->ourgame->name);
  1506. *wintitle = titlebuf;
  1507. return me->ourgame->configure(me->params);
  1508. case CFG_SEED:
  1509. case CFG_DESC:
  1510. if (!me->curparams) {
  1511. sfree(titlebuf);
  1512. return NULL;
  1513. }
  1514. sprintf(titlebuf, "%s %s selection", me->ourgame->name,
  1515. which == CFG_SEED ? "random" : "game");
  1516. *wintitle = titlebuf;
  1517. ret = snewn(2, config_item);
  1518. ret[0].type = C_STRING;
  1519. if (which == CFG_SEED)
  1520. ret[0].name = "Game random seed";
  1521. else
  1522. ret[0].name = "Game ID";
  1523. /*
  1524. * For CFG_DESC the text going in here will be a string
  1525. * encoding of the restricted parameters, plus a colon,
  1526. * plus the game description. For CFG_SEED it will be the
  1527. * full parameters, plus a hash, plus the random seed data.
  1528. * Either of these is a valid full game ID (although only
  1529. * the former is likely to persist across many code
  1530. * changes).
  1531. */
  1532. parstr = encode_params(me, me->curparams, which == CFG_SEED);
  1533. assert(parstr);
  1534. if (which == CFG_DESC) {
  1535. rest = me->desc ? me->desc : "";
  1536. sep = ':';
  1537. } else {
  1538. rest = me->seedstr ? me->seedstr : "";
  1539. sep = '#';
  1540. }
  1541. ret[0].u.string.sval = snewn(strlen(parstr) + strlen(rest) + 2, char);
  1542. sprintf(ret[0].u.string.sval, "%s%c%s", parstr, sep, rest);
  1543. sfree(parstr);
  1544. ret[1].type = C_END;
  1545. ret[1].name = NULL;
  1546. return ret;
  1547. case CFG_PREFS:
  1548. sprintf(titlebuf, "%s preferences", me->ourgame->name);
  1549. *wintitle = titlebuf;
  1550. return midend_get_prefs(me, NULL);
  1551. }
  1552. assert(!"We shouldn't be here");
  1553. return NULL;
  1554. }
  1555. static const char *midend_game_id_int(midend *me, const char *id, int defmode)
  1556. {
  1557. const char *error;
  1558. char *par = NULL;
  1559. const char *desc, *seed;
  1560. game_params *newcurparams, *newparams, *oldparams1, *oldparams2;
  1561. bool free_params;
  1562. seed = strchr(id, '#');
  1563. desc = strchr(id, ':');
  1564. if (desc && (!seed || desc < seed)) {
  1565. /*
  1566. * We have a colon separating parameters from game
  1567. * description. So `par' now points to the parameters
  1568. * string, and `desc' to the description string.
  1569. */
  1570. par = snewn(desc-id + 1, char);
  1571. strncpy(par, id, desc-id);
  1572. par[desc-id] = '\0';
  1573. desc++;
  1574. seed = NULL;
  1575. } else if (seed && (!desc || seed < desc)) {
  1576. /*
  1577. * We have a hash separating parameters from random seed.
  1578. * So `par' now points to the parameters string, and `seed'
  1579. * to the seed string.
  1580. */
  1581. par = snewn(seed-id + 1, char);
  1582. strncpy(par, id, seed-id);
  1583. par[seed-id] = '\0';
  1584. seed++;
  1585. desc = NULL;
  1586. } else {
  1587. /*
  1588. * We only have one string. Depending on `defmode', we take
  1589. * it to be either parameters, seed or description.
  1590. */
  1591. if (defmode == DEF_SEED) {
  1592. seed = id;
  1593. par = NULL;
  1594. desc = NULL;
  1595. } else if (defmode == DEF_DESC) {
  1596. desc = id;
  1597. par = NULL;
  1598. seed = NULL;
  1599. } else {
  1600. par = dupstr(id);
  1601. seed = desc = NULL;
  1602. }
  1603. }
  1604. /*
  1605. * We must be reasonably careful here not to modify anything in
  1606. * `me' until we have finished validating things. This function
  1607. * must either return an error and do nothing to the midend, or
  1608. * return success and do everything; nothing in between is
  1609. * acceptable.
  1610. */
  1611. newcurparams = newparams = oldparams1 = oldparams2 = NULL;
  1612. if (par) {
  1613. /*
  1614. * The params string may underspecify the game parameters, so
  1615. * we must first initialise newcurparams with a full set of
  1616. * params from somewhere else before we decode_params the
  1617. * input string over the top.
  1618. *
  1619. * But which set? It depends on what other data we have.
  1620. *
  1621. * If we've been given a _descriptive_ game id, then that may
  1622. * well underspecify by design, e.g. Solo game descriptions
  1623. * often start just '3x3:' without specifying one of Solo's
  1624. * difficulty settings, because it isn't necessary once a game
  1625. * has been generated (and you might not even know it, if
  1626. * you're manually transcribing a game description). In that
  1627. * situation, I've always felt that the best thing to set the
  1628. * difficulty to (for use if the user hits 'New Game' after
  1629. * pasting in that game id) is whatever it was previously set
  1630. * to. That is, we use whatever is already in me->params as
  1631. * the basis for our decoding of this input string.
  1632. *
  1633. * A random-seed based game id, however, should use the real,
  1634. * built-in default params, and not even check the
  1635. * <game>_DEFAULT environment setting, because when people
  1636. * paste each other random seeds - whether it's two users
  1637. * arranging to generate the same game at the same time to
  1638. * race solving them, or a user sending a bug report upstream
  1639. * - the whole point is for the random game id to always be
  1640. * interpreted the same way, even if it does underspecify.
  1641. *
  1642. * A parameter string typed in on its own, with no seed _or_
  1643. * description, gets treated the same way as a random seed,
  1644. * because again I think the most likely reason for doing that
  1645. * is to have a portable representation of a set of params.
  1646. */
  1647. if (desc) {
  1648. newcurparams = me->ourgame->dup_params(me->params);
  1649. } else {
  1650. newcurparams = me->ourgame->default_params();
  1651. }
  1652. me->ourgame->decode_params(newcurparams, par);
  1653. sfree(par);
  1654. error = me->ourgame->validate_params(newcurparams, desc == NULL);
  1655. if (error) {
  1656. me->ourgame->free_params(newcurparams);
  1657. return error;
  1658. }
  1659. oldparams1 = me->curparams;
  1660. /*
  1661. * Now filter only the persistent parts of this state into
  1662. * the long-term params structure, unless we've _only_
  1663. * received a params string in which case the whole lot is
  1664. * persistent.
  1665. */
  1666. oldparams2 = me->params;
  1667. if (seed || desc) {
  1668. char *tmpstr;
  1669. newparams = me->ourgame->dup_params(me->params);
  1670. tmpstr = encode_params(me, newcurparams, false);
  1671. me->ourgame->decode_params(newparams, tmpstr);
  1672. sfree(tmpstr);
  1673. } else {
  1674. newparams = me->ourgame->dup_params(newcurparams);
  1675. }
  1676. free_params = true;
  1677. } else {
  1678. newcurparams = me->curparams;
  1679. newparams = me->params;
  1680. free_params = false;
  1681. }
  1682. if (desc) {
  1683. error = me->ourgame->validate_desc(newparams, desc);
  1684. if (error) {
  1685. if (free_params) {
  1686. if (newcurparams)
  1687. me->ourgame->free_params(newcurparams);
  1688. if (newparams)
  1689. me->ourgame->free_params(newparams);
  1690. }
  1691. return error;
  1692. }
  1693. }
  1694. /*
  1695. * Now we've got past all possible error points. Update the
  1696. * midend itself.
  1697. */
  1698. me->params = newparams;
  1699. me->curparams = newcurparams;
  1700. if (oldparams1)
  1701. me->ourgame->free_params(oldparams1);
  1702. if (oldparams2)
  1703. me->ourgame->free_params(oldparams2);
  1704. sfree(me->desc);
  1705. sfree(me->privdesc);
  1706. me->desc = me->privdesc = NULL;
  1707. sfree(me->seedstr);
  1708. me->seedstr = NULL;
  1709. if (desc) {
  1710. me->desc = dupstr(desc);
  1711. me->genmode = GOT_DESC;
  1712. sfree(me->aux_info);
  1713. me->aux_info = NULL;
  1714. }
  1715. if (seed) {
  1716. me->seedstr = dupstr(seed);
  1717. me->genmode = GOT_SEED;
  1718. }
  1719. me->newgame_can_store_undo = false;
  1720. return NULL;
  1721. }
  1722. const char *midend_game_id(midend *me, const char *id)
  1723. {
  1724. return midend_game_id_int(me, id, DEF_PARAMS);
  1725. }
  1726. char *midend_get_game_id(midend *me)
  1727. {
  1728. char *parstr, *ret;
  1729. parstr = encode_params(me, me->curparams, false);
  1730. assert(parstr);
  1731. assert(me->desc);
  1732. ret = snewn(strlen(parstr) + strlen(me->desc) + 2, char);
  1733. sprintf(ret, "%s:%s", parstr, me->desc);
  1734. sfree(parstr);
  1735. return ret;
  1736. }
  1737. char *midend_get_random_seed(midend *me)
  1738. {
  1739. char *parstr, *ret;
  1740. if (!me->seedstr)
  1741. return NULL;
  1742. parstr = encode_params(me, me->curparams, true);
  1743. assert(parstr);
  1744. ret = snewn(strlen(parstr) + strlen(me->seedstr) + 2, char);
  1745. sprintf(ret, "%s#%s", parstr, me->seedstr);
  1746. sfree(parstr);
  1747. return ret;
  1748. }
  1749. const char *midend_set_config(midend *me, int which, config_item *cfg)
  1750. {
  1751. const char *error;
  1752. game_params *params;
  1753. switch (which) {
  1754. case CFG_SETTINGS:
  1755. params = me->ourgame->custom_params(cfg);
  1756. error = me->ourgame->validate_params(params, true);
  1757. if (error) {
  1758. me->ourgame->free_params(params);
  1759. return error;
  1760. }
  1761. me->ourgame->free_params(me->params);
  1762. me->params = params;
  1763. break;
  1764. case CFG_SEED:
  1765. case CFG_DESC:
  1766. error = midend_game_id_int(me, cfg[0].u.string.sval,
  1767. (which == CFG_SEED ? DEF_SEED : DEF_DESC));
  1768. if (error)
  1769. return error;
  1770. break;
  1771. case CFG_PREFS:
  1772. midend_set_prefs(me, me->ui, cfg);
  1773. break;
  1774. }
  1775. return NULL;
  1776. }
  1777. bool midend_can_format_as_text_now(midend *me)
  1778. {
  1779. if (me->ourgame->can_format_as_text_ever)
  1780. return me->ourgame->can_format_as_text_now(me->params);
  1781. else
  1782. return false;
  1783. }
  1784. char *midend_text_format(midend *me)
  1785. {
  1786. if (me->ourgame->can_format_as_text_ever && me->statepos > 0 &&
  1787. me->ourgame->can_format_as_text_now(me->params))
  1788. return me->ourgame->text_format(me->states[me->statepos-1].state);
  1789. else
  1790. return NULL;
  1791. }
  1792. const char *midend_solve(midend *me)
  1793. {
  1794. game_state *s;
  1795. const char *msg;
  1796. char *movestr;
  1797. if (!me->ourgame->can_solve)
  1798. return "This game does not support the Solve operation";
  1799. if (me->statepos < 1)
  1800. return "No game set up to solve"; /* _shouldn't_ happen! */
  1801. msg = NULL;
  1802. movestr = me->ourgame->solve(me->states[0].state,
  1803. me->states[me->statepos-1].state,
  1804. me->aux_info, &msg);
  1805. assert(movestr != MOVE_UI_UPDATE);
  1806. if (!movestr) {
  1807. if (!msg)
  1808. msg = "Solve operation failed"; /* _shouldn't_ happen, but can */
  1809. return msg;
  1810. }
  1811. assert_printable_ascii(movestr);
  1812. s = me->ourgame->execute_move(me->states[me->statepos-1].state, movestr);
  1813. assert(s);
  1814. /*
  1815. * Now enter the solved state as the next move.
  1816. */
  1817. midend_stop_anim(me);
  1818. midend_purge_states(me);
  1819. ensure(me);
  1820. me->states[me->nstates].state = s;
  1821. me->states[me->nstates].movestr = movestr;
  1822. me->states[me->nstates].movetype = SOLVE;
  1823. me->statepos = ++me->nstates;
  1824. if (me->ui)
  1825. me->ourgame->changed_state(me->ui,
  1826. me->states[me->statepos-2].state,
  1827. me->states[me->statepos-1].state);
  1828. me->dir = +1;
  1829. if (me->ourgame->flags & SOLVE_ANIMATES) {
  1830. me->oldstate = me->ourgame->dup_game(me->states[me->statepos-2].state);
  1831. me->anim_time =
  1832. me->ourgame->anim_length(me->states[me->statepos-2].state,
  1833. me->states[me->statepos-1].state,
  1834. +1, me->ui);
  1835. me->anim_pos = 0.0;
  1836. } else {
  1837. me->anim_time = 0.0;
  1838. midend_finish_move(me);
  1839. }
  1840. if (me->drawing)
  1841. midend_redraw(me);
  1842. midend_set_timer(me);
  1843. return NULL;
  1844. }
  1845. int midend_status(midend *me)
  1846. {
  1847. /*
  1848. * We should probably never be called when the state stack has no
  1849. * states on it at all - ideally, midends should never be left in
  1850. * that state for long enough to get put down and forgotten about.
  1851. * But if we are, I think we return _true_ - pedantically speaking
  1852. * a midend in that state is 'vacuously solved', and more
  1853. * practically, a user whose midend has been left in that state
  1854. * probably _does_ want the 'new game' option to be prominent.
  1855. */
  1856. if (me->statepos == 0)
  1857. return +1;
  1858. return me->ourgame->status(me->states[me->statepos-1].state);
  1859. }
  1860. char *midend_rewrite_statusbar(midend *me, const char *text)
  1861. {
  1862. /*
  1863. * An important special case is that we are occasionally called
  1864. * with our own laststatus, to update the timer.
  1865. */
  1866. if (me->laststatus != text) {
  1867. sfree(me->laststatus);
  1868. me->laststatus = dupstr(text);
  1869. }
  1870. if (me->ourgame->is_timed) {
  1871. char timebuf[100], *ret;
  1872. int min, sec;
  1873. sec = (int)me->elapsed;
  1874. min = sec / 60;
  1875. sec %= 60;
  1876. sprintf(timebuf, "[%d:%02d] ", min, sec);
  1877. ret = snewn(strlen(timebuf) + strlen(text) + 1, char);
  1878. strcpy(ret, timebuf);
  1879. strcat(ret, text);
  1880. return ret;
  1881. } else {
  1882. return dupstr(text);
  1883. }
  1884. }
  1885. #define SERIALISE_MAGIC "Simon Tatham's Portable Puzzle Collection"
  1886. #define SERIALISE_VERSION "1"
  1887. void midend_serialise(midend *me,
  1888. void (*write)(void *ctx, const void *buf, int len),
  1889. void *wctx)
  1890. {
  1891. int i;
  1892. /*
  1893. * Each line of the save file contains three components. First
  1894. * exactly 8 characters of header word indicating what type of
  1895. * data is contained on the line; then a colon followed by a
  1896. * decimal integer giving the length of the main string on the
  1897. * line; then a colon followed by the string itself (exactly as
  1898. * many bytes as previously specified, no matter what they
  1899. * contain). Then a newline (of reasonably flexible form).
  1900. */
  1901. #define wr(h,s) do { \
  1902. char hbuf[80]; \
  1903. const char *str = (s); \
  1904. char lbuf[9]; \
  1905. copy_left_justified(lbuf, sizeof(lbuf), h); \
  1906. sprintf(hbuf, "%s:%d:", lbuf, (int)strlen(str)); \
  1907. assert_printable_ascii(hbuf); \
  1908. write(wctx, hbuf, strlen(hbuf)); \
  1909. assert_printable_ascii(str); \
  1910. write(wctx, str, strlen(str)); \
  1911. write(wctx, "\n", 1); \
  1912. } while (0)
  1913. /*
  1914. * Magic string identifying the file, and version number of the
  1915. * file format.
  1916. */
  1917. wr("SAVEFILE", SERIALISE_MAGIC);
  1918. wr("VERSION", SERIALISE_VERSION);
  1919. /*
  1920. * The game name. (Copied locally to avoid const annoyance.)
  1921. */
  1922. {
  1923. char *s = dupstr(me->ourgame->name);
  1924. wr("GAME", s);
  1925. sfree(s);
  1926. }
  1927. /*
  1928. * The current long-term parameters structure, in full.
  1929. */
  1930. if (me->params) {
  1931. char *s = encode_params(me, me->params, true);
  1932. wr("PARAMS", s);
  1933. sfree(s);
  1934. }
  1935. /*
  1936. * The current short-term parameters structure, in full.
  1937. */
  1938. if (me->curparams) {
  1939. char *s = encode_params(me, me->curparams, true);
  1940. wr("CPARAMS", s);
  1941. sfree(s);
  1942. }
  1943. /*
  1944. * The current game description, the privdesc, and the random seed.
  1945. */
  1946. if (me->seedstr) {
  1947. /*
  1948. * Random seeds are not necessarily printable ASCII.
  1949. * Hex-encode the seed if necessary. Printable ASCII seeds
  1950. * are emitted unencoded for compatibility with older
  1951. * versions.
  1952. */
  1953. int i;
  1954. for (i = 0; me->seedstr[i]; i++)
  1955. if (me->seedstr[i] < 32 || me->seedstr[i] >= 127)
  1956. break;
  1957. if (me->seedstr[i]) {
  1958. char *hexseed = bin2hex((unsigned char *)me->seedstr,
  1959. strlen(me->seedstr));
  1960. wr("HEXSEED", hexseed);
  1961. sfree(hexseed);
  1962. } else
  1963. wr("SEED", me->seedstr);
  1964. }
  1965. if (me->desc)
  1966. wr("DESC", me->desc);
  1967. if (me->privdesc)
  1968. wr("PRIVDESC", me->privdesc);
  1969. /*
  1970. * The game's aux_info. We obfuscate this to prevent spoilers
  1971. * (people are likely to run `head' or similar on a saved game
  1972. * file simply to find out what it is, and don't necessarily
  1973. * want to be told the answer to the puzzle!)
  1974. */
  1975. if (me->aux_info) {
  1976. unsigned char *s1;
  1977. char *s2;
  1978. int len;
  1979. len = strlen(me->aux_info);
  1980. s1 = snewn(len, unsigned char);
  1981. memcpy(s1, me->aux_info, len);
  1982. obfuscate_bitmap(s1, len*8, false);
  1983. s2 = bin2hex(s1, len);
  1984. wr("AUXINFO", s2);
  1985. sfree(s2);
  1986. sfree(s1);
  1987. }
  1988. /*
  1989. * Any required serialisation of the game_ui.
  1990. */
  1991. if (me->ui && me->ourgame->encode_ui) {
  1992. char *s = me->ourgame->encode_ui(me->ui);
  1993. if (s) {
  1994. wr("UI", s);
  1995. sfree(s);
  1996. }
  1997. }
  1998. /*
  1999. * The game time, if it's a timed game.
  2000. */
  2001. if (me->ourgame->is_timed) {
  2002. char buf[80];
  2003. sprintf(buf, "%g", me->elapsed);
  2004. wr("TIME", buf);
  2005. }
  2006. /*
  2007. * The length of, and position in, the states list.
  2008. */
  2009. {
  2010. char buf[80];
  2011. sprintf(buf, "%d", me->nstates);
  2012. wr("NSTATES", buf);
  2013. assert(me->statepos >= 1 && me->statepos <= me->nstates);
  2014. sprintf(buf, "%d", me->statepos);
  2015. wr("STATEPOS", buf);
  2016. }
  2017. /*
  2018. * For each state after the initial one (which we know is
  2019. * constructed from either privdesc or desc), enough
  2020. * information for execute_move() to reconstruct it from the
  2021. * previous one.
  2022. */
  2023. for (i = 1; i < me->nstates; i++) {
  2024. assert(me->states[i].movetype != NEWGAME); /* only state 0 */
  2025. switch (me->states[i].movetype) {
  2026. case MOVE:
  2027. wr("MOVE", me->states[i].movestr);
  2028. break;
  2029. case SOLVE:
  2030. wr("SOLVE", me->states[i].movestr);
  2031. break;
  2032. case RESTART:
  2033. wr("RESTART", me->states[i].movestr);
  2034. break;
  2035. }
  2036. }
  2037. #undef wr
  2038. }
  2039. /*
  2040. * Internal version of midend_deserialise, taking an extra check
  2041. * function to be called just before beginning to install things in
  2042. * the midend.
  2043. *
  2044. * Like midend_deserialise proper, this function returns NULL on
  2045. * success, or an error message.
  2046. */
  2047. static const char *midend_deserialise_internal(
  2048. midend *me, bool (*read)(void *ctx, void *buf, int len), void *rctx,
  2049. const char *(*check)(void *ctx, midend *, const struct deserialise_data *),
  2050. void *cctx)
  2051. {
  2052. struct deserialise_data data;
  2053. int gotstates = 0;
  2054. bool started = false;
  2055. int i;
  2056. char *val = NULL;
  2057. /* Initially all errors give the same report */
  2058. const char *ret = "Data does not appear to be a saved game file";
  2059. data.seed = data.parstr = data.desc = data.privdesc = NULL;
  2060. data.auxinfo = data.uistr = data.cparstr = NULL;
  2061. data.elapsed = 0.0F;
  2062. data.params = data.cparams = NULL;
  2063. data.ui = NULL;
  2064. data.states = NULL;
  2065. data.nstates = 0;
  2066. data.statepos = -1;
  2067. /*
  2068. * Loop round and round reading one key/value pair at a time
  2069. * from the serialised stream, until we have enough game states
  2070. * to finish.
  2071. */
  2072. while (data.nstates <= 0 || data.statepos < 0 ||
  2073. gotstates < data.nstates-1) {
  2074. char key[9], c;
  2075. int len;
  2076. do {
  2077. if (!read(rctx, key, 1)) {
  2078. /* unexpected EOF */
  2079. goto cleanup;
  2080. }
  2081. } while (key[0] == '\r' || key[0] == '\n');
  2082. if (!read(rctx, key+1, 8)) {
  2083. /* unexpected EOF */
  2084. goto cleanup;
  2085. }
  2086. if (key[8] != ':') {
  2087. if (started)
  2088. ret = "Data was incorrectly formatted for a saved game file";
  2089. goto cleanup;
  2090. }
  2091. len = strcspn(key, ": ");
  2092. assert(len <= 8);
  2093. key[len] = '\0';
  2094. len = 0;
  2095. while (1) {
  2096. if (!read(rctx, &c, 1)) {
  2097. /* unexpected EOF */
  2098. goto cleanup;
  2099. }
  2100. if (c == ':') {
  2101. break;
  2102. } else if (c >= '0' && c <= '9' && len < (INT_MAX - 10) / 10) {
  2103. len = (len * 10) + (c - '0');
  2104. } else {
  2105. if (started)
  2106. ret = "Data was incorrectly formatted for a"
  2107. " saved game file";
  2108. goto cleanup;
  2109. }
  2110. }
  2111. val = snewn(len+1, char);
  2112. if (!read(rctx, val, len)) {
  2113. /* unexpected EOF */
  2114. goto cleanup;
  2115. }
  2116. val[len] = '\0';
  2117. /* Validate that all values (apart from SEED) are printable ASCII. */
  2118. if (strcmp(key, "SEED"))
  2119. for (i = 0; val[i]; i++)
  2120. if (val[i] < 32 || val[i] >= 127) {
  2121. ret = "Forbidden characters in saved game file";
  2122. goto cleanup;
  2123. }
  2124. if (!started) {
  2125. if (strcmp(key, "SAVEFILE") || strcmp(val, SERIALISE_MAGIC)) {
  2126. /* ret already has the right message in it */
  2127. goto cleanup;
  2128. }
  2129. /* Now most errors are this one, unless otherwise specified */
  2130. ret = "Saved data ended unexpectedly";
  2131. started = true;
  2132. } else {
  2133. if (!strcmp(key, "VERSION")) {
  2134. if (strcmp(val, SERIALISE_VERSION)) {
  2135. ret = "Cannot handle this version of the saved game"
  2136. " file format";
  2137. goto cleanup;
  2138. }
  2139. } else if (!strcmp(key, "GAME")) {
  2140. if (strcmp(val, me->ourgame->name)) {
  2141. ret = "Save file is from a different game";
  2142. goto cleanup;
  2143. }
  2144. } else if (!strcmp(key, "PARAMS")) {
  2145. sfree(data.parstr);
  2146. data.parstr = val;
  2147. val = NULL;
  2148. } else if (!strcmp(key, "CPARAMS")) {
  2149. sfree(data.cparstr);
  2150. data.cparstr = val;
  2151. val = NULL;
  2152. } else if (!strcmp(key, "HEXSEED")) {
  2153. unsigned char *tmp;
  2154. int len = strlen(val) / 2; /* length in bytes */
  2155. tmp = hex2bin(val, len);
  2156. sfree(data.seed);
  2157. data.seed = snewn(len + 1, char);
  2158. memcpy(data.seed, tmp, len);
  2159. data.seed[len] = '\0';
  2160. sfree(tmp);
  2161. } else if (!strcmp(key, "SEED")) {
  2162. sfree(data.seed);
  2163. data.seed = val;
  2164. val = NULL;
  2165. } else if (!strcmp(key, "DESC")) {
  2166. sfree(data.desc);
  2167. data.desc = val;
  2168. val = NULL;
  2169. } else if (!strcmp(key, "PRIVDESC")) {
  2170. sfree(data.privdesc);
  2171. data.privdesc = val;
  2172. val = NULL;
  2173. } else if (!strcmp(key, "AUXINFO")) {
  2174. unsigned char *tmp;
  2175. int len = strlen(val) / 2; /* length in bytes */
  2176. tmp = hex2bin(val, len);
  2177. obfuscate_bitmap(tmp, len*8, true);
  2178. sfree(data.auxinfo);
  2179. data.auxinfo = snewn(len + 1, char);
  2180. memcpy(data.auxinfo, tmp, len);
  2181. data.auxinfo[len] = '\0';
  2182. sfree(tmp);
  2183. } else if (!strcmp(key, "UI")) {
  2184. sfree(data.uistr);
  2185. data.uistr = val;
  2186. val = NULL;
  2187. } else if (!strcmp(key, "TIME")) {
  2188. data.elapsed = (float)atof(val);
  2189. } else if (!strcmp(key, "NSTATES")) {
  2190. if (data.states) {
  2191. ret = "Two state counts provided in save file";
  2192. goto cleanup;
  2193. }
  2194. data.nstates = atoi(val);
  2195. if (data.nstates <= 0) {
  2196. ret = "Number of states in save file was negative";
  2197. goto cleanup;
  2198. }
  2199. data.states = snewn(data.nstates, struct midend_state_entry);
  2200. for (i = 0; i < data.nstates; i++) {
  2201. data.states[i].state = NULL;
  2202. data.states[i].movestr = NULL;
  2203. data.states[i].movetype = NEWGAME;
  2204. }
  2205. } else if (!strcmp(key, "STATEPOS")) {
  2206. data.statepos = atoi(val);
  2207. } else if (!strcmp(key, "MOVE") ||
  2208. !strcmp(key, "SOLVE") ||
  2209. !strcmp(key, "RESTART")) {
  2210. if (!data.states) {
  2211. ret = "No state count provided in save file";
  2212. goto cleanup;
  2213. }
  2214. if (data.statepos < 0) {
  2215. ret = "No game position provided in save file";
  2216. goto cleanup;
  2217. }
  2218. gotstates++;
  2219. assert(gotstates < data.nstates);
  2220. if (!strcmp(key, "MOVE"))
  2221. data.states[gotstates].movetype = MOVE;
  2222. else if (!strcmp(key, "SOLVE"))
  2223. data.states[gotstates].movetype = SOLVE;
  2224. else
  2225. data.states[gotstates].movetype = RESTART;
  2226. data.states[gotstates].movestr = val;
  2227. val = NULL;
  2228. }
  2229. }
  2230. sfree(val);
  2231. val = NULL;
  2232. }
  2233. data.params = me->ourgame->default_params();
  2234. if (!data.parstr) {
  2235. ret = "Long-term parameters in save file are missing";
  2236. goto cleanup;
  2237. }
  2238. me->ourgame->decode_params(data.params, data.parstr);
  2239. if (me->ourgame->validate_params(data.params, true)) {
  2240. ret = "Long-term parameters in save file are invalid";
  2241. goto cleanup;
  2242. }
  2243. data.cparams = me->ourgame->default_params();
  2244. if (!data.cparstr) {
  2245. ret = "Short-term parameters in save file are missing";
  2246. goto cleanup;
  2247. }
  2248. me->ourgame->decode_params(data.cparams, data.cparstr);
  2249. if (me->ourgame->validate_params(data.cparams, false)) {
  2250. ret = "Short-term parameters in save file are invalid";
  2251. goto cleanup;
  2252. }
  2253. if (data.seed && me->ourgame->validate_params(data.cparams, true)) {
  2254. /*
  2255. * The seed's no use with this version, but we can perfectly
  2256. * well use the rest of the data.
  2257. */
  2258. sfree(data.seed);
  2259. data.seed = NULL;
  2260. }
  2261. if (!data.desc) {
  2262. ret = "Game description in save file is missing";
  2263. goto cleanup;
  2264. } else if (me->ourgame->validate_desc(data.cparams, data.desc)) {
  2265. ret = "Game description in save file is invalid";
  2266. goto cleanup;
  2267. }
  2268. if (data.privdesc &&
  2269. me->ourgame->validate_desc(data.cparams, data.privdesc)) {
  2270. ret = "Game private description in save file is invalid";
  2271. goto cleanup;
  2272. }
  2273. if (data.statepos < 1 || data.statepos > data.nstates) {
  2274. ret = "Game position in save file is out of range";
  2275. goto cleanup;
  2276. }
  2277. if (!data.states) {
  2278. ret = "No state count provided in save file";
  2279. goto cleanup;
  2280. }
  2281. data.states[0].state = me->ourgame->new_game(
  2282. me, data.cparams, data.privdesc ? data.privdesc : data.desc);
  2283. for (i = 1; i < data.nstates; i++) {
  2284. assert(data.states[i].movetype != NEWGAME);
  2285. switch (data.states[i].movetype) {
  2286. case MOVE:
  2287. case SOLVE:
  2288. data.states[i].state = me->ourgame->execute_move(
  2289. data.states[i-1].state, data.states[i].movestr);
  2290. if (data.states[i].state == NULL) {
  2291. ret = "Save file contained an invalid move";
  2292. goto cleanup;
  2293. }
  2294. break;
  2295. case RESTART:
  2296. if (me->ourgame->validate_desc(
  2297. data.cparams, data.states[i].movestr)) {
  2298. ret = "Save file contained an invalid restart move";
  2299. goto cleanup;
  2300. }
  2301. data.states[i].state = me->ourgame->new_game(
  2302. me, data.cparams, data.states[i].movestr);
  2303. break;
  2304. }
  2305. }
  2306. data.ui = me->ourgame->new_ui(data.states[0].state);
  2307. midend_apply_prefs(me, data.ui);
  2308. if (data.uistr && me->ourgame->decode_ui)
  2309. me->ourgame->decode_ui(data.ui, data.uistr,
  2310. data.states[data.statepos-1].state);
  2311. /*
  2312. * Run the externally provided check function, and abort if it
  2313. * returns an error message.
  2314. */
  2315. if (check && (ret = check(cctx, me, &data)) != NULL)
  2316. goto cleanup; /* error message is already in ret */
  2317. /*
  2318. * Now we've run out of possible error conditions, so we're
  2319. * ready to start overwriting the real data in the current
  2320. * midend. We'll do this by swapping things with the local
  2321. * variables, so that the same cleanup code will free the old
  2322. * stuff.
  2323. */
  2324. {
  2325. char *tmp;
  2326. tmp = me->desc;
  2327. me->desc = data.desc;
  2328. data.desc = tmp;
  2329. tmp = me->privdesc;
  2330. me->privdesc = data.privdesc;
  2331. data.privdesc = tmp;
  2332. tmp = me->seedstr;
  2333. me->seedstr = data.seed;
  2334. data.seed = tmp;
  2335. tmp = me->aux_info;
  2336. me->aux_info = data.auxinfo;
  2337. data.auxinfo = tmp;
  2338. }
  2339. me->genmode = GOT_NOTHING;
  2340. me->statesize = data.nstates;
  2341. data.nstates = me->nstates;
  2342. me->nstates = me->statesize;
  2343. {
  2344. struct midend_state_entry *tmp;
  2345. tmp = me->states;
  2346. me->states = data.states;
  2347. data.states = tmp;
  2348. }
  2349. me->statepos = data.statepos;
  2350. /*
  2351. * Don't save the "new game undo/redo" state. So "new game" twice or
  2352. * (in some environments) switching away and back, will make a
  2353. * "new game" irreversible. Maybe in the future we will have a
  2354. * more sophisticated way to decide when to discard the previous
  2355. * game state.
  2356. */
  2357. me->newgame_undo.len = 0;
  2358. me->newgame_redo.len = 0;
  2359. {
  2360. game_params *tmp;
  2361. tmp = me->params;
  2362. me->params = data.params;
  2363. data.params = tmp;
  2364. tmp = me->curparams;
  2365. me->curparams = data.cparams;
  2366. data.cparams = tmp;
  2367. }
  2368. me->oldstate = NULL;
  2369. me->anim_time = me->anim_pos = me->flash_time = me->flash_pos = 0.0F;
  2370. me->dir = 0;
  2371. {
  2372. game_ui *tmp;
  2373. tmp = me->ui;
  2374. me->ui = data.ui;
  2375. data.ui = tmp;
  2376. }
  2377. me->elapsed = data.elapsed;
  2378. me->pressed_mouse_button = 0;
  2379. midend_set_timer(me);
  2380. if (me->drawstate)
  2381. me->ourgame->free_drawstate(me->drawing, me->drawstate);
  2382. me->drawstate =
  2383. me->ourgame->new_drawstate(me->drawing,
  2384. me->states[me->statepos-1].state);
  2385. me->first_draw = true;
  2386. midend_size_new_drawstate(me);
  2387. if (me->game_id_change_notify_function)
  2388. me->game_id_change_notify_function(me->game_id_change_notify_ctx);
  2389. ret = NULL; /* success! */
  2390. cleanup:
  2391. sfree(val);
  2392. sfree(data.seed);
  2393. sfree(data.parstr);
  2394. sfree(data.cparstr);
  2395. sfree(data.desc);
  2396. sfree(data.privdesc);
  2397. sfree(data.auxinfo);
  2398. sfree(data.uistr);
  2399. if (data.params)
  2400. me->ourgame->free_params(data.params);
  2401. if (data.cparams)
  2402. me->ourgame->free_params(data.cparams);
  2403. if (data.ui)
  2404. me->ourgame->free_ui(data.ui);
  2405. if (data.states) {
  2406. int i;
  2407. for (i = 0; i < data.nstates; i++) {
  2408. if (data.states[i].state)
  2409. me->ourgame->free_game(data.states[i].state);
  2410. sfree(data.states[i].movestr);
  2411. }
  2412. sfree(data.states);
  2413. }
  2414. return ret;
  2415. }
  2416. const char *midend_deserialise(
  2417. midend *me, bool (*read)(void *ctx, void *buf, int len), void *rctx)
  2418. {
  2419. return midend_deserialise_internal(me, read, rctx, NULL, NULL);
  2420. }
  2421. /*
  2422. * This function examines a saved game file just far enough to
  2423. * determine which game type it contains. It returns NULL on success
  2424. * and the game name string in 'name' (which will be dynamically
  2425. * allocated and should be caller-freed), or an error message on
  2426. * failure.
  2427. */
  2428. const char *identify_game(char **name,
  2429. bool (*read)(void *ctx, void *buf, int len),
  2430. void *rctx)
  2431. {
  2432. int nstates = 0, statepos = -1, gotstates = 0;
  2433. bool started = false;
  2434. char *val = NULL;
  2435. /* Initially all errors give the same report */
  2436. const char *ret = "Data does not appear to be a saved game file";
  2437. *name = NULL;
  2438. /*
  2439. * Loop round and round reading one key/value pair at a time from
  2440. * the serialised stream, until we've found the game name.
  2441. */
  2442. while (nstates <= 0 || statepos < 0 || gotstates < nstates-1) {
  2443. char key[9], c;
  2444. int len;
  2445. do {
  2446. if (!read(rctx, key, 1)) {
  2447. /* unexpected EOF */
  2448. goto cleanup;
  2449. }
  2450. } while (key[0] == '\r' || key[0] == '\n');
  2451. if (!read(rctx, key+1, 8)) {
  2452. /* unexpected EOF */
  2453. goto cleanup;
  2454. }
  2455. if (key[8] != ':') {
  2456. if (started)
  2457. ret = "Data was incorrectly formatted for a saved game file";
  2458. goto cleanup;
  2459. }
  2460. len = strcspn(key, ": ");
  2461. assert(len <= 8);
  2462. key[len] = '\0';
  2463. len = 0;
  2464. while (1) {
  2465. if (!read(rctx, &c, 1)) {
  2466. /* unexpected EOF */
  2467. goto cleanup;
  2468. }
  2469. if (c == ':') {
  2470. break;
  2471. } else if (c >= '0' && c <= '9' && len < (INT_MAX - 10) / 10) {
  2472. len = (len * 10) + (c - '0');
  2473. } else {
  2474. if (started)
  2475. ret = "Data was incorrectly formatted for a"
  2476. " saved game file";
  2477. goto cleanup;
  2478. }
  2479. }
  2480. val = snewn(len+1, char);
  2481. if (!read(rctx, val, len)) {
  2482. /* unexpected EOF */
  2483. goto cleanup;
  2484. }
  2485. val[len] = '\0';
  2486. if (!started) {
  2487. if (strcmp(key, "SAVEFILE") || strcmp(val, SERIALISE_MAGIC)) {
  2488. /* ret already has the right message in it */
  2489. goto cleanup;
  2490. }
  2491. /* Now most errors are this one, unless otherwise specified */
  2492. ret = "Saved data ended unexpectedly";
  2493. started = true;
  2494. } else {
  2495. if (!strcmp(key, "VERSION")) {
  2496. if (strcmp(val, SERIALISE_VERSION)) {
  2497. ret = "Cannot handle this version of the saved game"
  2498. " file format";
  2499. goto cleanup;
  2500. }
  2501. } else if (!strcmp(key, "GAME")) {
  2502. *name = dupstr(val);
  2503. ret = NULL;
  2504. goto cleanup;
  2505. }
  2506. }
  2507. sfree(val);
  2508. val = NULL;
  2509. }
  2510. cleanup:
  2511. sfree(val);
  2512. return ret;
  2513. }
  2514. const char *midend_print_puzzle(midend *me, document *doc, bool with_soln)
  2515. {
  2516. game_state *soln = NULL;
  2517. if (me->statepos < 1)
  2518. return "No game set up to print";/* _shouldn't_ happen! */
  2519. if (with_soln) {
  2520. const char *msg;
  2521. char *movestr;
  2522. if (!me->ourgame->can_solve)
  2523. return "This game does not support the Solve operation";
  2524. msg = "Solve operation failed";/* game _should_ overwrite on error */
  2525. movestr = me->ourgame->solve(me->states[0].state,
  2526. me->states[me->statepos-1].state,
  2527. me->aux_info, &msg);
  2528. if (!movestr)
  2529. return msg;
  2530. soln = me->ourgame->execute_move(me->states[me->statepos-1].state,
  2531. movestr);
  2532. assert(soln);
  2533. sfree(movestr);
  2534. } else
  2535. soln = NULL;
  2536. /*
  2537. * This call passes over ownership of the two game_states, the
  2538. * game_params and the game_ui. Hence we duplicate the ones we
  2539. * want to keep, and we don't have to bother freeing soln if it
  2540. * was non-NULL.
  2541. */
  2542. game_ui *ui = me->ourgame->new_ui(me->states[0].state);
  2543. midend_apply_prefs(me, ui);
  2544. document_add_puzzle(doc, me->ourgame,
  2545. me->ourgame->dup_params(me->curparams), ui,
  2546. me->ourgame->dup_game(me->states[0].state), soln);
  2547. return NULL;
  2548. }
  2549. static void midend_apply_prefs(midend *me, game_ui *ui)
  2550. {
  2551. struct midend_serialise_buf_read_ctx rctx[1];
  2552. rctx->ser = &me->be_prefs;
  2553. rctx->len = me->be_prefs.len;
  2554. rctx->pos = 0;
  2555. const char *err = midend_deserialise_prefs(
  2556. me, ui, midend_serialise_buf_read, rctx);
  2557. /* This should have come from our own serialise function, so
  2558. * it should never be invalid. */
  2559. assert(!err && "Bad internal serialisation of preferences");
  2560. }
  2561. static config_item *midend_get_prefs(midend *me, game_ui *ui)
  2562. {
  2563. int n_be_prefs, n_me_prefs, pos, i;
  2564. config_item *all_prefs, *be_prefs;
  2565. be_prefs = NULL;
  2566. n_be_prefs = 0;
  2567. if (me->ourgame->get_prefs) {
  2568. if (ui) {
  2569. be_prefs = me->ourgame->get_prefs(ui);
  2570. } else if (me->ui) {
  2571. be_prefs = me->ourgame->get_prefs(me->ui);
  2572. } else {
  2573. game_ui *tmp_ui = me->ourgame->new_ui(NULL);
  2574. be_prefs = me->ourgame->get_prefs(tmp_ui);
  2575. me->ourgame->free_ui(tmp_ui);
  2576. }
  2577. while (be_prefs[n_be_prefs].type != C_END)
  2578. n_be_prefs++;
  2579. }
  2580. n_me_prefs = 1;
  2581. all_prefs = snewn(n_me_prefs + n_be_prefs + 1, config_item);
  2582. pos = 0;
  2583. assert(pos < n_me_prefs);
  2584. all_prefs[pos].name = "Keyboard shortcuts without Ctrl";
  2585. all_prefs[pos].kw = "one-key-shortcuts";
  2586. all_prefs[pos].type = C_BOOLEAN;
  2587. all_prefs[pos].u.boolean.bval = me->one_key_shortcuts;
  2588. pos++;
  2589. for (i = 0; i < n_be_prefs; i++) {
  2590. all_prefs[pos] = be_prefs[i]; /* structure copy */
  2591. pos++;
  2592. }
  2593. all_prefs[pos].name = NULL;
  2594. all_prefs[pos].type = C_END;
  2595. if (be_prefs)
  2596. /* We already copied each element, so don't free those with
  2597. free_cfg(). */
  2598. sfree(be_prefs);
  2599. return all_prefs;
  2600. }
  2601. static void midend_set_prefs(midend *me, game_ui *ui, config_item *all_prefs)
  2602. {
  2603. int pos = 0;
  2604. game_ui *tmpui = NULL;
  2605. me->one_key_shortcuts = all_prefs[pos].u.boolean.bval;
  2606. pos++;
  2607. if (me->ourgame->get_prefs) {
  2608. if (!ui)
  2609. ui = tmpui = me->ourgame->new_ui(NULL);
  2610. me->ourgame->set_prefs(ui, all_prefs + pos);
  2611. }
  2612. me->be_prefs.len = 0;
  2613. midend_serialise_prefs(me, ui, midend_serialise_buf_write, &me->be_prefs);
  2614. if (tmpui)
  2615. me->ourgame->free_ui(tmpui);
  2616. }
  2617. static void midend_serialise_prefs(
  2618. midend *me, game_ui *ui,
  2619. void (*write)(void *ctx, const void *buf, int len), void *wctx)
  2620. {
  2621. config_item *cfg;
  2622. int i;
  2623. cfg = midend_get_prefs(me, ui);
  2624. assert(cfg);
  2625. for (i = 0; cfg[i].type != C_END; i++) {
  2626. config_item *it = &cfg[i];
  2627. /* Expect keywords to be made up only of simple characters */
  2628. assert(it->kw[strspn(it->kw, "abcdefghijklmnopqrstuvwxyz-")] == '\0');
  2629. write(wctx, it->kw, strlen(it->kw));
  2630. write(wctx, "=", 1);
  2631. switch (it->type) {
  2632. case C_BOOLEAN:
  2633. if (it->u.boolean.bval)
  2634. write(wctx, "true", 4);
  2635. else
  2636. write(wctx, "false", 5);
  2637. break;
  2638. case C_STRING: {
  2639. const char *p = it->u.string.sval;
  2640. while (*p) {
  2641. char c = *p++;
  2642. write(wctx, &c, 1);
  2643. if (c == '\n')
  2644. write(wctx, " ", 1);
  2645. }
  2646. break;
  2647. }
  2648. case C_CHOICES: {
  2649. int n = it->u.choices.selected;
  2650. const char *p = it->u.choices.choicekws;
  2651. char sepstr[2];
  2652. sepstr[0] = *p++;
  2653. sepstr[1] = '\0';
  2654. while (n > 0) {
  2655. const char *q = strchr(p, sepstr[0]);
  2656. assert(q != NULL && "Value out of range in C_CHOICES");
  2657. p = q+1;
  2658. n--;
  2659. }
  2660. write(wctx, p, strcspn(p, sepstr));
  2661. break;
  2662. }
  2663. }
  2664. write(wctx, "\n", 1);
  2665. }
  2666. free_cfg(cfg);
  2667. }
  2668. struct buffer {
  2669. char *data;
  2670. size_t len, size;
  2671. };
  2672. static void buffer_append(struct buffer *buf, char c)
  2673. {
  2674. if (buf->len + 2 > buf->size) {
  2675. size_t new_size = buf->size + buf->size / 4 + 128;
  2676. assert(new_size > buf->size);
  2677. buf->data = sresize(buf->data, new_size, char);
  2678. buf->size = new_size;
  2679. assert(buf->len < buf->size);
  2680. }
  2681. buf->data[buf->len++] = c;
  2682. assert(buf->len < buf->size);
  2683. buf->data[buf->len] = '\0';
  2684. }
  2685. static const char *midend_deserialise_prefs(
  2686. midend *me, game_ui *ui,
  2687. bool (*read)(void *ctx, void *buf, int len), void *rctx)
  2688. {
  2689. config_item *cfg, *it;
  2690. int i;
  2691. struct buffer buf[1] = {{ NULL, 0, 0 }};
  2692. const char *errmsg = NULL;
  2693. char read_char;
  2694. char ungot_char = '\0';
  2695. bool have_ungot_a_char = false, eof = false;
  2696. cfg = midend_get_prefs(me, ui);
  2697. while (!eof) {
  2698. if (have_ungot_a_char) {
  2699. read_char = ungot_char;
  2700. have_ungot_a_char = false;
  2701. } else {
  2702. if (!read(rctx, &read_char, 1))
  2703. goto out; /* EOF at line start == success */
  2704. }
  2705. if (read_char == '#' || read_char == '\n') {
  2706. /* Skip comment or blank line */
  2707. while (read_char != '\n') {
  2708. if (!read(rctx, &read_char, 1))
  2709. goto out; /* EOF during boring line == success */
  2710. }
  2711. continue;
  2712. }
  2713. buf->len = 0;
  2714. while (true) {
  2715. buffer_append(buf, read_char);
  2716. if (!read(rctx, &read_char, 1)) {
  2717. errmsg = "Partial line at end of preferences file";
  2718. goto out;
  2719. }
  2720. if (read_char == '\n') {
  2721. errmsg = "Expected '=' after keyword";
  2722. goto out;
  2723. }
  2724. if (read_char == '=')
  2725. break;
  2726. }
  2727. it = NULL;
  2728. for (i = 0; cfg[i].type != C_END; i++)
  2729. if (!strcmp(buf->data, cfg[i].kw))
  2730. it = &cfg[i];
  2731. buf->len = 0;
  2732. while (true) {
  2733. if (!read(rctx, &read_char, 1)) {
  2734. /* We tolerate missing \n at the end of the file, so
  2735. * this is taken to mean we've got a complete config
  2736. * directive. But set the eof flag so that we stop
  2737. * after processing it. */
  2738. eof = true;
  2739. break;
  2740. } else if (read_char == '\n') {
  2741. /* Newline _might_ be the end of this config
  2742. * directive, unless it's followed by a space, in
  2743. * which case it's a space-stuffed line
  2744. * continuation. */
  2745. if (read(rctx, &read_char, 1)) {
  2746. if (read_char == ' ') {
  2747. buffer_append(buf, '\n');
  2748. continue;
  2749. } else {
  2750. /* But if the next character wasn't a space,
  2751. * then we must unget it so that it'll be
  2752. * available to the next iteration of our
  2753. * outer loop as the first character of the
  2754. * next keyword. */
  2755. ungot_char = read_char;
  2756. have_ungot_a_char = true;
  2757. break;
  2758. }
  2759. } else {
  2760. /* And if the newline was followed by EOF, then we
  2761. * should finish this iteration of the outer
  2762. * loop normally, and then not go round again. */
  2763. eof = true;
  2764. break;
  2765. }
  2766. } else {
  2767. /* Any other character is just added to the buffer. */
  2768. buffer_append(buf, read_char);
  2769. }
  2770. }
  2771. if (!it) {
  2772. /*
  2773. * Tolerate unknown keywords in a preferences file, on the
  2774. * assumption that they're from a different (probably
  2775. * later) version of the game.
  2776. */
  2777. continue;
  2778. }
  2779. switch (it->type) {
  2780. case C_BOOLEAN:
  2781. if (!strcmp(buf->data, "true"))
  2782. it->u.boolean.bval = true;
  2783. else if (!strcmp(buf->data, "false"))
  2784. it->u.boolean.bval = false;
  2785. else {
  2786. errmsg = "Value for boolean was not 'true' or 'false'";
  2787. goto out;
  2788. }
  2789. break;
  2790. case C_STRING:
  2791. sfree(it->u.string.sval);
  2792. it->u.string.sval = buf->data;
  2793. buf->data = NULL;
  2794. buf->len = buf->size = 0;
  2795. break;
  2796. case C_CHOICES: {
  2797. int n = 0;
  2798. bool found = false;
  2799. const char *p = it->u.choices.choicekws;
  2800. char sepstr[2];
  2801. sepstr[0] = *p;
  2802. sepstr[1] = '\0';
  2803. while (*p++) {
  2804. int len = strcspn(p, sepstr);
  2805. if (buf->len == len && !memcmp(p, buf->data, len)) {
  2806. it->u.choices.selected = n;
  2807. found = true;
  2808. break;
  2809. }
  2810. p += len;
  2811. n++;
  2812. }
  2813. if (!found) {
  2814. errmsg = "Invalid value for enumeration";
  2815. goto out;
  2816. }
  2817. break;
  2818. }
  2819. }
  2820. }
  2821. out:
  2822. if (!errmsg)
  2823. midend_set_prefs(me, ui, cfg);
  2824. free_cfg(cfg);
  2825. sfree(buf->data);
  2826. return errmsg;
  2827. }