Merge branch 'preload-maps'
[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         int     channel;
37         int     telemetry;
38         
39         boolean interrupted = false;
40         
41         public String toString() {
42                 return String.format("%-9.9s serial %-4d flight %-4d (channel %-2d %s)",
43                                      callsign, serial, flight, channel, Altos.telemetry_name(telemetry));
44         }
45
46         public String toShortString() {
47                 return String.format("%s %d %d %d %d",
48                                      callsign, serial, flight, channel, telemetry);
49         }
50
51         public AltosScanResult(String in_callsign, int in_serial,
52                                int in_flight, int in_channel, int in_telemetry) {
53                 callsign = in_callsign;
54                 serial = in_serial;
55                 flight = in_flight;
56                 channel = in_channel;
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                         channel == other.channel &&
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         AltosTelemetryReader            reader;
111         private JList                   list;
112         private JLabel                  scanning_label;
113         private JButton                 cancel_button;
114         private JButton                 monitor_button;
115         javax.swing.Timer               timer;
116         AltosScanResults                results = new AltosScanResults();
117
118         int                             telemetry;
119         int                             channel;
120
121         final static int                timeout = 1200;
122         TelemetryHandler                handler;
123         Thread                          thread;
124
125         void scan_exception(Exception e) {
126                 if (e instanceof FileNotFoundException) {
127                         JOptionPane.showMessageDialog(owner,
128                                                       String.format("Cannot open device \"%s\"",
129                                                                     device.toShortString()),
130                                                       "Cannot open target device",
131                                                       JOptionPane.ERROR_MESSAGE);
132                 } else if (e instanceof AltosSerialInUseException) {
133                         JOptionPane.showMessageDialog(owner,
134                                                       String.format("Device \"%s\" already in use",
135                                                                     device.toShortString()),
136                                                       "Device in use",
137                                                       JOptionPane.ERROR_MESSAGE);
138                 } else if (e instanceof IOException) {
139                         IOException ee = (IOException) e;
140                         JOptionPane.showMessageDialog(owner,
141                                                       device.toShortString(),
142                                                       ee.getLocalizedMessage(),
143                                                       JOptionPane.ERROR_MESSAGE);
144                 } else {
145                         JOptionPane.showMessageDialog(owner,
146                                                       String.format("Connection to \"%s\" failed",
147                                                                     device.toShortString()),
148                                                       "Connection Failed",
149                                                       JOptionPane.ERROR_MESSAGE);
150                 }
151                 close();
152         }
153
154         class TelemetryHandler implements Runnable {
155
156                 public void run() {
157
158                         boolean interrupted = false;
159
160                         try {
161                                 for (;;) {
162                                         try {
163                                                 AltosRecord     record = reader.read();
164                                                 if (record == null)
165                                                         continue;
166                                                 if ((record.seen & AltosRecord.seen_flight) != 0) {
167                                                         final AltosScanResult   result = new AltosScanResult(record.callsign,
168                                                                                                      record.serial,
169                                                                                                      record.flight,
170                                                                                                      channel,
171                                                                                                      telemetry);
172                                                         Runnable r = new Runnable() {
173                                                                         public void run() {
174                                                                                 results.add(result);
175                                                                         }
176                                                                 };
177                                                         SwingUtilities.invokeLater(r);
178                                                 }
179                                         } catch (ParseException pp) {
180                                         } catch (AltosCRCException ce) {
181                                         }
182                                 }
183                         } catch (InterruptedException ee) {
184                                 interrupted = true;
185                         } catch (IOException ie) {
186                         } finally {
187                                 reader.close(interrupted);
188                         }
189                 }
190         }
191
192         void set_label() {
193                 scanning_label.setText(String.format("Scanning: channel %d %s",
194                                                      channel,
195                                                      Altos.telemetry_name(telemetry)));
196         }
197
198         void next() {
199                 reader.serial.set_monitor(false);
200                 try {
201                         Thread.sleep(100);
202                 } catch (InterruptedException ie){
203                 }
204                 ++channel;
205                 if (channel > 9) {
206                         channel = 0;
207                         ++telemetry;
208                         if (telemetry > Altos.ao_telemetry_max)
209                                 telemetry = Altos.ao_telemetry_min;
210                         reader.serial.set_telemetry(telemetry);
211                 }
212                 reader.serial.set_channel(channel);
213                 set_label();
214                 reader.serial.set_monitor(true);
215         }
216
217
218         void close() {
219                 if (thread != null && thread.isAlive()) {
220                         thread.interrupt();
221                         try {
222                                 thread.join();
223                         } catch (InterruptedException ie) {}
224                 }
225                 thread = null;
226                 if (timer != null)
227                         timer.stop();
228                 setVisible(false);
229                 dispose();
230         }
231
232         void tick_timer() {
233                 next();
234         }
235
236         public void actionPerformed(ActionEvent e) {
237                 String cmd = e.getActionCommand();
238
239                 if (cmd.equals("cancel"))
240                         close();
241
242                 if (cmd.equals("tick"))
243                         tick_timer();
244
245                 if (cmd.equals("monitor")) {
246                         close();
247                         AltosScanResult r = (AltosScanResult) (list.getSelectedValue());
248                         if (r != null) {
249                                 if (device != null) {
250                                         if (reader != null) {
251                                                 reader.set_telemetry(r.telemetry);
252                                                 reader.set_channel(r.channel);
253                                                 owner.telemetry_window(device);
254                                         }
255                                 }
256                         }
257                 }
258         }
259
260         /* A window listener to catch closing events and tell the config code */
261         class ConfigListener extends WindowAdapter {
262                 AltosScanUI     ui;
263
264                 public ConfigListener(AltosScanUI this_ui) {
265                         ui = this_ui;
266                 }
267
268                 public void windowClosing(WindowEvent e) {
269                         ui.actionPerformed(new ActionEvent(e.getSource(),
270                                                            ActionEvent.ACTION_PERFORMED,
271                                                            "close"));
272                 }
273         }
274
275         private boolean open() {
276                 device = AltosDeviceDialog.show(owner, Altos.product_basestation);
277                 if (device == null)
278                         return false;
279                 try {
280                         reader = new AltosTelemetryReader(device);
281                         reader.serial.set_channel(channel);
282                         reader.serial.set_telemetry(telemetry);
283                         try {
284                                 Thread.sleep(100);
285                         } catch (InterruptedException ie) {
286                         }
287                         reader.flush();
288                         handler = new TelemetryHandler();
289                         thread = new Thread(handler);
290                         thread.start();
291                         return true;
292                 } catch (FileNotFoundException ee) {
293                         JOptionPane.showMessageDialog(owner,
294                                                       String.format("Cannot open device \"%s\"",
295                                                                     device.toShortString()),
296                                                       "Cannot open target device",
297                                                       JOptionPane.ERROR_MESSAGE);
298                 } catch (AltosSerialInUseException si) {
299                         JOptionPane.showMessageDialog(owner,
300                                                       String.format("Device \"%s\" already in use",
301                                                                     device.toShortString()),
302                                                       "Device in use",
303                                                       JOptionPane.ERROR_MESSAGE);
304                 } catch (IOException ee) {
305                         JOptionPane.showMessageDialog(owner,
306                                                       device.toShortString(),
307                                                       "Unkonwn I/O error",
308                                                       JOptionPane.ERROR_MESSAGE);
309                 }
310                 if (reader != null)
311                         reader.close(false);
312                 return false;
313         }
314
315         public AltosScanUI(AltosUI in_owner) {
316
317                 owner = in_owner;
318
319                 channel = 0;
320                 telemetry = Altos.ao_telemetry_min;
321
322                 if (!open())
323                         return;
324
325                 Container               pane = getContentPane();
326                 GridBagConstraints      c = new GridBagConstraints();
327                 Insets                  i = new Insets(4,4,4,4);
328
329                 timer = new javax.swing.Timer(timeout, this);
330                 timer.setActionCommand("tick");
331                 timer.restart();
332
333                 owner = in_owner;
334
335                 pane.setLayout(new GridBagLayout());
336
337                 scanning_label = new JLabel("Scanning:");
338                 
339                 set_label();
340
341                 c.fill = GridBagConstraints.NONE;
342                 c.anchor = GridBagConstraints.CENTER;
343                 c.insets = i;
344                 c.weightx = 1;
345                 c.weighty = 1;
346
347                 c.gridx = 0;
348                 c.gridy = 0;
349                 c.gridwidth = 2;
350                 c.anchor = GridBagConstraints.CENTER;
351
352                 pane.add(scanning_label, c);
353
354                 list = new JList(results) {
355                                 //Subclass JList to workaround bug 4832765, which can cause the
356                                 //scroll pane to not let the user easily scroll up to the beginning
357                                 //of the list.  An alternative would be to set the unitIncrement
358                                 //of the JScrollBar to a fixed value. You wouldn't get the nice
359                                 //aligned scrolling, but it should work.
360                                 public int getScrollableUnitIncrement(Rectangle visibleRect,
361                                                                       int orientation,
362                                                                       int direction) {
363                                         int row;
364                                         if (orientation == SwingConstants.VERTICAL &&
365                                             direction < 0 && (row = getFirstVisibleIndex()) != -1) {
366                                                 Rectangle r = getCellBounds(row, row);
367                                                 if ((r.y == visibleRect.y) && (row != 0))  {
368                                                         Point loc = r.getLocation();
369                                                         loc.y--;
370                                                         int prevIndex = locationToIndex(loc);
371                                                         Rectangle prevR = getCellBounds(prevIndex, prevIndex);
372
373                                                         if (prevR == null || prevR.y >= r.y) {
374                                                                 return 0;
375                                                         }
376                                                         return prevR.height;
377                                                 }
378                                         }
379                                         return super.getScrollableUnitIncrement(
380                                                 visibleRect, orientation, direction);
381                                 }
382                         };
383
384                 list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
385                 list.setLayoutOrientation(JList.HORIZONTAL_WRAP);
386                 list.setVisibleRowCount(-1);
387
388                 list.addMouseListener(new MouseAdapter() {
389                                  public void mouseClicked(MouseEvent e) {
390                                          if (e.getClickCount() == 2) {
391                                                  monitor_button.doClick(); //emulate button click
392                                          }
393                                  }
394                         });
395                 JScrollPane listScroller = new JScrollPane(list);
396                 listScroller.setPreferredSize(new Dimension(400, 80));
397                 listScroller.setAlignmentX(LEFT_ALIGNMENT);
398
399                 //Create a container so that we can add a title around
400                 //the scroll pane.  Can't add a title directly to the
401                 //scroll pane because its background would be white.
402                 //Lay out the label and scroll pane from top to bottom.
403                 JPanel listPane = new JPanel();
404                 listPane.setLayout(new BoxLayout(listPane, BoxLayout.PAGE_AXIS));
405
406                 JLabel label = new JLabel("Select Device");
407                 label.setLabelFor(list);
408                 listPane.add(label);
409                 listPane.add(Box.createRigidArea(new Dimension(0,5)));
410                 listPane.add(listScroller);
411                 listPane.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
412
413                 c.fill = GridBagConstraints.BOTH;
414                 c.anchor = GridBagConstraints.CENTER;
415                 c.insets = i;
416                 c.weightx = 1;
417                 c.weighty = 1;
418
419                 c.gridx = 0;
420                 c.gridy = 1;
421                 c.gridwidth = 2;
422                 c.anchor = GridBagConstraints.CENTER;
423
424                 pane.add(listPane, c);
425
426                 cancel_button = new JButton("Cancel");
427                 cancel_button.addActionListener(this);
428                 cancel_button.setActionCommand("cancel");
429
430                 c.fill = GridBagConstraints.NONE;
431                 c.anchor = GridBagConstraints.CENTER;
432                 c.insets = i;
433                 c.weightx = 1;
434                 c.weighty = 1;
435
436                 c.gridx = 0;
437                 c.gridy = 2;
438                 c.gridwidth = 1;
439                 c.anchor = GridBagConstraints.CENTER;
440
441                 pane.add(cancel_button, c);
442
443                 monitor_button = new JButton("Monitor");
444                 monitor_button.addActionListener(this);
445                 monitor_button.setActionCommand("monitor");
446
447                 c.fill = GridBagConstraints.NONE;
448                 c.anchor = GridBagConstraints.CENTER;
449                 c.insets = i;
450                 c.weightx = 1;
451                 c.weighty = 1;
452
453                 c.gridx = 1;
454                 c.gridy = 2;
455                 c.gridwidth = 1;
456                 c.anchor = GridBagConstraints.CENTER;
457
458                 pane.add(monitor_button, c);
459
460                 pack();
461                 setLocationRelativeTo(owner);
462
463                 addWindowListener(new ConfigListener(this));
464
465                 setVisible(true);
466         }
467 }