util.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873
  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. #include "util.h"
  23. #include "input.h"
  24. #include "global.h"
  25. #include "palcfg.h"
  26. #include <errno.h>
  27. #include "midi.h"
  28. #if SDL_VERSION_ATLEAST(2, 0, 0)
  29. #include "SDL_video.h"
  30. #include "SDL_messagebox.h"
  31. #endif
  32. static char internal_buffer[PAL_MAX_GLOBAL_BUFFERS + 1][PAL_GLOBAL_BUFFER_SIZE];
  33. void UTIL_MsgBox(char *string)
  34. {
  35. #if SDL_VERSION_ATLEAST(2, 0, 0)
  36. extern SDL_Window *gpWindow;
  37. char buffer[300];
  38. SDL_MessageBoxButtonData buttons[] = { { 0, 0, "OK" } };
  39. SDL_MessageBoxData mbd = { SDL_MESSAGEBOX_WARNING, gpWindow, "Alert",buffer, 1, buttons, NULL };
  40. int btnid;
  41. sprintf(buffer, "%s\n", string);
  42. SDL_ShowMessageBox(&mbd, &btnid);
  43. #endif
  44. }
  45. long
  46. flength(
  47. FILE *fp
  48. )
  49. {
  50. long old_pos = ftell(fp), length;
  51. if (old_pos == -1) return -1;
  52. if (fseek(fp, 0, SEEK_END) == -1) return -1;
  53. length = ftell(fp); fseek(fp, old_pos, SEEK_SET);
  54. return length;
  55. }
  56. void
  57. trim(
  58. char *str
  59. )
  60. /*++
  61. Purpose:
  62. Remove the leading and trailing spaces in a string.
  63. Parameters:
  64. str - the string to proceed.
  65. Return value:
  66. None.
  67. --*/
  68. {
  69. int pos = 0;
  70. char *dest = str;
  71. //
  72. // skip leading blanks
  73. //
  74. while (str[pos] <= ' ' && str[pos] > 0)
  75. pos++;
  76. while (str[pos])
  77. {
  78. *(dest++) = str[pos];
  79. pos++;
  80. }
  81. *(dest--) = '\0'; // store the null
  82. //
  83. // remove trailing blanks
  84. //
  85. while (dest >= str && *dest <= ' ' && *dest > 0)
  86. *(dest--) = '\0';
  87. }
  88. char *
  89. UTIL_va(
  90. char *buffer,
  91. int buflen,
  92. const char *format,
  93. ...
  94. )
  95. {
  96. if (buflen > 0 && buffer)
  97. {
  98. va_list argptr;
  99. va_start(argptr, format);
  100. vsnprintf(buffer, buflen, format, argptr);
  101. va_end(argptr);
  102. return buffer;
  103. }
  104. else
  105. {
  106. return NULL;
  107. }
  108. }
  109. /*
  110. * RNG code based on RACC by Pierre-Marie Baty.
  111. * http://racc.bots-united.com
  112. *
  113. * Copyright (c) 2004, Pierre-Marie Baty
  114. * All rights reserved.
  115. *
  116. * Redistribution and use in source and binary forms, with or
  117. * without modification, are permitted provided that the following
  118. * conditions are met:
  119. *
  120. * Redistributions of source code must retain the above copyright
  121. * notice, this list of conditions and the following disclaimer.
  122. *
  123. * Redistributions in binary form must reproduce the above copyright
  124. * notice, this list of conditions and the following disclaimer in
  125. * the documentation and/or other materials provided with the
  126. * distribution.
  127. *
  128. * Neither the name of the RACC nor the names of its contributors
  129. * may be used to endorse or promote products derived from this
  130. * software without specific prior written permission.
  131. *
  132. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  133. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  134. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  135. * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  136. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
  137. * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  138. * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
  139. * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  140. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  141. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  142. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  143. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  144. * POSSIBILITY OF SUCH DAMAGE.
  145. */
  146. //
  147. // Our random number generator's seed.
  148. //
  149. static int glSeed = 0;
  150. static void
  151. lsrand(
  152. unsigned int iInitialSeed
  153. )
  154. /*++
  155. Purpose:
  156. This function initializes the random seed based on the initial seed value passed in the
  157. iInitialSeed parameter.
  158. Parameters:
  159. [IN] iInitialSeed - The initial random seed.
  160. Return value:
  161. None.
  162. --*/
  163. {
  164. //
  165. // fill in the initial seed of the random number generator
  166. //
  167. glSeed = 1664525L * iInitialSeed + 1013904223L;
  168. }
  169. static int
  170. lrand(
  171. void
  172. )
  173. /*++
  174. Purpose:
  175. This function is the equivalent of the rand() standard C library function, except that
  176. whereas rand() works only with short integers (i.e. not above 32767), this function is
  177. able to generate 32-bit random numbers.
  178. Parameters:
  179. None.
  180. Return value:
  181. The generated random number.
  182. --*/
  183. {
  184. if (glSeed == 0) // if the random seed isn't initialized...
  185. lsrand((unsigned int)time(NULL)); // initialize it first
  186. glSeed = 1664525L * glSeed + 1013904223L; // do some twisted math (infinite suite)
  187. return ((glSeed >> 1) + 1073741824L); // and return the result.
  188. }
  189. int
  190. RandomLong(
  191. int from,
  192. int to
  193. )
  194. /*++
  195. Purpose:
  196. This function returns a random integer number between (and including) the starting and
  197. ending values passed by parameters from and to.
  198. Parameters:
  199. from - the starting value.
  200. to - the ending value.
  201. Return value:
  202. The generated random number.
  203. --*/
  204. {
  205. if (to <= from)
  206. return from;
  207. return from + lrand() / (INT_MAX / (to - from + 1));
  208. }
  209. float
  210. RandomFloat(
  211. float from,
  212. float to
  213. )
  214. /*++
  215. Purpose:
  216. This function returns a random floating-point number between (and including) the starting
  217. and ending values passed by parameters from and to.
  218. Parameters:
  219. from - the starting value.
  220. to - the ending value.
  221. Return value:
  222. The generated random number.
  223. --*/
  224. {
  225. if (to <= from)
  226. return from;
  227. return from + (float)lrand() / (INT_MAX / (to - from));
  228. }
  229. void
  230. UTIL_Delay(
  231. unsigned int ms
  232. )
  233. {
  234. unsigned int t = SDL_GetTicks() + ms;
  235. while (PAL_PollEvent(NULL));
  236. while (!SDL_TICKS_PASSED(SDL_GetTicks(), t))
  237. {
  238. SDL_Delay(1);
  239. while (PAL_PollEvent(NULL));
  240. }
  241. }
  242. void
  243. TerminateOnError(
  244. const char *fmt,
  245. ...
  246. )
  247. // This function terminates the game because of an error and
  248. // prints the message string pointed to by fmt both in the
  249. // console and in a messagebox.
  250. {
  251. va_list argptr;
  252. char string[256];
  253. extern VOID PAL_Shutdown(int);
  254. // concatenate all the arguments in one string
  255. va_start(argptr, fmt);
  256. vsnprintf(string, sizeof(string), fmt, argptr);
  257. va_end(argptr);
  258. fprintf(stderr, "\nFATAL ERROR: %s\n", string);
  259. #if SDL_VERSION_ATLEAST(2, 0, 0)
  260. {
  261. extern SDL_Window *gpWindow;
  262. char buffer[300];
  263. SDL_MessageBoxButtonData buttons[2] = { { 0, 0, "Yes" },{ 0, 1, "No" } };
  264. SDL_MessageBoxData mbd = { SDL_MESSAGEBOX_ERROR, gpWindow, "FATAL ERROR", buffer, 2, buttons, NULL };
  265. int btnid;
  266. sprintf(buffer, "%sLaunch setting dialog on next start?\n", string);
  267. if (SDL_ShowMessageBox(&mbd, &btnid) == 0 && btnid == 0)
  268. {
  269. gConfig.fLaunchSetting = TRUE;
  270. PAL_SaveConfig();
  271. }
  272. PAL_Shutdown(255);
  273. }
  274. #else
  275. PAL_FATAL_OUTPUT(string);
  276. #endif
  277. #ifdef _DEBUG
  278. assert(!"TerminateOnError()"); // allows jumping to debugger
  279. #endif
  280. PAL_Shutdown(255);
  281. }
  282. void *
  283. UTIL_malloc(
  284. size_t buffer_size
  285. )
  286. {
  287. // handy wrapper for operations we always forget, like checking malloc's returned pointer.
  288. void *buffer;
  289. // first off, check if buffer size is valid
  290. if (buffer_size == 0)
  291. TerminateOnError("UTIL_malloc() called with invalid buffer size: %d\n", buffer_size);
  292. buffer = malloc(buffer_size); // allocate real memory space
  293. // last check, check if malloc call succeeded
  294. if (buffer == NULL)
  295. TerminateOnError("UTIL_malloc() failure for %d bytes (out of memory?)\n", buffer_size);
  296. return buffer; // nothing went wrong, so return buffer pointer
  297. }
  298. void *
  299. UTIL_calloc(
  300. size_t n,
  301. size_t size
  302. )
  303. {
  304. // handy wrapper for operations we always forget, like checking calloc's returned pointer.
  305. void *buffer;
  306. // first off, check if buffer size is valid
  307. if (n == 0 || size == 0)
  308. TerminateOnError ("UTIL_calloc() called with invalid parameters\n");
  309. buffer = calloc(n, size); // allocate real memory space
  310. // last check, check if malloc call succeeded
  311. if (buffer == NULL)
  312. TerminateOnError("UTIL_calloc() failure for %d bytes (out of memory?)\n", size * n);
  313. return buffer; // nothing went wrong, so return buffer pointer
  314. }
  315. FILE *
  316. UTIL_OpenRequiredFile(
  317. LPCSTR lpszFileName
  318. )
  319. /*++
  320. Purpose:
  321. Open a required file. If fails, quit the program.
  322. Parameters:
  323. [IN] lpszFileName - file name to open.
  324. Return value:
  325. Pointer to the file.
  326. --*/
  327. {
  328. return UTIL_OpenRequiredFileForMode(lpszFileName, "rb");
  329. }
  330. FILE *
  331. UTIL_OpenRequiredFileForMode(
  332. LPCSTR lpszFileName,
  333. LPCSTR szMode
  334. )
  335. /*++
  336. Purpose:
  337. Open a required file. If fails, quit the program.
  338. Parameters:
  339. [IN] lpszFileName - file name to open.
  340. [IN] szMode - file open mode.
  341. Return value:
  342. Pointer to the file.
  343. --*/
  344. {
  345. FILE *fp = UTIL_OpenFileForMode(lpszFileName, szMode);
  346. if (fp == NULL)
  347. {
  348. TerminateOnError("File open error(%d): %s!\n", errno, lpszFileName);
  349. }
  350. return fp;
  351. }
  352. FILE *
  353. UTIL_OpenFile(
  354. LPCSTR lpszFileName
  355. )
  356. /*++
  357. Purpose:
  358. Open a file. If fails, return NULL.
  359. Parameters:
  360. [IN] lpszFileName - file name to open.
  361. Return value:
  362. Pointer to the file.
  363. --*/
  364. {
  365. return UTIL_OpenFileForMode(lpszFileName, "rb");
  366. }
  367. FILE *
  368. UTIL_OpenFileForMode(
  369. LPCSTR lpszFileName,
  370. LPCSTR szMode
  371. )
  372. /*++
  373. Purpose:
  374. Open a file. If fails, return NULL.
  375. Parameters:
  376. [IN] lpszFileName - file name to open.
  377. [IN] szMode - file open mode.
  378. Return value:
  379. Pointer to the file.
  380. --*/
  381. {
  382. //
  383. // If lpszFileName is an absolute path, use its last element as filename
  384. //
  385. if (UTIL_IsAbsolutePath(lpszFileName))
  386. {
  387. char *temp = strdup(lpszFileName), *filename = temp;
  388. FILE *fp = NULL;
  389. for (char *next = strpbrk(filename, PAL_PATH_SEPARATORS); next; next = strpbrk(filename = next + 1, PAL_PATH_SEPARATORS));
  390. if (*filename)
  391. {
  392. filename[-1] = '\0';
  393. fp = UTIL_OpenFileAtPathForMode(*temp ? temp : "/", filename, szMode);
  394. }
  395. free(temp);
  396. return fp;
  397. }
  398. return UTIL_OpenFileAtPathForMode(gConfig.pszGamePath, lpszFileName, szMode);
  399. }
  400. FILE *
  401. UTIL_OpenFileAtPath(
  402. LPCSTR lpszPath,
  403. LPCSTR lpszFileName
  404. )
  405. {
  406. return UTIL_OpenFileAtPathForMode(lpszPath, lpszFileName, "rb");
  407. }
  408. FILE *
  409. UTIL_OpenFileAtPathForMode(
  410. LPCSTR lpszPath,
  411. LPCSTR lpszFileName,
  412. LPCSTR szMode
  413. )
  414. {
  415. if (!lpszPath || !lpszFileName || !szMode) return NULL;
  416. //
  417. // Construct full path according to lpszPath and lpszFileName
  418. //
  419. const char *path = UTIL_GetFullPathName(internal_buffer[PAL_MAX_GLOBAL_BUFFERS], PAL_GLOBAL_BUFFER_SIZE, lpszPath, lpszFileName);
  420. //
  421. // If no matching path, check the open mode
  422. //
  423. if (path)
  424. {
  425. return fopen(path, szMode);
  426. }
  427. else if (szMode[0] != 'r')
  428. {
  429. return fopen(UTIL_CombinePath(internal_buffer[PAL_MAX_GLOBAL_BUFFERS], PAL_GLOBAL_BUFFER_SIZE, 2, lpszPath, lpszFileName), szMode);
  430. }
  431. else
  432. {
  433. return NULL;
  434. }
  435. }
  436. VOID
  437. UTIL_CloseFile(
  438. FILE *fp
  439. )
  440. /*++
  441. Purpose:
  442. Close a file.
  443. Parameters:
  444. [IN] fp - file handle to be closed.
  445. Return value:
  446. None.
  447. --*/
  448. {
  449. if (fp != NULL)
  450. {
  451. fclose(fp);
  452. }
  453. }
  454. const char *
  455. UTIL_GetFullPathName(
  456. char *buffer,
  457. size_t buflen,
  458. const char *basepath,
  459. const char *subpath
  460. )
  461. {
  462. if (!buffer || !basepath || !subpath || buflen == 0) return NULL;
  463. int baselen = strlen(basepath), sublen = strlen(subpath);
  464. if (sublen == 0) return NULL;
  465. char *_base = strdup(basepath), *_sub = strdup(subpath);
  466. const char *result = NULL;
  467. if (access(UTIL_CombinePath(internal_buffer[PAL_MAX_GLOBAL_BUFFERS], PAL_GLOBAL_BUFFER_SIZE, 2, _base, _sub), 0) == 0)
  468. {
  469. result = internal_buffer[PAL_MAX_GLOBAL_BUFFERS];
  470. }
  471. #if !defined(PAL_FILESYSTEM_IGNORE_CASE) || !PAL_FILESYSTEM_IGNORE_CASE
  472. if (result == NULL)
  473. {
  474. size_t pos = strspn(_sub, PAL_PATH_SEPARATORS);
  475. if (pos < sublen)
  476. {
  477. char *start = _sub + pos;
  478. char *end = strpbrk(start, PAL_PATH_SEPARATORS);
  479. if (end) *end = '\0';
  480. //
  481. // try to find the matching file in the directory.
  482. //
  483. struct dirent **list;
  484. int n = scandir(_base, &list, 0, alphasort);
  485. while (n-- > 0)
  486. {
  487. if (!result && strcasecmp(list[n]->d_name, start) == 0)
  488. {
  489. result = UTIL_CombinePath(internal_buffer[PAL_MAX_GLOBAL_BUFFERS], PAL_GLOBAL_BUFFER_SIZE, 2, _base, list[n]->d_name);
  490. if (end)
  491. result = UTIL_GetFullPathName(internal_buffer[PAL_MAX_GLOBAL_BUFFERS], PAL_GLOBAL_BUFFER_SIZE, result, end + 1);
  492. else if (access(result, 0) != 0)
  493. result = NULL;
  494. }
  495. free(list[n]);
  496. }
  497. free(list);
  498. }
  499. }
  500. #endif
  501. if (result != NULL)
  502. {
  503. result = (char *)memmove(buffer, result, min(buflen, strlen(result)));
  504. }
  505. free(_base);
  506. free(_sub);
  507. return result;
  508. }
  509. const char *
  510. UTIL_CombinePath(
  511. char *buffer,
  512. size_t buflen,
  513. int numentry,
  514. ...
  515. )
  516. {
  517. if (buffer && buflen > 0 && numentry > 0)
  518. {
  519. const char *retval = buffer;
  520. va_list argptr;
  521. va_start(argptr, numentry);
  522. for (int i = 0; i < numentry && buflen > 1; i++)
  523. {
  524. const char *path = va_arg(argptr, const char *);
  525. int path_len = path ? strlen(path) : 0;
  526. int append_delim = (i < numentry - 1 && path_len > 0 && !PAL_IS_PATH_SEPARATOR(path[path_len - 1]));
  527. for (int is_sep = 0, j = 0; j < path_len && buflen > (size_t)append_delim + 1; j++)
  528. {
  529. //
  530. // Skip continuous path separators
  531. //
  532. if (PAL_IS_PATH_SEPARATOR(path[j]))
  533. {
  534. if (is_sep)
  535. continue;
  536. else
  537. is_sep = 1;
  538. }
  539. else
  540. {
  541. is_sep = 0;
  542. }
  543. *buffer++ = path[j];
  544. buflen--;
  545. }
  546. //
  547. // Make sure a path delimeter is append to the destination if this is not the last entry
  548. //
  549. if (append_delim)
  550. {
  551. *buffer++ = PAL_PATH_SEPARATORS[0];
  552. buflen--;
  553. }
  554. }
  555. va_end(argptr);
  556. *buffer = '\0';
  557. return retval;
  558. }
  559. else
  560. {
  561. return NULL;
  562. }
  563. }
  564. char *
  565. UTIL_GlobalBuffer(
  566. int index
  567. )
  568. {
  569. return (index >= 0 && index < PAL_MAX_GLOBAL_BUFFERS) ? internal_buffer[index] : NULL;
  570. }
  571. #if !defined(PAL_HAS_PLATFORM_SPECIFIC_UTILS)
  572. BOOL
  573. UTIL_GetScreenSize(
  574. DWORD *pdwScreenWidth,
  575. DWORD *pdwScreenHeight
  576. )
  577. {
  578. return FALSE;
  579. }
  580. BOOL
  581. UTIL_IsAbsolutePath(
  582. LPCSTR lpszFileName
  583. )
  584. {
  585. return FALSE;
  586. }
  587. INT
  588. UTIL_Platform_Init(
  589. int argc,
  590. char* argv[]
  591. )
  592. {
  593. gConfig.fLaunchSetting = FALSE;
  594. return 0;
  595. }
  596. VOID
  597. UTIL_Platform_Quit(
  598. VOID
  599. )
  600. {
  601. }
  602. #endif
  603. /*
  604. * Logging utilities
  605. */
  606. #ifndef PAL_LOG_BUFFER_SIZE
  607. # define PAL_LOG_BUFFER_SIZE 4096
  608. #endif
  609. #define PAL_LOG_BUFFER_EXTRA_SIZE 32
  610. static LOGCALLBACK _log_callbacks[PAL_LOG_MAX_OUTPUTS];
  611. static LOGLEVEL _log_callback_levels[PAL_LOG_MAX_OUTPUTS];
  612. static char _log_buffer[PAL_LOG_BUFFER_SIZE + PAL_LOG_BUFFER_EXTRA_SIZE];
  613. static const char * const _loglevel_str[] = {
  614. "[VERBOSE]",
  615. " [DEBUG]",
  616. " [INFO]",
  617. "[WARNING]",
  618. " [ERROR]",
  619. " [FATAL]",
  620. };
  621. int
  622. UTIL_LogAddOutputCallback(
  623. LOGCALLBACK callback,
  624. LOGLEVEL loglevel
  625. )
  626. {
  627. if (!callback) return -1;
  628. // De-duplication
  629. for (int i = 0; i < PAL_LOG_MAX_OUTPUTS; i++)
  630. {
  631. if (!_log_callbacks[i])
  632. {
  633. _log_callbacks[i] = callback;
  634. }
  635. if (_log_callbacks[i] == callback)
  636. {
  637. _log_callback_levels[i] = loglevel;
  638. return i;
  639. }
  640. }
  641. return -1;
  642. }
  643. void
  644. UTIL_LogRemoveOutputCallback(
  645. int id
  646. )
  647. {
  648. if (id < 0 || id >= PAL_LOG_MAX_OUTPUTS) return;
  649. while (id < PAL_LOG_MAX_OUTPUTS - 1)
  650. {
  651. _log_callbacks[id] = _log_callbacks[id + 1];
  652. _log_callback_levels[id] = _log_callback_levels[id + 1];
  653. id++;
  654. }
  655. _log_callbacks[id] = NULL;
  656. _log_callback_levels[id] = LOGLEVEL_MIN;
  657. }
  658. void
  659. UTIL_LogOutput(
  660. LOGLEVEL level,
  661. const char *fmt,
  662. ...
  663. )
  664. {
  665. va_list va;
  666. time_t tv = time(NULL);
  667. struct tm *tmval = localtime(&tv);
  668. int id, n;
  669. if (level < gConfig.iLogLevel || !_log_callbacks[0]) return;
  670. if (level > LOGLEVEL_MAX) level = LOGLEVEL_MAX;
  671. snprintf(_log_buffer, PAL_LOG_BUFFER_EXTRA_SIZE,
  672. "%04d-%02d-%02d %02d:%02d:%02d %s: ",
  673. tmval->tm_year + 1900, tmval->tm_mon, tmval->tm_mday,
  674. tmval->tm_hour, tmval->tm_min, tmval->tm_sec,
  675. _loglevel_str[level]);
  676. va_start(va, fmt);
  677. n = vsnprintf(_log_buffer + PAL_LOG_BUFFER_EXTRA_SIZE - 1, PAL_LOG_BUFFER_SIZE, fmt, va);
  678. va_end(va);
  679. n = (n == -1) ? PAL_LOG_BUFFER_EXTRA_SIZE + PAL_LOG_BUFFER_SIZE - 1 : n + PAL_LOG_BUFFER_EXTRA_SIZE;
  680. _log_buffer[n--] = '\0';
  681. if (_log_buffer[n] != '\n') _log_buffer[n] = '\n';
  682. for(id = 0; id < PAL_LOG_MAX_OUTPUTS && _log_callbacks[id]; id++)
  683. {
  684. if (level >= _log_callback_levels[id])
  685. {
  686. _log_callbacks[id](level, _log_buffer, _log_buffer + PAL_LOG_BUFFER_EXTRA_SIZE - 1);
  687. }
  688. }
  689. }
  690. void
  691. UTIL_LogSetLevel(
  692. LOGLEVEL minlevel
  693. )
  694. {
  695. if (minlevel < LOGLEVEL_MIN)
  696. gConfig.iLogLevel = LOGLEVEL_MIN;
  697. else if (minlevel > LOGLEVEL_MAX)
  698. gConfig.iLogLevel = LOGLEVEL_MAX;
  699. else
  700. gConfig.iLogLevel = minlevel;
  701. }
  702. void
  703. UTIL_LogToFile(
  704. LOGLEVEL _,
  705. const char *string,
  706. const char *__
  707. )
  708. {
  709. FILE *fp = fopen(gConfig.pszLogFile, "a");
  710. if (fp)
  711. {
  712. fputs(string, fp);
  713. fclose(fp);
  714. }
  715. }