ConfigUserInterface.java 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783
  1. /*
  2. * This program is free software: you can redistribute it and/or modify it under
  3. * the terms of the GNU General Public License as published by the Free Software
  4. * Foundation, either version 3 of the License, or (at your option) any later
  5. * version.
  6. *
  7. * This program is distributed in the hope that it will be useful, but WITHOUT
  8. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  9. * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
  10. * details.
  11. *
  12. * You should have received a copy of the GNU General Public License along with
  13. * this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. package com.l2jserver.configurator;
  16. import java.awt.GridBagConstraints;
  17. import java.awt.GridBagLayout;
  18. import java.awt.Insets;
  19. import java.awt.Rectangle;
  20. import java.awt.event.ActionEvent;
  21. import java.awt.event.ActionListener;
  22. import java.io.BufferedWriter;
  23. import java.io.File;
  24. import java.io.FileInputStream;
  25. import java.io.FileOutputStream;
  26. import java.io.IOException;
  27. import java.io.InputStreamReader;
  28. import java.io.LineNumberReader;
  29. import java.io.OutputStreamWriter;
  30. import java.io.Writer;
  31. import java.net.Inet4Address;
  32. import java.net.InetAddress;
  33. import java.net.UnknownHostException;
  34. import java.util.List;
  35. import java.util.Locale;
  36. import java.util.NoSuchElementException;
  37. import java.util.ResourceBundle;
  38. import java.util.regex.Matcher;
  39. import java.util.regex.Pattern;
  40. import javax.swing.JButton;
  41. import javax.swing.JCheckBox;
  42. import javax.swing.JComponent;
  43. import javax.swing.JFrame;
  44. import javax.swing.JLabel;
  45. import javax.swing.JMenu;
  46. import javax.swing.JMenuBar;
  47. import javax.swing.JMenuItem;
  48. import javax.swing.JOptionPane;
  49. import javax.swing.JPanel;
  50. import javax.swing.JScrollPane;
  51. import javax.swing.JTabbedPane;
  52. import javax.swing.JTextArea;
  53. import javax.swing.JToolBar;
  54. import javax.swing.SwingUtilities;
  55. import javax.swing.ToolTipManager;
  56. import javax.swing.UIManager;
  57. import com.l2jserver.configurator.ConfigUserInterface.ConfigFile.ConfigComment;
  58. import com.l2jserver.configurator.ConfigUserInterface.ConfigFile.ConfigProperty;
  59. import com.l2jserver.i18n.LanguageControl;
  60. import com.l2jserver.images.ImagesTable;
  61. import javolution.util.FastList;
  62. /**
  63. *
  64. * @author KenM
  65. */
  66. public class ConfigUserInterface extends JFrame implements ActionListener
  67. {
  68. /**
  69. * Comment for <code>serialVersionUID</code>
  70. */
  71. private static final long serialVersionUID = 1L;
  72. private JTabbedPane _tabPane = new JTabbedPane();
  73. private List<ConfigFile> _configs = new FastList<ConfigFile>();
  74. private ResourceBundle _bundle;
  75. /**
  76. * @param args
  77. */
  78. public static void main(String[] args)
  79. {
  80. Locale locale = null;
  81. try
  82. {
  83. UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
  84. }
  85. catch (Exception e)
  86. {
  87. // couldn't care less
  88. }
  89. if (locale == null)
  90. {
  91. locale = Locale.getDefault();
  92. }
  93. final ResourceBundle bundle = ResourceBundle.getBundle("configurator.Configurator", locale, LanguageControl.INSTANCE);
  94. SwingUtilities.invokeLater
  95. (
  96. new Runnable()
  97. {
  98. @Override
  99. public void run()
  100. {
  101. ConfigUserInterface cui = new ConfigUserInterface(bundle);
  102. cui.setVisible(true);
  103. }
  104. }
  105. );
  106. }
  107. public ConfigUserInterface(ResourceBundle bundle)
  108. {
  109. setBundle(bundle);
  110. this.setTitle(bundle.getString("toolName"));
  111. this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  112. this.setSize(750, 500);
  113. this.setLayout(new GridBagLayout());
  114. GridBagConstraints cons = new GridBagConstraints();
  115. cons.fill = GridBagConstraints.HORIZONTAL;
  116. cons.gridx = 0;
  117. cons.gridy = 0;
  118. cons.weighty = 0;
  119. cons.weightx = 1;
  120. JMenuBar menubar = new JMenuBar();
  121. JMenu fileMenu = new JMenu(bundle.getString("fileMenu"));
  122. JMenu helpMenu = new JMenu(bundle.getString("helpMenu"));
  123. JMenuItem exitItem = new JMenuItem(bundle.getString("exitItem"));
  124. exitItem.setActionCommand("exit");
  125. exitItem.addActionListener(this);
  126. fileMenu.add(exitItem);
  127. JMenuItem aboutItem = new JMenuItem(bundle.getString("aboutItem"));
  128. aboutItem.setActionCommand("about");
  129. aboutItem.addActionListener(this);
  130. helpMenu.add(aboutItem);
  131. menubar.add(fileMenu);
  132. menubar.add(helpMenu);
  133. this.setJMenuBar(menubar);
  134. JToolBar toolBar = new JToolBar();
  135. toolBar.setFloatable(false);
  136. toolBar.setRollover(true);
  137. toolBar.add(this.createToolButton("disk.png", bundle.getString("save"), "save"));
  138. this.add(toolBar, cons);
  139. cons.gridy++;
  140. cons.fill = GridBagConstraints.BOTH;
  141. cons.weighty = 1;
  142. this.loadConfigs();
  143. this.buildInterface();
  144. this.add(_tabPane, cons);
  145. }
  146. private JButton createToolButton(String image, String text, String action)
  147. {
  148. JButton button = new JButton(text, ImagesTable.getImage(image));
  149. button.setActionCommand(action);
  150. button.addActionListener(this);
  151. return button;
  152. }
  153. /**
  154. *
  155. */
  156. @SuppressWarnings("serial")
  157. private void buildInterface()
  158. {
  159. ToolTipManager.sharedInstance().setDismissDelay(Integer.MAX_VALUE);
  160. ToolTipManager.sharedInstance().setInitialDelay(0);
  161. ToolTipManager.sharedInstance().setReshowDelay(0);
  162. GridBagConstraints cons = new GridBagConstraints();
  163. cons.fill = GridBagConstraints.NONE;
  164. cons.anchor = GridBagConstraints.FIRST_LINE_START;
  165. cons.insets = new Insets(2, 2, 2, 2);
  166. for (ConfigFile cf : getConfigs())
  167. {
  168. JPanel panel = new JPanel() {
  169. public void scrollRectToVisible(Rectangle r ) {}
  170. };
  171. panel.setLayout(new GridBagLayout());
  172. cons.gridy = 0;
  173. cons.weighty = 0;
  174. for (ConfigComment cc : cf.getConfigProperties())
  175. {
  176. if (!(cc instanceof ConfigProperty))
  177. {
  178. continue;
  179. }
  180. ConfigProperty cp = (ConfigProperty) cc;
  181. cons.gridx = 0;
  182. JLabel keyLabel = new JLabel(cp.getDisplayName()+':', ImagesTable.getImage("help.png"), JLabel.LEFT);
  183. String comments = "<b>"+cp.getName()+":</b><br>"+cp.getComments();
  184. comments = comments.replace("\r\n", "<br>");
  185. comments = "<html>"+comments+"</html>";
  186. keyLabel.setToolTipText(comments);
  187. cons.weightx = 0;
  188. panel.add(keyLabel, cons);
  189. cons.gridx++;
  190. JComponent valueComponent = cp.getValueComponent();
  191. valueComponent.setToolTipText(comments);
  192. cons.weightx = 1;
  193. panel.add(valueComponent, cons);
  194. cons.gridx++;
  195. cons.gridy++;
  196. }
  197. cons.gridy++;
  198. cons.weighty = 1;
  199. panel.add(new JLabel(), cons); // filler
  200. _tabPane.addTab(cf.getName(), new JScrollPane(panel));
  201. }
  202. }
  203. /**
  204. *
  205. */
  206. private void loadConfigs()
  207. {
  208. File configsDir = new File("config");
  209. for (File file : configsDir.listFiles())
  210. {
  211. if (file.getName().endsWith(".properties") && file.isFile() && file.canWrite())
  212. {
  213. try
  214. {
  215. this.parsePropertiesFile(file);
  216. }
  217. catch (IOException e)
  218. {
  219. JOptionPane.showMessageDialog(ConfigUserInterface.this,getBundle().getString("errorReading")+file.getName(),getBundle().getString("error"),JOptionPane.ERROR_MESSAGE);
  220. System.exit(3);
  221. // e.printStackTrace();
  222. }
  223. }
  224. }
  225. }
  226. /**
  227. * @param file
  228. * @throws IOException
  229. */
  230. private void parsePropertiesFile(File file) throws IOException
  231. {
  232. LineNumberReader lnr = new LineNumberReader(new InputStreamReader(new FileInputStream(file)));
  233. String line;
  234. StringBuilder commentBuffer = new StringBuilder();
  235. ConfigFile cf = new ConfigFile(file);
  236. while ((line = lnr.readLine()) != null)
  237. {
  238. line = line.trim();
  239. if (line.startsWith("#"))
  240. {
  241. if (commentBuffer.length() > 0)
  242. {
  243. commentBuffer.append("\r\n");
  244. }
  245. commentBuffer.append(line.substring(1));
  246. }
  247. else if (line.length() == 0)
  248. {
  249. // blank line, reset comments
  250. if (commentBuffer.length() > 0)
  251. {
  252. cf.addConfigComment(commentBuffer.toString());
  253. }
  254. commentBuffer.setLength(0);
  255. }
  256. else if (line.indexOf('=') >= 0)
  257. {
  258. String[] kv = line.split("=");
  259. String key = kv[0].trim();
  260. String value = "";
  261. if (kv.length > 1)
  262. {
  263. value = kv[1].trim();
  264. }
  265. if (line.indexOf('\\') >= 0)
  266. {
  267. while ((line = lnr.readLine()) != null && line.indexOf('\\') >= 0)
  268. {
  269. value += "\r\n"+line;
  270. }
  271. value += "\r\n"+line;
  272. }
  273. String comments = commentBuffer.toString();
  274. commentBuffer.setLength(0); //reset
  275. cf.addConfigProperty(key, parseValue(value), comments);
  276. }
  277. }
  278. getConfigs().add(cf);
  279. lnr.close();
  280. }
  281. /**
  282. * @param value
  283. */
  284. private Object parseValue(String value)
  285. {
  286. if (value.equalsIgnoreCase("false") || value.equalsIgnoreCase("true"))
  287. {
  288. return Boolean.parseBoolean(value);
  289. }
  290. /*try
  291. {
  292. double parseDouble = Double.parseDouble(value);
  293. return parseDouble;
  294. }
  295. catch (NumberFormatException e)
  296. {
  297. // not a double, ignore
  298. }*/
  299. // localhost -> 127.0.0.1
  300. if (value.equals("localhost"))
  301. {
  302. value = "127.0.0.1";
  303. }
  304. String[] parts = value.split("\\.");
  305. if (parts.length == 4)
  306. {
  307. boolean ok = true;
  308. for (int i = 0; i < 4 && ok; i++)
  309. {
  310. try
  311. {
  312. int parseInt = Integer.parseInt(parts[i]);
  313. if (parseInt < 0 || parseInt > 255)
  314. {
  315. ok = false;
  316. }
  317. }
  318. catch (NumberFormatException e)
  319. {
  320. ok = false;
  321. }
  322. }
  323. if (ok)
  324. {
  325. try
  326. {
  327. InetAddress address = InetAddress.getByName(value);
  328. return address;
  329. }
  330. catch (UnknownHostException e)
  331. {
  332. // ignore
  333. }
  334. }
  335. }
  336. return value;
  337. }
  338. static class ConfigFile
  339. {
  340. private File _file;
  341. private String _name;
  342. private final List<ConfigComment> _configs = new FastList<ConfigComment>();
  343. public ConfigFile(File file)
  344. {
  345. _file = file;
  346. int lastIndex = file.getName().lastIndexOf('.');
  347. setName(file.getName().substring(0, lastIndex));
  348. }
  349. public void addConfigProperty(String name, Object value, ValueType type, String comments)
  350. {
  351. _configs.add(new ConfigProperty(name, value, type, comments));
  352. }
  353. public void addConfigComment(String comment)
  354. {
  355. _configs.add(new ConfigComment(comment));
  356. }
  357. public void addConfigProperty(String name, Object value, String comments)
  358. {
  359. this.addConfigProperty(name, value, ValueType.firstTypeMatch(value), comments);
  360. }
  361. public List<ConfigComment> getConfigProperties()
  362. {
  363. return _configs;
  364. }
  365. /**
  366. * @param name The name to set.
  367. */
  368. public void setName(String name)
  369. {
  370. _name = name;
  371. }
  372. /**
  373. * @return Returns the name.
  374. */
  375. public String getName()
  376. {
  377. return _name;
  378. }
  379. public void save() throws IOException
  380. {
  381. BufferedWriter bufWriter = null;
  382. try
  383. {
  384. bufWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(_file)));
  385. for (ConfigComment cc : _configs)
  386. {
  387. cc.save(bufWriter);
  388. }
  389. }
  390. finally
  391. {
  392. if (bufWriter != null)
  393. {
  394. bufWriter.close();
  395. }
  396. }
  397. }
  398. class ConfigComment
  399. {
  400. private String _comments;
  401. /**
  402. * @param comments
  403. */
  404. public ConfigComment(String comments)
  405. {
  406. _comments = comments;
  407. }
  408. /**
  409. * @return Returns the comments.
  410. */
  411. public String getComments()
  412. {
  413. return _comments;
  414. }
  415. /**
  416. * @param comments The comments to set.
  417. */
  418. public void setComments(String comments)
  419. {
  420. _comments = comments;
  421. }
  422. public void save(Writer writer) throws IOException
  423. {
  424. StringBuilder sb = new StringBuilder();
  425. sb.append('#');
  426. sb.append(this.getComments().replace("\r\n", "\r\n#"));
  427. sb.append("\r\n\r\n");
  428. writer.write(sb.toString());
  429. }
  430. }
  431. class ConfigProperty extends ConfigComment
  432. {
  433. private String _propname;
  434. private Object _value;
  435. private ValueType _type;
  436. private JComponent _component;
  437. /**
  438. * @param name
  439. * @param value
  440. * @param type
  441. * @param comments
  442. */
  443. public ConfigProperty(String name, Object value, ValueType type, String comments)
  444. {
  445. super(comments);
  446. if (!type.getType().isAssignableFrom(value.getClass()))
  447. {
  448. throw new IllegalArgumentException("Value Instance Type doesn't match the type argument.");
  449. }
  450. _propname = name;
  451. _type = type;
  452. _value = value;
  453. }
  454. /**
  455. * @return Returns the name.
  456. */
  457. public String getName()
  458. {
  459. return _propname;
  460. }
  461. /**
  462. * @return Returns the name.
  463. */
  464. public String getDisplayName()
  465. {
  466. return unCamelize(_propname);
  467. }
  468. /**
  469. * @param name The name to set.
  470. */
  471. public void setName(String name)
  472. {
  473. _propname = name;
  474. }
  475. /**
  476. * @return Returns the value.
  477. */
  478. public Object getValue()
  479. {
  480. return _value;
  481. }
  482. /**
  483. * @param value The value to set.
  484. */
  485. public void setValue(String value)
  486. {
  487. _value = value;
  488. }
  489. /**
  490. * @return Returns the type.
  491. */
  492. public ValueType getType()
  493. {
  494. return _type;
  495. }
  496. /**
  497. * @param type The type to set.
  498. */
  499. public void setType(ValueType type)
  500. {
  501. _type = type;
  502. }
  503. public JComponent getValueComponent()
  504. {
  505. if (_component == null)
  506. {
  507. _component = createValueComponent();
  508. }
  509. return _component;
  510. }
  511. public JComponent createValueComponent()
  512. {
  513. switch (this.getType())
  514. {
  515. case BOOLEAN:
  516. boolean bool = (Boolean) this.getValue();
  517. JCheckBox checkBox = new JCheckBox();
  518. checkBox.setSelected(bool);
  519. return checkBox;
  520. case IPv4:
  521. return new JIPTextField((Inet4Address) this.getValue());
  522. case DOUBLE:
  523. case INTEGER:
  524. case STRING:
  525. default:
  526. String val = this.getValue().toString();
  527. JTextArea textArea = new JTextArea(val);
  528. textArea.setFont(UIManager.getFont("TextField.font"));
  529. int rows = 1;
  530. for (int i = 0; i < val.length(); i++)
  531. if (val.charAt(i) == '\\')
  532. rows++;
  533. textArea.setRows(rows);
  534. textArea.setColumns(Math.max(val.length() / rows, 20));
  535. return textArea;
  536. }
  537. }
  538. public void save(Writer writer) throws IOException
  539. {
  540. String value;
  541. if (this.getValueComponent() instanceof JCheckBox)
  542. {
  543. value = Boolean.toString(((JCheckBox) this.getValueComponent()).isSelected());
  544. value = value.substring(0, 1).toUpperCase() + value.substring(1);
  545. }
  546. else if (this.getValueComponent() instanceof JIPTextField)
  547. {
  548. value = ((JIPTextField) this.getValueComponent()).getText();
  549. }
  550. else if (this.getValueComponent() instanceof JTextArea)
  551. {
  552. value = ((JTextArea) this.getValueComponent()).getText();
  553. }
  554. else
  555. {
  556. throw new IllegalStateException("Unhandled component value");
  557. }
  558. StringBuilder sb = new StringBuilder();
  559. sb.append('#');
  560. sb.append(this.getComments().replace("\r\n", "\r\n#"));
  561. sb.append("\r\n");
  562. sb.append(this.getName());
  563. sb.append(" = ");
  564. sb.append(value);
  565. sb.append("\r\n");
  566. sb.append("\r\n");
  567. writer.write(sb.toString());
  568. }
  569. }
  570. }
  571. public static enum ValueType
  572. {
  573. BOOLEAN (Boolean.class),
  574. DOUBLE (Double.class),
  575. INTEGER (Integer.class),
  576. IPv4 (Inet4Address.class),
  577. STRING (String.class);
  578. private final Class<?> _type;
  579. private ValueType(Class<?> type)
  580. {
  581. _type = type;
  582. }
  583. /**
  584. * @return Returns the type.
  585. */
  586. public Class<?> getType()
  587. {
  588. return _type;
  589. }
  590. public static ValueType firstTypeMatch(Object value)
  591. {
  592. for (ValueType vt : ValueType.values())
  593. {
  594. if (vt.getType() == value.getClass())
  595. {
  596. return vt;
  597. }
  598. }
  599. throw new NoSuchElementException("No match for: "+value.getClass().getName());
  600. }
  601. }
  602. /**
  603. * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
  604. */
  605. @Override
  606. public void actionPerformed(ActionEvent e)
  607. {
  608. String cmd = e.getActionCommand();
  609. StringBuilder errors = new StringBuilder();
  610. if (cmd.equals("save"))
  611. {
  612. for (ConfigFile cf : ConfigUserInterface.this.getConfigs())
  613. {
  614. try
  615. {
  616. cf.save();
  617. }
  618. catch (Exception e1)
  619. {
  620. e1.printStackTrace();
  621. errors.append(getBundle().getString("errorSaving")+cf.getName()+".properties. "+getBundle().getString("reason")+e1.getLocalizedMessage()+"\r\n");
  622. }
  623. }
  624. if (errors.length() == 0)
  625. {
  626. JOptionPane.showMessageDialog(ConfigUserInterface.this, getBundle().getString("success"), "OK", JOptionPane.INFORMATION_MESSAGE);
  627. }
  628. else
  629. {
  630. JOptionPane.showMessageDialog(ConfigUserInterface.this,errors,getBundle().getString("error"),JOptionPane.ERROR_MESSAGE);
  631. System.exit(2);
  632. }
  633. }
  634. else if (cmd.equals("exit"))
  635. {
  636. System.exit(0);
  637. }
  638. else if (cmd.equals("about"))
  639. {
  640. JOptionPane.showMessageDialog(ConfigUserInterface.this, getBundle().getString("credits") + "\nhttp://www.l2jserver.com\n\n"+getBundle().getString("icons")+"\n\n"+getBundle().getString("language")+'\n'+getBundle().getString("translation"), getBundle().getString("aboutItem"), JOptionPane.INFORMATION_MESSAGE, ImagesTable.getImage("l2jserverlogo.png"));
  641. }
  642. }
  643. /**
  644. * @param configs The configuration to set.
  645. */
  646. public void setConfigs(List<ConfigFile> configs)
  647. {
  648. _configs = configs;
  649. }
  650. /**
  651. * @return Returns the configuration.
  652. */
  653. public List<ConfigFile> getConfigs()
  654. {
  655. return _configs;
  656. }
  657. /**
  658. * @return Returns the configuration setting name in a
  659. * human readable form.
  660. */
  661. public static String unCamelize(final String keyName) {
  662. Pattern p = Pattern.compile("\\p{Lu}");
  663. Matcher m = p.matcher(keyName);
  664. StringBuffer sb = new StringBuffer();
  665. int last = 0;
  666. while (m.find())
  667. {
  668. if (m.start() != last + 1)
  669. {
  670. m.appendReplacement(sb," " + m.group());
  671. }
  672. last = m.start();
  673. }
  674. m.appendTail(sb);
  675. return sb.toString().trim();
  676. }
  677. /**
  678. * @param bundle The bundle to set.
  679. */
  680. public void setBundle(ResourceBundle bundle)
  681. {
  682. _bundle = bundle;
  683. }
  684. /**
  685. * @return Returns the bundle.
  686. */
  687. public ResourceBundle getBundle()
  688. {
  689. return _bundle;
  690. }
  691. }