]> gitweb.fperrin.net Git - GpsPrune.git/blob - tim/prune/function/SetLanguage.java
d54e1be2cdef26eab604ce3358e059a3d839d22e
[GpsPrune.git] / tim / prune / function / SetLanguage.java
1 package tim.prune.function;
2
3 import java.awt.BorderLayout;
4 import java.awt.Component;
5 import java.awt.FlowLayout;
6 import java.awt.event.ActionEvent;
7 import java.awt.event.ActionListener;
8 import java.io.BufferedReader;
9 import java.io.File;
10 import java.io.FileReader;
11 import java.util.Locale;
12
13 import javax.swing.BorderFactory;
14 import javax.swing.Box;
15 import javax.swing.BoxLayout;
16 import javax.swing.JButton;
17 import javax.swing.JComboBox;
18 import javax.swing.JDialog;
19 import javax.swing.JFileChooser;
20 import javax.swing.JLabel;
21 import javax.swing.JOptionPane;
22 import javax.swing.JPanel;
23 import javax.swing.JTextField;
24 import javax.swing.SwingConstants;
25 import javax.swing.border.EtchedBorder;
26
27 import tim.prune.App;
28 import tim.prune.GenericFunction;
29 import tim.prune.I18nManager;
30 import tim.prune.config.Config;
31 import tim.prune.load.GenericFileFilter;
32
33 /**
34  * Class to show the popup window for setting the language code / file
35  */
36 public class SetLanguage extends GenericFunction
37 {
38         private JDialog _dialog = null;
39         private JComboBox _languageDropDown = null;
40         private JTextField _langFileBox = null;
41         private int _startIndex = 0;
42
43         /** Names of languages for display in dropdown (not translated) */
44         private static final String[] LANGUAGE_NAMES = {"deutsch", "english", "espa\u00F1ol", "fran\u00E7ais",
45                 "italiano", "polski", "\u4e2d\u6587 (chinese)", "\u65E5\u672C\u8A9E (japanese)",
46                 "schwiizerd\u00FC\u00FCtsch", "t\u00FCrk\u00E7e", "portugu\u00EAs", "bahasa indonesia", "rom\u00E2n\u0103"
47         };
48         /** Associated language codes (must be in same order as names!) */
49         private static final String[] LANGUAGE_CODES = {"de", "en", "es", "fr", "it", "pl", "zh", "ja",
50                 "de_ch", "tr", "pt", "in", "ro"
51         };
52
53
54         /**
55          * Constructor
56          * @param inApp app object
57          */
58         public SetLanguage(App inApp)
59         {
60                 super(inApp);
61         }
62
63         /**
64          * Return the name key for this function
65          */
66         public String getNameKey()
67         {
68                 return "function.setlanguage";
69         }
70
71         /**
72          * @return the contents of the window as a Component
73          */
74         private Component makeContents()
75         {
76                 JPanel mainPanel = new JPanel();
77                 mainPanel.setLayout(new BorderLayout(0, 5));
78                 JPanel midPanel = new JPanel();
79                 midPanel.setLayout(new BoxLayout(midPanel, BoxLayout.Y_AXIS));
80                 midPanel.setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3));
81                 // description labels
82                 JLabel label1 = new JLabel("<html>" + I18nManager.getText("dialog.setlanguage.firstintro") + "</html>");
83                 label1.setAlignmentX(Component.LEFT_ALIGNMENT);
84                 label1.setHorizontalAlignment(SwingConstants.LEFT);
85                 midPanel.add(label1);
86                 JLabel label2 = new JLabel("<html>" + I18nManager.getText("dialog.setlanguage.secondintro") + "</html>");
87                 label2.setAlignmentX(Component.LEFT_ALIGNMENT);
88                 label2.setHorizontalAlignment(SwingConstants.LEFT);
89                 midPanel.add(label2);
90                 midPanel.add(Box.createVerticalStrut(10));
91
92                 // built-in languages
93                 JPanel builtinPanel = new JPanel();
94                 builtinPanel.setBorder(BorderFactory.createCompoundBorder(
95                         BorderFactory.createEtchedBorder(EtchedBorder.LOWERED), BorderFactory.createEmptyBorder(3, 3, 3, 3))
96                 );
97                 builtinPanel.setLayout(new BoxLayout(builtinPanel, BoxLayout.X_AXIS));
98                 builtinPanel.add(new JLabel(I18nManager.getText("dialog.setlanguage.language") + " : "));
99                 // Language dropdown
100                 _languageDropDown = new JComboBox(LANGUAGE_NAMES);
101                 builtinPanel.add(_languageDropDown);
102                 builtinPanel.add(Box.createHorizontalGlue());
103                 JButton selectLangButton = new JButton(I18nManager.getText("button.select"));
104                 selectLangButton.addActionListener(new ActionListener() {
105                         public void actionPerformed(ActionEvent e) {
106                                 selectLanguage();
107                         }
108                 });
109                 builtinPanel.add(selectLangButton);
110                 builtinPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
111                 midPanel.add(builtinPanel);
112                 midPanel.add(Box.createVerticalStrut(4));
113
114                 // external language file
115                 JPanel extraPanel = new JPanel();
116                 extraPanel.setBorder(BorderFactory.createCompoundBorder(
117                         BorderFactory.createEtchedBorder(EtchedBorder.LOWERED), BorderFactory.createEmptyBorder(3, 3, 3, 3))
118                 );
119                 extraPanel.setLayout(new BoxLayout(extraPanel, BoxLayout.X_AXIS));
120                 extraPanel.add(new JLabel(I18nManager.getText("dialog.setlanguage.languagefile") + " : "));
121                 _langFileBox = new JTextField("some_long_example_file_path.txt");
122                 extraPanel.add(_langFileBox);
123                 // browse button
124                 JButton browseButton = new JButton(I18nManager.getText("button.browse"));
125                 extraPanel.add(browseButton);
126                 browseButton.addActionListener(new ActionListener() {
127                         public void actionPerformed(ActionEvent arg0) {
128                                 chooseFile();
129                         }
130                 });
131                 extraPanel.add(Box.createHorizontalStrut(5));
132                 JButton selectFileButton = new JButton(I18nManager.getText("button.select"));
133                 selectFileButton.addActionListener(new ActionListener() {
134                         public void actionPerformed(ActionEvent e) {
135                                 selectLanguageFile();
136                         }
137                 });
138                 extraPanel.add(selectFileButton);
139                 extraPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
140                 midPanel.add(Box.createVerticalStrut(5));
141                 midPanel.add(extraPanel);
142                 midPanel.add(Box.createVerticalGlue());
143                 mainPanel.add(midPanel, BorderLayout.CENTER);
144
145                 // Cancel button at the bottom
146                 JPanel buttonPanel = new JPanel();
147                 buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
148                 JButton cancelButton = new JButton(I18nManager.getText("button.cancel"));
149                 cancelButton.addActionListener(new ActionListener() {
150                         public void actionPerformed(ActionEvent e)
151                         {
152                                 _dialog.dispose();
153                         }
154                 });
155                 buttonPanel.add(cancelButton);
156                 mainPanel.add(buttonPanel, BorderLayout.SOUTH);
157                 return mainPanel;
158         }
159
160
161         /**
162          * Show window
163          */
164         public void begin()
165         {
166                 if (_dialog == null)
167                 {
168                         _dialog = new JDialog(_parentFrame, I18nManager.getText(getNameKey()));
169                         _dialog.setLocationRelativeTo(_parentFrame);
170                         _dialog.getContentPane().add(makeContents());
171                         _dialog.pack();
172                 }
173                 // Try to use code from config
174                 String code = Config.getConfigString(Config.KEY_LANGUAGE_CODE);
175                 int index = getLanguageIndex(code);
176                 // If it's not present, then use system locale settings
177                 if (index < 0) {
178                         Locale locale = Locale.getDefault();
179                         index = getLanguageIndex(locale.getLanguage() + "_" + locale.getCountry());
180                         if (index < 0) {
181                                 index = getLanguageIndex(locale.getLanguage());
182                         }
183                 }
184                 // Select appropriate language from dropdown
185                 if (index >= 0) {
186                         _languageDropDown.setSelectedIndex(index);
187                 }
188                 _startIndex = _languageDropDown.getSelectedIndex();
189                 // Get language file from config
190                 String langfile = Config.getConfigString(Config.KEY_LANGUAGE_FILE);
191                 _langFileBox.setText(langfile==null?"":langfile);
192                 _dialog.setVisible(true);
193         }
194
195         /**
196          * Find the index of the given language code
197          * @param inCode code to look for
198          * @return index if found or -1
199          */
200         private static int getLanguageIndex(String inCode)
201         {
202                 int idx = -1;
203                 if (inCode != null && !inCode.equals("")) {
204                         for (int i=0; i<LANGUAGE_CODES.length; i++) {
205                                 if (LANGUAGE_CODES[i].equalsIgnoreCase(inCode)) {
206                                         idx = i;
207                                 }
208                         }
209                 }
210                 return idx;
211         }
212
213         /**
214          * Set the currently selected language in the Config
215          */
216         private void selectLanguage()
217         {
218                 int index = _languageDropDown.getSelectedIndex();
219                 // If index hasn't changed then don't dismiss dialog
220                 if (index >= 0 && index != _startIndex)
221                 {
222                         String code = LANGUAGE_CODES[index];
223                         // Set code and langfile in config
224                         Config.setConfigString(Config.KEY_LANGUAGE_CODE, code);
225                         Config.setConfigString(Config.KEY_LANGUAGE_FILE, null);
226                         _dialog.dispose();
227                         showEndMessage();
228                 }
229         }
230
231         /**
232          * Select the currently selected language file to use for texts
233          */
234         private void selectLanguageFile()
235         {
236                 final String oldPath = Config.getConfigString(Config.KEY_LANGUAGE_FILE);
237                 String filename = _langFileBox.getText();
238                 // Check there is an entry in the box
239                 if (filename != null && !filename.equals(""))
240                 {
241                         // Check the file exists and is readable
242                         File textsFile = new File(filename);
243                         if (!textsFile.exists() || !textsFile.canRead())
244                         {
245                                 _app.showErrorMessage(getNameKey(), "error.load.noread");
246                         }
247                         else if (!languageFileLooksOk(textsFile))
248                         {
249                                 _app.showErrorMessage(getNameKey(), "error.language.wrongfile");
250                         }
251                         else if (oldPath == null || !textsFile.getAbsolutePath().equalsIgnoreCase(oldPath))
252                         {
253                                 // Set in Config
254                                 Config.setConfigString(Config.KEY_LANGUAGE_FILE, textsFile.getAbsolutePath());
255                                 _dialog.dispose();
256                                 showEndMessage();
257                         }
258                 }
259                 else {
260                         // if file was previously selected, and now it's blank, then reset Config
261                         if (oldPath != null && oldPath.length() > 0)
262                         {
263                                 Config.setConfigString(Config.KEY_LANGUAGE_FILE, null);
264                                 _dialog.dispose();
265                                 showEndMessage();
266                         }
267                 }
268         }
269
270         /**
271          * Check the given file to see if it looks like a language file
272          * @param inFile File object to load
273          * @return true if file looks ok
274          */
275         private static boolean languageFileLooksOk(File inFile)
276         {
277                 boolean ok = false;
278                 boolean wrong = false;
279                 BufferedReader reader = null;
280                 try
281                 {
282                         // Read through text file looking for lines with the right start
283                         reader = new BufferedReader(new FileReader(inFile));
284                         String currLine = reader.readLine();
285                         while (currLine != null && !ok && !wrong)
286                         {
287                                 if (currLine.trim().length() > 0 && currLine.matches("[a-z.]+=.+")) {
288                                         ok = true;
289                                 }
290                                 if (currLine.indexOf('\0', 0) >= 0) {
291                                         wrong = true;
292                                 }
293                                 currLine = reader.readLine();
294                         }
295                 }
296                 catch (Exception e) {} // ignore exceptions, flag remains as set
297                 finally {
298                         try {reader.close();} catch (Exception e2) {}
299                 }
300                 return ok && !wrong;
301         }
302
303         /**
304          * Function activated by the "Browse..." button to select a file
305          */
306         private void chooseFile()
307         {
308                 JFileChooser chooser = new JFileChooser();
309                 chooser.addChoosableFileFilter(
310                         new GenericFileFilter("filetype.txt", new String[] {"txt", "text"}));
311                 chooser.setAcceptAllFileFilterUsed(true);
312                 // Set start path from currently selected file
313                 String currPath = _langFileBox.getText();
314                 if (currPath != null && currPath.length() > 1) {
315                         chooser.setSelectedFile(new File(currPath));
316                 }
317                 if (chooser.showOpenDialog(_parentFrame) == JFileChooser.APPROVE_OPTION)
318                 {
319                         _langFileBox.setText(chooser.getSelectedFile().getAbsolutePath());
320                 }
321         }
322
323         /**
324          * Show message to remind about saving settings and restarting
325          */
326         private void showEndMessage()
327         {
328                 JOptionPane.showMessageDialog(_parentFrame,
329                         I18nManager.getText("dialog.setlanguage.endmessage"),
330                         I18nManager.getText(getNameKey()), JOptionPane.INFORMATION_MESSAGE);
331         }
332 }