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