/
LayoutBlock.java
4676 lines (4140 loc) · 187 KB
/
LayoutBlock.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
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package jmri.jmrit.display.layoutEditor;
import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.beans.*;
import java.util.*;
import javax.annotation.*;
import javax.swing.*;
import javax.swing.colorchooser.AbstractColorChooserPanel;
import jmri.*;
import jmri.implementation.AbstractNamedBean;
import jmri.jmrit.beantable.beanedit.*;
import jmri.jmrit.roster.RosterEntry;
import jmri.swing.NamedBeanComboBox;
import jmri.util.*;
import jmri.util.swing.*;
import org.slf4j.*;
/**
* A LayoutBlock is a group of track segments and turnouts on a LayoutEditor
* panel corresponding to a 'block'. LayoutBlock is a LayoutEditor specific
* extension of the JMRI Block object.
* <p>
* LayoutBlocks may have an occupancy Sensor. The getOccupancy method returns
* the occupancy state of the LayoutBlock - OCCUPIED, EMPTY, or UNKNOWN. If no
* occupancy sensor is provided, UNKNOWN is returned. The occupancy sensor if
* there is one, is the same as the occupancy sensor of the corresponding JMRI
* Block.
* <p>
* The name of each Layout Block is the same as that of the corresponding block
* as defined in Layout Editor. A corresponding JMRI Block object is created
* when a LayoutBlock is created. The JMRI Block uses the name of the block
* defined in Layout Editor as its user name and a unique IBnnn system name. The
* JMRI Block object and its associated Path objects are useful in tracking a
* train around the layout. Blocks may be viewed in the Block Table.
* <p>
* A LayoutBlock may have an associated Memory object. This Memory object
* contains a string representing the current "value" of the corresponding JMRI
* Block object. If the value contains a train name, for example, displaying
* Memory objects associated with LayoutBlocks, and displayed near each Layout
* Block can follow a train around the layout, displaying its name when it is in
* the LayoutBlock.
* <p>
* LayoutBlocks are "cross-panel", similar to sensors and turnouts. A
* LayoutBlock may be used by more than one Layout Editor panel simultaneously.
* As a consequence, LayoutBlocks are saved with the configuration, not with a
* panel.
* <p>
* LayoutBlocks are used by TrackSegments, LevelXings, and LayoutTurnouts.
* LevelXings carry two LayoutBlock designations, which may be the same.
* LayoutTurnouts carry LayoutBlock designations also, one per turnout, except
* for double crossovers and slips which can have up to four.
* <p>
* LayoutBlocks carry a use count. The use count counts the number of track
* segments, layout turnouts, and levelcrossings which use the LayoutBlock. Only
* LayoutBlocks which have a use count greater than zero are saved when the
* configuration is saved.
*
* @author Dave Duchamp Copyright (c) 2004-2008
* @author George Warner Copyright (c) 2017-2019
*/
public class LayoutBlock extends AbstractNamedBean implements PropertyChangeListener {
private final boolean enableAddRouteLogging = false;
private final boolean enableUpdateRouteLogging = false;
private boolean enableDeleteRouteLogging = false;
private final boolean enableSearchRouteLogging = false;
private static final List<Integer> updateReferences = new ArrayList<>(500);
// might want to use the jmri ordered HashMap, so that we can add at the top
// and remove at the bottom.
private final List<Integer> actedUponUpdates = new ArrayList<>(500);
public void enableDeleteRouteLog() {
enableDeleteRouteLogging = false;
}
public void disableDeleteRouteLog() {
enableDeleteRouteLogging = false;
}
// constants
public static final int OCCUPIED = Block.OCCUPIED;
public static final int EMPTY = Block.UNOCCUPIED;
// operational instance variables (not saved to disk)
private int useCount = 0;
private NamedBeanHandle<Sensor> occupancyNamedSensor = null;
private NamedBeanHandle<Memory> namedMemory = null;
private Block block = null;
private final List<LayoutEditor> panels = new ArrayList<>(); // panels using this block
private PropertyChangeListener mBlockListener = null;
private int jmriblknum = 1;
private boolean useExtraColor = false;
private boolean suppressNameUpdate = false;
// persistent instances variables (saved between sessions)
private String occupancySensorName = "";
private String memoryName = "";
private int occupiedSense = Sensor.ACTIVE;
private Color blockTrackColor = Color.darkGray;
private Color blockOccupiedColor = Color.red;
private Color blockExtraColor = Color.white;
/*
* Creates a LayoutBlock object.
*
* Note: initializeLayoutBlock() must be called to complete the process. They are split
* so that loading of panel files will be independent of whether LayoutBlocks or
* Blocks are loaded first.
* @param sName System name of this LayoutBlock
* @param uName User name of this LayoutBlock but also the user name of the associated Block
*/
public LayoutBlock(String sName, String uName) {
super(sName, uName);
//_instance = this;
}
/*
* Completes the creation of a LayoutBlock object by adding a Block to it.
*
* The block create process takes into account that the _bean register
* process considers IB1 and IB01 to be the same name which results in a
* silent failure.
*/
@SuppressWarnings("deprecation") // needs careful unwinding for Set operations, generics
public void initializeLayoutBlock() {
// get/create a Block object corresponding to this LayoutBlock
block = null; // assume failure (pessimist!)
String userName = getUserName();
if ((userName != null) && !userName.isEmpty()) {
block = InstanceManager.getDefault(BlockManager.class).getByUserName(userName);
}
if (block == null) {
// Not found, create a new Block
BlockManager bm = InstanceManager.getDefault(BlockManager.class);
String s;
while (true) {
if (jmriblknum > 50000) {
throw new IndexOutOfBoundsException("Run away prevented while trying to create a block");
}
s = "IB" + jmriblknum;
jmriblknum++;
// Find an unused system name
block = bm.getBySystemName(s);
if (block != null) {
log.debug("System name is already used: {}", s);
continue;
}
// Create a new block. User name is null to prevent user name checking.
block = bm.createNewBlock(s, null);
if (block == null) {
log.debug("Null block returned: {}", s);
continue;
}
// Verify registration
if (bm.getSystemNameList().contains(s)) {
log.debug("Block is valid: {}", s);
break;
}
log.debug("Registration failed: {}", s);
}
block.setUserName(getUserName());
}
// attach a listener for changes in the Block
mBlockListener = this::handleBlockChange;
block.addPropertyChangeListener(mBlockListener,
getUserName(), "Layout Block:" + getUserName());
if (occupancyNamedSensor != null) {
block.setNamedSensor(occupancyNamedSensor);
}
}
/* initializeLayoutBlockRouting */
public void initializeLayoutBlockRouting() {
if (!InstanceManager.getDefault(LayoutBlockManager.class).isAdvancedRoutingEnabled()) {
return;
}
setBlockMetric();
block.getPaths().stream().forEach(this::addAdjacency);
}
/*
* Accessor methods
*/
// TODO: deprecate and just use getUserName() directly
public String getId() {
return getUserName();
}
public Color getBlockTrackColor() {
return blockTrackColor;
}
public void setBlockTrackColor(Color color) {
blockTrackColor = color;
JmriColorChooser.addRecentColor(color);
}
public Color getBlockOccupiedColor() {
return blockOccupiedColor;
}
public void setBlockOccupiedColor(Color color) {
blockOccupiedColor = color;
JmriColorChooser.addRecentColor(color);
}
public Color getBlockExtraColor() {
return blockExtraColor;
}
public void setBlockExtraColor(Color color) {
blockExtraColor = color;
JmriColorChooser.addRecentColor(color);
}
// TODO: @Deprecated // Java standard pattern for boolean getters is "UseExtraColor()"
public boolean getUseExtraColor() {
return useExtraColor;
}
public void setUseExtraColor(boolean b) {
useExtraColor = b;
if (InstanceManager.getDefault(LayoutBlockManager.class).isAdvancedRoutingEnabled()) {
stateUpdate();
}
if (getBlock() != null) {
getBlock().setAllocated(b);
}
}
/* setUseExtraColor */
public void incrementUse() {
useCount++;
}
public void decrementUse() {
--useCount;
if (useCount <= 0) {
useCount = 0;
}
}
public int getUseCount() {
return useCount;
}
/**
* Keep track of LayoutEditor panels that are using this LayoutBlock.
*
* @param panel to keep track of
*/
public void addLayoutEditor(LayoutEditor panel) {
// add to the panels list if not already there
if (!panels.contains(panel)) {
panels.add(panel);
}
}
public void deleteLayoutEditor(LayoutEditor panel) {
// remove from the panels list if there
if (panels.contains(panel)) {
panels.remove(panel);
}
}
public boolean isOnPanel(LayoutEditor panel) {
// returns true if this Layout Block is used on panel
return panels.contains(panel);
}
/**
* Redraw panels using this layout block.
*/
public void redrawLayoutBlockPanels() {
panels.stream().forEach(LayoutEditor::redrawPanel);
firePropertyChange("redraw", null, null);
}
/**
* Validate that the supplied occupancy sensor name corresponds to an
* existing sensor and is unique among all blocks. If valid, returns the
* sensor and sets the block sensor name in the block. Else returns null,
* and does nothing to the block.
*
* @param sensorName to check
* @param openFrame determines the <code>Frame</code> in which the dialog
* is displayed; if <code>null</code>, or if the
* <code>parentComponent</code> has no <code>Frame</code>,
* a default <code>Frame</code> is used
* @return the validated sensor
*/
public Sensor validateSensor(String sensorName, Component openFrame) {
// check if anything entered
if ((sensorName == null) || sensorName.isEmpty()) {
// no sensor name entered
if (occupancyNamedSensor != null) {
setOccupancySensorName(null);
}
return null;
}
// get the sensor corresponding to this name
Sensor s = InstanceManager.sensorManagerInstance().getSensor(sensorName);
if (s == null) {
// There is no sensor corresponding to this name
JOptionPane.showMessageDialog(openFrame,
java.text.MessageFormat.format(Bundle.getMessage("Error7"),
new Object[]{sensorName}),
Bundle.getMessage("ErrorTitle"), JOptionPane.ERROR_MESSAGE);
return null;
}
// ensure that this sensor is unique among defined Layout Blocks
NamedBeanHandle<Sensor> savedNamedSensor = occupancyNamedSensor;
occupancyNamedSensor = null;
LayoutBlock b = InstanceManager.getDefault(LayoutBlockManager.class).
getBlockWithSensorAssigned(s);
if (b != this) {
if (b != null) {
if (b.getUseCount() > 0) {
// new sensor is not unique, return to the old one
occupancyNamedSensor = savedNamedSensor;
JOptionPane.showMessageDialog(openFrame,
java.text.MessageFormat.format(Bundle.getMessage("Error6"),
new Object[]{sensorName, b.getId()}),
Bundle.getMessage("ErrorTitle"), JOptionPane.ERROR_MESSAGE);
return null;
} else {
// the user is assigning a sensor which is already assigned to
// layout block b. Layout block b is no longer in use so this
// should be fine but it's technically possible to put
// this discarded layout block back into service (possibly
// by mistake) by entering its name in any edit layout block window.
// That would cause a problem with the sensor being in use in
// two active blocks, so as a precaution we remove the sensor
// from the discarded block here.
b.setOccupancySensorName(null);
}
}
// sensor is unique, or was only in use on a layout block not in use
setOccupancySensorName(sensorName);
}
return s;
}
/**
* Validate that the memory name corresponds to an existing memory. If
* valid, returns the memory. Else returns null, and notifies the user.
*
* @param memName the memory name
* @param openFrame the frame to display any error dialog in
* @return the memory
*/
public Memory validateMemory(String memName, Component openFrame) {
// check if anything entered
if ((memName == null) || memName.isEmpty()) {
// no memory entered
return null;
}
// get the memory corresponding to this name
Memory m = InstanceManager.memoryManagerInstance().getMemory(memName);
if (m == null) {
// There is no memory corresponding to this name
JOptionPane.showMessageDialog(openFrame,
java.text.MessageFormat.format(Bundle.getMessage("Error16"),
new Object[]{memName}),
Bundle.getMessage("ErrorTitle"), JOptionPane.ERROR_MESSAGE);
return null;
}
memoryName = memName;
// Go through the memory icons on the panel and see if any are linked to this layout block
if ((m != getMemory()) && (panels.size() > 0)) {
boolean updateall = false;
boolean found = false;
for (LayoutEditor panel : panels) {
for (MemoryIcon memIcon : panel.getMemoryLabelList()) {
if (memIcon.getLayoutBlock() == this) {
if (!updateall && !found) {
int n = JOptionPane.showConfirmDialog(
openFrame,
"Would you like to update all memory icons on the panel linked to the block to use the new one?",
"Update Memory Icons",
JOptionPane.YES_NO_OPTION);
// TODO I18N in Bundle.properties
found = true;
if (n == 0) {
updateall = true;
}
}
if (updateall) {
memIcon.setMemory(memoryName);
}
}
}
}
}
return m;
}
/**
* Get the color for drawing items in this block. Returns color based on
* block occupancy.
*
* @return color for block
*/
public Color getBlockColor() {
if (getOccupancy() == OCCUPIED) {
return blockOccupiedColor;
} else if (useExtraColor) {
return blockExtraColor;
} else {
return blockTrackColor;
}
}
/**
* Get the Block corresponding to this LayoutBlock.
*
* @return block
*/
public Block getBlock() {
return block;
}
/**
* Returns Memory name
*
* @return name of memory
*/
public String getMemoryName() {
if (namedMemory != null) {
return namedMemory.getName();
}
return memoryName;
}
/**
* Get Memory.
*
* @return memory bean
*/
public Memory getMemory() {
if (namedMemory == null) {
setMemoryName(memoryName);
}
if (namedMemory != null) {
return namedMemory.getBean();
}
return null;
}
/**
* Add Memory by name.
*
* @param name for memory
*/
public void setMemoryName(String name) {
if ((name == null) || name.isEmpty()) {
namedMemory = null;
memoryName = "";
return;
}
memoryName = name;
Memory memory = InstanceManager.memoryManagerInstance().getMemory(name);
if (memory != null) {
namedMemory = InstanceManager.getDefault(NamedBeanHandleManager.class).getNamedBeanHandle(name, memory);
}
}
public void setMemory(Memory m, String name) {
if (m == null) {
namedMemory = null;
memoryName = name == null ? "" : name;
return;
}
namedMemory = InstanceManager.getDefault(NamedBeanHandleManager.class).getNamedBeanHandle(name, m);
}
/**
* Get occupancy Sensor name.
*
* @return name of occupancy sensor
*/
public String getOccupancySensorName() {
if (occupancyNamedSensor == null) {
if (block != null) {
occupancyNamedSensor = block.getNamedSensor();
}
}
if (occupancyNamedSensor != null) {
return occupancyNamedSensor.getName();
}
return occupancySensorName;
}
/**
* Get occupancy Sensor.
*
* @return occ sensor name
*/
public Sensor getOccupancySensor() {
if (occupancyNamedSensor == null) {
if (block != null) {
occupancyNamedSensor = block.getNamedSensor();
}
}
if (occupancyNamedSensor != null) {
return occupancyNamedSensor.getBean();
}
return null;
}
/**
* Add occupancy sensor by name.
*
* @param name for senor to add
*/
public void setOccupancySensorName(String name) {
if ((name == null) || name.isEmpty()) {
if (occupancyNamedSensor != null) {
occupancyNamedSensor.getBean().removePropertyChangeListener(mBlockListener);
}
occupancyNamedSensor = null;
occupancySensorName = "";
if (block != null) {
block.setNamedSensor(null);
}
return;
}
occupancySensorName = name;
Sensor sensor = InstanceManager.sensorManagerInstance().getSensor(name);
if (sensor != null) {
occupancyNamedSensor = InstanceManager.getDefault(
NamedBeanHandleManager.class).getNamedBeanHandle(name, sensor);
if (block != null) {
block.setNamedSensor(occupancyNamedSensor);
}
}
}
/**
* Get occupied sensor state.
*
* @return occupied sensor state, defaults to Sensor.ACTIVE
*/
public int getOccupiedSense() {
return occupiedSense;
}
/**
* Set occupied sensor state.
*
* @param sense eg. Sensor.INACTIVE
*/
public void setOccupiedSense(int sense) {
occupiedSense = sense;
}
/**
* Test block occupancy.
*
* @return occupancy state
*/
public int getOccupancy() {
if (occupancyNamedSensor == null) {
Sensor s = null;
if (!occupancySensorName.isEmpty()) {
s = InstanceManager.sensorManagerInstance().getSensor(occupancySensorName);
}
if (s == null) {
// no occupancy sensor, so base upon block occupancy state
if (block != null) {
return block.getState();
}
// if no block or sensor return unknown
return UNKNOWN;
}
occupancyNamedSensor = InstanceManager.getDefault(
NamedBeanHandleManager.class).getNamedBeanHandle(occupancySensorName, s);
if (block != null) {
block.setNamedSensor(occupancyNamedSensor);
}
}
if (getOccupancySensor() == null) {
return UNKNOWN;
}
if (getOccupancySensor().getKnownState() != occupiedSense) {
return EMPTY;
} else if (getOccupancySensor().getKnownState() == occupiedSense) {
return OCCUPIED;
}
return UNKNOWN;
}
@Override
public int getState() {
return getOccupancy();
}
/**
* Does nothing, do not use. Dummy for completion of NamedBean interface
*/
@Override
public void setState(int i) {
log.error("this state does nothing {}", getDisplayName());
}
/**
* Get the panel with the highest connectivity to this Layout Block.
*
* @return panel with most connections to this block
*/
public LayoutEditor getMaxConnectedPanel() {
LayoutEditor result = null;
// a block is attached and this LayoutBlock is used
if ((block != null) && (panels.size() > 0)) {
// initialize connectivity as defined in first Layout Editor panel
int maxConnectivity = Integer.MIN_VALUE;
for (LayoutEditor panel : panels) {
List<LayoutConnectivity> c = panel.getLEAuxTools().getConnectivityList(this);
if (maxConnectivity < c.size()) {
maxConnectivity = c.size();
result = panel;
}
}
}
return result;
}
/**
* Check/Update Path objects for the attached Block
* <p>
* If multiple panels are present, Paths are set according to the panel with
* the highest connectivity (most LayoutConnectivity objects).
*/
public void updatePaths() {
// Update paths is called by the panel, turnouts, xings, track segments etc
if ((block != null) && !panels.isEmpty()) {
// a block is attached and this LayoutBlock is used
// initialize connectivity as defined in first Layout Editor panel
LayoutEditor panel = panels.get(0);
List<LayoutConnectivity> c = panel.getLEAuxTools().getConnectivityList(this);
// if more than one panel, find panel with the highest connectivity
if (panels.size() > 1) {
for (int i = 1; i < panels.size(); i++) {
if (c.size() < panels.get(i).getLEAuxTools().
getConnectivityList(this).size()) {
panel = panels.get(i);
c = panel.getLEAuxTools().getConnectivityList(this);
}
}
// Now try to determine if this block is across two panels due to a linked point
PositionablePoint point = panel.getFinder().findPositionableLinkPoint(this);
if ((point != null) && (point.getLinkedEditor() != null) && panels.contains(point.getLinkedEditor())) {
c = panel.getLEAuxTools().getConnectivityList(this);
c.addAll(point.getLinkedEditor().getLEAuxTools().getConnectivityList(this));
} else {
// check that this connectivity is compatible with that of other panels.
for (LayoutEditor tPanel : panels) {
if ((tPanel != panel) && InstanceManager.getDefault(
LayoutBlockManager.class).warn()
&& (!compareConnectivity(c, tPanel.getLEAuxTools().getConnectivityList(this)))) {
// send user an error message
int response = JOptionPane.showOptionDialog(null,
java.text.MessageFormat.format(Bundle.getMessage("Warn1"),
new Object[]{getUserName(), tPanel.getLayoutName(),
panel.getLayoutName()}), Bundle.getMessage("WarningTitle"),
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE,
null, new Object[]{Bundle.getMessage("ButtonOK"),
Bundle.getMessage("ButtonOKPlus")}, Bundle.getMessage("ButtonOK"));
if (response != 0) { // user elected to disable messages
InstanceManager.getDefault(
LayoutBlockManager.class).turnOffWarning();
}
}
}
}
}
// update block Paths to reflect connectivity as needed
updateBlockPaths(c, panel);
}
}
/**
* Check/Update Path objects for the attached Block using the connectivity
* in the specified Layout Editor panel.
*
* @param panel to extract paths
*/
public void updatePathsUsingPanel(LayoutEditor panel) {
if (panel == null) {
log.error("Null panel in call to updatePathsUsingPanel");
return;
}
List<LayoutConnectivity> c = panel.getLEAuxTools().getConnectivityList(this);
updateBlockPaths(c, panel);
}
private void updateBlockPaths(List<LayoutConnectivity> c, LayoutEditor panel) {
if (enableAddRouteLogging) {
log.info("From {} updateBlockPaths Called", this.getDisplayName());
}
auxTools = panel.getLEAuxTools();
List<Path> paths = block.getPaths();
boolean[] used = new boolean[c.size()];
int[] need = new int[paths.size()];
Arrays.fill(used, false);
Arrays.fill(need, -1);
// cycle over existing Paths, checking against LayoutConnectivity
for (int i = 0; i < paths.size(); i++) {
Path p = paths.get(i);
// cycle over LayoutConnectivity matching to this Path
for (int j = 0; ((j < c.size()) && (need[i] == -1)); j++) {
if (!used[j]) {
// this LayoutConnectivity not used yet
LayoutConnectivity lc = c.get(j);
if ((lc.getBlock1().getBlock() == p.getBlock()) || (lc.getBlock2().getBlock() == p.getBlock())) {
// blocks match - record
used[j] = true;
need[i] = j;
}
}
}
}
// update needed Paths
for (int i = 0; i < paths.size(); i++) {
if (need[i] >= 0) {
Path p = paths.get(i);
LayoutConnectivity lc = c.get(need[i]);
if (lc.getBlock1() == this) {
p.setToBlockDirection(lc.getDirection());
p.setFromBlockDirection(lc.getReverseDirection());
} else {
p.setToBlockDirection(lc.getReverseDirection());
p.setFromBlockDirection(lc.getDirection());
}
List<BeanSetting> beans = new ArrayList<>(p.getSettings());
for (BeanSetting bean : beans) {
p.removeSetting(bean);
}
auxTools.addBeanSettings(p, lc, this);
}
}
// delete unneeded Paths
for (int i = 0; i < paths.size(); i++) {
if (need[i] < 0) {
block.removePath(paths.get(i));
if (InstanceManager.getDefault(
LayoutBlockManager.class).isAdvancedRoutingEnabled()) {
removeAdjacency(paths.get(i));
}
}
}
// add Paths as required
for (int j = 0; j < c.size(); j++) {
if (!used[j]) {
// there is no corresponding Path, add one.
LayoutConnectivity lc = c.get(j);
Path newp;
if (lc.getBlock1() == this) {
newp = new Path(lc.getBlock2().getBlock(), lc.getDirection(),
lc.getReverseDirection());
} else {
newp = new Path(lc.getBlock1().getBlock(), lc.getReverseDirection(),
lc.getDirection());
}
block.addPath(newp);
if (enableAddRouteLogging) {
log.info("From {} addPath({})", this.getDisplayName(), newp.toString());
}
if (InstanceManager.getDefault(LayoutBlockManager.class).isAdvancedRoutingEnabled()) {
addAdjacency(newp);
}
auxTools.addBeanSettings(newp, lc, this);
}
}
// djd debugging - lists results of automatic initialization of Paths and BeanSettings
if (log.isDebugEnabled()) {
block.getPaths().stream().forEach((p) -> log.debug("From {} to {}", getDisplayName(), p.toString()));
}
}
/**
* Make sure all the layout connectivity objects in test are in main.
*
* @param main the main list of LayoutConnectivity objects
* @param test the test list of LayoutConnectivity objects
* @return true if all test layout connectivity objects are in main
*/
private boolean compareConnectivity(List<LayoutConnectivity> main, List<LayoutConnectivity> test) {
boolean result = false; // assume failure (pessimsit!)
if (!main.isEmpty() && !test.isEmpty()) {
result = true; // assume success (optimist!)
// loop over connectivities in test list
for (LayoutConnectivity tc : test) {
LayoutBlock tlb1 = tc.getBlock1(), tlb2 = tc.getBlock2();
// loop over main list to make sure the same blocks are connected
boolean found = false; // assume failure (pessimsit!)
for (LayoutConnectivity mc : main) {
LayoutBlock mlb1 = mc.getBlock1(), mlb2 = mc.getBlock2();
if (((tlb1 == mlb1) && (tlb2 == mlb2))
|| ((tlb1 == mlb2) && (tlb2 == mlb1))) {
found = true; // success!
break;
}
}
if (!found) {
result = false;
break;
}
}
} else if (main.isEmpty() && test.isEmpty()) {
result = true; // OK if both have no neighbors, common for turntable rays
}
return result;
}
/**
* Handle tasks when block changes
*
* @param e propChgEvent
*/
void handleBlockChange(PropertyChangeEvent e) {
// Update memory object if there is one
if ((getMemory() != null) && (block != null) && !suppressNameUpdate) {
// copy block value to memory if there is a value
Object val = block.getValue();
if (val != null) {
if (!(val instanceof RosterEntry) && !(val instanceof Reportable)) {
val = val.toString();
}
}
getMemory().setValue(val);
}
if (e.getPropertyName().equals("UserName")) {
setUserName(e.getNewValue().toString());
jmri.InstanceManager.getDefault(jmri.NamedBeanHandleManager.class).
renameBean(e.getOldValue().toString(), e.getNewValue().toString(), this);
}
// Redraw all Layout Editor panels using this Layout Block
redrawLayoutBlockPanels();
if (InstanceManager.getDefault(LayoutBlockManager.class).isAdvancedRoutingEnabled()) {
stateUpdate();
}
}
/**
* Deactivate block listener for redraw of panels and update of memories on
* change of state
*/
private void deactivateBlock() {
if ((mBlockListener != null) && (block != null)) {
block.removePropertyChangeListener(mBlockListener);
}
mBlockListener = null;
}
/**
* Set/reset update of memory name when block goes from occupied to
* unoccupied or vice versa. If set is true, name update is suppressed. If
* set is false, name update works normally.
*
* @param set true, update suppress. false, update normal
*/
public void setSuppressNameUpdate(boolean set) {
suppressNameUpdate = set;
}
// variables for Edit Layout Block pane
private JmriJFrame editLayoutBlockFrame = null;
private final JTextField sensorNameField = new JTextField(16);
private final JTextField sensorDebounceInactiveField = new JTextField(5);
private final JTextField sensorDebounceActiveField = new JTextField(5);
private final JCheckBox sensorDebounceGlobalCheck = new JCheckBox(Bundle.getMessage("SensorUseGlobalDebounce"));
private final NamedBeanComboBox<Memory> memoryComboBox = new NamedBeanComboBox<>(
InstanceManager.getDefault(MemoryManager.class), null, DisplayOptions.DISPLAYNAME);
private final JTextField metricField = new JTextField(10);
private final JComboBox<String> senseBox = new JComboBox<>();
private final JCheckBox permissiveCheck = new JCheckBox("Permissive Working Allowed");
// TODO I18N in Bundle.properties
private int senseActiveIndex;
private int senseInactiveIndex;
private JColorChooser trackColorChooser = null;
private JColorChooser occupiedColorChooser = null;
private JColorChooser extraColorChooser = null;
public void editLayoutBlock(Component callingPane) {
LayoutBlockEditAction beanEdit = new LayoutBlockEditAction();
if (block == null) {
// Block may not have been initialised due to an error so manually set it in the edit window
String userName = getUserName();
if ((userName != null) && !userName.isEmpty()) {
Block b = InstanceManager.getDefault(BlockManager.class).getBlock(userName);
if (b != null) {
beanEdit.setBean(b);
}
}
} else {
beanEdit.setBean(block);
}
beanEdit.actionPerformed(null);
}
private final String[] working = {"Bi-Directional", "Receive Only", "Send Only"};
// TODO I18N in ManagersBundle.properties
protected List<JComboBox<String>> neighbourDir;
void blockEditDonePressed(ActionEvent a) {
boolean needsRedraw = false;
// check if Sensor changed
String newName = NamedBean.normalizeUserName(sensorNameField.getText());
if (!(getOccupancySensorName()).equals(newName)) {
// sensor has changed
if ((newName == null) || newName.isEmpty()) {
setOccupancySensorName(newName);
sensorNameField.setText("");
needsRedraw = true;
} else if (validateSensor(newName, editLayoutBlockFrame) == null) {
// invalid sensor entered
occupancyNamedSensor = null;
occupancySensorName = "";
sensorNameField.setText("");
return;
} else {
sensorNameField.setText(newName);
needsRedraw = true;
}
}
if (getOccupancySensor() != null) {
if (sensorDebounceGlobalCheck.isSelected()) {
getOccupancySensor().setUseDefaultTimerSettings(true);
} else {
getOccupancySensor().setUseDefaultTimerSettings(false);
if (!sensorDebounceInactiveField.getText().trim().isEmpty()) {
getOccupancySensor().setSensorDebounceGoingInActiveTimer(Long.parseLong(sensorDebounceInactiveField.getText().trim()));
}
if (!sensorDebounceActiveField.getText().trim().isEmpty()) {
getOccupancySensor().setSensorDebounceGoingActiveTimer(Long.parseLong(sensorDebounceActiveField.getText().trim()));
}
}
Reporter reporter = getOccupancySensor().getReporter();
if (reporter != null && block != null) {
String msg = java.text.MessageFormat.format(
Bundle.getMessage("BlockAssignReporter"),
new Object[]{getOccupancySensor().getDisplayName(),
reporter.getDisplayName()});
if (JOptionPane.showConfirmDialog(editLayoutBlockFrame,
msg, Bundle.getMessage("BlockAssignReporterTitle"),
JOptionPane.YES_NO_OPTION) == 0) {
block.setReporter(reporter);
}
}
}
// check if occupied sense changed
int k = senseBox.getSelectedIndex();
int oldSense = occupiedSense;
if (k == senseActiveIndex) {
occupiedSense = Sensor.ACTIVE;
} else {
occupiedSense = Sensor.INACTIVE;
}
if (oldSense != occupiedSense) {