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);
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("0000"); // needed for font size 9
154        minuteBox.setPrototypeDisplayValue("0000");
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                updateDepartureTime();
703                pack();
704                repaint();
705            }
706        }
707    }
708
709    private void enableCheckboxes(boolean enable) {
710        for (int i = 0; i < typeCarCheckBoxes.size(); i++) {
711            typeCarCheckBoxes.get(i).setEnabled(enable);
712        }
713        for (int i = 0; i < typeEngineCheckBoxes.size(); i++) {
714            typeEngineCheckBoxes.get(i).setEnabled(enable);
715        }
716    }
717
718    private void addLocationCheckBoxAction(JCheckBox b) {
719        b.addActionListener(new java.awt.event.ActionListener() {
720            @Override
721            public void actionPerformed(java.awt.event.ActionEvent e) {
722                locationCheckBoxActionPerformed(e);
723            }
724        });
725    }
726
727    public void locationCheckBoxActionPerformed(java.awt.event.ActionEvent ae) {
728        JCheckBox b = (JCheckBox) ae.getSource();
729        log.debug("checkbox change {}", b.getText());
730        if (_train == null) {
731            return;
732        }
733        String id = b.getName();
734        if (b.isSelected()) {
735            _train.deleteTrainSkipsLocation(id);
736        } else {
737            // check to see if skipped location is staging
738            if (_train.getRoute().getLocationById(id).getLocation().isStaging()) {
739                int result = JmriJOptionPane.showConfirmDialog(this,
740                        Bundle.getMessage("TrainRouteStaging",
741                                _train.getName(), _train.getRoute().getLocationById(id).getName()),
742                        Bundle.getMessage("TrainRouteNotStaging"), JmriJOptionPane.OK_CANCEL_OPTION);
743                if (result != JmriJOptionPane.OK_OPTION ) {
744                    b.setSelected(true);
745                    return; // don't skip staging
746                }
747            }
748            _train.addTrainSkipsLocation(id);
749        }
750    }
751
752    private void updateRouteComboBox() {
753        routeBox.setEnabled(false);
754        routeManager.updateComboBox(routeBox);
755        if (_train != null) {
756            routeBox.setSelectedItem(_train.getRoute());
757        }
758        routeBox.setEnabled(true);
759    }
760
761    private void updateCarTypeCheckboxes() {
762        typeCarCheckBoxes.clear();
763        typeCarPanelCheckBoxes.removeAll();
764        loadCarTypes();
765        enableCheckboxes(_train != null);
766        typeCarPanelCheckBoxes.revalidate();
767        repaint();
768    }
769
770    private void loadCarTypes() {
771        int numberOfCheckboxes = getNumberOfCheckboxesPerLine(); // number per line
772        int x = 0;
773        int y = 1; // vertical position in panel
774        for (String type : InstanceManager.getDefault(CarTypes.class).getNames()) {
775            JCheckBox checkBox = new javax.swing.JCheckBox();
776            typeCarCheckBoxes.add(checkBox);
777            checkBox.setText(type);
778            addTypeCheckBoxAction(checkBox);
779            addItemLeft(typeCarPanelCheckBoxes, checkBox, x++, y);
780            if (_train != null && _train.isTypeNameAccepted(type)) {
781                checkBox.setSelected(true);
782            }
783            if (x > numberOfCheckboxes) {
784                y++;
785                x = 0;
786            }
787        }
788
789        JPanel p = new JPanel();
790        p.add(clearButton);
791        p.add(setButton);
792        GridBagConstraints gc = new GridBagConstraints();
793        gc.gridwidth = getNumberOfCheckboxesPerLine() + 1;
794        gc.gridy = ++y;
795        typeCarPanelCheckBoxes.add(p, gc);
796
797    }
798
799    private void updateEngineTypeCheckboxes() {
800        typeEngineCheckBoxes.clear();
801        typeEnginePanelCheckBoxes.removeAll();
802        loadEngineTypes();
803        enableCheckboxes(_train != null);
804        typeEnginePanelCheckBoxes.revalidate();
805        repaint();
806    }
807
808    private void loadEngineTypes() {
809        int numberOfCheckboxes = getNumberOfCheckboxesPerLine(); // number per line
810        int x = 0;
811        int y = 1;
812        for (String type : InstanceManager.getDefault(EngineTypes.class).getNames()) {
813            JCheckBox checkBox = new javax.swing.JCheckBox();
814            typeEngineCheckBoxes.add(checkBox);
815            checkBox.setText(type);
816            addTypeCheckBoxAction(checkBox);
817            addItemLeft(typeEnginePanelCheckBoxes, checkBox, x++, y);
818            if (_train != null && _train.isTypeNameAccepted(type)) {
819                checkBox.setSelected(true);
820            }
821            if (x > numberOfCheckboxes) {
822                y++;
823                x = 0;
824            }
825        }
826    }
827
828    private void updateRoadComboBoxes() {
829        updateCabooseRoadComboBox();
830        updateEngineRoadComboBox();
831    }
832
833    // update caboose road box based on radio selection
834    private void updateCabooseRoadComboBox() {
835        roadCabooseBox.removeAllItems();
836        roadCabooseBox.addItem(NONE);
837        if (noneRadioButton.isSelected()) {
838            roadCabooseBox.setEnabled(false);
839            return;
840        }
841        roadCabooseBox.setEnabled(true);
842        List<String> roads;
843        if (cabooseRadioButton.isSelected()) {
844            roads = InstanceManager.getDefault(CarManager.class).getCabooseRoadNames();
845        } else {
846            roads = InstanceManager.getDefault(CarManager.class).getFredRoadNames();
847        }
848        for (String road : roads) {
849            roadCabooseBox.addItem(road);
850        }
851        if (_train != null) {
852            roadCabooseBox.setSelectedItem(_train.getCabooseRoad());
853        }
854    }
855
856    private void updateEngineRoadComboBox() {
857        String engineModel = (String) modelEngineBox.getSelectedItem();
858        if (engineModel == null) {
859            return;
860        }
861        roadEngineBox.removeAllItems();
862        roadEngineBox.addItem(NONE);
863        List<String> roads = InstanceManager.getDefault(EngineManager.class).getEngineRoadNames(engineModel);
864        for (String roadName : roads) {
865            roadEngineBox.addItem(roadName);
866        }
867        if (_train != null) {
868            roadEngineBox.setSelectedItem(_train.getEngineRoad());
869        }
870    }
871
872    private void addTypeCheckBoxAction(JCheckBox b) {
873        b.addActionListener(new java.awt.event.ActionListener() {
874            @Override
875            public void actionPerformed(java.awt.event.ActionEvent e) {
876                typeCheckBoxActionPerformed(e);
877            }
878        });
879    }
880
881    public void typeCheckBoxActionPerformed(java.awt.event.ActionEvent ae) {
882        JCheckBox b = (JCheckBox) ae.getSource();
883        log.debug("checkbox change {}", b.getText());
884        if (_train == null) {
885            return;
886        }
887        if (b.isSelected()) {
888            _train.addTypeName(b.getText());
889        } else {
890            _train.deleteTypeName(b.getText());
891        }
892    }
893
894    // the train's route shown as locations with checkboxes
895    private void updateLocationCheckboxes() {
896        updateRouteStatus();
897        locationCheckBoxes.clear();
898        locationPanelCheckBoxes.removeAll();
899        int y = 0; // vertical position in panel
900        Route route = null;
901        if (_train != null) {
902            route = _train.getRoute();
903        }
904        if (route != null) {
905            List<RouteLocation> routeList = route.getLocationsBySequenceList();
906            for (RouteLocation rl : routeList) {
907                JCheckBox checkBox = new javax.swing.JCheckBox();
908                locationCheckBoxes.add(checkBox);
909                checkBox.setText(rl.toString());
910                checkBox.setName(rl.getId());
911                addItemLeft(locationPanelCheckBoxes, checkBox, 0, y++);
912                Location loc = InstanceManager.getDefault(LocationManager.class).getLocationByName(rl.getName());
913                // does the location exist?
914                if (loc != null) {
915                    // need to listen for name and direction changes
916                    loc.removePropertyChangeListener(this);
917                    loc.addPropertyChangeListener(this);
918                    boolean services = false;
919                    // does train direction service location?
920                    if ((rl.getTrainDirection() & loc.getTrainDirections()) != 0) {
921                        services = true;
922                    } // train must service last location or single location
923                    else if (_train.isLocalSwitcher() || rl == _train.getTrainTerminatesRouteLocation()) {
924                        services = true;
925                    }
926                    // check can drop and pick up, and moves > 0
927                    if (services && (rl.isDropAllowed() || rl.isPickUpAllowed()) && rl.getMaxCarMoves() > 0) {
928                        checkBox.setSelected(!_train.isLocationSkipped(rl.getId()));
929                    } else {
930                        checkBox.setEnabled(false);
931                    }
932                    addLocationCheckBoxAction(checkBox);
933                } else {
934                    checkBox.setEnabled(false);
935                }
936            }
937        }
938        locationPanelCheckBoxes.revalidate();
939    }
940
941    private void updateRouteStatus() {
942        Route route = null;
943        textRouteStatus.setText(NONE); // clear out previous status
944        if (_train != null) {
945            route = _train.getRoute();
946        }
947        if (route != null) {
948            if (!route.getStatus().equals(Route.OKAY)) {
949                textRouteStatus.setText(route.getStatus());
950                textRouteStatus.setForeground(Color.RED);
951            }
952        }
953    }
954
955    RouteEditFrame ref;
956
957    private void editAddRoute() {
958        log.debug("Edit/add route");
959        if (ref != null) {
960            ref.dispose();
961        }
962        ref = new RouteEditFrame();
963        setChildFrame(ref);
964        Route route = null;
965        Object selected = routeBox.getSelectedItem();
966        if (selected != null) {
967            route = (Route) selected;
968        }
969        // warn user if train is built that they shouldn't edit the train's route
970        if (route != null && route.getStatus().equals(Route.TRAIN_BUILT)) {
971            // list the built trains for this route
972            StringBuffer buf = new StringBuffer(Bundle.getMessage("DoNotModifyRoute"));
973            for (Train train : InstanceManager.getDefault(TrainManager.class).getTrainsByIdList()) {
974                if (train.getRoute() == route && train.isBuilt()) {
975                    buf.append(NEW_LINE +
976                            Bundle.getMessage("TrainIsBuilt",
977                                    train.getName(), route.getName()));
978                }
979            }
980            JmriJOptionPane.showMessageDialog(this, buf.toString(), Bundle.getMessage("BuiltTrain"),
981                    JmriJOptionPane.WARNING_MESSAGE);
982        }
983        ref.initComponents(route, _train);
984    }
985
986    private void updateDepartureTime() {
987        hourBox.setSelectedItem(_train.getDepartureTimeHour());
988        minuteBox.setSelectedItem(_train.getDepartureTimeMinute());
989        // check to see if route has a departure time from the 1st location
990        RouteLocation rl = _train.getTrainDepartsRouteLocation();
991        if (rl != null && !rl.getDepartureTime().equals(NONE)) {
992            hourBox.setEnabled(false);
993            minuteBox.setEnabled(false);
994        } else {
995            hourBox.setEnabled(true);
996            minuteBox.setEnabled(true);
997        }
998    }
999
1000    private void updateRoadAndLoadStatus() {
1001        if (_train != null) {
1002            // road options
1003            if (_train.getCarRoadOption().equals(Train.INCLUDE_ROADS)) {
1004                roadOptionButton.setText(Bundle.getMessage(
1005                        "AcceptOnly") + " " + _train.getCarRoadNames().length + " " + Bundle.getMessage("Roads"));
1006            } else if (_train.getCarRoadOption().equals(Train.EXCLUDE_ROADS)) {
1007                roadOptionButton.setText(Bundle.getMessage(
1008                        "Exclude") + " " + _train.getCarRoadNames().length + " " + Bundle.getMessage("Roads"));
1009            } else if (_train.getLocoRoadOption().equals(Train.INCLUDE_ROADS)) {
1010                roadOptionButton.setText(Bundle.getMessage(
1011                        "AcceptOnly") + " " + _train.getLocoRoadNames().length + " " + Bundle.getMessage("Roads"));
1012            } else if (_train.getLocoRoadOption().equals(Train.EXCLUDE_ROADS)) {
1013                roadOptionButton.setText(Bundle.getMessage(
1014                        "Exclude") + " " + _train.getLocoRoadNames().length + " " + Bundle.getMessage("Roads"));
1015            } else {
1016                roadOptionButton.setText(Bundle.getMessage("AcceptAll"));
1017            }
1018            // load options
1019            if (_train.getLoadOption().equals(Train.ALL_LOADS)) {
1020                loadOptionButton.setText(Bundle.getMessage("AcceptAll"));
1021            } else if (_train.getLoadOption().equals(Train.INCLUDE_LOADS)) {
1022                loadOptionButton.setText(Bundle.getMessage(
1023                        "AcceptOnly") + " " + _train.getLoadNames().length + " " + Bundle.getMessage("Loads"));
1024            } else {
1025                loadOptionButton.setText(Bundle.getMessage(
1026                        "Exclude") + " " + _train.getLoadNames().length + " " + Bundle.getMessage("Loads"));
1027            }
1028            if (!_train.getCarRoadOption().equals(Train.ALL_ROADS) ||
1029                    !_train.getLocoRoadOption().equals(Train.ALL_ROADS) ||
1030                    !_train.getLoadOption().equals(Train.ALL_LOADS)) {
1031                roadAndLoadStatusPanel.setVisible(true);
1032            }
1033        }
1034    }
1035
1036    List<Frame> children = new ArrayList<>();
1037
1038    public void setChildFrame(Frame frame) {
1039        if (children.contains(frame)) {
1040            return;
1041        }
1042        children.add(frame);
1043    }
1044
1045    @Override
1046    public void dispose() {
1047        InstanceManager.getDefault(LocationManager.class).removePropertyChangeListener(this);
1048        InstanceManager.getDefault(EngineTypes.class).removePropertyChangeListener(this);
1049        InstanceManager.getDefault(EngineModels.class).removePropertyChangeListener(this);
1050        InstanceManager.getDefault(CarTypes.class).removePropertyChangeListener(this);
1051        InstanceManager.getDefault(CarRoads.class).removePropertyChangeListener(this);
1052        routeManager.removePropertyChangeListener(this);
1053        for (Frame frame : children) {
1054            frame.dispose();
1055        }
1056        if (_train != null) {
1057            _train.removePropertyChangeListener(this);
1058            Route route = _train.getRoute();
1059            if (route != null) {
1060                for (RouteLocation rl : route.getLocationsBySequenceList()) {
1061                    Location loc = rl.getLocation();
1062                    if (loc != null) {
1063                        loc.removePropertyChangeListener(this);
1064                    }
1065                }
1066            }
1067        }
1068        super.dispose();
1069    }
1070
1071    @Override
1072    public void propertyChange(java.beans.PropertyChangeEvent e) {
1073        if (Control.SHOW_PROPERTY) {
1074            log.debug("Property change ({}) old: ({}) new: ({})", e.getPropertyName(), e.getOldValue(),
1075                    e.getNewValue()); // NOI18N
1076        }
1077        if (e.getPropertyName().equals(CarTypes.CARTYPES_CHANGED_PROPERTY) ||
1078                e.getPropertyName().equals(Train.TYPES_CHANGED_PROPERTY)) {
1079            updateCarTypeCheckboxes();
1080        }
1081        if (e.getPropertyName().equals(EngineTypes.ENGINETYPES_CHANGED_PROPERTY)) {
1082            updateEngineTypeCheckboxes();
1083        }
1084        if (e.getPropertyName().equals(RouteManager.LISTLENGTH_CHANGED_PROPERTY)) {
1085            updateRouteComboBox();
1086        }
1087        if (e.getPropertyName().equals(Route.LISTCHANGE_CHANGED_PROPERTY) ||
1088                e.getPropertyName().equals(LocationManager.LISTLENGTH_CHANGED_PROPERTY) ||
1089                e.getPropertyName().equals(Location.NAME_CHANGED_PROPERTY) ||
1090                e.getPropertyName().equals(Location.TRAIN_DIRECTION_CHANGED_PROPERTY)) {
1091            updateLocationCheckboxes();
1092            pack();
1093            repaint();
1094        }
1095        if (e.getPropertyName().equals(CarRoads.CARROADS_CHANGED_PROPERTY)) {
1096            updateRoadComboBoxes();
1097        }
1098        if (e.getPropertyName().equals(EngineModels.ENGINEMODELS_CHANGED_PROPERTY)) {
1099            InstanceManager.getDefault(EngineModels.class).updateComboBox(modelEngineBox);
1100            modelEngineBox.insertItemAt(NONE, 0);
1101            modelEngineBox.setSelectedIndex(0);
1102            if (_train != null) {
1103                modelEngineBox.setSelectedItem(_train.getEngineModel());
1104            }
1105        }
1106        if (e.getPropertyName().equals(Train.DEPARTURETIME_CHANGED_PROPERTY)) {
1107            updateDepartureTime();
1108        }
1109        if (e.getPropertyName().equals(Train.TRAIN_ROUTE_CHANGED_PROPERTY) && _train != null) {
1110            routeBox.setSelectedItem(_train.getRoute());
1111        }
1112        if (e.getPropertyName().equals(Route.ROUTE_STATUS_CHANGED_PROPERTY)) {
1113            enableButtons(_train != null);
1114            updateRouteStatus();
1115        }
1116        if (e.getPropertyName().equals(Train.ROADS_CHANGED_PROPERTY) ||
1117                e.getPropertyName().equals(Train.LOADS_CHANGED_PROPERTY)) {
1118            updateRoadAndLoadStatus();
1119        }
1120    }
1121
1122    private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(TrainEditFrame.class);
1123}