ConfigUserInterface.java 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784
  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.tools.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.SwingConstants;
  55. import javax.swing.SwingUtilities;
  56. import javax.swing.ToolTipManager;
  57. import javax.swing.UIManager;
  58. import javolution.util.FastList;
  59. import com.l2jserver.tools.configurator.ConfigUserInterface.ConfigFile.ConfigComment;
  60. import com.l2jserver.tools.configurator.ConfigUserInterface.ConfigFile.ConfigProperty;
  61. import com.l2jserver.tools.i18n.LanguageControl;
  62. import com.l2jserver.tools.images.ImagesTable;
  63. /**
  64. *
  65. * @author KenM
  66. */
  67. public class ConfigUserInterface extends JFrame implements ActionListener
  68. {
  69. /**
  70. * Comment for <code>serialVersionUID</code>
  71. */
  72. private static final long serialVersionUID = 1L;
  73. private JTabbedPane _tabPane = new JTabbedPane();
  74. private List<ConfigFile> _configs = new FastList<ConfigFile>();
  75. private ResourceBundle _bundle;
  76. /**
  77. * @param args
  78. */
  79. public static void main(String[] args)
  80. {
  81. try
  82. {
  83. UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
  84. }
  85. catch (Exception e)
  86. {
  87. // couldn't care less
  88. }
  89. final ResourceBundle bundle = ResourceBundle.getBundle("configurator.Configurator", Locale.getDefault(), LanguageControl.INSTANCE);
  90. SwingUtilities.invokeLater
  91. (
  92. new Runnable()
  93. {
  94. @Override
  95. public void run()
  96. {
  97. ConfigUserInterface cui = new ConfigUserInterface(bundle);
  98. cui.setVisible(true);
  99. }
  100. }
  101. );
  102. }
  103. public ConfigUserInterface(ResourceBundle bundle)
  104. {
  105. setBundle(bundle);
  106. this.setTitle(bundle.getString("toolName"));
  107. this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  108. this.setSize(750, 500);
  109. this.setLayout(new GridBagLayout());
  110. setDefaultLookAndFeelDecorated(true);
  111. setIconImage(ImagesTable.getImage("l2j.png").getImage());
  112. GridBagConstraints cons = new GridBagConstraints();
  113. cons.fill = GridBagConstraints.HORIZONTAL;
  114. cons.gridx = 0;
  115. cons.gridy = 0;
  116. cons.weighty = 0;
  117. cons.weightx = 1;
  118. JMenuBar menubar = new JMenuBar();
  119. JMenu fileMenu = new JMenu(bundle.getString("fileMenu"));
  120. JMenu helpMenu = new JMenu(bundle.getString("helpMenu"));
  121. JMenuItem exitItem = new JMenuItem(bundle.getString("exitItem"));
  122. exitItem.setActionCommand("exit");
  123. exitItem.addActionListener(this);
  124. fileMenu.add(exitItem);
  125. JMenuItem aboutItem = new JMenuItem(bundle.getString("aboutItem"));
  126. aboutItem.setActionCommand("about");
  127. aboutItem.addActionListener(this);
  128. helpMenu.add(aboutItem);
  129. menubar.add(fileMenu);
  130. menubar.add(helpMenu);
  131. this.setJMenuBar(menubar);
  132. JToolBar toolBar = new JToolBar();
  133. toolBar.setFloatable(false);
  134. toolBar.setRollover(true);
  135. toolBar.add(this.createToolButton("disk.png", bundle.getString("save"), "save"));
  136. this.add(toolBar, cons);
  137. cons.gridy++;
  138. cons.fill = GridBagConstraints.BOTH;
  139. cons.weighty = 1;
  140. this.loadConfigs();
  141. this.buildInterface();
  142. this.add(_tabPane, cons);
  143. }
  144. private JButton createToolButton(String image, String text, String action)
  145. {
  146. JButton button = new JButton(text, ImagesTable.getImage(image));
  147. button.setActionCommand(action);
  148. button.addActionListener(this);
  149. return button;
  150. }
  151. /**
  152. *
  153. */
  154. @SuppressWarnings("serial")
  155. private void buildInterface()
  156. {
  157. ToolTipManager.sharedInstance().setDismissDelay(Integer.MAX_VALUE);
  158. ToolTipManager.sharedInstance().setInitialDelay(0);
  159. ToolTipManager.sharedInstance().setReshowDelay(0);
  160. GridBagConstraints cons = new GridBagConstraints();
  161. cons.fill = GridBagConstraints.NONE;
  162. cons.anchor = GridBagConstraints.FIRST_LINE_START;
  163. cons.insets = new Insets(2, 2, 2, 2);
  164. for (ConfigFile cf : getConfigs())
  165. {
  166. JPanel panel = new JPanel() {
  167. @Override
  168. public void scrollRectToVisible(Rectangle r ) {}
  169. };
  170. panel.setLayout(new GridBagLayout());
  171. cons.gridy = 0;
  172. cons.weighty = 0;
  173. for (ConfigComment cc : cf.getConfigProperties())
  174. {
  175. if (!(cc instanceof ConfigProperty))
  176. {
  177. continue;
  178. }
  179. ConfigProperty cp = (ConfigProperty) cc;
  180. cons.gridx = 0;
  181. JLabel keyLabel = new JLabel(cp.getDisplayName()+':', ImagesTable.getImage("help.png"), SwingConstants.LEFT);
  182. String comments = "<b>"+cp.getName()+":</b><br>"+cp.getComments();
  183. comments = comments.replace("\r\n", "<br>");
  184. comments = "<html>"+comments+"</html>";
  185. keyLabel.setToolTipText(comments);
  186. cons.weightx = 0;
  187. panel.add(keyLabel, cons);
  188. cons.gridx++;
  189. JComponent valueComponent = cp.getValueComponent();
  190. valueComponent.setToolTipText(comments);
  191. cons.weightx = 1;
  192. panel.add(valueComponent, cons);
  193. cons.gridx++;
  194. cons.gridy++;
  195. }
  196. cons.gridy++;
  197. cons.weighty = 1;
  198. panel.add(new JLabel(), cons); // filler
  199. _tabPane.addTab(cf.getName(), new JScrollPane(panel));
  200. }
  201. }
  202. /**
  203. *
  204. */
  205. private void loadConfigs()
  206. {
  207. File configsDir = new File("config");
  208. for (File file : configsDir.listFiles())
  209. {
  210. if (file.getName().endsWith(".properties") && file.isFile() && file.canWrite())
  211. {
  212. try
  213. {
  214. this.parsePropertiesFile(file);
  215. }
  216. catch (IOException e)
  217. {
  218. JOptionPane.showMessageDialog(ConfigUserInterface.this,getBundle().getString("errorReading")+file.getName(),getBundle().getString("error"),JOptionPane.ERROR_MESSAGE);
  219. System.exit(3);
  220. // e.printStackTrace();
  221. }
  222. }
  223. }
  224. }
  225. /**
  226. * @param file
  227. * @throws IOException
  228. */
  229. private void parsePropertiesFile(File file) throws IOException
  230. {
  231. LineNumberReader lnr = new LineNumberReader(new InputStreamReader(new FileInputStream(file)));
  232. String line;
  233. StringBuilder commentBuffer = new StringBuilder();
  234. ConfigFile cf = new ConfigFile(file);
  235. while ((line = lnr.readLine()) != null)
  236. {
  237. line = line.trim();
  238. if (line.startsWith("#"))
  239. {
  240. if (commentBuffer.length() > 0)
  241. {
  242. commentBuffer.append("\r\n");
  243. }
  244. commentBuffer.append(line.substring(1));
  245. }
  246. else if (line.length() == 0)
  247. {
  248. // blank line, reset comments
  249. if (commentBuffer.length() > 0)
  250. {
  251. cf.addConfigComment(commentBuffer.toString());
  252. }
  253. commentBuffer.setLength(0);
  254. }
  255. else if (line.indexOf('=') >= 0)
  256. {
  257. String[] kv = line.split("=");
  258. String key = kv[0].trim();
  259. StringBuilder value = new StringBuilder();
  260. if (kv.length > 1)
  261. {
  262. value.append(kv[1].trim());
  263. }
  264. if (line.indexOf('\\') >= 0)
  265. {
  266. while ((line = lnr.readLine()) != null && line.indexOf('\\') >= 0)
  267. {
  268. value.append("\r\n"+line);
  269. }
  270. value.append("\r\n"+line);
  271. }
  272. String comments = commentBuffer.toString();
  273. commentBuffer.setLength(0); //reset
  274. cf.addConfigProperty(key, parseValue(value.toString()), comments);
  275. }
  276. }
  277. getConfigs().add(cf);
  278. lnr.close();
  279. }
  280. /**
  281. * @param value
  282. * @return
  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. @Override
  539. public void save(Writer writer) throws IOException
  540. {
  541. String value;
  542. if (this.getValueComponent() instanceof JCheckBox)
  543. {
  544. value = Boolean.toString(((JCheckBox) this.getValueComponent()).isSelected());
  545. value = value.substring(0, 1).toUpperCase() + value.substring(1);
  546. }
  547. else if (this.getValueComponent() instanceof JIPTextField)
  548. {
  549. value = ((JIPTextField) this.getValueComponent()).getText();
  550. }
  551. else if (this.getValueComponent() instanceof JTextArea)
  552. {
  553. value = ((JTextArea) this.getValueComponent()).getText();
  554. }
  555. else
  556. {
  557. throw new IllegalStateException("Unhandled component value");
  558. }
  559. StringBuilder sb = new StringBuilder();
  560. sb.append('#');
  561. sb.append(this.getComments().replace("\r\n", "\r\n#"));
  562. sb.append("\r\n");
  563. sb.append(this.getName());
  564. sb.append(" = ");
  565. sb.append(value);
  566. sb.append("\r\n");
  567. sb.append("\r\n");
  568. writer.write(sb.toString());
  569. }
  570. }
  571. }
  572. public static enum ValueType
  573. {
  574. BOOLEAN (Boolean.class),
  575. DOUBLE (Double.class),
  576. INTEGER (Integer.class),
  577. IPv4 (Inet4Address.class),
  578. STRING (String.class);
  579. private final Class<?> _type;
  580. private ValueType(Class<?> type)
  581. {
  582. _type = type;
  583. }
  584. /**
  585. * @return Returns the type.
  586. */
  587. public Class<?> getType()
  588. {
  589. return _type;
  590. }
  591. public static ValueType firstTypeMatch(Object value)
  592. {
  593. for (ValueType vt : ValueType.values())
  594. {
  595. if (vt.getType() == value.getClass())
  596. {
  597. return vt;
  598. }
  599. }
  600. throw new NoSuchElementException("No match for: "+value.getClass().getName());
  601. }
  602. }
  603. /**
  604. * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
  605. */
  606. @Override
  607. public void actionPerformed(ActionEvent e)
  608. {
  609. String cmd = e.getActionCommand();
  610. StringBuilder errors = new StringBuilder();
  611. if (cmd.equals("save"))
  612. {
  613. for (ConfigFile cf : ConfigUserInterface.this.getConfigs())
  614. {
  615. try
  616. {
  617. cf.save();
  618. }
  619. catch (Exception e1)
  620. {
  621. e1.printStackTrace();
  622. errors.append(getBundle().getString("errorSaving")+cf.getName()+".properties. "+getBundle().getString("reason")+e1.getLocalizedMessage()+"\r\n");
  623. }
  624. }
  625. if (errors.length() == 0)
  626. {
  627. JOptionPane.showMessageDialog(ConfigUserInterface.this, getBundle().getString("success"), "OK", JOptionPane.INFORMATION_MESSAGE);
  628. }
  629. else
  630. {
  631. JOptionPane.showMessageDialog(ConfigUserInterface.this,errors,getBundle().getString("error"),JOptionPane.ERROR_MESSAGE);
  632. System.exit(2);
  633. }
  634. }
  635. else if (cmd.equals("exit"))
  636. {
  637. System.exit(0);
  638. }
  639. else if (cmd.equals("about"))
  640. {
  641. 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"));
  642. }
  643. }
  644. /**
  645. * @param configs The configuration to set.
  646. */
  647. public void setConfigs(List<ConfigFile> configs)
  648. {
  649. _configs = configs;
  650. }
  651. /**
  652. * @return Returns the configuration.
  653. */
  654. public List<ConfigFile> getConfigs()
  655. {
  656. return _configs;
  657. }
  658. /**
  659. * @param keyName
  660. * @return Returns the configuration setting name in a
  661. * human readable form.
  662. */
  663. public static String unCamelize(final String keyName) {
  664. Pattern p = Pattern.compile("\\p{Lu}");
  665. Matcher m = p.matcher(keyName);
  666. StringBuffer sb = new StringBuffer();
  667. int last = 0;
  668. while (m.find())
  669. {
  670. if (m.start() != last + 1)
  671. {
  672. m.appendReplacement(sb," " + m.group());
  673. }
  674. last = m.start();
  675. }
  676. m.appendTail(sb);
  677. return sb.toString().trim();
  678. }
  679. /**
  680. * @param bundle The bundle to set.
  681. */
  682. public void setBundle(ResourceBundle bundle)
  683. {
  684. _bundle = bundle;
  685. }
  686. /**
  687. * @return Returns the bundle.
  688. */
  689. public ResourceBundle getBundle()
  690. {
  691. return _bundle;
  692. }
  693. }