ConfigUserInterface.java 18 KB

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