Bump java lib versions to 13
[fw/altos] / altosuilib / 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; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License along
15  * with this program; if not, write to the Free Software Foundation, Inc.,
16  * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
17  */
18
19 package org.altusmetrum.altosuilib_13;
20
21 import java.awt.*;
22 import java.awt.event.*;
23 import javax.swing.*;
24 import javax.swing.event.*;
25 import java.io.*;
26 import java.util.*;
27 import java.text.*;
28 import java.util.concurrent.*;
29 import org.altusmetrum.altoslib_13.*;
30
31 class AltosScanResult {
32         String          callsign;
33         int             serial;
34         int             flight;
35         AltosFrequency  frequency;
36         int             telemetry;
37         int             rate;
38
39         boolean interrupted = false;
40
41         public String toString() {
42                 return String.format("%-9.9s serial %-4d flight %-4d (%s %s %d)",
43                                      callsign, serial, flight,
44                                      frequency.toShortString(),
45                                      AltosLib.telemetry_name(telemetry),
46                                      AltosLib.ao_telemetry_rate_values[rate]);
47         }
48
49         public String toShortString() {
50                 return String.format("%s %d %d %7.3f %d %d",
51                                      callsign, serial, flight, frequency, telemetry, rate);
52         }
53
54         public AltosScanResult(String in_callsign, int in_serial,
55                                int in_flight, AltosFrequency in_frequency,
56                                int in_telemetry,
57                                int in_rate) {
58                 callsign = in_callsign;
59                 serial = in_serial;
60                 flight = in_flight;
61                 frequency = in_frequency;
62                 telemetry = in_telemetry;
63                 rate = in_rate;
64         }
65
66         public int hashCode() {
67                 return serial ^ frequency.hashCode() ^ telemetry ^ rate;
68         }
69
70         public boolean equals(Object o) {
71                 if (o == null)
72                         return false;
73                 if (!(o instanceof AltosScanResult))
74                         return false;
75                 AltosScanResult other = (AltosScanResult) o;
76                 return (serial == other.serial &&
77                         frequency.equals(other.frequency) &&
78                         telemetry == other.telemetry &&
79                         rate == other.rate);
80         }
81
82         public boolean up_to_date(AltosScanResult other) {
83                 if (flight == 0 && other.flight != 0) {
84                         flight = other.flight;
85                         return false;
86                 }
87                 if (callsign.equals("N0CALL") && !other.callsign.equals("N0CALL")) {
88                         callsign = other.callsign;
89                         return false;
90                 }
91                 return true;
92         }
93 }
94
95 class AltosScanResults extends LinkedList<AltosScanResult> implements ListModel<AltosScanResult> {
96
97         LinkedList<ListDataListener>    listeners = new LinkedList<ListDataListener>();
98
99         void changed(ListDataEvent de) {
100                 for (ListDataListener l : listeners)
101                         l.contentsChanged(de);
102         }
103
104         public boolean add(AltosScanResult r) {
105                 int i = 0;
106                 for (AltosScanResult old : this) {
107                         if (old.equals(r)) {
108                                 if (!old.up_to_date(r))
109                                         changed (new ListDataEvent(this,
110                                                                    ListDataEvent.CONTENTS_CHANGED,
111                                                                    i, i));
112                                 return true;
113                         }
114                         i++;
115                 }
116
117                 super.add(r);
118                 changed(new ListDataEvent(this,
119                                           ListDataEvent.INTERVAL_ADDED,
120                                           this.size() - 2, this.size() - 1));
121                 return true;
122         }
123
124         public void addListDataListener(ListDataListener l) {
125                 listeners.add(l);
126         }
127
128         public void removeListDataListener(ListDataListener l) {
129                 listeners.remove(l);
130         }
131
132         public AltosScanResult getElementAt(int i) {
133                 return this.get(i);
134         }
135
136         public int getSize() {
137                 return this.size();
138         }
139 }
140
141 public class AltosScanUI
142         extends AltosUIDialog
143         implements ActionListener
144 {
145         AltosUIFrame                    owner;
146         AltosDevice                     device;
147         AltosConfigData                 config_data;
148         AltosTelemetryReader            reader;
149         private JList<AltosScanResult>  list;
150         private JLabel                  scanning_label;
151         private JLabel                  frequency_label;
152         private JLabel                  telemetry_label;
153         private JLabel                  rate_label;
154         private JButton                 cancel_button;
155         private JButton                 monitor_button;
156         private JCheckBox[]             telemetry_boxes;
157         private JCheckBox[]             rate_boxes;
158         javax.swing.Timer               timer;
159         AltosScanResults                results = new AltosScanResults();
160
161         int                             telemetry;
162         boolean                         select_telemetry = false;
163
164         int                             rate;
165         boolean                         select_rate = false;
166
167         final static int                timeout = 1200;
168         TelemetryHandler                handler;
169         Thread                          thread;
170         AltosFrequency[]                frequencies;
171         int                             frequency_index;
172         int                             packet_count;
173         int                             tick_count;
174
175         void scan_exception(Exception e) {
176                 if (e instanceof FileNotFoundException) {
177                         JOptionPane.showMessageDialog(owner,
178                                                       ((FileNotFoundException) e).getMessage(),
179                                                       "Cannot open target device",
180                                                       JOptionPane.ERROR_MESSAGE);
181                 } else if (e instanceof AltosSerialInUseException) {
182                         JOptionPane.showMessageDialog(owner,
183                                                       String.format("Device \"%s\" already in use",
184                                                                     device.toShortString()),
185                                                       "Device in use",
186                                                       JOptionPane.ERROR_MESSAGE);
187                 } else if (e instanceof IOException) {
188                         IOException ee = (IOException) e;
189                         JOptionPane.showMessageDialog(owner,
190                                                       device.toShortString(),
191                                                       ee.getLocalizedMessage(),
192                                                       JOptionPane.ERROR_MESSAGE);
193                 } else {
194                         JOptionPane.showMessageDialog(owner,
195                                                       String.format("Connection to \"%s\" failed",
196                                                                     device.toShortString()),
197                                                       "Connection Failed",
198                                                       JOptionPane.ERROR_MESSAGE);
199                 }
200                 close();
201         }
202
203         class TelemetryHandler implements Runnable {
204
205                 public void run() {
206
207                         boolean interrupted = false;
208
209                         try {
210                                 for (;;) {
211                                         try {
212                                                 AltosState      state = reader.read();
213                                                 if (state == null)
214                                                         continue;
215                                                 packet_count++;
216                                                 AltosCalData    cal_data = state.cal_data();
217                                                 if (cal_data.flight != AltosLib.MISSING) {
218                                                         final AltosScanResult   result = new AltosScanResult(cal_data.callsign,
219                                                                                                              cal_data.serial,
220                                                                                                              cal_data.flight,
221                                                                                                              frequencies[frequency_index],
222                                                                                                              telemetry,
223                                                                                                              rate);
224                                                         Runnable r = new Runnable() {
225                                                                         public void run() {
226                                                                                 results.add(result);
227                                                                         }
228                                                                 };
229                                                         SwingUtilities.invokeLater(r);
230                                                 }
231                                         } catch (ParseException pp) {
232                                         } catch (AltosCRCException ce) {
233                                         }
234                                 }
235                         } catch (InterruptedException ee) {
236                                 interrupted = true;
237                         } catch (IOException ie) {
238                         } finally {
239                                 reader.close(interrupted);
240                         }
241                 }
242         }
243
244         void set_label() {
245                 frequency_label.setText(String.format("Frequency: %s", frequencies[frequency_index].toString()));
246                 if (select_telemetry)
247                         telemetry_label.setText(String.format("Telemetry: %s", AltosLib.telemetry_name(telemetry)));
248                 if (select_rate)
249                         rate_label.setText(String.format("Rate: %d baud", AltosLib.ao_telemetry_rate_values[rate]));
250         }
251
252         void set_telemetry() {
253                 reader.set_telemetry(telemetry);
254         }
255
256         void set_rate() {
257                 reader.set_telemetry_rate(rate);
258         }
259
260         void set_frequency() throws InterruptedException, TimeoutException {
261                 reader.set_frequency(frequencies[frequency_index].frequency);
262                 reader.reset();
263         }
264
265         void next() throws InterruptedException, TimeoutException {
266                 reader.set_monitor(false);
267
268                 if (select_rate) {
269                         boolean wrapped = false;
270                         do {
271                                 ++rate;
272                                 if (rate > AltosLib.ao_telemetry_rate_max) {
273                                         wrapped = true;
274                                         rate = 0;
275                                 }
276                         } while (!rate_boxes[rate].isSelected());
277                         set_rate();
278                         if (!wrapped) {
279                                 set_label();
280                                 return;
281                         }
282                 }
283                 if (select_telemetry) {
284                         boolean wrapped = false;
285                         do {
286                                 ++telemetry;
287                                 if (telemetry > AltosLib.ao_telemetry_max) {
288                                         wrapped = true;
289                                         telemetry = AltosLib.ao_telemetry_min;
290                                 }
291                         } while (!telemetry_boxes[telemetry - AltosLib.ao_telemetry_min].isSelected());
292                         set_telemetry();
293                         if (!wrapped) {
294                                 set_label();
295                                 return;
296                         }
297                 }
298                 packet_count = 0;
299                 tick_count = 0;
300                 ++frequency_index;
301                 if (frequency_index >= frequencies.length)
302                         frequency_index = 0;
303                 set_frequency();
304                 set_label();
305                 reader.set_monitor(true);
306         }
307
308
309         void close() {
310                 if (thread != null && thread.isAlive()) {
311                         thread.interrupt();
312                         try {
313                                 thread.join();
314                         } catch (InterruptedException ie) {}
315                 }
316                 thread = null;
317                 if (timer != null)
318                         timer.stop();
319                 setVisible(false);
320                 dispose();
321         }
322
323         void tick_timer() throws InterruptedException, TimeoutException {
324                 ++tick_count;
325                 if (packet_count == 0 || tick_count > 5)
326                         next();
327         }
328
329         public void actionPerformed(ActionEvent e) {
330                 String cmd = e.getActionCommand();
331
332                 try {
333                         if (cmd.equals("cancel"))
334                                 close();
335
336                         if (cmd.equals("tick"))
337                                 tick_timer();
338
339                         if (cmd.equals("telemetry")) {
340                                 int k;
341                                 int scanning_telemetry = 0;
342                                 for (k = AltosLib.ao_telemetry_min; k <= AltosLib.ao_telemetry_max; k++) {
343                                         int j = k - AltosLib.ao_telemetry_min;
344                                         if (telemetry_boxes[j].isSelected())
345                                                 scanning_telemetry |= (1 << k);
346                                 }
347                                 if (scanning_telemetry == 0) {
348                                         scanning_telemetry |= (1 << AltosLib.ao_telemetry_standard);
349                                         telemetry_boxes[AltosLib.ao_telemetry_standard - AltosLib.ao_telemetry_min].setSelected(true);
350                                 }
351                                 AltosUIPreferences.set_scanning_telemetry(scanning_telemetry);
352                         }
353
354                         if (cmd.equals("rate")) {
355                                 int k;
356                                 int scanning_rate = 0;
357                                 for (k = 0; k <= AltosLib.ao_telemetry_rate_max; k++) {
358                                         if (rate_boxes[k].isSelected())
359                                                 scanning_rate |= (1 << k);
360                                 }
361                                 if (scanning_rate == 0) {
362                                         scanning_rate = (1 << 0);
363                                         rate_boxes[0].setSelected(true);
364                                 }
365                                 AltosUIPreferences.set_scanning_telemetry_rate(scanning_rate);
366                         }
367
368                         if (cmd.equals("monitor")) {
369                                 close();
370                                 AltosScanResult r = (AltosScanResult) (list.getSelectedValue());
371                                 if (r != null) {
372                                         if (device != null) {
373                                                 if (reader != null) {
374                                                         reader.set_telemetry(r.telemetry);
375                                                         reader.set_telemetry_rate(r.rate);
376                                                         reader.set_frequency(r.frequency.frequency);
377                                                         reader.save_frequency();
378                                                         reader.save_telemetry();
379                                                         reader.save_telemetry_rate();
380                                                         owner.scan_device_selected(device);
381                                                 }
382                                         }
383                                 }
384                         }
385                 } catch (TimeoutException te) {
386                         close();
387                 } catch (InterruptedException ie) {
388                         close();
389                 }
390         }
391
392         /* A window listener to catch closing events and tell the config code */
393         class ConfigListener extends WindowAdapter {
394                 AltosScanUI     ui;
395
396                 public ConfigListener(AltosScanUI this_ui) {
397                         ui = this_ui;
398                 }
399
400                 public void windowClosing(WindowEvent e) {
401                         ui.actionPerformed(new ActionEvent(e.getSource(),
402                                                            ActionEvent.ACTION_PERFORMED,
403                                                            "close"));
404                 }
405         }
406
407         private boolean open() {
408                 device = AltosDeviceUIDialog.show(owner, AltosLib.product_basestation);
409                 if (device == null)
410                         return false;
411                 try {
412                         reader = new AltosTelemetryReader(new AltosSerial(device));
413                         set_frequency();
414                         set_telemetry();
415                         set_rate();
416                         try {
417                                 Thread.sleep(100);
418                         } catch (InterruptedException ie) {
419                         }
420                         reader.flush();
421                         handler = new TelemetryHandler();
422                         thread = new Thread(handler);
423                         thread.start();
424                         return true;
425                 } catch (FileNotFoundException ee) {
426                         JOptionPane.showMessageDialog(owner,
427                                                       ee.getMessage(),
428                                                       "Cannot open target device",
429                                                       JOptionPane.ERROR_MESSAGE);
430                 } catch (AltosSerialInUseException si) {
431                         JOptionPane.showMessageDialog(owner,
432                                                       String.format("Device \"%s\" already in use",
433                                                                     device.toShortString()),
434                                                       "Device in use",
435                                                       JOptionPane.ERROR_MESSAGE);
436                 } catch (IOException ee) {
437                         JOptionPane.showMessageDialog(owner,
438                                                       device.toShortString(),
439                                                       "Unkonwn I/O error",
440                                                       JOptionPane.ERROR_MESSAGE);
441                 } catch (TimeoutException te) {
442                         JOptionPane.showMessageDialog(owner,
443                                                       device.toShortString(),
444                                                       "Timeout error",
445                                                       JOptionPane.ERROR_MESSAGE);
446                 } catch (InterruptedException ie) {
447                         JOptionPane.showMessageDialog(owner,
448                                                       device.toShortString(),
449                                                       "Interrupted exception",
450                                                       JOptionPane.ERROR_MESSAGE);
451                 }
452                 if (reader != null)
453                         reader.close(false);
454                 return false;
455         }
456
457         public AltosScanUI(AltosUIFrame in_owner, boolean in_select_telemetry) {
458                 super(in_owner, "Scan Telemetry", false);
459
460                 owner = in_owner;
461                 select_telemetry = in_select_telemetry;
462                 select_rate = true;
463
464                 frequencies = AltosUIPreferences.common_frequencies();
465                 frequency_index = 0;
466
467                 telemetry = AltosLib.ao_telemetry_standard;
468                 rate = 0;
469
470                 if (!open())
471                         return;
472
473                 Container               pane = getContentPane();
474                 GridBagConstraints      c = new GridBagConstraints();
475                 Insets                  i = new Insets(4,4,4,4);
476
477                 timer = new javax.swing.Timer(timeout, this);
478                 timer.setActionCommand("tick");
479                 timer.restart();
480
481                 owner = in_owner;
482
483                 pane.setLayout(new GridBagLayout());
484
485                 scanning_label = new JLabel("Scanning:");
486                 frequency_label = new JLabel("");
487
488                 if (select_telemetry) {
489                         telemetry_label = new JLabel("");
490                         telemetry_label.setPreferredSize(new Dimension(100, 16));
491                         telemetry = AltosLib.ao_telemetry_min;
492                 } else {
493                         telemetry = AltosLib.ao_telemetry_standard;
494                 }
495
496                 if (select_rate) {
497                         rate_label = new JLabel("");
498                         rate_label.setPreferredSize(new Dimension(100, 16));
499                 }
500
501                 set_label();
502
503                 c.fill = GridBagConstraints.HORIZONTAL;
504                 c.anchor = GridBagConstraints.LINE_START;
505                 c.insets = i;
506                 c.weightx = 0;
507                 c.weighty = 0;
508
509                 c.gridx = 0;
510                 c.gridy = 0;
511                 c.gridwidth = 2;
512
513                 pane.add(scanning_label, c);
514                 c.gridy = 1;
515                 pane.add(frequency_label, c);
516
517                 int     y_offset_rate = 3;
518                 int     y_offset_telem = 3;
519
520                 int     check_x = 0;
521
522                 if (select_rate && select_telemetry)
523                         c.gridwidth = 1;
524
525                 if (select_rate) {
526                         c.gridy = 2;
527                         c.gridx = check_x++;
528                         pane.add(rate_label, c);
529
530                         int     scanning_rate = AltosUIPreferences.scanning_telemetry_rate();
531                         rate_boxes = new JCheckBox[AltosLib.ao_telemetry_rate_max + 1];
532                         for (int k = 0; k <= AltosLib.ao_telemetry_rate_max; k++) {
533                                 rate_boxes[k] = new JCheckBox(String.format("%d baud", AltosLib.ao_telemetry_rate_values[k]));
534                                 c.gridy = y_offset_rate + k;
535                                 pane.add(rate_boxes[k], c);
536                                 rate_boxes[k].setActionCommand("rate");
537                                 rate_boxes[k].addActionListener(this);
538                                 rate_boxes[k].setSelected((scanning_rate & (1 << k)) != 0);
539                         }
540                         y_offset_rate += AltosLib.ao_telemetry_rate_max + 1;
541                 }
542
543                 if (select_telemetry) {
544                         c.gridy = 2;
545                         c.gridx = check_x++;
546                         pane.add(telemetry_label, c);
547
548                         int     scanning_telemetry = AltosUIPreferences.scanning_telemetry();
549                         telemetry_boxes = new JCheckBox[AltosLib.ao_telemetry_max - AltosLib.ao_telemetry_min + 1];
550                         for (int k = AltosLib.ao_telemetry_min; k <= AltosLib.ao_telemetry_max; k++) {
551                                 int j = k - AltosLib.ao_telemetry_min;
552                                 telemetry_boxes[j] = new JCheckBox(AltosLib.telemetry_name(k));
553                                 c.gridy = y_offset_telem + j;
554                                 pane.add(telemetry_boxes[j], c);
555                                 telemetry_boxes[j].setActionCommand("telemetry");
556                                 telemetry_boxes[j].addActionListener(this);
557                                 telemetry_boxes[j].setSelected((scanning_telemetry & (1 << k)) != 0);
558                         }
559                         y_offset_telem += (AltosLib.ao_telemetry_max - AltosLib.ao_telemetry_min + 1);
560                 }
561
562                 int y_offset = Math.max(y_offset_rate, y_offset_telem);
563
564                 list = new JList<AltosScanResult>(results) {
565                                 //Subclass JList to workaround bug 4832765, which can cause the
566                                 //scroll pane to not let the user easily scroll up to the beginning
567                                 //of the list.  An alternative would be to set the unitIncrement
568                                 //of the JScrollBar to a fixed value. You wouldn't get the nice
569                                 //aligned scrolling, but it should work.
570                                 public int getScrollableUnitIncrement(Rectangle visibleRect,
571                                                                       int orientation,
572                                                                       int direction) {
573                                         int row;
574                                         if (orientation == SwingConstants.VERTICAL &&
575                                             direction < 0 && (row = getFirstVisibleIndex()) != -1) {
576                                                 Rectangle r = getCellBounds(row, row);
577                                                 if ((r.y == visibleRect.y) && (row != 0))  {
578                                                         Point loc = r.getLocation();
579                                                         loc.y--;
580                                                         int prevIndex = locationToIndex(loc);
581                                                         Rectangle prevR = getCellBounds(prevIndex, prevIndex);
582
583                                                         if (prevR == null || prevR.y >= r.y) {
584                                                                 return 0;
585                                                         }
586                                                         return prevR.height;
587                                                 }
588                                         }
589                                         return super.getScrollableUnitIncrement(
590                                                 visibleRect, orientation, direction);
591                                 }
592                         };
593
594                 list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
595                 list.setLayoutOrientation(JList.HORIZONTAL_WRAP);
596                 list.setVisibleRowCount(-1);
597
598                 list.addMouseListener(new MouseAdapter() {
599                                  public void mouseClicked(MouseEvent e) {
600                                          if (e.getClickCount() == 2) {
601                                                  monitor_button.doClick(); //emulate button click
602                                          }
603                                  }
604                         });
605                 JScrollPane listScroller = new JScrollPane(list);
606                 listScroller.setPreferredSize(new Dimension(400, 80));
607                 listScroller.setAlignmentX(LEFT_ALIGNMENT);
608
609                 //Create a container so that we can add a title around
610                 //the scroll pane.  Can't add a title directly to the
611                 //scroll pane because its background would be white.
612                 //Lay out the label and scroll pane from top to bottom.
613                 JPanel listPane = new JPanel();
614                 listPane.setLayout(new BoxLayout(listPane, BoxLayout.PAGE_AXIS));
615
616                 JLabel label = new JLabel("Select Device");
617                 label.setLabelFor(list);
618                 listPane.add(label);
619                 listPane.add(Box.createRigidArea(new Dimension(0,5)));
620                 listPane.add(listScroller);
621                 listPane.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
622
623                 c.fill = GridBagConstraints.BOTH;
624                 c.anchor = GridBagConstraints.CENTER;
625                 c.insets = i;
626                 c.weightx = 1;
627                 c.weighty = 1;
628
629                 c.gridx = 0;
630                 c.gridy = y_offset;
631                 c.gridwidth = 2;
632                 c.anchor = GridBagConstraints.CENTER;
633
634                 pane.add(listPane, c);
635
636                 cancel_button = new JButton("Cancel");
637                 cancel_button.addActionListener(this);
638                 cancel_button.setActionCommand("cancel");
639
640                 c.fill = GridBagConstraints.NONE;
641                 c.anchor = GridBagConstraints.CENTER;
642                 c.insets = i;
643                 c.weightx = 1;
644                 c.weighty = 1;
645
646                 c.gridx = 0;
647                 c.gridy = y_offset + 1;
648                 c.gridwidth = 1;
649                 c.anchor = GridBagConstraints.CENTER;
650
651                 pane.add(cancel_button, c);
652
653                 monitor_button = new JButton("Monitor");
654                 monitor_button.addActionListener(this);
655                 monitor_button.setActionCommand("monitor");
656
657                 c.fill = GridBagConstraints.NONE;
658                 c.anchor = GridBagConstraints.CENTER;
659                 c.insets = i;
660                 c.weightx = 1;
661                 c.weighty = 1;
662
663                 c.gridx = 1;
664                 c.gridy = y_offset + 1;
665                 c.gridwidth = 1;
666                 c.anchor = GridBagConstraints.CENTER;
667
668                 pane.add(monitor_button, c);
669
670                 pack();
671                 setLocationRelativeTo(owner);
672
673                 addWindowListener(new ConfigListener(this));
674
675                 setVisible(true);
676         }
677 }