text.c 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242
  1. /* -*- mode: c; tab-width: 4; c-basic-offset: 4; c-file-style: "linux" -*- */
  2. //
  3. // Copyright (c) 2009-2011, Wei Mingzhi <whistler_wmz@users.sf.net>.
  4. // Copyright (c) 2011-2017, SDLPAL development team.
  5. // All rights reserved.
  6. //
  7. // This file is part of SDLPAL.
  8. //
  9. // SDLPAL is free software: you can redistribute it and/or modify
  10. // it under the terms of the GNU General Public License as published by
  11. // the Free Software Foundation, either version 3 of the License, or
  12. // (at your option) any later version.
  13. //
  14. // This program is distributed in the hope that it will be useful,
  15. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. // GNU General Public License for more details.
  18. //
  19. // You should have received a copy of the GNU General Public License
  20. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  21. //
  22. // Portions based on PALx Project by palxex.
  23. // Copyright (c) 2006-2008, Pal Lockheart <palxex@gmail.com>.
  24. //
  25. #include "main.h"
  26. #include <errno.h>
  27. #include <wctype.h>
  28. #define FONT_COLOR_DEFAULT 0x4F
  29. #define FONT_COLOR_YELLOW 0x2D
  30. #define FONT_COLOR_RED 0x1A
  31. #define FONT_COLOR_CYAN 0x8D
  32. #define FONT_COLOR_CYAN_ALT 0x8C
  33. BOOL g_fUpdatedInBattle = FALSE;
  34. #define MESSAGE_MAX_BUFFER_SIZE 512
  35. #define INCLUDE_CODEPAGE_H
  36. #include "codepage.h"
  37. #ifndef PAL_CLASSIC
  38. # define ATB_WORD_COUNT 6
  39. static LPWSTR gc_rgszAdditionalWords[CP_MAX][ATB_WORD_COUNT] = {
  40. { L"\x6230\x9B25\x901F\x5EA6", L"\x4E00", L"\x4E8C", L"\x4E09", L"\x56DB", L"\x4E94" },
  41. { L"\x6218\x6597\x901F\x5EA6", L"\x4E00", L"\x4E8C", L"\x4E09", L"\x56DB", L"\x4E94" },
  42. //{ L"\x6226\x95D8\x901F\x5EA6", L"\x4E00", L"\x4E8C", L"\x4E09", L"\x56DB", L"\x4E94" },
  43. };
  44. static LPWSTR gc_rgszDefaultAdditionalWords[ATB_WORD_COUNT] = { NULL, L"\xFF11", L"\xFF12", L"\xFF13", L"\xFF14", L"\xFF15" };
  45. #endif
  46. #define SDLPAL_EXTRA_WORD_COUNT 1
  47. static LPWSTR gc_rgszSDLPalWords[CP_MAX][SDLPAL_EXTRA_WORD_COUNT] = {
  48. { L"\x8FD4\x56DE\x8A2D\x5B9A" },
  49. { L"\x8FD4\x56DE\x8BBE\x7F6E" },
  50. };
  51. LPWSTR g_rcCredits[12];
  52. TEXTLIB g_TextLib;
  53. PAL_FORCE_INLINE int
  54. PAL_ParseLine(
  55. char *line,
  56. char **value,
  57. int *length,
  58. int deltrail
  59. )
  60. {
  61. //
  62. // Remove the leading spaces
  63. //
  64. while (*line && iswspace(*line)) line++;
  65. //
  66. // Skip comments starting with '#'
  67. //
  68. if (*line && *line != '#')
  69. {
  70. //
  71. // Split the index and value
  72. //
  73. LPSTR val = strchr(line, '=');
  74. if (val)
  75. {
  76. //
  77. // Remove the trailing spaces
  78. //
  79. LPSTR end = line + strlen(line);
  80. int index;
  81. if (end > line && end[-1] == '\n') *(--end) = 0;
  82. if (deltrail) while (end > line && iswspace(end[-1])) *(--end) = 0;
  83. //
  84. // Parse the index and pass out value
  85. //
  86. if (sscanf(line, "%d", &index) == 1)
  87. {
  88. *value = val + 1;
  89. *length = end - *value;
  90. return index;
  91. }
  92. }
  93. }
  94. return 0;
  95. }
  96. PAL_FORCE_INLINE char *
  97. PAL_ReadOneLine(
  98. char *temp,
  99. int limit,
  100. FILE *fp
  101. )
  102. {
  103. if (fgets(temp, limit, fp))
  104. {
  105. int n = strlen(temp);
  106. if (n == limit - 1 && temp[n - 1] != '\n' && !feof(fp))
  107. {
  108. // Line too long, try to read it as a whole
  109. int nn = 2;
  110. char *tmp = strdup(temp);
  111. while (!feof(fp))
  112. {
  113. if (!(tmp = (char *)realloc(tmp, nn * limit)))
  114. {
  115. TerminateOnError("PAL_ReadOneLine(): failed to allocate memory for long line!");
  116. }
  117. if (fgets(tmp + n, limit + 1, fp))
  118. {
  119. n += strlen(tmp + n);
  120. if (n < limit - 1 || temp[n - 1] == '\n')
  121. break;
  122. else
  123. nn++;
  124. }
  125. }
  126. if (tmp[n - 1] == '\n') tmp[n - 1] = 0;
  127. return tmp;
  128. }
  129. else
  130. {
  131. while (n > 0 && (temp[n - 1] == '\n' || temp[n - 1] == '\r')) temp[--n] = 0;
  132. return temp;
  133. }
  134. }
  135. else
  136. return NULL;
  137. }
  138. static int
  139. PAL_ReadMessageFile(
  140. FILE *fp
  141. )
  142. {
  143. char temp[MESSAGE_MAX_BUFFER_SIZE];
  144. struct _msg_entry
  145. {
  146. struct _msg_entry *next;
  147. wchar_t *value;
  148. } *cur_val = NULL;
  149. struct _msg_list_entry
  150. {
  151. struct _msg_list_entry *next;
  152. struct _msg_entry *value;
  153. int index;
  154. int count;
  155. } *head = NULL, *item = NULL;
  156. struct _word_list_entry
  157. {
  158. struct _word_list_entry *next;
  159. wchar_t *value;
  160. int index;
  161. } whead = { NULL, NULL }, *witem = NULL;
  162. enum _message_state
  163. {
  164. ST_OUTSIDE,
  165. ST_SETTING,
  166. ST_DIALOG,
  167. ST_WORD,
  168. ST_CREDIT,
  169. ST_LAYOUT
  170. } state = ST_OUTSIDE;
  171. int idx_cnt = 0, msg_cnt = 0, word_cnt = 0, sid, eid = -1;
  172. while (!feof(fp))
  173. {
  174. char *buffer;
  175. if ((buffer = PAL_ReadOneLine(temp, MESSAGE_MAX_BUFFER_SIZE, fp)) != NULL)
  176. {
  177. switch(state)
  178. {
  179. case ST_OUTSIDE:
  180. //
  181. // Skip comments starting with '#'
  182. //
  183. if (*buffer && *buffer != '#')
  184. {
  185. if (strncmp(buffer, "[BEGIN MESSAGE]", 15) == 0 &&
  186. sscanf(buffer + 15, "%d", &sid) == 1 && sid > eid)
  187. {
  188. state = ST_DIALOG;
  189. //
  190. // First save values (converted wide string) into a linked list
  191. //
  192. if (head)
  193. {
  194. item->next = (struct _msg_list_entry *)UTIL_malloc(sizeof(struct _msg_list_entry));
  195. item = item->next;
  196. }
  197. else
  198. {
  199. head = (struct _msg_list_entry *)UTIL_malloc(sizeof(struct _msg_list_entry));
  200. item = head;
  201. }
  202. item->value = NULL; item->index = sid;
  203. item->count = 0; item->next = NULL; cur_val = NULL;
  204. if (idx_cnt < item->index) idx_cnt = item->index;
  205. }
  206. else if (strncmp(buffer, "[BEGIN SETTING]", 15) == 0 && !witem)
  207. {
  208. state = ST_SETTING;
  209. }
  210. else if (strncmp(buffer, "[BEGIN WORDS]", 13) == 0 && !witem)
  211. {
  212. state = ST_WORD;
  213. //
  214. // First save values (converted wide string) into a linked list
  215. //
  216. witem = &whead;
  217. }
  218. else if (strncmp(buffer, "[BEGIN CREDITS]", 15) == 0 && !witem)
  219. {
  220. state = ST_CREDIT;
  221. }
  222. else if (strncmp(buffer, "[BEGIN LAYOUT]", 14) == 0 && !witem)
  223. {
  224. state = ST_LAYOUT;
  225. gConfig.fUseCustomScreenLayout = TRUE;
  226. }
  227. else
  228. {
  229. // Just ignore invalid lines
  230. UTIL_LogOutput(LOGLEVEL_WARNING, "PAL_ReadMessageFile(): encounter invalid line '%s'!\n", buffer);
  231. }
  232. }
  233. break;
  234. case ST_DIALOG:
  235. //
  236. // Check if to end one dialog
  237. //
  238. if (strncmp(buffer, "[END MESSAGE]", 13) == 0 &&
  239. sscanf(buffer + 13, "%d", &eid) == 1 && eid >= sid)
  240. {
  241. // End dialog
  242. state = ST_OUTSIDE;
  243. }
  244. else
  245. {
  246. if (cur_val)
  247. {
  248. cur_val->next = (struct _msg_entry *)UTIL_malloc(sizeof(struct _msg_entry));
  249. cur_val = cur_val->next;
  250. }
  251. else
  252. cur_val = (struct _msg_entry *)UTIL_malloc(sizeof(struct _msg_entry));
  253. if (strncmp(buffer, "[CLEAR MESSAGE]", 15) == 0)
  254. {
  255. cur_val->value = NULL;
  256. }
  257. else
  258. {
  259. int len = PAL_MultiByteToWideCharCP(CP_UTF_8, buffer, -1, NULL, 0);
  260. cur_val->value = (wchar_t *)UTIL_malloc(len * sizeof(wchar_t));
  261. PAL_MultiByteToWideCharCP(CP_UTF_8, buffer, -1, cur_val->value, len);
  262. msg_cnt++;
  263. }
  264. if (!item->value) item->value = cur_val;
  265. cur_val->next = NULL; item->count++;
  266. }
  267. break;
  268. case ST_WORD:
  269. //
  270. // Check if to end word list
  271. //
  272. if (strncmp(buffer, "[END WORDS]", 11) == 0)
  273. {
  274. // End word list
  275. state = ST_OUTSIDE;
  276. }
  277. else
  278. {
  279. char *v;
  280. int l, i = PAL_ParseLine(buffer, &v, &l, FALSE);
  281. if (i > 0)
  282. {
  283. int len = PAL_MultiByteToWideCharCP(CP_UTF_8, v, -1, NULL, 0);
  284. struct _word_list_entry *val = (struct _word_list_entry *)UTIL_malloc(sizeof(struct _word_list_entry));
  285. val->value = (wchar_t *)UTIL_malloc(len * sizeof(wchar_t));
  286. PAL_MultiByteToWideCharCP(CP_UTF_8, v, -1, val->value, len);
  287. val->index = i; val->next = NULL;
  288. witem->next = val; witem = witem->next;
  289. if (word_cnt < i) word_cnt = i;
  290. }
  291. }
  292. break;
  293. case ST_SETTING:
  294. //
  295. // Check if to end setting list
  296. //
  297. if (strncmp(buffer, "[END SETTING]", 13) == 0)
  298. {
  299. // End setting list
  300. state = ST_OUTSIDE;
  301. }
  302. else
  303. {
  304. char *line = buffer;
  305. while (*buffer && iswspace(*buffer)) line++;
  306. //
  307. // Skip comments starting with '#'
  308. //
  309. if (*line && *line != '#')
  310. {
  311. //
  312. // Split the index and value
  313. //
  314. LPSTR val = strchr(line, '=');
  315. if (val)
  316. {
  317. char index[80];
  318. *val = '\0';
  319. //
  320. // Remove the trailing spaces
  321. //
  322. LPSTR end = line + strlen(line);
  323. if (end > line && end[-1] == '\n') *(--end) = 0;
  324. if (FALSE) while (end > line && iswspace(end[-1])) *(--end) = 0;
  325. //
  326. // Parse the index and pass out value
  327. //
  328. if (sscanf(line, "%s", index) == 1 && strncasecmp(index, "UseISOFont", 10) == 0 )
  329. {
  330. g_TextLib.fUseISOFont = atoi(val + 1) == 1;
  331. }
  332. }
  333. }
  334. }
  335. break;
  336. case ST_CREDIT:
  337. //
  338. // Check if to end credit list
  339. //
  340. if (strncmp(buffer, "[END CREDITS]", 13) == 0)
  341. {
  342. // End credit list
  343. state = ST_OUTSIDE;
  344. }
  345. else
  346. {
  347. char *v;
  348. int l, i = PAL_ParseLine(buffer, &v, &l, FALSE);
  349. if ((i == 1 || (i >= 6 && i <= 11)) && !g_rcCredits[i])
  350. {
  351. int limit = (i == 1) ? 24 * 8 : 40 * 8, w = 0, j = 0, len;
  352. if (i == 6 || i == 7)
  353. {
  354. if (PAL_PLATFORM && PAL_CREDIT && PAL_PORTYEAR)
  355. {
  356. const char *templates[] = { "${platform}", "${author}", "${year}" };
  357. const char *values[] = { PAL_PLATFORM, PAL_CREDIT, PAL_PORTYEAR };
  358. const int matchlen[] = { 11, 9, 7 };
  359. const int valuelen[] = { sizeof(PAL_PLATFORM) - 1, sizeof(PAL_CREDIT) - 1, sizeof(PAL_PORTYEAR) - 1 };
  360. char *tmp = (char *)alloca(valuelen[0] + valuelen[1] + valuelen[2] + l + 1);
  361. char *dst = tmp, *src = v;
  362. while (*src)
  363. {
  364. if (*src == '$')
  365. {
  366. int k;
  367. for (k = 0; k < 3 && strncmp(src, templates[k], matchlen[k]); k++);
  368. if (k < 3)
  369. {
  370. strcpy(dst, values[k]);
  371. dst += valuelen[k];
  372. src += matchlen[k];
  373. continue;
  374. }
  375. }
  376. *dst++ = *src++;
  377. }
  378. *dst = 0;
  379. len = PAL_MultiByteToWideCharCP(CP_UTF_8, tmp, -1, NULL, 0);
  380. g_rcCredits[i] = (wchar_t *)UTIL_malloc(len * sizeof(wchar_t));
  381. PAL_MultiByteToWideCharCP(CP_UTF_8, tmp, -1, g_rcCredits[i], len);
  382. }
  383. }
  384. else
  385. {
  386. len = PAL_MultiByteToWideCharCP(CP_UTF_8, v, -1, NULL, 0);
  387. g_rcCredits[i] = (wchar_t *)UTIL_malloc(len * sizeof(wchar_t));
  388. PAL_MultiByteToWideCharCP(CP_UTF_8, v, -1, g_rcCredits[i], len);
  389. }
  390. if (g_rcCredits[i])
  391. {
  392. // Limit the length of texts
  393. while (w < limit && j < len - 1) w += PAL_CharWidth(g_rcCredits[i][j++]);
  394. if (w >= limit) g_rcCredits[i][w > limit ? j - 1 : j] = 0;
  395. }
  396. }
  397. }
  398. break;
  399. case ST_LAYOUT:
  400. if (strncmp(buffer, "[END LAYOUT]", 12) == 0)
  401. {
  402. // End layout
  403. state = ST_OUTSIDE;
  404. }
  405. else
  406. {
  407. char *v;
  408. int x, y, f, n, l, i = PAL_ParseLine(buffer, &v, &l, FALSE);
  409. if (i >= 1 && i <= (sizeof(SCREENLAYOUT) / sizeof(PAL_POS)))
  410. {
  411. if ((n = sscanf(v, "%d,%d,%d", &x, &y, &f)) >= 2 && x < 320 && y < 200)
  412. {
  413. gConfig.ScreenLayoutArray[i - 1] = PAL_XY(x, y);
  414. if (n == 3) gConfig.ScreenLayoutFlag[i - 1] = f;
  415. }
  416. }
  417. }
  418. break;
  419. default:
  420. TerminateOnError("PAL_ReadMessageFile(): Reached an unknown state. Something really wrong may have happened!");
  421. break;
  422. }
  423. if (buffer != temp) free(buffer);
  424. }
  425. }
  426. if (msg_cnt > 0)
  427. {
  428. //
  429. // Move values from linked list to array
  430. //
  431. int idx_msg = 1;
  432. g_TextLib.nIndices = (idx_cnt += 1);
  433. g_TextLib.nMsgs = (msg_cnt += 1);
  434. g_TextLib.lpIndexBuf = (int **)UTIL_calloc(idx_cnt, sizeof(int *));
  435. g_TextLib.lpMsgBuf = (LPWSTR *)UTIL_calloc(msg_cnt, sizeof(LPWSTR));
  436. for (item = head; item; )
  437. {
  438. struct _msg_list_entry *temp = item->next;
  439. struct _msg_entry *msg = item->value;
  440. int index = 0;
  441. g_TextLib.lpIndexBuf[item->index] = (int *)UTIL_calloc(item->count + 1, sizeof(int));
  442. while (msg)
  443. {
  444. struct _msg_entry *tmp = msg->next;
  445. if (msg->value)
  446. {
  447. g_TextLib.lpIndexBuf[item->index][index++] = idx_msg;
  448. g_TextLib.lpMsgBuf[idx_msg++] = msg->value;
  449. }
  450. else
  451. g_TextLib.lpIndexBuf[item->index][index++] = 0;
  452. free(msg); msg = tmp;
  453. }
  454. g_TextLib.lpIndexBuf[item->index][item->count] = -1;
  455. free(item); item = temp;
  456. }
  457. }
  458. if (word_cnt > 0)
  459. {
  460. //
  461. // Move values from linked list to array
  462. //
  463. #ifndef PAL_CLASSIC
  464. int i;
  465. #endif
  466. if (word_cnt < MINIMAL_WORD_COUNT - 1) word_cnt = MINIMAL_WORD_COUNT - 1;
  467. g_TextLib.nWords = (word_cnt += 1);
  468. g_TextLib.lpWordBuf = (LPWSTR *)UTIL_calloc(word_cnt, sizeof(LPWSTR));
  469. for (witem = whead.next; witem; )
  470. {
  471. struct _word_list_entry *temp = witem->next;
  472. g_TextLib.lpWordBuf[witem->index] = witem->value;
  473. free(witem); witem = temp;
  474. }
  475. #ifndef PAL_CLASSIC
  476. for (i = 1; i < ATB_WORD_COUNT; i++)
  477. if (!g_TextLib.lpWordBuf[i + SYSMENU_LABEL_BATTLEMODE])
  478. g_TextLib.lpWordBuf[i + SYSMENU_LABEL_BATTLEMODE] = gc_rgszDefaultAdditionalWords[i];
  479. #endif
  480. }
  481. fclose(fp);
  482. return (msg_cnt > 0 && word_cnt > 0) ? 1 : 0;
  483. }
  484. INT
  485. PAL_InitText(
  486. VOID
  487. )
  488. /*++
  489. Purpose:
  490. Initialize the in-game texts.
  491. Parameters:
  492. None.
  493. Return value:
  494. 0 = success.
  495. -1 = memory allocation error.
  496. --*/
  497. {
  498. if (gConfig.pszMsgFile)
  499. {
  500. //
  501. // Open the message, index and word data files.
  502. //
  503. FILE *fp = UTIL_OpenRequiredFileForMode(gConfig.pszMsgFile, "r");
  504. //
  505. // Read the contents of the message, index and word data files.
  506. //
  507. if (!PAL_ReadMessageFile(fp))
  508. {
  509. return -1;
  510. }
  511. else
  512. {
  513. DWORD dwWordLength = 0;
  514. int i;
  515. for (i = 1; i < g_TextLib.nWords; i++)
  516. {
  517. if (g_TextLib.lpWordBuf[i])
  518. {
  519. LPWSTR ptr = g_TextLib.lpWordBuf[i];
  520. DWORD n = 0;
  521. while (*ptr) n += PAL_CharWidth(*ptr++) >> 3;
  522. if (dwWordLength < n) dwWordLength = n;
  523. }
  524. }
  525. gConfig.dwWordLength = dwWordLength;
  526. for (i = 0; i < 12; i++)
  527. {
  528. if (!g_rcCredits[i])
  529. g_rcCredits[i] = L"";
  530. }
  531. }
  532. }
  533. else
  534. {
  535. FILE *fpMsg, *fpWord;
  536. DWORD *offsets;
  537. LPWSTR tmp;
  538. LPBYTE temp;
  539. int wpos, wlen, i;
  540. //
  541. // Open the message and word data files.
  542. //
  543. fpMsg = UTIL_OpenRequiredFile("m.msg");
  544. fpWord = UTIL_OpenRequiredFile("word.dat");
  545. //
  546. // See how many words we have
  547. //
  548. fseek(fpWord, 0, SEEK_END);
  549. i = ftell(fpWord);
  550. //
  551. // Each word has 10 bytes
  552. //
  553. g_TextLib.nWords = (i + (gConfig.dwWordLength - 1)) / gConfig.dwWordLength;
  554. if (g_TextLib.nWords < MINIMAL_WORD_COUNT) g_TextLib.nWords = MINIMAL_WORD_COUNT;
  555. //
  556. // Read the words
  557. //
  558. temp = (LPBYTE)malloc(gConfig.dwWordLength * g_TextLib.nWords);
  559. if (temp == NULL)
  560. {
  561. fclose(fpWord);
  562. fclose(fpMsg);
  563. return -1;
  564. }
  565. fseek(fpWord, 0, SEEK_SET);
  566. if (fread(temp, 1, i, fpWord) < (size_t)i)
  567. {
  568. fclose(fpWord);
  569. fclose(fpMsg);
  570. return -1;
  571. }
  572. memset(temp + i, 0, gConfig.dwWordLength * g_TextLib.nWords - i);
  573. //
  574. // Close the words file
  575. //
  576. fclose(fpWord);
  577. // Split the words and do code page conversion
  578. for (i = 0, wlen = 0; i < g_TextLib.nWords; i++)
  579. {
  580. int base = i * gConfig.dwWordLength;
  581. int pos = base + gConfig.dwWordLength - 1;
  582. while (pos >= base && temp[pos] == ' ') temp[pos--] = 0;
  583. wlen += PAL_MultiByteToWideChar((LPCSTR)temp + base, gConfig.dwWordLength, NULL, 0) + 1;
  584. }
  585. g_TextLib.lpWordBuf = (LPWSTR*)malloc(g_TextLib.nWords * sizeof(LPWSTR));
  586. if (g_TextLib.lpWordBuf == NULL)
  587. {
  588. free(temp);
  589. fclose(fpMsg);
  590. return -1;
  591. }
  592. tmp = (LPWSTR)malloc(wlen * sizeof(WCHAR));
  593. if (tmp == NULL)
  594. {
  595. free(g_TextLib.lpWordBuf);
  596. free(temp);
  597. fclose(fpMsg);
  598. return -1;
  599. }
  600. for (i = 0, wpos = 0; i < g_TextLib.nWords; i++)
  601. {
  602. int l;
  603. g_TextLib.lpWordBuf[i] = tmp + wpos;
  604. l = PAL_MultiByteToWideChar((LPCSTR)temp + i * gConfig.dwWordLength, gConfig.dwWordLength, g_TextLib.lpWordBuf[i], wlen - wpos);
  605. if (l > 0 && g_TextLib.lpWordBuf[i][l - 1] == '1')
  606. g_TextLib.lpWordBuf[i][l - 1] = 0;
  607. g_TextLib.lpWordBuf[i][l] = 0;
  608. wpos += l + 1;
  609. }
  610. free(temp);
  611. //
  612. // Read the message offsets. The message offsets are in SSS.MKF #3
  613. //
  614. i = PAL_MKFGetChunkSize(3, gpGlobals->f.fpSSS) / sizeof(DWORD);
  615. g_TextLib.nMsgs = i - 1;
  616. offsets = (LPDWORD)malloc(i * sizeof(DWORD));
  617. if (offsets == NULL)
  618. {
  619. free(g_TextLib.lpWordBuf[0]);
  620. free(g_TextLib.lpWordBuf);
  621. fclose(fpMsg);
  622. return -1;
  623. }
  624. PAL_MKFReadChunk((LPBYTE)(offsets), i * sizeof(DWORD), 3, gpGlobals->f.fpSSS);
  625. //
  626. // Read the messages.
  627. //
  628. fseek(fpMsg, 0, SEEK_END);
  629. i = ftell(fpMsg);
  630. temp = (LPBYTE)malloc(i);
  631. if (temp == NULL)
  632. {
  633. free(offsets);
  634. free(g_TextLib.lpWordBuf[0]);
  635. free(g_TextLib.lpWordBuf);
  636. fclose(fpMsg);
  637. return -1;
  638. }
  639. fseek(fpMsg, 0, SEEK_SET);
  640. if (fread(temp, 1, i, fpMsg) < (size_t)i)
  641. {
  642. free(offsets);
  643. free(g_TextLib.lpWordBuf[0]);
  644. free(g_TextLib.lpWordBuf);
  645. fclose(fpMsg);
  646. return -1;
  647. }
  648. fclose(fpMsg);
  649. // Split messages and do code page conversion here
  650. for (i = 0, wlen = 0; i < g_TextLib.nMsgs; i++)
  651. {
  652. wlen += PAL_MultiByteToWideChar((LPCSTR)temp + SDL_SwapLE32(offsets[i]), SDL_SwapLE32(offsets[i + 1]) - SDL_SwapLE32(offsets[i]), NULL, 0) + 1;
  653. }
  654. g_TextLib.lpMsgBuf = (LPWSTR*)malloc(g_TextLib.nMsgs * sizeof(LPWSTR));
  655. if (g_TextLib.lpMsgBuf == NULL)
  656. {
  657. free(g_TextLib.lpWordBuf[0]);
  658. free(g_TextLib.lpWordBuf);
  659. free(offsets);
  660. return -1;
  661. }
  662. tmp = (LPWSTR)malloc(wlen * sizeof(WCHAR));
  663. if (tmp == NULL)
  664. {
  665. free(g_TextLib.lpMsgBuf);
  666. free(g_TextLib.lpWordBuf[0]);
  667. free(g_TextLib.lpWordBuf);
  668. free(offsets);
  669. return -1;
  670. }
  671. for (i = 0, wpos = 0; i < g_TextLib.nMsgs; i++)
  672. {
  673. int l;
  674. g_TextLib.lpMsgBuf[i] = tmp + wpos;
  675. l = PAL_MultiByteToWideChar((LPCSTR)temp + SDL_SwapLE32(offsets[i]), SDL_SwapLE32(offsets[i + 1]) - SDL_SwapLE32(offsets[i]), g_TextLib.lpMsgBuf[i], wlen - wpos);
  676. g_TextLib.lpMsgBuf[i][l] = 0;
  677. wpos += l + 1;
  678. }
  679. free(temp);
  680. free(offsets);
  681. g_TextLib.lpIndexBuf = NULL;
  682. memcpy(g_TextLib.lpWordBuf + SYSMENU_LABEL_LAUNCHSETTING, gc_rgszSDLPalWords[PAL_GetCodePage()], SDLPAL_EXTRA_WORD_COUNT * sizeof(LPCWSTR));
  683. #ifndef PAL_CLASSIC
  684. memcpy(g_TextLib.lpWordBuf + SYSMENU_LABEL_BATTLEMODE, gc_rgszAdditionalWords[PAL_GetCodePage()], ATB_WORD_COUNT * sizeof(LPCWSTR));
  685. #endif
  686. }
  687. g_TextLib.bCurrentFontColor = FONT_COLOR_DEFAULT;
  688. g_TextLib.bIcon = 0;
  689. g_TextLib.posIcon = 0;
  690. g_TextLib.nCurrentDialogLine = 0;
  691. g_TextLib.iDelayTime = 3;
  692. g_TextLib.posDialogTitle = PAL_XY(12, 8);
  693. g_TextLib.posDialogText = PAL_XY(44, 26);
  694. g_TextLib.bDialogPosition = kDialogUpper;
  695. g_TextLib.fUserSkip = FALSE;
  696. PAL_MKFReadChunk(g_TextLib.bufDialogIcons, 282, 12, gpGlobals->f.fpDATA);
  697. return 0;
  698. }
  699. VOID
  700. PAL_FreeText(
  701. VOID
  702. )
  703. /*++
  704. Purpose:
  705. Free the memory used by the texts.
  706. Parameters:
  707. None.
  708. Return value:
  709. None.
  710. --*/
  711. {
  712. int i;
  713. if (g_TextLib.lpMsgBuf != NULL)
  714. {
  715. if (gConfig.pszMsgFile)
  716. for(i = 0; i < g_TextLib.nMsgs; i++) free(g_TextLib.lpMsgBuf[i]);
  717. else
  718. free(g_TextLib.lpMsgBuf[0]);
  719. free(g_TextLib.lpMsgBuf);
  720. g_TextLib.lpMsgBuf = NULL;
  721. }
  722. if (g_TextLib.lpWordBuf != NULL)
  723. {
  724. if (gConfig.pszMsgFile)
  725. for(i = 0; i < g_TextLib.nWords; i++) free(g_TextLib.lpWordBuf[i]);
  726. else
  727. free(g_TextLib.lpWordBuf[0]);
  728. free(g_TextLib.lpWordBuf);
  729. g_TextLib.lpWordBuf = NULL;
  730. }
  731. if (g_TextLib.lpIndexBuf != NULL)
  732. {
  733. if (gConfig.pszMsgFile)
  734. for(i = 0; i < g_TextLib.nIndices; i++) free(g_TextLib.lpIndexBuf[i]);
  735. else
  736. free(g_TextLib.lpIndexBuf[0]);
  737. free(g_TextLib.lpIndexBuf);
  738. g_TextLib.lpIndexBuf = NULL;
  739. }
  740. }
  741. LPCWSTR
  742. PAL_GetWord(
  743. int iNumWord
  744. )
  745. /*++
  746. Purpose:
  747. Get the specified word.
  748. Parameters:
  749. [IN] wNumWord - the number of the requested word.
  750. Return value:
  751. Pointer to the requested word. NULL if not found.
  752. --*/
  753. {
  754. return (iNumWord >= g_TextLib.nWords || !g_TextLib.lpWordBuf[iNumWord]) ? L"" : g_TextLib.lpWordBuf[iNumWord];
  755. }
  756. LPCWSTR
  757. PAL_GetMsg(
  758. int iNumMsg
  759. )
  760. /*++
  761. Purpose:
  762. Get the specified message.
  763. Parameters:
  764. [IN] wNumMsg - the number of the requested message.
  765. Return value:
  766. Pointer to the requested message. NULL if not found.
  767. --*/
  768. {
  769. return (iNumMsg >= g_TextLib.nMsgs || !g_TextLib.lpMsgBuf[iNumMsg]) ? L"" : g_TextLib.lpMsgBuf[iNumMsg];
  770. }
  771. int
  772. PAL_GetMsgNum(
  773. int iIndex,
  774. int iOrder
  775. )
  776. /*++
  777. Purpose:
  778. Get the number of specified message from index & order.
  779. Parameters:
  780. [IN] iMsgIndex - index.
  781. [IN] iOrder - order inside the index.
  782. Return value:
  783. The number of message. Zero means pausing for key, and -1 means end.
  784. --*/
  785. {
  786. return (iIndex >= g_TextLib.nMsgs || !g_TextLib.lpIndexBuf[iIndex]) ? -1 : g_TextLib.lpIndexBuf[iIndex][iOrder];
  787. }
  788. VOID
  789. PAL_DrawText(
  790. LPCWSTR lpszText,
  791. PAL_POS pos,
  792. BYTE bColor,
  793. BOOL fShadow,
  794. BOOL fUpdate,
  795. BOOL fUse8x8Font
  796. )
  797. /*++
  798. Purpose:
  799. Draw text on the screen.
  800. Parameters:
  801. [IN] lpszText - the text to be drawn.
  802. [IN] pos - Position of the text.
  803. [IN] bColor - Color of the text.
  804. [IN] fShadow - TRUE if the text is shadowed or not.
  805. [IN] fUpdate - TRUE if update the screen area.
  806. [IN] fUse8x8Font - TRUE if use 8x8 font.
  807. Return value:
  808. None.
  809. --*/
  810. {
  811. SDL_Rect rect, urect;
  812. urect.x = rect.x = PAL_X(pos);
  813. urect.y = rect.y = PAL_Y(pos);
  814. urect.h = (fUse8x8Font ? 8 : PAL_FontHeight()) + (fShadow ? 1 : 0);
  815. urect.w = 0;
  816. // Handle text overflow
  817. if (rect.x >= 320) return;
  818. while (*lpszText)
  819. {
  820. //
  821. // Draw the character
  822. //
  823. int char_width = fUse8x8Font ? 8 : PAL_CharWidth(*lpszText);
  824. if (fShadow)
  825. {
  826. PAL_DrawCharOnSurface(*lpszText, gpScreen, PAL_XY(rect.x + 1, rect.y + 1), 0, fUse8x8Font);
  827. PAL_DrawCharOnSurface(*lpszText, gpScreen, PAL_XY(rect.x + 1, rect.y), 0, fUse8x8Font);
  828. }
  829. PAL_DrawCharOnSurface(*lpszText++, gpScreen, PAL_XY(rect.x, rect.y), bColor, fUse8x8Font);
  830. rect.x += char_width; urect.w += char_width;
  831. }
  832. //
  833. // Update the screen area
  834. //
  835. if (fUpdate && urect.w > 0)
  836. {
  837. if (fShadow) urect.w++;
  838. if (urect.x + urect.w > 320)
  839. {
  840. urect.w = 320 - urect.x;
  841. }
  842. VIDEO_UpdateScreen(&urect);
  843. }
  844. }
  845. VOID
  846. PAL_DialogSetDelayTime(
  847. INT iDelayTime
  848. )
  849. /*++
  850. Purpose:
  851. Set the delay time for dialog.
  852. Parameters:
  853. [IN] iDelayTime - the delay time to be set.
  854. Return value:
  855. None.
  856. --*/
  857. {
  858. g_TextLib.iDelayTime = iDelayTime;
  859. }
  860. VOID
  861. PAL_StartDialog(
  862. BYTE bDialogLocation,
  863. BYTE bFontColor,
  864. INT iNumCharFace,
  865. BOOL fPlayingRNG
  866. )
  867. /*++
  868. Purpose:
  869. Start a new dialog.
  870. Parameters:
  871. [IN] bDialogLocation - the location of the text on the screen.
  872. [IN] bFontColor - the font color of the text.
  873. [IN] iNumCharFace - number of the character face in RGM.MKF.
  874. [IN] fPlayingRNG - whether we are playing a RNG video or not.
  875. Return value:
  876. None.
  877. --*/
  878. {
  879. PAL_LARGE BYTE buf[16384];
  880. SDL_Rect rect;
  881. if (gpGlobals->fInBattle && !g_fUpdatedInBattle)
  882. {
  883. //
  884. // Update the screen in battle, or the graphics may seem messed up
  885. //
  886. VIDEO_UpdateScreen(NULL);
  887. g_fUpdatedInBattle = TRUE;
  888. }
  889. g_TextLib.bIcon = 0;
  890. g_TextLib.posIcon = 0;
  891. g_TextLib.nCurrentDialogLine = 0;
  892. g_TextLib.posDialogTitle = PAL_XY(12, 8);
  893. g_TextLib.fUserSkip = FALSE;
  894. if (bFontColor != 0)
  895. {
  896. g_TextLib.bCurrentFontColor = bFontColor;
  897. }
  898. if (fPlayingRNG && iNumCharFace)
  899. {
  900. VIDEO_BackupScreen(gpScreen);
  901. g_TextLib.fPlayingRNG = TRUE;
  902. }
  903. switch (bDialogLocation)
  904. {
  905. case kDialogUpper:
  906. if (iNumCharFace > 0)
  907. {
  908. //
  909. // Display the character face at the upper part of the screen
  910. //
  911. if (PAL_MKFReadChunk(buf, 16384, iNumCharFace, gpGlobals->f.fpRGM) > 0)
  912. {
  913. rect.w = PAL_RLEGetWidth((LPCBITMAPRLE)buf);
  914. rect.h = PAL_RLEGetHeight((LPCBITMAPRLE)buf);
  915. rect.x = 48 - rect.w / 2;
  916. rect.y = 55 - rect.h / 2;
  917. if (rect.x < 0)
  918. {
  919. rect.x = 0;
  920. }
  921. if (rect.y < 0)
  922. {
  923. rect.y = 0;
  924. }
  925. PAL_RLEBlitToSurface((LPCBITMAPRLE)buf, gpScreen, PAL_XY(rect.x, rect.y));
  926. if (rect.x < 0)
  927. {
  928. rect.x = 0;
  929. }
  930. if (rect.y < 0)
  931. {
  932. rect.y = 0;
  933. }
  934. VIDEO_UpdateScreen(&rect);
  935. }
  936. }
  937. g_TextLib.posDialogTitle = PAL_XY(iNumCharFace > 0 ? 80 : 12, 8);
  938. g_TextLib.posDialogText = PAL_XY(iNumCharFace > 0 ? 96 : 44, 26);
  939. break;
  940. case kDialogCenter:
  941. g_TextLib.posDialogText = PAL_XY(80, 40);
  942. break;
  943. case kDialogLower:
  944. if (iNumCharFace > 0)
  945. {
  946. //
  947. // Display the character face at the lower part of the screen
  948. //
  949. if (PAL_MKFReadChunk(buf, 16384, iNumCharFace, gpGlobals->f.fpRGM) > 0)
  950. {
  951. rect.x = 270 - PAL_RLEGetWidth((LPCBITMAPRLE)buf) / 2;
  952. rect.y = 144 - PAL_RLEGetHeight((LPCBITMAPRLE)buf) / 2;
  953. PAL_RLEBlitToSurface((LPCBITMAPRLE)buf, gpScreen, PAL_XY(rect.x, rect.y));
  954. VIDEO_UpdateScreen(NULL);
  955. }
  956. }
  957. g_TextLib.posDialogTitle = PAL_XY(iNumCharFace > 0 ? 4 : 12, 108);
  958. g_TextLib.posDialogText = PAL_XY(iNumCharFace > 0 ? 20 : 44, 126);
  959. break;
  960. case kDialogCenterWindow:
  961. g_TextLib.posDialogText = PAL_XY(160, 40);
  962. break;
  963. }
  964. g_TextLib.bDialogPosition = bDialogLocation;
  965. }
  966. static VOID
  967. PAL_DialogWaitForKey(
  968. VOID
  969. )
  970. /*++
  971. Purpose:
  972. Wait for player to press a key after showing a dialog.
  973. Parameters:
  974. None.
  975. Return value:
  976. None.
  977. --*/
  978. {
  979. PAL_LARGE SDL_Color palette[256];
  980. SDL_Color *pCurrentPalette, t;
  981. int i;
  982. //
  983. // get the current palette
  984. //
  985. pCurrentPalette = PAL_GetPalette(gpGlobals->wNumPalette, gpGlobals->fNightPalette);
  986. memcpy(palette, pCurrentPalette, sizeof(palette));
  987. if (g_TextLib.bDialogPosition != kDialogCenterWindow &&
  988. g_TextLib.bDialogPosition != kDialogCenter)
  989. {
  990. //
  991. // show the icon
  992. //
  993. LPCBITMAPRLE p = PAL_SpriteGetFrame(g_TextLib.bufDialogIcons, g_TextLib.bIcon);
  994. if (p != NULL)
  995. {
  996. SDL_Rect rect;
  997. rect.x = PAL_X(g_TextLib.posIcon);
  998. rect.y = PAL_Y(g_TextLib.posIcon);
  999. rect.w = 16;
  1000. rect.h = 16;
  1001. PAL_RLEBlitToSurface(p, gpScreen, g_TextLib.posIcon);
  1002. VIDEO_UpdateScreen(&rect);
  1003. }
  1004. }
  1005. PAL_ClearKeyState();
  1006. while (TRUE)
  1007. {
  1008. UTIL_Delay(100);
  1009. if (g_TextLib.bDialogPosition != kDialogCenterWindow &&
  1010. g_TextLib.bDialogPosition != kDialogCenter)
  1011. {
  1012. //
  1013. // palette shift
  1014. //
  1015. t = palette[0xF9];
  1016. for (i = 0xF9; i < 0xFE; i++)
  1017. {
  1018. palette[i] = palette[i + 1];
  1019. }
  1020. palette[0xFE] = t;
  1021. VIDEO_SetPalette(palette);
  1022. }
  1023. if (g_InputState.dwKeyPress != 0)
  1024. {
  1025. break;
  1026. }
  1027. }
  1028. if (g_TextLib.bDialogPosition != kDialogCenterWindow &&
  1029. g_TextLib.bDialogPosition != kDialogCenter)
  1030. {
  1031. PAL_SetPalette(gpGlobals->wNumPalette, gpGlobals->fNightPalette);
  1032. }
  1033. PAL_ClearKeyState();
  1034. g_TextLib.fUserSkip = FALSE;
  1035. }
  1036. VOID
  1037. PAL_ShowDialogText(
  1038. LPCWSTR lpszText
  1039. )
  1040. /*++
  1041. Purpose:
  1042. Show one line of the dialog text.
  1043. Parameters:
  1044. [IN] lpszText - the text to be shown.
  1045. Return value:
  1046. None.
  1047. --*/
  1048. {
  1049. SDL_Rect rect;
  1050. int x, y;
  1051. PAL_ClearKeyState();
  1052. g_TextLib.bIcon = 0;
  1053. if (gpGlobals->fInBattle && !g_fUpdatedInBattle)
  1054. {
  1055. //
  1056. // Update the screen in battle, or the graphics may seem messed up
  1057. //
  1058. VIDEO_UpdateScreen(NULL);
  1059. g_fUpdatedInBattle = TRUE;
  1060. }
  1061. if (g_TextLib.nCurrentDialogLine > 3)
  1062. {
  1063. //
  1064. // The rest dialogs should be shown in the next page.
  1065. //
  1066. PAL_DialogWaitForKey();
  1067. g_TextLib.nCurrentDialogLine = 0;
  1068. VIDEO_RestoreScreen(gpScreen);
  1069. VIDEO_UpdateScreen(NULL);
  1070. }
  1071. x = PAL_X(g_TextLib.posDialogText);
  1072. y = PAL_Y(g_TextLib.posDialogText) + g_TextLib.nCurrentDialogLine * 18;
  1073. if (g_TextLib.bDialogPosition == kDialogCenterWindow)
  1074. {
  1075. //
  1076. // The text should be shown in a small window at the center of the screen
  1077. //
  1078. #ifndef PAL_CLASSIC
  1079. if (gpGlobals->fInBattle && g_Battle.BattleResult == kBattleResultOnGoing)
  1080. {
  1081. PAL_BattleUIShowText(lpszText, 1400);
  1082. }
  1083. else
  1084. #endif
  1085. {
  1086. PAL_POS pos;
  1087. LPBOX lpBox;
  1088. int i, w = wcslen(lpszText), len = 0;
  1089. for (i = 0; i < w; i++)
  1090. len += PAL_CharWidth(lpszText[i]) >> 3;
  1091. //
  1092. // Create the window box
  1093. //
  1094. pos = PAL_XY(PAL_X(g_TextLib.posDialogText) - len * 4, PAL_Y(g_TextLib.posDialogText));
  1095. // Follow behavior of original version
  1096. lpBox = PAL_CreateSingleLineBoxWithShadow(pos, (len + 1) / 2, FALSE, 0);
  1097. rect.x = PAL_X(pos);
  1098. rect.y = PAL_Y(pos);
  1099. rect.w = 320 - rect.x * 2 + 32;
  1100. rect.h = 64;
  1101. //
  1102. // Show the text on the screen
  1103. //
  1104. pos = PAL_XY(PAL_X(pos) + 8 + ((len & 1) << 2), PAL_Y(pos) + 10);
  1105. PAL_DrawText(lpszText, pos, 0, FALSE, FALSE, FALSE);
  1106. VIDEO_UpdateScreen(&rect);
  1107. PAL_DialogWaitForKey();
  1108. //
  1109. // Delete the box
  1110. //
  1111. PAL_DeleteBox(lpBox);
  1112. VIDEO_UpdateScreen(&rect);
  1113. PAL_EndDialog();
  1114. }
  1115. }
  1116. else
  1117. {
  1118. int len = wcslen(lpszText);
  1119. if (g_TextLib.nCurrentDialogLine == 0 &&
  1120. g_TextLib.bDialogPosition != kDialogCenter &&
  1121. (lpszText[len - 1] == 0xff1a ||
  1122. lpszText[len - 1] == 0x2236 || // Special case for Pal WIN95 Simplified Chinese version
  1123. lpszText[len - 1] == ':')
  1124. )
  1125. {
  1126. //
  1127. // name of character
  1128. //
  1129. PAL_DrawText(lpszText, g_TextLib.posDialogTitle, FONT_COLOR_CYAN_ALT, TRUE, TRUE, FALSE);
  1130. }
  1131. else
  1132. {
  1133. //
  1134. // normal texts
  1135. //
  1136. WCHAR text[2];
  1137. if (!g_TextLib.fPlayingRNG && g_TextLib.nCurrentDialogLine == 0)
  1138. {
  1139. //
  1140. // Save the screen before we show the first line of dialog
  1141. //
  1142. VIDEO_BackupScreen(gpScreen);
  1143. }
  1144. while (lpszText != NULL && *lpszText != '\0')
  1145. {
  1146. switch (*lpszText)
  1147. {
  1148. case '-':
  1149. //
  1150. // Set the font color to Cyan
  1151. //
  1152. if (g_TextLib.bCurrentFontColor == FONT_COLOR_CYAN)
  1153. {
  1154. g_TextLib.bCurrentFontColor = FONT_COLOR_DEFAULT;
  1155. }
  1156. else
  1157. {
  1158. g_TextLib.bCurrentFontColor = FONT_COLOR_CYAN;
  1159. }
  1160. lpszText++;
  1161. break;
  1162. #if 0
  1163. /* Not used */
  1164. case '\'':
  1165. //
  1166. // Set the font color to Red
  1167. //
  1168. if (g_TextLib.bCurrentFontColor == FONT_COLOR_RED)
  1169. {
  1170. g_TextLib.bCurrentFontColor = FONT_COLOR_DEFAULT;
  1171. }
  1172. else
  1173. {
  1174. g_TextLib.bCurrentFontColor = FONT_COLOR_RED;
  1175. }
  1176. lpszText++;
  1177. break;
  1178. #endif
  1179. case '\"':
  1180. //
  1181. // Set the font color to Yellow
  1182. //
  1183. if (g_TextLib.bCurrentFontColor == FONT_COLOR_YELLOW)
  1184. {
  1185. g_TextLib.bCurrentFontColor = FONT_COLOR_DEFAULT;
  1186. }
  1187. else
  1188. {
  1189. g_TextLib.bCurrentFontColor = FONT_COLOR_YELLOW;
  1190. }
  1191. lpszText++;
  1192. break;
  1193. case '$':
  1194. //
  1195. // Set the delay time of text-displaying
  1196. //
  1197. g_TextLib.iDelayTime = wcstol(lpszText + 1, NULL, 10) * 10 / 7;
  1198. lpszText += 3;
  1199. break;
  1200. case '~':
  1201. //
  1202. // Delay for a period and quit
  1203. //
  1204. if (g_TextLib.fUserSkip)
  1205. {
  1206. VIDEO_UpdateScreen(NULL);
  1207. }
  1208. UTIL_Delay(wcstol(lpszText + 1, NULL, 10) * 80 / 7);
  1209. g_TextLib.nCurrentDialogLine = 0;
  1210. g_TextLib.fUserSkip = FALSE;
  1211. return; // don't go further
  1212. case ')':
  1213. //
  1214. // Set the waiting icon
  1215. //
  1216. g_TextLib.bIcon = 1;
  1217. lpszText++;
  1218. break;
  1219. case '(':
  1220. //
  1221. // Set the waiting icon
  1222. //
  1223. g_TextLib.bIcon = 2;
  1224. lpszText++;
  1225. break;
  1226. case '\\':
  1227. lpszText++;
  1228. default:
  1229. text[0] = *lpszText++;
  1230. text[1] = 0;
  1231. // Update the screen on each draw operation is time-consuming, so disable it if user want to skip
  1232. PAL_DrawText(text, PAL_XY(x, y), g_TextLib.bCurrentFontColor, TRUE, !g_TextLib.fUserSkip, FALSE);
  1233. x += PAL_CharWidth(text[0]);
  1234. if (!g_TextLib.fUserSkip)
  1235. {
  1236. PAL_ClearKeyState();
  1237. UTIL_Delay(g_TextLib.iDelayTime * 8);
  1238. if (g_InputState.dwKeyPress & (kKeySearch | kKeyMenu))
  1239. {
  1240. //
  1241. // User pressed a key to skip the dialog
  1242. //
  1243. g_TextLib.fUserSkip = TRUE;
  1244. }
  1245. }
  1246. }
  1247. }
  1248. // and update the full screen at once after all texts are drawn
  1249. if (g_TextLib.fUserSkip)
  1250. {
  1251. VIDEO_UpdateScreen(NULL);
  1252. }
  1253. g_TextLib.posIcon = PAL_XY(x, y);
  1254. g_TextLib.nCurrentDialogLine++;
  1255. }
  1256. }
  1257. }
  1258. VOID
  1259. PAL_ClearDialog(
  1260. BOOL fWaitForKey
  1261. )
  1262. /*++
  1263. Purpose:
  1264. Clear the state of the dialog.
  1265. Parameters:
  1266. [IN] fWaitForKey - whether wait for any key or not.
  1267. Return value:
  1268. None.
  1269. --*/
  1270. {
  1271. if (g_TextLib.nCurrentDialogLine > 0 && fWaitForKey)
  1272. {
  1273. PAL_DialogWaitForKey();
  1274. }
  1275. g_TextLib.nCurrentDialogLine = 0;
  1276. if (g_TextLib.bDialogPosition == kDialogCenter)
  1277. {
  1278. g_TextLib.posDialogTitle = PAL_XY(12, 8);
  1279. g_TextLib.posDialogText = PAL_XY(44, 26);
  1280. g_TextLib.bCurrentFontColor = FONT_COLOR_DEFAULT;
  1281. g_TextLib.bDialogPosition = kDialogUpper;
  1282. }
  1283. }
  1284. VOID
  1285. PAL_EndDialog(
  1286. VOID
  1287. )
  1288. /*++
  1289. Purpose:
  1290. Ends a dialog.
  1291. Parameters:
  1292. None.
  1293. Return value:
  1294. None.
  1295. --*/
  1296. {
  1297. PAL_ClearDialog(TRUE);
  1298. //
  1299. // Set some default parameters, as there are some parts of script
  1300. // which doesn't have a "start dialog" instruction before showing the dialog.
  1301. //
  1302. g_TextLib.posDialogTitle = PAL_XY(12, 8);
  1303. g_TextLib.posDialogText = PAL_XY(44, 26);
  1304. g_TextLib.bCurrentFontColor = FONT_COLOR_DEFAULT;
  1305. g_TextLib.bDialogPosition = kDialogUpper;
  1306. g_TextLib.fUserSkip = FALSE;
  1307. g_TextLib.fPlayingRNG = FALSE;
  1308. }
  1309. BOOL
  1310. PAL_IsInDialog(
  1311. VOID
  1312. )
  1313. /*++
  1314. Purpose:
  1315. Check if there are dialog texts on the screen.
  1316. Parameters:
  1317. None.
  1318. Return value:
  1319. TRUE if there are dialog texts on the screen, FALSE if not.
  1320. --*/
  1321. {
  1322. return (g_TextLib.nCurrentDialogLine != 0);
  1323. }
  1324. BOOL
  1325. PAL_DialogIsPlayingRNG(
  1326. VOID
  1327. )
  1328. /*++
  1329. Purpose:
  1330. Check if the script used the RNG playing parameter when displaying texts.
  1331. Parameters:
  1332. None.
  1333. Return value:
  1334. TRUE if the script used the RNG playing parameter, FALSE if not.
  1335. --*/
  1336. {
  1337. return g_TextLib.fPlayingRNG;
  1338. }
  1339. WCHAR
  1340. PAL_GetInvalidChar(
  1341. CODEPAGE uCodePage
  1342. )
  1343. {
  1344. switch (uCodePage)
  1345. {
  1346. case CP_BIG5: return 0x3f;
  1347. case CP_GBK: return 0x3f;
  1348. //case CP_SHIFTJIS: return 0x30fb;
  1349. case CP_UTF_8: return 0x3f;
  1350. default: return 0;
  1351. }
  1352. }
  1353. static CODEPAGE g_codepage = CP_UTF_8;
  1354. CODEPAGE
  1355. PAL_GetCodePage(
  1356. void
  1357. )
  1358. {
  1359. return g_codepage;
  1360. }
  1361. void
  1362. PAL_SetCodePage(
  1363. CODEPAGE uCodePage
  1364. )
  1365. {
  1366. g_codepage = uCodePage;
  1367. }
  1368. CODEPAGE
  1369. PAL_DetectCodePageForString(
  1370. const char * text,
  1371. int text_len,
  1372. CODEPAGE default_cp,
  1373. int * probability
  1374. )
  1375. {
  1376. // Try to convert the content of word.dat with different codepages,
  1377. // and use the codepage with minimal inconvertible characters
  1378. // Works fine currently for detecting Simplified Chinese & Traditional Chinese.
  1379. // Since we're using language files to support additional languages, this detection
  1380. // should be fine for us now.
  1381. int min_invalids = INT_MAX;
  1382. if (text && text_len > 0)
  1383. {
  1384. // The file to be detected should not contain characters outside these ranges
  1385. const static int valid_ranges[][2] = {
  1386. { 0x4E00, 0x9FFF }, // CJK Unified Ideographs
  1387. { 0x3400, 0x4DBF }, // CJK Unified Ideographs Extension A
  1388. { 0xF900, 0xFAFF }, // CJK Compatibility Ideographs
  1389. { 0x0020, 0x007E }, // Basic ASCII
  1390. { 0x3000, 0x301E }, // CJK Symbols
  1391. { 0xFF01, 0xFF5E }, // Fullwidth Forms
  1392. };
  1393. for (CODEPAGE i = CP_BIG5; i <= CP_GBK; i++)
  1394. {
  1395. int invalids, length = PAL_MultiByteToWideCharCP(i, text, text_len, NULL, 0);
  1396. WCHAR *wbuf = (WCHAR *)malloc(length * sizeof(WCHAR));
  1397. PAL_MultiByteToWideCharCP(i, text, text_len, wbuf, length);
  1398. for (int j = invalids = 0; j < length; j++)
  1399. {
  1400. int score = 1;
  1401. for (int k = 0; k < sizeof(valid_ranges) / sizeof(valid_ranges[0]); k++)
  1402. {
  1403. if (wbuf[j] >= valid_ranges[k][0] &&
  1404. wbuf[j] <= valid_ranges[k][1])
  1405. {
  1406. score = 0;
  1407. break;
  1408. }
  1409. }
  1410. invalids += score;
  1411. }
  1412. // code page with less invalid chars wins
  1413. if (invalids < min_invalids)
  1414. {
  1415. min_invalids = invalids;
  1416. default_cp = i;
  1417. }
  1418. free(wbuf);
  1419. }
  1420. }
  1421. if (probability)
  1422. {
  1423. if (min_invalids < text_len / 2)
  1424. *probability = (text_len / 2 - min_invalids) * 200 / text_len;
  1425. else
  1426. *probability = 0;
  1427. }
  1428. return default_cp;
  1429. }
  1430. INT
  1431. PAL_MultiByteToWideCharCP(
  1432. CODEPAGE cp,
  1433. LPCSTR mbs,
  1434. int mbslength,
  1435. LPWSTR wcs,
  1436. int wcslength
  1437. )
  1438. /*++
  1439. Purpose:
  1440. Convert multi-byte string into the corresponding unicode string.
  1441. Parameters:
  1442. [IN] cp - Code page for conversion.
  1443. [IN] mbs - Pointer to the multi-byte string.
  1444. [IN] mbslength - Length of the multi-byte string, or -1 for auto-detect.
  1445. [IN] wcs - Pointer to the wide string buffer.
  1446. [IN] wcslength - Length of the wide string buffer.
  1447. Return value:
  1448. The length of converted wide string. If mbslength is set to -1, the returned
  1449. value includes the terminal null-char; otherwise, the null-char is not included.
  1450. If wcslength is set to 0, wcs can be set to NULL and the return value is the
  1451. required length of the wide string buffer.
  1452. --*/
  1453. {
  1454. int i = 0, state = 0, wlen = 0, null = 0;
  1455. if (mbslength == -1)
  1456. {
  1457. mbslength = strlen(mbs);
  1458. null = 1;
  1459. }
  1460. if (!wcs)
  1461. {
  1462. switch (cp)
  1463. {
  1464. //case CP_SHIFTJIS:
  1465. // for (i = 0; i < mbslength && mbs[i]; i++)
  1466. // {
  1467. // if (state == 0)
  1468. // {
  1469. // if ((BYTE)mbs[i] <= 0x80 || (BYTE)mbs[i] >= 0xfd || ((BYTE)mbs[i] >= 0xa0 && (BYTE)mbs[i] <= 0xdf))
  1470. // wlen++;
  1471. // else
  1472. // state = 1;
  1473. // }
  1474. // else
  1475. // {
  1476. // wlen++;
  1477. // state = 0;
  1478. // }
  1479. // }
  1480. // break;
  1481. case CP_GBK:
  1482. case CP_BIG5:
  1483. for (i = 0; i < mbslength && mbs[i]; i++)
  1484. {
  1485. if (state == 0)
  1486. {
  1487. if ((BYTE)mbs[i] <= 0x80 || (BYTE)mbs[i] == 0xff)
  1488. wlen++;
  1489. else
  1490. state = 1;
  1491. }
  1492. else
  1493. {
  1494. wlen++;
  1495. state = 0;
  1496. }
  1497. }
  1498. break;
  1499. case CP_UTF_8:
  1500. for (i = 0; i < mbslength && mbs[i]; i++)
  1501. {
  1502. if (state == 0)
  1503. {
  1504. if ((BYTE)mbs[i] >= 0x80)
  1505. {
  1506. BYTE s = (BYTE)mbs[i] << 1;
  1507. while (s >= 0x80) { state++; s <<= 1; }
  1508. if (state < 1 || state > 3)
  1509. {
  1510. state = 0;
  1511. wlen++;
  1512. }
  1513. }
  1514. else
  1515. wlen++;
  1516. }
  1517. else
  1518. {
  1519. if ((BYTE)mbs[i] >= 0x80 && (BYTE)mbs[i] < 0xc0)
  1520. {
  1521. if (--state == 0) wlen++;
  1522. }
  1523. else
  1524. {
  1525. state = 0; wlen++;
  1526. }
  1527. }
  1528. }
  1529. break;
  1530. default:
  1531. return -1;
  1532. }
  1533. if (i < mbslength && !mbs[i]) null = 1;
  1534. return wlen + null + (state != 0);
  1535. }
  1536. else
  1537. {
  1538. WCHAR invalid_char;
  1539. switch (cp)
  1540. {
  1541. //case CP_SHIFTJIS:
  1542. // invalid_char = 0x30fb;
  1543. // for (i = 0; i < mbslength && wlen < wcslength && mbs[i]; i++)
  1544. // {
  1545. // if (state == 0)
  1546. // {
  1547. // if ((BYTE)mbs[i] <= 0x80)
  1548. // wcs[wlen++] = mbs[i];
  1549. // else if ((BYTE)mbs[i] >= 0xa0 && (BYTE)mbs[i] <= 0xdf)
  1550. // wcs[wlen++] = cptbl_jis_half[(BYTE)mbs[i] - 0xa0];
  1551. // else if ((BYTE)mbs[i] == 0xfd)
  1552. // wcs[wlen++] = 0xf8f1;
  1553. // else if ((BYTE)mbs[i] == 0xfe)
  1554. // wcs[wlen++] = 0xf8f2;
  1555. // else if ((BYTE)mbs[i] == 0xff)
  1556. // wcs[wlen++] = 0xf8f3;
  1557. // else
  1558. // state = 1;
  1559. // }
  1560. // else
  1561. // {
  1562. // if ((BYTE)mbs[i] < 0x40)
  1563. // wcs[wlen++] = 0x30fb;
  1564. // else if ((BYTE)mbs[i - 1] < 0xa0)
  1565. // wcs[wlen++] = cptbl_jis[(BYTE)mbs[i - 1] - 0x81][(BYTE)mbs[i] - 0x40];
  1566. // else
  1567. // wcs[wlen++] = cptbl_jis[(BYTE)mbs[i - 1] - 0xc1][(BYTE)mbs[i] - 0x40];
  1568. // state = 0;
  1569. // }
  1570. // }
  1571. // break;
  1572. case CP_GBK:
  1573. invalid_char = 0x3f;
  1574. for (i = 0; i < mbslength && wlen < wcslength && mbs[i]; i++)
  1575. {
  1576. if (state == 0)
  1577. {
  1578. if ((BYTE)mbs[i] < 0x80)
  1579. wcs[wlen++] = mbs[i];
  1580. else if ((BYTE)mbs[i] == 0x80)
  1581. wcs[wlen++] = 0x20ac;
  1582. else if ((BYTE)mbs[i] == 0xff)
  1583. wcs[wlen++] = 0xf8f5;
  1584. else
  1585. state = 1;
  1586. }
  1587. else
  1588. {
  1589. if ((BYTE)mbs[i] < 0x40)
  1590. wcs[wlen++] = invalid_char;
  1591. else
  1592. wcs[wlen++] = cptbl_gbk[(BYTE)mbs[i - 1] - 0x81][(BYTE)mbs[i] - 0x40];
  1593. state = 0;
  1594. }
  1595. }
  1596. break;
  1597. case CP_BIG5:
  1598. invalid_char = 0x3f;
  1599. for (i = 0; i < mbslength && wlen < wcslength && mbs[i]; i++)
  1600. {
  1601. if (state == 0)
  1602. {
  1603. if ((BYTE)mbs[i] <= 0x80)
  1604. wcs[wlen++] = mbs[i];
  1605. else if ((BYTE)mbs[i] == 0xff)
  1606. wcs[wlen++] = 0xf8f8;
  1607. else
  1608. state = 1;
  1609. }
  1610. else
  1611. {
  1612. if ((BYTE)mbs[i] < 0x40 || ((BYTE)mbs[i] >= 0x7f && (BYTE)mbs[i] <= 0xa0))
  1613. wcs[wlen++] = invalid_char;
  1614. else if ((BYTE)mbs[i] <= 0x7e)
  1615. wcs[wlen++] = cptbl_big5[(BYTE)mbs[i - 1] - 0x81][(BYTE)mbs[i] - 0x40];
  1616. else
  1617. wcs[wlen++] = cptbl_big5[(BYTE)mbs[i - 1] - 0x81][(BYTE)mbs[i] - 0x60];
  1618. state = 0;
  1619. }
  1620. }
  1621. break;
  1622. case CP_UTF_8:
  1623. invalid_char = 0x3f;
  1624. for (i = 0; i < mbslength && wlen < wcslength && mbs[i]; i++)
  1625. {
  1626. if (state == 0)
  1627. {
  1628. if ((BYTE)mbs[i] >= 0x80)
  1629. {
  1630. BYTE s = (BYTE)mbs[i] << 1;
  1631. while (s >= 0x80) { state++; s <<= 1; }
  1632. if (state < 1 || state > 3)
  1633. {
  1634. state = 0;
  1635. wcs[wlen++] = invalid_char;
  1636. }
  1637. else
  1638. {
  1639. wcs[wlen] = s >> (state + 1);
  1640. }
  1641. }
  1642. else
  1643. wcs[wlen++] = mbs[i];
  1644. }
  1645. else
  1646. {
  1647. if ((BYTE)mbs[i] >= 0x80 && (BYTE)mbs[i] < 0xc0)
  1648. {
  1649. wcs[wlen] <<= 6;
  1650. wcs[wlen] |= (BYTE)mbs[i] & 0x3f;
  1651. if (--state == 0) wlen++;
  1652. }
  1653. else
  1654. {
  1655. state = 0;
  1656. wcs[wlen++] = invalid_char;
  1657. }
  1658. }
  1659. }
  1660. break;
  1661. default:
  1662. return -1;
  1663. }
  1664. if (state != 0 && wlen < wcslength)
  1665. {
  1666. wcs[wlen++] = invalid_char;
  1667. }
  1668. if (null || (i < mbslength && !mbs[i]))
  1669. {
  1670. if (wlen < wcslength)
  1671. wcs[wlen++] = 0;
  1672. else
  1673. wcs[wlen - 1] = 0;
  1674. }
  1675. return wlen;
  1676. }
  1677. }
  1678. INT
  1679. PAL_MultiByteToWideChar(
  1680. LPCSTR mbs,
  1681. int mbslength,
  1682. LPWSTR wcs,
  1683. int wcslength
  1684. )
  1685. /*++
  1686. Purpose:
  1687. Convert multi-byte string into the corresponding unicode string.
  1688. Parameters:
  1689. [IN] mbs - Pointer to the multi-byte string.
  1690. [IN] mbslength - Length of the multi-byte string, or -1 for auto-detect.
  1691. [IN] wcs - Pointer to the wide string buffer.
  1692. [IN] wcslength - Length of the wide string buffer.
  1693. Return value:
  1694. The length of converted wide string. If mbslength is set to -1, the returned
  1695. value includes the terminal null-char; otherwise, the null-char is not included.
  1696. If wcslength is set to 0, wcs can be set to NULL and the return value is the
  1697. required length of the wide string buffer.
  1698. --*/
  1699. {
  1700. return PAL_MultiByteToWideCharCP(g_codepage, mbs, mbslength, wcs, wcslength);
  1701. }
  1702. INT
  1703. PAL_swprintf(
  1704. LPWSTR buffer,
  1705. size_t count,
  1706. LPCWSTR format,
  1707. ...
  1708. )
  1709. /*++
  1710. Purpose:
  1711. Formatted wide-character output conversion that output Chinese characters correctly.
  1712. This function supported a subset of format strings that are commonly supported by
  1713. various C libraries, which can be formalized as following:
  1714. %[flags] [width] [.precision] [{h | l | ll}] type
  1715. When handling '%c' and '%s', this function follows the Linux's library convention,
  1716. which means '%c' and '%s' always output multi-byte strings, and '%lc' and '%ls'
  1717. always output wide-char strings.
  1718. Parameters:
  1719. [IN] buffer - Storage location for output.
  1720. [IN] count - Length of the output buffer in characters including the termination null one.
  1721. [IN] format - Format-control string.
  1722. [IN] ... - Optional arguments.
  1723. Return value:
  1724. The length of outputed wide string, not including the termination null character.
  1725. --*/
  1726. {
  1727. va_list ap;
  1728. const WCHAR * const format_end = format + wcslen(format);
  1729. const WCHAR * const buffer_end = buffer + count - 1;
  1730. WCHAR chr_buf[2] = { 0, 0 };
  1731. LPCWSTR fmt_start = NULL;
  1732. LPWSTR cur_fmt = NULL;
  1733. size_t fmt_len = 0;
  1734. int state, precision = 0, width = 0;
  1735. int left_aligned = 0, wide = 0, narrow = 0;
  1736. int width_var = 0, precision_var = 0, precision_defined = 0;
  1737. // Buffer & length check
  1738. if (buffer == NULL || format == NULL)
  1739. {
  1740. errno = EINVAL;
  1741. return -1;
  1742. }
  1743. if (buffer_end <= buffer)
  1744. return 0;
  1745. va_start(ap, format);
  1746. count = 0; state = 0;
  1747. while (buffer < buffer_end && format < format_end)
  1748. {
  1749. switch (state)
  1750. {
  1751. case 0: // Outside format spec
  1752. if (*format != L'%')
  1753. {
  1754. *buffer++ = *format++;
  1755. count++;
  1756. }
  1757. else
  1758. {
  1759. fmt_start = format++;
  1760. left_aligned = wide = narrow = 0;
  1761. precision_var = width_var = 0;
  1762. precision_defined = 0;
  1763. state = 1;
  1764. }
  1765. continue;
  1766. case 1: // [flags]
  1767. switch (*format)
  1768. {
  1769. case L'-':
  1770. left_aligned = 1;
  1771. case L'+':
  1772. case L' ':
  1773. case L'#':
  1774. case L'0':
  1775. format++;
  1776. continue;
  1777. default:
  1778. state = 2;
  1779. width = width_var = 0;
  1780. }
  1781. case 2: // [width]
  1782. switch (*format)
  1783. {
  1784. case '0':
  1785. case '1':
  1786. case '2':
  1787. case '3':
  1788. case '4':
  1789. case '5':
  1790. case '6':
  1791. case '7':
  1792. case '8':
  1793. case '9':
  1794. if (width >= 0)
  1795. width = width * 10 + (*format - L'0');
  1796. format++;
  1797. continue;
  1798. case '*':
  1799. if (width == 0)
  1800. width_var = 1;
  1801. format++;
  1802. continue;
  1803. case '.':
  1804. format++;
  1805. precision = precision_var = 0;
  1806. precision_defined = 1;
  1807. state = 3;
  1808. continue;
  1809. default:
  1810. state = 4;
  1811. continue;
  1812. }
  1813. case 3: // [.precision]
  1814. switch (*format)
  1815. {
  1816. case '0':
  1817. case '1':
  1818. case '2':
  1819. case '3':
  1820. case '4':
  1821. case '5':
  1822. case '6':
  1823. case '7':
  1824. case '8':
  1825. case '9':
  1826. if (precision >= 0)
  1827. precision = precision * 10 + (*format - L'0');
  1828. format++;
  1829. continue;
  1830. case '*':
  1831. if (precision == 0)
  1832. precision_var = 1;
  1833. format++;
  1834. continue;
  1835. default:
  1836. state = 4;
  1837. }
  1838. case 4: // [{h | l | ll}]
  1839. switch (*format)
  1840. {
  1841. case 'l': if (narrow == 0) wide++; format++; continue;
  1842. case 'h': if (wide == 0) narrow++; format++; continue;
  1843. default: state = 5;
  1844. }
  1845. case 5: // type
  1846. if (*format == 'c' || *format == 's')
  1847. {
  1848. // We handle char & str specially
  1849. LPWSTR buf;
  1850. size_t len;
  1851. int i;
  1852. // Check width
  1853. if (width_var)
  1854. {
  1855. width = va_arg(ap, int);
  1856. left_aligned = (width < 0);
  1857. width = left_aligned ? -width : width;
  1858. }
  1859. // Although precision has no meaning to '%c' output, however
  1860. // the argument still needs to be read if '.*' is provided
  1861. if (precision_var)
  1862. precision = va_arg(ap, int);
  1863. else if (!precision_defined)
  1864. precision = INT_MAX;
  1865. if (*format == 's')
  1866. {
  1867. // For ANSI string, convert it through PAL_MultiByteToWideChar
  1868. // To improve effciency, here just test the length and left
  1869. // actual conversion later directly into the output buffer
  1870. if (wide)
  1871. {
  1872. buf = va_arg(ap, LPWSTR);
  1873. len = wcslen(buf);
  1874. }
  1875. else
  1876. {
  1877. buf = (LPWSTR)va_arg(ap, LPSTR);
  1878. len = PAL_MultiByteToWideChar((LPCSTR)buf, -1, NULL, 0) - 1;
  1879. }
  1880. }
  1881. else
  1882. {
  1883. // For ANSI character, put it into the internal buffer
  1884. if (wide)
  1885. chr_buf[0] = va_arg(ap, WCHAR);
  1886. else
  1887. chr_buf[0] = va_arg(ap, int);
  1888. buf = chr_buf; len = 1;
  1889. }
  1890. // Limit output length no longer then precision
  1891. if (precision > (int)len)
  1892. precision = len;
  1893. // Left-side padding
  1894. for (i = 0; !left_aligned && i < width - precision && buffer < buffer_end; i++)
  1895. *buffer++ = L' ', count++;
  1896. // Do not overflow the output buffer
  1897. if (buffer + precision > buffer_end)
  1898. precision = buffer_end - buffer;
  1899. // Convert or copy string (char) into output buffer
  1900. if (*format == 's' && !wide)
  1901. PAL_MultiByteToWideChar((LPCSTR)buf, -1, buffer, precision);
  1902. else
  1903. wcsncpy(buffer, buf, precision);
  1904. buffer += precision; count += precision;
  1905. // Right-side padding
  1906. for (i = 0; left_aligned && i < width - precision && buffer < buffer_end; i++)
  1907. *buffer++ = L' ', count++;
  1908. }
  1909. else
  1910. {
  1911. // For other types, pass them directly into vswprintf
  1912. int cur_cnt = 0;
  1913. va_list apd;
  1914. // We copy this argument's format string into internal buffer
  1915. if (fmt_len < (size_t)(format - fmt_start + 1))
  1916. cur_fmt = realloc(cur_fmt, ((fmt_len = format - fmt_start + 1) + 1) * sizeof(WCHAR));
  1917. wcsncpy(cur_fmt, fmt_start, fmt_len);
  1918. cur_fmt[fmt_len] = L'\0';
  1919. // And pass it into vswprintf to get the output
  1920. va_copy(apd, ap);
  1921. cur_cnt = vswprintf(buffer, buffer_end - buffer, cur_fmt, apd);
  1922. va_end(apd);
  1923. buffer += cur_cnt; count += cur_cnt;
  1924. // Then we need to move the argument pointer into next one
  1925. // Check if width/precision should be read from arguments
  1926. if (width_var) va_arg(ap, int);
  1927. if (precision_var) va_arg(ap, int);
  1928. // Move pointer to pass the actual value argument
  1929. switch (*format)
  1930. {
  1931. case 'd':
  1932. case 'i':
  1933. case 'o':
  1934. case 'u':
  1935. case 'x':
  1936. case 'X':
  1937. if (wide == 1)
  1938. va_arg(ap, long);
  1939. else if (wide >= 2)
  1940. va_arg(ap, long long);
  1941. else
  1942. va_arg(ap, int);
  1943. break;
  1944. case 'e':
  1945. case 'E':
  1946. case 'f':
  1947. case 'g':
  1948. case 'G':
  1949. case 'a':
  1950. case 'A':
  1951. va_arg(ap, double);
  1952. break;
  1953. case 'p':
  1954. case 'n':
  1955. va_arg(ap, void*);
  1956. break;
  1957. }
  1958. }
  1959. state = 0;
  1960. format++;
  1961. break;
  1962. }
  1963. }
  1964. // If the format string is malformed, try to copy it into the dest buffer
  1965. if (state && buffer < buffer_end)
  1966. {
  1967. int fmt_len = format - fmt_start;
  1968. int buf_len = buffer_end - buffer;
  1969. if (fmt_len <= buf_len)
  1970. {
  1971. wcsncpy(buffer, fmt_start, buf_len);
  1972. buffer += fmt_len;
  1973. }
  1974. else
  1975. {
  1976. wcsncpy(buffer, fmt_start, buf_len);
  1977. buffer += buf_len;
  1978. }
  1979. }
  1980. // NULL-terminate the string
  1981. *buffer = L'\0';
  1982. va_end(ap);
  1983. return count;
  1984. }