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