altosui: Match directories in hex file matcher
[fw/altos] / altosui / AltosFlashUI.java
1 /*
2  * Copyright © 2010 Keith Packard <keithp@keithp.com>
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; version 2 of the License.
7  *
8  * This program is distributed in the hope that it will be useful, but
9  * WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License along
14  * with this program; if not, write to the Free Software Foundation, Inc.,
15  * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
16  */
17
18 package altosui;
19
20 import java.awt.*;
21 import java.awt.event.*;
22 import javax.swing.*;
23 import javax.swing.filechooser.FileNameExtensionFilter;
24 import java.io.*;
25 import java.util.concurrent.*;
26 import org.altusmetrum.altoslib_2.*;
27 import org.altusmetrum.altosuilib_1.*;
28
29 public class AltosFlashUI
30         extends AltosUIDialog
31         implements ActionListener
32 {
33         Container       pane;
34         Box             box;
35         JLabel          serial_label;
36         JLabel          serial_value;
37         JLabel          file_label;
38         JLabel          file_value;
39         JProgressBar    pbar;
40         JButton         cancel;
41
42         JFrame          frame;
43
44         // Hex file with rom image
45         File            file;
46
47         // Debug connection
48         AltosDevice     device;
49
50         AltosLink       link;
51
52         // Desired Rom configuration
53         AltosRomconfig  rom_config;
54
55         // Flash controller
56         AltosProgrammer programmer;
57
58         private static String[] pair_programmed = {
59                 "teleballoon",
60                 "telebt",
61                 "teledongle",
62                 "telefire",
63                 "telemetrum-v0",
64                 "telemetrum-v1",
65                 "telemini",
66                 "telenano",
67                 "teleshield",
68                 "teleterra"
69         };
70
71         private boolean is_pair_programmed() {
72                 String  name = file.getName();
73                 for (int i = 0; i < pair_programmed.length; i++) {
74                         if (name.startsWith(pair_programmed[i]))
75                                 return true;
76                 }
77                 return false;
78         }
79
80         public void actionPerformed(ActionEvent e) {
81                 if (e.getSource() == cancel) {
82                         if (programmer != null)
83                                 programmer.abort();
84                         setVisible(false);
85                         dispose();
86                 } else {
87                         String  cmd = e.getActionCommand();
88                         if (e.getID() == -1) {
89                                 JOptionPane.showMessageDialog(frame,
90                                                               e.getActionCommand(),
91                                                               file.toString(),
92                                                               JOptionPane.ERROR_MESSAGE);
93                                 setVisible(false);
94                                 dispose();
95                         } else if (cmd.equals("done")) {
96                                 setVisible(false);
97                                 dispose();
98                         } else if (cmd.equals("start")) {
99                                 setVisible(true);
100                         } else {
101                                 pbar.setValue(e.getID());
102                                 pbar.setString(cmd);
103                         }
104                 }
105         }
106
107         public void build_dialog() {
108                 GridBagConstraints c;
109                 Insets il = new Insets(4,4,4,4);
110                 Insets ir = new Insets(4,4,4,4);
111
112                 pane = getContentPane();
113                 pane.setLayout(new GridBagLayout());
114
115                 c = new GridBagConstraints();
116                 c.gridx = 0; c.gridy = 0;
117                 c.fill = GridBagConstraints.NONE;
118                 c.anchor = GridBagConstraints.LINE_START;
119                 c.insets = il;
120                 serial_label = new JLabel("Serial:");
121                 pane.add(serial_label, c);
122
123                 c = new GridBagConstraints();
124                 c.gridx = 1; c.gridy = 0;
125                 c.fill = GridBagConstraints.HORIZONTAL;
126                 c.weightx = 1;
127                 c.anchor = GridBagConstraints.LINE_START;
128                 c.insets = ir;
129                 serial_value = new JLabel("");
130                 pane.add(serial_value, c);
131
132                 c = new GridBagConstraints();
133                 c.fill = GridBagConstraints.NONE;
134                 c.gridx = 0; c.gridy = 1;
135                 c.anchor = GridBagConstraints.LINE_START;
136                 c.insets = il;
137                 file_label = new JLabel("File:");
138                 pane.add(file_label, c);
139
140                 c = new GridBagConstraints();
141                 c.fill = GridBagConstraints.HORIZONTAL;
142                 c.weightx = 1;
143                 c.gridx = 1; c.gridy = 1;
144                 c.anchor = GridBagConstraints.LINE_START;
145                 c.insets = ir;
146                 file_value = new JLabel(file.toString());
147                 pane.add(file_value, c);
148
149                 pbar = new JProgressBar();
150                 pbar.setMinimum(0);
151                 pbar.setMaximum(100);
152                 pbar.setValue(0);
153                 pbar.setString("");
154                 pbar.setStringPainted(true);
155                 pbar.setPreferredSize(new Dimension(600, 20));
156                 c = new GridBagConstraints();
157                 c.fill = GridBagConstraints.HORIZONTAL;
158                 c.anchor = GridBagConstraints.CENTER;
159                 c.gridx = 0; c.gridy = 2;
160                 c.gridwidth = GridBagConstraints.REMAINDER;
161                 Insets ib = new Insets(4,4,4,4);
162                 c.insets = ib;
163                 pane.add(pbar, c);
164
165                 cancel = new JButton("Cancel");
166                 c = new GridBagConstraints();
167                 c.fill = GridBagConstraints.NONE;
168                 c.anchor = GridBagConstraints.CENTER;
169                 c.gridx = 0; c.gridy = 3;
170                 c.gridwidth = GridBagConstraints.REMAINDER;
171                 Insets ic = new Insets(4,4,4,4);
172                 c.insets = ic;
173                 pane.add(cancel, c);
174                 cancel.addActionListener(this);
175                 pack();
176                 setLocationRelativeTo(frame);
177         }
178
179         void set_serial(int serial_number) {
180                 serial_value.setText(String.format("%d", serial_number));
181         }
182
183         static class AltosHexfileFilter extends javax.swing.filechooser.FileFilter {
184                 int product;
185                 String head;
186                 String description;
187
188                 public AltosHexfileFilter(int product, String head, String description) {
189                         this.product = product;
190                         this.head = head;
191                         this.description = description;
192                 }
193
194                 public boolean accept(File file) {
195                         return !file.isFile() || (file.getName().startsWith(head) && file.getName().endsWith(".ihx"));
196                 }
197
198                 public String getDescription() {
199                         return description;
200                 }
201         }
202
203         static AltosHexfileFilter[] filters = {
204                 new AltosHexfileFilter(AltosLib.product_telemetrum, "telemetrum", "TeleMetrum Image"),
205                 new AltosHexfileFilter(AltosLib.product_teledongle, "teledongle", "TeleDongle Image"),
206                 new AltosHexfileFilter(AltosLib.product_telemega, "telemega", "TeleMega Image"),
207                 new AltosHexfileFilter(AltosLib.product_easymini, "easymini", "EasyMini Image"),
208         };
209
210         boolean select_source_file() {
211                 JFileChooser    hexfile_chooser = new JFileChooser();
212
213                 File firmwaredir = AltosUIPreferences.firmwaredir();
214                 if (firmwaredir != null)
215                         hexfile_chooser.setCurrentDirectory(firmwaredir);
216
217                 hexfile_chooser.setDialogTitle("Select Flash Image");
218
219                 for (int i = 0; i < filters.length; i++) {
220                         hexfile_chooser.addChoosableFileFilter(filters[i]);
221                 }
222                 javax.swing.filechooser.FileFilter ihx_filter = new FileNameExtensionFilter("Flash Image", "ihx");
223                 hexfile_chooser.addChoosableFileFilter(ihx_filter);
224                 hexfile_chooser.setFileFilter(ihx_filter);
225                 
226                 if (!device.matchProduct(AltosLib.product_altusmetrum)) {
227                         for (int i = 0; i < filters.length; i++) {
228                                 if (device != null && device.matchProduct(filters[i].product))
229                                         hexfile_chooser.setFileFilter(filters[i]);
230                         }
231                 }
232
233                 int returnVal = hexfile_chooser.showOpenDialog(frame);
234
235                 if (returnVal != JFileChooser.APPROVE_OPTION)
236                         return false;
237                 file = hexfile_chooser.getSelectedFile();
238                 if (file == null)
239                         return false;
240                 AltosUIPreferences.set_firmwaredir(file.getParentFile());
241                 
242                 return true;
243         }
244
245         boolean select_device() {
246                 int     product = Altos.product_any;
247
248                 device = AltosDeviceUIDialog.show(frame, Altos.product_any);
249
250                 if (device == null)
251                         return false;
252                 return true;
253         }
254
255         boolean update_rom_config_info(AltosRomconfig existing_config) {
256                 AltosRomconfig  new_config;
257                 new_config = AltosRomconfigUI.show(frame, existing_config);
258                 if (new_config == null)
259                         return false;
260                 rom_config = new_config;
261                 set_serial(rom_config.serial_number);
262                 setVisible(true);
263                 return true;
264         }
265
266         void exception (Exception e) {
267                 if (e instanceof FileNotFoundException) {
268                         JOptionPane.showMessageDialog(frame,
269                                                       ((FileNotFoundException) e).getMessage(),
270                                                       "Cannot open file",
271                                                       JOptionPane.ERROR_MESSAGE);
272                 } else if (e instanceof AltosSerialInUseException) {
273                         JOptionPane.showMessageDialog(frame,
274                                                       String.format("Device \"%s\" already in use",
275                                                                     device.toShortString()),
276                                                       "Device in use",
277                                                       JOptionPane.ERROR_MESSAGE);
278                 } else if (e instanceof IOException) {
279                         JOptionPane.showMessageDialog(frame,
280                                                       e.getMessage(),
281                                                       file.toString(),
282                                                       JOptionPane.ERROR_MESSAGE);
283                 }
284         }
285
286         class flash_task implements Runnable, AltosFlashListener {
287                 AltosFlashUI    ui;
288                 Thread          t;
289                 AltosProgrammer programmer;
290
291                 public void position(String in_s, int in_percent) {
292                         final String s = in_s;
293                         final int percent = in_percent;
294                         Runnable r = new Runnable() {
295                                         public void run() {
296                                                 try {
297                                                         ui.actionPerformed(new ActionEvent(this,
298                                                                                            percent,
299                                                                                            s));
300                                                 } catch (Exception ex) {
301                                                 }
302                                         }
303                                 };
304                         SwingUtilities.invokeLater(r);
305                 }
306
307                 public void run () {
308                         try {
309                                 if (ui.is_pair_programmed())
310                                         programmer = new AltosFlash(ui.file, link, this);
311                                 else
312                                         programmer = new AltosSelfFlash(ui.file, link, this);
313
314                                 final AltosRomconfig    current_config = programmer.romconfig();
315
316                                 final Semaphore await_rom_config = new Semaphore(0);
317                                 SwingUtilities.invokeLater(new Runnable() {
318                                                 public void run() {
319                                                         ui.programmer = programmer;
320                                                         ui.update_rom_config_info(current_config);
321                                                         await_rom_config.release();
322                                                 }
323                                         });
324                                 await_rom_config.acquire();
325
326                                 if (ui.rom_config != null) {
327                                         programmer.set_romconfig(ui.rom_config);
328                                         programmer.flash();
329                                 }
330                         } catch (InterruptedException ee) {
331                                 final Exception e = ee;
332                                 SwingUtilities.invokeLater(new Runnable() {
333                                                 public void run() {
334                                                         ui.exception(e);
335                                                 }
336                                         });
337                         } catch (IOException ee) {
338                                 final Exception e = ee;
339                                 SwingUtilities.invokeLater(new Runnable() {
340                                                 public void run() {
341                                                         ui.exception(e);
342                                                 }
343                                         });
344                         } finally {
345                                 if (programmer != null)
346                                         programmer.close();
347                         }
348                 }
349
350                 public flash_task(AltosFlashUI in_ui) {
351                         ui = in_ui;
352                         t = new Thread(this);
353                         t.start();
354                 }
355         }
356
357         flash_task      flasher;
358
359         private boolean open_device() {
360                 try {
361                         link = new AltosSerial(device);
362                         if (is_pair_programmed())
363                                 return true;
364
365                         if (link == null)
366                                 throw new IOException(String.format("%s: open failed", device.toShortString()));
367
368                         while (!link.is_loader()) {
369                                 link.to_loader();
370
371                                 java.util.List<AltosDevice> devices = AltosUSBDevice.list(AltosLib.product_altusmetrum);
372                                 if (devices.size() == 1)
373                                         device = devices.get(0);
374                                 else {
375                                         device = AltosDeviceUIDialog.show(frame, AltosLib.product_altusmetrum);
376                                         if (device == null)
377                                                 return false;
378                                 }
379                                 link = new AltosSerial(device);
380                         }
381                         return true;
382                 } catch (AltosSerialInUseException ee) {
383                         exception(ee);
384                 } catch (FileNotFoundException fe) {
385                         exception(fe);
386                 } catch (IOException ie) {
387                         exception (ie);
388                 }
389                 return false;
390         }
391
392         /*
393          * Execute the steps for flashing
394          * a device. Note that this returns immediately;
395          * this dialog is not modal
396          */
397         void showDialog() {
398                 if (!select_device())
399                         return;
400                 if (!select_source_file())
401                         return;
402                 if (!open_device())
403                         return;
404                 build_dialog();
405                 flash_task      f = new flash_task(this);
406         }
407
408         static void show(JFrame frame) {
409                 AltosFlashUI    ui = new AltosFlashUI(frame);
410
411                 ui.showDialog();
412         }
413
414         public AltosFlashUI(JFrame in_frame) {
415                 super(in_frame, "Program Altusmetrum Device", false);
416
417                 frame = in_frame;
418         }
419 }