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