New e-d-s backend which indexes all local addressbooks and calendars.
[beagle.git] / Util / StringFu.cs
blobbb4db891405bcb55b2deb7f1efc38aca2a158c0e
1 //
2 // StringFu.cs
3 //
4 // Copyright (C) 2004 Novell, Inc.
5 //
7 //
8 // Permission is hereby granted, free of charge, to any person obtaining a
9 // copy of this software and associated documentation files (the "Software"),
10 // to deal in the Software without restriction, including without limitation
11 // the rights to use, copy, modify, merge, publish, distribute, sublicense,
12 // and/or sell copies of the Software, and to permit persons to whom the
13 // Software is furnished to do so, subject to the following conditions:
15 // The above copyright notice and this permission notice shall be included in
16 // all copies or substantial portions of the Software.
18 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23 // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
24 // DEALINGS IN THE SOFTWARE.
27 using System;
28 using System.Collections;
29 using System.Globalization;
30 using System.IO;
31 using System.Text;
32 using System.Xml;
34 using Mono.Posix;
36 namespace Beagle.Util {
38 public class StringFu {
40 private StringFu () { } // class is static
42 private const String timeFormat = "yyyyMMddHHmmss";
44 static public string DateTimeToString (DateTime dt)
46 return dt.ToString (timeFormat);
49 static public DateTime StringToDateTime (string str)
51 if (str == null || str == "")
52 return new DateTime ();
54 return DateTime.ParseExact (str, timeFormat, CultureInfo.CurrentCulture);
57 static public string DateTimeToFuzzy (DateTime dt)
59 DateTime today = DateTime.Today;
60 TimeSpan sinceToday = today - dt;
62 string date = null, time = null;
64 if (sinceToday.TotalDays <= 0)
65 date = Catalog.GetString ("Today");
66 else if (sinceToday.TotalDays < 1)
67 date = Catalog.GetString ("Yesterday");
68 else if (today.Year == dt.Year)
69 date = dt.ToString (Catalog.GetString ("MMM d"));
70 else
71 date = dt.ToString (Catalog.GetString ("MMM d, yyyy"));
73 time = dt.ToString (Catalog.GetString ("h:mm tt"));
75 string fuzzy;
77 if (date != null && time != null)
78 /* Translators: {0} is a date (e.g. 'Today' or 'Apr 23'), {1} is the time */
79 fuzzy = String.Format (Catalog.GetString ("{0}, {1}"), date, time);
80 else if (date != null)
81 fuzzy = date;
82 else
83 fuzzy = time;
85 return fuzzy;
88 public static string DateTimeToPrettyString (DateTime date)
90 DateTime now = DateTime.Now;
91 string short_time = date.ToShortTimeString ();
93 if (date.Year == now.Year) {
94 if (date.DayOfYear == now.DayOfYear) {
95 /* To translators: {0} is the time of the day, eg. 13:45 */
96 return String.Format (Catalog.GetString ("Today, {0}"), short_time);
97 } else if (date.DayOfYear == now.DayOfYear - 1) {
98 /* To translators: {0} is the time of the day, eg. 13:45 */
99 return String.Format (Catalog.GetString ("Yesterday, {0}"), short_time);
100 } else if (date.DayOfYear > now.DayOfYear - 6) {
101 /* To translators: {0} is the number of days that have passed, {1} is the time of the day, eg. 13:45 */
102 return String.Format (Catalog.GetString ("{0} days ago, {1}"),
103 now.DayOfYear - date.DayOfYear,
104 short_time);
105 } else {
106 return date.ToString (Catalog.GetString ("MMMM d, h:mm tt"));
110 return date.ToString (Catalog.GetString ("MMMM d yyyy, h:mm tt"));
113 public static string DurationToPrettyString (DateTime end_time, DateTime start_time)
115 TimeSpan span = end_time - start_time;
117 string span_str = "";
119 if (span.Hours > 0) {
120 span_str = String.Format (Catalog.GetPluralString ("{0} hour", "{0} hours", span.Hours), span.Hours);
122 if (span.Minutes > 0)
123 span_str += ", ";
126 if (span.Minutes > 0) {
127 span_str += String.Format (Catalog.GetPluralString ("{0} minute", "{0} minutes", span.Minutes), span.Minutes);
131 return span_str;
134 static public string FileLengthToString (long len)
136 const long oneMb = 1024*1024;
138 if (len < 0)
139 return "*BadLength*";
141 if (len < 1024)
142 /* Translators: {0} is a file size in bytes */
143 return String.Format (Catalog.GetString ("{0} bytes"), len);
145 if (len < oneMb)
146 /* Translators: {0} is a file size in kilobytes */
147 return String.Format (Catalog.GetString ("{0:0.0} KB"), len/(double)1024);
149 /* Translators: {0} is a file size in megabytes */
150 return String.Format (Catalog.GetString ("{0:0.0} MB"), len/(double)oneMb);
153 // FIXME: This is pretty inefficient
154 static public string[] FuzzySplit (string line)
156 int i;
158 // Replace non-alphanumeric characters with spaces
159 StringBuilder builder = new StringBuilder (line.Length);
160 for (i = 0; i < line.Length; ++i) {
161 if (Char.IsLetterOrDigit (line [i]))
162 builder.Append (line [i]);
163 else
164 builder.Append (" ");
166 line = builder.ToString ();
168 // Inject whitespace on all case changes except
169 // from upper to lower.
170 i = 0;
171 int prevCase = 0;
172 while (i < line.Length) {
173 int thisCase;
174 if (Char.IsUpper (line [i]))
175 thisCase = +1;
176 else if (Char.IsLower (line [i]))
177 thisCase = -1;
178 else
179 thisCase = 0;
181 if (prevCase != thisCase
182 && !(prevCase == +1 && thisCase == -1)) {
183 line = line.Substring (0, i) + " " + line.Substring (i);
184 ++i;
187 prevCase = thisCase;
189 ++i;
192 // Filter out empty parts
193 ArrayList partsArray = new ArrayList ();
194 foreach (string str in line.Split (' ')) {
195 if (str != "")
196 partsArray.Add (str);
199 // Assemble the array to return
200 string[] parts = new string [partsArray.Count];
201 for (i = 0; i < partsArray.Count; ++i)
202 parts [i] = (string) partsArray [i];
203 return parts;
206 // Match strings against patterns that are allowed to contain
207 // glob-style * wildcards.
208 // This recursive implementation is not particularly efficient,
209 // and probably will fail for weird corner cases.
210 static public bool GlobMatch (string pattern, string str)
212 if (pattern == "*")
213 return true;
214 else if (pattern.StartsWith ("**"))
215 return GlobMatch (pattern.Substring (1), str);
216 else if (str == "" && pattern != "")
217 return false;
219 int i = pattern.IndexOf ('*');
220 if (i == -1)
221 return pattern == str;
222 else if (i > 0 && i < str.Length)
223 return pattern.Substring (0, i) == str.Substring (0, i)
224 && GlobMatch (pattern.Substring (i), str.Substring (i));
225 else if (i == 0)
226 return GlobMatch (pattern.Substring (1), str.Substring (1))
227 || GlobMatch (pattern.Substring (1), str)
228 || GlobMatch (pattern, str.Substring (1));
230 return false;
233 // FIXME: how do we do this operation in a culture-neutral way?
234 static public string[] SplitQuoted (string str)
236 char[] specialChars = new char [2] { ' ', '"' };
238 ArrayList array = new ArrayList ();
240 int i;
241 while ((i = str.IndexOfAny (specialChars)) != -1) {
242 if (str [i] == ' ') {
243 if (i > 0)
244 array.Add (str.Substring (0, i));
245 str = str.Substring (i+1);
246 } else if (str [i] == '"') {
247 int j = str.IndexOf ('"', i+1);
248 if (i > 0)
249 array.Add (str.Substring (0, i));
250 if (j == -1) {
251 if (i+1 < str.Length)
252 array.Add (str.Substring (i+1));
253 str = "";
254 } else {
255 if (j-i-1 > 0)
256 array.Add (str.Substring (i+1, j-i-1));
257 str = str.Substring (j+1);
261 if (str != "")
262 array.Add (str);
264 string [] retval = new string [array.Count];
265 for (i = 0; i < array.Count; ++i)
266 retval [i] = (string) array [i];
267 return retval;
270 static public bool ContainsWhiteSpace (string str)
272 foreach (char c in str)
273 if (char.IsWhiteSpace (c))
274 return true;
275 return false;
278 static char[] CharsToQuote = { ';', '?', ':', '@', '&', '=', '$', ',', '#', '%', '"', ' ' };
280 static public string HexEscape (string str)
282 StringBuilder builder = new StringBuilder ();
283 int i;
285 while ((i = str.IndexOfAny (CharsToQuote)) != -1) {
286 if (i > 0)
287 builder.Append (str.Substring (0, i));
288 builder.Append (Uri.HexEscape (str [i]));
289 str = str.Substring (i+1);
291 builder.Append (str);
293 return builder.ToString ();
296 // Translate all %xx codes into real characters
297 static public string HexUnescape (string str)
299 int i = 0, pos = 0;
300 while ((i = str.IndexOf ('%', pos)) != -1) {
301 pos = i;
302 char unescaped = UriFu.HexUnescape (str, ref pos);
303 str = str.Remove (i, 3);
304 str = str.Insert (i, new String(unescaped, 1));
305 pos -= 2;
307 return str;
310 static public string PathToQuotedFileUri (string path)
312 path = Path.GetFullPath (path);
313 return Uri.UriSchemeFile + Uri.SchemeDelimiter + HexEscape (path);
316 // These strings should never be exposed to the user.
317 static int uid = 0;
318 static object uidLock = new object ();
319 static public string GetUniqueId ()
321 lock (uidLock) {
322 if (uid == 0) {
323 Random r = new Random ();
324 uid = r.Next ();
326 ++uid;
328 return string.Format ("{0}-{1}-{2}-{3}",
329 Environment.GetEnvironmentVariable ("USER"),
330 Environment.GetEnvironmentVariable ("HOST"),
331 DateTime.Now.Ticks,
332 uid);
336 static string [] replacements = new string [] {
337 "&amp;", "&lt;", "&gt;", "&quot;", "&apos;",
338 "&#xD;", "&#xA;"};
340 static private StringBuilder cachedStringBuilder;
341 static private char QuoteChar = '\"';
343 private static bool IsInvalid (int ch)
345 switch (ch) {
346 case 9:
347 case 10:
348 case 13:
349 return false;
351 if (ch < 32)
352 return true;
353 if (ch < 0xD800)
354 return false;
355 if (ch < 0xE000)
356 return true;
357 if (ch < 0xFFFE)
358 return false;
359 if (ch < 0x10000)
360 return true;
361 if (ch < 0x110000)
362 return false;
363 else
364 return true;
367 static public string EscapeStringForHtml (string source, bool skipQuotations)
369 int start = 0;
370 int pos = 0;
371 int count = source.Length;
372 char invalid = ' ';
373 for (int i = 0; i < count; i++) {
374 switch (source [i]) {
375 case '&': pos = 0; break;
376 case '<': pos = 1; break;
377 case '>': pos = 2; break;
378 case '\"':
379 if (skipQuotations) continue;
380 if (QuoteChar == '\'') continue;
381 pos = 3; break;
382 case '\'':
383 if (skipQuotations) continue;
384 if (QuoteChar == '\"') continue;
385 pos = 4; break;
386 case '\r':
387 if (skipQuotations) continue;
388 pos = 5; break;
389 case '\n':
390 if (skipQuotations) continue;
391 pos = 6; break;
392 default:
393 if (IsInvalid (source [i])) {
394 invalid = source [i];
395 pos = -1;
396 break;
398 else
399 continue;
401 if (cachedStringBuilder == null)
402 cachedStringBuilder = new StringBuilder
404 cachedStringBuilder.Append (source.Substring (start, i - start));
405 if (pos < 0) {
406 cachedStringBuilder.Append ("&#x");
407 if (invalid < (char) 255)
408 cachedStringBuilder.Append (((int) invalid).ToString ("X02", CultureInfo.InvariantCulture));
409 else
410 cachedStringBuilder.Append (((int) invalid).ToString ("X04", CultureInfo.InvariantCulture));
411 cachedStringBuilder.Append (";");
413 else
414 cachedStringBuilder.Append (replacements [pos]);
415 start = i + 1;
417 if (start == 0)
418 return source;
419 else if (start < count)
420 cachedStringBuilder.Append (source.Substring (start, count - start));
421 string s = cachedStringBuilder.ToString ();
422 cachedStringBuilder.Length = 0;
423 return s;
426 static public string CleanupInvalidXmlCharacters (string str)
428 if (str == null)
429 return null;
431 int len = str.Length;
433 // Find the first invalid character in the string
434 int i = 0;
435 while (i < len && ! IsInvalid (str [i]))
436 ++i;
438 // If the string doesn't contain invalid characters,
439 // just return it.
440 if (i >= len)
441 return str;
443 // Otherwise copy the first chunk, then go through
444 // character by character looking for more invalid stuff.
446 char [] char_array = new char[len];
448 for (int j = 0; j < i; ++j)
449 char_array [j] = str [j];
450 char_array [i] = ' ';
452 for (int j = i+1; j < len; ++j) {
453 char c = str [j];
454 if (IsInvalid (c))
455 char_array [j] = ' ';
456 else
457 char_array [j] = c;
460 return new string (char_array);
463 static public int CountWords (string str, int max_words)
465 if (str == null)
466 return 0;
468 bool last_was_white = true;
469 int words = 0;
470 for (int i = 0; i < str.Length; ++i) {
471 if (Char.IsWhiteSpace (str [i])) {
472 last_was_white = true;
473 } else {
474 if (last_was_white) {
475 ++words;
476 if (max_words > 0 && words >= max_words)
477 break;
479 last_was_white = false;
483 return words;
486 static public int CountWords (string str)
488 return CountWords (str, -1);