]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/lib/string.qh
Since strftime(false, "%s") doesn't work on Windows implement a qc version of it...
[xonotic/xonotic-data.pk3dir.git] / qcsrc / lib / string.qh
1 #pragma once
2
3 #include "nil.qh"
4 #include "sort.qh"
5 #include "oo.qh"
6
7 // string logic
8 //
9 // true: is truthy
10 // == "": is equal to ""
11 // is "": has the same string index as the string constant ""
12 // strunzone: can be strunzoned
13 //
14 // |              | true | == "" | is "" | strunzone |
15 // | :----------: | :--: | :---: | :---: | :-------: |
16 // | nil          |      | yes   |       |           |
17 // | strcat(nil)  | yes  | yes   |       |           |
18 // | strzone(nil) | yes  | yes   |       | yes       |
19 // | ""           | yes  | yes   | yes   |           |
20 // | strcat("")   | yes  | yes   |       |           |
21 // | strzone("")  | yes  | yes   |       | yes       |
22 // | "s"          | yes  |       |       |           |
23 // | strcat("s")  | yes  |       |       |           |
24 // | strzone("s") | yes  |       |       | yes       |
25
26 #ifdef CSQC
27         float stringwidth_colors(string s, vector theSize)
28         {
29                 return stringwidth_builtin(s, true, theSize);
30         }
31
32         float stringwidth_nocolors(string s, vector theSize)
33         {
34                 return stringwidth_builtin(s, false, theSize);
35         }
36 #endif
37 #ifdef MENUQC
38         float stringwidth_colors(string s, vector theSize)
39         {
40                 return stringwidth(s, true, theSize);
41         }
42
43         float stringwidth_nocolors(string s, vector theSize)
44         {
45                 return stringwidth(s, false, theSize);
46         }
47 #endif
48
49 #define strcpy(this, s) MACRO_BEGIN \
50         if (this) { \
51                 strunzone(this); \
52         } \
53         this = strzone(s); \
54 MACRO_END
55
56 #define strfree(this) MACRO_BEGIN \
57         if (this) { \
58                 strunzone(this); \
59         } \
60         this = string_null; \
61 MACRO_END
62
63 // Returns the number of days since 0000-03-01 (March 1, year 0)
64 // Starting counting from March, as the 1st month of the year, February becomes the 12th and last month,
65 // so its variable duration does not affect, given that the 29th is the last day of the period
66 ERASEABLE
67 int days_up_to_date(int Y, int M, int D)
68 {
69         int years = (M <= 2) ? Y - 1 : Y;
70
71         int leap_days = floor(years / 4) - floor(years / 100) + floor(years / 400);
72
73         // using these 2 formulas to save 2 arrays or switches (performance isn't important here)
74         int months = (M <= 2) ? (M + 9) : (M - 3); // 10, 11, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
75         int leftover_days = (M <= 2) ? (M + 5) : floor(0.58 * M - 1.1); // 6, 7, 0, 1, 1, 2, 2, 3, 4, 4, 5, 5
76
77         int month_days = 30 * months + leftover_days;
78
79         return 365 * years + month_days + D + leap_days;
80 }
81
82 #define DAYS_UP_TO_EPOCH 719469 // days_up_to_date(1970, 1, 1);
83
84 // Returns the number of seconds since the Epoch, 1970-01-01 00:00:00 +0000 (UTC).
85 // This function exists only as a replacement for strftime(false, "%s") which doesn't work
86 // on Windows (%s is not supported)
87 // NOTE: at the current date, the number (string) returned by both strftime(false, "%s") and
88 // strftime_s() is so high that can't be converted to int (with ftos) without precision loss
89 ERASEABLE
90 string strftime_s()
91 {
92         string date = strftime(false, "%Y-%m-%d %H:%M:%S");
93         int i, seconds = 0;
94         i =0; int Y = stof(substring(date, i, 4)); // years
95         i+=5; int M = stof(substring(date, i, 2)); // months
96         i+=3; int D = stof(substring(date, i, 2)); // days
97
98         i+=3; seconds += stof(substring(date, i, 2)) * 60 * 60; // hours
99         i+=3; seconds += stof(substring(date, i, 2)) * 60; // minutes
100         i+=3; seconds += stof(substring(date, i, 2)); // seconds
101
102         // doing so we loose precision
103         //seconds += (days_up_to_date(Y, M, D) - DAYS_UP_TO_EPOCH) * 24 * 60 * 60;
104         //return ftos(seconds);
105
106         int days_since_epoch = days_up_to_date(Y, M, D) - DAYS_UP_TO_EPOCH;
107         // use hundreds of seconds as unit to avoid precision loss
108         int hundreds_of_seconds = days_since_epoch * 24 * 6 * 6;
109         hundreds_of_seconds += floor(seconds / 100);
110
111         // tens of seconds and seconds
112         string seconds_str = ftos(seconds % 100);
113         if ((seconds % 100) < 10)
114                 seconds_str = strcat("0", seconds_str);
115
116         return strcat(ftos(hundreds_of_seconds), seconds_str);
117 }
118
119 ERASEABLE
120 string seconds_tostring(float sec)
121 {
122         float minutes = floor(sec / 60);
123         sec -= minutes * 60;
124         return sprintf("%d:%02d", minutes, sec);
125 }
126
127 ERASEABLE
128 string format_time(float seconds)
129 {
130         seconds = floor(seconds + 0.5);
131         float days = floor(seconds / 864000);
132         seconds -= days * 864000;
133         float hours = floor(seconds / 36000);
134         seconds -= hours * 36000;
135         float minutes = floor(seconds / 600);
136         seconds -= minutes * 600;
137         if (days > 0) return sprintf(_("%d days, %02d:%02d:%02d"), days, hours, minutes, seconds);
138         else return sprintf(_("%02d:%02d:%02d"), hours, minutes, seconds);
139 }
140
141 ERASEABLE
142 string mmsss(float tenths)
143 {
144         tenths = floor(tenths + 0.5);
145         float minutes = floor(tenths / 600);
146         tenths -= minutes * 600;
147         string s = ftos(1000 + tenths);
148         return strcat(ftos(minutes), ":", substring(s, 1, 2), ".", substring(s, 3, 1));
149 }
150
151 ERASEABLE
152 string mmssss(float hundredths)
153 {
154         hundredths = floor(hundredths + 0.5);
155         float minutes = floor(hundredths / 6000);
156         hundredths -= minutes * 6000;
157         string s = ftos(10000 + hundredths);
158         return strcat(ftos(minutes), ":", substring(s, 1, 2), ".", substring(s, 3, 2));
159 }
160
161 int ColorTranslateMode;
162
163 ERASEABLE
164 string ColorTranslateRGB(string s)
165 {
166         return (ColorTranslateMode & 1) ? strdecolorize(s) : s;
167 }
168
169 #ifdef GAMEQC
170 // color code replace, place inside of sprintf and parse the string... defaults described as constants
171 // foreground/normal colors
172 string autocvar_hud_colorset_foreground_1 = "2"; // F1 - Green  // primary priority (important names, etc)
173 string autocvar_hud_colorset_foreground_2 = "3"; // F2 - Yellow // secondary priority (items, locations, numbers, etc)
174 string autocvar_hud_colorset_foreground_3 = "4"; // F3 - Blue   // tertiary priority or relatively inconsequential text
175 string autocvar_hud_colorset_foreground_4 = "1"; // F4 - Red    // notice/attention grabbing texting
176 // "kill" colors
177 string autocvar_hud_colorset_kill_1 = "1";       // K1 - Red    // "bad" or "dangerous" text (death messages against you, kill notifications, etc)
178 string autocvar_hud_colorset_kill_2 = "3";       // K2 - Yellow // similar to above, but less important... OR, a highlight out of above message type
179 string autocvar_hud_colorset_kill_3 = "4";       // K3 - Blue   // "good" or "beneficial" text (you fragging someone, etc)
180 // background color
181 string autocvar_hud_colorset_background = "7";   // BG - White // neutral/unimportant text
182
183 /** color code replace, place inside of sprintf and parse the string */
184 string CCR(string input)
185 {
186         // foreground/normal colors
187         input = strreplace("^F1", strcat("^", autocvar_hud_colorset_foreground_1), input);
188         input = strreplace("^F2", strcat("^", autocvar_hud_colorset_foreground_2), input);
189         input = strreplace("^F3", strcat("^", autocvar_hud_colorset_foreground_3), input);
190         input = strreplace("^F4", strcat("^", autocvar_hud_colorset_foreground_4), input);
191
192         // "kill" colors
193         input = strreplace("^K1", strcat("^", autocvar_hud_colorset_kill_1), input);
194         input = strreplace("^K2", strcat("^", autocvar_hud_colorset_kill_2), input);
195         input = strreplace("^K3", strcat("^", autocvar_hud_colorset_kill_3), input);
196
197         // background colors
198         input = strreplace("^BG", strcat("^", autocvar_hud_colorset_background), input);
199         input = strreplace("^N", "^7", input);  // "none"-- reset to white...
200         return input;
201 }
202 #endif
203
204 #define startsWith(haystack, needle) (strstrofs(haystack, needle, 0) == 0)
205
206 ERASEABLE
207 bool startsWithNocase(string haystack, string needle)
208 {
209         return strcasecmp(substring(haystack, 0, strlen(needle)), needle) == 0;
210 }
211
212 noref string _endsWith_suffix;
213 #define endsWith(this, suffix) (_endsWith_suffix = suffix, substring(this, -strlen(_endsWith_suffix), -1) == _endsWith_suffix)
214
215 /** unzone the string, and return it as tempstring. Safe to be called on string_null */
216 ERASEABLE
217 string fstrunzone(string s)
218 {
219         if (!s) return s;
220         string sc = strcat(s, "");
221         strunzone(s);
222         return sc;
223 }
224
225 /** returns first word */
226 ERASEABLE
227 string car(string s)
228 {
229         int o = strstrofs(s, " ", 0);
230         if (o < 0) return s;
231         return substring(s, 0, o);
232 }
233
234 /** returns all but first word */
235 ERASEABLE
236 string cdr(string s)
237 {
238         int o = strstrofs(s, " ", 0);
239         if (o < 0) return string_null;
240         return substring(s, o + 1, strlen(s) - (o + 1));
241 }
242
243 ERASEABLE
244 string cons(string a, string b)
245 {
246         if (a == "") return b;
247         if (b == "") return a;
248         return strcat(a, " ", b);
249 }
250
251 ERASEABLE
252 string cons_mid(string a, string mid, string b)
253 {
254         if (a == "") return b;
255         if (b == "") return a;
256         return strcat(a, mid, b);
257 }
258
259 ERASEABLE
260 string substring_range(string s, float b, float e)
261 {
262         return substring(s, b, e - b);
263 }
264
265 ERASEABLE
266 string swapwords(string str, float i, float j)
267 {
268         float n;
269         string s1, s2, s3, s4, s5;
270         float si, ei, sj, ej, s0, en;
271         n = tokenizebyseparator(str, " ");  // must match g_maplist processing in ShuffleMaplist and "shuffle"
272         si = argv_start_index(i);
273         sj = argv_start_index(j);
274         ei = argv_end_index(i);
275         ej = argv_end_index(j);
276         s0 = argv_start_index(0);
277         en = argv_end_index(n - 1);
278         s1 = substring_range(str, s0, si);
279         s2 = substring_range(str, si, ei);
280         s3 = substring_range(str, ei, sj);
281         s4 = substring_range(str, sj, ej);
282         s5 = substring_range(str, ej, en);
283         return strcat(s1, s4, s3, s2, s5);
284 }
285
286 string _shufflewords_str;
287 ERASEABLE
288 void _shufflewords_swapfunc(float i, float j, entity pass)
289 {
290         _shufflewords_str = swapwords(_shufflewords_str, i, j);
291 }
292
293 ERASEABLE
294 string shufflewords(string str)
295 {
296         _shufflewords_str = str;
297         int n = tokenizebyseparator(str, " ");
298         shuffle(n, _shufflewords_swapfunc, NULL);
299         str = _shufflewords_str;
300         _shufflewords_str = string_null;
301         return str;
302 }
303
304 ERASEABLE
305 string unescape(string in)
306 {
307         in = strzone(in);  // but it doesn't seem to be necessary in my tests at least
308
309         int len = strlen(in);
310         string str = "";
311         for (int i = 0; i < len; ++i)
312         {
313                 string s = substring(in, i, 1);
314                 if (s == "\\")
315                 {
316                         s = substring(in, i + 1, 1);
317                         if (s == "n") str = strcat(str, "\n");
318                         else if (s == "\\") str = strcat(str, "\\");
319                         else str = strcat(str, substring(in, i, 2));
320                         ++i;
321                         continue;
322                 }
323                 str = strcat(str, s);
324         }
325         strunzone(in);
326         return str;
327 }
328
329 ERASEABLE
330 string strwords(string s, int w)
331 {
332         int endpos = 0;
333         for ( ; w && endpos >= 0; --w)
334                 endpos = strstrofs(s, " ", endpos + 1);
335         if (endpos < 0) return s;
336         return substring(s, 0, endpos);
337 }
338
339 #define strhasword(s, w) (strstrofs(strcat(" ", s, " "), strcat(" ", w, " "), 0) >= 0)
340
341 ERASEABLE
342 int u8_strsize(string s)
343 {
344         int l = 0;
345         for (int i = 0, c; (c = str2chr(s, i)) > 0; ++i, ++l)
346         {
347                 l += (c >= 0x80);
348                 l += (c >= 0x800);
349                 l += (c >= 0x10000);
350         }
351         return l;
352 }
353
354 // List of Unicode spaces: http://jkorpela.fi/chars/spaces.html
355 ERASEABLE
356 bool isInvisibleString(string s)
357 {
358         s = strdecolorize(s);
359         bool utf8 = cvar("utf8_enable");
360         for (int i = 0, n = strlen(s); i < n; ++i)
361         {
362                 int c = str2chr(s, i);
363                 switch (c)
364                 {
365                         case 0:
366                         case 32:           // space
367                                 break;
368                         case 192:          // charmap space
369                                 if (!utf8) break;
370                                 return false;
371                         case 0xE000: // invisible char of the utf8 quake charmap
372                         case 0xE00A: // invisible char of the utf8 quake charmap
373                         case 0xE0A0: // invisible char of the utf8 quake charmap
374                         case 0xE020: // invisible char of the utf8 quake charmap
375                         case 0x00A0: // NO-BREAK SPACE
376                         //case 0x1680: // OGHAM SPACE MARK
377                         case 0x180E: // MONGOLIAN VOWEL SEPARATOR
378                         case 0x2000: // EN QUAD
379                         case 0x2001: // EM QUAD
380                         case 0x2002: // EN SPACE
381                         case 0x2003: // EM SPACE
382                         case 0x2004: // THREE-PER-EM SPACE
383                         case 0x2005: // FOUR-PER-EM SPACE
384                         case 0x2006: // SIX-PER-EM SPACE
385                         case 0x2007: // FIGURE SPACE
386                         case 0x2008: // PUNCTUATION SPACE
387                         case 0x2009: // THIN SPACE
388                         case 0x200A: // HAIR SPACE
389                         case 0x200B: // ZERO WIDTH SPACE
390                         case 0x202F: // NARROW NO-BREAK SPACE
391                         case 0x205F: // MEDIUM MATHEMATICAL SPACE
392                         case 0x3000: // IDEOGRAPHIC SPACE
393                         case 0xFEFF: // ZERO WIDTH NO-BREAK SPACE
394                                 if (utf8) break;
395                         default:
396                                 return false;
397                 }
398         }
399         return true;
400 }
401
402 // Multiline text file buffers
403
404 ERASEABLE
405 int buf_load(string pFilename)
406 {
407         int buf = buf_create();
408         if (buf < 0) return -1;
409         int fh = fopen(pFilename, FILE_READ);
410         if (fh < 0)
411         {
412                 buf_del(buf);
413                 return -1;
414         }
415         string l;
416         for (int i = 0; (l = fgets(fh)); ++i)
417                 bufstr_set(buf, i, l);
418         fclose(fh);
419         return buf;
420 }
421
422 ERASEABLE
423 void buf_save(float buf, string pFilename)
424 {
425         int fh = fopen(pFilename, FILE_WRITE);
426         if (fh < 0) error(strcat("Can't write buf to ", pFilename));
427         int n = buf_getsize(buf);
428         for (int i = 0; i < n; ++i)
429                 fputs(fh, strcat(bufstr_get(buf, i), "\n"));
430         fclose(fh);
431 }
432
433 /**
434  * converts a number to a string with the indicated number of decimals
435  */
436 ERASEABLE
437 string ftos_decimals(float number, int decimals)
438 {
439         // inhibit stupid negative zero
440         if (number == 0) number = 0;
441         return sprintf("%.*f", decimals, number);
442 }
443
444 /**
445  * converts a number to a string with the minimum number of decimals
446  */
447 ERASEABLE
448 string ftos_mindecimals(float number)
449 {
450         // inhibit stupid negative zero
451         if (number == 0) number = 0;
452         return sprintf("%.7g", number);
453 }
454
455 ERASEABLE
456 int vercmp_recursive(string v1, string v2)
457 {
458         int dot1 = strstrofs(v1, ".", 0);
459         int dot2 = strstrofs(v2, ".", 0);
460         string s1 = (dot1 == -1) ? v1 : substring(v1, 0, dot1);
461         string s2 = (dot2 == -1) ? v2 : substring(v2, 0, dot2);
462
463         float r;
464         r = stof(s1) - stof(s2);
465         if (r != 0) return r;
466
467         r = strcasecmp(s1, s2);
468         if (r != 0) return r;
469
470         if (dot1 == -1) return (dot2 == -1) ? 0 : -1;
471         else return (dot2 == -1) ? 1 : vercmp_recursive(substring(v1, dot1 + 1, 999), substring(v2, dot2 + 1, 999));
472 }
473
474 ERASEABLE
475 int vercmp(string v1, string v2)
476 {
477         if (strcasecmp(v1, v2) == 0) return 0;  // early out check
478
479         // "git" beats all
480         if (v1 == "git") return 1;
481         if (v2 == "git") return -1;
482
483         return vercmp_recursive(v1, v2);
484 }
485
486 const string HEXDIGITS_MINSET = "0123456789ABCDEFabcdef";
487 const string HEXDIGITS = "0123456789ABCDEF0123456789abcdef";
488 #define HEXDIGIT_TO_DEC_RAW(d) (strstrofs(HEXDIGITS, (d), 0))
489 #define HEXDIGIT_TO_DEC(d) ((HEXDIGIT_TO_DEC_RAW(d) | 0x10) - 0x10)
490 #define DEC_TO_HEXDIGIT(d) (substring(HEXDIGITS_MINSET, (d), 1))
491 #define IS_HEXDIGIT(d) (strstrofs(HEXDIGITS_MINSET, (d), 0) >= 0)
492
493 const string DIGITS = "0123456789";
494 #define IS_DIGIT(d) (strstrofs(DIGITS, (d), 0) >= 0)
495
496 // returns true if the caret at position pos is escaped
497 ERASEABLE
498 bool isCaretEscaped(string theText, float pos)
499 {
500         // count all the previous carets
501         int carets = 0;
502         while(pos - carets >= 1 && substring(theText, pos - carets - 1, 1) == "^")
503                 ++carets;
504         // if number of previous carets is odd then this carets is escaped
505         return (carets & 1);
506 }
507
508 ERASEABLE
509 bool isValidColorCodeValue(string theText, int cc_len, int tag_start)
510 {
511         if (cc_len == 2)
512                 return IS_DIGIT(substring(theText, tag_start + 1, 1));
513         if (cc_len == 5)
514                 return (IS_HEXDIGIT(substring(theText, tag_start + 2, 1))
515                         && IS_HEXDIGIT(substring(theText, tag_start + 3, 1))
516                         && IS_HEXDIGIT(substring(theText, tag_start + 4, 1)));
517         return false;
518 }
519
520 // it returns 0 if pos is NOT in the middle or at the end of a color code
521 // otherwise it returns a vector with color code length as the first component
522 // and the offset from '^' position to pos as the second component
523 // e.g.:
524 // "j^2kl" | returns 0 if pos == 0 or 1 or 4
525 //    ^^   | returns '2 1' or '2 2' if pos == 2 or 3
526 ERASEABLE
527 vector checkColorCode(string theText, int text_len, int pos, bool check_at_the_end)
528 {
529         if (text_len == 0)
530                 text_len = strlen(theText);
531         string tag_type = "^";
532         int cc_len = 2;
533         int tag_len = 1;
534
535         LABEL(check_color_tag)
536
537         int ofs = cc_len;
538         if (!check_at_the_end)
539                 ofs--;
540         for (; ofs >= 1; ofs--)
541         {
542                 if (!(pos >= ofs && text_len >= pos + (cc_len - ofs)))
543                         continue;
544                 if(substring(theText, pos - ofs, tag_len) == tag_type)
545                 {
546                         if (!isCaretEscaped(theText, pos - ofs) && isValidColorCodeValue(theText, cc_len, pos - ofs))
547                                 return eX * cc_len + eY * ofs;
548                 }
549         }
550         if (cc_len == 2)
551         {
552                 tag_type = "^x";
553                 cc_len = 5;
554                 tag_len = 2;
555                 goto check_color_tag;
556         }
557         return '0 0 0';
558 }