Debian Codegraph @

engine/stratagus/util.cpp

raw
1 // ____ _ __
2 // / __ )____ _____ | | / /___ ___________
3 // / __ / __ \/ ___/ | | /| / / __ `/ ___/ ___/
4 // / /_/ / /_/ (__ ) | |/ |/ / /_/ / / (__ )
5 // /_____/\____/____/ |__/|__/\__,_/_/ /____/
6 //
7 // A futuristic real-time strategy game.
8 // This file is part of Bos Wars.
9 //
10 /**@name util.cpp - General utilites. */
11 //
12 // (c) Copyright 1998-2006 by Lutz Sammer and Jimmy Salmon
13 //
14 // This program is free software; you can redistribute it and/or modify
15 // it under the terms of the GNU General Public License as published by
16 // the Free Software Foundation; only version 2 of the License.
17 //
18 // This program is distributed in the hope that it will be useful,
19 // but WITHOUT ANY WARRANTY; without even the implied warranty of
20 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 // GNU General Public License for more details.
22 //
23 // You should have received a copy of the GNU General Public License
24 // along with this program; if not, write to the Free Software
25 // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
26 // 02111-1307, USA.
27 //
28
29 #include <stdlib.h>
30 #include <stdio.h>
31 #include <stdarg.h>
32 #include <string.h>
33 #include <ctype.h>
34 #include <errno.h>
35
36 #include "stratagus.h"
37 #include "util.h"
38
39 #ifdef USE_WIN32
40 #define WIN32_LEAN_AND_MEAN
41 #undef NOUSER
42 #include <windows.h>
43 #elif defined(HAVE_X)
44 #include <X11/Xlib.h>
45 #include <X11/Xatom.h>
46 #endif
47
48 /*----------------------------------------------------------------------------
49 -- Random
50 ----------------------------------------------------------------------------*/
51
52 unsigned SyncRandSeed; /// sync random seed value.
53
54 /**
55 ** Inititalize sync rand seed.
56 */
57 void InitSyncRand(void)
58 {
59 SyncRandSeed = 0x87654321;
60 }
61
62 /**
63 ** Synchronized random number.
64 **
65 ** @note This random value must be same on all machines in network game.
66 ** Very simple random generations, enough for us.
67 */
68 int SyncRand(void)
69 {
70 int val;
71
72 val = SyncRandSeed >> 16;
73
74 SyncRandSeed = SyncRandSeed * (0x12345678 * 4 + 1) + 1;
75
76 return val;
77 }
78
79 /**
80 ** Synchronized random number.
81 **
82 ** @param max Max value of random number to return
83 */
84 int SyncRand(int max)
85 {
86 return SyncRand() % max;
87 }
88
89
90 /*----------------------------------------------------------------------------
91 -- Math
92 ----------------------------------------------------------------------------*/
93
94 /**
95 ** Compute a square root using ints
96 **
97 ** Uses John Halleck's method, see
98 ** http://www.cc.utah.edu/~nahaj/factoring/isqrt.legalize.c.html
99 **
100 ** @param num Calculate the square root of this number
101 **
102 ** @return The integer square root.
103 */
104 long isqrt(long num)
105 {
106 long squaredbit;
107 long remainder;
108 long root;
109
110 if (num < 1) {
111 return 0;
112 }
113
114 //
115 // Load the binary constant 01 00 00 ... 00, where the number
116 // of zero bits to the right of the single one bit
117 // is even, and the one bit is as far left as is consistant
118 // with that condition.)
119 //
120 // This portable load replaces the loop that used to be
121 // here, and was donated by [email protected]
122 //
123 squaredbit = (long)((((unsigned long)~0L) >> 1) & ~(((unsigned long)~0L) >> 2));
124
125 // Form bits of the answer.
126 remainder = num;
127 root = 0;
128 while (squaredbit > 0) {
129 if (remainder >= (squaredbit | root)) {
130 remainder -= (squaredbit | root);
131 root >>= 1;
132 root |= squaredbit;
133 } else {
134 root >>= 1;
135 }
136 squaredbit >>= 2;
137 }
138
139 return root;
140 }
141
142
143 /*----------------------------------------------------------------------------
144 -- Strings
145 ----------------------------------------------------------------------------*/
146
147 #if !defined(_MSC_VER) || _MSC_VER < 1400
148 unsigned int strcpy_s(char *dst, size_t dstsize, const char *src)
149 {
150 if (dst == NULL || src == NULL) {
151 return EINVAL;
152 }
153 if (strlen(src) >= dstsize) {
154 return ERANGE;
155 }
156 strcpy(dst, src);
157 return 0;
158 }
159
160 #ifndef HAVE_STRNLEN
161 size_t strnlen(const char *str, size_t strsize)
162 {
163 size_t len = 0;
164 while (len < strsize) {
165 if (*str == '\0') {
166 break;
167 }
168 ++str;
169 ++len;
170 }
171 return len;
172 }
173 #endif
174
175 unsigned int strncpy_s(char *dst, size_t dstsize, const char *src, size_t count)
176 {
177 if (dst == NULL || src == NULL || dstsize == 0) {
178 return EINVAL;
179 }
180
181 size_t mincount;
182 if (count == _TRUNCATE) {
183 mincount = strnlen(src, dstsize);
184 } else {
185 mincount = strnlen(src, count);
186 }
187 if (mincount >= dstsize) {
188 if (count != _TRUNCATE) {
189 dst[0] = '\0';
190 return EINVAL;
191 } else {
192 mincount = dstsize - 1;
193 }
194 }
195 for (size_t i = 0; i < mincount; ++i) {
196 *dst++ = *src++;
197 }
198 *dst = '\0';
199 return 0;
200 }
201
202 unsigned int strcat_s(char *dst, size_t dstsize, const char *src)
203 {
204 if (dst == NULL || src == NULL) {
205 return EINVAL;
206 }
207 char *enddst = dst;
208 size_t count = dstsize;
209 while (count > 0 && *enddst != '\0') {
210 ++enddst;
211 count--;
212 }
213 if (count == 0) {
214 return EINVAL;
215 }
216 if (strlen(src) >= count ) {
217 return ERANGE;
218 }
219 strcpy(enddst, src);
220 return 0;
221 }
222
223 int sprintf_s(char *dest, size_t destSize, const char *format, ...)
224 {
225 va_list args;
226 int ret;
227
228 if (dest == NULL || format == NULL) {
229 errno = EINVAL;
230 return -1;
231 }
232
233 va_start(args, format);
234 ret = vsnprintf(dest, destSize, format, args);
235 va_end(args);
236
237 if (ret < 0 || (size_t)ret >= destSize) {
238 dest[0] = '\0';
239 errno = EINVAL;
240 ret = -1;
241 }
242
243 return ret;
244 }
245 #endif
246
247 /**
248 ** String duplicate/concatenate (two arguments)
249 **
250 ** @param l Left string
251 ** @param r Right string
252 **
253 ** @return Allocated combined string (must be freed).
254 */
255 char *strdcat(const char *l, const char *r)
256 {
257 int len = strlen(l) + strlen(r) + 1;
258 char *res = new char[len];
259
260 if (res) {
261 strcpy_s(res, len, l);
262 strcat_s(res, len, r);
263 }
264 return res;
265 }
266
267 /**
268 ** String duplicate/concatenate (three arguments)
269 **
270 ** @param l Left string
271 ** @param m Middle string
272 ** @param r Right string
273 **
274 ** @return Allocated combined string (must be freeded).
275 */
276 char *strdcat3(const char *l, const char *m, const char *r)
277 {
278 int len = strlen(l) + strlen(m) + strlen(r) + 1;
279 char *res = new char[len];
280
281 if (res) {
282 strcpy_s(res, len, l);
283 strcat_s(res, len, m);
284 strcat_s(res, len, r);
285 }
286 return res;
287 }
288
289 #if !defined(HAVE_STRCASESTR)
290 /**
291 ** Case insensitive version of strstr
292 **
293 ** @param a String to search in
294 ** @param b Substring to search for
295 **
296 ** @return Pointer to first occurence of b or NULL if not found.
297 */
298 char *strcasestr(const char *a, const char *b)
299 {
300 int x;
301
302 if (!a || !*a || !b || !*b || strlen(a) < strlen(b)) {
303 return NULL;
304 }
305
306 x = 0;
307 while (*a) {
308 if (a[x] && (tolower(a[x]) == tolower(b[x]))) {
309 ++x;
310 } else if (b[x]) {
311 ++a;
312 x = 0;
313 } else {
314 return (char *)a;
315 }
316 }
317
318 return NULL;
319 }
320 #endif // !HAVE_STRCASESTR
321
322
323 /*----------------------------------------------------------------------------
324 -- Getopt
325 ----------------------------------------------------------------------------*/
326
327 /**
328 ** Standard implementation of getopt(3).
329 **
330 ** One extension: If the first character of the optionsstring is a ':'
331 ** the error return for 'argument required' is a ':' not a '?'.
332 ** This makes it easier to differentiate between an 'illegal option' and
333 ** an 'argument required' error.
334 */
335
336 #if defined(_MSC_VER)
337
338 #include <io.h>
339 #include <string.h>
340
341 int opterr = 1;
342 int optind = 1;
343 int optopt;
344 char *optarg;
345
346 static void getopt_err(char *argv0, char *str, char opt)
347 {
348 if (opterr) {
349 char errbuf[2];
350 char *x;
351
352 errbuf[0] = opt;
353 errbuf[1] = '\n';
354
355 while ((x = strchr(argv0, '/'))) {
356 argv0 = x + 1;
357 }
358
359 write(2, argv0, strlen(argv0));
360 write(2, str, strlen(str));
361 write(2, errbuf, 2);
362 }
363 }
364
365 int getopt(int argc, char *const *argv, const char *opts)
366 {
367 static int sp = 1;
368 register int c;
369 register const char *cp;
370
371 optarg = NULL;
372
373 if (sp == 1) {
374 if (optind >= argc || argv[optind][0] != '-' || argv[optind][1] == '\0') {
375 return EOF;
376 } else if (!strcmp(argv[optind], "--")) {
377 optind++;
378 return EOF;
379 }
380 }
381 optopt = c = argv[optind][sp];
382 if (c == ':' || (cp = strchr(opts, c)) == NULL) {
383 getopt_err(argv[0], ": illegal option -", (char)c);
384 cp = "xx"; /* make the next if false */
385 c = '?';
386 }
387 if (*++cp == ':') {
388 if (argv[optind][++sp] != '\0') {
389 optarg = &argv[optind++][sp];
390 } else if (++optind < argc) {
391 optarg = argv[optind++];
392 } else {
393 getopt_err(argv[0], ": option requires an argument -", (char)c);
394 c = (*opts == ':') ? ':' : '?';
395 }
396 sp = 1;
397 } else if (argv[optind][++sp] == '\0') {
398 optind++;
399 sp = 1;
400 }
401 return c;
402 }
403
404 #endif /* _MSC_VER */
405
406
407 /*----------------------------------------------------------------------------
408 -- Clipboard
409 ----------------------------------------------------------------------------*/
410
411 /**
412 ** Paste text from the clipboard
413 */
414 int GetClipboard(std::string &str)
415 {
416 #if defined(USE_WIN32) || defined(HAVE_X)
417 int i;
418 unsigned char *clipboard;
419 #ifdef USE_WIN32
420 HGLOBAL handle;
421 #elif defined(HAVE_X)
422 Display *display;
423 Window window;
424 Atom rettype;
425 unsigned long nitem;
426 unsigned long dummy;
427 int retform;
428 XEvent event;
429 #endif
430
431 #ifdef USE_WIN32
432 if (!IsClipboardFormatAvailable(CF_TEXT) || !OpenClipboard(NULL)) {
433 return -1;
434 }
435 handle = GetClipboardData(CF_TEXT);
436 if (!handle) {
437 CloseClipboard();
438 return -1;
439 }
440 clipboard = (unsigned char *)GlobalLock(handle);
441 if (!clipboard) {
442 CloseClipboard();
443 return -1;
444 }
445 #elif defined(HAVE_X)
446 if (!(display = XOpenDisplay(NULL))) {
447 return -1;
448 }
449
450 // Creates a non maped temporary X window to hold the selection
451 if (!(window = XCreateSimpleWindow(display,
452 DefaultRootWindow(display), 0, 0, 1, 1, 0, 0, 0))) {
453 XCloseDisplay(display);
454 return -1;
455 }
456
457 XConvertSelection(display, XA_PRIMARY, XA_STRING, XA_STRING,
458 window, CurrentTime);
459
460 XNextEvent(display, &event);
461
462 if (event.type != SelectionNotify ||
463 event.xselection.property != XA_STRING) {
464 return -1;
465 }
466
467 XGetWindowProperty(display, window, XA_STRING, 0, 1024, False,
468 XA_STRING, &rettype, &retform, &nitem, &dummy, &clipboard);
469
470 XDestroyWindow(display, window);
471 XCloseDisplay(display);
472
473 if (rettype != XA_STRING || retform != 8) {
474 if (clipboard != NULL) {
475 XFree(clipboard);
476 }
477 clipboard = NULL;
478 }
479
480 if (clipboard == NULL) {
481 return -1;
482 }
483 #endif
484 // Only allow ascii characters
485 for (i = 0; clipboard[i] != '\0'; ++i) {
486 if (clipboard[i] < 32 || clipboard[i] > 126) {
487 return -1;
488 }
489 }
490 str = (char *)clipboard;
491 #ifdef USE_WIN32
492 GlobalUnlock(handle);
493 CloseClipboard();
494 #elif defined(HAVE_X)
495 if (clipboard != NULL) {
496 XFree(clipboard);
497 }
498 #endif
499 return 0;
500 #else
501 return -1;
502 #endif
503 }
504
505
506 /*----------------------------------------------------------------------------
507 -- UTF8
508 ----------------------------------------------------------------------------*/
509
510 int UTF8GetPrev(const std::string &text, int curpos)
511 {
512 --curpos;
513 if (curpos < 0) {
514 return curpos;
515 }
516 while (curpos >= 0) {
517 if ((text[curpos] & 0xC0) != 0x80) {
518 return curpos;
519 }
520 --curpos;
521 }
522 if (curpos < 0) {
523 fprintf(stderr, "Invalid UTF8.\n");
524 }
525 return 0;
526 }
527
528 int UTF8GetNext(const std::string &text, int curpos)
529 {
530 if (curpos == (int)text.size()) {
531 return curpos + 1;
532 }
533 char c = text[curpos];
534 if (!(c & 0x80)) {
535 return curpos + 1;
536 }
537 if ((c & 0xE0) == 0xC0) {
538 return curpos + 2;
539 }
540 if ((c & 0xF0) == 0xE0) {
541 return curpos + 3;
542 }
543 fprintf(stderr, "Invalid UTF8.\n");
544 return text.size();
545 }
546