windows.c 89 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459
  1. /*
  2. * windows.c: Windows front end for my puzzle collection.
  3. */
  4. #include <windows.h>
  5. #include <commctrl.h>
  6. #ifndef NO_HTMLHELP
  7. #include <htmlhelp.h>
  8. #endif /* NO_HTMLHELP */
  9. #include <io.h>
  10. #include <stdio.h>
  11. #include <assert.h>
  12. #include <ctype.h>
  13. #include <stdarg.h>
  14. #include <stdlib.h>
  15. #include <limits.h>
  16. #include <time.h>
  17. #include "puzzles.h"
  18. #define IDM_NEW 0x0010
  19. #define IDM_RESTART 0x0020
  20. #define IDM_UNDO 0x0030
  21. #define IDM_REDO 0x0040
  22. #define IDM_COPY 0x0050
  23. #define IDM_SOLVE 0x0060
  24. #define IDM_QUIT 0x0070
  25. #define IDM_CONFIG 0x0080
  26. #define IDM_DESC 0x0090
  27. #define IDM_SEED 0x00A0
  28. #define IDM_HELPC 0x00B0
  29. #define IDM_GAMEHELP 0x00C0
  30. #define IDM_ABOUT 0x00D0
  31. #define IDM_SAVE 0x00E0
  32. #define IDM_LOAD 0x00F0
  33. #define IDM_PRINT 0x0100
  34. #define IDM_PREFS 0x0110
  35. /* Menu items for preset game_params go up from IDM_PRESET_BASE in
  36. * steps of MENUITEM_STEP = 0x20. Menu items for selecting different
  37. * games (in -DCOMBINED mode) go up from IDM_GAME_BASE similarly. */
  38. #define IDM_PRESET_BASE 0x0120
  39. #define IDM_GAME_BASE 0x0130
  40. #define MENUITEM_STEP 0x0020
  41. #define HELP_FILE_NAME "puzzles.hlp"
  42. #define HELP_CNT_NAME "puzzles.cnt"
  43. #ifndef NO_HTMLHELP
  44. #define CHM_FILE_NAME "puzzles.chm"
  45. #endif /* NO_HTMLHELP */
  46. #ifndef NO_HTMLHELP
  47. typedef HWND (CALLBACK *htmlhelp_t)(HWND, LPCSTR, UINT, DWORD);
  48. static htmlhelp_t htmlhelp;
  49. static HINSTANCE hh_dll;
  50. #endif /* NO_HTMLHELP */
  51. enum { NONE, HLP, CHM } help_type;
  52. char *help_path;
  53. bool help_has_contents;
  54. #ifndef FILENAME_MAX
  55. #define FILENAME_MAX (260)
  56. #endif
  57. #ifndef HGDI_ERROR
  58. #define HGDI_ERROR ((HANDLE)GDI_ERROR)
  59. #endif
  60. #ifdef COMBINED
  61. #define CLASSNAME "Puzzles"
  62. #else
  63. #define CLASSNAME thegame.name
  64. #endif
  65. #ifdef DEBUGGING
  66. static FILE *debug_fp = NULL;
  67. static HANDLE debug_hdl = INVALID_HANDLE_VALUE;
  68. static int debug_got_console = 0;
  69. static void dputs(char *buf)
  70. {
  71. /*DWORD dw;
  72. if (!debug_got_console) {
  73. if (AllocConsole()) {
  74. debug_got_console = 1;
  75. debug_hdl = GetStdHandle(STD_OUTPUT_HANDLE);
  76. }
  77. }
  78. if (!debug_fp) {
  79. debug_fp = fopen("debug.log", "w");
  80. }
  81. if (debug_hdl != INVALID_HANDLE_VALUE) {
  82. WriteFile(debug_hdl, buf, strlen(buf), &dw, NULL);
  83. }
  84. if (debug_fp) {
  85. fputs(buf, debug_fp);
  86. fflush(debug_fp);
  87. }*/
  88. OutputDebugString(buf);
  89. }
  90. void debug_printf(const char *fmt, ...)
  91. {
  92. char buf[4096];
  93. va_list ap;
  94. static int debugging = -1;
  95. if (debugging == -1)
  96. debugging = getenv_bool("DEBUG_PUZZLES", false);
  97. if (debugging) {
  98. va_start(ap, fmt);
  99. _vsnprintf(buf, 4095, fmt, ap);
  100. dputs(buf);
  101. va_end(ap);
  102. }
  103. }
  104. #endif
  105. #define WINFLAGS (WS_OVERLAPPEDWINDOW &~ \
  106. (WS_MAXIMIZEBOX | WS_OVERLAPPED))
  107. static void new_game_size(frontend *fe, float scale);
  108. static void load_prefs(midend *me);
  109. static char *save_prefs(midend *me);
  110. struct font {
  111. HFONT font;
  112. int type;
  113. int size;
  114. };
  115. struct cfg_aux {
  116. int ctlid;
  117. };
  118. struct blitter {
  119. HBITMAP bitmap;
  120. frontend *fe;
  121. int x, y, w, h;
  122. };
  123. enum { CFG_PRINT = CFG_FRONTEND_SPECIFIC };
  124. struct preset_menuitemref {
  125. HMENU which_menu;
  126. int item_index;
  127. };
  128. struct frontend {
  129. const game *game;
  130. midend *me;
  131. HWND hwnd, statusbar, cfgbox;
  132. HINSTANCE inst;
  133. HBITMAP bitmap, prevbm;
  134. RECT bitmapPosition; /* game bitmap position within game window */
  135. HDC hdc;
  136. COLORREF *colours;
  137. HBRUSH *brushes;
  138. HPEN *pens;
  139. HRGN clip;
  140. HMENU gamemenu, typemenu;
  141. UINT timer;
  142. DWORD timer_last_tickcount;
  143. struct preset_menu *preset_menu;
  144. struct preset_menuitemref *preset_menuitems;
  145. int n_preset_menuitems;
  146. struct font *fonts;
  147. int nfonts, fontsize;
  148. config_item *cfg;
  149. struct cfg_aux *cfgaux;
  150. int cfg_which, dlg_done;
  151. HFONT cfgfont;
  152. HBRUSH oldbr;
  153. HPEN oldpen;
  154. bool help_running;
  155. enum { DRAWING, PRINTING, NOTHING } drawstatus;
  156. DOCINFO di;
  157. int printcount, printw, printh;
  158. bool printsolns, printcurr, printcolour;
  159. float printscale;
  160. int printoffsetx, printoffsety;
  161. float printpixelscale;
  162. int fontstart;
  163. int linewidth;
  164. bool linedotted;
  165. drawing *dr;
  166. int xmin, ymin;
  167. float puzz_scale;
  168. };
  169. void frontend_free(frontend *fe)
  170. {
  171. midend_free(fe->me);
  172. sfree(fe->colours);
  173. sfree(fe->brushes);
  174. sfree(fe->pens);
  175. sfree(fe->fonts);
  176. sfree(fe);
  177. }
  178. static void update_type_menu_tick(frontend *fe);
  179. static void update_copy_menu_greying(frontend *fe);
  180. void fatal(const char *fmt, ...)
  181. {
  182. char buf[2048];
  183. va_list ap;
  184. va_start(ap, fmt);
  185. vsprintf(buf, fmt, ap);
  186. va_end(ap);
  187. MessageBox(NULL, buf, "Fatal error", MB_ICONEXCLAMATION | MB_OK);
  188. exit(1);
  189. }
  190. char *geterrstr(void)
  191. {
  192. LPVOID lpMsgBuf;
  193. DWORD dw = GetLastError();
  194. char *ret;
  195. FormatMessage(
  196. FORMAT_MESSAGE_ALLOCATE_BUFFER |
  197. FORMAT_MESSAGE_FROM_SYSTEM,
  198. NULL,
  199. dw,
  200. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  201. (LPTSTR) &lpMsgBuf,
  202. 0, NULL );
  203. ret = dupstr(lpMsgBuf);
  204. LocalFree(lpMsgBuf);
  205. return ret;
  206. }
  207. void get_random_seed(void **randseed, int *randseedsize)
  208. {
  209. SYSTEMTIME *st = snew(SYSTEMTIME);
  210. GetLocalTime(st);
  211. *randseed = (void *)st;
  212. *randseedsize = sizeof(SYSTEMTIME);
  213. }
  214. static void win_status_bar(void *handle, const char *text)
  215. {
  216. frontend *fe = (frontend *)handle;
  217. SetWindowText(fe->statusbar, text);
  218. }
  219. static blitter *win_blitter_new(void *handle, int w, int h)
  220. {
  221. blitter *bl = snew(blitter);
  222. memset(bl, 0, sizeof(blitter));
  223. bl->w = w;
  224. bl->h = h;
  225. bl->bitmap = 0;
  226. return bl;
  227. }
  228. static void win_blitter_free(void *handle, blitter *bl)
  229. {
  230. if (bl->bitmap) DeleteObject(bl->bitmap);
  231. sfree(bl);
  232. }
  233. static void blitter_mkbitmap(frontend *fe, blitter *bl)
  234. {
  235. HDC hdc = GetDC(fe->hwnd);
  236. bl->bitmap = CreateCompatibleBitmap(hdc, bl->w, bl->h);
  237. ReleaseDC(fe->hwnd, hdc);
  238. }
  239. /* BitBlt(dstDC, dstX, dstY, dstW, dstH, srcDC, srcX, srcY, dType) */
  240. static void win_blitter_save(void *handle, blitter *bl, int x, int y)
  241. {
  242. frontend *fe = (frontend *)handle;
  243. HDC hdc_win, hdc_blit;
  244. HBITMAP prev_blit;
  245. assert(fe->drawstatus == DRAWING);
  246. if (!bl->bitmap) blitter_mkbitmap(fe, bl);
  247. bl->x = x; bl->y = y;
  248. hdc_win = GetDC(fe->hwnd);
  249. hdc_blit = CreateCompatibleDC(hdc_win);
  250. if (!hdc_blit) fatal("hdc_blit failed: 0x%x", GetLastError());
  251. prev_blit = SelectObject(hdc_blit, bl->bitmap);
  252. if (prev_blit == NULL || prev_blit == HGDI_ERROR)
  253. fatal("SelectObject for hdc_main failed: 0x%x", GetLastError());
  254. if (!BitBlt(hdc_blit, 0, 0, bl->w, bl->h,
  255. fe->hdc, x, y, SRCCOPY))
  256. fatal("BitBlt failed: 0x%x", GetLastError());
  257. SelectObject(hdc_blit, prev_blit);
  258. DeleteDC(hdc_blit);
  259. ReleaseDC(fe->hwnd, hdc_win);
  260. }
  261. static void win_blitter_load(void *handle, blitter *bl, int x, int y)
  262. {
  263. frontend *fe = (frontend *)handle;
  264. HDC hdc_win, hdc_blit;
  265. HBITMAP prev_blit;
  266. assert(fe->drawstatus == DRAWING);
  267. assert(bl->bitmap); /* we should always have saved before loading */
  268. if (x == BLITTER_FROMSAVED) x = bl->x;
  269. if (y == BLITTER_FROMSAVED) y = bl->y;
  270. hdc_win = GetDC(fe->hwnd);
  271. hdc_blit = CreateCompatibleDC(hdc_win);
  272. prev_blit = SelectObject(hdc_blit, bl->bitmap);
  273. BitBlt(fe->hdc, x, y, bl->w, bl->h,
  274. hdc_blit, 0, 0, SRCCOPY);
  275. SelectObject(hdc_blit, prev_blit);
  276. DeleteDC(hdc_blit);
  277. ReleaseDC(fe->hwnd, hdc_win);
  278. }
  279. void frontend_default_colour(frontend *fe, float *output)
  280. {
  281. DWORD c = GetSysColor(COLOR_MENU); /* ick */
  282. output[0] = (float)(GetRValue(c) / 255.0);
  283. output[1] = (float)(GetGValue(c) / 255.0);
  284. output[2] = (float)(GetBValue(c) / 255.0);
  285. }
  286. static POINT win_transform_point(frontend *fe, int x, int y)
  287. {
  288. POINT ret;
  289. assert(fe->drawstatus != NOTHING);
  290. if (fe->drawstatus == PRINTING) {
  291. ret.x = (int)(fe->printoffsetx + fe->printpixelscale * x);
  292. ret.y = (int)(fe->printoffsety + fe->printpixelscale * y);
  293. } else {
  294. ret.x = x;
  295. ret.y = y;
  296. }
  297. return ret;
  298. }
  299. static void win_text_colour(frontend *fe, int colour)
  300. {
  301. assert(fe->drawstatus != NOTHING);
  302. if (fe->drawstatus == PRINTING) {
  303. int hatch;
  304. float r, g, b;
  305. print_get_colour(fe->dr, colour, fe->printcolour, &hatch, &r, &g, &b);
  306. /*
  307. * Displaying text in hatched colours is not permitted.
  308. */
  309. assert(hatch < 0);
  310. SetTextColor(fe->hdc, RGB(r * 255, g * 255, b * 255));
  311. } else {
  312. SetTextColor(fe->hdc, fe->colours[colour]);
  313. }
  314. }
  315. static void win_set_brush(frontend *fe, int colour)
  316. {
  317. HBRUSH br;
  318. assert(fe->drawstatus != NOTHING);
  319. if (fe->drawstatus == PRINTING) {
  320. int hatch;
  321. float r, g, b;
  322. print_get_colour(fe->dr, colour, fe->printcolour, &hatch, &r, &g, &b);
  323. if (hatch < 0) {
  324. br = CreateSolidBrush(RGB(r * 255, g * 255, b * 255));
  325. } else {
  326. br = CreateHatchBrush(hatch == HATCH_BACKSLASH ? HS_FDIAGONAL :
  327. hatch == HATCH_SLASH ? HS_BDIAGONAL :
  328. hatch == HATCH_HORIZ ? HS_HORIZONTAL :
  329. hatch == HATCH_VERT ? HS_VERTICAL :
  330. hatch == HATCH_PLUS ? HS_CROSS :
  331. /* hatch == HATCH_X ? */ HS_DIAGCROSS,
  332. RGB(0,0,0));
  333. }
  334. } else {
  335. br = fe->brushes[colour];
  336. }
  337. fe->oldbr = SelectObject(fe->hdc, br);
  338. }
  339. static void win_reset_brush(frontend *fe)
  340. {
  341. HBRUSH br;
  342. assert(fe->drawstatus != NOTHING);
  343. br = SelectObject(fe->hdc, fe->oldbr);
  344. if (fe->drawstatus == PRINTING)
  345. DeleteObject(br);
  346. }
  347. static void win_set_pen(frontend *fe, int colour, bool thin)
  348. {
  349. HPEN pen;
  350. assert(fe->drawstatus != NOTHING);
  351. if (fe->drawstatus == PRINTING) {
  352. int hatch;
  353. float r, g, b;
  354. int width = thin ? 0 : fe->linewidth;
  355. if (fe->linedotted)
  356. width = 0;
  357. print_get_colour(fe->dr, colour, fe->printcolour, &hatch, &r, &g, &b);
  358. /*
  359. * Stroking in hatched colours is not permitted.
  360. */
  361. assert(hatch < 0);
  362. pen = CreatePen(fe->linedotted ? PS_DOT : PS_SOLID,
  363. width, RGB(r * 255, g * 255, b * 255));
  364. } else {
  365. pen = fe->pens[colour];
  366. }
  367. fe->oldpen = SelectObject(fe->hdc, pen);
  368. }
  369. static void win_reset_pen(frontend *fe)
  370. {
  371. HPEN pen;
  372. assert(fe->drawstatus != NOTHING);
  373. pen = SelectObject(fe->hdc, fe->oldpen);
  374. if (fe->drawstatus == PRINTING)
  375. DeleteObject(pen);
  376. }
  377. static void win_clip(void *handle, int x, int y, int w, int h)
  378. {
  379. frontend *fe = (frontend *)handle;
  380. POINT p, q;
  381. if (fe->drawstatus == NOTHING)
  382. return;
  383. p = win_transform_point(fe, x, y);
  384. q = win_transform_point(fe, x+w, y+h);
  385. IntersectClipRect(fe->hdc, p.x, p.y, q.x, q.y);
  386. }
  387. static void win_unclip(void *handle)
  388. {
  389. frontend *fe = (frontend *)handle;
  390. if (fe->drawstatus == NOTHING)
  391. return;
  392. SelectClipRgn(fe->hdc, NULL);
  393. }
  394. static void win_draw_text(void *handle, int x, int y, int fonttype,
  395. int fontsize, int align, int colour,
  396. const char *text)
  397. {
  398. frontend *fe = (frontend *)handle;
  399. POINT xy;
  400. int i;
  401. LOGFONT lf;
  402. if (fe->drawstatus == NOTHING)
  403. return;
  404. if (fe->drawstatus == PRINTING)
  405. fontsize = (int)(fontsize * fe->printpixelscale);
  406. xy = win_transform_point(fe, x, y);
  407. /*
  408. * Find or create the font.
  409. */
  410. for (i = fe->fontstart; i < fe->nfonts; i++)
  411. if (fe->fonts[i].type == fonttype && fe->fonts[i].size == fontsize)
  412. break;
  413. if (i == fe->nfonts) {
  414. if (fe->fontsize <= fe->nfonts) {
  415. fe->fontsize = fe->nfonts + 10;
  416. fe->fonts = sresize(fe->fonts, fe->fontsize, struct font);
  417. }
  418. fe->nfonts++;
  419. fe->fonts[i].type = fonttype;
  420. fe->fonts[i].size = fontsize;
  421. memset (&lf, 0, sizeof(LOGFONT));
  422. lf.lfHeight = -fontsize;
  423. lf.lfWeight = (fe->drawstatus == PRINTING ? 0 : FW_BOLD);
  424. lf.lfCharSet = DEFAULT_CHARSET;
  425. lf.lfOutPrecision = OUT_DEFAULT_PRECIS;
  426. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  427. lf.lfQuality = DEFAULT_QUALITY;
  428. lf.lfPitchAndFamily = (fonttype == FONT_FIXED ?
  429. FIXED_PITCH | FF_DONTCARE :
  430. VARIABLE_PITCH | FF_SWISS);
  431. fe->fonts[i].font = CreateFontIndirect(&lf);
  432. }
  433. /*
  434. * Position and draw the text.
  435. */
  436. {
  437. HFONT oldfont;
  438. TEXTMETRIC tm;
  439. SIZE size;
  440. WCHAR wText[256];
  441. MultiByteToWideChar (CP_UTF8, 0, text, -1, wText, 256);
  442. oldfont = SelectObject(fe->hdc, fe->fonts[i].font);
  443. if (GetTextMetrics(fe->hdc, &tm)) {
  444. if (align & ALIGN_VCENTRE)
  445. xy.y -= (tm.tmAscent+tm.tmDescent)/2;
  446. else
  447. xy.y -= tm.tmAscent;
  448. }
  449. if (GetTextExtentPoint32W(fe->hdc, wText, wcslen(wText), &size))
  450. {
  451. if (align & ALIGN_HCENTRE)
  452. xy.x -= size.cx / 2;
  453. else if (align & ALIGN_HRIGHT)
  454. xy.x -= size.cx;
  455. }
  456. SetBkMode(fe->hdc, TRANSPARENT);
  457. win_text_colour(fe, colour);
  458. ExtTextOutW(fe->hdc, xy.x, xy.y, 0, NULL, wText, wcslen(wText), NULL);
  459. SelectObject(fe->hdc, oldfont);
  460. }
  461. }
  462. static void win_draw_rect(void *handle, int x, int y, int w, int h, int colour)
  463. {
  464. frontend *fe = (frontend *)handle;
  465. POINT p, q;
  466. if (fe->drawstatus == NOTHING)
  467. return;
  468. if (fe->drawstatus == DRAWING && w == 1 && h == 1) {
  469. /*
  470. * Rectangle() appears to get uppity if asked to draw a 1x1
  471. * rectangle, presumably on the grounds that that's beneath
  472. * its dignity and you ought to be using SetPixel instead.
  473. * So I will.
  474. */
  475. SetPixel(fe->hdc, x, y, fe->colours[colour]);
  476. } else {
  477. win_set_brush(fe, colour);
  478. win_set_pen(fe, colour, true);
  479. p = win_transform_point(fe, x, y);
  480. q = win_transform_point(fe, x+w, y+h);
  481. Rectangle(fe->hdc, p.x, p.y, q.x, q.y);
  482. win_reset_brush(fe);
  483. win_reset_pen(fe);
  484. }
  485. }
  486. static void win_draw_line(void *handle, int x1, int y1, int x2, int y2, int colour)
  487. {
  488. frontend *fe = (frontend *)handle;
  489. POINT pp[2];
  490. if (fe->drawstatus == NOTHING)
  491. return;
  492. win_set_pen(fe, colour, false);
  493. pp[0] = win_transform_point(fe, x1, y1);
  494. pp[1] = win_transform_point(fe, x2, y2);
  495. Polyline(fe->hdc, pp, 2);
  496. if (fe->drawstatus == DRAWING)
  497. SetPixel(fe->hdc, pp[1].x, pp[1].y, fe->colours[colour]);
  498. win_reset_pen(fe);
  499. }
  500. static void win_draw_circle(void *handle, int cx, int cy, int radius,
  501. int fillcolour, int outlinecolour)
  502. {
  503. frontend *fe = (frontend *)handle;
  504. POINT p, q;
  505. assert(outlinecolour >= 0);
  506. if (fe->drawstatus == NOTHING)
  507. return;
  508. if (fillcolour >= 0)
  509. win_set_brush(fe, fillcolour);
  510. else
  511. fe->oldbr = SelectObject(fe->hdc, GetStockObject(NULL_BRUSH));
  512. win_set_pen(fe, outlinecolour, false);
  513. p = win_transform_point(fe, cx - radius, cy - radius);
  514. q = win_transform_point(fe, cx + radius, cy + radius);
  515. Ellipse(fe->hdc, p.x, p.y, q.x+1, q.y+1);
  516. win_reset_brush(fe);
  517. win_reset_pen(fe);
  518. }
  519. static void win_draw_polygon(void *handle, const int *coords, int npoints,
  520. int fillcolour, int outlinecolour)
  521. {
  522. frontend *fe = (frontend *)handle;
  523. POINT *pts;
  524. int i;
  525. if (fe->drawstatus == NOTHING)
  526. return;
  527. pts = snewn(npoints+1, POINT);
  528. for (i = 0; i <= npoints; i++) {
  529. int j = (i < npoints ? i : 0);
  530. pts[i] = win_transform_point(fe, coords[j*2], coords[j*2+1]);
  531. }
  532. assert(outlinecolour >= 0);
  533. if (fillcolour >= 0) {
  534. win_set_brush(fe, fillcolour);
  535. win_set_pen(fe, outlinecolour, false);
  536. Polygon(fe->hdc, pts, npoints);
  537. win_reset_brush(fe);
  538. win_reset_pen(fe);
  539. } else {
  540. win_set_pen(fe, outlinecolour, false);
  541. Polyline(fe->hdc, pts, npoints+1);
  542. win_reset_pen(fe);
  543. }
  544. sfree(pts);
  545. }
  546. static void win_start_draw(void *handle)
  547. {
  548. frontend *fe = (frontend *)handle;
  549. HDC hdc_win;
  550. assert(fe->drawstatus == NOTHING);
  551. hdc_win = GetDC(fe->hwnd);
  552. fe->hdc = CreateCompatibleDC(hdc_win);
  553. fe->prevbm = SelectObject(fe->hdc, fe->bitmap);
  554. ReleaseDC(fe->hwnd, hdc_win);
  555. fe->clip = NULL;
  556. SetMapMode(fe->hdc, MM_TEXT);
  557. fe->drawstatus = DRAWING;
  558. }
  559. static void win_draw_update(void *handle, int x, int y, int w, int h)
  560. {
  561. frontend *fe = (frontend *)handle;
  562. RECT r;
  563. if (fe->drawstatus != DRAWING)
  564. return;
  565. r.left = x;
  566. r.top = y;
  567. r.right = x + w;
  568. r.bottom = y + h;
  569. OffsetRect(&r, fe->bitmapPosition.left, fe->bitmapPosition.top);
  570. InvalidateRect(fe->hwnd, &r, false);
  571. }
  572. static void win_end_draw(void *handle)
  573. {
  574. frontend *fe = (frontend *)handle;
  575. assert(fe->drawstatus == DRAWING);
  576. SelectObject(fe->hdc, fe->prevbm);
  577. DeleteDC(fe->hdc);
  578. if (fe->clip) {
  579. DeleteObject(fe->clip);
  580. fe->clip = NULL;
  581. }
  582. fe->drawstatus = NOTHING;
  583. }
  584. static void win_line_width(void *handle, float width)
  585. {
  586. frontend *fe = (frontend *)handle;
  587. assert(fe->drawstatus != DRAWING);
  588. if (fe->drawstatus == NOTHING)
  589. return;
  590. fe->linewidth = (int)(width * fe->printpixelscale);
  591. }
  592. static void win_line_dotted(void *handle, bool dotted)
  593. {
  594. frontend *fe = (frontend *)handle;
  595. assert(fe->drawstatus != DRAWING);
  596. if (fe->drawstatus == NOTHING)
  597. return;
  598. fe->linedotted = dotted;
  599. }
  600. static void win_begin_doc(void *handle, int pages)
  601. {
  602. frontend *fe = (frontend *)handle;
  603. assert(fe->drawstatus != DRAWING);
  604. if (fe->drawstatus == NOTHING)
  605. return;
  606. if (StartDoc(fe->hdc, &fe->di) <= 0) {
  607. char *e = geterrstr();
  608. MessageBox(fe->hwnd, e, "Error starting to print",
  609. MB_ICONERROR | MB_OK);
  610. sfree(e);
  611. fe->drawstatus = NOTHING;
  612. }
  613. /*
  614. * Push a marker on the font stack so that we won't use the
  615. * same fonts for printing and drawing. (This is because
  616. * drawing seems to look generally better in bold, but printing
  617. * is better not in bold.)
  618. */
  619. fe->fontstart = fe->nfonts;
  620. }
  621. static void win_begin_page(void *handle, int number)
  622. {
  623. frontend *fe = (frontend *)handle;
  624. assert(fe->drawstatus != DRAWING);
  625. if (fe->drawstatus == NOTHING)
  626. return;
  627. if (StartPage(fe->hdc) <= 0) {
  628. char *e = geterrstr();
  629. MessageBox(fe->hwnd, e, "Error starting a page",
  630. MB_ICONERROR | MB_OK);
  631. sfree(e);
  632. fe->drawstatus = NOTHING;
  633. }
  634. }
  635. static void win_begin_puzzle(void *handle, float xm, float xc,
  636. float ym, float yc, int pw, int ph, float wmm)
  637. {
  638. frontend *fe = (frontend *)handle;
  639. int ppw, pph, pox, poy;
  640. float mmpw, mmph, mmox, mmoy;
  641. float scale;
  642. assert(fe->drawstatus != DRAWING);
  643. if (fe->drawstatus == NOTHING)
  644. return;
  645. ppw = GetDeviceCaps(fe->hdc, HORZRES);
  646. pph = GetDeviceCaps(fe->hdc, VERTRES);
  647. mmpw = (float)GetDeviceCaps(fe->hdc, HORZSIZE);
  648. mmph = (float)GetDeviceCaps(fe->hdc, VERTSIZE);
  649. /*
  650. * Compute the puzzle's position on the logical page.
  651. */
  652. mmox = xm * mmpw + xc;
  653. mmoy = ym * mmph + yc;
  654. /*
  655. * Work out what that comes to in pixels.
  656. */
  657. pox = (int)(mmox * (float)ppw / mmpw);
  658. poy = (int)(mmoy * (float)pph / mmph);
  659. /*
  660. * And determine the scale.
  661. *
  662. * I need a scale such that the maximum puzzle-coordinate
  663. * extent of the rectangle (pw * scale) is equal to the pixel
  664. * equivalent of the puzzle's millimetre width (wmm * ppw /
  665. * mmpw).
  666. */
  667. scale = (wmm * ppw) / (mmpw * pw);
  668. /*
  669. * Now store pox, poy and scale for use in the main drawing
  670. * functions.
  671. */
  672. fe->printoffsetx = pox;
  673. fe->printoffsety = poy;
  674. fe->printpixelscale = scale;
  675. fe->linewidth = 1;
  676. fe->linedotted = false;
  677. }
  678. static void win_end_puzzle(void *handle)
  679. {
  680. /* Nothing needs to be done here. */
  681. }
  682. static void win_end_page(void *handle, int number)
  683. {
  684. frontend *fe = (frontend *)handle;
  685. assert(fe->drawstatus != DRAWING);
  686. if (fe->drawstatus == NOTHING)
  687. return;
  688. if (EndPage(fe->hdc) <= 0) {
  689. char *e = geterrstr();
  690. MessageBox(fe->hwnd, e, "Error finishing a page",
  691. MB_ICONERROR | MB_OK);
  692. sfree(e);
  693. fe->drawstatus = NOTHING;
  694. }
  695. }
  696. static void win_end_doc(void *handle)
  697. {
  698. frontend *fe = (frontend *)handle;
  699. assert(fe->drawstatus != DRAWING);
  700. /*
  701. * Free all the fonts created since we began printing.
  702. */
  703. while (fe->nfonts > fe->fontstart) {
  704. fe->nfonts--;
  705. DeleteObject(fe->fonts[fe->nfonts].font);
  706. }
  707. fe->fontstart = 0;
  708. /*
  709. * The MSDN web site sample code doesn't bother to call EndDoc
  710. * if an error occurs half way through printing. I expect doing
  711. * so would cause the erroneous document to actually be
  712. * printed, or something equally undesirable.
  713. */
  714. if (fe->drawstatus == NOTHING)
  715. return;
  716. if (EndDoc(fe->hdc) <= 0) {
  717. char *e = geterrstr();
  718. MessageBox(fe->hwnd, e, "Error finishing printing",
  719. MB_ICONERROR | MB_OK);
  720. sfree(e);
  721. fe->drawstatus = NOTHING;
  722. }
  723. }
  724. char *win_text_fallback(void *handle, const char *const *strings, int nstrings)
  725. {
  726. /*
  727. * We assume Windows can cope with any UTF-8 likely to be
  728. * emitted by a puzzle.
  729. */
  730. return dupstr(strings[0]);
  731. }
  732. const struct drawing_api win_drawing = {
  733. win_draw_text,
  734. win_draw_rect,
  735. win_draw_line,
  736. win_draw_polygon,
  737. win_draw_circle,
  738. win_draw_update,
  739. win_clip,
  740. win_unclip,
  741. win_start_draw,
  742. win_end_draw,
  743. win_status_bar,
  744. win_blitter_new,
  745. win_blitter_free,
  746. win_blitter_save,
  747. win_blitter_load,
  748. win_begin_doc,
  749. win_begin_page,
  750. win_begin_puzzle,
  751. win_end_puzzle,
  752. win_end_page,
  753. win_end_doc,
  754. win_line_width,
  755. win_line_dotted,
  756. win_text_fallback,
  757. };
  758. void print(frontend *fe)
  759. {
  760. PRINTDLG pd;
  761. char doctitle[256];
  762. document *doc;
  763. midend *nme = NULL; /* non-interactive midend for bulk puzzle generation */
  764. int i;
  765. const char *err = NULL;
  766. /*
  767. * Create our document structure and fill it up with puzzles.
  768. */
  769. doc = document_new(fe->printw, fe->printh, fe->printscale / 100.0F);
  770. for (i = 0; i < fe->printcount; i++) {
  771. if (i == 0 && fe->printcurr) {
  772. err = midend_print_puzzle(fe->me, doc, fe->printsolns);
  773. } else {
  774. if (!nme) {
  775. game_params *params;
  776. nme = midend_new(NULL, fe->game, NULL, NULL);
  777. load_prefs(nme);
  778. /*
  779. * Set the non-interactive mid-end to have the same
  780. * parameters as the standard one.
  781. */
  782. params = midend_get_params(fe->me);
  783. midend_set_params(nme, params);
  784. fe->game->free_params(params);
  785. }
  786. midend_new_game(nme);
  787. err = midend_print_puzzle(nme, doc, fe->printsolns);
  788. }
  789. if (err)
  790. break;
  791. }
  792. if (nme)
  793. midend_free(nme);
  794. if (err) {
  795. MessageBox(fe->hwnd, err, "Error preparing puzzles for printing",
  796. MB_ICONERROR | MB_OK);
  797. document_free(doc);
  798. return;
  799. }
  800. memset(&pd, 0, sizeof(pd));
  801. pd.lStructSize = sizeof(pd);
  802. pd.hwndOwner = fe->hwnd;
  803. pd.hDevMode = NULL;
  804. pd.hDevNames = NULL;
  805. pd.Flags = PD_USEDEVMODECOPIESANDCOLLATE | PD_RETURNDC |
  806. PD_NOPAGENUMS | PD_NOSELECTION;
  807. pd.nCopies = 1;
  808. pd.nFromPage = pd.nToPage = 0xFFFF;
  809. pd.nMinPage = pd.nMaxPage = 1;
  810. if (!PrintDlg(&pd)) {
  811. document_free(doc);
  812. return;
  813. }
  814. /*
  815. * Now pd.hDC is a device context for the printer.
  816. */
  817. /*
  818. * FIXME: IWBNI we put up an Abort box here.
  819. */
  820. memset(&fe->di, 0, sizeof(fe->di));
  821. fe->di.cbSize = sizeof(fe->di);
  822. sprintf(doctitle, "Printed puzzles from %s (from Simon Tatham's"
  823. " Portable Puzzle Collection)", fe->game->name);
  824. fe->di.lpszDocName = doctitle;
  825. fe->di.lpszOutput = NULL;
  826. fe->di.lpszDatatype = NULL;
  827. fe->di.fwType = 0;
  828. fe->drawstatus = PRINTING;
  829. fe->hdc = pd.hDC;
  830. fe->dr = drawing_new(&win_drawing, NULL, fe);
  831. document_print(doc, fe->dr);
  832. drawing_free(fe->dr);
  833. fe->dr = NULL;
  834. fe->drawstatus = NOTHING;
  835. DeleteDC(pd.hDC);
  836. document_free(doc);
  837. }
  838. void deactivate_timer(frontend *fe)
  839. {
  840. if (!fe)
  841. return; /* for non-interactive midend */
  842. if (fe->hwnd) KillTimer(fe->hwnd, fe->timer);
  843. fe->timer = 0;
  844. }
  845. void activate_timer(frontend *fe)
  846. {
  847. if (!fe)
  848. return; /* for non-interactive midend */
  849. if (!fe->timer) {
  850. fe->timer = SetTimer(fe->hwnd, 1, 20, NULL);
  851. fe->timer_last_tickcount = GetTickCount();
  852. }
  853. }
  854. void write_clip(HWND hwnd, char *data)
  855. {
  856. HGLOBAL clipdata;
  857. int len, i, j;
  858. char *data2;
  859. void *lock;
  860. /*
  861. * Windows expects CRLF in the clipboard, so we must convert
  862. * any \n that has come out of the puzzle backend.
  863. */
  864. len = 0;
  865. for (i = 0; data[i]; i++) {
  866. if (data[i] == '\n')
  867. len++;
  868. len++;
  869. }
  870. data2 = snewn(len+1, char);
  871. j = 0;
  872. for (i = 0; data[i]; i++) {
  873. if (data[i] == '\n')
  874. data2[j++] = '\r';
  875. data2[j++] = data[i];
  876. }
  877. assert(j == len);
  878. data2[j] = '\0';
  879. clipdata = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, len + 1);
  880. if (!clipdata) {
  881. sfree(data2);
  882. return;
  883. }
  884. lock = GlobalLock(clipdata);
  885. if (!lock) {
  886. GlobalFree(clipdata);
  887. sfree(data2);
  888. return;
  889. }
  890. memcpy(lock, data2, len);
  891. ((unsigned char *) lock)[len] = 0;
  892. GlobalUnlock(clipdata);
  893. if (OpenClipboard(hwnd)) {
  894. EmptyClipboard();
  895. SetClipboardData(CF_TEXT, clipdata);
  896. CloseClipboard();
  897. } else
  898. GlobalFree(clipdata);
  899. sfree(data2);
  900. }
  901. /*
  902. * Set up Help and see if we can find a help file.
  903. */
  904. static void init_help(void)
  905. {
  906. char b[2048], *p, *q, *r;
  907. FILE *fp;
  908. /*
  909. * Find the executable file path, so we can look alongside
  910. * it for help files. Trim the filename off the end.
  911. */
  912. GetModuleFileName(NULL, b, sizeof(b) - 1);
  913. r = b;
  914. p = strrchr(b, '\\');
  915. if (p && p >= r) r = p+1;
  916. q = strrchr(b, ':');
  917. if (q && q >= r) r = q+1;
  918. #ifndef NO_HTMLHELP
  919. /*
  920. * Try HTML Help first.
  921. */
  922. strcpy(r, CHM_FILE_NAME);
  923. if ( (fp = fopen(b, "r")) != NULL) {
  924. fclose(fp);
  925. /*
  926. * We have a .CHM. See if we can use it.
  927. */
  928. hh_dll = LoadLibrary("hhctrl.ocx");
  929. if (hh_dll) {
  930. htmlhelp = (htmlhelp_t)GetProcAddress(hh_dll, "HtmlHelpA");
  931. if (!htmlhelp)
  932. FreeLibrary(hh_dll);
  933. }
  934. if (htmlhelp) {
  935. help_path = dupstr(b);
  936. help_type = CHM;
  937. return;
  938. }
  939. }
  940. #endif /* NO_HTMLHELP */
  941. /*
  942. * Now try old-style .HLP.
  943. */
  944. strcpy(r, HELP_FILE_NAME);
  945. if ( (fp = fopen(b, "r")) != NULL) {
  946. fclose(fp);
  947. help_path = dupstr(b);
  948. help_type = HLP;
  949. /*
  950. * See if there's a .CNT file alongside it.
  951. */
  952. strcpy(r, HELP_CNT_NAME);
  953. if ( (fp = fopen(b, "r")) != NULL) {
  954. fclose(fp);
  955. help_has_contents = true;
  956. } else
  957. help_has_contents = false;
  958. return;
  959. }
  960. help_type = NONE; /* didn't find any */
  961. }
  962. /*
  963. * Start Help.
  964. */
  965. static void start_help(frontend *fe, const char *topic)
  966. {
  967. char *str = NULL;
  968. int cmd;
  969. switch (help_type) {
  970. case HLP:
  971. assert(help_path);
  972. if (topic) {
  973. str = snewn(10+strlen(topic), char);
  974. sprintf(str, "JI(`',`%s')", topic);
  975. cmd = HELP_COMMAND;
  976. } else if (help_has_contents) {
  977. cmd = HELP_FINDER;
  978. } else {
  979. cmd = HELP_CONTENTS;
  980. }
  981. WinHelp(fe->hwnd, help_path, cmd, (ULONG_PTR)str);
  982. fe->help_running = true;
  983. break;
  984. case CHM:
  985. #ifndef NO_HTMLHELP
  986. assert(help_path);
  987. assert(htmlhelp);
  988. if (topic) {
  989. str = snewn(20 + strlen(topic) + strlen(help_path), char);
  990. sprintf(str, "%s::/%s.html>main", help_path, topic);
  991. } else {
  992. str = dupstr(help_path);
  993. }
  994. htmlhelp(fe->hwnd, str, HH_DISPLAY_TOPIC, 0);
  995. fe->help_running = true;
  996. break;
  997. #endif /* NO_HTMLHELP */
  998. case NONE:
  999. assert(!"This shouldn't happen");
  1000. break;
  1001. }
  1002. sfree(str);
  1003. }
  1004. /*
  1005. * Stop Help on window cleanup.
  1006. */
  1007. static void stop_help(frontend *fe)
  1008. {
  1009. if (fe->help_running) {
  1010. switch (help_type) {
  1011. case HLP:
  1012. WinHelp(fe->hwnd, help_path, HELP_QUIT, 0);
  1013. break;
  1014. case CHM:
  1015. #ifndef NO_HTMLHELP
  1016. assert(htmlhelp);
  1017. htmlhelp(NULL, NULL, HH_CLOSE_ALL, 0);
  1018. break;
  1019. #endif /* NO_HTMLHELP */
  1020. case NONE:
  1021. assert(!"This shouldn't happen");
  1022. break;
  1023. }
  1024. fe->help_running = false;
  1025. }
  1026. }
  1027. /*
  1028. * Terminate Help on process exit.
  1029. */
  1030. static void cleanup_help(void)
  1031. {
  1032. /* Nothing to do currently.
  1033. * (If we were running HTML Help single-threaded, this is where we'd
  1034. * call HH_UNINITIALIZE.) */
  1035. }
  1036. static int get_statusbar_height(frontend *fe)
  1037. {
  1038. int sy;
  1039. if (fe->statusbar) {
  1040. RECT sr;
  1041. GetWindowRect(fe->statusbar, &sr);
  1042. sy = sr.bottom - sr.top;
  1043. } else {
  1044. sy = 0;
  1045. }
  1046. return sy;
  1047. }
  1048. static void adjust_statusbar(frontend *fe, RECT *r)
  1049. {
  1050. int sy;
  1051. if (!fe->statusbar) return;
  1052. sy = get_statusbar_height(fe);
  1053. SetWindowPos(fe->statusbar, NULL, 0, r->bottom-r->top-sy, r->right-r->left,
  1054. sy, SWP_NOZORDER);
  1055. }
  1056. static void get_menu_size(HWND wh, RECT *r)
  1057. {
  1058. HMENU bar = GetMenu(wh);
  1059. RECT rect;
  1060. int i;
  1061. SetRect(r, 0, 0, 0, 0);
  1062. for (i = 0; i < GetMenuItemCount(bar); i++) {
  1063. GetMenuItemRect(wh, bar, i, &rect);
  1064. UnionRect(r, r, &rect);
  1065. }
  1066. }
  1067. /*
  1068. * Given a proposed new puzzle size (cx,cy), work out the actual
  1069. * puzzle size that would be (px,py) and the window size including
  1070. * furniture (wx,wy).
  1071. */
  1072. static bool check_window_resize(frontend *fe, int cx, int cy,
  1073. int *px, int *py, int *wx, int *wy)
  1074. {
  1075. RECT r;
  1076. int x, y, sy = get_statusbar_height(fe);
  1077. bool changed = false;
  1078. /* disallow making window thinner than menu bar */
  1079. x = max(cx, fe->xmin);
  1080. y = max(cy - sy, fe->ymin);
  1081. /*
  1082. * See if we actually got the window size we wanted, and adjust
  1083. * the puzzle size if not.
  1084. */
  1085. midend_size(fe->me, &x, &y, true, 1.0);
  1086. if (x != cx || y != cy) {
  1087. /*
  1088. * Resize the window, now we know what size we _really_
  1089. * want it to be.
  1090. */
  1091. r.left = r.top = 0;
  1092. r.right = x;
  1093. r.bottom = y + sy;
  1094. AdjustWindowRectEx(&r, WINFLAGS, true, 0);
  1095. *wx = r.right - r.left;
  1096. *wy = r.bottom - r.top;
  1097. changed = true;
  1098. }
  1099. *px = x;
  1100. *py = y;
  1101. fe->puzz_scale =
  1102. (float)midend_tilesize(fe->me) / (float)fe->game->preferred_tilesize;
  1103. return changed;
  1104. }
  1105. /*
  1106. * Given the current window size, make sure it's sane for the
  1107. * current puzzle and resize if necessary.
  1108. */
  1109. static void check_window_size(frontend *fe, int *px, int *py)
  1110. {
  1111. RECT r;
  1112. int wx, wy, cx, cy;
  1113. GetClientRect(fe->hwnd, &r);
  1114. cx = r.right - r.left;
  1115. cy = r.bottom - r.top;
  1116. if (check_window_resize(fe, cx, cy, px, py, &wx, &wy))
  1117. SetWindowPos(fe->hwnd, NULL, 0, 0, wx, wy, SWP_NOMOVE | SWP_NOZORDER);
  1118. GetClientRect(fe->hwnd, &r);
  1119. adjust_statusbar(fe, &r);
  1120. }
  1121. static void get_max_puzzle_size(frontend *fe, int *x, int *y)
  1122. {
  1123. RECT r, sr;
  1124. if (SystemParametersInfo(SPI_GETWORKAREA, 0, &sr, false)) {
  1125. *x = sr.right - sr.left;
  1126. *y = sr.bottom - sr.top;
  1127. r.left = 100;
  1128. r.right = 200;
  1129. r.top = 100;
  1130. r.bottom = 200;
  1131. AdjustWindowRectEx(&r, WINFLAGS, true, 0);
  1132. *x -= r.right - r.left - 100;
  1133. *y -= r.bottom - r.top - 100;
  1134. } else {
  1135. *x = *y = INT_MAX;
  1136. }
  1137. if (fe->statusbar != NULL) {
  1138. GetWindowRect(fe->statusbar, &sr);
  1139. *y -= sr.bottom - sr.top;
  1140. }
  1141. }
  1142. /*
  1143. * Allocate a new frontend structure and create its main window.
  1144. */
  1145. static frontend *frontend_new(HINSTANCE inst)
  1146. {
  1147. frontend *fe;
  1148. const char *nogame = "Puzzles (no game selected)";
  1149. fe = snew(frontend);
  1150. fe->inst = inst;
  1151. fe->game = NULL;
  1152. fe->me = NULL;
  1153. fe->timer = 0;
  1154. fe->hwnd = NULL;
  1155. fe->help_running = false;
  1156. fe->drawstatus = NOTHING;
  1157. fe->dr = NULL;
  1158. fe->fontstart = 0;
  1159. fe->fonts = NULL;
  1160. fe->nfonts = fe->fontsize = 0;
  1161. fe->colours = NULL;
  1162. fe->brushes = NULL;
  1163. fe->pens = NULL;
  1164. fe->puzz_scale = 1.0;
  1165. fe->hwnd = CreateWindowEx(0, CLASSNAME, nogame,
  1166. WS_OVERLAPPEDWINDOW &~
  1167. (WS_MAXIMIZEBOX),
  1168. CW_USEDEFAULT, CW_USEDEFAULT,
  1169. CW_USEDEFAULT, CW_USEDEFAULT,
  1170. NULL, NULL, inst, NULL);
  1171. if (!fe->hwnd) {
  1172. DWORD lerr = GetLastError();
  1173. printf("no window: 0x%x\n", (unsigned)lerr);
  1174. }
  1175. fe->gamemenu = NULL;
  1176. fe->preset_menu = NULL;
  1177. fe->statusbar = NULL;
  1178. fe->bitmap = NULL;
  1179. SetWindowLongPtr(fe->hwnd, GWLP_USERDATA, (LONG_PTR)fe);
  1180. return fe;
  1181. }
  1182. static void savefile_write(void *wctx, const void *buf, int len)
  1183. {
  1184. FILE *fp = (FILE *)wctx;
  1185. fwrite(buf, 1, len, fp);
  1186. }
  1187. static bool savefile_read(void *wctx, void *buf, int len)
  1188. {
  1189. FILE *fp = (FILE *)wctx;
  1190. int ret;
  1191. ret = fread(buf, 1, len, fp);
  1192. return (ret == len);
  1193. }
  1194. /*
  1195. * Create an appropriate midend structure to go in a puzzle window,
  1196. * given a game type and/or a command-line argument.
  1197. *
  1198. * 'arg' can be either a game ID string (descriptive, random, or a
  1199. * plain set of parameters) or the filename of a save file. The two
  1200. * boolean flag arguments indicate which possibilities are
  1201. * permissible.
  1202. */
  1203. static midend *midend_for_new_game(frontend *fe, const game *cgame,
  1204. char *arg, bool maybe_game_id,
  1205. bool maybe_save_file, char **error)
  1206. {
  1207. midend *me = NULL;
  1208. if (!arg) {
  1209. if (me) midend_free(me);
  1210. me = midend_new(fe, cgame, &win_drawing, fe);
  1211. load_prefs(me);
  1212. midend_new_game(me);
  1213. } else {
  1214. FILE *fp;
  1215. const char *err_param, *err_load;
  1216. /*
  1217. * See if arg is a valid filename of a save game file.
  1218. */
  1219. err_load = NULL;
  1220. if (maybe_save_file && (fp = fopen(arg, "r")) != NULL) {
  1221. const game *loadgame;
  1222. #ifdef COMBINED
  1223. /*
  1224. * Find out what kind of game is stored in the save
  1225. * file; if we're going to end up loading that, it
  1226. * will have to override our caller's judgment as to
  1227. * what game to initialise our midend with.
  1228. */
  1229. char *id_name;
  1230. err_load = identify_game(&id_name, savefile_read, fp);
  1231. if (!err_load) {
  1232. int i;
  1233. for (i = 0; i < gamecount; i++)
  1234. if (!strcmp(id_name, gamelist[i]->name))
  1235. break;
  1236. if (i == gamecount) {
  1237. err_load = "Save file is for a game not supported by"
  1238. " this program";
  1239. } else {
  1240. loadgame = gamelist[i];
  1241. rewind(fp); /* go back to the start for actual load */
  1242. }
  1243. }
  1244. #else
  1245. loadgame = cgame;
  1246. #endif
  1247. if (!err_load) {
  1248. if (me) midend_free(me);
  1249. me = midend_new(fe, loadgame, &win_drawing, fe);
  1250. load_prefs(me);
  1251. err_load = midend_deserialise(me, savefile_read, fp);
  1252. }
  1253. } else {
  1254. err_load = "Unable to open file";
  1255. }
  1256. if (maybe_game_id && (!maybe_save_file || err_load)) {
  1257. /*
  1258. * See if arg is a game description.
  1259. */
  1260. if (me) midend_free(me);
  1261. me = midend_new(fe, cgame, &win_drawing, fe);
  1262. load_prefs(me);
  1263. err_param = midend_game_id(me, arg);
  1264. if (!err_param) {
  1265. midend_new_game(me);
  1266. } else {
  1267. if (maybe_save_file) {
  1268. *error = snewn(256 + strlen(arg) + strlen(err_param) +
  1269. strlen(err_load), char);
  1270. sprintf(*error, "Supplied argument \"%s\" is neither a"
  1271. " game ID (%s) nor a save file (%s)",
  1272. arg, err_param, err_load);
  1273. } else {
  1274. *error = dupstr(err_param);
  1275. }
  1276. midend_free(me);
  1277. sfree(fe);
  1278. return NULL;
  1279. }
  1280. } else if (err_load) {
  1281. *error = dupstr(err_load);
  1282. midend_free(me);
  1283. sfree(fe);
  1284. return NULL;
  1285. }
  1286. }
  1287. return me;
  1288. }
  1289. static void populate_preset_menu(frontend *fe,
  1290. struct preset_menu *menu, HMENU winmenu)
  1291. {
  1292. int i;
  1293. for (i = 0; i < menu->n_entries; i++) {
  1294. struct preset_menu_entry *entry = &menu->entries[i];
  1295. UINT_PTR id_or_sub;
  1296. UINT flags = MF_ENABLED;
  1297. if (entry->params) {
  1298. id_or_sub = (UINT_PTR)(
  1299. IDM_PRESET_BASE + MENUITEM_STEP * entry->id);
  1300. fe->preset_menuitems[entry->id].which_menu = winmenu;
  1301. fe->preset_menuitems[entry->id].item_index =
  1302. GetMenuItemCount(winmenu);
  1303. } else {
  1304. HMENU winsubmenu = CreateMenu();
  1305. id_or_sub = (UINT_PTR)winsubmenu;
  1306. flags |= MF_POPUP;
  1307. populate_preset_menu(fe, entry->submenu, winsubmenu);
  1308. }
  1309. /*
  1310. * FIXME: we ought to go through and do something with ampersands
  1311. * here.
  1312. */
  1313. AppendMenu(winmenu, flags, id_or_sub, entry->title);
  1314. }
  1315. }
  1316. /*
  1317. * Populate a frontend structure with a new midend structure, and
  1318. * create any window furniture that it needs.
  1319. *
  1320. * Previously-allocated memory and window furniture will be freed by
  1321. * this function.
  1322. *
  1323. */
  1324. static int fe_set_midend(frontend *fe, midend *me)
  1325. {
  1326. int x, y;
  1327. RECT r;
  1328. if (fe->me) {
  1329. midend_free(fe->me);
  1330. fe->preset_menu = NULL;
  1331. sfree(fe->preset_menuitems);
  1332. }
  1333. fe->me = me;
  1334. fe->game = midend_which_game(fe->me);
  1335. {
  1336. int i, ncolours;
  1337. float *colours;
  1338. colours = midend_colours(fe->me, &ncolours);
  1339. if (fe->colours) sfree(fe->colours);
  1340. if (fe->brushes) sfree(fe->brushes);
  1341. if (fe->pens) sfree(fe->pens);
  1342. fe->colours = snewn(ncolours, COLORREF);
  1343. fe->brushes = snewn(ncolours, HBRUSH);
  1344. fe->pens = snewn(ncolours, HPEN);
  1345. for (i = 0; i < ncolours; i++) {
  1346. fe->colours[i] = RGB(255 * colours[i*3+0],
  1347. 255 * colours[i*3+1],
  1348. 255 * colours[i*3+2]);
  1349. fe->brushes[i] = CreateSolidBrush(fe->colours[i]);
  1350. fe->pens[i] = CreatePen(PS_SOLID, 1, fe->colours[i]);
  1351. }
  1352. sfree(colours);
  1353. }
  1354. if (fe->statusbar)
  1355. DestroyWindow(fe->statusbar);
  1356. if (midend_wants_statusbar(fe->me)) {
  1357. fe->statusbar = CreateWindowEx(0, STATUSCLASSNAME,
  1358. TEXT(DEFAULT_STATUSBAR_TEXT),
  1359. WS_CHILD | WS_VISIBLE,
  1360. 0, 0, 0, 0, /* status bar does these */
  1361. NULL, NULL, fe->inst, NULL);
  1362. } else
  1363. fe->statusbar = NULL;
  1364. get_max_puzzle_size(fe, &x, &y);
  1365. midend_size(fe->me, &x, &y, false, 1.0);
  1366. r.left = r.top = 0;
  1367. r.right = x;
  1368. r.bottom = y;
  1369. AdjustWindowRectEx(&r, WINFLAGS, true, 0);
  1370. SetWindowText(fe->hwnd, fe->game->name);
  1371. if (fe->statusbar)
  1372. DestroyWindow(fe->statusbar);
  1373. if (midend_wants_statusbar(fe->me)) {
  1374. RECT sr;
  1375. fe->statusbar = CreateWindowEx(0, STATUSCLASSNAME, TEXT("ooh"),
  1376. WS_CHILD | WS_VISIBLE,
  1377. 0, 0, 0, 0, /* status bar does these */
  1378. fe->hwnd, NULL, fe->inst, NULL);
  1379. /*
  1380. * Now resize the window to take account of the status bar.
  1381. */
  1382. GetWindowRect(fe->statusbar, &sr);
  1383. GetWindowRect(fe->hwnd, &r);
  1384. SetWindowPos(fe->hwnd, NULL, 0, 0, r.right - r.left,
  1385. r.bottom - r.top + sr.bottom - sr.top,
  1386. SWP_NOMOVE | SWP_NOZORDER);
  1387. } else {
  1388. fe->statusbar = NULL;
  1389. }
  1390. {
  1391. HMENU oldmenu = GetMenu(fe->hwnd);
  1392. HMENU bar = CreateMenu();
  1393. HMENU menu = CreateMenu();
  1394. RECT menusize;
  1395. AppendMenu(bar, MF_ENABLED|MF_POPUP, (UINT_PTR)menu, "&Game");
  1396. fe->gamemenu = menu;
  1397. AppendMenu(menu, MF_ENABLED, IDM_NEW, TEXT("&New"));
  1398. AppendMenu(menu, MF_ENABLED, IDM_RESTART, TEXT("&Restart"));
  1399. /* ...here I run out of sensible accelerator characters. */
  1400. AppendMenu(menu, MF_ENABLED, IDM_DESC, TEXT("Speci&fic..."));
  1401. AppendMenu(menu, MF_ENABLED, IDM_SEED, TEXT("Rando&m Seed..."));
  1402. assert(!fe->preset_menu);
  1403. fe->preset_menu = midend_get_presets(
  1404. fe->me, &fe->n_preset_menuitems);
  1405. fe->preset_menuitems = snewn(fe->n_preset_menuitems,
  1406. struct preset_menuitemref);
  1407. {
  1408. int i;
  1409. for (i = 0; i < fe->n_preset_menuitems; i++)
  1410. fe->preset_menuitems[i].which_menu = NULL;
  1411. }
  1412. if (fe->preset_menu->n_entries > 0 || fe->game->can_configure) {
  1413. HMENU sub = CreateMenu();
  1414. AppendMenu(bar, MF_ENABLED|MF_POPUP, (UINT_PTR)sub, "&Type");
  1415. populate_preset_menu(fe, fe->preset_menu, sub);
  1416. if (fe->game->can_configure) {
  1417. AppendMenu(sub, MF_ENABLED, IDM_CONFIG, TEXT("&Custom..."));
  1418. }
  1419. fe->typemenu = sub;
  1420. } else {
  1421. fe->typemenu = INVALID_HANDLE_VALUE;
  1422. }
  1423. #ifdef COMBINED
  1424. {
  1425. HMENU games = CreateMenu();
  1426. int i;
  1427. AppendMenu(menu, MF_SEPARATOR, 0, 0);
  1428. AppendMenu(menu, MF_ENABLED|MF_POPUP, (UINT_PTR)games, "&Other");
  1429. for (i = 0; i < gamecount; i++) {
  1430. if (strcmp(gamelist[i]->name, fe->game->name) != 0) {
  1431. /* only include those games that aren't the same as the
  1432. * game we're currently playing. */
  1433. AppendMenu(games, MF_ENABLED,
  1434. IDM_GAME_BASE + MENUITEM_STEP * i,
  1435. gamelist[i]->name);
  1436. }
  1437. }
  1438. }
  1439. #endif
  1440. AppendMenu(menu, MF_SEPARATOR, 0, 0);
  1441. AppendMenu(menu, MF_ENABLED, IDM_LOAD, TEXT("&Load..."));
  1442. AppendMenu(menu, MF_ENABLED, IDM_SAVE, TEXT("&Save..."));
  1443. AppendMenu(menu, MF_SEPARATOR, 0, 0);
  1444. if (fe->game->can_print) {
  1445. AppendMenu(menu, MF_ENABLED, IDM_PRINT, TEXT("&Print..."));
  1446. AppendMenu(menu, MF_SEPARATOR, 0, 0);
  1447. }
  1448. AppendMenu(menu, MF_ENABLED, IDM_UNDO, TEXT("Undo"));
  1449. AppendMenu(menu, MF_ENABLED, IDM_REDO, TEXT("Redo"));
  1450. if (fe->game->can_format_as_text_ever) {
  1451. AppendMenu(menu, MF_SEPARATOR, 0, 0);
  1452. AppendMenu(menu, MF_ENABLED, IDM_COPY, TEXT("&Copy"));
  1453. }
  1454. if (fe->game->can_solve) {
  1455. AppendMenu(menu, MF_SEPARATOR, 0, 0);
  1456. AppendMenu(menu, MF_ENABLED, IDM_SOLVE, TEXT("Sol&ve"));
  1457. }
  1458. AppendMenu(menu, MF_SEPARATOR, 0, 0);
  1459. AppendMenu(menu, MF_ENABLED, IDM_PREFS, TEXT("Pre&ferences"));
  1460. AppendMenu(menu, MF_SEPARATOR, 0, 0);
  1461. AppendMenu(menu, MF_ENABLED, IDM_QUIT, TEXT("E&xit"));
  1462. menu = CreateMenu();
  1463. AppendMenu(bar, MF_ENABLED|MF_POPUP, (UINT_PTR)menu, TEXT("&Help"));
  1464. AppendMenu(menu, MF_ENABLED, IDM_ABOUT, TEXT("&About"));
  1465. if (help_type != NONE) {
  1466. char *item;
  1467. AppendMenu(menu, MF_SEPARATOR, 0, 0);
  1468. AppendMenu(menu, MF_ENABLED, IDM_HELPC, TEXT("&Contents"));
  1469. assert(fe->game->name);
  1470. item = snewn(10+strlen(fe->game->name), char); /*ick*/
  1471. sprintf(item, "&Help on %s", fe->game->name);
  1472. AppendMenu(menu, MF_ENABLED, IDM_GAMEHELP, item);
  1473. sfree(item);
  1474. }
  1475. DestroyMenu(oldmenu);
  1476. SetMenu(fe->hwnd, bar);
  1477. get_menu_size(fe->hwnd, &menusize);
  1478. fe->xmin = (menusize.right - menusize.left) + 25;
  1479. }
  1480. if (fe->bitmap) DeleteObject(fe->bitmap);
  1481. fe->bitmap = NULL;
  1482. new_game_size(fe, fe->puzz_scale); /* initialises fe->bitmap */
  1483. return 0;
  1484. }
  1485. static void show_window(frontend *fe)
  1486. {
  1487. ShowWindow(fe->hwnd, SW_SHOWNORMAL);
  1488. SetForegroundWindow(fe->hwnd);
  1489. update_type_menu_tick(fe);
  1490. update_copy_menu_greying(fe);
  1491. midend_redraw(fe->me);
  1492. }
  1493. static int CALLBACK AboutDlgProc(HWND hwnd, UINT msg,
  1494. WPARAM wParam, LPARAM lParam)
  1495. {
  1496. frontend *fe = (frontend *)GetWindowLongPtr(hwnd, GWLP_USERDATA);
  1497. switch (msg) {
  1498. case WM_INITDIALOG:
  1499. return 1;
  1500. case WM_COMMAND:
  1501. if (LOWORD(wParam) == IDOK)
  1502. fe->dlg_done = 1;
  1503. return 0;
  1504. case WM_CLOSE:
  1505. fe->dlg_done = 1;
  1506. return 0;
  1507. }
  1508. return 0;
  1509. }
  1510. /*
  1511. * Wrappers on midend_{get,set}_config, which extend the CFG_*
  1512. * enumeration to add CFG_PRINT.
  1513. */
  1514. static config_item *frontend_get_config(frontend *fe, int which,
  1515. char **wintitle)
  1516. {
  1517. if (which < CFG_FRONTEND_SPECIFIC) {
  1518. return midend_get_config(fe->me, which, wintitle);
  1519. } else if (which == CFG_PRINT) {
  1520. config_item *ret;
  1521. int i;
  1522. *wintitle = snewn(40 + strlen(fe->game->name), char);
  1523. sprintf(*wintitle, "%s print setup", fe->game->name);
  1524. ret = snewn(8, config_item);
  1525. i = 0;
  1526. ret[i].name = "Number of puzzles to print";
  1527. ret[i].type = C_STRING;
  1528. ret[i].u.string.sval = dupstr("1");
  1529. i++;
  1530. ret[i].name = "Number of puzzles across the page";
  1531. ret[i].type = C_STRING;
  1532. ret[i].u.string.sval = dupstr("1");
  1533. i++;
  1534. ret[i].name = "Number of puzzles down the page";
  1535. ret[i].type = C_STRING;
  1536. ret[i].u.string.sval = dupstr("1");
  1537. i++;
  1538. ret[i].name = "Percentage of standard size";
  1539. ret[i].type = C_STRING;
  1540. ret[i].u.string.sval = dupstr("100.0");
  1541. i++;
  1542. ret[i].name = "Include currently shown puzzle";
  1543. ret[i].type = C_BOOLEAN;
  1544. ret[i].u.boolean.bval = true;
  1545. i++;
  1546. ret[i].name = "Print solutions";
  1547. ret[i].type = C_BOOLEAN;
  1548. ret[i].u.boolean.bval = false;
  1549. i++;
  1550. if (fe->game->can_print_in_colour) {
  1551. ret[i].name = "Print in colour";
  1552. ret[i].type = C_BOOLEAN;
  1553. ret[i].u.boolean.bval = false;
  1554. i++;
  1555. }
  1556. ret[i].name = NULL;
  1557. ret[i].type = C_END;
  1558. i++;
  1559. return ret;
  1560. } else {
  1561. assert(!"We should never get here");
  1562. return NULL;
  1563. }
  1564. }
  1565. static const char *frontend_set_config(
  1566. frontend *fe, int which, config_item *cfg)
  1567. {
  1568. if (which < CFG_FRONTEND_SPECIFIC) {
  1569. return midend_set_config(fe->me, which, cfg);
  1570. } else if (which == CFG_PRINT) {
  1571. if ((fe->printcount = atoi(cfg[0].u.string.sval)) <= 0)
  1572. return "Number of puzzles to print should be at least one";
  1573. if ((fe->printw = atoi(cfg[1].u.string.sval)) <= 0)
  1574. return "Number of puzzles across the page should be at least one";
  1575. if ((fe->printh = atoi(cfg[2].u.string.sval)) <= 0)
  1576. return "Number of puzzles down the page should be at least one";
  1577. if ((fe->printscale = (float)atof(cfg[3].u.string.sval)) <= 0)
  1578. return "Print size should be positive";
  1579. fe->printcurr = cfg[4].u.boolean.bval;
  1580. fe->printsolns = cfg[5].u.boolean.bval;
  1581. fe->printcolour = fe->game->can_print_in_colour &&
  1582. cfg[6].u.boolean.bval;
  1583. return NULL;
  1584. } else {
  1585. assert(!"We should never get here");
  1586. return "Internal error";
  1587. }
  1588. }
  1589. static int CALLBACK ConfigDlgProc(HWND hwnd, UINT msg,
  1590. WPARAM wParam, LPARAM lParam)
  1591. {
  1592. frontend *fe = (frontend *)GetWindowLongPtr(hwnd, GWLP_USERDATA);
  1593. config_item *i;
  1594. struct cfg_aux *j;
  1595. switch (msg) {
  1596. case WM_INITDIALOG:
  1597. return 1;
  1598. case WM_COMMAND:
  1599. /*
  1600. * OK and Cancel are special cases.
  1601. */
  1602. if ((LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)) {
  1603. if (LOWORD(wParam) == IDOK) {
  1604. const char *err = frontend_set_config(
  1605. fe, fe->cfg_which, fe->cfg);
  1606. if (err) {
  1607. MessageBox(hwnd, err, "Validation error",
  1608. MB_ICONERROR | MB_OK);
  1609. } else {
  1610. fe->dlg_done = 2;
  1611. }
  1612. } else {
  1613. fe->dlg_done = 1;
  1614. }
  1615. return 0;
  1616. }
  1617. /*
  1618. * First find the control whose id this is.
  1619. */
  1620. for (i = fe->cfg, j = fe->cfgaux; i->type != C_END; i++, j++) {
  1621. if (j->ctlid == LOWORD(wParam))
  1622. break;
  1623. }
  1624. if (i->type == C_END)
  1625. return 0; /* not our problem */
  1626. if (i->type == C_STRING && HIWORD(wParam) == EN_CHANGE) {
  1627. char buffer[4096];
  1628. GetDlgItemText(fe->cfgbox, j->ctlid, buffer, lenof(buffer));
  1629. buffer[lenof(buffer)-1] = '\0';
  1630. sfree(i->u.string.sval);
  1631. i->u.string.sval = dupstr(buffer);
  1632. } else if (i->type == C_BOOLEAN &&
  1633. (HIWORD(wParam) == BN_CLICKED ||
  1634. HIWORD(wParam) == BN_DBLCLK)) {
  1635. i->u.boolean.bval = IsDlgButtonChecked(fe->cfgbox, j->ctlid);
  1636. } else if (i->type == C_CHOICES &&
  1637. HIWORD(wParam) == CBN_SELCHANGE) {
  1638. i->u.choices.selected = SendDlgItemMessage(fe->cfgbox, j->ctlid,
  1639. CB_GETCURSEL, 0, 0);
  1640. }
  1641. return 0;
  1642. case WM_CLOSE:
  1643. fe->dlg_done = 1;
  1644. return 0;
  1645. }
  1646. return 0;
  1647. }
  1648. HWND mkctrl(frontend *fe, int x1, int x2, int y1, int y2,
  1649. char *wclass, int wstyle,
  1650. int exstyle, const char *wtext, INT_PTR wid)
  1651. {
  1652. HWND ret;
  1653. ret = CreateWindowEx(exstyle, wclass, wtext,
  1654. wstyle | WS_CHILD | WS_VISIBLE, x1, y1, x2-x1, y2-y1,
  1655. fe->cfgbox, (HMENU) wid, fe->inst, NULL);
  1656. SendMessage(ret, WM_SETFONT, (WPARAM)fe->cfgfont, MAKELPARAM(true, 0));
  1657. return ret;
  1658. }
  1659. static void about(frontend *fe)
  1660. {
  1661. int i;
  1662. WNDCLASS wc;
  1663. MSG msg;
  1664. TEXTMETRIC tm;
  1665. HDC hdc;
  1666. HFONT oldfont;
  1667. SIZE size;
  1668. int gm, id;
  1669. int winwidth, winheight, y;
  1670. int height, width, maxwid;
  1671. const char *strings[16];
  1672. int lengths[16];
  1673. int nstrings = 0;
  1674. char titlebuf[512];
  1675. sprintf(titlebuf, "About %.250s", fe->game->name);
  1676. strings[nstrings++] = fe->game->name;
  1677. strings[nstrings++] = "from Simon Tatham's Portable Puzzle Collection";
  1678. strings[nstrings++] = ver;
  1679. wc.style = CS_DBLCLKS | CS_SAVEBITS;
  1680. wc.lpfnWndProc = DefDlgProc;
  1681. wc.cbClsExtra = 0;
  1682. wc.cbWndExtra = DLGWINDOWEXTRA + 8;
  1683. wc.hInstance = fe->inst;
  1684. wc.hIcon = NULL;
  1685. wc.hCursor = LoadCursor(NULL, IDC_ARROW);
  1686. wc.hbrBackground = (HBRUSH) (COLOR_BACKGROUND +1);
  1687. wc.lpszMenuName = NULL;
  1688. wc.lpszClassName = "GameAboutBox";
  1689. RegisterClass(&wc);
  1690. hdc = GetDC(fe->hwnd);
  1691. SetMapMode(hdc, MM_TEXT);
  1692. fe->dlg_done = 0;
  1693. fe->cfgfont = CreateFont(-MulDiv(8, GetDeviceCaps(hdc, LOGPIXELSY), 72),
  1694. 0, 0, 0, 0,
  1695. false, false, false, DEFAULT_CHARSET,
  1696. OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
  1697. DEFAULT_QUALITY,
  1698. FF_SWISS,
  1699. "MS Shell Dlg");
  1700. oldfont = SelectObject(hdc, fe->cfgfont);
  1701. if (GetTextMetrics(hdc, &tm)) {
  1702. height = tm.tmAscent + tm.tmDescent;
  1703. width = tm.tmAveCharWidth;
  1704. } else {
  1705. height = width = 30;
  1706. }
  1707. /*
  1708. * Figure out the layout of the About box by measuring the
  1709. * length of each piece of text.
  1710. */
  1711. maxwid = 0;
  1712. winheight = height/2;
  1713. for (i = 0; i < nstrings; i++) {
  1714. if (GetTextExtentPoint32(hdc, strings[i], strlen(strings[i]), &size))
  1715. lengths[i] = size.cx;
  1716. else
  1717. lengths[i] = 0; /* *shrug* */
  1718. if (maxwid < lengths[i])
  1719. maxwid = lengths[i];
  1720. winheight += height * 3 / 2 + (height / 2);
  1721. }
  1722. winheight += height + height * 7 / 4; /* OK button */
  1723. winwidth = maxwid + 4*width;
  1724. SelectObject(hdc, oldfont);
  1725. ReleaseDC(fe->hwnd, hdc);
  1726. /*
  1727. * Create the dialog, now that we know its size.
  1728. */
  1729. {
  1730. RECT r, r2;
  1731. r.left = r.top = 0;
  1732. r.right = winwidth;
  1733. r.bottom = winheight;
  1734. AdjustWindowRectEx(&r, (WS_OVERLAPPEDWINDOW /*|
  1735. DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
  1736. WS_CAPTION | WS_SYSMENU*/) &~
  1737. (WS_MAXIMIZEBOX | WS_OVERLAPPED),
  1738. false, 0);
  1739. /*
  1740. * Centre the dialog on its parent window.
  1741. */
  1742. r.right -= r.left;
  1743. r.bottom -= r.top;
  1744. GetWindowRect(fe->hwnd, &r2);
  1745. r.left = (r2.left + r2.right - r.right) / 2;
  1746. r.top = (r2.top + r2.bottom - r.bottom) / 2;
  1747. r.right += r.left;
  1748. r.bottom += r.top;
  1749. fe->cfgbox = CreateWindowEx(0, wc.lpszClassName, titlebuf,
  1750. DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
  1751. WS_CAPTION | WS_SYSMENU,
  1752. r.left, r.top,
  1753. r.right-r.left, r.bottom-r.top,
  1754. fe->hwnd, NULL, fe->inst, NULL);
  1755. }
  1756. SendMessage(fe->cfgbox, WM_SETFONT, (WPARAM)fe->cfgfont, false);
  1757. SetWindowLongPtr(fe->cfgbox, GWLP_USERDATA, (LONG_PTR)fe);
  1758. SetWindowLongPtr(fe->cfgbox, DWLP_DLGPROC, (LONG_PTR)AboutDlgProc);
  1759. id = 1000;
  1760. y = height/2;
  1761. for (i = 0; i < nstrings; i++) {
  1762. int border = width*2 + (maxwid - lengths[i]) / 2;
  1763. mkctrl(fe, border, border+lengths[i], y+height*1/8, y+height*9/8,
  1764. "Static", 0, 0, strings[i], id++);
  1765. y += height*3/2;
  1766. assert(y < winheight);
  1767. y += height/2;
  1768. }
  1769. y += height/2; /* extra space before OK */
  1770. mkctrl(fe, width*2, maxwid+width*2, y, y+height*7/4, "BUTTON",
  1771. BS_PUSHBUTTON | WS_TABSTOP | BS_DEFPUSHBUTTON, 0,
  1772. "OK", IDOK);
  1773. SendMessage(fe->cfgbox, WM_INITDIALOG, 0, 0);
  1774. EnableWindow(fe->hwnd, false);
  1775. ShowWindow(fe->cfgbox, SW_SHOWNORMAL);
  1776. while ((gm=GetMessage(&msg, NULL, 0, 0)) > 0) {
  1777. if (!IsDialogMessage(fe->cfgbox, &msg))
  1778. DispatchMessage(&msg);
  1779. if (fe->dlg_done)
  1780. break;
  1781. }
  1782. EnableWindow(fe->hwnd, true);
  1783. SetForegroundWindow(fe->hwnd);
  1784. DestroyWindow(fe->cfgbox);
  1785. DeleteObject(fe->cfgfont);
  1786. }
  1787. static bool get_config(frontend *fe, int which)
  1788. {
  1789. config_item *i;
  1790. struct cfg_aux *j;
  1791. char *title;
  1792. WNDCLASS wc;
  1793. MSG msg;
  1794. TEXTMETRIC tm;
  1795. HDC hdc;
  1796. HFONT oldfont;
  1797. SIZE size;
  1798. HWND ctl;
  1799. int gm, id, nctrls;
  1800. int winwidth, winheight, col1l, col1r, col2l, col2r, y;
  1801. int height, width, maxlabel, maxcheckbox;
  1802. wc.style = CS_DBLCLKS | CS_SAVEBITS;
  1803. wc.lpfnWndProc = DefDlgProc;
  1804. wc.cbClsExtra = 0;
  1805. wc.cbWndExtra = DLGWINDOWEXTRA + 8;
  1806. wc.hInstance = fe->inst;
  1807. wc.hIcon = NULL;
  1808. wc.hCursor = LoadCursor(NULL, IDC_ARROW);
  1809. wc.hbrBackground = (HBRUSH) (COLOR_BACKGROUND +1);
  1810. wc.lpszMenuName = NULL;
  1811. wc.lpszClassName = "GameConfigBox";
  1812. RegisterClass(&wc);
  1813. hdc = GetDC(fe->hwnd);
  1814. SetMapMode(hdc, MM_TEXT);
  1815. fe->dlg_done = 0;
  1816. fe->cfgfont = CreateFont(-MulDiv(8, GetDeviceCaps(hdc, LOGPIXELSY), 72),
  1817. 0, 0, 0, 0,
  1818. false, false, false, DEFAULT_CHARSET,
  1819. OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
  1820. DEFAULT_QUALITY,
  1821. FF_SWISS,
  1822. "MS Shell Dlg");
  1823. oldfont = SelectObject(hdc, fe->cfgfont);
  1824. if (GetTextMetrics(hdc, &tm)) {
  1825. height = tm.tmAscent + tm.tmDescent;
  1826. width = tm.tmAveCharWidth;
  1827. } else {
  1828. height = width = 30;
  1829. }
  1830. fe->cfg = frontend_get_config(fe, which, &title);
  1831. fe->cfg_which = which;
  1832. /*
  1833. * Figure out the layout of the config box by measuring the
  1834. * length of each piece of text.
  1835. */
  1836. maxlabel = maxcheckbox = 0;
  1837. winheight = height/2;
  1838. for (i = fe->cfg; i->type != C_END; i++) {
  1839. switch (i->type) {
  1840. case C_STRING:
  1841. case C_CHOICES:
  1842. /*
  1843. * Both these control types have a label filling only
  1844. * the left-hand column of the box.
  1845. */
  1846. if (GetTextExtentPoint32(hdc, i->name, strlen(i->name), &size) &&
  1847. maxlabel < size.cx)
  1848. maxlabel = size.cx;
  1849. winheight += height * 3 / 2 + (height / 2);
  1850. break;
  1851. case C_BOOLEAN:
  1852. /*
  1853. * Checkboxes take up the whole of the box width.
  1854. */
  1855. if (GetTextExtentPoint32(hdc, i->name, strlen(i->name), &size) &&
  1856. maxcheckbox < size.cx)
  1857. maxcheckbox = size.cx;
  1858. winheight += height + (height / 2);
  1859. break;
  1860. }
  1861. }
  1862. winheight += height + height * 7 / 4; /* OK / Cancel buttons */
  1863. col1l = 2*width;
  1864. col1r = col1l + maxlabel;
  1865. col2l = col1r + 2*width;
  1866. col2r = col2l + 30*width;
  1867. if (col2r < col1l+2*height+maxcheckbox)
  1868. col2r = col1l+2*height+maxcheckbox;
  1869. winwidth = col2r + 2*width;
  1870. SelectObject(hdc, oldfont);
  1871. ReleaseDC(fe->hwnd, hdc);
  1872. /*
  1873. * Create the dialog, now that we know its size.
  1874. */
  1875. {
  1876. RECT r, r2;
  1877. r.left = r.top = 0;
  1878. r.right = winwidth;
  1879. r.bottom = winheight;
  1880. AdjustWindowRectEx(&r, (WS_OVERLAPPEDWINDOW /*|
  1881. DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
  1882. WS_CAPTION | WS_SYSMENU*/) &~
  1883. (WS_MAXIMIZEBOX | WS_OVERLAPPED),
  1884. false, 0);
  1885. /*
  1886. * Centre the dialog on its parent window.
  1887. */
  1888. r.right -= r.left;
  1889. r.bottom -= r.top;
  1890. GetWindowRect(fe->hwnd, &r2);
  1891. r.left = (r2.left + r2.right - r.right) / 2;
  1892. r.top = (r2.top + r2.bottom - r.bottom) / 2;
  1893. r.right += r.left;
  1894. r.bottom += r.top;
  1895. fe->cfgbox = CreateWindowEx(0, wc.lpszClassName, title,
  1896. DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
  1897. WS_CAPTION | WS_SYSMENU,
  1898. r.left, r.top,
  1899. r.right-r.left, r.bottom-r.top,
  1900. fe->hwnd, NULL, fe->inst, NULL);
  1901. sfree(title);
  1902. }
  1903. SendMessage(fe->cfgbox, WM_SETFONT, (WPARAM)fe->cfgfont, false);
  1904. SetWindowLongPtr(fe->cfgbox, GWLP_USERDATA, (LONG_PTR)fe);
  1905. SetWindowLongPtr(fe->cfgbox, DWLP_DLGPROC, (LONG_PTR)ConfigDlgProc);
  1906. /*
  1907. * Count the controls so we can allocate cfgaux.
  1908. */
  1909. for (nctrls = 0, i = fe->cfg; i->type != C_END; i++)
  1910. nctrls++;
  1911. fe->cfgaux = snewn(nctrls, struct cfg_aux);
  1912. id = 1000;
  1913. y = height/2;
  1914. for (i = fe->cfg, j = fe->cfgaux; i->type != C_END; i++, j++) {
  1915. switch (i->type) {
  1916. case C_STRING:
  1917. /*
  1918. * Edit box with a label beside it.
  1919. */
  1920. mkctrl(fe, col1l, col1r, y+height*1/8, y+height*9/8,
  1921. "Static", 0, 0, i->name, id++);
  1922. ctl = mkctrl(fe, col2l, col2r, y, y+height*3/2,
  1923. "EDIT", WS_TABSTOP | ES_AUTOHSCROLL,
  1924. WS_EX_CLIENTEDGE, "", (j->ctlid = id++));
  1925. SetWindowText(ctl, i->u.string.sval);
  1926. y += height*3/2;
  1927. break;
  1928. case C_BOOLEAN:
  1929. /*
  1930. * Simple checkbox.
  1931. */
  1932. mkctrl(fe, col1l, col2r, y, y+height, "BUTTON",
  1933. BS_NOTIFY | BS_AUTOCHECKBOX | WS_TABSTOP,
  1934. 0, i->name, (j->ctlid = id++));
  1935. CheckDlgButton(fe->cfgbox, j->ctlid, i->u.boolean.bval);
  1936. y += height;
  1937. break;
  1938. case C_CHOICES:
  1939. /*
  1940. * Drop-down list with a label beside it.
  1941. */
  1942. mkctrl(fe, col1l, col1r, y+height*1/8, y+height*9/8,
  1943. "STATIC", 0, 0, i->name, id++);
  1944. ctl = mkctrl(fe, col2l, col2r, y, y+height*41/2,
  1945. "COMBOBOX", WS_TABSTOP |
  1946. CBS_DROPDOWNLIST | CBS_HASSTRINGS,
  1947. WS_EX_CLIENTEDGE, "", (j->ctlid = id++));
  1948. {
  1949. char c;
  1950. const char *p, *q;
  1951. char *str;
  1952. SendMessage(ctl, CB_RESETCONTENT, 0, 0);
  1953. p = i->u.choices.choicenames;
  1954. c = *p++;
  1955. while (*p) {
  1956. q = p;
  1957. while (*q && *q != c) q++;
  1958. str = snewn(q-p+1, char);
  1959. strncpy(str, p, q-p);
  1960. str[q-p] = '\0';
  1961. SendMessage(ctl, CB_ADDSTRING, 0, (LPARAM)str);
  1962. sfree(str);
  1963. if (*q) q++;
  1964. p = q;
  1965. }
  1966. }
  1967. SendMessage(ctl, CB_SETCURSEL, i->u.choices.selected, 0);
  1968. y += height*3/2;
  1969. break;
  1970. }
  1971. assert(y < winheight);
  1972. y += height/2;
  1973. }
  1974. y += height/2; /* extra space before OK and Cancel */
  1975. mkctrl(fe, col1l, (col1l+col2r)/2-width, y, y+height*7/4, "BUTTON",
  1976. BS_PUSHBUTTON | WS_TABSTOP | BS_DEFPUSHBUTTON, 0,
  1977. "OK", IDOK);
  1978. mkctrl(fe, (col1l+col2r)/2+width, col2r, y, y+height*7/4, "BUTTON",
  1979. BS_PUSHBUTTON | WS_TABSTOP, 0, "Cancel", IDCANCEL);
  1980. SendMessage(fe->cfgbox, WM_INITDIALOG, 0, 0);
  1981. EnableWindow(fe->hwnd, false);
  1982. ShowWindow(fe->cfgbox, SW_SHOWNORMAL);
  1983. while ((gm=GetMessage(&msg, NULL, 0, 0)) > 0) {
  1984. if (!IsDialogMessage(fe->cfgbox, &msg))
  1985. DispatchMessage(&msg);
  1986. if (fe->dlg_done)
  1987. break;
  1988. }
  1989. EnableWindow(fe->hwnd, true);
  1990. SetForegroundWindow(fe->hwnd);
  1991. DestroyWindow(fe->cfgbox);
  1992. DeleteObject(fe->cfgfont);
  1993. free_cfg(fe->cfg);
  1994. sfree(fe->cfgaux);
  1995. return (fe->dlg_done == 2);
  1996. }
  1997. static void calculate_bitmap_position(frontend *fe, int x, int y)
  1998. {
  1999. /* Plain Windows - position the game in the upper-left corner */
  2000. fe->bitmapPosition.left = 0;
  2001. fe->bitmapPosition.top = 0;
  2002. fe->bitmapPosition.right = fe->bitmapPosition.left + x;
  2003. fe->bitmapPosition.bottom = fe->bitmapPosition.top + y;
  2004. }
  2005. static void new_bitmap(frontend *fe, int x, int y)
  2006. {
  2007. HDC hdc;
  2008. if (fe->bitmap) DeleteObject(fe->bitmap);
  2009. hdc = GetDC(fe->hwnd);
  2010. fe->bitmap = CreateCompatibleBitmap(hdc, x, y);
  2011. calculate_bitmap_position(fe, x, y);
  2012. ReleaseDC(fe->hwnd, hdc);
  2013. }
  2014. static void new_game_size(frontend *fe, float scale)
  2015. {
  2016. RECT r, sr;
  2017. int x, y;
  2018. get_max_puzzle_size(fe, &x, &y);
  2019. midend_size(fe->me, &x, &y, false, 1.0);
  2020. if (scale != 1.0) {
  2021. x = (int)((float)x * fe->puzz_scale);
  2022. y = (int)((float)y * fe->puzz_scale);
  2023. midend_size(fe->me, &x, &y, true, 1.0);
  2024. }
  2025. fe->ymin = (fe->xmin * y) / x;
  2026. r.left = r.top = 0;
  2027. r.right = x;
  2028. r.bottom = y;
  2029. AdjustWindowRectEx(&r, WINFLAGS, true, 0);
  2030. if (fe->statusbar != NULL) {
  2031. GetWindowRect(fe->statusbar, &sr);
  2032. } else {
  2033. sr.left = sr.right = sr.top = sr.bottom = 0;
  2034. }
  2035. SetWindowPos(fe->hwnd, NULL, 0, 0,
  2036. r.right - r.left,
  2037. r.bottom - r.top + sr.bottom - sr.top,
  2038. SWP_NOMOVE | SWP_NOZORDER);
  2039. check_window_size(fe, &x, &y);
  2040. if (fe->statusbar != NULL)
  2041. SetWindowPos(fe->statusbar, NULL, 0, y, x,
  2042. sr.bottom - sr.top, SWP_NOZORDER);
  2043. new_bitmap(fe, x, y);
  2044. midend_redraw(fe->me);
  2045. }
  2046. /*
  2047. * Given a proposed new window rect, work out the resulting
  2048. * difference in client size (from current), and use to try
  2049. * and resize the puzzle, returning (wx,wy) as the actual
  2050. * new window size.
  2051. */
  2052. static void adjust_game_size(frontend *fe, RECT *proposed, bool isedge,
  2053. int *wx_r, int *wy_r)
  2054. {
  2055. RECT cr, wr;
  2056. int nx, ny, xdiff, ydiff, wx, wy;
  2057. /* Work out the current window sizing, and thus the
  2058. * difference in size we're asking for. */
  2059. GetClientRect(fe->hwnd, &cr);
  2060. wr = cr;
  2061. AdjustWindowRectEx(&wr, WINFLAGS, true, 0);
  2062. xdiff = (proposed->right - proposed->left) - (wr.right - wr.left);
  2063. ydiff = (proposed->bottom - proposed->top) - (wr.bottom - wr.top);
  2064. if (isedge) {
  2065. /* These next four lines work around the fact that midend_size
  2066. * is happy to shrink _but not grow_ if you change one dimension
  2067. * but not the other. */
  2068. if (xdiff > 0 && ydiff == 0)
  2069. ydiff = (xdiff * (wr.right - wr.left)) / (wr.bottom - wr.top);
  2070. if (xdiff == 0 && ydiff > 0)
  2071. xdiff = (ydiff * (wr.bottom - wr.top)) / (wr.right - wr.left);
  2072. }
  2073. if (check_window_resize(fe,
  2074. (cr.right - cr.left) + xdiff,
  2075. (cr.bottom - cr.top) + ydiff,
  2076. &nx, &ny, &wx, &wy)) {
  2077. new_bitmap(fe, nx, ny);
  2078. midend_force_redraw(fe->me);
  2079. } else {
  2080. /* reset size to current window size */
  2081. wx = wr.right - wr.left;
  2082. wy = wr.bottom - wr.top;
  2083. }
  2084. /* Re-fetch rectangle; size limits mean we might not have
  2085. * taken it quite to the mouse drag positions. */
  2086. GetClientRect(fe->hwnd, &cr);
  2087. adjust_statusbar(fe, &cr);
  2088. *wx_r = wx; *wy_r = wy;
  2089. }
  2090. static void update_type_menu_tick(frontend *fe)
  2091. {
  2092. int total, n, i;
  2093. if (fe->typemenu == INVALID_HANDLE_VALUE)
  2094. return;
  2095. n = midend_which_preset(fe->me);
  2096. for (i = 0; i < fe->n_preset_menuitems; i++) {
  2097. if (fe->preset_menuitems[i].which_menu) {
  2098. int flag = (i == n ? MF_CHECKED : MF_UNCHECKED);
  2099. CheckMenuItem(fe->preset_menuitems[i].which_menu,
  2100. fe->preset_menuitems[i].item_index,
  2101. MF_BYPOSITION | flag);
  2102. }
  2103. }
  2104. if (fe->game->can_configure) {
  2105. int flag = (n < 0 ? MF_CHECKED : MF_UNCHECKED);
  2106. /* "Custom" menu item is at the bottom of the top-level Type menu */
  2107. total = GetMenuItemCount(fe->typemenu);
  2108. CheckMenuItem(fe->typemenu, total - 1, MF_BYPOSITION | flag);
  2109. }
  2110. DrawMenuBar(fe->hwnd);
  2111. }
  2112. static char *prefs_dir(void)
  2113. {
  2114. const char *var;
  2115. if ((var = getenv("APPDATA")) != NULL) {
  2116. size_t size = strlen(var) + 80;
  2117. char *dir = snewn(size, char);
  2118. sprintf(dir, "%s\\Simon Tatham's Portable Puzzle Collection", var);
  2119. return dir;
  2120. }
  2121. return NULL;
  2122. }
  2123. static char *prefs_path_general(const game *game, const char *suffix)
  2124. {
  2125. char *dir, *path;
  2126. dir = prefs_dir();
  2127. if (!dir)
  2128. return NULL;
  2129. path = make_prefs_path(dir, "\\", game, suffix);
  2130. sfree(dir);
  2131. return path;
  2132. }
  2133. static char *prefs_path(const game *game)
  2134. {
  2135. return prefs_path_general(game, ".conf");
  2136. }
  2137. static char *prefs_tmp_path(const game *game)
  2138. {
  2139. return prefs_path_general(game, ".tmp");
  2140. }
  2141. static void load_prefs(midend *me)
  2142. {
  2143. const game *game = midend_which_game(me);
  2144. char *path = prefs_path(game);
  2145. if (!path)
  2146. return;
  2147. FILE *fp = fopen(path, "r");
  2148. if (!fp)
  2149. return;
  2150. const char *err = midend_load_prefs(me, savefile_read, fp);
  2151. fclose(fp);
  2152. if (err)
  2153. fprintf(stderr, "Unable to load preferences file %s:\n%s\n",
  2154. path, err);
  2155. sfree(path);
  2156. }
  2157. static char *save_prefs(midend *me)
  2158. {
  2159. const game *game = midend_which_game(me);
  2160. char *dir_path = prefs_dir();
  2161. char *file_path = prefs_path(game);
  2162. char *tmp_path = prefs_tmp_path(game);
  2163. HANDLE fh;
  2164. FILE *fp;
  2165. bool cleanup_dir = false, cleanup_tmpfile = false;
  2166. char *err = NULL;
  2167. if (!dir_path || !file_path || !tmp_path) {
  2168. sprintf(err = snewn(256, char),
  2169. "Unable to save preferences:\n"
  2170. "Could not determine pathname for configuration files");
  2171. goto out;
  2172. }
  2173. if (!CreateDirectory(dir_path, NULL)) {
  2174. /* Ignore errors while trying to make the directory. It may
  2175. * well already exist, and even if we got some error code
  2176. * other than EEXIST, it's still worth at least _trying_ to
  2177. * make the file inside it, and see if that goes wrong. */
  2178. } else {
  2179. cleanup_dir = true;
  2180. }
  2181. fh = CreateFile(tmp_path, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS,
  2182. FILE_ATTRIBUTE_NORMAL, NULL);
  2183. if (fh == INVALID_HANDLE_VALUE) {
  2184. char *os_err = geterrstr();
  2185. sprintf(err = snewn(256 + strlen(tmp_path) + strlen(os_err), char),
  2186. "Unable to save preferences:\n"
  2187. "Unable to create file '%s':\n%s", tmp_path, os_err);
  2188. sfree(os_err);
  2189. goto out;
  2190. } else {
  2191. cleanup_tmpfile = true;
  2192. }
  2193. fp = _fdopen(_open_osfhandle((intptr_t)fh, 0), "w");
  2194. SetLastError(0);
  2195. midend_save_prefs(me, savefile_write, fp);
  2196. fclose(fp);
  2197. if (GetLastError()) {
  2198. char *os_err = geterrstr();
  2199. sprintf(err = snewn(80 + strlen(tmp_path) + strlen(os_err), char),
  2200. "Unable to write file '%s':\n%s", tmp_path, os_err);
  2201. sfree(os_err);
  2202. goto out;
  2203. }
  2204. if (MoveFileEx(tmp_path, file_path, MOVEFILE_REPLACE_EXISTING) < 0) {
  2205. char *os_err = geterrstr();
  2206. sprintf(err = snewn(256 + strlen(tmp_path) + strlen(file_path) +
  2207. strlen(os_err), char),
  2208. "Unable to save preferences:\n"
  2209. "Unable to rename '%s' to '%s':\n%s", tmp_path, file_path,
  2210. os_err);
  2211. sfree(os_err);
  2212. goto out;
  2213. } else {
  2214. cleanup_dir = false;
  2215. cleanup_tmpfile = false;
  2216. }
  2217. out:
  2218. if (cleanup_tmpfile) {
  2219. if (!DeleteFile(tmp_path)) { /* can't do anything about this */ }
  2220. }
  2221. if (cleanup_dir) {
  2222. if (!RemoveDirectory(dir_path)) { /* can't do anything about this */ }
  2223. }
  2224. sfree(dir_path);
  2225. sfree(file_path);
  2226. sfree(tmp_path);
  2227. return err;
  2228. }
  2229. static void update_copy_menu_greying(frontend *fe)
  2230. {
  2231. UINT enable = (midend_can_format_as_text_now(fe->me) ?
  2232. MF_ENABLED : MF_GRAYED);
  2233. EnableMenuItem(fe->gamemenu, IDM_COPY, MF_BYCOMMAND | enable);
  2234. }
  2235. static void new_game_type(frontend *fe)
  2236. {
  2237. midend_new_game(fe->me);
  2238. new_game_size(fe, 1.0);
  2239. update_type_menu_tick(fe);
  2240. update_copy_menu_greying(fe);
  2241. }
  2242. static bool is_alt_pressed(void)
  2243. {
  2244. BYTE keystate[256];
  2245. int r = GetKeyboardState(keystate);
  2246. if (!r)
  2247. return false;
  2248. if (keystate[VK_MENU] & 0x80)
  2249. return true;
  2250. if (keystate[VK_RMENU] & 0x80)
  2251. return true;
  2252. return false;
  2253. }
  2254. static LRESULT CALLBACK WndProc(HWND hwnd, UINT message,
  2255. WPARAM wParam, LPARAM lParam)
  2256. {
  2257. frontend *fe = (frontend *)GetWindowLongPtr(hwnd, GWLP_USERDATA);
  2258. int cmd;
  2259. switch (message) {
  2260. case WM_CLOSE:
  2261. DestroyWindow(hwnd);
  2262. return 0;
  2263. case WM_COMMAND:
  2264. cmd = wParam & ~0xF; /* low 4 bits reserved to Windows */
  2265. switch (cmd) {
  2266. case IDM_NEW:
  2267. if (midend_process_key(fe->me, 0, 0, UI_NEWGAME) == PKR_QUIT)
  2268. PostQuitMessage(0);
  2269. break;
  2270. case IDM_RESTART:
  2271. midend_restart_game(fe->me);
  2272. break;
  2273. case IDM_UNDO:
  2274. if (midend_process_key(fe->me, 0, 0, UI_UNDO) == PKR_QUIT)
  2275. PostQuitMessage(0);
  2276. break;
  2277. case IDM_REDO:
  2278. if (midend_process_key(fe->me, 0, 0, UI_REDO) == PKR_QUIT)
  2279. PostQuitMessage(0);
  2280. break;
  2281. case IDM_COPY:
  2282. {
  2283. char *text = midend_text_format(fe->me);
  2284. if (text)
  2285. write_clip(hwnd, text);
  2286. else
  2287. MessageBeep(MB_ICONWARNING);
  2288. sfree(text);
  2289. }
  2290. break;
  2291. case IDM_SOLVE:
  2292. {
  2293. const char *msg = midend_solve(fe->me);
  2294. if (msg)
  2295. MessageBox(hwnd, msg, "Unable to solve",
  2296. MB_ICONERROR | MB_OK);
  2297. }
  2298. break;
  2299. case IDM_QUIT:
  2300. if (midend_process_key(fe->me, 0, 0, UI_QUIT) == PKR_QUIT)
  2301. PostQuitMessage(0);
  2302. break;
  2303. case IDM_CONFIG:
  2304. if (get_config(fe, CFG_SETTINGS))
  2305. new_game_type(fe);
  2306. break;
  2307. case IDM_SEED:
  2308. if (get_config(fe, CFG_SEED))
  2309. new_game_type(fe);
  2310. break;
  2311. case IDM_DESC:
  2312. if (get_config(fe, CFG_DESC))
  2313. new_game_type(fe);
  2314. break;
  2315. case IDM_PRINT:
  2316. if (get_config(fe, CFG_PRINT))
  2317. print(fe);
  2318. break;
  2319. case IDM_PREFS:
  2320. if (get_config(fe, CFG_PREFS)) {
  2321. char *prefs_err = save_prefs(fe->me);
  2322. if (prefs_err) {
  2323. MessageBox(fe->hwnd, prefs_err, "Error saving preferences",
  2324. MB_ICONERROR | MB_OK);
  2325. sfree(prefs_err);
  2326. }
  2327. }
  2328. break;
  2329. case IDM_ABOUT:
  2330. about(fe);
  2331. break;
  2332. case IDM_LOAD:
  2333. case IDM_SAVE:
  2334. {
  2335. OPENFILENAME of;
  2336. char filename[FILENAME_MAX];
  2337. int ret;
  2338. memset(&of, 0, sizeof(of));
  2339. of.hwndOwner = hwnd;
  2340. of.lpstrFilter = "All Files (*.*)\0*\0\0\0";
  2341. of.lpstrCustomFilter = NULL;
  2342. of.nFilterIndex = 1;
  2343. of.lpstrFile = filename;
  2344. filename[0] = '\0';
  2345. of.nMaxFile = lenof(filename);
  2346. of.lpstrFileTitle = NULL;
  2347. of.lpstrTitle = (cmd == IDM_SAVE ?
  2348. "Enter name of game file to save" :
  2349. "Enter name of saved game file to load");
  2350. of.Flags = 0;
  2351. #ifdef OPENFILENAME_SIZE_VERSION_400
  2352. of.lStructSize = OPENFILENAME_SIZE_VERSION_400;
  2353. #else
  2354. of.lStructSize = sizeof(of);
  2355. #endif
  2356. of.lpstrInitialDir = NULL;
  2357. if (cmd == IDM_SAVE)
  2358. ret = GetSaveFileName(&of);
  2359. else
  2360. ret = GetOpenFileName(&of);
  2361. if (ret) {
  2362. if (cmd == IDM_SAVE) {
  2363. FILE *fp;
  2364. if ((fp = fopen(filename, "r")) != NULL) {
  2365. char buf[256 + FILENAME_MAX];
  2366. fclose(fp);
  2367. /* file exists */
  2368. sprintf(buf, "Are you sure you want to overwrite"
  2369. " the file \"%.*s\"?",
  2370. FILENAME_MAX, filename);
  2371. if (MessageBox(hwnd, buf, "Question",
  2372. MB_YESNO | MB_ICONQUESTION)
  2373. != IDYES)
  2374. break;
  2375. }
  2376. fp = fopen(filename, "w");
  2377. if (!fp) {
  2378. MessageBox(hwnd, "Unable to open save file",
  2379. "Error", MB_ICONERROR | MB_OK);
  2380. break;
  2381. }
  2382. midend_serialise(fe->me, savefile_write, fp);
  2383. fclose(fp);
  2384. } else {
  2385. FILE *fp = fopen(filename, "r");
  2386. const char *err = NULL;
  2387. char *err_w = NULL;
  2388. midend *me = fe->me;
  2389. #ifdef COMBINED
  2390. char *id_name;
  2391. #endif
  2392. if (!fp) {
  2393. MessageBox(hwnd, "Unable to open saved game file",
  2394. "Error", MB_ICONERROR | MB_OK);
  2395. break;
  2396. }
  2397. #ifdef COMBINED
  2398. /*
  2399. * This save file might be from a different
  2400. * game.
  2401. */
  2402. err = identify_game(&id_name, savefile_read, fp);
  2403. if (!err) {
  2404. int i;
  2405. for (i = 0; i < gamecount; i++)
  2406. if (!strcmp(id_name, gamelist[i]->name))
  2407. break;
  2408. if (i == gamecount) {
  2409. err = "Save file is for a game not "
  2410. "supported by this program";
  2411. } else {
  2412. me = midend_for_new_game(fe, gamelist[i], NULL,
  2413. false, false, &err_w);
  2414. err = err_w;
  2415. rewind(fp); /* for the actual load */
  2416. }
  2417. sfree(id_name);
  2418. }
  2419. #endif
  2420. if (!err)
  2421. err = midend_deserialise(me, savefile_read, fp);
  2422. fclose(fp);
  2423. if (err) {
  2424. MessageBox(hwnd, err, "Error", MB_ICONERROR|MB_OK);
  2425. sfree(err_w);
  2426. break;
  2427. }
  2428. if (fe->me != me)
  2429. fe_set_midend(fe, me);
  2430. new_game_size(fe, 1.0);
  2431. }
  2432. }
  2433. }
  2434. break;
  2435. case IDM_HELPC:
  2436. start_help(fe, NULL);
  2437. break;
  2438. case IDM_GAMEHELP:
  2439. assert(help_type != NONE);
  2440. start_help(fe, help_type == CHM ?
  2441. fe->game->htmlhelp_topic : fe->game->winhelp_topic);
  2442. break;
  2443. default: {
  2444. unsigned n;
  2445. #ifdef COMBINED
  2446. n = (wParam - IDM_GAME_BASE) / MENUITEM_STEP;
  2447. if (n < gamecount && wParam == IDM_GAME_BASE + MENUITEM_STEP * n) {
  2448. char *error = NULL;
  2449. fe_set_midend(fe, midend_for_new_game(fe, gamelist[n], NULL,
  2450. false, false, &error));
  2451. sfree(error);
  2452. break;
  2453. }
  2454. #endif
  2455. n = (wParam - IDM_PRESET_BASE) / MENUITEM_STEP;
  2456. if (wParam == IDM_PRESET_BASE + MENUITEM_STEP * n) {
  2457. game_params *preset = preset_menu_lookup_by_id(
  2458. fe->preset_menu, n);
  2459. if (preset) {
  2460. midend_set_params(fe->me, preset);
  2461. new_game_type(fe);
  2462. break;
  2463. }
  2464. }
  2465. break;
  2466. }
  2467. }
  2468. break;
  2469. case WM_DESTROY:
  2470. stop_help(fe);
  2471. frontend_free(fe);
  2472. PostQuitMessage(0);
  2473. return 0;
  2474. case WM_PAINT:
  2475. {
  2476. PAINTSTRUCT p;
  2477. HDC hdc, hdc2;
  2478. HBITMAP prevbm;
  2479. RECT rcDest;
  2480. hdc = BeginPaint(hwnd, &p);
  2481. hdc2 = CreateCompatibleDC(hdc);
  2482. prevbm = SelectObject(hdc2, fe->bitmap);
  2483. IntersectRect(&rcDest, &(fe->bitmapPosition), &(p.rcPaint));
  2484. BitBlt(hdc,
  2485. rcDest.left, rcDest.top,
  2486. rcDest.right - rcDest.left,
  2487. rcDest.bottom - rcDest.top,
  2488. hdc2,
  2489. rcDest.left - fe->bitmapPosition.left,
  2490. rcDest.top - fe->bitmapPosition.top,
  2491. SRCCOPY);
  2492. SelectObject(hdc2, prevbm);
  2493. DeleteDC(hdc2);
  2494. EndPaint(hwnd, &p);
  2495. }
  2496. return 0;
  2497. case WM_KEYDOWN:
  2498. {
  2499. int key = -1;
  2500. BYTE keystate[256];
  2501. int r = GetKeyboardState(keystate);
  2502. int shift = (r && (keystate[VK_SHIFT] & 0x80)) ? MOD_SHFT : 0;
  2503. int ctrl = (r && (keystate[VK_CONTROL] & 0x80)) ? MOD_CTRL : 0;
  2504. switch (wParam) {
  2505. case VK_LEFT:
  2506. if (!(lParam & 0x01000000))
  2507. key = MOD_NUM_KEYPAD | '4';
  2508. else
  2509. key = shift | ctrl | CURSOR_LEFT;
  2510. break;
  2511. case VK_RIGHT:
  2512. if (!(lParam & 0x01000000))
  2513. key = MOD_NUM_KEYPAD | '6';
  2514. else
  2515. key = shift | ctrl | CURSOR_RIGHT;
  2516. break;
  2517. case VK_UP:
  2518. if (!(lParam & 0x01000000))
  2519. key = MOD_NUM_KEYPAD | '8';
  2520. else
  2521. key = shift | ctrl | CURSOR_UP;
  2522. break;
  2523. case VK_DOWN:
  2524. if (!(lParam & 0x01000000))
  2525. key = MOD_NUM_KEYPAD | '2';
  2526. else
  2527. key = shift | ctrl | CURSOR_DOWN;
  2528. break;
  2529. /*
  2530. * Diagonal keys on the numeric keypad.
  2531. */
  2532. case VK_PRIOR:
  2533. if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '9';
  2534. break;
  2535. case VK_NEXT:
  2536. if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '3';
  2537. break;
  2538. case VK_HOME:
  2539. if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '7';
  2540. break;
  2541. case VK_END:
  2542. if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '1';
  2543. break;
  2544. case VK_INSERT:
  2545. if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '0';
  2546. break;
  2547. case VK_CLEAR:
  2548. if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '5';
  2549. break;
  2550. /*
  2551. * Numeric keypad keys with Num Lock on.
  2552. */
  2553. case VK_NUMPAD4: key = MOD_NUM_KEYPAD | '4'; break;
  2554. case VK_NUMPAD6: key = MOD_NUM_KEYPAD | '6'; break;
  2555. case VK_NUMPAD8: key = MOD_NUM_KEYPAD | '8'; break;
  2556. case VK_NUMPAD2: key = MOD_NUM_KEYPAD | '2'; break;
  2557. case VK_NUMPAD5: key = MOD_NUM_KEYPAD | '5'; break;
  2558. case VK_NUMPAD9: key = MOD_NUM_KEYPAD | '9'; break;
  2559. case VK_NUMPAD3: key = MOD_NUM_KEYPAD | '3'; break;
  2560. case VK_NUMPAD7: key = MOD_NUM_KEYPAD | '7'; break;
  2561. case VK_NUMPAD1: key = MOD_NUM_KEYPAD | '1'; break;
  2562. case VK_NUMPAD0: key = MOD_NUM_KEYPAD | '0'; break;
  2563. }
  2564. if (key != -1) {
  2565. if (midend_process_key(fe->me, 0, 0, key) == PKR_QUIT)
  2566. PostQuitMessage(0);
  2567. } else {
  2568. MSG m;
  2569. m.hwnd = hwnd;
  2570. m.message = WM_KEYDOWN;
  2571. m.wParam = wParam;
  2572. m.lParam = lParam & 0xdfff;
  2573. TranslateMessage(&m);
  2574. }
  2575. }
  2576. break;
  2577. case WM_LBUTTONDOWN:
  2578. case WM_RBUTTONDOWN:
  2579. case WM_MBUTTONDOWN:
  2580. {
  2581. int button;
  2582. /*
  2583. * Shift-clicks count as middle-clicks, since otherwise
  2584. * two-button Windows users won't have any kind of
  2585. * middle click to use.
  2586. */
  2587. if (message == WM_MBUTTONDOWN || (wParam & MK_SHIFT))
  2588. button = MIDDLE_BUTTON;
  2589. else if (message == WM_RBUTTONDOWN || is_alt_pressed())
  2590. button = RIGHT_BUTTON;
  2591. else
  2592. button = LEFT_BUTTON;
  2593. if (midend_process_key(fe->me,
  2594. (signed short)LOWORD(lParam) - fe->bitmapPosition.left,
  2595. (signed short)HIWORD(lParam) - fe->bitmapPosition.top,
  2596. button) == PKR_QUIT)
  2597. PostQuitMessage(0);
  2598. SetCapture(hwnd);
  2599. }
  2600. break;
  2601. case WM_LBUTTONUP:
  2602. case WM_RBUTTONUP:
  2603. case WM_MBUTTONUP:
  2604. {
  2605. int button;
  2606. /*
  2607. * Shift-clicks count as middle-clicks, since otherwise
  2608. * two-button Windows users won't have any kind of
  2609. * middle click to use.
  2610. */
  2611. if (message == WM_MBUTTONUP || (wParam & MK_SHIFT))
  2612. button = MIDDLE_RELEASE;
  2613. else if (message == WM_RBUTTONUP || is_alt_pressed())
  2614. button = RIGHT_RELEASE;
  2615. else
  2616. button = LEFT_RELEASE;
  2617. if (midend_process_key(fe->me,
  2618. (signed short)LOWORD(lParam) - fe->bitmapPosition.left,
  2619. (signed short)HIWORD(lParam) - fe->bitmapPosition.top,
  2620. button) == PKR_QUIT)
  2621. PostQuitMessage(0);
  2622. ReleaseCapture();
  2623. }
  2624. break;
  2625. case WM_MOUSEMOVE:
  2626. {
  2627. int button;
  2628. if (wParam & (MK_MBUTTON | MK_SHIFT))
  2629. button = MIDDLE_DRAG;
  2630. else if (wParam & MK_RBUTTON || is_alt_pressed())
  2631. button = RIGHT_DRAG;
  2632. else
  2633. button = LEFT_DRAG;
  2634. if (midend_process_key(fe->me,
  2635. (signed short)LOWORD(lParam) - fe->bitmapPosition.left,
  2636. (signed short)HIWORD(lParam) - fe->bitmapPosition.top,
  2637. button) == PKR_QUIT)
  2638. PostQuitMessage(0);
  2639. }
  2640. break;
  2641. case WM_CHAR:
  2642. {
  2643. int key = (unsigned char)wParam;
  2644. if (key == '\x1A') {
  2645. BYTE keystate[256];
  2646. if (GetKeyboardState(keystate) &&
  2647. (keystate[VK_SHIFT] & 0x80) &&
  2648. (keystate[VK_CONTROL] & 0x80))
  2649. key = UI_REDO;
  2650. }
  2651. if (midend_process_key(fe->me, 0, 0, key) == PKR_QUIT)
  2652. PostQuitMessage(0);
  2653. }
  2654. return 0;
  2655. case WM_TIMER:
  2656. if (fe->timer) {
  2657. DWORD now = GetTickCount();
  2658. float elapsed = (float) (now - fe->timer_last_tickcount) * 0.001F;
  2659. midend_timer(fe->me, elapsed);
  2660. fe->timer_last_tickcount = now;
  2661. }
  2662. return 0;
  2663. case WM_SIZING:
  2664. {
  2665. RECT *sr = (RECT *)lParam;
  2666. int wx, wy;
  2667. bool isedge = false;
  2668. if (wParam == WMSZ_TOP ||
  2669. wParam == WMSZ_RIGHT ||
  2670. wParam == WMSZ_BOTTOM ||
  2671. wParam == WMSZ_LEFT) isedge = true;
  2672. adjust_game_size(fe, sr, isedge, &wx, &wy);
  2673. /* Given the window size the puzzles constrain
  2674. * us to, work out which edge we should be moving. */
  2675. if (wParam == WMSZ_TOP ||
  2676. wParam == WMSZ_TOPLEFT ||
  2677. wParam == WMSZ_TOPRIGHT) {
  2678. sr->top = sr->bottom - wy;
  2679. } else {
  2680. sr->bottom = sr->top + wy;
  2681. }
  2682. if (wParam == WMSZ_LEFT ||
  2683. wParam == WMSZ_TOPLEFT ||
  2684. wParam == WMSZ_BOTTOMLEFT) {
  2685. sr->left = sr->right - wx;
  2686. } else {
  2687. sr->right = sr->left + wx;
  2688. }
  2689. return true;
  2690. }
  2691. break;
  2692. }
  2693. return DefWindowProc(hwnd, message, wParam, lParam);
  2694. }
  2695. /*
  2696. * Split a complete command line into argc/argv, attempting to do it
  2697. * exactly the same way the Visual Studio C library would do it (so
  2698. * that our console utilities, which receive argc and argv already
  2699. * broken apart by the C library, will have their command lines
  2700. * processed in the same way as the GUI utilities which get a whole
  2701. * command line and must call this function).
  2702. *
  2703. * Does not modify the input command line.
  2704. *
  2705. * The final parameter (argstart) is used to return a second array
  2706. * of char * pointers, the same length as argv, each one pointing
  2707. * at the start of the corresponding element of argv in the
  2708. * original command line. So if you get half way through processing
  2709. * your command line in argc/argv form and then decide you want to
  2710. * treat the rest as a raw string, you can. If you don't want to,
  2711. * `argstart' can be safely left NULL.
  2712. */
  2713. void split_into_argv(char *cmdline, int *argc, char ***argv,
  2714. char ***argstart)
  2715. {
  2716. char *p;
  2717. char *outputline, *q;
  2718. char **outputargv, **outputargstart;
  2719. int outputargc;
  2720. /*
  2721. * These argument-breaking rules apply to Visual Studio 7, which
  2722. * is currently the compiler expected to be used for the Windows
  2723. * port of my puzzles. Visual Studio 10 has different rules,
  2724. * lacking the curious mod 3 behaviour of consecutive quotes
  2725. * described below; I presume they fixed a bug. As and when we
  2726. * migrate to a newer compiler, we'll have to adjust this to
  2727. * match; however, for the moment we faithfully imitate in our GUI
  2728. * utilities what our CLI utilities can't be prevented from doing.
  2729. *
  2730. * When I investigated this, at first glance the rules appeared to
  2731. * be:
  2732. *
  2733. * - Single quotes are not special characters.
  2734. *
  2735. * - Double quotes are removed, but within them spaces cease
  2736. * to be special.
  2737. *
  2738. * - Backslashes are _only_ special when a sequence of them
  2739. * appear just before a double quote. In this situation,
  2740. * they are treated like C backslashes: so \" just gives a
  2741. * literal quote, \\" gives a literal backslash and then
  2742. * opens or closes a double-quoted segment, \\\" gives a
  2743. * literal backslash and then a literal quote, \\\\" gives
  2744. * two literal backslashes and then opens/closes a
  2745. * double-quoted segment, and so forth. Note that this
  2746. * behaviour is identical inside and outside double quotes.
  2747. *
  2748. * - Two successive double quotes become one literal double
  2749. * quote, but only _inside_ a double-quoted segment.
  2750. * Outside, they just form an empty double-quoted segment
  2751. * (which may cause an empty argument word).
  2752. *
  2753. * - That only leaves the interesting question of what happens
  2754. * when one or more backslashes precedes two or more double
  2755. * quotes, starting inside a double-quoted string. And the
  2756. * answer to that appears somewhat bizarre. Here I tabulate
  2757. * number of backslashes (across the top) against number of
  2758. * quotes (down the left), and indicate how many backslashes
  2759. * are output, how many quotes are output, and whether a
  2760. * quoted segment is open at the end of the sequence:
  2761. *
  2762. * backslashes
  2763. *
  2764. * 0 1 2 3 4
  2765. *
  2766. * 0 0,0,y | 1,0,y 2,0,y 3,0,y 4,0,y
  2767. * --------+-----------------------------
  2768. * 1 0,0,n | 0,1,y 1,0,n 1,1,y 2,0,n
  2769. * q 2 0,1,n | 0,1,n 1,1,n 1,1,n 2,1,n
  2770. * u 3 0,1,y | 0,2,n 1,1,y 1,2,n 2,1,y
  2771. * o 4 0,1,n | 0,2,y 1,1,n 1,2,y 2,1,n
  2772. * t 5 0,2,n | 0,2,n 1,2,n 1,2,n 2,2,n
  2773. * e 6 0,2,y | 0,3,n 1,2,y 1,3,n 2,2,y
  2774. * s 7 0,2,n | 0,3,y 1,2,n 1,3,y 2,2,n
  2775. * 8 0,3,n | 0,3,n 1,3,n 1,3,n 2,3,n
  2776. * 9 0,3,y | 0,4,n 1,3,y 1,4,n 2,3,y
  2777. * 10 0,3,n | 0,4,y 1,3,n 1,4,y 2,3,n
  2778. * 11 0,4,n | 0,4,n 1,4,n 1,4,n 2,4,n
  2779. *
  2780. *
  2781. * [Test fragment was of the form "a\\\"""b c" d.]
  2782. *
  2783. * There is very weird mod-3 behaviour going on here in the
  2784. * number of quotes, and it even applies when there aren't any
  2785. * backslashes! How ghastly.
  2786. *
  2787. * With a bit of thought, this extremely odd diagram suddenly
  2788. * coalesced itself into a coherent, if still ghastly, model of
  2789. * how things work:
  2790. *
  2791. * - As before, backslashes are only special when one or more
  2792. * of them appear contiguously before at least one double
  2793. * quote. In this situation the backslashes do exactly what
  2794. * you'd expect: each one quotes the next thing in front of
  2795. * it, so you end up with n/2 literal backslashes (if n is
  2796. * even) or (n-1)/2 literal backslashes and a literal quote
  2797. * (if n is odd). In the latter case the double quote
  2798. * character right after the backslashes is used up.
  2799. *
  2800. * - After that, any remaining double quotes are processed. A
  2801. * string of contiguous unescaped double quotes has a mod-3
  2802. * behaviour:
  2803. *
  2804. * * inside a quoted segment, a quote ends the segment.
  2805. * * _immediately_ after ending a quoted segment, a quote
  2806. * simply produces a literal quote.
  2807. * * otherwise, outside a quoted segment, a quote begins a
  2808. * quoted segment.
  2809. *
  2810. * So, for example, if we started inside a quoted segment
  2811. * then two contiguous quotes would close the segment and
  2812. * produce a literal quote; three would close the segment,
  2813. * produce a literal quote, and open a new segment. If we
  2814. * started outside a quoted segment, then two contiguous
  2815. * quotes would open and then close a segment, producing no
  2816. * output (but potentially creating a zero-length argument);
  2817. * but three quotes would open and close a segment and then
  2818. * produce a literal quote.
  2819. */
  2820. /*
  2821. * First deal with the simplest of all special cases: if there
  2822. * aren't any arguments, return 0,NULL,NULL.
  2823. */
  2824. while (*cmdline && isspace(*cmdline)) cmdline++;
  2825. if (!*cmdline) {
  2826. if (argc) *argc = 0;
  2827. if (argv) *argv = NULL;
  2828. if (argstart) *argstart = NULL;
  2829. return;
  2830. }
  2831. /*
  2832. * This will guaranteeably be big enough; we can realloc it
  2833. * down later.
  2834. */
  2835. outputline = snewn(1+strlen(cmdline), char);
  2836. outputargv = snewn(strlen(cmdline)+1 / 2, char *);
  2837. outputargstart = snewn(strlen(cmdline)+1 / 2, char *);
  2838. p = cmdline; q = outputline; outputargc = 0;
  2839. while (*p) {
  2840. bool quote;
  2841. /* Skip whitespace searching for start of argument. */
  2842. while (*p && isspace(*p)) p++;
  2843. if (!*p) break;
  2844. /* We have an argument; start it. */
  2845. outputargv[outputargc] = q;
  2846. outputargstart[outputargc] = p;
  2847. outputargc++;
  2848. quote = false;
  2849. /* Copy data into the argument until it's finished. */
  2850. while (*p) {
  2851. if (!quote && isspace(*p))
  2852. break; /* argument is finished */
  2853. if (*p == '"' || *p == '\\') {
  2854. /*
  2855. * We have a sequence of zero or more backslashes
  2856. * followed by a sequence of zero or more quotes.
  2857. * Count up how many of each, and then deal with
  2858. * them as appropriate.
  2859. */
  2860. int i, slashes = 0, quotes = 0;
  2861. while (*p == '\\') slashes++, p++;
  2862. while (*p == '"') quotes++, p++;
  2863. if (!quotes) {
  2864. /*
  2865. * Special case: if there are no quotes,
  2866. * slashes are not special at all, so just copy
  2867. * n slashes to the output string.
  2868. */
  2869. while (slashes--) *q++ = '\\';
  2870. } else {
  2871. /* Slashes annihilate in pairs. */
  2872. while (slashes >= 2) slashes -= 2, *q++ = '\\';
  2873. /* One remaining slash takes out the first quote. */
  2874. if (slashes) quotes--, *q++ = '"';
  2875. if (quotes > 0) {
  2876. /* Outside a quote segment, a quote starts one. */
  2877. if (!quote) quotes--, quote = true;
  2878. /* Now we produce (n+1)/3 literal quotes... */
  2879. for (i = 3; i <= quotes+1; i += 3) *q++ = '"';
  2880. /* ... and end in a quote segment iff 3 divides n. */
  2881. quote = (quotes % 3 == 0);
  2882. }
  2883. }
  2884. } else {
  2885. *q++ = *p++;
  2886. }
  2887. }
  2888. /* At the end of an argument, just append a trailing NUL. */
  2889. *q++ = '\0';
  2890. }
  2891. outputargv = sresize(outputargv, outputargc, char *);
  2892. outputargstart = sresize(outputargstart, outputargc, char *);
  2893. if (argc) *argc = outputargc;
  2894. if (argv) *argv = outputargv; else sfree(outputargv);
  2895. if (argstart) *argstart = outputargstart; else sfree(outputargstart);
  2896. }
  2897. int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show)
  2898. {
  2899. MSG msg;
  2900. char *error = NULL;
  2901. const game *gg;
  2902. frontend *fe;
  2903. midend *me;
  2904. int argc;
  2905. char **argv;
  2906. split_into_argv(cmdline, &argc, &argv, NULL);
  2907. InitCommonControls();
  2908. if (!prev) {
  2909. WNDCLASS wndclass;
  2910. wndclass.style = 0;
  2911. wndclass.lpfnWndProc = WndProc;
  2912. wndclass.cbClsExtra = 0;
  2913. wndclass.cbWndExtra = 0;
  2914. wndclass.hInstance = inst;
  2915. wndclass.hIcon = LoadIcon(inst, MAKEINTRESOURCE(200));
  2916. if (!wndclass.hIcon) /* in case resource file is absent */
  2917. wndclass.hIcon = LoadIcon(inst, IDI_APPLICATION);
  2918. wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
  2919. wndclass.hbrBackground = NULL;
  2920. wndclass.lpszMenuName = NULL;
  2921. wndclass.lpszClassName = CLASSNAME;
  2922. RegisterClass(&wndclass);
  2923. }
  2924. while (*cmdline && isspace((unsigned char)*cmdline))
  2925. cmdline++;
  2926. init_help();
  2927. #ifdef COMBINED
  2928. gg = gamelist[0];
  2929. if (argc > 0) {
  2930. int i;
  2931. for (i = 0; i < gamecount; i++) {
  2932. const char *p = gamelist[i]->name;
  2933. char *q = argv[0];
  2934. while (*p && *q) {
  2935. if (isspace((unsigned char)*p)) {
  2936. while (*q && isspace((unsigned char)*q))
  2937. q++;
  2938. } else {
  2939. if (tolower((unsigned char)*p) !=
  2940. tolower((unsigned char)*q))
  2941. break;
  2942. q++;
  2943. }
  2944. p++;
  2945. }
  2946. if (!*p) {
  2947. gg = gamelist[i];
  2948. --argc;
  2949. ++argv;
  2950. break;
  2951. }
  2952. }
  2953. }
  2954. #else
  2955. gg = &thegame;
  2956. #endif
  2957. fe = frontend_new(inst);
  2958. me = midend_for_new_game(fe, gg, argc > 0 ? argv[0] : NULL,
  2959. true, true, &error);
  2960. if (!me) {
  2961. char buf[128];
  2962. #ifdef COMBINED
  2963. sprintf(buf, "Puzzles Error");
  2964. #else
  2965. sprintf(buf, "%.100s Error", gg->name);
  2966. #endif
  2967. MessageBox(NULL, error, buf, MB_OK|MB_ICONERROR);
  2968. sfree(error);
  2969. return 1;
  2970. }
  2971. fe_set_midend(fe, me);
  2972. show_window(fe);
  2973. while (GetMessage(&msg, NULL, 0, 0)) {
  2974. DispatchMessage(&msg);
  2975. }
  2976. DestroyWindow(fe->hwnd);
  2977. cleanup_help();
  2978. return msg.wParam;
  2979. }
  2980. /* vim: set shiftwidth=4 tabstop=8: */