ConfigUserInterface.java 21 KB

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