ConfigUserInterface.java 18 KB

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