ConfigUserInterface.java 18 KB

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