use multimaint-merge to make Debian changelogs less ugly
[fw/altos] / altosui / AltosScanUI.java
1 /*
2  * Copyright © 2011 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 javax.swing.table.*;
25 import javax.swing.event.*;
26 import java.io.*;
27 import java.util.*;
28 import java.text.*;
29 import java.util.prefs.*;
30 import java.util.concurrent.*;
31
32 class AltosScanResult {
33         String          callsign;
34         int             serial;
35         int             flight;
36         AltosFrequency  frequency;
37         int             telemetry;
38         
39         boolean interrupted = false;
40         
41         public String toString() {
42                 return String.format("%-9.9s serial %-4d flight %-4d (%s %s)",
43                                      callsign, serial, flight, frequency.toShortString(), Altos.telemetry_name(telemetry));
44         }
45
46         public String toShortString() {
47                 return String.format("%s %d %d %7.3f %d",
48                                      callsign, serial, flight, frequency, telemetry);
49         }
50
51         public AltosScanResult(String in_callsign, int in_serial,
52                                int in_flight, AltosFrequency in_frequency, int in_telemetry) {
53                 callsign = in_callsign;
54                 serial = in_serial;
55                 flight = in_flight;
56                 frequency = in_frequency;
57                 telemetry = in_telemetry;
58         }
59
60         public boolean equals(AltosScanResult other) {
61                 return (callsign.equals(other.callsign) &&
62                         serial == other.serial &&
63                         flight == other.flight &&
64                         frequency.frequency == other.frequency.frequency &&
65                         telemetry == other.telemetry);
66         }
67 }
68
69 class AltosScanResults extends LinkedList<AltosScanResult> implements ListModel {
70         
71         LinkedList<ListDataListener>    listeners = new LinkedList<ListDataListener>();
72
73         public boolean add(AltosScanResult r) {
74                 for (AltosScanResult old : this)
75                         if (old.equals(r))
76                                 return true;
77
78                 super.add(r);
79                 ListDataEvent   de = new ListDataEvent(this,
80                                                        ListDataEvent.INTERVAL_ADDED,
81                                                        this.size() - 2, this.size() - 1);
82                 for (ListDataListener l : listeners)
83                         l.contentsChanged(de);
84                 return true;
85         }
86
87         public void addListDataListener(ListDataListener l) {
88                 listeners.add(l);
89         }
90         
91         public void removeListDataListener(ListDataListener l) {
92                 listeners.remove(l);
93         }
94
95         public AltosScanResult getElementAt(int i) {
96                 return this.get(i);
97         }
98
99         public int getSize() {
100                 return this.size();
101         }
102 }
103
104 public class AltosScanUI
105         extends JDialog
106         implements ActionListener
107 {
108         AltosUI                         owner;
109         AltosDevice                     device;
110         AltosConfigData                 config_data;
111         AltosTelemetryReader            reader;
112         private JList                   list;
113         private JLabel                  scanning_label;
114         private JLabel                  frequency_label;
115         private JLabel                  telemetry_label;
116         private JButton                 cancel_button;
117         private JButton                 monitor_button;
118         private JCheckBox[]             telemetry_boxes;
119         javax.swing.Timer               timer;
120         AltosScanResults                results = new AltosScanResults();
121
122         int                             telemetry;
123
124         final static int                timeout = 1200;
125         TelemetryHandler                handler;
126         Thread                          thread;
127         AltosFrequency[]                frequencies;
128         int                             frequency_index;
129
130         void scan_exception(Exception e) {
131                 if (e instanceof FileNotFoundException) {
132                         JOptionPane.showMessageDialog(owner,
133                                                       String.format("Cannot open device \"%s\"",
134                                                                     device.toShortString()),
135                                                       "Cannot open target device",
136                                                       JOptionPane.ERROR_MESSAGE);
137                 } else if (e instanceof AltosSerialInUseException) {
138                         JOptionPane.showMessageDialog(owner,
139                                                       String.format("Device \"%s\" already in use",
140                                                                     device.toShortString()),
141                                                       "Device in use",
142                                                       JOptionPane.ERROR_MESSAGE);
143                 } else if (e instanceof IOException) {
144                         IOException ee = (IOException) e;
145                         JOptionPane.showMessageDialog(owner,
146                                                       device.toShortString(),
147                                                       ee.getLocalizedMessage(),
148                                                       JOptionPane.ERROR_MESSAGE);
149                 } else {
150                         JOptionPane.showMessageDialog(owner,
151                                                       String.format("Connection to \"%s\" failed",
152                                                                     device.toShortString()),
153                                                       "Connection Failed",
154                                                       JOptionPane.ERROR_MESSAGE);
155                 }
156                 close();
157         }
158
159         class TelemetryHandler implements Runnable {
160
161                 public void run() {
162
163                         boolean interrupted = false;
164
165                         try {
166                                 for (;;) {
167                                         try {
168                                                 AltosRecord     record = reader.read();
169                                                 if (record == null)
170                                                         continue;
171                                                 if ((record.seen & AltosRecord.seen_flight) != 0) {
172                                                         final AltosScanResult   result = new AltosScanResult(record.callsign,
173                                                                                                      record.serial,
174                                                                                                      record.flight,
175                                                                                                      frequencies[frequency_index],
176                                                                                                      telemetry);
177                                                         Runnable r = new Runnable() {
178                                                                         public void run() {
179                                                                                 results.add(result);
180                                                                         }
181                                                                 };
182                                                         SwingUtilities.invokeLater(r);
183                                                 }
184                                         } catch (ParseException pp) {
185                                         } catch (AltosCRCException ce) {
186                                         }
187                                 }
188                         } catch (InterruptedException ee) {
189                                 interrupted = true;
190                         } catch (IOException ie) {
191                         } finally {
192                                 reader.close(interrupted);
193                         }
194                 }
195         }
196
197         void set_label() {
198                 frequency_label.setText(String.format("Frequency: %s", frequencies[frequency_index].toString()));
199                 telemetry_label.setText(String.format("Telemetry: %s", Altos.telemetry_name(telemetry)));
200         }
201
202         void set_telemetry() {
203                 reader.set_telemetry(telemetry);
204         }
205         
206         void set_frequency() throws InterruptedException, TimeoutException {
207                 reader.set_frequency(frequencies[frequency_index].frequency);
208         }
209         
210         void next() throws InterruptedException, TimeoutException {
211                 reader.serial.set_monitor(false);
212                 Thread.sleep(100);
213                 ++frequency_index;
214                 if (frequency_index >= frequencies.length ||
215                     !telemetry_boxes[telemetry - Altos.ao_telemetry_min].isSelected())
216                 {
217                         frequency_index = 0;
218                         do {
219                                 ++telemetry;
220                                 if (telemetry > Altos.ao_telemetry_max)
221                                         telemetry = Altos.ao_telemetry_min;
222                         } while (!telemetry_boxes[telemetry - Altos.ao_telemetry_min].isSelected());
223                         set_telemetry();
224                 }
225                 set_frequency();
226                 set_label();
227                 reader.serial.set_monitor(true);
228         }
229
230
231         void close() {
232                 if (thread != null && thread.isAlive()) {
233                         thread.interrupt();
234                         try {
235                                 thread.join();
236                         } catch (InterruptedException ie) {}
237                 }
238                 thread = null;
239                 if (timer != null)
240                         timer.stop();
241                 setVisible(false);
242                 dispose();
243         }
244
245         void tick_timer() throws InterruptedException, TimeoutException {
246                 next();
247         }
248
249         public void actionPerformed(ActionEvent e) {
250                 String cmd = e.getActionCommand();
251
252                 try {
253                         if (cmd.equals("cancel"))
254                                 close();
255
256                         if (cmd.equals("tick"))
257                                 tick_timer();
258
259                         if (cmd.equals("telemetry")) {
260                                 int k;
261                                 int scanning_telemetry = 0;
262                                 for (k = Altos.ao_telemetry_min; k <= Altos.ao_telemetry_max; k++) {
263                                         int j = k - Altos.ao_telemetry_min;
264                                         if (telemetry_boxes[j].isSelected())
265                                                 scanning_telemetry |= (1 << k);
266                                 }
267                                 if (scanning_telemetry == 0) {
268                                         scanning_telemetry |= (1 << Altos.ao_telemetry_standard);
269                                         telemetry_boxes[Altos.ao_telemetry_standard - Altos.ao_telemetry_min].setSelected(true);
270                                 }
271                                 AltosPreferences.set_scanning_telemetry(scanning_telemetry);
272                         }
273
274                         if (cmd.equals("monitor")) {
275                                 close();
276                                 AltosScanResult r = (AltosScanResult) (list.getSelectedValue());
277                                 if (r != null) {
278                                         if (device != null) {
279                                                 if (reader != null) {
280                                                         reader.set_telemetry(r.telemetry);
281                                                         reader.set_frequency(r.frequency.frequency);
282                                                         reader.save_frequency();
283                                                         owner.telemetry_window(device);
284                                                 }
285                                         }
286                                 }
287                         }
288                 } catch (TimeoutException te) {
289                         close();
290                 } catch (InterruptedException ie) {
291                         close();
292                 }
293         }
294
295         /* A window listener to catch closing events and tell the config code */
296         class ConfigListener extends WindowAdapter {
297                 AltosScanUI     ui;
298
299                 public ConfigListener(AltosScanUI this_ui) {
300                         ui = this_ui;
301                 }
302
303                 public void windowClosing(WindowEvent e) {
304                         ui.actionPerformed(new ActionEvent(e.getSource(),
305                                                            ActionEvent.ACTION_PERFORMED,
306                                                            "close"));
307                 }
308         }
309
310         private boolean open() {
311                 device = AltosDeviceDialog.show(owner, Altos.product_basestation);
312                 if (device == null)
313                         return false;
314                 try {
315                         reader = new AltosTelemetryReader(device);
316                         set_frequency();
317                         set_telemetry();
318                         try {
319                                 Thread.sleep(100);
320                         } catch (InterruptedException ie) {
321                         }
322                         reader.flush();
323                         handler = new TelemetryHandler();
324                         thread = new Thread(handler);
325                         thread.start();
326                         return true;
327                 } catch (FileNotFoundException ee) {
328                         JOptionPane.showMessageDialog(owner,
329                                                       String.format("Cannot open device \"%s\"",
330                                                                     device.toShortString()),
331                                                       "Cannot open target device",
332                                                       JOptionPane.ERROR_MESSAGE);
333                 } catch (AltosSerialInUseException si) {
334                         JOptionPane.showMessageDialog(owner,
335                                                       String.format("Device \"%s\" already in use",
336                                                                     device.toShortString()),
337                                                       "Device in use",
338                                                       JOptionPane.ERROR_MESSAGE);
339                 } catch (IOException ee) {
340                         JOptionPane.showMessageDialog(owner,
341                                                       device.toShortString(),
342                                                       "Unkonwn I/O error",
343                                                       JOptionPane.ERROR_MESSAGE);
344                 } catch (TimeoutException te) {
345                         JOptionPane.showMessageDialog(owner,
346                                                       device.toShortString(),
347                                                       "Timeout error",
348                                                       JOptionPane.ERROR_MESSAGE);
349                 } catch (InterruptedException ie) {
350                         JOptionPane.showMessageDialog(owner,
351                                                       device.toShortString(),
352                                                       "Interrupted exception",
353                                                       JOptionPane.ERROR_MESSAGE);
354                 }
355                 if (reader != null)
356                         reader.close(false);
357                 return false;
358         }
359
360         public AltosScanUI(AltosUI in_owner) {
361
362                 owner = in_owner;
363
364                 frequencies = AltosPreferences.common_frequencies();
365                 frequency_index = 0;
366                 telemetry = Altos.ao_telemetry_min;
367
368                 if (!open())
369                         return;
370
371                 Container               pane = getContentPane();
372                 GridBagConstraints      c = new GridBagConstraints();
373                 Insets                  i = new Insets(4,4,4,4);
374
375                 timer = new javax.swing.Timer(timeout, this);
376                 timer.setActionCommand("tick");
377                 timer.restart();
378
379                 owner = in_owner;
380
381                 pane.setLayout(new GridBagLayout());
382
383                 scanning_label = new JLabel("Scanning:");
384                 frequency_label = new JLabel("");
385                 telemetry_label = new JLabel("");
386                 
387                 set_label();
388
389                 c.fill = GridBagConstraints.HORIZONTAL;
390                 c.anchor = GridBagConstraints.WEST;
391                 c.insets = i;
392                 c.weightx = 1;
393                 c.weighty = 1;
394
395                 c.gridx = 0;
396                 c.gridy = 0;
397                 c.gridwidth = 2;
398
399                 pane.add(scanning_label, c);
400                 c.gridy = 1;
401                 pane.add(frequency_label, c);
402                 c.gridy = 2;
403                 pane.add(telemetry_label, c);
404
405                 int     scanning_telemetry = AltosPreferences.scanning_telemetry();
406                 telemetry_boxes = new JCheckBox[Altos.ao_telemetry_max - Altos.ao_telemetry_min + 1];
407                 for (int k = Altos.ao_telemetry_min; k <= Altos.ao_telemetry_max; k++) {
408                         int j = k - Altos.ao_telemetry_min;
409                         telemetry_boxes[j] = new JCheckBox(Altos.ao_telemetry_name[k]);
410                         c.gridy = 3 + j;
411                         pane.add(telemetry_boxes[j], c);
412                         telemetry_boxes[j].setActionCommand("telemetry");
413                         telemetry_boxes[j].addActionListener(this);
414                         telemetry_boxes[j].setSelected((scanning_telemetry & (1 << k)) != 0);
415                 }
416
417                 int     y_offset = 3 + (Altos.ao_telemetry_max - Altos.ao_telemetry_min + 1);
418                                 
419                 list = new JList(results) {
420                                 //Subclass JList to workaround bug 4832765, which can cause the
421                                 //scroll pane to not let the user easily scroll up to the beginning
422                                 //of the list.  An alternative would be to set the unitIncrement
423                                 //of the JScrollBar to a fixed value. You wouldn't get the nice
424                                 //aligned scrolling, but it should work.
425                                 public int getScrollableUnitIncrement(Rectangle visibleRect,
426                                                                       int orientation,
427                                                                       int direction) {
428                                         int row;
429                                         if (orientation == SwingConstants.VERTICAL &&
430                                             direction < 0 && (row = getFirstVisibleIndex()) != -1) {
431                                                 Rectangle r = getCellBounds(row, row);
432                                                 if ((r.y == visibleRect.y) && (row != 0))  {
433                                                         Point loc = r.getLocation();
434                                                         loc.y--;
435                                                         int prevIndex = locationToIndex(loc);
436                                                         Rectangle prevR = getCellBounds(prevIndex, prevIndex);
437
438                                                         if (prevR == null || prevR.y >= r.y) {
439                                                                 return 0;
440                                                         }
441                                                         return prevR.height;
442                                                 }
443                                         }
444                                         return super.getScrollableUnitIncrement(
445                                                 visibleRect, orientation, direction);
446                                 }
447                         };
448
449                 list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
450                 list.setLayoutOrientation(JList.HORIZONTAL_WRAP);
451                 list.setVisibleRowCount(-1);
452
453                 list.addMouseListener(new MouseAdapter() {
454                                  public void mouseClicked(MouseEvent e) {
455                                          if (e.getClickCount() == 2) {
456                                                  monitor_button.doClick(); //emulate button click
457                                          }
458                                  }
459                         });
460                 JScrollPane listScroller = new JScrollPane(list);
461                 listScroller.setPreferredSize(new Dimension(400, 80));
462                 listScroller.setAlignmentX(LEFT_ALIGNMENT);
463
464                 //Create a container so that we can add a title around
465                 //the scroll pane.  Can't add a title directly to the
466                 //scroll pane because its background would be white.
467                 //Lay out the label and scroll pane from top to bottom.
468                 JPanel listPane = new JPanel();
469                 listPane.setLayout(new BoxLayout(listPane, BoxLayout.PAGE_AXIS));
470
471                 JLabel label = new JLabel("Select Device");
472                 label.setLabelFor(list);
473                 listPane.add(label);
474                 listPane.add(Box.createRigidArea(new Dimension(0,5)));
475                 listPane.add(listScroller);
476                 listPane.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
477
478                 c.fill = GridBagConstraints.BOTH;
479                 c.anchor = GridBagConstraints.CENTER;
480                 c.insets = i;
481                 c.weightx = 1;
482                 c.weighty = 1;
483
484                 c.gridx = 0;
485                 c.gridy = y_offset;
486                 c.gridwidth = 2;
487                 c.anchor = GridBagConstraints.CENTER;
488
489                 pane.add(listPane, c);
490
491                 cancel_button = new JButton("Cancel");
492                 cancel_button.addActionListener(this);
493                 cancel_button.setActionCommand("cancel");
494
495                 c.fill = GridBagConstraints.NONE;
496                 c.anchor = GridBagConstraints.CENTER;
497                 c.insets = i;
498                 c.weightx = 1;
499                 c.weighty = 1;
500
501                 c.gridx = 0;
502                 c.gridy = y_offset + 1;
503                 c.gridwidth = 1;
504                 c.anchor = GridBagConstraints.CENTER;
505
506                 pane.add(cancel_button, c);
507
508                 monitor_button = new JButton("Monitor");
509                 monitor_button.addActionListener(this);
510                 monitor_button.setActionCommand("monitor");
511
512                 c.fill = GridBagConstraints.NONE;
513                 c.anchor = GridBagConstraints.CENTER;
514                 c.insets = i;
515                 c.weightx = 1;
516                 c.weighty = 1;
517
518                 c.gridx = 1;
519                 c.gridy = y_offset + 1;
520                 c.gridwidth = 1;
521                 c.anchor = GridBagConstraints.CENTER;
522
523                 pane.add(monitor_button, c);
524
525                 pack();
526                 setLocationRelativeTo(owner);
527
528                 addWindowListener(new ConfigListener(this));
529
530                 setVisible(true);
531         }
532 }