001package jmri.jmrit.operations.trains;
002
003import java.awt.*;
004import java.util.ArrayList;
005import java.util.List;
006
007import javax.swing.*;
008
009import jmri.InstanceManager;
010import jmri.jmrit.operations.*;
011import jmri.jmrit.operations.locations.Location;
012import jmri.jmrit.operations.locations.LocationManager;
013import jmri.jmrit.operations.rollingstock.RollingStock;
014import jmri.jmrit.operations.rollingstock.cars.*;
015import jmri.jmrit.operations.rollingstock.engines.*;
016import jmri.jmrit.operations.routes.*;
017import jmri.jmrit.operations.setup.Control;
018import jmri.jmrit.operations.setup.Setup;
019import jmri.jmrit.operations.trains.tools.*;
020import jmri.util.swing.JmriJOptionPane;
021
022/**
023 * Frame for user edit of a train
024 *
025 * @author Dan Boudreau Copyright (C) 2008, 2011, 2012, 2013, 2014
026 */
027public class TrainEditFrame extends OperationsFrame implements java.beans.PropertyChangeListener {
028
029    TrainManager trainManager = InstanceManager.getDefault(TrainManager.class);
030    RouteManager routeManager = InstanceManager.getDefault(RouteManager.class);
031
032    public Train _train = null;
033    List<JCheckBox> typeCarCheckBoxes = new ArrayList<>();
034    List<JCheckBox> typeEngineCheckBoxes = new ArrayList<>();
035    List<JCheckBox> locationCheckBoxes = new ArrayList<>();
036    JPanel typeCarPanelCheckBoxes = new JPanel();
037    JPanel typeEnginePanelCheckBoxes = new JPanel();
038    JPanel roadAndLoadStatusPanel = new JPanel();
039    JPanel locationPanelCheckBoxes = new JPanel();
040    JScrollPane typeCarPane;
041    JScrollPane typeEnginePane;
042    JScrollPane locationsPane;
043
044    // labels
045    JLabel textRouteStatus = new JLabel();
046    JLabel textModel = new JLabel(Bundle.getMessage("Model"));
047    JLabel textRoad2 = new JLabel(Bundle.getMessage("Road"));
048    JLabel textRoad3 = new JLabel(Bundle.getMessage("Road"));
049    JLabel textEngine = new JLabel(Bundle.getMessage("Engines"));
050
051    // major buttons
052    JButton editButton = new JButton(Bundle.getMessage("ButtonEdit")); // edit route
053    JButton clearButton = new JButton(Bundle.getMessage("ClearAll"));
054    JButton setButton = new JButton(Bundle.getMessage("SelectAll"));
055    JButton resetButton = new JButton(Bundle.getMessage("ResetTrain"));
056    JButton saveTrainButton = new JButton(Bundle.getMessage("SaveTrain"));
057    JButton deleteTrainButton = new JButton(Bundle.getMessage("DeleteTrain"));
058    JButton addTrainButton = new JButton(Bundle.getMessage("AddTrain"));
059
060    // alternate buttons
061    JButton loadOptionButton = new JButton(Bundle.getMessage("AcceptAll"));
062    JButton roadOptionButton = new JButton(Bundle.getMessage("AcceptAll"));
063
064    // radio buttons
065    JRadioButton noneRadioButton = new JRadioButton(Bundle.getMessage("None"));
066    JRadioButton cabooseRadioButton = new JRadioButton(Bundle.getMessage("Caboose"));
067    JRadioButton fredRadioButton = new JRadioButton(Bundle.getMessage("FRED"));
068    ButtonGroup group = new ButtonGroup();
069
070    // text field
071    JTextField trainNameTextField = new JTextField(Control.max_len_string_train_name - 5); // make slightly smaller
072    JTextField trainDescriptionTextField = new JTextField(30);
073
074    // text area
075    JTextArea commentTextArea = new JTextArea(2, 70);
076    JScrollPane commentScroller = new JScrollPane(commentTextArea);
077    JColorChooser commentColorChooser = new JColorChooser(Color.black);
078
079    // for padding out panel
080    JLabel space1 = new JLabel(" "); // before hour
081    JLabel space2 = new JLabel(" "); // between hour and minute
082    JLabel space3 = new JLabel(" "); // after minute
083    JLabel space4 = new JLabel(" "); // between route and edit
084    JLabel space5 = new JLabel(" "); // after edit
085
086    // combo boxes
087    JComboBox<String> hourBox = new JComboBox<>();
088    JComboBox<String> minuteBox = new JComboBox<>();
089    JComboBox<Route> routeBox = routeManager.getComboBox();
090    JComboBox<String> roadCabooseBox = new JComboBox<>();
091    JComboBox<String> roadEngineBox = new JComboBox<>();
092    JComboBox<String> modelEngineBox = InstanceManager.getDefault(EngineModels.class).getComboBox();
093    JComboBox<String> numEnginesBox = new JComboBox<>();
094
095    JMenu toolMenu = new JMenu(Bundle.getMessage("MenuTools"));
096
097    public static final String DISPOSE = "dispose"; // NOI18N
098
099    public TrainEditFrame(Train train) {
100        super(Bundle.getMessage("TitleTrainEdit"));
101        // Set up the jtable in a Scroll Pane..
102        locationsPane = new JScrollPane(locationPanelCheckBoxes);
103        locationsPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
104        locationsPane.setBorder(BorderFactory.createTitledBorder(Bundle.getMessage("Stops")));
105
106        typeCarPane = new JScrollPane(typeCarPanelCheckBoxes);
107        typeCarPane.setBorder(BorderFactory.createTitledBorder(Bundle.getMessage("TypesCar")));
108        typeCarPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
109
110        typeEnginePane = new JScrollPane(typeEnginePanelCheckBoxes);
111        typeEnginePane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
112        typeEnginePane.setBorder(BorderFactory.createTitledBorder(Bundle.getMessage("TypesEngine")));
113
114        _train = train;
115
116        getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
117
118        // Set up the panels
119        JPanel p = new JPanel();
120        p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
121        JScrollPane pPane = new JScrollPane(p);
122        pPane.setMinimumSize(new Dimension(300, 5 * trainNameTextField.getPreferredSize().height));
123        pPane.setBorder(BorderFactory.createTitledBorder(""));
124
125        // Layout the panel by rows
126        // row 1
127        JPanel p1 = new JPanel();
128        p1.setLayout(new BoxLayout(p1, BoxLayout.X_AXIS));
129        // row 1a
130        JPanel pName = new JPanel();
131        pName.setLayout(new GridBagLayout());
132        pName.setBorder(BorderFactory.createTitledBorder(Bundle.getMessage("Name")));
133        addItem(pName, trainNameTextField, 0, 0);
134        // row 1b
135        JPanel pDesc = new JPanel();
136        pDesc.setLayout(new GridBagLayout());
137        pDesc.setBorder(BorderFactory.createTitledBorder(Bundle.getMessage("Description")));
138        trainDescriptionTextField.setToolTipText(Bundle.getMessage("TipTrainDescription"));
139        addItem(pDesc, trainDescriptionTextField, 0, 0);
140
141        p1.add(pName);
142        p1.add(pDesc);
143
144        // row 2
145        JPanel p2 = new JPanel();
146        p2.setLayout(new BoxLayout(p2, BoxLayout.X_AXIS));
147        // row 2a
148        JPanel pdt = new JPanel();
149        pdt.setLayout(new GridBagLayout());
150        pdt.setBorder(BorderFactory.createTitledBorder(Bundle.getMessage("DepartTime")));
151
152        // build hour and minute menus
153        hourBox.setPrototypeDisplayValue("000"); // needed for font size 9
154        minuteBox.setPrototypeDisplayValue("000");
155        for (int i = 0; i < 24; i++) {
156            if (i < 10) {
157                hourBox.addItem("0" + Integer.toString(i));
158            } else {
159                hourBox.addItem(Integer.toString(i));
160            }
161        }
162        for (int i = 0; i < 60; i += 1) {
163            if (i < 10) {
164                minuteBox.addItem("0" + Integer.toString(i));
165            } else {
166                minuteBox.addItem(Integer.toString(i));
167            }
168        }
169
170        addItem(pdt, space1, 0, 5);
171        addItem(pdt, hourBox, 1, 5);
172        addItem(pdt, space2, 2, 5);
173        addItem(pdt, minuteBox, 3, 5);
174        addItem(pdt, space3, 4, 5);
175        // row 2b
176        // BUG! routeBox needs its own panel when resizing frame!
177        JPanel pr = new JPanel();
178        pr.setLayout(new GridBagLayout());
179        pr.setBorder(BorderFactory.createTitledBorder(Bundle.getMessage("Route")));
180        addItem(pr, routeBox, 0, 5);
181        addItem(pr, space4, 1, 5);
182        addItem(pr, editButton, 2, 5);
183        addItem(pr, space5, 3, 5);
184        addItem(pr, textRouteStatus, 4, 5);
185
186        p2.add(pdt);
187        p2.add(pr);
188
189        p.add(p1);
190        p.add(p2);
191
192        // row 5
193        locationPanelCheckBoxes.setLayout(new GridBagLayout());
194
195        // row 6
196        typeCarPanelCheckBoxes.setLayout(new GridBagLayout());
197
198        // row 8
199        typeEnginePanelCheckBoxes.setLayout(new GridBagLayout());
200
201        // status panel for roads and loads
202        roadAndLoadStatusPanel.setLayout(new BoxLayout(roadAndLoadStatusPanel, BoxLayout.X_AXIS));
203        JPanel pRoadOption = new JPanel();
204        pRoadOption.setBorder(BorderFactory.createTitledBorder(Bundle.getMessage("RoadOption")));
205        pRoadOption.add(roadOptionButton);
206        roadOptionButton.addActionListener(new TrainRoadOptionsAction(this));
207
208        JPanel pLoadOption = new JPanel();
209        pLoadOption.setBorder(BorderFactory.createTitledBorder(Bundle.getMessage("LoadOption")));
210        pLoadOption.add(loadOptionButton);
211        loadOptionButton.addActionListener(new TrainLoadOptionsAction(this));
212
213        roadAndLoadStatusPanel.add(pRoadOption);
214        roadAndLoadStatusPanel.add(pLoadOption);
215        roadAndLoadStatusPanel.setVisible(false); // don't show unless there's a restriction
216
217        // row 10
218        JPanel trainReq = new JPanel();
219        trainReq.setLayout(new GridBagLayout());
220        trainReq.setBorder(BorderFactory.createTitledBorder(Bundle.getMessage("TrainRequires")));
221
222        for (int i = 0; i < Setup.getMaxNumberEngines() + 1; i++) {
223            numEnginesBox.addItem(Integer.toString(i));
224        }
225        numEnginesBox.addItem(Train.AUTO);
226        numEnginesBox.setMinimumSize(new Dimension(100, 20));
227        numEnginesBox.setToolTipText(Bundle.getMessage("TipNumberOfLocos"));
228        addItem(trainReq, textEngine, 1, 1);
229        addItem(trainReq, numEnginesBox, 2, 1);
230        addItem(trainReq, textModel, 3, 1);
231        modelEngineBox.insertItemAt(NONE, 0);
232        modelEngineBox.setSelectedIndex(0);
233        modelEngineBox.setMinimumSize(new Dimension(120, 20));
234        modelEngineBox.setToolTipText(Bundle.getMessage("ModelEngineTip"));
235        addItem(trainReq, modelEngineBox, 4, 1);
236        addItem(trainReq, textRoad2, 5, 1);
237        roadEngineBox.insertItemAt(NONE, 0);
238        roadEngineBox.setSelectedIndex(0);
239        roadEngineBox.setMinimumSize(new Dimension(120, 20));
240        roadEngineBox.setToolTipText(Bundle.getMessage("RoadEngineTip"));
241        addItem(trainReq, roadEngineBox, 6, 1);
242
243        JPanel trainLastCar = new JPanel();
244        trainLastCar.setLayout(new GridBagLayout());
245        trainLastCar.setBorder(BorderFactory.createTitledBorder(Bundle.getMessage("TrainLastCar")));
246
247        addItem(trainLastCar, noneRadioButton, 2, 2);
248        noneRadioButton.setToolTipText(Bundle.getMessage("TipNoCabooseOrFRED"));
249        addItem(trainLastCar, fredRadioButton, 3, 2);
250        fredRadioButton.setToolTipText(Bundle.getMessage("TipFRED"));
251        addItem(trainLastCar, cabooseRadioButton, 4, 2);
252        cabooseRadioButton.setToolTipText(Bundle.getMessage("TipCaboose"));
253        addItem(trainLastCar, textRoad3, 5, 2);
254        roadCabooseBox.setMinimumSize(new Dimension(120, 20));
255        roadCabooseBox.setToolTipText(Bundle.getMessage("RoadCabooseTip"));
256        addItem(trainLastCar, roadCabooseBox, 6, 2);
257        group.add(noneRadioButton);
258        group.add(cabooseRadioButton);
259        group.add(fredRadioButton);
260        noneRadioButton.setSelected(true);
261
262        // row 13 comment
263        JPanel pC = new JPanel();
264        pC.setBorder(BorderFactory.createTitledBorder(Bundle.getMessage("Comment")));
265        pC.setLayout(new GridBagLayout());
266        addItem(pC, commentScroller, 1, 0);
267        if (_train != null) {
268            addItem(pC, OperationsPanel.getColorChooserPanel(_train.getCommentWithColor(), commentColorChooser), 2, 0);
269        } else {
270            addItem(pC, OperationsPanel.getColorChooserPanel("", commentColorChooser), 2, 0);
271        }
272
273        // adjust text area width based on window size less color chooser
274        Dimension d = new Dimension(getPreferredSize().width - 100, getPreferredSize().height);
275        adjustTextAreaColumnWidth(commentScroller, commentTextArea, d);
276
277        // row 15 buttons
278        JPanel pB = new JPanel();
279        pB.setLayout(new GridBagLayout());
280        addItem(pB, deleteTrainButton, 0, 0);
281        addItem(pB, resetButton, 1, 0);
282        addItem(pB, addTrainButton, 2, 0);
283        addItem(pB, saveTrainButton, 3, 0);
284
285        getContentPane().add(pPane);
286        getContentPane().add(locationsPane);
287        getContentPane().add(typeCarPane);
288        getContentPane().add(typeEnginePane);
289        getContentPane().add(roadAndLoadStatusPanel);
290        getContentPane().add(trainReq);
291        getContentPane().add(trainLastCar);
292        getContentPane().add(pC);
293        getContentPane().add(pB);
294
295        // setup buttons
296        addButtonAction(editButton);
297        addButtonAction(setButton);
298        addButtonAction(clearButton);
299        addButtonAction(resetButton);
300        addButtonAction(deleteTrainButton);
301        addButtonAction(addTrainButton);
302        addButtonAction(saveTrainButton);
303
304        addRadioButtonAction(noneRadioButton);
305        addRadioButtonAction(cabooseRadioButton);
306        addRadioButtonAction(fredRadioButton);
307
308        // tool tips
309        resetButton.setToolTipText(Bundle.getMessage("TipTrainReset"));
310
311        // build menu
312        JMenuBar menuBar = new JMenuBar();
313        menuBar.add(toolMenu);
314        loadToolMenu(toolMenu);
315        setJMenuBar(menuBar);
316        addHelpMenu("package.jmri.jmrit.operations.Operations_TrainEdit", true); // NOI18N
317
318        if (_train != null) {
319            trainNameTextField.setText(_train.getName());
320            trainDescriptionTextField.setText(_train.getRawDescription());
321            routeBox.setSelectedItem(_train.getRoute());
322            modelEngineBox.setSelectedItem(_train.getEngineModel());
323            commentTextArea.setText(TrainCommon.getTextColorString(_train.getCommentWithColor()));
324            cabooseRadioButton.setSelected(_train.isCabooseNeeded());
325            fredRadioButton.setSelected(_train.isFredNeeded());
326            updateDepartureTime();
327            enableButtons(true);
328            // listen for train changes
329            _train.addPropertyChangeListener(this);
330
331            Route route = _train.getRoute();
332            if (route != null) {
333                if (_train.getTrainDepartsRouteLocation() != null &&
334                        _train.getTrainDepartsRouteLocation().getLocation() != null &&
335                        !_train.getTrainDepartsRouteLocation().getLocation().isStaging())
336                    numEnginesBox.addItem(Train.AUTO_HPT);
337            }
338            numEnginesBox.setSelectedItem(_train.getNumberEngines());
339        } else {
340            setTitle(Bundle.getMessage("TitleTrainAdd"));
341            enableButtons(false);
342        }
343
344        modelEngineBox.setEnabled(!numEnginesBox.getSelectedItem().equals("0"));
345        roadEngineBox.setEnabled(!numEnginesBox.getSelectedItem().equals("0"));
346
347        // load route location checkboxes
348        updateLocationCheckboxes();
349        updateCarTypeCheckboxes();
350        updateEngineTypeCheckboxes();
351        updateRoadAndLoadStatus();
352        updateCabooseRoadComboBox();
353        updateEngineRoadComboBox();
354
355        // setup combobox
356        addComboBoxAction(numEnginesBox);
357        addComboBoxAction(routeBox);
358        addComboBoxAction(modelEngineBox);
359
360        // get notified if combo box gets modified
361        routeManager.addPropertyChangeListener(this);
362        // get notified if car types or roads gets modified
363        InstanceManager.getDefault(CarTypes.class).addPropertyChangeListener(this);
364        InstanceManager.getDefault(CarRoads.class).addPropertyChangeListener(this);
365        InstanceManager.getDefault(EngineTypes.class).addPropertyChangeListener(this);
366        InstanceManager.getDefault(EngineModels.class).addPropertyChangeListener(this);
367        InstanceManager.getDefault(LocationManager.class).addPropertyChangeListener(this);
368
369        initMinimumSize(new Dimension(Control.panelWidth600, Control.panelHeight600));
370    }
371
372    private void loadToolMenu(JMenu toolMenu) {
373        toolMenu.removeAll();
374        // first 5 menu items will also close when the edit train window closes
375        toolMenu.add(new TrainEditBuildOptionsAction(this));
376        toolMenu.add(new TrainLoadOptionsAction(this));
377        toolMenu.add(new TrainRoadOptionsAction(this));
378        toolMenu.add(new TrainManifestOptionAction(this));
379        toolMenu.add(new TrainCopyAction(_train));
380        toolMenu.addSeparator();
381        toolMenu.add(new TrainScriptAction(this));
382        toolMenu.add(new TrainConductorAction(_train));
383        toolMenu.addSeparator();
384        toolMenu.add(new TrainByCarTypeAction(_train));
385        toolMenu.addSeparator();
386        toolMenu.add(new PrintTrainAction(false, _train));
387        toolMenu.add(new PrintTrainAction(true, _train));
388        toolMenu.add(new PrintTrainManifestAction(false, _train));
389        toolMenu.add(new PrintTrainManifestAction(true, _train));
390        toolMenu.add(new PrintTrainBuildReportAction(false, _train));
391        toolMenu.add(new PrintTrainBuildReportAction(true, _train));
392        toolMenu.add(new PrintSavedTrainManifestAction(false, _train));
393        toolMenu.add(new PrintSavedTrainManifestAction(true, _train));
394        toolMenu.add(new PrintSavedBuildReportAction(false, _train));
395        toolMenu.add(new PrintSavedBuildReportAction(true, _train));
396    }
397
398    // Save, Delete, Add, Edit, Reset, Set, Clear
399    @Override
400    public void buttonActionPerformed(java.awt.event.ActionEvent ae) {
401        Train train = trainManager.getTrainByName(trainNameTextField.getText().trim());
402        if (ae.getSource() == saveTrainButton) {
403            log.debug("train save button activated");
404            if (_train == null && train == null) {
405                saveNewTrain(); // this can't happen, Save button is disabled
406            } else {
407                if (train != null && train != _train) {
408                    reportTrainExists(Bundle.getMessage("save"));
409                    return;
410                }
411                // check to see if user supplied a route
412                if (!checkRoute() || !saveTrain()) {
413                    return;
414                }
415            }
416            if (Setup.isCloseWindowOnSaveEnabled()) {
417                dispose();
418            }
419        }
420        if (ae.getSource() == deleteTrainButton) {
421            log.debug("train delete button activated");
422            if (train == null) {
423                return;
424            }
425            if (!_train.reset()) {
426                JmriJOptionPane.showMessageDialog(this,
427                        Bundle.getMessage("TrainIsInRoute",
428                                train.getTrainTerminatesName()),
429                        Bundle.getMessage("CanNotDeleteTrain"), JmriJOptionPane.ERROR_MESSAGE);
430                return;
431            }
432            if (JmriJOptionPane.showConfirmDialog(this,
433                    Bundle.getMessage("deleteMsg", train.getName()),
434                    Bundle.getMessage("deleteTrain"), JmriJOptionPane.YES_NO_OPTION) != JmriJOptionPane.YES_OPTION) {
435                return;
436            }
437            routeBox.setSelectedItem(null);
438            trainManager.deregister(train);
439            for (Frame frame : children) {
440                frame.dispose();
441            }
442            _train = null;
443            enableButtons(false);
444            // save train file
445            OperationsXml.save();
446        }
447        if (ae.getSource() == addTrainButton) {
448            if (train != null) {
449                reportTrainExists(Bundle.getMessage("add"));
450                return;
451            }
452            saveNewTrain();
453        }
454        if (ae.getSource() == editButton) {
455            editAddRoute();
456        }
457        if (ae.getSource() == setButton) {
458            selectCheckboxes(true);
459        }
460        if (ae.getSource() == clearButton) {
461            selectCheckboxes(false);
462        }
463        if (ae.getSource() == resetButton) {
464            if (_train != null) {
465                if (!_train.reset()) {
466                    JmriJOptionPane.showMessageDialog(this,
467                            Bundle.getMessage("TrainIsInRoute",
468                                    _train.getTrainTerminatesName()),
469                            Bundle.getMessage("CanNotResetTrain"), JmriJOptionPane.ERROR_MESSAGE);
470                }
471            }
472        }
473    }
474
475    @Override
476    public void radioButtonActionPerformed(java.awt.event.ActionEvent ae) {
477        log.debug("radio button activated");
478        if (_train != null) {
479            if (ae.getSource() == noneRadioButton ||
480                    ae.getSource() == cabooseRadioButton ||
481                    ae.getSource() == fredRadioButton) {
482                updateCabooseRoadComboBox();
483            }
484        }
485    }
486
487    private void saveNewTrain() {
488        if (!checkName(Bundle.getMessage("add"))) {
489            return;
490        }
491        Train train = trainManager.newTrain(trainNameTextField.getText());
492        _train = train;
493        _train.addPropertyChangeListener(this);
494
495        // update check boxes
496        updateCarTypeCheckboxes();
497        updateEngineTypeCheckboxes();
498        // enable check boxes and buttons
499        enableButtons(true);
500        saveTrain();
501        loadToolMenu(toolMenu);
502    }
503
504    private boolean saveTrain() {
505        if (!checkName(Bundle.getMessage("save"))) {
506            return false;
507        }
508        if (!checkModel() || !checkEngineRoad()) {
509            return false;
510        }
511        if (!_train.getName().equals(trainNameTextField.getText().trim()) ||
512                !_train.getRawDescription().equals(trainDescriptionTextField.getText()) ||
513                !_train.getCommentWithColor().equals(
514                        TrainCommon.formatColorString(commentTextArea.getText(), commentColorChooser.getColor()))) {
515            _train.setModified(true);
516        }
517        _train.setDepartureTime(hourBox.getSelectedItem().toString(), minuteBox.getSelectedItem().toString());
518        _train.setNumberEngines((String) numEnginesBox.getSelectedItem());
519        if (_train.getNumberEngines().equals("0")) {
520            modelEngineBox.setSelectedIndex(0);
521            roadEngineBox.setSelectedIndex(0);
522        }
523        _train.setEngineRoad((String) roadEngineBox.getSelectedItem());
524        _train.setEngineModel((String) modelEngineBox.getSelectedItem());
525        if (cabooseRadioButton.isSelected()) {
526            _train.setRequirements(Train.CABOOSE);
527        }
528        if (fredRadioButton.isSelected()) {
529            _train.setRequirements(Train.FRED);
530        }
531        if (noneRadioButton.isSelected()) {
532            _train.setRequirements(Train.NO_CABOOSE_OR_FRED);
533        }
534        _train.setCabooseRoad((String) roadCabooseBox.getSelectedItem());
535        _train.setName(trainNameTextField.getText().trim());
536        _train.setDescription(trainDescriptionTextField.getText());
537        _train.setComment(TrainCommon.formatColorString(commentTextArea.getText(), commentColorChooser.getColor()));
538        // save train file
539        OperationsXml.save();
540        return true;
541    }
542
543    /**
544     *
545     * @return true if name isn't too long and is at least one character
546     */
547    private boolean checkName(String s) {
548        String trainName = trainNameTextField.getText().trim();
549        if (trainName.isEmpty()) {
550            log.debug("Must enter a train name");
551            JmriJOptionPane.showMessageDialog(this, Bundle.getMessage("MustEnterName"),
552                    Bundle.getMessage("CanNot", s), JmriJOptionPane.ERROR_MESSAGE);
553            return false;
554        }
555        if (trainName.length() > Control.max_len_string_train_name) {
556            JmriJOptionPane.showMessageDialog(this,
557                    Bundle.getMessage("TrainNameLess",
558                            Control.max_len_string_train_name + 1),
559                    Bundle.getMessage("CanNot", s), JmriJOptionPane.ERROR_MESSAGE);
560            return false;
561        }
562        if (!OperationsXml.checkFileName(trainName)) { // NOI18N
563            log.error("Train name must not contain reserved characters");
564            JmriJOptionPane.showMessageDialog(this,
565                    Bundle.getMessage("NameResChar") + NEW_LINE + Bundle.getMessage("ReservedChar"),
566                    Bundle.getMessage("CanNot", s), JmriJOptionPane.ERROR_MESSAGE);
567            return false;
568        }
569
570        return true;
571    }
572
573    private boolean checkModel() {
574        String model = (String) modelEngineBox.getSelectedItem();
575        if (numEnginesBox.getSelectedItem().equals("0") || model.equals(NONE)) {
576            return true;
577        }
578        String type = InstanceManager.getDefault(EngineModels.class).getModelType(model);
579        if (!_train.isTypeNameAccepted(type)) {
580            JmriJOptionPane.showMessageDialog(this,
581                    Bundle.getMessage("TrainModelService", model, type),
582                    Bundle.getMessage("CanNot", Bundle.getMessage("save")),
583                    JmriJOptionPane.ERROR_MESSAGE);
584            return false;
585        }
586        if (roadEngineBox.getItemCount() == 1) {
587            log.debug("No locos available that match the model selected!");
588            JmriJOptionPane.showMessageDialog(this,
589                    Bundle.getMessage("NoLocosModel", model),
590                    Bundle.getMessage("TrainWillNotBuild", _train.getName()),
591                    JmriJOptionPane.WARNING_MESSAGE);
592        }
593        return true;
594    }
595
596    private boolean checkEngineRoad() {
597        String road = (String) roadEngineBox.getSelectedItem();
598        if (numEnginesBox.getSelectedItem().equals("0") || road.equals(NONE)) {
599            return true;
600        }
601        if (!road.equals(NONE) && !_train.isLocoRoadNameAccepted(road)) {
602            JmriJOptionPane.showMessageDialog(this,
603                    Bundle.getMessage("TrainNotThisRoad", _train.getName(), road),
604                    Bundle.getMessage("TrainWillNotBuild", _train.getName()),
605                    JmriJOptionPane.WARNING_MESSAGE);
606            return false;
607        }
608        for (RollingStock rs : InstanceManager.getDefault(EngineManager.class).getList()) {
609            if (!_train.isTypeNameAccepted(rs.getTypeName())) {
610                continue;
611            }
612            if (rs.getRoadName().equals(road)) {
613                return true;
614            }
615        }
616        JmriJOptionPane.showMessageDialog(this,
617                Bundle.getMessage("NoLocoRoad", road),
618                Bundle.getMessage("TrainWillNotBuild", _train.getName()),
619                JmriJOptionPane.WARNING_MESSAGE);
620        return false; // couldn't find a loco with the selected road
621    }
622
623    private boolean checkRoute() {
624        if (_train.getRoute() == null) {
625            JmriJOptionPane.showMessageDialog(this, Bundle.getMessage("TrainNeedsRoute"), Bundle.getMessage("TrainNoRoute"),
626                    JmriJOptionPane.WARNING_MESSAGE);
627            return false;
628        }
629        return true;
630
631    }
632
633    private void reportTrainExists(String s) {
634        log.debug("Can not {}, train already exists", s);
635        JmriJOptionPane.showMessageDialog(this, Bundle.getMessage("TrainNameExists"),
636                Bundle.getMessage("CanNot", s), JmriJOptionPane.ERROR_MESSAGE);
637    }
638
639    private void enableButtons(boolean enabled) {
640        toolMenu.setEnabled(enabled);
641        editButton.setEnabled(enabled);
642        routeBox.setEnabled(enabled && _train != null && !_train.isBuilt());
643        clearButton.setEnabled(enabled);
644        resetButton.setEnabled(enabled);
645        setButton.setEnabled(enabled);
646        saveTrainButton.setEnabled(enabled);
647        deleteTrainButton.setEnabled(enabled);
648        numEnginesBox.setEnabled(enabled);
649        enableCheckboxes(enabled);
650        noneRadioButton.setEnabled(enabled);
651        fredRadioButton.setEnabled(enabled);
652        cabooseRadioButton.setEnabled(enabled);
653        roadOptionButton.setEnabled(enabled);
654        loadOptionButton.setEnabled(enabled);
655        // the inverse!
656        addTrainButton.setEnabled(!enabled);
657    }
658
659    private void selectCheckboxes(boolean enable) {
660        for (int i = 0; i < typeCarCheckBoxes.size(); i++) {
661            JCheckBox checkBox = typeCarCheckBoxes.get(i);
662            checkBox.setSelected(enable);
663            if (_train != null) {
664                _train.removePropertyChangeListener(this);
665                if (enable) {
666                    _train.addTypeName(checkBox.getText());
667                } else {
668                    _train.deleteTypeName(checkBox.getText());
669                }
670                _train.addPropertyChangeListener(this);
671            }
672        }
673    }
674
675    @Override
676    public void comboBoxActionPerformed(java.awt.event.ActionEvent ae) {
677        if (_train == null) {
678            return;
679        }
680        if (ae.getSource() == numEnginesBox) {
681            modelEngineBox.setEnabled(!numEnginesBox.getSelectedItem().equals("0"));
682            roadEngineBox.setEnabled(!numEnginesBox.getSelectedItem().equals("0"));
683        }
684        if (ae.getSource() == modelEngineBox) {
685            updateEngineRoadComboBox();
686        }
687        if (ae.getSource() == routeBox) {
688            if (routeBox.isEnabled()) {
689                Route route = _train.getRoute();
690                if (route != null) {
691                    route.removePropertyChangeListener(this);
692                }
693                Object selected = routeBox.getSelectedItem();
694                if (selected != null) {
695                    route = (Route) selected;
696                    _train.setRoute(route);
697                    route.addPropertyChangeListener(this);
698                } else {
699                    _train.setRoute(null);
700                }
701                updateLocationCheckboxes();
702                pack();
703                repaint();
704            }
705        }
706    }
707
708    private void enableCheckboxes(boolean enable) {
709        for (int i = 0; i < typeCarCheckBoxes.size(); i++) {
710            typeCarCheckBoxes.get(i).setEnabled(enable);
711        }
712        for (int i = 0; i < typeEngineCheckBoxes.size(); i++) {
713            typeEngineCheckBoxes.get(i).setEnabled(enable);
714        }
715    }
716
717    private void addLocationCheckBoxAction(JCheckBox b) {
718        b.addActionListener(new java.awt.event.ActionListener() {
719            @Override
720            public void actionPerformed(java.awt.event.ActionEvent e) {
721                locationCheckBoxActionPerformed(e);
722            }
723        });
724    }
725
726    public void locationCheckBoxActionPerformed(java.awt.event.ActionEvent ae) {
727        JCheckBox b = (JCheckBox) ae.getSource();
728        log.debug("checkbox change {}", b.getText());
729        if (_train == null) {
730            return;
731        }
732        String id = b.getName();
733        if (b.isSelected()) {
734            _train.deleteTrainSkipsLocation(id);
735        } else {
736            // check to see if skipped location is staging
737            if (_train.getRoute().getLocationById(id).getLocation().isStaging()) {
738                int result = JmriJOptionPane.showConfirmDialog(this,
739                        Bundle.getMessage("TrainRouteStaging",
740                                _train.getName(), _train.getRoute().getLocationById(id).getName()),
741                        Bundle.getMessage("TrainRouteNotStaging"), JmriJOptionPane.OK_CANCEL_OPTION);
742                if (result != JmriJOptionPane.OK_OPTION ) {
743                    b.setSelected(true);
744                    return; // don't skip staging
745                }
746            }
747            _train.addTrainSkipsLocation(id);
748        }
749    }
750
751    private void updateRouteComboBox() {
752        routeBox.setEnabled(false);
753        routeManager.updateComboBox(routeBox);
754        if (_train != null) {
755            routeBox.setSelectedItem(_train.getRoute());
756        }
757        routeBox.setEnabled(true);
758    }
759
760    private void updateCarTypeCheckboxes() {
761        typeCarCheckBoxes.clear();
762        typeCarPanelCheckBoxes.removeAll();
763        loadCarTypes();
764        enableCheckboxes(_train != null);
765        typeCarPanelCheckBoxes.revalidate();
766        repaint();
767    }
768
769    private void loadCarTypes() {
770        int numberOfCheckboxes = getNumberOfCheckboxesPerLine(); // number per line
771        int x = 0;
772        int y = 1; // vertical position in panel
773        for (String type : InstanceManager.getDefault(CarTypes.class).getNames()) {
774            JCheckBox checkBox = new javax.swing.JCheckBox();
775            typeCarCheckBoxes.add(checkBox);
776            checkBox.setText(type);
777            addTypeCheckBoxAction(checkBox);
778            addItemLeft(typeCarPanelCheckBoxes, checkBox, x++, y);
779            if (_train != null && _train.isTypeNameAccepted(type)) {
780                checkBox.setSelected(true);
781            }
782            if (x > numberOfCheckboxes) {
783                y++;
784                x = 0;
785            }
786        }
787
788        JPanel p = new JPanel();
789        p.add(clearButton);
790        p.add(setButton);
791        GridBagConstraints gc = new GridBagConstraints();
792        gc.gridwidth = getNumberOfCheckboxesPerLine() + 1;
793        gc.gridy = ++y;
794        typeCarPanelCheckBoxes.add(p, gc);
795
796    }
797
798    private void updateEngineTypeCheckboxes() {
799        typeEngineCheckBoxes.clear();
800        typeEnginePanelCheckBoxes.removeAll();
801        loadEngineTypes();
802        enableCheckboxes(_train != null);
803        typeEnginePanelCheckBoxes.revalidate();
804        repaint();
805    }
806
807    private void loadEngineTypes() {
808        int numberOfCheckboxes = getNumberOfCheckboxesPerLine(); // number per line
809        int x = 0;
810        int y = 1;
811        for (String type : InstanceManager.getDefault(EngineTypes.class).getNames()) {
812            JCheckBox checkBox = new javax.swing.JCheckBox();
813            typeEngineCheckBoxes.add(checkBox);
814            checkBox.setText(type);
815            addTypeCheckBoxAction(checkBox);
816            addItemLeft(typeEnginePanelCheckBoxes, checkBox, x++, y);
817            if (_train != null && _train.isTypeNameAccepted(type)) {
818                checkBox.setSelected(true);
819            }
820            if (x > numberOfCheckboxes) {
821                y++;
822                x = 0;
823            }
824        }
825    }
826
827    private void updateRoadComboBoxes() {
828        updateCabooseRoadComboBox();
829        updateEngineRoadComboBox();
830    }
831
832    // update caboose road box based on radio selection
833    private void updateCabooseRoadComboBox() {
834        roadCabooseBox.removeAllItems();
835        roadCabooseBox.addItem(NONE);
836        if (noneRadioButton.isSelected()) {
837            roadCabooseBox.setEnabled(false);
838            return;
839        }
840        roadCabooseBox.setEnabled(true);
841        List<String> roads;
842        if (cabooseRadioButton.isSelected()) {
843            roads = InstanceManager.getDefault(CarManager.class).getCabooseRoadNames();
844        } else {
845            roads = InstanceManager.getDefault(CarManager.class).getFredRoadNames();
846        }
847        for (String road : roads) {
848            roadCabooseBox.addItem(road);
849        }
850        if (_train != null) {
851            roadCabooseBox.setSelectedItem(_train.getCabooseRoad());
852        }
853    }
854
855    private void updateEngineRoadComboBox() {
856        String engineModel = (String) modelEngineBox.getSelectedItem();
857        if (engineModel == null) {
858            return;
859        }
860        roadEngineBox.removeAllItems();
861        roadEngineBox.addItem(NONE);
862        List<String> roads = InstanceManager.getDefault(EngineManager.class).getEngineRoadNames(engineModel);
863        for (String roadName : roads) {
864            roadEngineBox.addItem(roadName);
865        }
866        if (_train != null) {
867            roadEngineBox.setSelectedItem(_train.getEngineRoad());
868        }
869    }
870
871    private void addTypeCheckBoxAction(JCheckBox b) {
872        b.addActionListener(new java.awt.event.ActionListener() {
873            @Override
874            public void actionPerformed(java.awt.event.ActionEvent e) {
875                typeCheckBoxActionPerformed(e);
876            }
877        });
878    }
879
880    public void typeCheckBoxActionPerformed(java.awt.event.ActionEvent ae) {
881        JCheckBox b = (JCheckBox) ae.getSource();
882        log.debug("checkbox change {}", b.getText());
883        if (_train == null) {
884            return;
885        }
886        if (b.isSelected()) {
887            _train.addTypeName(b.getText());
888        } else {
889            _train.deleteTypeName(b.getText());
890        }
891    }
892
893    // the train's route shown as locations with checkboxes
894    private void updateLocationCheckboxes() {
895        updateRouteStatus();
896        locationCheckBoxes.clear();
897        locationPanelCheckBoxes.removeAll();
898        int y = 0; // vertical position in panel
899        Route route = null;
900        if (_train != null) {
901            route = _train.getRoute();
902        }
903        if (route != null) {
904            List<RouteLocation> routeList = route.getLocationsBySequenceList();
905            for (RouteLocation rl : routeList) {
906                JCheckBox checkBox = new javax.swing.JCheckBox();
907                locationCheckBoxes.add(checkBox);
908                checkBox.setText(rl.toString());
909                checkBox.setName(rl.getId());
910                addItemLeft(locationPanelCheckBoxes, checkBox, 0, y++);
911                Location loc = InstanceManager.getDefault(LocationManager.class).getLocationByName(rl.getName());
912                // does the location exist?
913                if (loc != null) {
914                    // need to listen for name and direction changes
915                    loc.removePropertyChangeListener(this);
916                    loc.addPropertyChangeListener(this);
917                    boolean services = false;
918                    // does train direction service location?
919                    if ((rl.getTrainDirection() & loc.getTrainDirections()) != 0) {
920                        services = true;
921                    } // train must service last location or single location
922                    else if (_train.isLocalSwitcher() || rl == _train.getTrainTerminatesRouteLocation()) {
923                        services = true;
924                    }
925                    // check can drop and pick up, and moves > 0
926                    if (services && (rl.isDropAllowed() || rl.isPickUpAllowed()) && rl.getMaxCarMoves() > 0) {
927                        checkBox.setSelected(!_train.isLocationSkipped(rl.getId()));
928                    } else {
929                        checkBox.setEnabled(false);
930                    }
931                    addLocationCheckBoxAction(checkBox);
932                } else {
933                    checkBox.setEnabled(false);
934                }
935            }
936        }
937        locationPanelCheckBoxes.revalidate();
938    }
939
940    private void updateRouteStatus() {
941        Route route = null;
942        textRouteStatus.setText(NONE); // clear out previous status
943        if (_train != null) {
944            route = _train.getRoute();
945        }
946        if (route != null) {
947            if (!route.getStatus().equals(Route.OKAY)) {
948                textRouteStatus.setText(route.getStatus());
949                textRouteStatus.setForeground(Color.RED);
950            }
951        }
952    }
953
954    RouteEditFrame ref;
955
956    private void editAddRoute() {
957        log.debug("Edit/add route");
958        if (ref != null) {
959            ref.dispose();
960        }
961        ref = new RouteEditFrame();
962        setChildFrame(ref);
963        Route route = null;
964        Object selected = routeBox.getSelectedItem();
965        if (selected != null) {
966            route = (Route) selected;
967        }
968        // warn user if train is built that they shouldn't edit the train's route
969        if (route != null && route.getStatus().equals(Route.TRAIN_BUILT)) {
970            // list the built trains for this route
971            StringBuffer buf = new StringBuffer(Bundle.getMessage("DoNotModifyRoute"));
972            for (Train train : InstanceManager.getDefault(TrainManager.class).getTrainsByIdList()) {
973                if (train.getRoute() == route && train.isBuilt()) {
974                    buf.append(NEW_LINE +
975                            Bundle.getMessage("TrainIsBuilt",
976                                    train.getName(), route.getName()));
977                }
978            }
979            JmriJOptionPane.showMessageDialog(this, buf.toString(), Bundle.getMessage("BuiltTrain"),
980                    JmriJOptionPane.WARNING_MESSAGE);
981        }
982        ref.initComponents(route, _train);
983    }
984
985    private void updateDepartureTime() {
986        hourBox.setSelectedItem(_train.getDepartureTimeHour());
987        minuteBox.setSelectedItem(_train.getDepartureTimeMinute());
988        // check to see if route has a departure time from the 1st location
989        RouteLocation rl = _train.getTrainDepartsRouteLocation();
990        if (rl != null && !rl.getDepartureTime().equals(NONE)) {
991            hourBox.setEnabled(false);
992            minuteBox.setEnabled(false);
993        } else {
994            hourBox.setEnabled(true);
995            minuteBox.setEnabled(true);
996        }
997    }
998
999    private void updateRoadAndLoadStatus() {
1000        if (_train != null) {
1001            // road options
1002            if (_train.getCarRoadOption().equals(Train.INCLUDE_ROADS)) {
1003                roadOptionButton.setText(Bundle.getMessage(
1004                        "AcceptOnly") + " " + _train.getCarRoadNames().length + " " + Bundle.getMessage("Roads"));
1005            } else if (_train.getCarRoadOption().equals(Train.EXCLUDE_ROADS)) {
1006                roadOptionButton.setText(Bundle.getMessage(
1007                        "Exclude") + " " + _train.getCarRoadNames().length + " " + Bundle.getMessage("Roads"));
1008            } else if (_train.getLocoRoadOption().equals(Train.INCLUDE_ROADS)) {
1009                roadOptionButton.setText(Bundle.getMessage(
1010                        "AcceptOnly") + " " + _train.getLocoRoadNames().length + " " + Bundle.getMessage("Roads"));
1011            } else if (_train.getLocoRoadOption().equals(Train.EXCLUDE_ROADS)) {
1012                roadOptionButton.setText(Bundle.getMessage(
1013                        "Exclude") + " " + _train.getLocoRoadNames().length + " " + Bundle.getMessage("Roads"));
1014            } else {
1015                roadOptionButton.setText(Bundle.getMessage("AcceptAll"));
1016            }
1017            // load options
1018            if (_train.getLoadOption().equals(Train.ALL_LOADS)) {
1019                loadOptionButton.setText(Bundle.getMessage("AcceptAll"));
1020            } else if (_train.getLoadOption().equals(Train.INCLUDE_LOADS)) {
1021                loadOptionButton.setText(Bundle.getMessage(
1022                        "AcceptOnly") + " " + _train.getLoadNames().length + " " + Bundle.getMessage("Loads"));
1023            } else {
1024                loadOptionButton.setText(Bundle.getMessage(
1025                        "Exclude") + " " + _train.getLoadNames().length + " " + Bundle.getMessage("Loads"));
1026            }
1027            if (!_train.getCarRoadOption().equals(Train.ALL_ROADS) ||
1028                    !_train.getLocoRoadOption().equals(Train.ALL_ROADS) ||
1029                    !_train.getLoadOption().equals(Train.ALL_LOADS)) {
1030                roadAndLoadStatusPanel.setVisible(true);
1031            }
1032        }
1033    }
1034
1035    List<Frame> children = new ArrayList<>();
1036
1037    public void setChildFrame(Frame frame) {
1038        if (children.contains(frame)) {
1039            return;
1040        }
1041        children.add(frame);
1042    }
1043
1044    @Override
1045    public void dispose() {
1046        InstanceManager.getDefault(LocationManager.class).removePropertyChangeListener(this);
1047        InstanceManager.getDefault(EngineTypes.class).removePropertyChangeListener(this);
1048        InstanceManager.getDefault(EngineModels.class).removePropertyChangeListener(this);
1049        InstanceManager.getDefault(CarTypes.class).removePropertyChangeListener(this);
1050        InstanceManager.getDefault(CarRoads.class).removePropertyChangeListener(this);
1051        routeManager.removePropertyChangeListener(this);
1052        for (Frame frame : children) {
1053            frame.dispose();
1054        }
1055        if (_train != null) {
1056            _train.removePropertyChangeListener(this);
1057            Route route = _train.getRoute();
1058            if (route != null) {
1059                for (RouteLocation rl : route.getLocationsBySequenceList()) {
1060                    Location loc = rl.getLocation();
1061                    if (loc != null) {
1062                        loc.removePropertyChangeListener(this);
1063                    }
1064                }
1065            }
1066        }
1067        super.dispose();
1068    }
1069
1070    @Override
1071    public void propertyChange(java.beans.PropertyChangeEvent e) {
1072        if (Control.SHOW_PROPERTY) {
1073            log.debug("Property change ({}) old: ({}) new: ({})", e.getPropertyName(), e.getOldValue(),
1074                    e.getNewValue()); // NOI18N
1075        }
1076        if (e.getPropertyName().equals(CarTypes.CARTYPES_CHANGED_PROPERTY) ||
1077                e.getPropertyName().equals(Train.TYPES_CHANGED_PROPERTY)) {
1078            updateCarTypeCheckboxes();
1079        }
1080        if (e.getPropertyName().equals(EngineTypes.ENGINETYPES_CHANGED_PROPERTY)) {
1081            updateEngineTypeCheckboxes();
1082        }
1083        if (e.getPropertyName().equals(RouteManager.LISTLENGTH_CHANGED_PROPERTY)) {
1084            updateRouteComboBox();
1085        }
1086        if (e.getPropertyName().equals(Route.LISTCHANGE_CHANGED_PROPERTY) ||
1087                e.getPropertyName().equals(LocationManager.LISTLENGTH_CHANGED_PROPERTY) ||
1088                e.getPropertyName().equals(Location.NAME_CHANGED_PROPERTY) ||
1089                e.getPropertyName().equals(Location.TRAIN_DIRECTION_CHANGED_PROPERTY)) {
1090            updateLocationCheckboxes();
1091            pack();
1092            repaint();
1093        }
1094        if (e.getPropertyName().equals(CarRoads.CARROADS_CHANGED_PROPERTY)) {
1095            updateRoadComboBoxes();
1096        }
1097        if (e.getPropertyName().equals(EngineModels.ENGINEMODELS_CHANGED_PROPERTY)) {
1098            InstanceManager.getDefault(EngineModels.class).updateComboBox(modelEngineBox);
1099            modelEngineBox.insertItemAt(NONE, 0);
1100            modelEngineBox.setSelectedIndex(0);
1101            if (_train != null) {
1102                modelEngineBox.setSelectedItem(_train.getEngineModel());
1103            }
1104        }
1105        if (e.getPropertyName().equals(Train.DEPARTURETIME_CHANGED_PROPERTY)) {
1106            updateDepartureTime();
1107        }
1108        if (e.getPropertyName().equals(Train.TRAIN_ROUTE_CHANGED_PROPERTY) && _train != null) {
1109            routeBox.setSelectedItem(_train.getRoute());
1110        }
1111        if (e.getPropertyName().equals(Route.ROUTE_STATUS_CHANGED_PROPERTY)) {
1112            enableButtons(_train != null);
1113            updateRouteStatus();
1114        }
1115        if (e.getPropertyName().equals(Train.ROADS_CHANGED_PROPERTY) ||
1116                e.getPropertyName().equals(Train.LOADS_CHANGED_PROPERTY)) {
1117            updateRoadAndLoadStatus();
1118        }
1119    }
1120
1121    private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(TrainEditFrame.class);
1122}