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