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