ConfigUserInterface.java 18 KB

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