ConfigUserInterface.java 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763
  1. /*
  2. * Copyright (C) 2004-2015 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.ArrayList;
  39. import java.util.List;
  40. import java.util.Locale;
  41. import java.util.NoSuchElementException;
  42. import java.util.ResourceBundle;
  43. import java.util.regex.Matcher;
  44. import java.util.regex.Pattern;
  45. import javax.swing.JButton;
  46. import javax.swing.JCheckBox;
  47. import javax.swing.JComponent;
  48. import javax.swing.JFrame;
  49. import javax.swing.JLabel;
  50. import javax.swing.JMenu;
  51. import javax.swing.JMenuBar;
  52. import javax.swing.JMenuItem;
  53. import javax.swing.JOptionPane;
  54. import javax.swing.JPanel;
  55. import javax.swing.JScrollPane;
  56. import javax.swing.JTabbedPane;
  57. import javax.swing.JTextArea;
  58. import javax.swing.JToolBar;
  59. import javax.swing.SwingConstants;
  60. import javax.swing.SwingUtilities;
  61. import javax.swing.ToolTipManager;
  62. import javax.swing.UIManager;
  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 ArrayList<>();
  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. final File configsDir = new File("config");
  199. final File[] files = configsDir.listFiles();
  200. if (files == null)
  201. {
  202. JOptionPane.showMessageDialog(ConfigUserInterface.this, getBundle().getString("errorReading") + "config", getBundle().getString("error"), JOptionPane.ERROR_MESSAGE);
  203. return;
  204. }
  205. for (File file : files)
  206. {
  207. if (file.getName().endsWith(".properties") && file.isFile() && file.canWrite())
  208. {
  209. try
  210. {
  211. parsePropertiesFile(file);
  212. }
  213. catch (IOException e)
  214. {
  215. JOptionPane.showMessageDialog(ConfigUserInterface.this, getBundle().getString("errorReading") + file.getName(), getBundle().getString("error"), JOptionPane.ERROR_MESSAGE);
  216. System.exit(3);
  217. }
  218. }
  219. }
  220. }
  221. /**
  222. * @param file
  223. * @throws IOException
  224. */
  225. private void parsePropertiesFile(File file) throws IOException
  226. {
  227. try (FileInputStream fis = new FileInputStream(file);
  228. InputStreamReader isr = new InputStreamReader(fis);
  229. LineNumberReader lnr = new LineNumberReader(isr))
  230. {
  231. String line;
  232. StringBuilder commentBuffer = new StringBuilder();
  233. ConfigFile cf = new ConfigFile(file);
  234. while ((line = lnr.readLine()) != null)
  235. {
  236. line = line.trim();
  237. if (line.isEmpty())
  238. {
  239. // blank line, reset comments
  240. if (commentBuffer.length() > 0)
  241. {
  242. cf.addConfigComment(commentBuffer.toString());
  243. }
  244. commentBuffer.setLength(0);
  245. }
  246. else if (line.charAt(0) == '#')
  247. {
  248. if (commentBuffer.length() > 0)
  249. {
  250. commentBuffer.append(EOL);
  251. }
  252. commentBuffer.append(line.substring(1));
  253. }
  254. else if (line.indexOf('=') >= 0)
  255. {
  256. String[] kv = line.split("=");
  257. String key = kv[0].trim();
  258. StringBuilder value = new StringBuilder();
  259. if (kv.length > 1)
  260. {
  261. value.append(kv[1].trim());
  262. }
  263. if (line.indexOf('\\') >= 0)
  264. {
  265. while (((line = lnr.readLine()) != null) && (line.indexOf('\\') >= 0))
  266. {
  267. value.append(EOL + line);
  268. }
  269. value.append(EOL + line);
  270. }
  271. String comments = commentBuffer.toString();
  272. commentBuffer.setLength(0); // reset
  273. cf.addConfigProperty(key, parseValue(value.toString()), comments);
  274. }
  275. }
  276. getConfigs().add(cf);
  277. }
  278. }
  279. /**
  280. * @param value
  281. * @return
  282. */
  283. private Object parseValue(String value)
  284. {
  285. if (value.equalsIgnoreCase("false") || value.equalsIgnoreCase("true"))
  286. {
  287. return Boolean.parseBoolean(value);
  288. }
  289. /*
  290. * try { double parseDouble = Double.parseDouble(value); return parseDouble; } catch (NumberFormatException e) { // not a double, ignore }
  291. */
  292. // localhost -> 127.0.0.1
  293. if (value.equals("localhost"))
  294. {
  295. value = "127.0.0.1";
  296. }
  297. String[] parts = value.split("\\.");
  298. if (parts.length == 4)
  299. {
  300. boolean ok = true;
  301. for (int i = 0; (i < 4) && ok; i++)
  302. {
  303. try
  304. {
  305. int parseInt = Integer.parseInt(parts[i]);
  306. if ((parseInt < 0) || (parseInt > 255))
  307. {
  308. ok = false;
  309. }
  310. }
  311. catch (NumberFormatException e)
  312. {
  313. ok = false;
  314. }
  315. }
  316. if (ok)
  317. {
  318. try
  319. {
  320. InetAddress address = InetAddress.getByName(value);
  321. return address;
  322. }
  323. catch (UnknownHostException e)
  324. {
  325. // ignore
  326. }
  327. }
  328. }
  329. return value;
  330. }
  331. static class ConfigFile
  332. {
  333. private final File _file;
  334. private String _name;
  335. private final List<ConfigComment> _configs = new ArrayList<>();
  336. public ConfigFile(File file)
  337. {
  338. _file = file;
  339. int lastIndex = file.getName().lastIndexOf('.');
  340. setName(file.getName().substring(0, lastIndex));
  341. }
  342. public void addConfigProperty(String name, Object value, ValueType type, String comments)
  343. {
  344. _configs.add(new ConfigProperty(name, value, type, comments));
  345. }
  346. public void addConfigComment(String comment)
  347. {
  348. _configs.add(new ConfigComment(comment));
  349. }
  350. public void addConfigProperty(String name, Object value, String comments)
  351. {
  352. this.addConfigProperty(name, value, ValueType.firstTypeMatch(value), comments);
  353. }
  354. public List<ConfigComment> getConfigProperties()
  355. {
  356. return _configs;
  357. }
  358. /**
  359. * @param name The name to set.
  360. */
  361. public void setName(String name)
  362. {
  363. _name = name;
  364. }
  365. /**
  366. * @return Returns the name.
  367. */
  368. public String getName()
  369. {
  370. return _name;
  371. }
  372. public void save() throws IOException
  373. {
  374. try (FileOutputStream fos = new FileOutputStream(_file);
  375. OutputStreamWriter osw = new OutputStreamWriter(fos);
  376. BufferedWriter bufWriter = new BufferedWriter(osw))
  377. {
  378. for (ConfigComment cc : _configs)
  379. {
  380. cc.save(bufWriter);
  381. }
  382. }
  383. }
  384. class ConfigComment
  385. {
  386. private String _comments;
  387. /**
  388. * @param comments
  389. */
  390. public ConfigComment(String comments)
  391. {
  392. _comments = comments;
  393. }
  394. /**
  395. * @return Returns the comments.
  396. */
  397. public String getComments()
  398. {
  399. return _comments;
  400. }
  401. /**
  402. * @param comments The comments to set.
  403. */
  404. public void setComments(String comments)
  405. {
  406. _comments = comments;
  407. }
  408. public void save(Writer writer) throws IOException
  409. {
  410. StringBuilder sb = new StringBuilder();
  411. sb.append('#');
  412. sb.append(getComments().replace(EOL, EOL + "#"));
  413. sb.append(EOL + EOL);
  414. writer.write(sb.toString());
  415. }
  416. }
  417. class ConfigProperty extends ConfigComment
  418. {
  419. private String _propname;
  420. private Object _value;
  421. private ValueType _type;
  422. private JComponent _component;
  423. /**
  424. * @param name
  425. * @param value
  426. * @param type
  427. * @param comments
  428. */
  429. public ConfigProperty(String name, Object value, ValueType type, String comments)
  430. {
  431. super(comments);
  432. if (!type.getType().isAssignableFrom(value.getClass()))
  433. {
  434. throw new IllegalArgumentException("Value Instance Type doesn't match the type argument.");
  435. }
  436. _propname = name;
  437. _type = type;
  438. _value = value;
  439. }
  440. /**
  441. * @return Returns the name.
  442. */
  443. public String getName()
  444. {
  445. return _propname;
  446. }
  447. /**
  448. * @return Returns the name.
  449. */
  450. public String getDisplayName()
  451. {
  452. return unCamelize(_propname);
  453. }
  454. /**
  455. * @param name The name to set.
  456. */
  457. public void setName(String name)
  458. {
  459. _propname = name;
  460. }
  461. /**
  462. * @return Returns the value.
  463. */
  464. public Object getValue()
  465. {
  466. return _value;
  467. }
  468. /**
  469. * @param value The value to set.
  470. */
  471. public void setValue(String value)
  472. {
  473. _value = value;
  474. }
  475. /**
  476. * @return Returns the type.
  477. */
  478. public ValueType getType()
  479. {
  480. return _type;
  481. }
  482. /**
  483. * @param type The type to set.
  484. */
  485. public void setType(ValueType type)
  486. {
  487. _type = type;
  488. }
  489. public JComponent getValueComponent()
  490. {
  491. if (_component == null)
  492. {
  493. _component = createValueComponent();
  494. }
  495. return _component;
  496. }
  497. public JComponent createValueComponent()
  498. {
  499. switch (getType())
  500. {
  501. case BOOLEAN:
  502. boolean bool = (Boolean) getValue();
  503. JCheckBox checkBox = new JCheckBox();
  504. checkBox.setSelected(bool);
  505. return checkBox;
  506. case IPv4:
  507. return new JIPTextField((Inet4Address) getValue());
  508. case DOUBLE:
  509. case INTEGER:
  510. case STRING:
  511. default:
  512. String val = getValue().toString();
  513. JTextArea textArea = new JTextArea(val);
  514. textArea.setFont(UIManager.getFont("TextField.font"));
  515. int rows = 1;
  516. for (int i = 0; i < val.length(); i++)
  517. {
  518. if (val.charAt(i) == '\\')
  519. {
  520. rows++;
  521. }
  522. }
  523. textArea.setRows(rows);
  524. textArea.setColumns(Math.max(val.length() / rows, 20));
  525. return textArea;
  526. }
  527. }
  528. @Override
  529. public void save(Writer writer) throws IOException
  530. {
  531. String value;
  532. if (getValueComponent() instanceof JCheckBox)
  533. {
  534. value = Boolean.toString(((JCheckBox) getValueComponent()).isSelected());
  535. value = value.substring(0, 1).toUpperCase() + value.substring(1);
  536. }
  537. else if (getValueComponent() instanceof JIPTextField)
  538. {
  539. value = ((JIPTextField) getValueComponent()).getText();
  540. }
  541. else if (getValueComponent() instanceof JTextArea)
  542. {
  543. value = ((JTextArea) getValueComponent()).getText();
  544. }
  545. else
  546. {
  547. throw new IllegalStateException("Unhandled component value");
  548. }
  549. StringBuilder sb = new StringBuilder();
  550. sb.append('#');
  551. sb.append(getComments().replace(EOL, EOL + "#"));
  552. sb.append(EOL);
  553. sb.append(getName());
  554. sb.append(" = ");
  555. sb.append(value);
  556. sb.append(EOL);
  557. sb.append(EOL);
  558. writer.write(sb.toString());
  559. }
  560. }
  561. }
  562. public static enum ValueType
  563. {
  564. BOOLEAN(Boolean.class),
  565. DOUBLE(Double.class),
  566. INTEGER(Integer.class),
  567. IPv4(Inet4Address.class),
  568. STRING(String.class);
  569. private final Class<?> _type;
  570. private ValueType(Class<?> type)
  571. {
  572. _type = type;
  573. }
  574. /**
  575. * @return Returns the type.
  576. */
  577. public Class<?> getType()
  578. {
  579. return _type;
  580. }
  581. public static ValueType firstTypeMatch(Object value)
  582. {
  583. for (ValueType vt : ValueType.values())
  584. {
  585. if (vt.getType() == value.getClass())
  586. {
  587. return vt;
  588. }
  589. }
  590. throw new NoSuchElementException("No match for: " + value.getClass().getName());
  591. }
  592. }
  593. @Override
  594. public void actionPerformed(ActionEvent e)
  595. {
  596. String cmd = e.getActionCommand();
  597. StringBuilder errors = new StringBuilder();
  598. if (cmd.equals("save"))
  599. {
  600. for (ConfigFile cf : ConfigUserInterface.this.getConfigs())
  601. {
  602. try
  603. {
  604. cf.save();
  605. }
  606. catch (Exception e1)
  607. {
  608. e1.printStackTrace();
  609. errors.append(getBundle().getString("errorSaving") + cf.getName() + ".properties. " + getBundle().getString("reason") + e1.getLocalizedMessage() + EOL);
  610. }
  611. }
  612. if (errors.length() == 0)
  613. {
  614. JOptionPane.showMessageDialog(ConfigUserInterface.this, getBundle().getString("success"), "OK", JOptionPane.INFORMATION_MESSAGE);
  615. }
  616. else
  617. {
  618. JOptionPane.showMessageDialog(ConfigUserInterface.this, errors, getBundle().getString("error"), JOptionPane.ERROR_MESSAGE);
  619. System.exit(2);
  620. }
  621. }
  622. else if (cmd.equals("exit"))
  623. {
  624. System.exit(0);
  625. }
  626. else if (cmd.equals("about"))
  627. {
  628. 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"));
  629. }
  630. }
  631. /**
  632. * @param configs The configuration to set.
  633. */
  634. public void setConfigs(List<ConfigFile> configs)
  635. {
  636. _configs = configs;
  637. }
  638. /**
  639. * @return Returns the configuration.
  640. */
  641. public List<ConfigFile> getConfigs()
  642. {
  643. return _configs;
  644. }
  645. /**
  646. * @param keyName
  647. * @return Returns the configuration setting name in a human readable form.
  648. */
  649. public static String unCamelize(final String keyName)
  650. {
  651. Pattern p = Pattern.compile("\\p{Lu}");
  652. Matcher m = p.matcher(keyName);
  653. StringBuffer sb = new StringBuffer();
  654. int last = 0;
  655. while (m.find())
  656. {
  657. if (m.start() != (last + 1))
  658. {
  659. m.appendReplacement(sb, " " + m.group());
  660. }
  661. last = m.start();
  662. }
  663. m.appendTail(sb);
  664. return sb.toString().trim();
  665. }
  666. /**
  667. * @param bundle The bundle to set.
  668. */
  669. public void setBundle(ResourceBundle bundle)
  670. {
  671. _bundle = bundle;
  672. }
  673. /**
  674. * @return Returns the bundle.
  675. */
  676. public ResourceBundle getBundle()
  677. {
  678. return _bundle;
  679. }
  680. }