PageRenderTime 45ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/jEdit/tags/jedit-4-3-pre7/org/gjt/sp/jedit/MiscUtilities.java

#
Java | 1809 lines | 979 code | 153 blank | 677 comment | 311 complexity | fe697073260acd996a2d6b0283a34c25 MD5 | raw file
Possible License(s): BSD-3-Clause, AGPL-1.0, Apache-2.0, LGPL-2.0, LGPL-3.0, GPL-2.0, CC-BY-SA-3.0, LGPL-2.1, GPL-3.0, MPL-2.0-no-copyleft-exception, IPL-1.0
  1. /*
  2. * MiscUtilities.java - Various miscallaneous utility functions
  3. * :tabSize=8:indentSize=8:noTabs=false:
  4. * :folding=explicit:collapseFolds=1:
  5. *
  6. * Copyright (C) 1999, 2005 Slava Pestov
  7. * Portions copyright (C) 2000 Richard S. Hall
  8. * Portions copyright (C) 2001 Dirk Moebius
  9. *
  10. * This program is free software; you can redistribute it and/or
  11. * modify it under the terms of the GNU General Public License
  12. * as published by the Free Software Foundation; either version 2
  13. * of the License, or any later version.
  14. *
  15. * This program is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. * GNU General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU General Public License
  21. * along with this program; if not, write to the Free Software
  22. * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  23. */
  24. package org.gjt.sp.jedit;
  25. //{{{ Imports
  26. import javax.swing.text.Segment;
  27. import javax.swing.JMenuItem;
  28. import java.io.*;
  29. import java.net.MalformedURLException;
  30. import java.net.URL;
  31. import java.nio.charset.Charset;
  32. import java.text.DecimalFormat;
  33. import java.util.*;
  34. import java.util.regex.Matcher;
  35. import java.util.regex.Pattern;
  36. import java.util.zip.GZIPInputStream;
  37. import org.xml.sax.InputSource;
  38. import org.xml.sax.helpers.DefaultHandler;
  39. import org.gjt.sp.jedit.io.*;
  40. import org.gjt.sp.util.Log;
  41. import org.gjt.sp.util.ProgressObserver;
  42. import org.gjt.sp.util.StandardUtilities;
  43. import org.gjt.sp.util.IOUtilities;
  44. import org.gjt.sp.util.XMLUtilities;
  45. import org.gjt.sp.jedit.menu.EnhancedMenuItem;
  46. import org.gjt.sp.jedit.bufferio.BufferIORequest;
  47. import org.gjt.sp.jedit.buffer.JEditBuffer;
  48. //}}}
  49. /**
  50. * Path name manipulation, string manipulation, and more.<p>
  51. *
  52. * The most frequently used members of this class are:<p>
  53. *
  54. * <b>Some path name methods:</b><p>
  55. * <ul>
  56. * <li>{@link #getFileName(String)}</li>
  57. * <li>{@link #getParentOfPath(String)}</li>
  58. * <li>{@link #constructPath(String,String)}</li>
  59. * </ul>
  60. * <b>String comparison:</b><p>
  61. * A {@link #compareStrings(String,String,boolean)} method that unlike
  62. * <function>String.compareTo()</function>, correctly recognizes and handles
  63. * embedded numbers.<p>
  64. *
  65. * This class also defines several inner classes for use with the
  66. * sorting features of the Java collections API:
  67. *
  68. * <ul>
  69. * <li>{@link MiscUtilities.StringCompare}</li>
  70. * <li>{@link MiscUtilities.StringICaseCompare}</li>
  71. * <li>{@link MiscUtilities.MenuItemCompare}</li>
  72. * </ul>
  73. *
  74. * For example, you might call:<p>
  75. *
  76. * <code>Arrays.sort(myListOfStrings,
  77. * new MiscUtilities.StringICaseCompare());</code>
  78. *
  79. * @author Slava Pestov
  80. * @author John Gellene (API documentation)
  81. * @version $Id: MiscUtilities.java 7135 2006-09-26 03:40:58Z ezust $
  82. */
  83. public class MiscUtilities
  84. {
  85. /**
  86. * This encoding is not supported by Java, yet it is useful.
  87. * A UTF-8 file that begins with 0xEFBBBF.
  88. */
  89. public static final String UTF_8_Y = "UTF-8Y";
  90. //{{{ Path name methods
  91. //{{{ canonPath() method
  92. /**
  93. * Returns the canonical form of the specified path name. Currently
  94. * only expands a leading <code>~</code>. <b>For local path names
  95. * only.</b>
  96. * @param path The path name
  97. * @since jEdit 4.0pre2
  98. */
  99. public static String canonPath(String path)
  100. {
  101. if(path.length() == 0)
  102. return path;
  103. if(path.startsWith("file://"))
  104. path = path.substring("file://".length());
  105. else if(path.startsWith("file:"))
  106. path = path.substring("file:".length());
  107. else if(isURL(path))
  108. return path;
  109. if(File.separatorChar == '\\')
  110. {
  111. // get rid of mixed paths on Windows
  112. path = path.replace('/','\\');
  113. // also get rid of trailing spaces on Windows
  114. int trim = path.length();
  115. while(path.charAt(trim - 1) == ' ')
  116. trim--;
  117. if (path.charAt(trim - 1) == '\\')
  118. while (trim > 1 && path.charAt(trim - 2) == '\\')
  119. {
  120. trim--;
  121. }
  122. path = path.substring(0,trim);
  123. }
  124. else if(OperatingSystem.isMacOS())
  125. {
  126. // do the same on OS X
  127. path = path.replace(':','/');
  128. }
  129. if(path.startsWith('~' + File.separator))
  130. {
  131. path = path.substring(2);
  132. String home = System.getProperty("user.home");
  133. if(home.endsWith(File.separator))
  134. return home + path;
  135. else
  136. return home + File.separator + path;
  137. }
  138. else if(path.equals("~"))
  139. return System.getProperty("user.home");
  140. else
  141. return path;
  142. } //}}}
  143. //{{ expandVariables() method
  144. static final String varPatternString = "([$%])([a-zA-Z0-9_]+)(\\1?)";
  145. static final String varPatternString2 = "([$%])\\{([^}]+)\\}";
  146. static final Pattern varPattern = Pattern.compile(varPatternString);
  147. static final Pattern varPattern2 = Pattern.compile(varPatternString2);
  148. /** Accepts a string from the user which may contain variables of various syntaxes.
  149. * The goal is to support the following:
  150. * $varname
  151. * ${varname}
  152. * %varname%?
  153. * And expand each of these by looking at the system environment variables for possible
  154. * expansions.
  155. * @return a string which is either the unchanged input string, or one with expanded variables.
  156. * @since 4.3pre7
  157. */
  158. public static String expandVariables(String arg)
  159. {
  160. Pattern p = varPattern;
  161. Matcher m = p.matcher(arg);
  162. if (!m.find())
  163. {
  164. p = varPattern2;
  165. m = p.matcher(arg);
  166. if (!m.find()) // no variables to substitute
  167. return arg;
  168. }
  169. String varName = m.group(2);
  170. String expansion = System.getenv(varName);
  171. if (expansion == null)
  172. { // try everything uppercase?
  173. varName = varName.toUpperCase();
  174. String uparg = arg.toUpperCase();
  175. m = p.matcher(uparg);
  176. expansion = System.getenv(varName);
  177. }
  178. if (expansion != null)
  179. {
  180. expansion = expansion.replace("\\", "\\\\");
  181. return m.replaceFirst(expansion);
  182. }
  183. return arg;
  184. }
  185. //{{{ resolveSymlinks() method
  186. /**
  187. * Resolves any symbolic links in the path name specified
  188. * using <code>File.getCanonicalPath()</code>. <b>For local path
  189. * names only.</b>
  190. * @since jEdit 4.2pre1
  191. */
  192. public static String resolveSymlinks(String path)
  193. {
  194. if(isURL(path))
  195. return path;
  196. // 2 aug 2003: OS/2 Java has a broken getCanonicalPath()
  197. if(OperatingSystem.isOS2())
  198. return path;
  199. // 18 nov 2003: calling this on a drive letter on Windows causes
  200. // drive access
  201. if(OperatingSystem.isDOSDerived())
  202. {
  203. if(path.length() == 2 || path.length() == 3)
  204. {
  205. if(path.charAt(1) == ':')
  206. return path;
  207. }
  208. }
  209. try
  210. {
  211. return new File(path).getCanonicalPath();
  212. }
  213. catch(IOException io)
  214. {
  215. return path;
  216. }
  217. } //}}}
  218. //{{{ isAbsolutePath() method
  219. /**
  220. * Returns if the specified path name is an absolute path or URL.
  221. * @since jEdit 4.1pre11
  222. */
  223. public static boolean isAbsolutePath(String path)
  224. {
  225. if(isURL(path))
  226. return true;
  227. else if(path.startsWith("~/") || path.startsWith("~" + File.separator) || path.equals("~"))
  228. return true;
  229. else if(OperatingSystem.isDOSDerived())
  230. {
  231. if(path.length() == 2 && path.charAt(1) == ':')
  232. return true;
  233. if(path.length() > 2 && path.charAt(1) == ':'
  234. && (path.charAt(2) == '\\'
  235. || path.charAt(2) == '/'))
  236. return true;
  237. if(path.startsWith("\\\\")
  238. || path.startsWith("//"))
  239. return true;
  240. }
  241. // not sure if this is correct for OpenVMS.
  242. else if(OperatingSystem.isUnix()
  243. || OperatingSystem.isVMS())
  244. {
  245. // nice and simple
  246. if(path.length() > 0 && path.charAt(0) == '/')
  247. return true;
  248. }
  249. return false;
  250. } //}}}
  251. //{{{ constructPath() method
  252. /**
  253. * Constructs an absolute path name from a directory and another
  254. * path name. This method is VFS-aware.
  255. * @param parent The directory
  256. * @param path The path name
  257. */
  258. public static String constructPath(String parent, String path)
  259. {
  260. if(isAbsolutePath(path))
  261. return canonPath(path);
  262. // have to handle this case specially on windows.
  263. // insert \ between, eg A: and myfile.txt.
  264. if(OperatingSystem.isDOSDerived())
  265. {
  266. if(path.length() == 2 && path.charAt(1) == ':')
  267. return path;
  268. else if(path.length() > 2 && path.charAt(1) == ':'
  269. && path.charAt(2) != '\\')
  270. {
  271. path = path.substring(0,2) + '\\'
  272. + path.substring(2);
  273. return canonPath(path);
  274. }
  275. }
  276. String dd = ".." + File.separator;
  277. String d = '.' + File.separator;
  278. if(parent == null)
  279. parent = System.getProperty("user.dir");
  280. for(;;)
  281. {
  282. if(path.equals("."))
  283. return parent;
  284. else if(path.equals(".."))
  285. return getParentOfPath(parent);
  286. else if(path.startsWith(dd) || path.startsWith("../"))
  287. {
  288. parent = getParentOfPath(parent);
  289. path = path.substring(3);
  290. }
  291. else if(path.startsWith(d) || path.startsWith("./"))
  292. path = path.substring(2);
  293. else
  294. break;
  295. }
  296. if(OperatingSystem.isDOSDerived()
  297. && !isURL(parent)
  298. && path.charAt(0) == '\\')
  299. parent = parent.substring(0,2);
  300. VFS vfs = VFSManager.getVFSForPath(parent);
  301. return canonPath(vfs.constructPath(parent,path));
  302. } //}}}
  303. //{{{ constructPath() method
  304. /**
  305. * Constructs an absolute path name from three path components.
  306. * This method is VFS-aware.
  307. * @param parent The parent directory
  308. * @param path1 The first path
  309. * @param path2 The second path
  310. */
  311. public static String constructPath(String parent,
  312. String path1, String path2)
  313. {
  314. return constructPath(constructPath(parent,path1),path2);
  315. } //}}}
  316. //{{{ concatPath() method
  317. /**
  318. * Like {@link #constructPath}, except <code>path</code> will be
  319. * appended to <code>parent</code> even if it is absolute.
  320. * <b>For local path names only.</b>.
  321. *
  322. * @param path
  323. * @param parent
  324. */
  325. public static String concatPath(String parent, String path)
  326. {
  327. parent = canonPath(parent);
  328. path = canonPath(path);
  329. // Make all child paths relative.
  330. if (path.startsWith(File.separator))
  331. path = path.substring(1);
  332. else if ((path.length() >= 3) && (path.charAt(1) == ':'))
  333. path = path.replace(':', File.separatorChar);
  334. if (parent == null)
  335. parent = System.getProperty("user.dir");
  336. if (parent.endsWith(File.separator))
  337. return parent + path;
  338. else
  339. return parent + File.separator + path;
  340. } //}}}
  341. //{{{ getFirstSeparatorIndex() method
  342. /**
  343. * Return the first index of either / or the OS-specific file
  344. * separator.
  345. * @param path The path
  346. * @since jEdit 4.3pre3
  347. */
  348. public static int getFirstSeparatorIndex(String path)
  349. {
  350. int start = getPathStart(path);
  351. int index = path.indexOf('/',start);
  352. if(index == -1)
  353. index = path.indexOf(File.separatorChar,start);
  354. return index;
  355. } //}}}
  356. //{{{ getLastSeparatorIndex() method
  357. /**
  358. * Return the last index of either / or the OS-specific file
  359. * separator.
  360. * @param path The path
  361. * @since jEdit 4.3pre3
  362. */
  363. public static int getLastSeparatorIndex(String path)
  364. {
  365. int start = getPathStart(path);
  366. if(start != 0)
  367. path = path.substring(start);
  368. int index = Math.max(path.lastIndexOf('/'),
  369. path.lastIndexOf(File.separatorChar));
  370. if(index == -1)
  371. return index;
  372. else
  373. return index + start;
  374. } //}}}
  375. //{{{ getFileExtension() method
  376. /**
  377. * Returns the extension of the specified filename, or an empty
  378. * string if there is none.
  379. * @param path The path
  380. */
  381. public static String getFileExtension(String path)
  382. {
  383. int fsIndex = getLastSeparatorIndex(path);
  384. int index = path.indexOf('.',fsIndex);
  385. if(index == -1)
  386. return "";
  387. else
  388. return path.substring(index);
  389. } //}}}
  390. //{{{ getFileName() method
  391. /**
  392. * Returns the last component of the specified path.
  393. * This method is VFS-aware.
  394. * @param path The path name
  395. */
  396. public static String getFileName(String path)
  397. {
  398. return VFSManager.getVFSForPath(path).getFileName(path);
  399. } //}}}
  400. //{{{ getFileNameNoExtension() method
  401. /**
  402. * Returns the last component of the specified path name without the
  403. * trailing extension (if there is one).
  404. * @param path The path name
  405. * @since jEdit 4.0pre8
  406. */
  407. public static String getFileNameNoExtension(String path)
  408. {
  409. String name = getFileName(path);
  410. int index = name.indexOf('.');
  411. if(index == -1)
  412. return name;
  413. else
  414. return name.substring(0,index);
  415. } //}}}
  416. //{{{ getFileParent() method
  417. /**
  418. * @deprecated Call getParentOfPath() instead
  419. */
  420. public static String getFileParent(String path)
  421. {
  422. return getParentOfPath(path);
  423. } //}}}
  424. //{{{ getParentOfPath() method
  425. /**
  426. * Returns the parent of the specified path. This method is VFS-aware.
  427. * @param path The path name
  428. * @since jEdit 2.6pre5
  429. */
  430. public static String getParentOfPath(String path)
  431. {
  432. return VFSManager.getVFSForPath(path).getParentOfPath(path);
  433. } //}}}
  434. //{{{ getFileProtocol() method
  435. /**
  436. * @deprecated Call getProtocolOfURL() instead
  437. */
  438. public static String getFileProtocol(String url)
  439. {
  440. return getProtocolOfURL(url);
  441. } //}}}
  442. //{{{ getProtocolOfURL() method
  443. /**
  444. * Returns the protocol specified by a URL.
  445. * @param url The URL
  446. * @since jEdit 2.6pre5
  447. */
  448. public static String getProtocolOfURL(String url)
  449. {
  450. return url.substring(0,url.indexOf(':'));
  451. } //}}}
  452. //{{{ isURL() method
  453. /**
  454. * Checks if the specified string is a URL.
  455. * @param str The string to check
  456. * @return True if the string is a URL, false otherwise
  457. */
  458. public static boolean isURL(String str)
  459. {
  460. int fsIndex = getLastSeparatorIndex(str);
  461. if(fsIndex == 0) // /etc/passwd
  462. return false;
  463. else if(fsIndex == 2) // C:\AUTOEXEC.BAT
  464. return false;
  465. int cIndex = str.indexOf(':');
  466. if(cIndex <= 1) // D:\WINDOWS, or doesn't contain : at all
  467. return false;
  468. String protocol = str.substring(0,cIndex);
  469. VFS vfs = VFSManager.getVFSForProtocol(protocol);
  470. if(vfs != null && !(vfs instanceof UrlVFS))
  471. return true;
  472. try
  473. {
  474. new URL(str);
  475. return true;
  476. }
  477. catch(MalformedURLException mf)
  478. {
  479. return false;
  480. }
  481. } //}}}
  482. //{{{ saveBackup() method
  483. /**
  484. * Saves a backup (optionally numbered) of a file.
  485. * @param file A local file
  486. * @param backups The number of backups. Must be >= 1. If > 1, backup
  487. * files will be numbered.
  488. * @param backupPrefix The backup file name prefix
  489. * @param backupSuffix The backup file name suffix
  490. * @param backupDirectory The directory where to save backups; if null,
  491. * they will be saved in the same directory as the file itself.
  492. * @since jEdit 4.0pre1
  493. */
  494. public static void saveBackup(File file, int backups,
  495. String backupPrefix, String backupSuffix,
  496. String backupDirectory)
  497. {
  498. saveBackup(file,backups,backupPrefix,backupSuffix,backupDirectory,0);
  499. } //}}}
  500. //{{{ saveBackup() method
  501. /**
  502. * Saves a backup (optionally numbered) of a file.
  503. * @param file A local file
  504. * @param backups The number of backups. Must be >= 1. If > 1, backup
  505. * files will be numbered.
  506. * @param backupPrefix The backup file name prefix
  507. * @param backupSuffix The backup file name suffix
  508. * @param backupDirectory The directory where to save backups; if null,
  509. * they will be saved in the same directory as the file itself.
  510. * @param backupTimeDistance The minimum time in minutes when a backup
  511. * version 1 shall be moved into version 2; if 0, backups are always
  512. * moved.
  513. * @since jEdit 4.2pre5
  514. */
  515. public static void saveBackup(File file, int backups,
  516. String backupPrefix, String backupSuffix,
  517. String backupDirectory, int backupTimeDistance)
  518. {
  519. if(backupPrefix == null)
  520. backupPrefix = "";
  521. if(backupSuffix == null)
  522. backupSuffix = "";
  523. String name = file.getName();
  524. // If backups is 1, create ~ file
  525. if(backups == 1)
  526. {
  527. File backupFile = new File(backupDirectory,
  528. backupPrefix + name + backupSuffix);
  529. long modTime = backupFile.lastModified();
  530. /* if backup file was created less than
  531. * 'backupTimeDistance' ago, we do not
  532. * create the backup */
  533. if(System.currentTimeMillis() - modTime
  534. >= backupTimeDistance)
  535. {
  536. backupFile.delete();
  537. if (!file.renameTo(backupFile))
  538. moveFile(file, backupFile);
  539. }
  540. }
  541. // If backups > 1, move old ~n~ files, create ~1~ file
  542. else
  543. {
  544. /* delete a backup created using above method */
  545. new File(backupDirectory,
  546. backupPrefix + name + backupSuffix
  547. + backups + backupSuffix).delete();
  548. File firstBackup = new File(backupDirectory,
  549. backupPrefix + name + backupSuffix
  550. + "1" + backupSuffix);
  551. long modTime = firstBackup.lastModified();
  552. /* if backup file was created less than
  553. * 'backupTimeDistance' ago, we do not
  554. * create the backup */
  555. if(System.currentTimeMillis() - modTime
  556. >= backupTimeDistance)
  557. {
  558. for(int i = backups - 1; i > 0; i--)
  559. {
  560. File backup = new File(backupDirectory,
  561. backupPrefix + name
  562. + backupSuffix + i
  563. + backupSuffix);
  564. backup.renameTo(
  565. new File(backupDirectory,
  566. backupPrefix + name
  567. + backupSuffix + (i+1)
  568. + backupSuffix));
  569. }
  570. File backupFile = new File(backupDirectory,
  571. backupPrefix + name + backupSuffix
  572. + "1" + backupSuffix);
  573. if (!file.renameTo(backupFile))
  574. moveFile(file, backupFile);
  575. }
  576. }
  577. } //}}}
  578. //{{{ moveFile() method
  579. /**
  580. * Moves the source file to the destination.
  581. *
  582. * If the destination cannot be created or is a read-only file, the
  583. * method returns <code>false</code>. Otherwise, the contents of the
  584. * source are copied to the destination, the source is deleted,
  585. * and <code>true</code> is returned.
  586. *
  587. * @param source The source file to move.
  588. * @param dest The destination where to move the file.
  589. * @return true on success, false otherwise.
  590. *
  591. * @since jEdit 4.3pre1
  592. */
  593. public static boolean moveFile(File source, File dest)
  594. {
  595. boolean ok = false;
  596. if ((dest.exists() && dest.canWrite())
  597. || (!dest.exists() && dest.getParentFile().canWrite()))
  598. {
  599. OutputStream fos = null;
  600. InputStream fis = null;
  601. try
  602. {
  603. fos = new FileOutputStream(dest);
  604. fis = new FileInputStream(source);
  605. ok = copyStream(32768,null,fis,fos,false);
  606. }
  607. catch (IOException ioe)
  608. {
  609. Log.log(Log.WARNING, MiscUtilities.class,
  610. "Error moving file: " + ioe + " : " + ioe.getMessage());
  611. }
  612. finally
  613. {
  614. try
  615. {
  616. if(fos != null)
  617. fos.close();
  618. if(fis != null)
  619. fis.close();
  620. }
  621. catch(Exception e)
  622. {
  623. Log.log(Log.ERROR,MiscUtilities.class,e);
  624. }
  625. }
  626. if(ok)
  627. source.delete();
  628. }
  629. return ok;
  630. } //}}}
  631. //{{{ copyStream() method
  632. /**
  633. * Copy an input stream to an output stream.
  634. *
  635. * @param bufferSize the size of the buffer
  636. * @param progress the progress observer it could be null
  637. * @param in the input stream
  638. * @param out the output stream
  639. * @param canStop if true, the copy can be stopped by interrupting the thread
  640. * @return <code>true</code> if the copy was done, <code>false</code> if it was interrupted
  641. * @throws IOException IOException If an I/O error occurs
  642. * @since jEdit 4.3pre3
  643. * @deprecated use {@link IOUtilities#copyStream(int, org.gjt.sp.util.ProgressObserver, java.io.InputStream, java.io.OutputStream, boolean)}
  644. */
  645. public static boolean copyStream(int bufferSize, ProgressObserver progress,
  646. InputStream in, OutputStream out, boolean canStop)
  647. throws IOException
  648. {
  649. return IOUtilities.copyStream(bufferSize, progress, in, out, canStop);
  650. } //}}}
  651. //{{{ copyStream() method
  652. /**
  653. * Copy an input stream to an output stream with a buffer of 4096 bytes.
  654. *
  655. * @param progress the progress observer it could be null
  656. * @param in the input stream
  657. * @param out the output stream
  658. * @param canStop if true, the copy can be stopped by interrupting the thread
  659. * @return <code>true</code> if the copy was done, <code>false</code> if it was interrupted
  660. * @throws IOException IOException If an I/O error occurs
  661. * @since jEdit 4.3pre3
  662. * @deprecated use {@link IOUtilities#copyStream(org.gjt.sp.util.ProgressObserver, java.io.InputStream, java.io.OutputStream, boolean)}
  663. */
  664. public static boolean copyStream(ProgressObserver progress,
  665. InputStream in, OutputStream out, boolean canStop)
  666. throws IOException
  667. {
  668. return copyStream(4096,progress, in, out, canStop);
  669. } //}}}
  670. //{{{ isBinaryFile() method
  671. /**
  672. * Check if a Reader is binary.
  673. * To check if a file is binary, we will check the first characters 100
  674. * (jEdit property vfs.binaryCheck.length)
  675. * If more than 1 (jEdit property vfs.binaryCheck.count), the
  676. * file is declared binary.
  677. * This is not 100% because sometimes the autodetection could fail.
  678. * This method will not close your reader. You have to do it yourself
  679. *
  680. * @param reader the reader
  681. * @return <code>true</code> if the Reader was detected as binary
  682. * @throws IOException IOException If an I/O error occurs
  683. * @since jEdit 4.3pre5
  684. */
  685. public static boolean isBinary(Reader reader)
  686. throws IOException
  687. {
  688. int nbChars = jEdit.getIntegerProperty("vfs.binaryCheck.length",100);
  689. int authorized = jEdit.getIntegerProperty("vfs.binaryCheck.count",1);
  690. for (long i = 0L;i < nbChars;i++)
  691. {
  692. int c = reader.read();
  693. if (c == -1)
  694. return false;
  695. if (c == 0)
  696. {
  697. authorized--;
  698. if (authorized == 0)
  699. return true;
  700. }
  701. }
  702. return false;
  703. } //}}}
  704. //{{{ isBackup() method
  705. /**
  706. * Check if the filename is a backup file.
  707. * @param filename the filename to check
  708. * @return true if this is a backup file.
  709. * @since jEdit 4.3pre5
  710. */
  711. public static boolean isBackup( String filename ) {
  712. if (filename.startsWith("#")) return true;
  713. if (filename.endsWith("~")) return true;
  714. if (filename.endsWith(".bak")) return true;
  715. return false;
  716. } //}}}
  717. //{{{ autodetect() method
  718. /**
  719. * Tries to detect if the stream is gzipped, and if it has an encoding
  720. * specified with an XML PI.
  721. *
  722. * @param in the input stream reader that must be autodetected
  723. * @param buffer a buffer. It can be null if you only want to autodetect the encoding of a file
  724. * @return a reader using the detected encoding
  725. * @throws IOException io exception during read
  726. * @since jEdit 4.3pre5
  727. */
  728. public static Reader autodetect(InputStream in, Buffer buffer) throws IOException
  729. {
  730. in = new BufferedInputStream(in);
  731. String encoding;
  732. if (buffer == null)
  733. encoding = System.getProperty("file.encoding");
  734. else
  735. encoding = buffer.getStringProperty(JEditBuffer.ENCODING);
  736. if(!in.markSupported())
  737. Log.log(Log.WARNING,MiscUtilities.class,"Mark not supported: " + in);
  738. else if(buffer == null || buffer.getBooleanProperty(Buffer.ENCODING_AUTODETECT))
  739. {
  740. in.mark(BufferIORequest.XML_PI_LENGTH);
  741. int b1 = in.read();
  742. int b2 = in.read();
  743. int b3 = in.read();
  744. if(b1 == BufferIORequest.GZIP_MAGIC_1 && b2 == BufferIORequest.GZIP_MAGIC_2)
  745. {
  746. in.reset();
  747. in = new GZIPInputStream(in);
  748. if (buffer != null)
  749. buffer.setBooleanProperty(Buffer.GZIPPED,true);
  750. // auto-detect encoding within the gzip stream.
  751. return autodetect(in, buffer);
  752. }
  753. else if (b1 == BufferIORequest.UNICODE_MAGIC_1
  754. && b2 == BufferIORequest.UNICODE_MAGIC_2)
  755. {
  756. in.reset();
  757. in.read();
  758. in.read();
  759. encoding = "UTF-16BE";
  760. if (buffer != null)
  761. buffer.setProperty(JEditBuffer.ENCODING,encoding);
  762. }
  763. else if (b1 == BufferIORequest.UNICODE_MAGIC_2
  764. && b2 == BufferIORequest.UNICODE_MAGIC_1)
  765. {
  766. in.reset();
  767. in.read();
  768. in.read();
  769. encoding = "UTF-16LE";
  770. if (buffer != null)
  771. buffer.setProperty(JEditBuffer.ENCODING,encoding);
  772. }
  773. else if(b1 == BufferIORequest.UTF8_MAGIC_1 && b2 == BufferIORequest.UTF8_MAGIC_2
  774. && b3 == BufferIORequest.UTF8_MAGIC_3)
  775. {
  776. // do not reset the stream and just treat it
  777. // like a normal UTF-8 file.
  778. if (buffer != null)
  779. buffer.setProperty(JEditBuffer.ENCODING, MiscUtilities.UTF_8_Y);
  780. encoding = "UTF-8";
  781. }
  782. else
  783. {
  784. in.reset();
  785. byte[] _xmlPI = new byte[BufferIORequest.XML_PI_LENGTH];
  786. int offset = 0;
  787. int count;
  788. while((count = in.read(_xmlPI,offset,
  789. BufferIORequest.XML_PI_LENGTH - offset)) != -1)
  790. {
  791. offset += count;
  792. if(offset == BufferIORequest.XML_PI_LENGTH)
  793. break;
  794. }
  795. String xmlEncoding = getXMLEncoding(new String(
  796. _xmlPI,0,offset,"ASCII"));
  797. if(xmlEncoding != null)
  798. {
  799. encoding = xmlEncoding;
  800. if (buffer != null)
  801. buffer.setProperty(JEditBuffer.ENCODING,encoding);
  802. }
  803. if(encoding.equals(MiscUtilities.UTF_8_Y))
  804. encoding = "UTF-8";
  805. in.reset();
  806. }
  807. }
  808. return new InputStreamReader(in,encoding);
  809. } //}}}
  810. //{{{ getXMLEncoding() method
  811. /**
  812. * Extract XML encoding name from PI.
  813. */
  814. private static String getXMLEncoding(String xmlPI)
  815. {
  816. if(!xmlPI.startsWith("<?xml"))
  817. return null;
  818. int index = xmlPI.indexOf("encoding=");
  819. if(index == -1 || index + 9 == xmlPI.length())
  820. return null;
  821. char ch = xmlPI.charAt(index + 9);
  822. int endIndex = xmlPI.indexOf(ch,index + 10);
  823. if(endIndex == -1)
  824. return null;
  825. String encoding = xmlPI.substring(index + 10,endIndex);
  826. if(Charset.isSupported(encoding))
  827. return encoding;
  828. else
  829. {
  830. Log.log(Log.WARNING,MiscUtilities.class,"XML PI specifies "
  831. + "unsupported encoding: " + encoding);
  832. return null;
  833. }
  834. } //}}}
  835. //{{{ closeQuietly() method
  836. /**
  837. * Method that will close an {@link InputStream} ignoring it if it is null and ignoring exceptions.
  838. *
  839. * @param in the InputStream to close.
  840. * @since jEdit 4.3pre3
  841. * @deprecated use {@link IOUtilities#closeQuietly(java.io.InputStream)}
  842. */
  843. public static void closeQuietly(InputStream in)
  844. {
  845. IOUtilities.closeQuietly(in);
  846. } //}}}
  847. //{{{ copyStream() method
  848. /**
  849. * Method that will close an {@link OutputStream} ignoring it if it is null and ignoring exceptions.
  850. *
  851. * @param out the OutputStream to close.
  852. * @since jEdit 4.3pre3
  853. * @deprecated use {@link IOUtilities#closeQuietly(java.io.OutputStream)}
  854. */
  855. public static void closeQuietly(OutputStream out)
  856. {
  857. IOUtilities.closeQuietly(out);
  858. } //}}}
  859. //{{{ fileToClass() method
  860. /**
  861. * Converts a file name to a class name. All slash characters are
  862. * replaced with periods and the trailing '.class' is removed.
  863. * @param name The file name
  864. */
  865. public static String fileToClass(String name)
  866. {
  867. char[] clsName = name.toCharArray();
  868. for(int i = clsName.length - 6; i >= 0; i--)
  869. if(clsName[i] == '/')
  870. clsName[i] = '.';
  871. return new String(clsName,0,clsName.length - 6);
  872. } //}}}
  873. //{{{ classToFile() method
  874. /**
  875. * Converts a class name to a file name. All periods are replaced
  876. * with slashes and the '.class' extension is added.
  877. * @param name The class name
  878. */
  879. public static String classToFile(String name)
  880. {
  881. return name.replace('.','/').concat(".class");
  882. } //}}}
  883. //{{{ pathsEqual() method
  884. /**
  885. * @param p1 A path name
  886. * @param p2 A path name
  887. * @return True if both paths are equal, ignoring trailing slashes, as
  888. * well as case insensitivity on Windows.
  889. * @since jEdit 4.3pre2
  890. */
  891. public static boolean pathsEqual(String p1, String p2)
  892. {
  893. VFS v1 = VFSManager.getVFSForPath(p1);
  894. VFS v2 = VFSManager.getVFSForPath(p2);
  895. if(v1 != v2)
  896. return false;
  897. if(p1.endsWith("/") || p1.endsWith(File.separator))
  898. p1 = p1.substring(0,p1.length() - 1);
  899. if(p2.endsWith("/") || p2.endsWith(File.separator))
  900. p2 = p2.substring(0,p2.length() - 1);
  901. if((v1.getCapabilities() & VFS.CASE_INSENSITIVE_CAP) != 0)
  902. return p1.equalsIgnoreCase(p2);
  903. else
  904. return p1.equals(p2);
  905. } //}}}
  906. //}}}
  907. //{{{ Text methods
  908. //{{{ getLeadingWhiteSpace() method
  909. /**
  910. * Returns the number of leading white space characters in the
  911. * specified string.
  912. * @param str The string
  913. * @deprecated use {@link StandardUtilities#getLeadingWhiteSpace(String)}
  914. */
  915. public static int getLeadingWhiteSpace(String str)
  916. {
  917. return StandardUtilities.getLeadingWhiteSpace(str);
  918. } //}}}
  919. //{{{ getTrailingWhiteSpace() method
  920. /**
  921. * Returns the number of trailing whitespace characters in the
  922. * specified string.
  923. * @param str The string
  924. * @since jEdit 2.5pre5
  925. * @deprecated use {@link StandardUtilities#getTrailingWhiteSpace(String)}
  926. */
  927. public static int getTrailingWhiteSpace(String str)
  928. {
  929. return StandardUtilities.getTrailingWhiteSpace(str);
  930. } //}}}
  931. //{{{ getLeadingWhiteSpaceWidth() method
  932. /**
  933. * Returns the width of the leading white space in the specified
  934. * string.
  935. * @param str The string
  936. * @param tabSize The tab size
  937. * @deprecated use {@link StandardUtilities#getLeadingWhiteSpace(String)}
  938. */
  939. public static int getLeadingWhiteSpaceWidth(String str, int tabSize)
  940. {
  941. return StandardUtilities.getLeadingWhiteSpaceWidth(str, tabSize);
  942. } //}}}
  943. //{{{ getVirtualWidth() method
  944. /**
  945. * Returns the virtual column number (taking tabs into account) of the
  946. * specified offset in the segment.
  947. *
  948. * @param seg The segment
  949. * @param tabSize The tab size
  950. * @since jEdit 4.1pre1
  951. * @deprecated use {@link StandardUtilities#getVirtualWidth(javax.swing.text.Segment, int)}
  952. */
  953. public static int getVirtualWidth(Segment seg, int tabSize)
  954. {
  955. return StandardUtilities.getVirtualWidth(seg, tabSize);
  956. } //}}}
  957. //{{{ getOffsetOfVirtualColumn() method
  958. /**
  959. * Returns the array offset of a virtual column number (taking tabs
  960. * into account) in the segment.
  961. *
  962. * @param seg The segment
  963. * @param tabSize The tab size
  964. * @param column The virtual column number
  965. * @param totalVirtualWidth If this array is non-null, the total
  966. * virtual width will be stored in its first location if this method
  967. * returns -1.
  968. *
  969. * @return -1 if the column is out of bounds
  970. *
  971. * @since jEdit 4.1pre1
  972. * @deprecated use {@link StandardUtilities#getVirtualWidth(javax.swing.text.Segment, int)}
  973. */
  974. public static int getOffsetOfVirtualColumn(Segment seg, int tabSize,
  975. int column, int[] totalVirtualWidth)
  976. {
  977. return StandardUtilities.getOffsetOfVirtualColumn(seg, tabSize, column, totalVirtualWidth);
  978. } //}}}
  979. //{{{ createWhiteSpace() method
  980. /**
  981. * Creates a string of white space with the specified length.<p>
  982. *
  983. * To get a whitespace string tuned to the current buffer's
  984. * settings, call this method as follows:
  985. *
  986. * <pre>myWhitespace = MiscUtilities.createWhiteSpace(myLength,
  987. * (buffer.getBooleanProperty("noTabs") ? 0
  988. * : buffer.getTabSize()));</pre>
  989. *
  990. * @param len The length
  991. * @param tabSize The tab size, or 0 if tabs are not to be used
  992. * @deprecated use {@link StandardUtilities#createWhiteSpace(int, int)}
  993. */
  994. public static String createWhiteSpace(int len, int tabSize)
  995. {
  996. return StandardUtilities.createWhiteSpace(len,tabSize,0);
  997. } //}}}
  998. //{{{ createWhiteSpace() method
  999. /**
  1000. * Creates a string of white space with the specified length.<p>
  1001. *
  1002. * To get a whitespace string tuned to the current buffer's
  1003. * settings, call this method as follows:
  1004. *
  1005. * <pre>myWhitespace = MiscUtilities.createWhiteSpace(myLength,
  1006. * (buffer.getBooleanProperty("noTabs") ? 0
  1007. * : buffer.getTabSize()));</pre>
  1008. *
  1009. * @param len The length
  1010. * @param tabSize The tab size, or 0 if tabs are not to be used
  1011. * @param start The start offset, for tab alignment
  1012. * @since jEdit 4.2pre1
  1013. * @deprecated use {@link StandardUtilities#createWhiteSpace(int, int, int)}
  1014. */
  1015. public static String createWhiteSpace(int len, int tabSize, int start)
  1016. {
  1017. return StandardUtilities.createWhiteSpace(len, tabSize, start);
  1018. } //}}}
  1019. //{{{ globToRE() method
  1020. /**
  1021. * Converts a Unix-style glob to a regular expression.<p>
  1022. *
  1023. * ? becomes ., * becomes .*, {aa,bb} becomes (aa|bb).
  1024. * @param glob The glob pattern
  1025. * @deprecated Use {@link StandardUtilities#globToRE(String)}.
  1026. */
  1027. public static String globToRE(String glob)
  1028. {
  1029. return StandardUtilities.globToRE(glob);
  1030. } //}}}
  1031. //{{{ escapesToChars() method
  1032. /**
  1033. * Converts "\n" and "\t" escapes in the specified string to
  1034. * newlines and tabs.
  1035. * @param str The string
  1036. * @since jEdit 2.3pre1
  1037. */
  1038. public static String escapesToChars(String str)
  1039. {
  1040. StringBuffer buf = new StringBuffer();
  1041. for(int i = 0; i < str.length(); i++)
  1042. {
  1043. char c = str.charAt(i);
  1044. switch(c)
  1045. {
  1046. case '\\':
  1047. if(i == str.length() - 1)
  1048. {
  1049. buf.append('\\');
  1050. break;
  1051. }
  1052. c = str.charAt(++i);
  1053. switch(c)
  1054. {
  1055. case 'n':
  1056. buf.append('\n');
  1057. break;
  1058. case 't':
  1059. buf.append('\t');
  1060. break;
  1061. default:
  1062. buf.append(c);
  1063. break;
  1064. }
  1065. break;
  1066. default:
  1067. buf.append(c);
  1068. }
  1069. }
  1070. return buf.toString();
  1071. } //}}}
  1072. //{{{ charsToEscapes() method
  1073. /**
  1074. * Escapes newlines, tabs, backslashes, and quotes in the specified
  1075. * string.
  1076. * @param str The string
  1077. * @since jEdit 2.3pre1
  1078. */
  1079. public static String charsToEscapes(String str)
  1080. {
  1081. return charsToEscapes(str,"\n\t\\\"'");
  1082. } //}}}
  1083. //{{{ charsToEscapes() method
  1084. /**
  1085. * Escapes the specified characters in the specified string.
  1086. * @param str The string
  1087. * @param toEscape Any characters that require escaping
  1088. * @since jEdit 4.1pre3
  1089. */
  1090. public static String charsToEscapes(String str, String toEscape)
  1091. {
  1092. StringBuffer buf = new StringBuffer();
  1093. for(int i = 0; i < str.length(); i++)
  1094. {
  1095. char c = str.charAt(i);
  1096. if(toEscape.indexOf(c) != -1)
  1097. {
  1098. if(c == '\n')
  1099. buf.append("\\n");
  1100. else if(c == '\t')
  1101. buf.append("\\t");
  1102. else
  1103. {
  1104. buf.append('\\');
  1105. buf.append(c);
  1106. }
  1107. }
  1108. else
  1109. buf.append(c);
  1110. }
  1111. return buf.toString();
  1112. } //}}}
  1113. //{{{ compareVersions() method
  1114. /**
  1115. * @deprecated Call <code>compareStrings()</code> instead
  1116. */
  1117. public static int compareVersions(String v1, String v2)
  1118. {
  1119. return StandardUtilities.compareStrings(v1,v2,false);
  1120. } //}}}
  1121. //{{{ compareStrings() method
  1122. /**
  1123. * Compares two strings.<p>
  1124. *
  1125. * Unlike <function>String.compareTo()</function>,
  1126. * this method correctly recognizes and handles embedded numbers.
  1127. * For example, it places "My file 2" before "My file 10".<p>
  1128. *
  1129. * @param str1 The first string
  1130. * @param str2 The second string
  1131. * @param ignoreCase If true, case will be ignored
  1132. * @return negative If str1 &lt; str2, 0 if both are the same,
  1133. * positive if str1 &gt; str2
  1134. * @since jEdit 4.0pre1
  1135. * @deprecated use {@link StandardUtilities#compareStrings(String, String, boolean)}
  1136. */
  1137. public static int compareStrings(String str1, String str2, boolean ignoreCase)
  1138. {
  1139. return StandardUtilities.compareStrings(str1, str2, ignoreCase);
  1140. } //}}}
  1141. //{{{ stringsEqual() method
  1142. /**
  1143. * @deprecated Call <code>objectsEqual()</code> instead.
  1144. */
  1145. public static boolean stringsEqual(String s1, String s2)
  1146. {
  1147. return StandardUtilities.objectsEqual(s1,s2);
  1148. } //}}}
  1149. //{{{ objectsEqual() method
  1150. /**
  1151. * Returns if two strings are equal. This correctly handles null pointers,
  1152. * as opposed to calling <code>o1.equals(o2)</code>.
  1153. * @since jEdit 4.2pre1
  1154. * @deprecated use {@link StandardUtilities#objectsEqual(Object, Object)}
  1155. */
  1156. public static boolean objectsEqual(Object o1, Object o2)
  1157. {
  1158. return StandardUtilities.objectsEqual(o1, o2);
  1159. } //}}}
  1160. //{{{ charsToEntities() method
  1161. /**
  1162. * Converts &lt;, &gt;, &amp; in the string to their HTML entity
  1163. * equivalents.
  1164. * @param str The string
  1165. * @since jEdit 4.2pre1
  1166. * @deprecated Use {@link XMLUtilities#charToEntiries(String,boolean)}.
  1167. */
  1168. public static String charsToEntities(String str)
  1169. {
  1170. return XMLUtilities.charsToEntities(str,false);
  1171. } //}}}
  1172. //{{{ formatFileSize() method
  1173. public static final DecimalFormat KB_FORMAT = new DecimalFormat("#.# KB");
  1174. public static final DecimalFormat MB_FORMAT = new DecimalFormat("#.# MB");
  1175. /**
  1176. * Formats the given file size into a nice string (123 bytes, 10.6 KB,
  1177. * 1.2 MB).
  1178. * @param length The size
  1179. * @since jEdit 4.2pre1
  1180. */
  1181. public static String formatFileSize(long length)
  1182. {
  1183. if(length < 1024)
  1184. return length + " bytes";
  1185. else if(length < 1024*1024)
  1186. return KB_FORMAT.format((double)length / 1024);
  1187. else
  1188. return MB_FORMAT.format((double)length / 1024 / 1024);
  1189. } //}}}
  1190. //{{{ getLongestPrefix() method
  1191. /**
  1192. * Returns the longest common prefix in the given set of strings.
  1193. * @param str The strings
  1194. * @param ignoreCase If true, case insensitive
  1195. * @since jEdit 4.2pre2
  1196. */
  1197. public static String getLongestPrefix(List str, boolean ignoreCase)
  1198. {
  1199. if(str.size() == 0)
  1200. return "";
  1201. int prefixLength = 0;
  1202. loop: for(;;)
  1203. {
  1204. String s = str.get(0).toString();
  1205. if(prefixLength >= s.length())
  1206. break loop;
  1207. char ch = s.charAt(prefixLength);
  1208. for(int i = 1; i < str.size(); i++)
  1209. {
  1210. s = str.get(i).toString();
  1211. if(prefixLength >= s.length())
  1212. break loop;
  1213. if(!compareChars(s.charAt(prefixLength),ch,ignoreCase))
  1214. break loop;
  1215. }
  1216. prefixLength++;
  1217. }
  1218. return str.get(0).toString().substring(0,prefixLength);
  1219. } //}}}
  1220. //{{{ getLongestPrefix() method
  1221. /**
  1222. * Returns the longest common prefix in the given set of strings.
  1223. * @param str The strings
  1224. * @param ignoreCase If true, case insensitive
  1225. * @since jEdit 4.2pre2
  1226. */
  1227. public static String getLongestPrefix(String[] str, boolean ignoreCase)
  1228. {
  1229. return getLongestPrefix((Object[])str,ignoreCase);
  1230. } //}}}
  1231. //{{{ getLongestPrefix() method
  1232. /**
  1233. * Returns the longest common prefix in the given set of strings.
  1234. * @param str The strings (calls <code>toString()</code> on each object)
  1235. * @param ignoreCase If true, case insensitive
  1236. * @since jEdit 4.2pre6
  1237. */
  1238. public static String getLongestPrefix(Object[] str, boolean ignoreCase)
  1239. {
  1240. if(str.length == 0)
  1241. return "";
  1242. int prefixLength = 0;
  1243. String first = str[0].toString();
  1244. loop: for(;;)
  1245. {
  1246. if(prefixLength >= first.length())
  1247. break loop;
  1248. char ch = first.charAt(prefixLength);
  1249. for(int i = 1; i < str.length; i++)
  1250. {
  1251. String s = str[i].toString();
  1252. if(prefixLength >= s.length())
  1253. break loop;
  1254. if(!compareChars(s.charAt(prefixLength),ch,ignoreCase))
  1255. break loop;
  1256. }
  1257. prefixLength++;
  1258. }
  1259. return first.substring(0,prefixLength);
  1260. } //}}}
  1261. //}}}
  1262. //{{{ Sorting methods
  1263. //{{{ quicksort() method
  1264. /**
  1265. * Sorts the specified array. Equivalent to calling
  1266. * <code>Arrays.sort()</code>.
  1267. * @param obj The array
  1268. * @param compare Compares the objects
  1269. * @since jEdit 4.0pre4
  1270. * @deprecated use <code>Arrays.sort()</code>
  1271. */
  1272. public static void quicksort(Object[] obj, Comparator compare)
  1273. {
  1274. Arrays.sort(obj,compare);
  1275. } //}}}
  1276. //{{{ quicksort() method
  1277. /**
  1278. * Sorts the specified vector.
  1279. * @param vector The vector
  1280. * @param compare Compares the objects
  1281. * @since jEdit 4.0pre4
  1282. * @deprecated <code>Collections.sort()</code>
  1283. */
  1284. public static void quicksort(Vector vector, Comparator compare)
  1285. {
  1286. Collections.sort(vector,compare);
  1287. } //}}}
  1288. //{{{ quicksort() method
  1289. /**
  1290. * Sorts the specified list.
  1291. * @param list The list
  1292. * @param compare Compares the objects
  1293. * @since jEdit 4.0pre4
  1294. * @deprecated <code>Collections.sort()</code>
  1295. */
  1296. public static void quicksort(List list, Comparator compare)
  1297. {
  1298. Collections.sort(list,compare);
  1299. } //}}}
  1300. //{{{ quicksort() method
  1301. /**
  1302. * Sorts the specified array. Equivalent to calling
  1303. * <code>Arrays.sort()</code>.
  1304. * @param obj The array
  1305. * @param compare Compares the objects
  1306. * @deprecated use <code>Arrays.sort()</code>
  1307. */
  1308. public static void quicksort(Object[] obj, Compare compare)
  1309. {
  1310. Arrays.sort(obj,compare);
  1311. } //}}}
  1312. //{{{ quicksort() method
  1313. /**
  1314. * Sorts the specified vector.
  1315. * @param vector The vector
  1316. * @param compare Compares the objects
  1317. * @deprecated <code>Collections.sort()</code>
  1318. */
  1319. public static void quicksort(Vector vector, Compare compare)
  1320. {
  1321. Collections.sort(vector,compare);
  1322. } //}}}
  1323. //{{{ Compare interface
  1324. /**
  1325. * An interface for comparing objects. This is a hold-over from
  1326. * they days when jEdit had its own sorting API due to JDK 1.1
  1327. * compatibility requirements. Use <code>java.util.Comparable</code>
  1328. * instead.
  1329. * @deprecated
  1330. */
  1331. public interface Compare extends Comparator
  1332. {
  1333. int compare(Object obj1, Object obj2);
  1334. } //}}}
  1335. //{{{ StringCompare class
  1336. /**
  1337. * Compares strings.
  1338. * @deprecated use {@link StandardUtilities.StringCompare}
  1339. */
  1340. public static class StringCompare implements Compare
  1341. {
  1342. public int compare(Object obj1, Object obj2)
  1343. {
  1344. return StandardUtilities.compareStrings(obj1.toString(),
  1345. obj2.toString(),false);
  1346. }
  1347. } //}}}
  1348. //{{{ StringICaseCompare class
  1349. /**
  1350. * Compares strings ignoring case.
  1351. */
  1352. public static class StringICaseCompare implements Comparator<Object>
  1353. {
  1354. public int compare(Object obj1, Object obj2)
  1355. {
  1356. return StandardUtilities.compareStrings(obj1.toString(), obj2.toString(), true);
  1357. }
  1358. } //}}}
  1359. //{{{ MenuItemCompare class
  1360. /**
  1361. * Compares menu item labels.
  1362. */
  1363. public static class MenuItemCompare implements Compare
  1364. {
  1365. public int compare(Object obj1, Object obj2)
  1366. {
  1367. boolean obj1E, obj2E;
  1368. obj1E = obj1 instanceof EnhancedMenuItem;
  1369. obj2E = obj2 instanceof EnhancedMenuItem;
  1370. if(obj1E && !obj2E)
  1371. return 1;
  1372. else if(obj2E && !obj1E)
  1373. return -1;
  1374. else
  1375. return StandardUtilities.compareStrings(((JMenuItem)obj1).getText(),
  1376. ((JMenuItem)obj2).getText(),true);
  1377. }
  1378. } //}}}
  1379. //}}}
  1380. //{{{ buildToVersion() method
  1381. /**
  1382. * Converts an internal version number (build) into a
  1383. * `human-readable' form.
  1384. * @param build The build
  1385. */
  1386. public static String buildToVersion(String build)
  1387. {
  1388. if(build.length() != 11)
  1389. return "<unknown version: " + build + ">";
  1390. // First 2 chars are the major version number
  1391. int major = Integer.parseInt(build.substring(0,2));
  1392. // Second 2 are the minor number
  1393. int minor = Integer.parseInt(build.substring(3,5));
  1394. // Then the pre-release status
  1395. int beta = Integer.parseInt(build.substring(6,8));
  1396. // Finally the bug fix release
  1397. int bugfix = Integer.parseInt(build.substring(9,11));
  1398. return major + "." + minor
  1399. + (beta != 99 ? "pre" + beta :
  1400. (bugfix != 0 ? "." + bugfix : "final"));
  1401. } //}}}
  1402. //{{{ isToolsJarAvailable() method
  1403. /**
  1404. * If on JDK 1.2 or higher, make sure that tools.jar is available.
  1405. * This method should be called by plugins requiring the classes
  1406. * in this library.
  1407. * <p>
  1408. * tools.jar is searched for in the following places:
  1409. * <ol>
  1410. * <li>the classpath that was used when jEdit was started,
  1411. * <li>jEdit's jars folder in the user's home,
  1412. * <li>jEdit's system jars folder,
  1413. * <li><i>java.home</i>/lib/. In this case, tools.jar is added to
  1414. * jEdit's list of known jars using jEdit.addPluginJAR(),
  1415. * so that it gets loaded through JARClassLoader.
  1416. * </ol><p>
  1417. *
  1418. * On older JDK's this method does not perform any checks, and returns
  1419. * <code>true</code> (even though there is no tools.jar).
  1420. *
  1421. * @return <code>false</code> if and only if on JDK 1.2 and tools.jar
  1422. * could not be found. In this case it prints some warnings on Log,
  1423. * too, about the places where it was searched for.
  1424. * @since jEdit 3.2.2
  1425. */
  1426. public static boolean isToolsJarAvailable()
  1427. {
  1428. Log.log(Log.DEBUG, MiscUtilities.class,"Searching for tools.jar...");
  1429. Vector paths = new Vector();
  1430. //{{{ 1. Check whether tools.jar is in the system classpath:
  1431. paths.addElement("System classpath: "
  1432. + System.getProperty("java.class.path"));
  1433. try
  1434. {
  1435. // Either class sun.tools.javac.Main or
  1436. // com.sun.tools.javac.Main must be there:
  1437. try
  1438. {
  1439. Class.forName("sun.tools.javac.Main");
  1440. }
  1441. catch(ClassNotFoundException e1)
  1442. {
  1443. Class.forName("com.sun.tools.javac.Main");
  1444. }
  1445. Log.log(Log.DEBUG, MiscUtilities.class,
  1446. "- is in classpath. Fine.");
  1447. return true;
  1448. }
  1449. catch(ClassNotFoundException e)
  1450. {
  1451. //Log.log(Log.DEBUG, MiscUtilities.class,
  1452. // "- is not in system classpath.");
  1453. } //}}}
  1454. //{{{ 2. Check whether it is in the jEdit user settings jars folder:
  1455. String settingsDir = jEdit.getSettingsDirectory();
  1456. if(settingsDir != null)
  1457. {
  1458. String toolsPath = constructPath(settingsDir, "jars",
  1459. "tools.jar");
  1460. paths.addElement(toolsPath);
  1461. if(new File(toolsPath).exists())
  1462. {
  1463. Log.log(Log.DEBUG, MiscUtilities.class,
  1464. "- is in the user's jars folder. Fine.");
  1465. // jEdit will load it automatically
  1466. return true;
  1467. }
  1468. } //}}}
  1469. //{{{ 3. Check whether it is in jEdit's system jars folder:
  1470. String jEditDir = jEdit.getJEditHome();
  1471. if(jEditDir != null)
  1472. {
  1473. String toolsPath = constructPath(jEditDir, "jars", "tools.jar");
  1474. paths.addElement(toolsPath);
  1475. if(new File(toolsPath).exists())
  1476. {
  1477. Log.log(Log.DEBUG, MiscUtilities.class,
  1478. "- is in jEdit's system jars folder. Fine.");
  1479. // jEdit will load it automatically
  1480. return true;
  1481. }
  1482. } //}}}
  1483. //{{{ 4. Check whether it is in <java.home>/lib:
  1484. String toolsPath = System.getProperty("java.home");
  1485. if(toolsPath.toLowerCase().endsWith(File.separator + "jre"))
  1486. toolsPath = toolsPath.substring(0, toolsPath.length() - 4);
  1487. toolsPath = constructPath(toolsPath, "lib", "tools.jar");
  1488. paths.addElement(toolsPath);
  1489. if(!(new File(toolsPath).exists()))
  1490. {
  1491. Log.log(Log.WARNING, MiscUtilities.class,
  1492. "Could not find tools.jar.\n"
  1493. + "I checked the following locations:\n"
  1494. + paths.toString());
  1495. return false;
  1496. } //}}}
  1497. //{{{ Load it, if not yet done:
  1498. PluginJAR jar = jEdit.getPluginJAR(toolsPath);
  1499. if(jar == null)
  1500. {
  1501. Log.log(Log.DEBUG, MiscUtilities.class,
  1502. "- adding " + toolsPath + " to jEdit plugins.");
  1503. jEdit.addPluginJAR(toolsPath);
  1504. }
  1505. else
  1506. Log.log(Log.DEBUG, MiscUtilities.class,
  1507. "- has been loaded before.");
  1508. //}}}
  1509. return true;
  1510. } //}}}
  1511. //{{{ parsePermissions() method
  1512. /**
  1513. * Parse a Unix-style permission string (rwxrwxrwx).
  1514. * @param s The string (must be 9 characters long).
  1515. * @since jEdit 4.1pre8
  1516. */
  1517. public static int parsePermissions(String s)
  1518. {
  1519. int permissions = 0;
  1520. if(s.length() == 9)
  1521. {
  1522. if(s.charAt(0) == 'r')
  1523. permissions += 0400;
  1524. if(s.charAt(1) == 'w')
  1525. permissions += 0200;
  1526. if(s.charAt(2) == 'x')
  1527. permissions += 0100;
  1528. else if(s.charAt(2) == 's')
  1529. permissions += 04100;
  1530. else if(s.charAt(2) == 'S')
  1531. permissions += 04000;
  1532. if(s.charAt(3) == 'r')
  1533. permissions += 040;
  1534. if(s.charAt(4) == 'w')
  1535. permissions += 020;
  1536. if(s.charAt(5) == 'x')
  1537. permissions += 010;
  1538. else if(s.charAt(5) == 's')
  1539. permissions += 02010;
  1540. else if(s.charAt(5) == 'S')
  1541. permissions += 02000;
  1542. if(s.charAt(6) == 'r')
  1543. permissions += 04;
  1544. if(s.charAt(7) == 'w')
  1545. permissions += 02;
  1546. if(s.charAt(8) == 'x')
  1547. permissions += 01;
  1548. else if(s.charAt(8) == 't')
  1549. permissions += 01001;
  1550. else if(s.charAt(8) == 'T')
  1551. permissions += 01000;
  1552. }
  1553. return permissions;
  1554. } //}}}
  1555. //{{{ getEncodings() method
  1556. /**
  1557. * Returns a list of supported character encodings.
  1558. * @since jEdit 4.2pre5
  1559. * @deprecated See #getEncodings( boolean )
  1560. */
  1561. public static String[] getEncodings()
  1562. {
  1563. return getEncodings(false);
  1564. } //}}}
  1565. //{{{ getEncodings() method
  1566. /**
  1567. * Returns a list of supported character encodings.
  1568. * @since jEdit 4.3pre5
  1569. * @param getSelected Whether to return just the selected encodings or all.
  1570. */
  1571. public static String[] getEncodings(boolean getSelected)
  1572. {
  1573. List returnValue = new ArrayList();
  1574. Map map = Charset.availableCharsets();
  1575. Iterator iter = map.keySet().iterator();
  1576. if ((getSelected && !jEdit.getBooleanProperty("encoding.opt-out."+UTF_8_Y,false)) ||
  1577. !getSelected)
  1578. {
  1579. returnValue.add(UTF_8_Y);
  1580. }
  1581. while(iter.hasNext())
  1582. {
  1583. String encoding = (String)iter.next();
  1584. if ((getSelected && !jEdit.getBooleanProperty("encoding.opt-out."+encoding,false)) ||
  1585. !getSelected)
  1586. {
  1587. returnValue.add(encoding);
  1588. }
  1589. }
  1590. return (String[])returnValue.toArray(
  1591. new String[returnValue.size()]);
  1592. } //}}}
  1593. //{{{ throwableToString() method
  1594. /**
  1595. * Returns a string containing the stack trace of the given throwable.
  1596. * @since jEdit 4.2pre6
  1597. */
  1598. public static String throwableToString(Throwable t)
  1599. {
  1600. StringWriter s = new StringWriter();
  1601. t.printStackTrace(new PrintWriter(s));
  1602. return s.toString();
  1603. } //}}}
  1604. //{{{ parseXML() method
  1605. /**
  1606. * Convenience method for parsing an XML file.
  1607. *
  1608. * @return Whether any error occured during parsing.
  1609. * @since jEdit 4.3pre5
  1610. * @deprecated Use {@link XMLUtilities#parseXML(InputStream,DefaultHandler)}.
  1611. */
  1612. public static boolean parseXML(InputStream in, DefaultHandler handler)
  1613. throws IOException
  1614. {
  1615. return XMLUtilities.parseXML(in, handler);
  1616. } //}}}
  1617. //{{{ resolveEntity() method
  1618. /**
  1619. * Tries to find the given systemId in the context of the given
  1620. * class.
  1621. *
  1622. * @deprecated Use {@link XMLUtilities#findEntity(String,String,Class)}.
  1623. */
  1624. public static InputSource findEntity(String systemId, String test, Class where)
  1625. {
  1626. return XMLUtilities.findEntity(systemId, test, where);
  1627. } //}}}
  1628. //{{{ Private members
  1629. private MiscUtilities() {}
  1630. //{{{ compareChars()
  1631. /** should this be public? */
  1632. private static boolean compareChars(char ch1, char ch2, boolean ignoreCase)
  1633. {
  1634. if(ignoreCase)
  1635. return Character.toUpperCase(ch1) == Character.toUpperCase(ch2);
  1636. else
  1637. return ch1 == ch2;
  1638. } //}}}
  1639. //{{{ getPathStart()
  1640. private static int getPathStart(String path)
  1641. {
  1642. int start = 0;
  1643. if(path.startsWith("/"))
  1644. return 1;
  1645. else if(OperatingSystem.isDOSDerived()
  1646. && path.length() >= 3
  1647. && path.charAt(1) == ':'
  1648. && (path.charAt(2) == '/'
  1649. || path.charAt(2) == '\\'))
  1650. return 3;
  1651. else
  1652. return 0;
  1653. } //}}}
  1654. //}}}
  1655. }