PageRenderTime 91ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

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

#
Java | 1803 lines | 974 code | 151 blank | 678 comment | 302 complexity | 0c310408a016f25d852fc0efd8f18a7c 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 8687 2007-01-20 10:07:37Z vampire0 $
  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_]+))";
  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. * And expand each of these by looking at the system environment variables for possible
  153. * expansions.
  154. * @return a string which is either the unchanged input string, or one with expanded variables.
  155. * @since 4.3pre7
  156. * @author ezust
  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. @Deprecated
  421. public static String getFileParent(String path)
  422. {
  423. return getParentOfPath(path);
  424. } //}}}
  425. //{{{ getParentOfPath() method
  426. /**
  427. * Returns the parent of the specified path. This method is VFS-aware.
  428. * @param path The path name
  429. * @since jEdit 2.6pre5
  430. */
  431. public static String getParentOfPath(String path)
  432. {
  433. return VFSManager.getVFSForPath(path).getParentOfPath(path);
  434. } //}}}
  435. //{{{ getFileProtocol() method
  436. /**
  437. * @deprecated Call getProtocolOfURL() instead
  438. */
  439. @Deprecated
  440. public static String getFileProtocol(String url)
  441. {
  442. return getProtocolOfURL(url);
  443. } //}}}
  444. //{{{ getProtocolOfURL() method
  445. /**
  446. * Returns the protocol specified by a URL.
  447. * @param url The URL
  448. * @since jEdit 2.6pre5
  449. */
  450. public static String getProtocolOfURL(String url)
  451. {
  452. return url.substring(0,url.indexOf(':'));
  453. } //}}}
  454. //{{{ isURL() method
  455. /**
  456. * Checks if the specified string is a URL.
  457. * @param str The string to check
  458. * @return True if the string is a URL, false otherwise
  459. */
  460. public static boolean isURL(String str)
  461. {
  462. int fsIndex = getLastSeparatorIndex(str);
  463. if(fsIndex == 0) // /etc/passwd
  464. return false;
  465. else if(fsIndex == 2) // C:\AUTOEXEC.BAT
  466. return false;
  467. int cIndex = str.indexOf(':');
  468. if(cIndex <= 1) // D:\WINDOWS, or doesn't contain : at all
  469. return false;
  470. String protocol = str.substring(0,cIndex);
  471. VFS vfs = VFSManager.getVFSForProtocol(protocol);
  472. if(vfs != null && !(vfs instanceof UrlVFS))
  473. return true;
  474. try
  475. {
  476. new URL(str);
  477. return true;
  478. }
  479. catch(MalformedURLException mf)
  480. {
  481. return false;
  482. }
  483. } //}}}
  484. //{{{ saveBackup() method
  485. /**
  486. * Saves a backup (optionally numbered) of a file.
  487. * @param file A local file
  488. * @param backups The number of backups. Must be >= 1. If > 1, backup
  489. * files will be numbered.
  490. * @param backupPrefix The backup file name prefix
  491. * @param backupSuffix The backup file name suffix
  492. * @param backupDirectory The directory where to save backups; if null,
  493. * they will be saved in the same directory as the file itself.
  494. * @since jEdit 4.0pre1
  495. */
  496. public static void saveBackup(File file, int backups,
  497. String backupPrefix, String backupSuffix,
  498. String backupDirectory)
  499. {
  500. saveBackup(file,backups,backupPrefix,backupSuffix,backupDirectory,0);
  501. } //}}}
  502. //{{{ saveBackup() method
  503. /**
  504. * Saves a backup (optionally numbered) of a file.
  505. * @param file A local file
  506. * @param backups The number of backups. Must be >= 1. If > 1, backup
  507. * files will be numbered.
  508. * @param backupPrefix The backup file name prefix
  509. * @param backupSuffix The backup file name suffix
  510. * @param backupDirectory The directory where to save backups; if null,
  511. * they will be saved in the same directory as the file itself.
  512. * @param backupTimeDistance The minimum time in minutes when a backup
  513. * version 1 shall be moved into version 2; if 0, backups are always
  514. * moved.
  515. * @since jEdit 4.2pre5
  516. */
  517. public static void saveBackup(File file, int backups,
  518. String backupPrefix, String backupSuffix,
  519. String backupDirectory, int backupTimeDistance)
  520. {
  521. if(backupPrefix == null)
  522. backupPrefix = "";
  523. if(backupSuffix == null)
  524. backupSuffix = "";
  525. String name = file.getName();
  526. // If backups is 1, create ~ file
  527. if(backups == 1)
  528. {
  529. File backupFile = new File(backupDirectory,
  530. backupPrefix + name + backupSuffix);
  531. long modTime = backupFile.lastModified();
  532. /* if backup file was created less than
  533. * 'backupTimeDistance' ago, we do not
  534. * create the backup */
  535. if(System.currentTimeMillis() - modTime
  536. >= backupTimeDistance)
  537. {
  538. backupFile.delete();
  539. if (!file.renameTo(backupFile))
  540. IOUtilities.moveFile(file, backupFile);
  541. }
  542. }
  543. // If backups > 1, move old ~n~ files, create ~1~ file
  544. else
  545. {
  546. /* delete a backup created using above method */
  547. new File(backupDirectory,
  548. backupPrefix + name + backupSuffix
  549. + backups + backupSuffix).delete();
  550. File firstBackup = new File(backupDirectory,
  551. backupPrefix + name + backupSuffix
  552. + "1" + backupSuffix);
  553. long modTime = firstBackup.lastModified();
  554. /* if backup file was created less than
  555. * 'backupTimeDistance' ago, we do not
  556. * create the backup */
  557. if(System.currentTimeMillis() - modTime
  558. >= backupTimeDistance)
  559. {
  560. for(int i = backups - 1; i > 0; i--)
  561. {
  562. File backup = new File(backupDirectory,
  563. backupPrefix + name
  564. + backupSuffix + i
  565. + backupSuffix);
  566. backup.renameTo(
  567. new File(backupDirectory,
  568. backupPrefix + name
  569. + backupSuffix + (i+1)
  570. + backupSuffix));
  571. }
  572. File backupFile = new File(backupDirectory,
  573. backupPrefix + name + backupSuffix
  574. + "1" + backupSuffix);
  575. if (!file.renameTo(backupFile))
  576. IOUtilities.moveFile(file, backupFile);
  577. }
  578. }
  579. } //}}}
  580. //{{{ moveFile() method
  581. /**
  582. * Moves the source file to the destination.
  583. *
  584. * If the destination cannot be created or is a read-only file, the
  585. * method returns <code>false</code>. Otherwise, the contents of the
  586. * source are copied to the destination, the source is deleted,
  587. * and <code>true</code> is returned.
  588. *
  589. * @param source The source file to move.
  590. * @param dest The destination where to move the file.
  591. * @return true on success, false otherwise.
  592. *
  593. * @since jEdit 4.3pre1
  594. * @deprecated use {@link org.gjt.sp.util.IOUtilities#moveFile(java.io.File, java.io.File)}
  595. */
  596. @Deprecated
  597. public static boolean moveFile(File source, File dest)
  598. {
  599. return IOUtilities.moveFile(source, dest);
  600. } //}}}
  601. //{{{ copyStream() method
  602. /**
  603. * Copy an input stream to an output stream.
  604. *
  605. * @param bufferSize the size of the buffer
  606. * @param progress the progress observer it could be null
  607. * @param in the input stream
  608. * @param out the output stream
  609. * @param canStop if true, the copy can be stopped by interrupting the thread
  610. * @return <code>true</code> if the copy was done, <code>false</code> if it was interrupted
  611. * @throws IOException IOException If an I/O error occurs
  612. * @since jEdit 4.3pre3
  613. * @deprecated use {@link IOUtilities#copyStream(int, org.gjt.sp.util.ProgressObserver, java.io.InputStream, java.io.OutputStream, boolean)}
  614. */
  615. @Deprecated
  616. public static boolean copyStream(int bufferSize, ProgressObserver progress,
  617. InputStream in, OutputStream out, boolean canStop)
  618. throws IOException
  619. {
  620. return IOUtilities.copyStream(bufferSize, progress, in, out, canStop);
  621. } //}}}
  622. //{{{ copyStream() method
  623. /**
  624. * Copy an input stream to an output stream with a buffer of 4096 bytes.
  625. *
  626. * @param progress the progress observer it could be null
  627. * @param in the input stream
  628. * @param out the output stream
  629. * @param canStop if true, the copy can be stopped by interrupting the thread
  630. * @return <code>true</code> if the copy was done, <code>false</code> if it was interrupted
  631. * @throws IOException IOException If an I/O error occurs
  632. * @since jEdit 4.3pre3
  633. * @deprecated use {@link IOUtilities#copyStream(org.gjt.sp.util.ProgressObserver, java.io.InputStream, java.io.OutputStream, boolean)}
  634. */
  635. @Deprecated
  636. public static boolean copyStream(ProgressObserver progress, InputStream in, OutputStream out, boolean canStop)
  637. throws IOException
  638. {
  639. return IOUtilities.copyStream(4096,progress, in, out, canStop);
  640. } //}}}
  641. //{{{ isBinaryFile() method
  642. /**
  643. * Check if a Reader is binary.
  644. * To check if a file is binary, we will check the first characters 100
  645. * (jEdit property vfs.binaryCheck.length)
  646. * If more than 1 (jEdit property vfs.binaryCheck.count), the
  647. * file is declared binary.
  648. * This is not 100% because sometimes the autodetection could fail.
  649. * This method will not close your reader. You have to do it yourself
  650. *
  651. * @param reader the reader
  652. * @return <code>true</code> if the Reader was detected as binary
  653. * @throws IOException IOException If an I/O error occurs
  654. * @since jEdit 4.3pre5
  655. */
  656. public static boolean isBinary(Reader reader)
  657. throws IOException
  658. {
  659. int nbChars = jEdit.getIntegerProperty("vfs.binaryCheck.length",100);
  660. int authorized = jEdit.getIntegerProperty("vfs.binaryCheck.count",1);
  661. for (long i = 0L;i < nbChars;i++)
  662. {
  663. int c = reader.read();
  664. if (c == -1)
  665. return false;
  666. if (c == 0)
  667. {
  668. authorized--;
  669. if (authorized == 0)
  670. return true;
  671. }
  672. }
  673. return false;
  674. } //}}}
  675. //{{{ isBackup() method
  676. /**
  677. * Check if the filename is a backup file.
  678. * @param filename the filename to check
  679. * @return true if this is a backup file.
  680. * @since jEdit 4.3pre5
  681. */
  682. public static boolean isBackup( String filename ) {
  683. if (filename.startsWith("#")) return true;
  684. if (filename.endsWith("~")) return true;
  685. if (filename.endsWith(".bak")) return true;
  686. return false;
  687. } //}}}
  688. //{{{ autodetect() method
  689. /**
  690. * Tries to detect if the stream is gzipped, and if it has an encoding
  691. * specified with an XML PI.
  692. *
  693. * @param in the input stream reader that must be autodetected
  694. * @param buffer a buffer. It can be null if you only want to autodetect the encoding of a file
  695. * @return a reader using the detected encoding
  696. * @throws IOException io exception during read
  697. * @since jEdit 4.3pre5
  698. */
  699. public static Reader autodetect(InputStream in, Buffer buffer) throws IOException
  700. {
  701. in = new BufferedInputStream(in);
  702. String encoding;
  703. if (buffer == null)
  704. encoding = System.getProperty("file.encoding");
  705. else
  706. encoding = buffer.getStringProperty(JEditBuffer.ENCODING);
  707. if(!in.markSupported())
  708. Log.log(Log.WARNING,MiscUtilities.class,"Mark not supported: " + in);
  709. else if(buffer == null || buffer.getBooleanProperty(Buffer.ENCODING_AUTODETECT))
  710. {
  711. in.mark(BufferIORequest.XML_PI_LENGTH);
  712. int b1 = in.read();
  713. int b2 = in.read();
  714. int b3 = in.read();
  715. if(b1 == BufferIORequest.GZIP_MAGIC_1 && b2 == BufferIORequest.GZIP_MAGIC_2)
  716. {
  717. in.reset();
  718. in = new GZIPInputStream(in);
  719. if (buffer != null)
  720. buffer.setBooleanProperty(Buffer.GZIPPED,true);
  721. // auto-detect encoding within the gzip stream.
  722. return autodetect(in, buffer);
  723. }
  724. else if (b1 == BufferIORequest.UNICODE_MAGIC_1
  725. && b2 == BufferIORequest.UNICODE_MAGIC_2)
  726. {
  727. in.reset();
  728. in.read();
  729. in.read();
  730. encoding = "UTF-16BE";
  731. if (buffer != null)
  732. buffer.setProperty(JEditBuffer.ENCODING,encoding);
  733. }
  734. else if (b1 == BufferIORequest.UNICODE_MAGIC_2
  735. && b2 == BufferIORequest.UNICODE_MAGIC_1)
  736. {
  737. in.reset();
  738. in.read();
  739. in.read();
  740. encoding = "UTF-16LE";
  741. if (buffer != null)
  742. buffer.setProperty(JEditBuffer.ENCODING,encoding);
  743. }
  744. else if(b1 == BufferIORequest.UTF8_MAGIC_1 && b2 == BufferIORequest.UTF8_MAGIC_2
  745. && b3 == BufferIORequest.UTF8_MAGIC_3)
  746. {
  747. // do not reset the stream and just treat it
  748. // like a normal UTF-8 file.
  749. if (buffer != null)
  750. buffer.setProperty(JEditBuffer.ENCODING, MiscUtilities.UTF_8_Y);
  751. encoding = "UTF-8";
  752. }
  753. else
  754. {
  755. in.reset();
  756. byte[] _xmlPI = new byte[BufferIORequest.XML_PI_LENGTH];
  757. int offset = 0;
  758. int count;
  759. while((count = in.read(_xmlPI,offset,
  760. BufferIORequest.XML_PI_LENGTH - offset)) != -1)
  761. {
  762. offset += count;
  763. if(offset == BufferIORequest.XML_PI_LENGTH)
  764. break;
  765. }
  766. String xmlEncoding = getXMLEncoding(new String(
  767. _xmlPI,0,offset,"ASCII"));
  768. if(xmlEncoding != null)
  769. {
  770. encoding = xmlEncoding;
  771. if (buffer != null)
  772. buffer.setProperty(JEditBuffer.ENCODING,encoding);
  773. }
  774. if(encoding.equals(MiscUtilities.UTF_8_Y))
  775. encoding = "UTF-8";
  776. in.reset();
  777. }
  778. }
  779. return new InputStreamReader(in,encoding);
  780. } //}}}
  781. //{{{ getXMLEncoding() method
  782. /**
  783. * Extract XML encoding name from PI.
  784. */
  785. private static String getXMLEncoding(String xmlPI)
  786. {
  787. if(!xmlPI.startsWith("<?xml"))
  788. return null;
  789. int index = xmlPI.indexOf("encoding=");
  790. if(index == -1 || index + 9 == xmlPI.length())
  791. return null;
  792. char ch = xmlPI.charAt(index + 9);
  793. int endIndex = xmlPI.indexOf(ch,index + 10);
  794. if(endIndex == -1)
  795. return null;
  796. String encoding = xmlPI.substring(index + 10,endIndex);
  797. if(Charset.isSupported(encoding))
  798. return encoding;
  799. else
  800. {
  801. Log.log(Log.WARNING,MiscUtilities.class,"XML PI specifies "
  802. + "unsupported encoding: " + encoding);
  803. return null;
  804. }
  805. } //}}}
  806. //{{{ closeQuietly() method
  807. /**
  808. * Method that will close an {@link InputStream} ignoring it if it is null and ignoring exceptions.
  809. *
  810. * @param in the InputStream to close.
  811. * @since jEdit 4.3pre3
  812. * @deprecated use {@link IOUtilities#closeQuietly(java.io.InputStream)}
  813. */
  814. @Deprecated
  815. public static void closeQuietly(InputStream in)
  816. {
  817. IOUtilities.closeQuietly(in);
  818. } //}}}
  819. //{{{ copyStream() method
  820. /**
  821. * Method that will close an {@link OutputStream} ignoring it if it is null and ignoring exceptions.
  822. *
  823. * @param out the OutputStream to close.
  824. * @since jEdit 4.3pre3
  825. * @deprecated use {@link IOUtilities#closeQuietly(java.io.OutputStream)}
  826. */
  827. @Deprecated
  828. public static void closeQuietly(OutputStream out)
  829. {
  830. IOUtilities.closeQuietly(out);
  831. } //}}}
  832. //{{{ fileToClass() method
  833. /**
  834. * Converts a file name to a class name. All slash characters are
  835. * replaced with periods and the trailing '.class' is removed.
  836. * @param name The file name
  837. */
  838. public static String fileToClass(String name)
  839. {
  840. char[] clsName = name.toCharArray();
  841. for(int i = clsName.length - 6; i >= 0; i--)
  842. if(clsName[i] == '/')
  843. clsName[i] = '.';
  844. return new String(clsName,0,clsName.length - 6);
  845. } //}}}
  846. //{{{ classToFile() method
  847. /**
  848. * Converts a class name to a file name. All periods are replaced
  849. * with slashes and the '.class' extension is added.
  850. * @param name The class name
  851. */
  852. public static String classToFile(String name)
  853. {
  854. return name.replace('.','/').concat(".class");
  855. } //}}}
  856. //{{{ pathsEqual() method
  857. /**
  858. * @param p1 A path name
  859. * @param p2 A path name
  860. * @return True if both paths are equal, ignoring trailing slashes, as
  861. * well as case insensitivity on Windows.
  862. * @since jEdit 4.3pre2
  863. */
  864. public static boolean pathsEqual(String p1, String p2)
  865. {
  866. VFS v1 = VFSManager.getVFSForPath(p1);
  867. VFS v2 = VFSManager.getVFSForPath(p2);
  868. if(v1 != v2)
  869. return false;
  870. if(p1.endsWith("/") || p1.endsWith(File.separator))
  871. p1 = p1.substring(0,p1.length() - 1);
  872. if(p2.endsWith("/") || p2.endsWith(File.separator))
  873. p2 = p2.substring(0,p2.length() - 1);
  874. if((v1.getCapabilities() & VFS.CASE_INSENSITIVE_CAP) != 0)
  875. return p1.equalsIgnoreCase(p2);
  876. else
  877. return p1.equals(p2);
  878. } //}}}
  879. //}}}
  880. //{{{ Text methods
  881. //{{{ getLeadingWhiteSpace() method
  882. /**
  883. * Returns the number of leading white space characters in the
  884. * specified string.
  885. * @param str The string
  886. * @deprecated use {@link StandardUtilities#getLeadingWhiteSpace(String)}
  887. */
  888. @Deprecated
  889. public static int getLeadingWhiteSpace(String str)
  890. {
  891. return StandardUtilities.getLeadingWhiteSpace(str);
  892. } //}}}
  893. //{{{ getTrailingWhiteSpace() method
  894. /**
  895. * Returns the number of trailing whitespace characters in the
  896. * specified string.
  897. * @param str The string
  898. * @since jEdit 2.5pre5
  899. * @deprecated use {@link StandardUtilities#getTrailingWhiteSpace(String)}
  900. */
  901. @Deprecated
  902. public static int getTrailingWhiteSpace(String str)
  903. {
  904. return StandardUtilities.getTrailingWhiteSpace(str);
  905. } //}}}
  906. //{{{ getLeadingWhiteSpaceWidth() method
  907. /**
  908. * Returns the width of the leading white space in the specified
  909. * string.
  910. * @param str The string
  911. * @param tabSize The tab size
  912. * @deprecated use {@link StandardUtilities#getLeadingWhiteSpace(String)}
  913. */
  914. @Deprecated
  915. public static int getLeadingWhiteSpaceWidth(String str, int tabSize)
  916. {
  917. return StandardUtilities.getLeadingWhiteSpaceWidth(str, tabSize);
  918. } //}}}
  919. //{{{ getVirtualWidth() method
  920. /**
  921. * Returns the virtual column number (taking tabs into account) of the
  922. * specified offset in the segment.
  923. *
  924. * @param seg The segment
  925. * @param tabSize The tab size
  926. * @since jEdit 4.1pre1
  927. * @deprecated use {@link StandardUtilities#getVirtualWidth(javax.swing.text.Segment, int)}
  928. */
  929. @Deprecated
  930. public static int getVirtualWidth(Segment seg, int tabSize)
  931. {
  932. return StandardUtilities.getVirtualWidth(seg, tabSize);
  933. } //}}}
  934. //{{{ getOffsetOfVirtualColumn() method
  935. /**
  936. * Returns the array offset of a virtual column number (taking tabs
  937. * into account) in the segment.
  938. *
  939. * @param seg The segment
  940. * @param tabSize The tab size
  941. * @param column The virtual column number
  942. * @param totalVirtualWidth If this array is non-null, the total
  943. * virtual width will be stored in its first location if this method
  944. * returns -1.
  945. *
  946. * @return -1 if the column is out of bounds
  947. *
  948. * @since jEdit 4.1pre1
  949. * @deprecated use {@link StandardUtilities#getVirtualWidth(javax.swing.text.Segment, int)}
  950. */
  951. @Deprecated
  952. public static int getOffsetOfVirtualColumn(Segment seg, int tabSize,
  953. int column, int[] totalVirtualWidth)
  954. {
  955. return StandardUtilities.getOffsetOfVirtualColumn(seg, tabSize, column, totalVirtualWidth);
  956. } //}}}
  957. //{{{ createWhiteSpace() method
  958. /**
  959. * Creates a string of white space with the specified length.<p>
  960. *
  961. * To get a whitespace string tuned to the current buffer's
  962. * settings, call this method as follows:
  963. *
  964. * <pre>myWhitespace = MiscUtilities.createWhiteSpace(myLength,
  965. * (buffer.getBooleanProperty("noTabs") ? 0
  966. * : buffer.getTabSize()));</pre>
  967. *
  968. * @param len The length
  969. * @param tabSize The tab size, or 0 if tabs are not to be used
  970. * @deprecated use {@link StandardUtilities#createWhiteSpace(int, int)}
  971. */
  972. @Deprecated
  973. public static String createWhiteSpace(int len, int tabSize)
  974. {
  975. return StandardUtilities.createWhiteSpace(len,tabSize,0);
  976. } //}}}
  977. //{{{ createWhiteSpace() method
  978. /**
  979. * Creates a string of white space with the specified length.<p>
  980. *
  981. * To get a whitespace string tuned to the current buffer's
  982. * settings, call this method as follows:
  983. *
  984. * <pre>myWhitespace = MiscUtilities.createWhiteSpace(myLength,
  985. * (buffer.getBooleanProperty("noTabs") ? 0
  986. * : buffer.getTabSize()));</pre>
  987. *
  988. * @param len The length
  989. * @param tabSize The tab size, or 0 if tabs are not to be used
  990. * @param start The start offset, for tab alignment
  991. * @since jEdit 4.2pre1
  992. * @deprecated use {@link StandardUtilities#createWhiteSpace(int, int, int)}
  993. */
  994. @Deprecated
  995. public static String createWhiteSpace(int len, int tabSize, int start)
  996. {
  997. return StandardUtilities.createWhiteSpace(len, tabSize, start);
  998. } //}}}
  999. //{{{ globToRE() method
  1000. /**
  1001. * Converts a Unix-style glob to a regular expression.<p>
  1002. *
  1003. * ? becomes ., * becomes .*, {aa,bb} becomes (aa|bb).
  1004. * @param glob The glob pattern
  1005. * @deprecated Use {@link StandardUtilities#globToRE(String)}.
  1006. */
  1007. @Deprecated
  1008. public static String globToRE(String glob)
  1009. {
  1010. return StandardUtilities.globToRE(glob);
  1011. } //}}}
  1012. //{{{ escapesToChars() method
  1013. /**
  1014. * Converts "\n" and "\t" escapes in the specified string to
  1015. * newlines and tabs.
  1016. * @param str The string
  1017. * @since jEdit 2.3pre1
  1018. */
  1019. public static String escapesToChars(String str)
  1020. {
  1021. StringBuffer buf = new StringBuffer();
  1022. for(int i = 0; i < str.length(); i++)
  1023. {
  1024. char c = str.charAt(i);
  1025. switch(c)
  1026. {
  1027. case '\\':
  1028. if(i == str.length() - 1)
  1029. {
  1030. buf.append('\\');
  1031. break;
  1032. }
  1033. c = str.charAt(++i);
  1034. switch(c)
  1035. {
  1036. case 'n':
  1037. buf.append('\n');
  1038. break;
  1039. case 't':
  1040. buf.append('\t');
  1041. break;
  1042. default:
  1043. buf.append(c);
  1044. break;
  1045. }
  1046. break;
  1047. default:
  1048. buf.append(c);
  1049. }
  1050. }
  1051. return buf.toString();
  1052. } //}}}
  1053. //{{{ charsToEscapes() method
  1054. /**
  1055. * Escapes newlines, tabs, backslashes, and quotes in the specified
  1056. * string.
  1057. * @param str The string
  1058. * @since jEdit 2.3pre1
  1059. */
  1060. public static String charsToEscapes(String str)
  1061. {
  1062. return charsToEscapes(str,"\n\t\\\"'");
  1063. } //}}}
  1064. //{{{ charsToEscapes() method
  1065. /**
  1066. * Escapes the specified characters in the specified string.
  1067. * @param str The string
  1068. * @param toEscape Any characters that require escaping
  1069. * @since jEdit 4.1pre3
  1070. */
  1071. public static String charsToEscapes(String str, String toEscape)
  1072. {
  1073. StringBuffer buf = new StringBuffer();
  1074. for(int i = 0; i < str.length(); i++)
  1075. {
  1076. char c = str.charAt(i);
  1077. if(toEscape.indexOf(c) != -1)
  1078. {
  1079. if(c == '\n')
  1080. buf.append("\\n");
  1081. else if(c == '\t')
  1082. buf.append("\\t");
  1083. else
  1084. {
  1085. buf.append('\\');
  1086. buf.append(c);
  1087. }
  1088. }
  1089. else
  1090. buf.append(c);
  1091. }
  1092. return buf.toString();
  1093. } //}}}
  1094. //{{{ compareVersions() method
  1095. /**
  1096. * @deprecated Call <code>compareStrings()</code> instead
  1097. */
  1098. @Deprecated
  1099. public static int compareVersions(String v1, String v2)
  1100. {
  1101. return StandardUtilities.compareStrings(v1,v2,false);
  1102. } //}}}
  1103. //{{{ compareStrings() method
  1104. /**
  1105. * Compares two strings.<p>
  1106. *
  1107. * Unlike <function>String.compareTo()</function>,
  1108. * this method correctly recognizes and handles embedded numbers.
  1109. * For example, it places "My file 2" before "My file 10".<p>
  1110. *
  1111. * @param str1 The first string
  1112. * @param str2 The second string
  1113. * @param ignoreCase If true, case will be ignored
  1114. * @return negative If str1 &lt; str2, 0 if both are the same,
  1115. * positive if str1 &gt; str2
  1116. * @since jEdit 4.0pre1
  1117. * @deprecated use {@link StandardUtilities#compareStrings(String, String, boolean)}
  1118. */
  1119. @Deprecated
  1120. public static int compareStrings(String str1, String str2, boolean ignoreCase)
  1121. {
  1122. return StandardUtilities.compareStrings(str1, str2, ignoreCase);
  1123. } //}}}
  1124. //{{{ stringsEqual() method
  1125. /**
  1126. * @deprecated Call <code>objectsEqual()</code> instead.
  1127. */
  1128. @Deprecated
  1129. public static boolean stringsEqual(String s1, String s2)
  1130. {
  1131. return StandardUtilities.objectsEqual(s1,s2);
  1132. } //}}}
  1133. //{{{ objectsEqual() method
  1134. /**
  1135. * Returns if two strings are equal. This correctly handles null pointers,
  1136. * as opposed to calling <code>o1.equals(o2)</code>.
  1137. * @since jEdit 4.2pre1
  1138. * @deprecated use {@link StandardUtilities#objectsEqual(Object, Object)}
  1139. */
  1140. @Deprecated
  1141. public static boolean objectsEqual(Object o1, Object o2)
  1142. {
  1143. return StandardUtilities.objectsEqual(o1, o2);
  1144. } //}}}
  1145. //{{{ charsToEntities() method
  1146. /**
  1147. * Converts &lt;, &gt;, &amp; in the string to their HTML entity
  1148. * equivalents.
  1149. * @param str The string
  1150. * @since jEdit 4.2pre1
  1151. * @deprecated Use {@link org.gjt.sp.util.XMLUtilities#charsToEntities(String, boolean)}.
  1152. */
  1153. @Deprecated
  1154. public static String charsToEntities(String str)
  1155. {
  1156. return XMLUtilities.charsToEntities(str,false);
  1157. } //}}}
  1158. //{{{ formatFileSize() method
  1159. public static final DecimalFormat KB_FORMAT = new DecimalFormat("#.# KB");
  1160. public static final DecimalFormat MB_FORMAT = new DecimalFormat("#.# MB");
  1161. /**
  1162. * Formats the given file size into a nice string (123 bytes, 10.6 KB,
  1163. * 1.2 MB).
  1164. * @param length The size
  1165. * @since jEdit 4.2pre1
  1166. */
  1167. public static String formatFileSize(long length)
  1168. {
  1169. if(length < 1024)
  1170. return length + " bytes";
  1171. else if(length < 1024 << 10)
  1172. return KB_FORMAT.format((double)length / 1024);
  1173. else
  1174. return MB_FORMAT.format((double)length / 1024 / 1024);
  1175. } //}}}
  1176. //{{{ getLongestPrefix() method
  1177. /**
  1178. * Returns the longest common prefix in the given set of strings.
  1179. * @param str The strings
  1180. * @param ignoreCase If true, case insensitive
  1181. * @since jEdit 4.2pre2
  1182. */
  1183. public static String getLongestPrefix(List str, boolean ignoreCase)
  1184. {
  1185. if(str.size() == 0)
  1186. return "";
  1187. int prefixLength = 0;
  1188. loop: for(;;)
  1189. {
  1190. String s = str.get(0).toString();
  1191. if(prefixLength >= s.length())
  1192. break loop;
  1193. char ch = s.charAt(prefixLength);
  1194. for(int i = 1; i < str.size(); i++)
  1195. {
  1196. s = str.get(i).toString();
  1197. if(prefixLength >= s.length())
  1198. break loop;
  1199. if(!compareChars(s.charAt(prefixLength),ch,ignoreCase))
  1200. break loop;
  1201. }
  1202. prefixLength++;
  1203. }
  1204. return str.get(0).toString().substring(0,prefixLength);
  1205. } //}}}
  1206. //{{{ getLongestPrefix() method
  1207. /**
  1208. * Returns the longest common prefix in the given set of strings.
  1209. * @param str The strings
  1210. * @param ignoreCase If true, case insensitive
  1211. * @since jEdit 4.2pre2
  1212. */
  1213. public static String getLongestPrefix(String[] str, boolean ignoreCase)
  1214. {
  1215. return getLongestPrefix((Object[])str,ignoreCase);
  1216. } //}}}
  1217. //{{{ getLongestPrefix() method
  1218. /**
  1219. * Returns the longest common prefix in the given set of strings.
  1220. * @param str The strings (calls <code>toString()</code> on each object)
  1221. * @param ignoreCase If true, case insensitive
  1222. * @since jEdit 4.2pre6
  1223. */
  1224. public static String getLongestPrefix(Object[] str, boolean ignoreCase)
  1225. {
  1226. if(str.length == 0)
  1227. return "";
  1228. int prefixLength = 0;
  1229. String first = str[0].toString();
  1230. loop: for(;;)
  1231. {
  1232. if(prefixLength >= first.length())
  1233. break loop;
  1234. char ch = first.charAt(prefixLength);
  1235. for(int i = 1; i < str.length; i++)
  1236. {
  1237. String s = str[i].toString();
  1238. if(prefixLength >= s.length())
  1239. break loop;
  1240. if(!compareChars(s.charAt(prefixLength),ch,ignoreCase))
  1241. break loop;
  1242. }
  1243. prefixLength++;
  1244. }
  1245. return first.substring(0,prefixLength);
  1246. } //}}}
  1247. //}}}
  1248. //{{{ Sorting methods
  1249. //{{{ quicksort() method
  1250. /**
  1251. * Sorts the specified array. Equivalent to calling
  1252. * <code>Arrays.sort()</code>.
  1253. * @param obj The array
  1254. * @param compare Compares the objects
  1255. * @since jEdit 4.0pre4
  1256. * @deprecated use <code>Arrays.sort()</code>
  1257. */
  1258. @Deprecated
  1259. public static void quicksort(Object[] obj, Comparator compare)
  1260. {
  1261. Arrays.sort(obj,compare);
  1262. } //}}}
  1263. //{{{ quicksort() method
  1264. /**
  1265. * Sorts the specified vector.
  1266. * @param vector The vector
  1267. * @param compare Compares the objects
  1268. * @since jEdit 4.0pre4
  1269. * @deprecated <code>Collections.sort()</code>
  1270. */
  1271. @Deprecated
  1272. public static void quicksort(Vector vector, Comparator compare)
  1273. {
  1274. Collections.sort(vector,compare);
  1275. } //}}}
  1276. //{{{ quicksort() method
  1277. /**
  1278. * Sorts the specified list.
  1279. * @param list The list
  1280. * @param compare Compares the objects
  1281. * @since jEdit 4.0pre4
  1282. * @deprecated <code>Collections.sort()</code>
  1283. */
  1284. @Deprecated
  1285. public static void quicksort(List list, Comparator compare)
  1286. {
  1287. Collections.sort(list,compare);
  1288. } //}}}
  1289. //{{{ quicksort() method
  1290. /**
  1291. * Sorts the specified array. Equivalent to calling
  1292. * <code>Arrays.sort()</code>.
  1293. * @param obj The array
  1294. * @param compare Compares the objects
  1295. * @deprecated use <code>Arrays.sort()</code>
  1296. */
  1297. @Deprecated
  1298. public static void quicksort(Object[] obj, Compare compare)
  1299. {
  1300. Arrays.sort(obj,compare);
  1301. } //}}}
  1302. //{{{ quicksort() method
  1303. /**
  1304. * Sorts the specified vector.
  1305. * @param vector The vector
  1306. * @param compare Compares the objects
  1307. * @deprecated <code>Collections.sort()</code>
  1308. */
  1309. @Deprecated
  1310. public static void quicksort(Vector vector, Compare compare)
  1311. {
  1312. Collections.sort(vector,compare);
  1313. } //}}}
  1314. //{{{ Compare interface
  1315. /**
  1316. * An interface for comparing objects. This is a hold-over from
  1317. * they days when jEdit had its own sorting API due to JDK 1.1
  1318. * compatibility requirements. Use <code>java.util.Comparable</code>
  1319. * instead.
  1320. * @deprecated
  1321. */
  1322. @Deprecated
  1323. public interface Compare extends Comparator
  1324. {
  1325. int compare(Object obj1, Object obj2);
  1326. } //}}}
  1327. //{{{ StringCompare class
  1328. /**
  1329. * Compares strings.
  1330. * @deprecated use {@link StandardUtilities.StringCompare}
  1331. */
  1332. @Deprecated
  1333. public static class StringCompare implements Compare
  1334. {
  1335. public int compare(Object obj1, Object obj2)
  1336. {
  1337. return StandardUtilities.compareStrings(obj1.toString(),
  1338. obj2.toString(),false);
  1339. }
  1340. } //}}}
  1341. //{{{ StringICaseCompare class
  1342. /**
  1343. * Compares strings ignoring case.
  1344. */
  1345. public static class StringICaseCompare implements Comparator<Object>
  1346. {
  1347. public int compare(Object obj1, Object obj2)
  1348. {
  1349. return StandardUtilities.compareStrings(obj1.toString(), obj2.toString(), true);
  1350. }
  1351. } //}}}
  1352. //{{{ MenuItemCompare class
  1353. /**
  1354. * Compares menu item labels.
  1355. */
  1356. public static class MenuItemCompare implements Compare
  1357. {
  1358. public int compare(Object obj1, Object obj2)
  1359. {
  1360. boolean obj1E, obj2E;
  1361. obj1E = obj1 instanceof EnhancedMenuItem;
  1362. obj2E = obj2 instanceof EnhancedMenuItem;
  1363. if(obj1E && !obj2E)
  1364. return 1;
  1365. else if(obj2E && !obj1E)
  1366. return -1;
  1367. else
  1368. return StandardUtilities.compareStrings(((JMenuItem)obj1).getText(),
  1369. ((JMenuItem)obj2).getText(),true);
  1370. }
  1371. } //}}}
  1372. //}}}
  1373. //{{{ buildToVersion() method
  1374. /**
  1375. * Converts an internal version number (build) into a
  1376. * `human-readable' form.
  1377. * @param build The build
  1378. */
  1379. public static String buildToVersion(String build)
  1380. {
  1381. if(build.length() != 11)
  1382. return "<unknown version: " + build + ">";
  1383. // First 2 chars are the major version number
  1384. int major = Integer.parseInt(build.substring(0,2));
  1385. // Second 2 are the minor number
  1386. int minor = Integer.parseInt(build.substring(3,5));
  1387. // Then the pre-release status
  1388. int beta = Integer.parseInt(build.substring(6,8));
  1389. // Finally the bug fix release
  1390. int bugfix = Integer.parseInt(build.substring(9,11));
  1391. return major + "." + minor
  1392. + (beta != 99 ? "pre" + beta :
  1393. (bugfix != 0 ? "." + bugfix : "final"));
  1394. } //}}}
  1395. //{{{ isToolsJarAvailable() method
  1396. /**
  1397. * If on JDK 1.2 or higher, make sure that tools.jar is available.
  1398. * This method should be called by plugins requiring the classes
  1399. * in this library.
  1400. * <p>
  1401. * tools.jar is searched for in the following places:
  1402. * <ol>
  1403. * <li>the classpath that was used when jEdit was started,
  1404. * <li>jEdit's jars folder in the user's home,
  1405. * <li>jEdit's system jars folder,
  1406. * <li><i>java.home</i>/lib/. In this case, tools.jar is added to
  1407. * jEdit's list of known jars using jEdit.addPluginJAR(),
  1408. * so that it gets loaded through JARClassLoader.
  1409. * </ol><p>
  1410. *
  1411. * On older JDK's this method does not perform any checks, and returns
  1412. * <code>true</code> (even though there is no tools.jar).
  1413. *
  1414. * @return <code>false</code> if and only if on JDK 1.2 and tools.jar
  1415. * could not be found. In this case it prints some warnings on Log,
  1416. * too, about the places where it was searched for.
  1417. * @since jEdit 3.2.2
  1418. */
  1419. public static boolean isToolsJarAvailable()
  1420. {
  1421. Log.log(Log.DEBUG, MiscUtilities.class,"Searching for tools.jar...");
  1422. Vector paths = new Vector();
  1423. //{{{ 1. Check whether tools.jar is in the system classpath:
  1424. paths.addElement("System classpath: "
  1425. + System.getProperty("java.class.path"));
  1426. try
  1427. {
  1428. // Either class sun.tools.javac.Main or
  1429. // com.sun.tools.javac.Main must be there:
  1430. try
  1431. {
  1432. Class.forName("sun.tools.javac.Main");
  1433. }
  1434. catch(ClassNotFoundException e1)
  1435. {
  1436. Class.forName("com.sun.tools.javac.Main");
  1437. }
  1438. Log.log(Log.DEBUG, MiscUtilities.class,
  1439. "- is in classpath. Fine.");
  1440. return true;
  1441. }
  1442. catch(ClassNotFoundException e)
  1443. {
  1444. //Log.log(Log.DEBUG, MiscUtilities.class,
  1445. // "- is not in system classpath.");
  1446. } //}}}
  1447. //{{{ 2. Check whether it is in the jEdit user settings jars folder:
  1448. String settingsDir = jEdit.getSettingsDirectory();
  1449. if(settingsDir != null)
  1450. {
  1451. String toolsPath = constructPath(settingsDir, "jars",
  1452. "tools.jar");
  1453. paths.addElement(toolsPath);
  1454. if(new File(toolsPath).exists())
  1455. {
  1456. Log.log(Log.DEBUG, MiscUtilities.class,
  1457. "- is in the user's jars folder. Fine.");
  1458. // jEdit will load it automatically
  1459. return true;
  1460. }
  1461. } //}}}
  1462. //{{{ 3. Check whether it is in jEdit's system jars folder:
  1463. String jEditDir = jEdit.getJEditHome();
  1464. if(jEditDir != null)
  1465. {
  1466. String toolsPath = constructPath(jEditDir, "jars", "tools.jar");
  1467. paths.addElement(toolsPath);
  1468. if(new File(toolsPath).exists())
  1469. {
  1470. Log.log(Log.DEBUG, MiscUtilities.class,
  1471. "- is in jEdit's system jars folder. Fine.");
  1472. // jEdit will load it automatically
  1473. return true;
  1474. }
  1475. } //}}}
  1476. //{{{ 4. Check whether it is in <java.home>/lib:
  1477. String toolsPath = System.getProperty("java.home");
  1478. if(toolsPath.toLowerCase().endsWith(File.separator + "jre"))
  1479. toolsPath = toolsPath.substring(0, toolsPath.length() - 4);
  1480. toolsPath = constructPath(toolsPath, "lib", "tools.jar");
  1481. paths.addElement(toolsPath);
  1482. if(!(new File(toolsPath).exists()))
  1483. {
  1484. Log.log(Log.WARNING, MiscUtilities.class,
  1485. "Could not find tools.jar.\n"
  1486. + "I checked the following locations:\n"
  1487. + paths.toString());
  1488. return false;
  1489. } //}}}
  1490. //{{{ Load it, if not yet done:
  1491. PluginJAR jar = jEdit.getPluginJAR(toolsPath);
  1492. if(jar == null)
  1493. {
  1494. Log.log(Log.DEBUG, MiscUtilities.class,
  1495. "- adding " + toolsPath + " to jEdit plugins.");
  1496. jEdit.addPluginJAR(toolsPath);
  1497. }
  1498. else
  1499. Log.log(Log.DEBUG, MiscUtilities.class,
  1500. "- has been loaded before.");
  1501. //}}}
  1502. return true;
  1503. } //}}}
  1504. //{{{ parsePermissions() method
  1505. /**
  1506. * Parse a Unix-style permission string (rwxrwxrwx).
  1507. * @param s The string (must be 9 characters long).
  1508. * @since jEdit 4.1pre8
  1509. */
  1510. public static int parsePermissions(String s)
  1511. {
  1512. int permissions = 0;
  1513. if(s.length() == 9)
  1514. {
  1515. if(s.charAt(0) == 'r')
  1516. permissions += 0400;
  1517. if(s.charAt(1) == 'w')
  1518. permissions += 0200;
  1519. if(s.charAt(2) == 'x')
  1520. permissions += 0100;
  1521. else if(s.charAt(2) == 's')
  1522. permissions += 04100;
  1523. else if(s.charAt(2) == 'S')
  1524. permissions += 04000;
  1525. if(s.charAt(3) == 'r')
  1526. permissions += 040;
  1527. if(s.charAt(4) == 'w')
  1528. permissions += 020;
  1529. if(s.charAt(5) == 'x')
  1530. permissions += 010;
  1531. else if(s.charAt(5) == 's')
  1532. permissions += 02010;
  1533. else if(s.charAt(5) == 'S')
  1534. permissions += 02000;
  1535. if(s.charAt(6) == 'r')
  1536. permissions += 04;
  1537. if(s.charAt(7) == 'w')
  1538. permissions += 02;
  1539. if(s.charAt(8) == 'x')
  1540. permissions += 01;
  1541. else if(s.charAt(8) == 't')
  1542. permissions += 01001;
  1543. else if(s.charAt(8) == 'T')
  1544. permissions += 01000;
  1545. }
  1546. return permissions;
  1547. } //}}}
  1548. //{{{ getEncodings() method
  1549. /**
  1550. * Returns a list of supported character encodings.
  1551. * @since jEdit 4.2pre5
  1552. * @deprecated See #getEncodings( boolean )
  1553. */
  1554. @Deprecated
  1555. public static String[] getEncodings()
  1556. {
  1557. return getEncodings(false);
  1558. } //}}}
  1559. //{{{ getEncodings() method
  1560. /**
  1561. * Returns a list of supported character encodings.
  1562. * @since jEdit 4.3pre5
  1563. * @param getSelected Whether to return just the selected encodings or all.
  1564. */
  1565. public static String[] getEncodings(boolean getSelected)
  1566. {
  1567. List returnValue = new ArrayList();
  1568. Map map = Charset.availableCharsets();
  1569. Iterator iter = map.keySet().iterator();
  1570. if ((getSelected && !jEdit.getBooleanProperty("encoding.opt-out."+UTF_8_Y,false)) ||
  1571. !getSelected)
  1572. {
  1573. returnValue.add(UTF_8_Y);
  1574. }
  1575. while(iter.hasNext())
  1576. {
  1577. String encoding = (String)iter.next();
  1578. if ((getSelected && !jEdit.getBooleanProperty("encoding.opt-out."+encoding,false)) ||
  1579. !getSelected)
  1580. {
  1581. returnValue.add(encoding);
  1582. }
  1583. }
  1584. return (String[])returnValue.toArray(
  1585. new String[returnValue.size()]);
  1586. } //}}}
  1587. //{{{ throwableToString() method
  1588. /**
  1589. * Returns a string containing the stack trace of the given throwable.
  1590. * @since jEdit 4.2pre6
  1591. */
  1592. public static String throwableToString(Throwable t)
  1593. {
  1594. StringWriter s = new StringWriter();
  1595. t.printStackTrace(new PrintWriter(s));
  1596. return s.toString();
  1597. } //}}}
  1598. //{{{ parseXML() method
  1599. /**
  1600. * Convenience method for parsing an XML file.
  1601. *
  1602. * @return Whether any error occured during parsing.
  1603. * @since jEdit 4.3pre5
  1604. * @deprecated Use {@link XMLUtilities#parseXML(InputStream,DefaultHandler)}.
  1605. */
  1606. @Deprecated
  1607. public static boolean parseXML(InputStream in, DefaultHandler handler)
  1608. throws IOException
  1609. {
  1610. return XMLUtilities.parseXML(in, handler);
  1611. } //}}}
  1612. //{{{ resolveEntity() method
  1613. /**
  1614. * Tries to find the given systemId in the context of the given
  1615. * class.
  1616. *
  1617. * @deprecated Use {@link XMLUtilities#findEntity(String,String,Class)}.
  1618. */
  1619. @Deprecated
  1620. public static InputSource findEntity(String systemId, String test, Class where)
  1621. {
  1622. return XMLUtilities.findEntity(systemId, test, where);
  1623. } //}}}
  1624. //{{{ Private members
  1625. private MiscUtilities() {}
  1626. //{{{ compareChars()
  1627. /** should this be public? */
  1628. private static boolean compareChars(char ch1, char ch2, boolean ignoreCase)
  1629. {
  1630. if(ignoreCase)
  1631. return Character.toUpperCase(ch1) == Character.toUpperCase(ch2);
  1632. else
  1633. return ch1 == ch2;
  1634. } //}}}
  1635. //{{{ getPathStart()
  1636. private static int getPathStart(String path)
  1637. {
  1638. int start = 0;
  1639. if(path.startsWith("/"))
  1640. return 1;
  1641. else if(OperatingSystem.isDOSDerived()
  1642. && path.length() >= 3
  1643. && path.charAt(1) == ':'
  1644. && (path.charAt(2) == '/'
  1645. || path.charAt(2) == '\\'))
  1646. return 3;
  1647. else
  1648. return 0;
  1649. } //}}}
  1650. //}}}
  1651. }