2
0

ConfigUserInterface.java 18 KB

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