ConfigUserInterface.java 18 KB

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