/
AbstractSerialConnectionConfig.java
651 lines (576 loc) · 24.1 KB
/
AbstractSerialConnectionConfig.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
package jmri.jmrix;
import java.awt.Color;
import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.ItemEvent;
import java.util.Collections;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.ListCellRenderer;
import javax.swing.SpinnerNumberModel;
import jmri.util.PortNameMapper;
import jmri.util.PortNameMapper.SerialPortFriendlyName;
import jmri.util.swing.JComboBoxUtil;
/**
* Abstract base class for common implementation of the SerialConnectionConfig.
*
* @author Bob Jacobsen Copyright (C) 2001, 2003
*/
abstract public class AbstractSerialConnectionConfig extends AbstractConnectionConfig {
/**
* Ctor for an object being created during load process.
*
* @param p port being configured
*/
@edu.umd.cs.findbugs.annotations.SuppressFBWarnings(value = "BC_UNCONFIRMED_CAST", justification = "Thought to be safe as default connection config")
public AbstractSerialConnectionConfig(jmri.jmrix.PortAdapter p) {
this((jmri.jmrix.SerialPortAdapter) p);
}
public AbstractSerialConnectionConfig(jmri.jmrix.SerialPortAdapter p) {
adapter = p;
}
/**
* Ctor for a functional object with no preexisting adapter. Expect that the
* subclass setInstance() will fill the adapter member.
*/
public AbstractSerialConnectionConfig() {
adapter = null;
}
@Override
public jmri.jmrix.SerialPortAdapter getAdapter() {
return adapter;
}
protected boolean init = false;
/**
* {@inheritDoc}
*/
@Override
protected void checkInitDone() {
log.debug("init called for {}", name());
if (init) {
return;
}
baudBox.addActionListener(e -> {
adapter.configureBaudRate((String) baudBox.getSelectedItem());
p.setComboBoxLastSelection(adapter.getClass().getName() + ".baud", (String) baudBox.getSelectedItem()); // NOI18N
});
addNameEntryCheckers(adapter);
portBox.addFocusListener(new FocusListener() {
@Override
public void focusGained(FocusEvent e) {
refreshPortBox();
}
@Override
public void focusLost(FocusEvent e) {
}
});
// set/change delay interval between (actually before) output (Turnout) commands
outputIntervalSpinner.addChangeListener(e -> adapter.getSystemConnectionMemo().setOutputInterval((Integer) outputIntervalSpinner.getValue()));
for (Map.Entry<String, Option> entry : options.entrySet()) {
final String item = entry.getKey();
if (entry.getValue().getComponent() instanceof JComboBox) {
((JComboBox<?>) entry.getValue().getComponent()).addActionListener((ActionEvent e) -> {
adapter.setOptionState(item, options.get(item).getItem());
});
JComboBoxUtil.setupComboBoxMaxRows((JComboBox<?>) entry.getValue().getComponent());
}
}
init = true;
}
@Override
public void updateAdapter() {
log.debug("updateAdapter() to {}", systemPrefixField.getText());
adapter.setPort(PortNameMapper.getPortFromName((String) portBox.getSelectedItem()));
adapter.configureBaudRateFromIndex(baudBox.getSelectedIndex()); // manage by index, not item value
for (Map.Entry<String, Option> entry : options.entrySet()) {
adapter.setOptionState(entry.getKey(), entry.getValue().getItem());
}
if (adapter.getSystemConnectionMemo() != null && !adapter.getSystemConnectionMemo().setSystemPrefix(systemPrefixField.getText())) {
systemPrefixField.setText(adapter.getSystemConnectionMemo().getSystemPrefix());
connectionNameField.setText(adapter.getSystemConnectionMemo().getUserName());
}
}
jmri.UserPreferencesManager p = jmri.InstanceManager.getDefault(jmri.UserPreferencesManager.class);
protected JComboBox<String> portBox = new JComboBox<>();
protected JLabel portBoxLabel;
protected JComboBox<String> baudBox = new JComboBox<>();
protected JLabel baudBoxLabel;
protected String[] baudList;
private final SpinnerNumberModel intervalSpinner = new SpinnerNumberModel(250, 0, 10000, 1); // 10 sec max seems long enough
// the following items are protected so they can be hidden when not applicable from a specific ConnectionConfig (ie. Simulator) implementation
protected JSpinner outputIntervalSpinner = new JSpinner(intervalSpinner);
protected JLabel outputIntervalLabel;
protected JButton outputIntervalReset = new JButton(Bundle.getMessage("ButtonReset"));
protected jmri.jmrix.SerialPortAdapter adapter;
/**
* {@inheritDoc}
*/
@Override
abstract protected void setInstance();
@Override
public String getInfo() {
String t = (String) portBox.getSelectedItem();
if (t != null) {
return PortNameMapper.getPortFromName(t);
//return t;
} else if ((adapter != null) && (adapter.getCurrentPortName() != null)) {
return adapter.getCurrentPortName();
}
return JmrixConfigPane.NONE;
}
// @SuppressWarnings("UseOfObsoleteCollectionType")
Vector<String> v;
// @SuppressWarnings("UseOfObsoleteCollectionType")
Vector<String> originalList;
String invalidPort = null;
// @SuppressWarnings("UseOfObsoleteCollectionType")
public void refreshPortBox() {
if (!init) {
v = getPortNames();
portBox.setRenderer(new ComboBoxRenderer());
// Add this line to ensure that the combo box header isn't made too narrow
portBox.setPrototypeDisplayValue("A fairly long port name of 40 characters"); //NO18N
} else {
Vector<String> v2 = getPortNames();
if (v2.equals(originalList)) {
log.debug("List of valid Ports has not changed, therefore we will not refresh the port list");
// but we will insist on setting the current value into the port
adapter.setPort(PortNameMapper.getPortFromName((String) portBox.getSelectedItem()));
return;
}
log.debug("List of valid Ports has been changed, therefore we will refresh the port list");
v = new Vector<>();
v.setSize(v2.size());
Collections.copy(v, v2);
}
if (v == null) {
log.error("port name Vector v is null!");
return;
}
/* as we make amendments to the list of port in vector v, we keep a copy of it before
modification, this copy is then used to validate against any changes in the port lists.
*/
originalList = new Vector<>();
originalList.setSize(v.size());
Collections.copy(originalList, v);
if (portBox.getActionListeners().length > 0) {
portBox.removeActionListener(portBox.getActionListeners()[0]);
}
portBox.removeAllItems();
log.debug("getting fresh list of available Serial Ports");
if (v.isEmpty()) {
v.add(0, Bundle.getMessage("noPortsFound"));
}
String portName = adapter.getCurrentPortName();
if (portName != null && !portName.equals(Bundle.getMessage("noneSelected")) && !portName.equals(Bundle.getMessage("noPortsFound"))) {
if (!v.contains(portName)) {
v.add(0, portName);
invalidPort = portName;
portBox.setForeground(Color.red);
} else if (invalidPort != null && invalidPort.equals(portName)) {
invalidPort = null;
}
} else {
if (!v.contains(portName)) {
v.add(0, Bundle.getMessage("noneSelected"));
} else if (p.getComboBoxLastSelection(adapter.getClass().getName() + ".port") == null) {
v.add(0, Bundle.getMessage("noneSelected"));
}
}
updateSerialPortNames(portName, portBox, v);
JComboBoxUtil.setupComboBoxMaxRows(portBox);
// If there's no name selected, select one that seems most likely
boolean didSetName = false;
if (portName == null || portName.equals(Bundle.getMessage("noneSelected")) || portName.equals(Bundle.getMessage("noPortsFound"))) {
for (int i = 0; i < portBox.getItemCount(); i++) {
for (String friendlyName : getPortFriendlyNames()) {
if ((portBox.getItemAt(i)).contains(friendlyName)) {
portBox.setSelectedIndex(i);
adapter.setPort(PortNameMapper.getPortFromName(portBox.getItemAt(i)));
didSetName = true;
break;
}
}
}
// if didn't set name, don't leave it hanging
if (!didSetName) {
portBox.setSelectedIndex(0);
}
}
// finally, insist on synchronization of selected port name with underlying port
adapter.setPort(PortNameMapper.getPortFromName((String) portBox.getSelectedItem()));
// add a listener for later changes
portBox.addActionListener((ActionEvent e) -> {
String port = PortNameMapper.getPortFromName((String) portBox.getSelectedItem());
adapter.setPort(port);
});
}
/**
* {@inheritDoc}
*/
@Override
// @SuppressWarnings("UseOfObsoleteCollectionType")
public void loadDetails(final JPanel details) {
_details = details;
setInstance();
if (!init) {
//Build up list of options
String[] optionsAvailable = adapter.getOptions();
options.clear();
for (String i : optionsAvailable) {
JComboBox<String> opt = new JComboBox<>(adapter.getOptionChoices(i));
opt.setSelectedItem(adapter.getOptionState(i));
// check that it worked
if (!adapter.getOptionState(i).equals(opt.getSelectedItem())) {
// no, set 1st option choice
opt.setSelectedIndex(0);
// log before setting new value to show old value
log.warn("Loading found invalid value for option {}, found \"{}\", setting to \"{}\"", i, adapter.getOptionState(i), opt.getSelectedItem());
adapter.setOptionState(i, (String) opt.getSelectedItem());
}
options.put(i, new Option(adapter.getOptionDisplayName(i), opt, adapter.isOptionAdvanced(i)));
}
}
try {
v = getPortNames();
if (log.isDebugEnabled()) {
log.debug("loadDetails called in class {}", this.getClass().getName());
log.debug("adapter class: {}", adapter.getClass().getName());
log.debug("loadDetails called for {}", name());
if (v != null) {
log.debug("Found {} ports", v.size());
} else {
log.debug("Zero-length port vector");
}
}
} catch (java.lang.UnsatisfiedLinkError e1) {
log.error("UnsatisfiedLinkError - the serial library has not been installed properly");
log.error("java.library.path={}", System.getProperty("java.library.path", "<unknown>"));
jmri.util.swing.JmriJOptionPane.showMessageDialog(null, "Failed to load comm library.\nYou have to fix that before setting preferences.");
return;
}
if (adapter.getSystemConnectionMemo() != null) {
systemPrefixField.setText(adapter.getSystemConnectionMemo().getSystemPrefix());
connectionNameField.setText(adapter.getSystemConnectionMemo().getUserName());
NUMOPTIONS = NUMOPTIONS + 2;
}
refreshPortBox();
baudList = adapter.validBaudRates(); // when not supported should not return null, but an empty String[] {}
// need to remove ActionListener before addItem() or action event will occur
if (baudBox.getActionListeners().length > 0) {
baudBox.removeActionListener(baudBox.getActionListeners()[0]);
}
// rebuild baudBox combo list
baudBox.removeAllItems();
if (log.isDebugEnabled()) {
log.debug("after remove, {} items, first is {}", baudBox.getItemCount(),
baudBox.getItemAt(0));
}
// empty array means: baud not supported by adapter (but extends serialConnConfig)
if (baudList.length == 0) {
log.debug("empty array received from adapter");
}
for (String baudList1 : baudList) {
baudBox.addItem(baudList1);
}
if (log.isDebugEnabled()) {
log.debug("after reload, {} items, first is {}", baudBox.getItemCount(),
baudBox.getItemAt(0));
}
if (baudList.length > 1) {
baudBox.setToolTipText(Bundle.getMessage("TipBaudRateMatch"));
baudBox.setEnabled(true);
} else {
baudBox.setToolTipText(Bundle.getMessage("TipBaudRateFixed"));
baudBox.setEnabled(false);
}
NUMOPTIONS = NUMOPTIONS + options.size();
portBoxLabel = new JLabel(Bundle.getMessage("SerialPortLabel"));
baudBoxLabel = new JLabel(Bundle.getMessage("BaudRateLabel"));
if (baudBox.getItemCount() > 0) { // skip when adapter returned an empty array (= spotbug's preference)
baudBox.setSelectedIndex(adapter.getCurrentBaudIndex());
}
// connection (memo) specific output command delay option, calls jmri.jmrix.SystemConnectionMemo#setOutputInterval(int)
outputIntervalLabel = new JLabel(Bundle.getMessage("OutputIntervalLabel"));
outputIntervalSpinner.setToolTipText(Bundle.getMessage("OutputIntervalTooltip",
adapter.getSystemConnectionMemo().getDefaultOutputInterval(),adapter.getManufacturer()));
JTextField field = ((JSpinner.DefaultEditor) outputIntervalSpinner.getEditor()).getTextField();
field.setColumns(6);
outputIntervalSpinner.setMaximumSize(outputIntervalSpinner.getPreferredSize()); // set spinner JTextField width
outputIntervalSpinner.setValue(adapter.getSystemConnectionMemo().getOutputInterval());
outputIntervalSpinner.setEnabled(true);
outputIntervalReset.addActionListener((ActionEvent event) -> {
outputIntervalSpinner.setValue(adapter.getSystemConnectionMemo().getDefaultOutputInterval());
adapter.getSystemConnectionMemo().setOutputInterval(adapter.getSystemConnectionMemo().getDefaultOutputInterval());
});
showAdvanced.setFont(showAdvanced.getFont().deriveFont(9f));
showAdvanced.setForeground(Color.blue);
showAdvanced.addItemListener((ItemEvent e) -> {
showAdvancedItems();
});
showAdvancedItems();
init = false; // need to reload action listeners
checkInitDone();
}
@Override
@edu.umd.cs.findbugs.annotations.SuppressFBWarnings(value = "BC_UNCONFIRMED_CAST_OF_RETURN_VALUE",
justification = "Type is checked before casting")
protected void showAdvancedItems() {
_details.removeAll();
cL.anchor = GridBagConstraints.WEST;
cL.insets = new Insets(2, 5, 0, 5);
cR.insets = new Insets(2, 0, 0, 5);
cR.anchor = GridBagConstraints.WEST;
cR.gridx = 1;
cL.gridx = 0;
int i = 0;
int stdrows = 0;
boolean incAdvancedOptions = true;
if (!isBaudAdvanced()) {
stdrows++;
}
if (!isPortAdvanced()) {
stdrows++;
}
for (Map.Entry<String, Option> entry : options.entrySet()) {
if (!entry.getValue().isAdvanced()) {
stdrows++;
}
}
if (adapter.getSystemConnectionMemo() != null) {
stdrows = stdrows + 2;
}
if (stdrows == NUMOPTIONS) {
incAdvancedOptions = false;
}
_details.setLayout(gbLayout);
i = addStandardDetails(incAdvancedOptions, i);
if (showAdvanced.isSelected()) {
if (isPortAdvanced()) {
cR.gridy = i;
cL.gridy = i;
gbLayout.setConstraints(portBoxLabel, cL);
gbLayout.setConstraints(portBox, cR);
_details.add(portBoxLabel);
_details.add(portBox);
i++;
}
if (isBaudAdvanced()) {
cR.gridy = i;
cL.gridy = i;
gbLayout.setConstraints(baudBoxLabel, cL);
gbLayout.setConstraints(baudBox, cR);
_details.add(baudBoxLabel);
_details.add(baudBox);
i++;
}
for (Map.Entry<String, Option> entry : options.entrySet()) {
if (entry.getValue().isAdvanced()) {
cR.gridy = i;
cL.gridy = i;
gbLayout.setConstraints(entry.getValue().getLabel(), cL);
gbLayout.setConstraints(entry.getValue().getComponent(), cR);
_details.add(entry.getValue().getLabel());
_details.add(entry.getValue().getComponent());
i++;
}
}
// interval config field
cR.gridy = i;
cL.gridy = i;
gbLayout.setConstraints(outputIntervalLabel, cL);
_details.add(outputIntervalLabel);
JPanel intervalPanel = new JPanel();
gbLayout.setConstraints(intervalPanel, cR);
intervalPanel.add(outputIntervalSpinner);
intervalPanel.add(outputIntervalReset);
_details.add(intervalPanel);
i++;
}
cL.gridwidth = 2;
for (JComponent item : additionalItems) {
cL.gridy = i;
gbLayout.setConstraints(item, cL);
_details.add(item);
i++;
}
cL.gridwidth = 1;
if (_details.getParent() != null && _details.getParent() instanceof javax.swing.JViewport) {
javax.swing.JViewport vp = (javax.swing.JViewport) _details.getParent();
vp.revalidate();
vp.repaint();
}
}
protected int addStandardDetails(boolean incAdvanced, int i) {
if (!isPortAdvanced()) {
cR.gridy = i;
cL.gridy = i;
gbLayout.setConstraints(portBoxLabel, cL);
gbLayout.setConstraints(portBox, cR);
_details.add(portBoxLabel);
_details.add(portBox);
i++;
}
if (!isBaudAdvanced()) {
cR.gridy = i;
cL.gridy = i;
gbLayout.setConstraints(baudBoxLabel, cL);
gbLayout.setConstraints(baudBox, cR);
_details.add(baudBoxLabel);
_details.add(baudBox);
i++;
}
return addStandardDetails(adapter, incAdvanced, i);
}
public boolean isPortAdvanced() {
return false;
}
public boolean isBaudAdvanced() {
return true;
}
@Override
public String getManufacturer() {
return adapter.getManufacturer();
}
@Override
public void setManufacturer(String manufacturer) {
setInstance();
adapter.setManufacturer(manufacturer);
}
@Override
public boolean getDisabled() {
if (adapter == null) {
return true;
}
return adapter.getDisabled();
}
@Override
public void setDisabled(boolean disabled) {
if (adapter != null) {
adapter.setDisabled(disabled);
}
}
@Override
public String getConnectionName() {
if ((adapter != null) && (adapter.getSystemConnectionMemo() != null)) {
return adapter.getSystemConnectionMemo().getUserName();
} else {
return name();
}
}
@Override
public void dispose() {
super.dispose();
if (adapter != null) {
adapter.dispose();
adapter = null;
}
}
class ComboBoxRenderer extends JLabel
implements ListCellRenderer<String> {
public ComboBoxRenderer() {
setHorizontalAlignment(LEFT);
setVerticalAlignment(CENTER);
}
/*
* This method finds the image and text corresponding
* to the selected value and returns the label, set up
* to display the text and image.
*/
@Override
public Component getListCellRendererComponent(
JList<? extends String> list,
String name,
int index,
boolean isSelected,
boolean cellHasFocus) {
setOpaque(index > -1);
setForeground(Color.black);
list.setSelectionForeground(Color.black);
if (isSelected && index > -1) {
setBackground(list.getSelectionBackground());
} else {
setBackground(list.getBackground());
}
if (invalidPort != null) {
String port = PortNameMapper.getPortFromName(name);
if (port.equals(invalidPort)) {
list.setSelectionForeground(Color.red);
setForeground(Color.red);
}
}
setText(name);
return this;
}
}
/**
* Handle friendly port names. Note that this
* changes the selection in portCombo, so
* that should be tracked after this returns.
*
* @param portName The currently-selected port name
* @param portCombo The combo box that's displaying the available ports
* @param portList The list of valid (unfriendly) port names
*/
// @SuppressWarnings("UseOfObsoleteCollectionType")
protected synchronized static void updateSerialPortNames(String portName, JComboBox<String> portCombo, Vector<String> portList) {
for (Map.Entry<String, SerialPortFriendlyName> en : PortNameMapper.getPortNameMap().entrySet()) {
en.getValue().setValidPort(false);
}
for (int i = 0; i < portList.size(); i++) {
String commPort = portList.elementAt(i);
SerialPortFriendlyName port = PortNameMapper.getPortNameMap().get(commPort);
if (port == null) {
port = new SerialPortFriendlyName(commPort, null);
PortNameMapper.getPortNameMap().put(commPort, port);
}
port.setValidPort(true);
portCombo.addItem(port.getDisplayName());
if (commPort.equals(portName)) {
portCombo.setSelectedIndex(i);
}
}
}
/**
* Provide a vector of valid port names, each a String.
* This may be implemented differently in subclasses
* that e.g. do loopback or use a custom port-access library.
* @return Valid port names in the form used to select them later.
*/
// @SuppressWarnings("UseOfObsoleteCollectionType") // historical interface
protected Vector<String> getPortNames() {
return AbstractSerialPortController.getActualPortNames();
}
/**
* This provides a method to return potentially meaningful names that are
* used in OS to help identify ports against Hardware.
*
* @return array of friendly port names
*/
protected String[] getPortFriendlyNames() {
return new String[]{};
}
/**
* This is purely here for systems that do not implement the
* SystemConnectionMemo and can be removed once they have been migrated.
*
* @return Resource bundle for action model
*/
protected ResourceBundle getActionModelResourceBundle() {
return null;
}
private final static org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(AbstractSerialConnectionConfig.class);
}