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