Add session to cache with both hostname and address.
[cyberduck.git] / source / ch / cyberduck / core / Utils.cs
blobdd90a6cbfc73a76dac6514ed49eb8766fae61c6a
1 //
2 // Copyright (c) 2010-2014 Yves Langisch. All rights reserved.
3 // http://cyberduck.ch/
4 //
5 // This program is free software; you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation; either version 2 of the License, or
8 // (at your option) any later version.
9 //
10 // This program is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
14 //
15 // Bug fixes, suggestions and comments should be sent to:
16 // yves@cyberduck.ch
17 //
19 using System;
20 using System.Collections.Generic;
21 using System.ComponentModel;
22 using System.Diagnostics;
23 using System.Globalization;
24 using System.IO;
25 using System.Linq;
26 using System.Reflection;
27 using ch.cyberduck.core;
28 using ch.cyberduck.core.local;
29 using java.util;
30 using Microsoft.Win32;
31 using org.apache.commons.io;
32 using org.apache.log4j;
33 using Collection = java.util.Collection;
35 namespace Ch.Cyberduck.Core
37 public class Utils
39 public delegate object ApplyPerItemForwardDelegate<T>(T item);
41 public delegate T ApplyPerItemReverseDelegate<T>(object item);
43 private static readonly List<String> ExtendedCharsets = new List<string>
45 "Big5",
46 "Big5-HKSCS",
47 "EUC-JP",
48 "EUC-KR",
49 "GB18030",
50 "GB2312",
51 "GBK",
52 "ISO-2022-CN",
53 "ISO-2022-JP",
54 "ISO-2022-JP-2",
55 "ISO-2022-KR",
56 "ISO-8859-3",
57 "ISO-8859-6",
58 "ISO-8859-8",
59 "JIS_X0201",
60 "JIS_X0212-1990",
61 "Shift_JIS",
62 "TIS-620",
63 "windows-1255",
64 "windows-1256",
65 "windows-1258",
66 "windows-31j"
69 public static readonly bool IsVistaOrLater = OperatingSystemVersion.Current >= OSVersionInfo.Vista;
70 public static readonly bool IsWin7OrLater = OperatingSystemVersion.Current >= OSVersionInfo.Win7;
71 private static readonly Logger Log = Logger.getLogger(typeof (Utils).FullName);
73 public static bool IsBlank(string value)
75 if (String.IsNullOrEmpty(value))
77 return true;
80 return String.IsNullOrEmpty(value.Trim());
83 public static Assembly Me()
85 return Assembly.GetExecutingAssembly();
88 public static bool IsNotBlank(string value)
90 return !IsBlank(value);
93 /// <summary>
94 /// Get file extension. Ignores OS specific special characters. Includes the dot if available.
95 /// </summary>
96 /// <param name="filename"></param>
97 /// <returns></returns>
98 public static string GetSafeExtension(string filename)
100 if (IsNotBlank(filename))
102 //see http://windevblog.blogspot.com/2008/09/get-default-application-in-windows-xp.html
103 string extension = FilenameUtils.getExtension(filename);
104 if (IsBlank(extension))
106 return String.Empty;
108 return "." + extension;
110 return String.Empty;
113 public static string SafeString(string s)
115 return s ?? string.Empty;
118 /// <summary>
119 /// Check if a given object is parseable to an int32
120 /// </summary>
121 /// <param name="expression"></param>
122 /// <returns></returns>
123 public static bool IsInt(object expression)
125 int retNum;
127 bool isNum = int.TryParse(Convert.ToString(expression), NumberStyles.Any, NumberFormatInfo.InvariantInfo,
128 out retNum);
129 return isNum;
132 /// <summary>
133 /// Convert a generic IEnumerable to a java list
134 /// </summary>
135 /// <typeparam name="T"></typeparam>
136 /// <param name="list">IEnumerable to convert</param>
137 /// <param name="applyPerItem">Apply this delegate to all list items before adding</param>
138 /// <returns>A java list</returns>
139 public static List ConvertToJavaList<T>(IEnumerable<T> list, ApplyPerItemForwardDelegate<T> applyPerItem)
141 ArrayList javaList = new ArrayList();
142 foreach (T item in list)
144 if (null != applyPerItem)
146 javaList.add(applyPerItem(item));
147 continue;
149 javaList.Add(item);
151 return javaList;
154 /// <summary>
155 ///
156 /// </summary>
157 /// <typeparam name="K"></typeparam>
158 /// <typeparam name="V"></typeparam>
159 /// <param name="dictionary"></param>
160 /// <returns></returns>
161 public static Map ConvertToJavaMap<K, V>(IDictionary<K, V> dictionary)
163 Map javaMap = new HashMap();
164 foreach (KeyValuePair<K, V> pair in dictionary)
166 javaMap.put(pair.Key, pair.Value);
168 return javaMap;
171 /// <summary>
172 ///
173 /// </summary>
174 /// <typeparam name="K"></typeparam>
175 /// <typeparam name="V"></typeparam>
176 /// <param name="javaMap"></param>
177 /// <returns></returns>
178 public static IDictionary<K, V> ConvertFromJavaMap<K, V>(Map javaMap)
180 IDictionary<K, V> result = new Dictionary<K, V>();
181 Iterator iterator = javaMap.entrySet().iterator();
182 while (iterator.hasNext())
184 Map.Entry entry = (Map.Entry) iterator.next();
185 result.Add((K) entry.getKey(), (V) entry.getValue());
187 return result;
190 /// <summary>
191 /// Convert a generic IEnumerable to a java list
192 /// </summary>
193 /// <typeparam name="T"></typeparam>
194 /// <param name="list">IEnumerable to convert</param>
195 /// <returns>A java list</returns>
196 public static List ConvertToJavaList<T>(IEnumerable<T> list)
198 return ConvertToJavaList(list, null);
201 /// <summary>
202 /// Convert a java list to a generic collection
203 /// </summary>
204 /// <typeparam name="T"></typeparam>
205 /// <param name="collection"></param>
206 /// <returns>A List<typeparamref name="T"/></returns>
207 public static ICollection<T> ConvertFromJavaList<T>(Collection collection)
209 return ConvertFromJavaList<T>(collection, null);
212 /// <summary>
213 /// Convert a java list to a generic collection
214 /// </summary>
215 /// <typeparam name="T"></typeparam>
216 /// <param name="collection"></param>
217 /// <param name="applyPerItem">Apply this delegate to all list items before adding</param>
218 /// <returns>A List<typeparamref name="T"/></returns>
219 public static IList<T> ConvertFromJavaList<T>(Collection collection, ApplyPerItemReverseDelegate<T> applyPerItem)
221 List<T> result = new List<T>(collection.size());
222 for (Iterator iterator = collection.iterator(); iterator.hasNext();)
224 Object next = iterator.next();
225 if (null != applyPerItem)
227 result.Add(applyPerItem(next));
228 continue;
230 result.Add((T) next);
232 return result;
235 public static IList<KeyValuePair<string, string>> OpenWithListForExtension(String ext)
237 IList<String> progs = new List<string>();
238 List<KeyValuePair<string, string>> map = new List<KeyValuePair<string, string>>();
240 if (IsBlank(ext)) return map;
242 if (!ext.StartsWith(".")) ext = "." + ext;
243 using (RegistryKey clsExt = Registry.ClassesRoot.OpenSubKey(ext))
245 IList<string> rootList = OpenWithListForExtension(ext, clsExt);
246 foreach (string s in rootList)
248 progs.Add(s);
251 using (
252 RegistryKey clsExt =
253 Registry.CurrentUser.OpenSubKey(
254 "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts\\" + ext))
256 IList<string> explorerList = OpenWithListForExtension(ext, clsExt);
257 foreach (string s in explorerList)
259 progs.Add(s);
263 foreach (string exe in progs.Distinct())
265 ApplicationFinder finder = ApplicationFinderFactory.get();
266 Application application = finder.getDescription(exe);
267 if (finder.isInstalled(application))
269 map.Add(new KeyValuePair<string, string>(application.getName(), exe));
271 else
273 map.Add(new KeyValuePair<string, string>(LocalFactory.get(exe).getName(), exe));
276 map.Sort(
277 delegate(KeyValuePair<string, string> pair1, KeyValuePair<string, string> pair2)
279 return pair1.Key.CompareTo(pair2.Key);
282 return map;
285 public static IList<String> OpenWithListForExtension(String ext, RegistryKey rootKey)
287 IList<String> result = new List<string>();
289 if (null != rootKey)
291 //PerceivedType
292 String perceivedType = (String) rootKey.GetValue("PerceivedType");
293 if (null != perceivedType)
295 using (
296 RegistryKey openWithKey =
297 Registry.ClassesRoot.OpenSubKey("SystemFileAssociations\\" + perceivedType +
298 "\\OpenWithList"))
300 IList<String> appCmds = GetApplicationCmdsFromOpenWithList(openWithKey);
301 foreach (string appCmd in appCmds)
303 result.Add(appCmd);
308 //OpenWithProgIds
309 using (RegistryKey key = rootKey.OpenSubKey("OpenWithProgIds"))
311 IList<String> appCmds = GetApplicationCmdsFromOpenWithProgIds(key);
312 foreach (string appCmd in appCmds)
314 result.Add(appCmd);
318 //OpenWithList
319 using (RegistryKey openWithKey = rootKey.OpenSubKey("OpenWithList"))
321 IList<String> appCmds = GetApplicationCmdsFromOpenWithList(openWithKey);
322 foreach (string appCmd in appCmds)
324 result.Add(appCmd);
328 return result;
331 private static IList<String> GetApplicationCmdsFromOpenWithList(RegistryKey openWithKey)
333 IList<String> appCmds = new List<string>();
334 if (openWithKey != null)
336 //all subkeys
337 string[] exes = openWithKey.GetSubKeyNames();
338 IList<String> cands = exes.ToList();
339 //all values);
340 string[] values = openWithKey.GetValueNames();
341 foreach (string value in values)
343 object o = openWithKey.GetValue(value);
344 if (o is String)
346 cands.Add(o as String);
351 foreach (string s in exes)
353 cands.Add(s);
356 foreach (string progid in cands)
358 using (RegistryKey key = Registry.ClassesRoot.OpenSubKey("Applications\\" + progid))
360 String cmd = GetExeFromOpenCommand(key);
361 if (!String.IsNullOrEmpty(cmd))
363 appCmds.Add(cmd);
368 return appCmds;
371 private static IList<String> GetApplicationCmdsFromOpenWithProgIds(RegistryKey key)
373 IList<String> appCmds = new List<string>();
374 if (key != null)
376 string[] progids = key.GetValueNames();
377 foreach (string progid in progids)
379 if (!string.IsNullOrEmpty(progid))
381 using (RegistryKey clsProgid = Registry.ClassesRoot.OpenSubKey(progid))
383 String cmd = GetExeFromOpenCommand(clsProgid);
384 if (!String.IsNullOrEmpty(cmd))
386 appCmds.Add(cmd);
392 return appCmds;
395 public static bool StartProcess(Process process)
399 process.Start();
400 return true;
402 catch (InvalidOperationException e)
404 Log.error(e);
406 catch (Win32Exception e)
408 Log.error(String.Format("Error while StartProcess: {0},{1}", e.Message, e.NativeErrorCode));
410 return false;
413 public static string ExtractApplicationPath(string cmd)
415 if (!String.IsNullOrEmpty(cmd) && !cmd.Contains("rundll32.exe"))
417 String command = null;
418 if (cmd.StartsWith("\""))
420 int i = cmd.IndexOf("\"", 1);
421 if (i > 2)
422 command = cmd.Substring(1, i - 1);
424 else
426 int i = cmd.IndexOf(" ");
427 if (i > 0)
428 command = cmd.Substring(0, i);
431 if (File.Exists(command))
433 return command;
436 return null;
439 /// <summary>
440 /// Extract open command
441 /// </summary>
442 /// <param name="root">expected substructure is shell/open/command</param>
443 /// <returns>null if not found</returns>
444 public static string GetExeFromOpenCommand(RegistryKey root)
446 if (null != root)
448 using (var editSk = root.OpenSubKey("shell\\open\\command"))
450 if (null != editSk)
452 String cmd = (String) editSk.GetValue(String.Empty);
453 return ExtractApplicationPath(cmd);
457 return null;
460 /// <summary>
461 /// method for retrieving the users default web browser
462 /// </summary>
463 /// <returns></returns>
464 public static string GetSystemDefaultBrowser()
468 //for Vista and later we first check the UserChoice
469 using (
470 var uc =
471 Registry.CurrentUser.OpenSubKey(
472 @"HKEY_CURRENT_USER\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice")
475 if (null != uc)
477 string progid = (string) uc.GetValue("Progid");
478 if (null != progid)
480 string exe = GetExeFromOpenCommand(Registry.ClassesRoot);
481 if (null != exe)
483 return exe;
489 //set the registry key we want to open
490 using (var regKey = Registry.ClassesRoot.OpenSubKey("HTTP\\shell\\open\\command", false))
492 return ExtractExeFromCommand((string) regKey.GetValue(null));
495 catch (Exception)
497 return null;
501 public static string ExtractExeFromCommand(string command)
503 if (!String.IsNullOrEmpty(command))
505 String cmd = null;
506 if (command.StartsWith("\""))
508 int i = command.IndexOf("\"", 1);
509 if (i > 2)
510 cmd = command.Substring(1, i - 1);
512 else
514 int i = command.IndexOf(" ");
515 if (i > 0)
516 cmd = command.Substring(0, i);
519 if (null != cmd && LocalFactory.get(cmd).exists())
521 return cmd;
524 return null;