001package jmri.jmrit.beantable;
002
003import java.awt.*;
004import java.awt.datatransfer.Clipboard;
005import java.awt.datatransfer.StringSelection;
006import java.awt.event.ActionEvent;
007import java.awt.event.ActionListener;
008import java.awt.event.KeyEvent;
009import java.beans.PropertyChangeEvent;
010import java.beans.PropertyChangeListener;
011import java.beans.PropertyVetoException;
012import java.io.IOException;
013import java.text.DateFormat;
014import java.text.MessageFormat;
015import java.util.ArrayList;
016import java.util.Date;
017import java.util.Enumeration;
018import java.util.EventObject;
019import java.util.List;
020import java.util.Objects;
021import java.util.function.Predicate;
022import java.util.stream.Stream;
023
024import javax.annotation.CheckForNull;
025import javax.annotation.Nonnull;
026import javax.annotation.OverridingMethodsMustInvokeSuper;
027import javax.swing.*;
028import javax.swing.table.*;
029
030import jmri.*;
031import jmri.NamedBean.DisplayOptions;
032import jmri.jmrit.display.layoutEditor.LayoutBlock;
033import jmri.jmrit.display.layoutEditor.LayoutBlockManager;
034import jmri.swing.JTablePersistenceManager;
035import jmri.util.davidflanagan.HardcopyWriter;
036import jmri.util.swing.*;
037import jmri.util.table.ButtonEditor;
038import jmri.util.table.ButtonRenderer;
039
040/**
041 * Abstract Table data model for display of NamedBean manager contents.
042 *
043 * @author Bob Jacobsen Copyright (C) 2003
044 * @author Dennis Miller Copyright (C) 2006
045 * @param <T> the type of NamedBean supported by this model
046 */
047abstract public class BeanTableDataModel<T extends NamedBean> extends AbstractTableModel implements PropertyChangeListener {
048
049    static public final int SYSNAMECOL = 0;
050    static public final int USERNAMECOL = 1;
051    static public final int VALUECOL = 2;
052    static public final int COMMENTCOL = 3;
053    static public final int DELETECOL = 4;
054    static public final int NUMCOLUMN = 5;
055    protected List<String> sysNameList = null;
056    private NamedBeanHandleManager nbMan;
057    private Predicate<? super T> filter;
058
059    /**
060     * Create a new Bean Table Data Model.
061     * The default Manager for the bean type may well be a Proxy Manager.
062     */
063    public BeanTableDataModel() {
064        super();
065        initModel();
066    }
067
068    /**
069     * Internal routine to avoid over ride method call in constructor.
070     */
071    private void initModel(){
072        nbMan = InstanceManager.getDefault(NamedBeanHandleManager.class);
073        // log.error("get mgr is: {}",this.getManager());
074        getManager().addPropertyChangeListener(this);
075        updateNameList();
076    }
077
078    /**
079     * Get the total number of custom bean property columns.
080     * Proxy managers will return the total number of custom columns for all
081     * hardware types of that Bean type.
082     * Single hardware types will return the total just for that hardware.
083     * @return total number of custom columns within the table.
084     */
085    protected int getPropertyColumnCount() {
086        return getManager().getKnownBeanProperties().size();
087    }
088
089    /**
090     * Get the Named Bean Property Descriptor for a given column number.
091     * @param column table column number.
092     * @return the descriptor if available, else null.
093     */
094    @CheckForNull
095    protected NamedBeanPropertyDescriptor<?> getPropertyColumnDescriptor(int column) {
096        List<NamedBeanPropertyDescriptor<?>> propertyColumns = getManager().getKnownBeanProperties();
097        int totalCount = getColumnCount();
098        int propertyCount = propertyColumns.size();
099        int tgt = column - (totalCount - propertyCount);
100        if (tgt < 0 || tgt >= propertyCount ) {
101            return null;
102        }
103        return propertyColumns.get(tgt);
104    }
105
106    protected synchronized void updateNameList() {
107        // first, remove listeners from the individual objects
108        if (sysNameList != null) {
109            for (String s : sysNameList) {
110                // if object has been deleted, it's not here; ignore it
111                T b = getBySystemName(s);
112                if (b != null) {
113                    b.removePropertyChangeListener(this);
114                }
115            }
116        }
117        Stream<T> stream = getManager().getNamedBeanSet().stream();
118        if (filter != null) stream = stream.filter(filter);
119        sysNameList = stream.map(NamedBean::getSystemName).collect( java.util.stream.Collectors.toList() );
120        // and add them back in
121        for (String s : sysNameList) {
122            // if object has been deleted, it's not here; ignore it
123            T b = getBySystemName(s);
124            if (b != null) {
125                b.addPropertyChangeListener(this);
126            }
127        }
128    }
129
130    /**
131     * {@inheritDoc}
132     */
133    @Override
134    public void propertyChange(PropertyChangeEvent e) {
135        if (e.getPropertyName().equals("length")) {
136            // a new NamedBean is available in the manager
137            updateNameList();
138            log.debug("Table changed length to {}", sysNameList.size());
139            fireTableDataChanged();
140        } else if (matchPropertyName(e)) {
141            // a value changed.  Find it, to avoid complete redraw
142            if (e.getSource() instanceof NamedBean) {
143                String name = ((NamedBean) e.getSource()).getSystemName();
144                int row = sysNameList.indexOf(name);
145                log.debug("Update cell {},{} for {}", row, VALUECOL, name);
146                // since we can add columns, the entire row is marked as updated
147                try {
148                    fireTableRowsUpdated(row, row);
149                } catch (Exception ex) {
150                    log.error("Exception updating table", ex);
151                }
152            }
153        }
154    }
155
156    /**
157     * Is this property event announcing a change this table should display?
158     * <p>
159     * Note that events will come both from the NamedBeans and also from the
160     * manager
161     *
162     * @param e the event to match
163     * @return true if the property name is of interest, false otherwise
164     */
165    protected boolean matchPropertyName(PropertyChangeEvent e) {
166        return (e.getPropertyName().contains("State")
167                || e.getPropertyName().contains("Appearance")
168                || e.getPropertyName().contains("Comment"))
169                || e.getPropertyName().contains("UserName");
170    }
171
172    /**
173     * {@inheritDoc}
174     */
175    @Override
176    public int getRowCount() {
177        return sysNameList.size();
178    }
179
180    /**
181     * Get Column Count INCLUDING Bean Property Columns.
182     * {@inheritDoc}
183     */
184    @Override
185    public int getColumnCount() {
186        return NUMCOLUMN + getPropertyColumnCount();
187    }
188
189    /**
190     * {@inheritDoc}
191     */
192    @Override
193    public String getColumnName(int col) {
194        switch (col) {
195            case SYSNAMECOL:
196                return Bundle.getMessage("ColumnSystemName"); // "System Name";
197            case USERNAMECOL:
198                return Bundle.getMessage("ColumnUserName");   // "User Name";
199            case VALUECOL:
200                return Bundle.getMessage("ColumnState");      // "State";
201            case COMMENTCOL:
202                return Bundle.getMessage("ColumnComment");    // "Comment";
203            case DELETECOL:
204                return "";
205            default:
206                NamedBeanPropertyDescriptor<?> desc = getPropertyColumnDescriptor(col);
207                if (desc == null) {
208                    return "btm unknown"; // NOI18N
209                }
210                return desc.getColumnHeaderText();
211        }
212    }
213
214    /**
215     * {@inheritDoc}
216     */
217    @Override
218    public Class<?> getColumnClass(int col) {
219        switch (col) {
220            case SYSNAMECOL:
221                return NamedBean.class; // can't get class of T
222            case USERNAMECOL:
223            case COMMENTCOL:
224                return String.class;
225            case VALUECOL:
226            case DELETECOL:
227                return JButton.class;
228            default:
229                NamedBeanPropertyDescriptor<?> desc = getPropertyColumnDescriptor(col);
230                if (desc == null) {
231                    return null;
232                }
233                if ( desc instanceof SelectionPropertyDescriptor ){
234                    return JComboBox.class;
235                }
236                return desc.getValueClass();
237        }
238    }
239
240    /**
241     * {@inheritDoc}
242     */
243    @Override
244    public boolean isCellEditable(int row, int col) {
245        String uname;
246        switch (col) {
247            case VALUECOL:
248            case COMMENTCOL:
249            case DELETECOL:
250                return true;
251            case USERNAMECOL:
252                T b = getBySystemName(sysNameList.get(row));
253                uname = b.getUserName();
254                return ((uname == null) || uname.isEmpty());
255            default:
256                NamedBeanPropertyDescriptor<?> desc = getPropertyColumnDescriptor(col);
257                if (desc == null) {
258                    return false;
259                }
260                return desc.isEditable(getBySystemName(sysNameList.get(row)));
261        }
262    }
263
264    /**
265     *
266     * SYSNAMECOL returns the actual Bean, NOT the System Name.
267     *
268     * {@inheritDoc}
269     */
270    @Override
271    public Object getValueAt(int row, int col) {
272        T b;
273        switch (col) {
274            case SYSNAMECOL:  // slot number
275                return getBySystemName(sysNameList.get(row));
276            case USERNAMECOL:  // return user name
277                // sometimes, the TableSorter invokes this on rows that no longer exist, so we check
278                b = getBySystemName(sysNameList.get(row));
279                return (b != null) ? b.getUserName() : null;
280            case VALUECOL:  //
281                return getValue(sysNameList.get(row));
282            case COMMENTCOL:
283                b = getBySystemName(sysNameList.get(row));
284                return (b != null) ? b.getComment() : null;
285            case DELETECOL:  //
286                return Bundle.getMessage("ButtonDelete");
287            default:
288                NamedBeanPropertyDescriptor<?> desc = getPropertyColumnDescriptor(col);
289                if (desc == null) {
290                    log.error("internal state inconsistent with table requst for getValueAt {} {}", row, col);
291                    return null;
292                }
293                if ( !isCellEditable(row, col) ) {
294                    return null; // do not display if not applicable to hardware type
295                }
296                b = getBySystemName(sysNameList.get(row));
297                Object value = b.getProperty(desc.propertyKey);
298                if (desc instanceof SelectionPropertyDescriptor){
299                    JComboBox<String> c = new JComboBox<>(((SelectionPropertyDescriptor) desc).getOptions());
300                    c.setSelectedItem(( value!=null ? value.toString() : desc.defaultValue.toString() ));
301                    ComboBoxToolTipRenderer renderer = new ComboBoxToolTipRenderer();
302                    c.setRenderer(renderer);
303                    renderer.setTooltips(((SelectionPropertyDescriptor) desc).getOptionToolTips());
304                    return c;
305                }
306                if (value == null) {
307                    return desc.defaultValue;
308                }
309                return value;
310        }
311    }
312
313    public int getPreferredWidth(int col) {
314        switch (col) {
315            case SYSNAMECOL:
316                return new JTextField(5).getPreferredSize().width;
317            case COMMENTCOL:
318            case USERNAMECOL:
319                return new JTextField(15).getPreferredSize().width; // TODO I18N using Bundle.getMessage()
320            case VALUECOL: // not actually used due to the configureTable, setColumnToHoldButton, configureButton
321            case DELETECOL: // not actually used due to the configureTable, setColumnToHoldButton, configureButton
322                return new JTextField(Bundle.getMessage("ButtonDelete")).getPreferredSize().width;
323            default:
324                NamedBeanPropertyDescriptor<?> desc = getPropertyColumnDescriptor(col);
325                if (desc == null || desc.getColumnHeaderText() == null) {
326                    log.error("Unexpected column in getPreferredWidth: {} table {}", col,this);
327                    return new JTextField(8).getPreferredSize().width;
328                }
329                return new JTextField(desc.getColumnHeaderText()).getPreferredSize().width;
330        }
331    }
332
333    /**
334     * Get the current Bean state value in human readable form.
335     * @param systemName System name of Bean.
336     * @return state value in localised human readable form.
337     */
338    abstract public String getValue(String systemName);
339
340    /**
341     * Get the Table Model Bean Manager.
342     * In many cases, especially around Model startup,
343     * this will be the Proxy Manager, which is then changed to the
344     * hardware specific manager.
345     * @return current Manager in use by the Model.
346     */
347    abstract protected Manager<T> getManager();
348
349    /**
350     * Set the Model Bean Manager.
351     * Note that for many Models this may not work as the manager is
352     * currently obtained directly from the Action class.
353     *
354     * @param man Bean Manager that the Model should use.
355     */
356    protected void setManager(@Nonnull Manager<T> man) {
357    }
358
359    abstract protected T getBySystemName(@Nonnull String name);
360
361    abstract protected T getByUserName(@Nonnull String name);
362
363    /**
364     * Process a click on The value cell.
365     * @param t the Bean that has been clicked.
366     */
367    abstract protected void clickOn(T t);
368
369    public int getDisplayDeleteMsg() {
370        return InstanceManager.getDefault(UserPreferencesManager.class).getMultipleChoiceOption(getMasterClassName(), "deleteInUse");
371    }
372
373    public void setDisplayDeleteMsg(int boo) {
374        InstanceManager.getDefault(UserPreferencesManager.class).setMultipleChoiceOption(getMasterClassName(), "deleteInUse", boo);
375    }
376
377    abstract protected String getMasterClassName();
378
379    /**
380     * {@inheritDoc}
381     */
382    @Override
383    public void setValueAt(Object value, int row, int col) {
384        switch (col) {
385            case USERNAMECOL:
386                // Directly changing the username should only be possible if the username was previously null or ""
387                // check to see if user name already exists
388                if (value.equals("")) {
389                    value = null;
390                } else {
391                    T nB = getByUserName((String) value);
392                    if (nB != null) {
393                        log.error("User name is not unique {}", value);
394                        String msg = Bundle.getMessage("WarningUserName", "" + value);
395                        JmriJOptionPane.showMessageDialog(null, msg,
396                                Bundle.getMessage("WarningTitle"),
397                                JmriJOptionPane.ERROR_MESSAGE);
398                        return;
399                    }
400                }
401                T nBean = getBySystemName(sysNameList.get(row));
402                nBean.setUserName((String) value);
403                if (nbMan.inUse(sysNameList.get(row), nBean)) {
404                    String msg = Bundle.getMessage("UpdateToUserName", getBeanType(), value, sysNameList.get(row));
405                    int optionPane = JmriJOptionPane.showConfirmDialog(null,
406                            msg, Bundle.getMessage("UpdateToUserNameTitle"),
407                            JmriJOptionPane.YES_NO_OPTION);
408                    if (optionPane == JmriJOptionPane.YES_OPTION) {
409                        //This will update the bean reference from the systemName to the userName
410                        try {
411                            nbMan.updateBeanFromSystemToUser(nBean);
412                        } catch (JmriException ex) {
413                            //We should never get an exception here as we already check that the username is not valid
414                            log.error("Impossible exception setting user name", ex);
415                        }
416                    }
417                }
418                break;
419            case COMMENTCOL:
420                getBySystemName(sysNameList.get(row)).setComment(
421                        (String) value);
422                break;
423            case VALUECOL:
424                // button fired, swap state
425                T t = getBySystemName(sysNameList.get(row));
426                clickOn(t);
427                break;
428            case DELETECOL:
429                // button fired, delete Bean
430                deleteBean(row, col);
431                return; // manager will update rows if a delete occurs
432            default:
433                NamedBeanPropertyDescriptor<?> desc = getPropertyColumnDescriptor(col);
434                if (desc == null) {
435                    log.error("btdm setvalueat {} {}",row,col);
436                    break;
437                }
438                if (value instanceof JComboBox) {
439                    value = ((JComboBox<?>) value).getSelectedItem();
440                }
441                NamedBean b = getBySystemName(sysNameList.get(row));
442                b.setProperty(desc.propertyKey, value);
443        }
444        fireTableRowsUpdated(row, row);
445    }
446
447    protected void deleteBean(int row, int col) {
448        jmri.util.ThreadingUtil.runOnGUI(() -> {
449            try {
450                var worker = new DeleteBeanWorker(getBySystemName(sysNameList.get(row)));
451                log.debug("Delete Bean {}", worker.toString());
452            } catch (Exception e ){
453                log.error("Exception while deleting bean", e);
454            }
455        });
456    }
457
458    /**
459     * Delete the bean after all the checking has been done.
460     * <p>
461     * Separate so that it can be easily subclassed if other functionality is
462     * needed.
463     *
464     * @param bean NamedBean to delete
465     */
466    protected void doDelete(T bean) {
467        try {
468            getManager().deleteBean(bean, "DoDelete");
469        } catch (PropertyVetoException e) {
470            //At this stage the DoDelete shouldn't fail, as we have already done a can delete, which would trigger a veto
471            log.error("doDelete should not fail after canDelete. {}", e.getMessage());
472        }
473    }
474
475    /**
476     * Configure a table to have our standard rows and columns. This is
477     * optional, in that other table formats can use this table model. But we
478     * put it here to help keep it consistent.
479     * This also persists the table user interface state.
480     *
481     * @param table {@link JTable} to configure
482     */
483    public void configureTable(JTable table) {
484        // Property columns will be invisible at start.
485        setPropertyColumnsVisible(table, false);
486
487        table.setDefaultRenderer(JComboBox.class, new BtValueRenderer());
488        table.setDefaultEditor(JComboBox.class, new BtComboboxEditor());
489        table.setDefaultRenderer(Boolean.class, new EnablingCheckboxRenderer());
490        table.setDefaultRenderer(Date.class, new DateRenderer());
491
492        // allow reordering of the columns
493        table.getTableHeader().setReorderingAllowed(true);
494
495        // have to shut off autoResizeMode to get horizontal scroll to work (JavaSwing p 541)
496        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
497
498        XTableColumnModel columnModel = (XTableColumnModel) table.getColumnModel();
499        for (int i = 0; i < columnModel.getColumnCount(false); i++) {
500
501            // resize columns as requested
502            int width = getPreferredWidth(i);
503            columnModel.getColumnByModelIndex(i).setPreferredWidth(width);
504
505        }
506        table.sizeColumnsToFit(-1);
507
508        configValueColumn(table);
509        configDeleteColumn(table);
510
511        JmriMouseListener popupListener = new PopupListener();
512        table.addMouseListener(JmriMouseListener.adapt(popupListener));
513        this.persistTable(table);
514    }
515
516    protected void configValueColumn(JTable table) {
517        // have the value column hold a button
518        setColumnToHoldButton(table, VALUECOL, configureButton());
519    }
520
521    public JButton configureButton() {
522        // pick a large size
523        JButton b = new JButton(Bundle.getMessage("BeanStateInconsistent"));
524        b.putClientProperty("JComponent.sizeVariant", "small");
525        b.putClientProperty("JButton.buttonType", "square");
526        return b;
527    }
528
529    protected void configDeleteColumn(JTable table) {
530        // have the delete column hold a button
531        setColumnToHoldButton(table, DELETECOL,
532                new JButton(Bundle.getMessage("ButtonDelete")));
533    }
534
535    /**
536     * Service method to setup a column so that it will hold a button for its
537     * values.
538     *
539     * @param table  {@link JTable} to use
540     * @param column index for column to setup
541     * @param sample typical button, used to determine preferred size
542     */
543    protected void setColumnToHoldButton(JTable table, int column, JButton sample) {
544        // install a button renderer & editor
545        ButtonRenderer buttonRenderer = new ButtonRenderer();
546        table.setDefaultRenderer(JButton.class, buttonRenderer);
547        TableCellEditor buttonEditor = new ButtonEditor(new JButton());
548        table.setDefaultEditor(JButton.class, buttonEditor);
549        // ensure the table rows, columns have enough room for buttons
550        table.setRowHeight(sample.getPreferredSize().height);
551        table.getColumnModel().getColumn(column)
552                .setPreferredWidth((sample.getPreferredSize().width) + 4);
553    }
554
555    /**
556     * Removes property change listeners from Beans.
557     */
558    public synchronized void dispose() {
559        getManager().removePropertyChangeListener(this);
560        if (sysNameList != null) {
561            for (String s : sysNameList) {
562                T b = getBySystemName(s);
563                if (b != null) {
564                    b.removePropertyChangeListener(this);
565                }
566            }
567        }
568    }
569
570    /**
571     * Method to self print or print preview the table. Printed in equally sized
572     * columns across the page with headings and vertical lines between each
573     * column. Data is word wrapped within a column. Can handle data as strings,
574     * comboboxes or booleans
575     *
576     * @param w the printer writer
577     */
578    public void printTable(HardcopyWriter w) {
579        // determine the column size - evenly sized, with space between for lines
580        int columnSize = (w.getCharactersPerLine() - this.getColumnCount() - 1) / this.getColumnCount();
581
582        // Draw horizontal dividing line
583        w.write(w.getCurrentLineNumber(), 0, w.getCurrentLineNumber(),
584                (columnSize + 1) * this.getColumnCount());
585
586        // print the column header labels
587        String[] columnStrings = new String[this.getColumnCount()];
588        // Put each column header in the array
589        for (int i = 0; i < this.getColumnCount(); i++) {
590            columnStrings[i] = this.getColumnName(i);
591        }
592        w.setFontStyle(Font.BOLD);
593        printColumns(w, columnStrings, columnSize);
594        w.setFontStyle(0);
595        w.write(w.getCurrentLineNumber(), 0, w.getCurrentLineNumber(),
596                (columnSize + 1) * this.getColumnCount());
597
598        // now print each row of data
599        // create a base string the width of the column
600        StringBuilder spaces = new StringBuilder(); // NOI18N
601        for (int i = 0; i < columnSize; i++) {
602            spaces.append(" "); // NOI18N
603        }
604        for (int i = 0; i < this.getRowCount(); i++) {
605            for (int j = 0; j < this.getColumnCount(); j++) {
606                //check for special, non string contents
607                Object value = this.getValueAt(i, j);
608                if (value == null) {
609                    columnStrings[j] = spaces.toString();
610                } else if (value instanceof JComboBox<?>) {
611                    columnStrings[j] = Objects.requireNonNull(((JComboBox<?>) value).getSelectedItem()).toString();
612                } else {
613                    // Boolean or String
614                    columnStrings[j] = value.toString();
615                }
616            }
617            printColumns(w, columnStrings, columnSize);
618            w.write(w.getCurrentLineNumber(), 0, w.getCurrentLineNumber(),
619                    (columnSize + 1) * this.getColumnCount());
620        }
621        w.close();
622    }
623
624    protected void printColumns(HardcopyWriter w, String[] columnStrings, int columnSize) {
625        // create a base string the width of the column
626        StringBuilder spaces = new StringBuilder(); // NOI18N
627        for (int i = 0; i < columnSize; i++) {
628            spaces.append(" "); // NOI18N
629        }
630        // loop through each column
631        boolean complete = false;
632        while (!complete) {
633            StringBuilder lineString = new StringBuilder(); // NOI18N
634            complete = true;
635            for (int i = 0; i < columnStrings.length; i++) {
636                String columnString = ""; // NOI18N
637                // if the column string is too wide cut it at word boundary (valid delimiters are space, - and _)
638                // use the intial part of the text,pad it with spaces and place the remainder back in the array
639                // for further processing on next line
640                // if column string isn't too wide, pad it to column width with spaces if needed
641                if (columnStrings[i].length() > columnSize) {
642                    boolean noWord = true;
643                    for (int k = columnSize; k >= 1; k--) {
644                        if (columnStrings[i].charAt(k - 1) == ' '
645                                || columnStrings[i].charAt(k - 1) == '-'
646                                || columnStrings[i].charAt(k - 1) == '_') {
647                            columnString = columnStrings[i].substring(0, k)
648                                    + spaces.substring(columnStrings[i].substring(0, k).length());
649                            columnStrings[i] = columnStrings[i].substring(k);
650                            noWord = false;
651                            complete = false;
652                            break;
653                        }
654                    }
655                    if (noWord) {
656                        columnString = columnStrings[i].substring(0, columnSize);
657                        columnStrings[i] = columnStrings[i].substring(columnSize);
658                        complete = false;
659                    }
660
661                } else {
662                    columnString = columnStrings[i] + spaces.substring(columnStrings[i].length());
663                    columnStrings[i] = "";
664                }
665                lineString.append(columnString).append(" "); // NOI18N
666            }
667            try {
668                w.write(lineString.toString());
669                //write vertical dividing lines
670                for (int i = 0; i < w.getCharactersPerLine(); i = i + columnSize + 1) {
671                    w.write(w.getCurrentLineNumber(), i, w.getCurrentLineNumber() + 1, i);
672                }
673                w.write("\n"); // NOI18N
674            } catch (IOException e) {
675                log.warn("error during printing: {}", e.getMessage());
676            }
677        }
678    }
679
680    /**
681     * Create and configure a new table using the given model and row sorter.
682     *
683     * @param name   the name of the table
684     * @param model  the data model for the table
685     * @param sorter the row sorter for the table; if null, the table will not
686     *               be sortable
687     * @return the table
688     * @throws NullPointerException if name or model is null
689     */
690    public JTable makeJTable(@Nonnull String name, @Nonnull TableModel model, @CheckForNull RowSorter<? extends TableModel> sorter) {
691        Objects.requireNonNull(name, "the table name must be nonnull");
692        Objects.requireNonNull(model, "the table model must be nonnull");
693        JTable table = new JTable(model) {
694
695            // TODO: Create base BeanTableJTable.java,
696            // extend TurnoutTableJTable from it as next 2 classes duplicate.
697
698            @Override
699            public String getToolTipText(java.awt.event.MouseEvent e) {
700                java.awt.Point p = e.getPoint();
701                int rowIndex = rowAtPoint(p);
702                int colIndex = columnAtPoint(p);
703                int realRowIndex = convertRowIndexToModel(rowIndex);
704                int realColumnIndex = convertColumnIndexToModel(colIndex);
705                return getCellToolTip(this, realRowIndex, realColumnIndex);
706            }
707
708            /**
709             * Disable Windows Key or Mac Meta Keys being pressed acting
710             * as a trigger for editing the focused cell.
711             * Causes unexpected behaviour, i.e. button presses.
712             * {@inheritDoc}
713             */
714            @Override
715            public boolean editCellAt(int row, int column, EventObject e) {
716                if (e instanceof KeyEvent) {
717                    if ( ((KeyEvent) e).getKeyCode() == KeyEvent.VK_WINDOWS
718                        || ( (KeyEvent) e).getKeyCode() == KeyEvent.VK_META ) {
719                        return false;
720                    }
721                }
722                return super.editCellAt(row, column, e);
723            }
724        };
725        return this.configureJTable(name, table, sorter);
726    }
727
728    /**
729     * Configure a new table using the given model and row sorter.
730     *
731     * @param table  the table to configure
732     * @param name   the table name
733     * @param sorter the row sorter for the table; if null, the table will not
734     *               be sortable
735     * @return the table
736     * @throws NullPointerException if table or the table name is null
737     */
738    protected JTable configureJTable(@Nonnull String name, @Nonnull JTable table, @CheckForNull RowSorter<? extends TableModel> sorter) {
739        Objects.requireNonNull(table, "the table must be nonnull");
740        Objects.requireNonNull(name, "the table name must be nonnull");
741        table.setRowSorter(sorter);
742        table.setName(name);
743        table.getTableHeader().setReorderingAllowed(true);
744        table.setColumnModel(new XTableColumnModel());
745        table.createDefaultColumnsFromModel();
746        addMouseListenerToHeader(table);
747        table.getTableHeader().setDefaultRenderer(new BeanTableTooltipHeaderRenderer(table.getTableHeader().getDefaultRenderer()));
748        return table;
749    }
750
751    /**
752     * Get String of the Single Bean Type.
753     * In many cases the return is Bundle localised
754     * so should not be used for matching Bean types.
755     *
756     * @return Bean Type String.
757     */
758    protected String getBeanType(){
759        return getManager().getBeanTypeHandled(false);
760    }
761
762    /**
763     * Updates the visibility settings of the property columns.
764     *
765     * @param table   the JTable object for the current display.
766     * @param visible true to make the property columns visible, false to hide.
767     */
768    public void setPropertyColumnsVisible(JTable table, boolean visible) {
769        XTableColumnModel columnModel = (XTableColumnModel) table.getColumnModel();
770        for (int i = getColumnCount() - 1; i >= getColumnCount() - getPropertyColumnCount(); --i) {
771            TableColumn column = columnModel.getColumnByModelIndex(i);
772            columnModel.setColumnVisible(column, visible);
773        }
774    }
775
776    /**
777     * Is a bean allowed to have the user name cleared?
778     * @return true if clear is allowed, false otherwise
779     */
780    protected boolean isClearUserNameAllowed() {
781        return true;
782    }
783
784    /**
785     * Display popup menu when right clicked on table cell.
786     * <p>
787     * Copy UserName
788     * Rename
789     * Remove UserName
790     * Move
791     * Edit Comment
792     * Delete
793     * @param e source event.
794     */
795    protected void showPopup(JmriMouseEvent e) {
796        JTable source = (JTable) e.getSource();
797        int row = source.rowAtPoint(e.getPoint());
798        int column = source.columnAtPoint(e.getPoint());
799        if (!source.isRowSelected(row)) {
800            source.changeSelection(row, column, false, false);
801        }
802        final int rowindex = source.convertRowIndexToModel(row);
803
804        JPopupMenu popupMenu = new JPopupMenu();
805        JMenuItem menuItem = new JMenuItem(Bundle.getMessage("CopyName"));
806        menuItem.addActionListener((ActionEvent e1) -> copyName(rowindex, 0));
807        popupMenu.add(menuItem);
808
809        menuItem = new JMenuItem(Bundle.getMessage("Rename"));
810        menuItem.addActionListener((ActionEvent e1) -> renameBean(rowindex, 0));
811        popupMenu.add(menuItem);
812
813        if (isClearUserNameAllowed()) {
814            menuItem = new JMenuItem(Bundle.getMessage("ClearName"));
815            menuItem.addActionListener((ActionEvent e1) -> removeName(rowindex, 0));
816            popupMenu.add(menuItem);
817        }
818
819        menuItem = new JMenuItem(Bundle.getMessage("MoveName"));
820        menuItem.addActionListener((ActionEvent e1) -> moveBean(rowindex, 0));
821        if (getRowCount() == 1) {
822            menuItem.setEnabled(false); // you can't move when there is just 1 item (to other table?
823        }
824        popupMenu.add(menuItem);
825
826        menuItem = new JMenuItem(Bundle.getMessage("EditComment"));
827        menuItem.addActionListener((ActionEvent e1) -> editComment(rowindex, 0));
828        popupMenu.add(menuItem);
829
830        menuItem = new JMenuItem(Bundle.getMessage("ButtonDelete"));
831        menuItem.addActionListener((ActionEvent e1) -> deleteBean(rowindex, 0));
832        popupMenu.add(menuItem);
833
834        popupMenu.show(e.getComponent(), e.getX(), e.getY());
835    }
836
837    public void copyName(int row, int column) {
838        T nBean = getBySystemName(sysNameList.get(row));
839        Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
840        StringSelection name = new StringSelection(nBean.getUserName());
841        clipboard.setContents(name, null);
842    }
843
844    /**
845     * Change the bean User Name in a dialog.
846     *
847     * @param row table model row number of bean
848     * @param column always passed in as 0, not used
849     */
850    public void renameBean(int row, int column) {
851        T nBean = getBySystemName(sysNameList.get(row));
852        String oldName = (nBean.getUserName() == null ? "" : nBean.getUserName());
853        String newName = JmriJOptionPane.showInputDialog(null,
854                Bundle.getMessage("RenameFrom", getBeanType(), "\"" +oldName+"\""), oldName);
855        if (newName == null || newName.equals(nBean.getUserName())) {
856            // name not changed
857            return;
858        } else {
859            T nB = getByUserName(newName);
860            if (nB != null) {
861                log.error("User name is not unique {}", newName);
862                String msg = Bundle.getMessage("WarningUserName", "" + newName);
863                JmriJOptionPane.showMessageDialog(null, msg,
864                        Bundle.getMessage("WarningTitle"),
865                        JmriJOptionPane.ERROR_MESSAGE);
866                return;
867            }
868        }
869
870        if (!allowBlockNameChange("Rename", nBean, newName)) {
871            return;  // NOI18N
872        }
873
874        try {
875            nBean.setUserName(newName);
876        } catch (NamedBean.BadSystemNameException | NamedBean.BadUserNameException ex) {
877            JmriJOptionPane.showMessageDialog(null, ex.getLocalizedMessage(),
878                    Bundle.getMessage("ErrorTitle"), // NOI18N
879                    JmriJOptionPane.ERROR_MESSAGE);
880            return;
881        }
882
883        fireTableRowsUpdated(row, row);
884        if (!newName.isEmpty()) {
885            if (oldName == null || oldName.isEmpty()) {
886                if (!nbMan.inUse(sysNameList.get(row), nBean)) {
887                    return;
888                }
889                String msg = Bundle.getMessage("UpdateToUserName", getBeanType(), newName, sysNameList.get(row));
890                int optionPane = JmriJOptionPane.showConfirmDialog(null,
891                        msg, Bundle.getMessage("UpdateToUserNameTitle"),
892                        JmriJOptionPane.YES_NO_OPTION);
893                if (optionPane == JmriJOptionPane.YES_OPTION) {
894                    //This will update the bean reference from the systemName to the userName
895                    try {
896                        nbMan.updateBeanFromSystemToUser(nBean);
897                    } catch (JmriException ex) {
898                        //We should never get an exception here as we already check that the username is not valid
899                        log.error("Impossible exception renaming Bean", ex);
900                    }
901                }
902            } else {
903                nbMan.renameBean(oldName, newName, nBean);
904            }
905
906        } else {
907            //This will update the bean reference from the old userName to the SystemName
908            nbMan.updateBeanFromUserToSystem(nBean);
909        }
910    }
911
912    public void removeName(int row, int column) {
913        T nBean = getBySystemName(sysNameList.get(row));
914        if (!allowBlockNameChange("Remove", nBean, "")) return;  // NOI18N
915        String msg = Bundle.getMessage("UpdateToSystemName", getBeanType());
916        int optionPane = JmriJOptionPane.showConfirmDialog(null,
917                msg, Bundle.getMessage("UpdateToSystemNameTitle"),
918                JmriJOptionPane.YES_NO_OPTION);
919        if (optionPane == JmriJOptionPane.YES_OPTION) {
920            nbMan.updateBeanFromUserToSystem(nBean);
921        }
922        nBean.setUserName(null);
923        fireTableRowsUpdated(row, row);
924    }
925
926    /**
927     * Determine whether it is safe to rename/remove a Block user name.
928     * <p>The user name is used by the LayoutBlock to link to the block and
929     * by Layout Editor track components to link to the layout block.
930     *
931     * @param changeType This will be Remove or Rename.
932     * @param bean The affected bean.  Only the Block bean is of interest.
933     * @param newName For Remove this will be empty, for Rename it will be the new user name.
934     * @return true to continue with the user name change.
935     */
936    boolean allowBlockNameChange(String changeType, T bean, String newName) {
937        if (!(bean instanceof jmri.Block)) {
938            return true;
939        }
940        // If there is no layout block or the block name is empty, Block rename and remove are ok without notification.
941        String oldName = bean.getUserName();
942        if (oldName == null) return true;
943        LayoutBlock layoutBlock = jmri.InstanceManager.getDefault(LayoutBlockManager.class).getByUserName(oldName);
944        if (layoutBlock == null) return true;
945
946        // Remove is not allowed if there is a layout block
947        if (changeType.equals("Remove")) {
948            log.warn("Cannot remove user name for block {}", oldName);  // NOI18N
949                JmriJOptionPane.showMessageDialog(null,
950                        Bundle.getMessage("BlockRemoveUserNameWarning", oldName),  // NOI18N
951                        Bundle.getMessage("WarningTitle"),  // NOI18N
952                        JmriJOptionPane.WARNING_MESSAGE);
953            return false;
954        }
955
956        // Confirmation dialog
957        int optionPane = JmriJOptionPane.showConfirmDialog(null,
958                Bundle.getMessage("BlockChangeUserName", oldName, newName),  // NOI18N
959                Bundle.getMessage("QuestionTitle"),  // NOI18N
960                JmriJOptionPane.YES_NO_OPTION);
961        return optionPane == JmriJOptionPane.YES_OPTION;
962    }
963
964    public void moveBean(int row, int column) {
965        final T t = getBySystemName(sysNameList.get(row));
966        String currentName = t.getUserName();
967        T oldNameBean = getBySystemName(sysNameList.get(row));
968
969        if ((currentName == null) || currentName.isEmpty()) {
970            JmriJOptionPane.showMessageDialog(null, Bundle.getMessage("MoveDialogErrorMessage"));
971            return;
972        }
973
974        JComboBox<String> box = new JComboBox<>();
975        getManager().getNamedBeanSet().forEach((T b) -> {
976            //Only add items that do not have a username assigned.
977            String userName = b.getUserName();
978            if (userName == null || userName.isEmpty()) {
979                box.addItem(b.getSystemName());
980            }
981        });
982
983        int retval = JmriJOptionPane.showOptionDialog(null,
984                Bundle.getMessage("MoveDialog", getBeanType(), currentName, oldNameBean.getSystemName()),
985                Bundle.getMessage("MoveDialogTitle"),
986                JmriJOptionPane.YES_NO_OPTION, JmriJOptionPane.INFORMATION_MESSAGE, null,
987                new Object[]{Bundle.getMessage("ButtonCancel"), Bundle.getMessage("ButtonOK"), box}, null);
988        log.debug("Dialog value {} selected {}:{}", retval, box.getSelectedIndex(), box.getSelectedItem());
989        if (retval != 1) {
990            return;
991        }
992        String entry = (String) box.getSelectedItem();
993        assert entry != null;
994        T newNameBean = getBySystemName(entry);
995        if (oldNameBean != newNameBean) {
996            oldNameBean.setUserName(null);
997            newNameBean.setUserName(currentName);
998            InstanceManager.getDefault(NamedBeanHandleManager.class).moveBean(oldNameBean, newNameBean, currentName);
999            if (nbMan.inUse(newNameBean.getSystemName(), newNameBean)) {
1000                String msg = Bundle.getMessage("UpdateToUserName", getBeanType(), currentName, sysNameList.get(row));
1001                int optionPane = JmriJOptionPane.showConfirmDialog(null, msg, Bundle.getMessage("UpdateToUserNameTitle"), JmriJOptionPane.YES_NO_OPTION);
1002                if (optionPane == JmriJOptionPane.YES_OPTION) {
1003                    try {
1004                        nbMan.updateBeanFromSystemToUser(newNameBean);
1005                    } catch (JmriException ex) {
1006                        //We should never get an exception here as we already check that the username is not valid
1007                        log.error("Impossible exception moving Bean", ex);
1008                    }
1009                }
1010            }
1011            fireTableRowsUpdated(row, row);
1012            InstanceManager.getDefault(UserPreferencesManager.class).
1013                    showInfoMessage(Bundle.getMessage("ReminderTitle"),
1014                            Bundle.getMessage("UpdateComplete", getBeanType()),
1015                            getMasterClassName(), "remindSaveReLoad");
1016        }
1017    }
1018
1019    public void editComment(int row, int column) {
1020        T nBean = getBySystemName(sysNameList.get(row));
1021        JTextArea commentField = new JTextArea(5, 50);
1022        JScrollPane commentFieldScroller = new JScrollPane(commentField);
1023        commentField.setText(nBean.getComment());
1024        Object[] editCommentOption = {Bundle.getMessage("ButtonCancel"), Bundle.getMessage("ButtonUpdate")};
1025        int retval = JmriJOptionPane.showOptionDialog(null,
1026                commentFieldScroller, Bundle.getMessage("EditComment"),
1027                JmriJOptionPane.YES_NO_OPTION, JmriJOptionPane.INFORMATION_MESSAGE, null,
1028                editCommentOption, editCommentOption[1]);
1029        if (retval != 1) {
1030            return;
1031        }
1032        nBean.setComment(commentField.getText());
1033   }
1034
1035    /**
1036     * Display the comment text for the current row as a tool tip.
1037     *
1038     * Most of the bean tables use the standard model with comments in column 3.
1039     *
1040     * @param table The current table.
1041     * @param row The current row.
1042     * @param col The current column.
1043     * @return a formatted tool tip or null if there is none.
1044     */
1045    public String getCellToolTip(JTable table, int row, int col) {
1046        String tip = null;
1047        int column = COMMENTCOL;
1048        if (table.getName().contains("SignalGroup")) column = 2;
1049        if (col == column) {
1050            T nBean = getBySystemName(sysNameList.get(row));
1051            if (nBean != null) {
1052                tip = formatToolTip(nBean.getComment());
1053            }
1054        }
1055        return tip;
1056    }
1057
1058    /**
1059     * Get a ToolTip for a Table Column Header.
1060     * @param columnModelIndex the model column number.
1061     * @return ToolTip, else null.
1062     */
1063    @OverridingMethodsMustInvokeSuper
1064    protected String getHeaderTooltip(int columnModelIndex) {
1065        return null;
1066    }
1067
1068    /**
1069     * Format a comment field as a tool tip string. Multi line comments are supported.
1070     * @param comment The comment string.
1071     * @return a html formatted string or null if the comment is empty.
1072     */
1073    protected String formatToolTip(String comment) {
1074        String tip = null;
1075        if (comment != null && !comment.isEmpty()) {
1076            tip = "<html>" + comment.replaceAll(System.getProperty("line.separator"), "<br>") + "</html>";
1077        }
1078        return tip;
1079    }
1080
1081    /**
1082     * Show the Table Column Menu.
1083     * @param e Instigating event ( e.g. from Mouse click )
1084     * @param table table to get columns from
1085     */
1086    protected void showTableHeaderPopup(JmriMouseEvent e, JTable table) {
1087        JPopupMenu popupMenu = new JPopupMenu();
1088        XTableColumnModel tcm = (XTableColumnModel) table.getColumnModel();
1089        for (int i = 0; i < tcm.getColumnCount(false); i++) {
1090            TableColumn tc = tcm.getColumnByModelIndex(i);
1091            String columnName = table.getModel().getColumnName(i);
1092            if (columnName != null && !columnName.isEmpty()) {
1093                StayOpenCheckBoxItem menuItem = new StayOpenCheckBoxItem(table.getModel().getColumnName(i), tcm.isColumnVisible(tc));
1094                menuItem.addActionListener(new HeaderActionListener(tc, tcm));
1095                TableModel mod = table.getModel();
1096                if (mod instanceof BeanTableDataModel<?>) {
1097                    menuItem.setToolTipText(((BeanTableDataModel<?>)mod).getHeaderTooltip(i));
1098                }
1099                popupMenu.add(menuItem);
1100            }
1101
1102        }
1103        popupMenu.show(e.getComponent(), e.getX(), e.getY());
1104    }
1105
1106    protected void addMouseListenerToHeader(JTable table) {
1107        JmriMouseListener mouseHeaderListener = new TableHeaderListener(table);
1108        table.getTableHeader().addMouseListener(JmriMouseListener.adapt(mouseHeaderListener));
1109    }
1110
1111    /**
1112     * Persist the state of the table after first setting the table to the last
1113     * persisted state.
1114     *
1115     * @param table the table to persist
1116     * @throws NullPointerException if the name of the table is null
1117     */
1118    public void persistTable(@Nonnull JTable table) throws NullPointerException {
1119        InstanceManager.getOptionalDefault(JTablePersistenceManager.class).ifPresent((manager) -> {
1120            setColumnIdentities(table);
1121            manager.resetState(table); // throws NPE if table name is null
1122            manager.persist(table);
1123        });
1124    }
1125
1126    /**
1127     * Stop persisting the state of the table.
1128     *
1129     * @param table the table to stop persisting
1130     * @throws NullPointerException if the name of the table is null
1131     */
1132    public void stopPersistingTable(@Nonnull JTable table) throws NullPointerException {
1133        InstanceManager.getOptionalDefault(JTablePersistenceManager.class).ifPresent((manager) -> {
1134            manager.stopPersisting(table); // throws NPE if table name is null
1135        });
1136    }
1137
1138    /**
1139     * Set identities for any columns that need an identity.
1140     *
1141     * It is recommended that all columns get a constant identity to
1142     * prevent identities from being subject to changes due to translation.
1143     * <p>
1144     * The default implementation sets column identities to the String
1145     * {@code Column#} where {@code #} is the model index for the column.
1146     * Note that if the TableColumnModel is a {@link jmri.util.swing.XTableColumnModel},
1147     * the index includes hidden columns.
1148     *
1149     * @param table the table to set identities for.
1150     */
1151    protected void setColumnIdentities(JTable table) {
1152        Objects.requireNonNull(table.getModel(), "Table must have data model");
1153        Objects.requireNonNull(table.getColumnModel(), "Table must have column model");
1154        Enumeration<TableColumn> columns;
1155        if (table.getColumnModel() instanceof XTableColumnModel) {
1156            columns = ((XTableColumnModel) table.getColumnModel()).getColumns(false);
1157        } else {
1158            columns = table.getColumnModel().getColumns();
1159        }
1160        int i = 0;
1161        while (columns.hasMoreElements()) {
1162            TableColumn column = columns.nextElement();
1163            if (column.getIdentifier() == null || column.getIdentifier().toString().isEmpty()) {
1164                column.setIdentifier(String.format("Column%d", i));
1165            }
1166            i += 1;
1167        }
1168    }
1169
1170    protected class BeanTableTooltipHeaderRenderer extends DefaultTableCellRenderer  {
1171        private final TableCellRenderer _existingRenderer;
1172
1173        protected BeanTableTooltipHeaderRenderer(TableCellRenderer existingRenderer) {
1174            _existingRenderer = existingRenderer;
1175        }
1176
1177        @Override
1178        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
1179            
1180            Component rendererComponent = _existingRenderer.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
1181            TableModel mod = table.getModel();
1182            if ( rendererComponent instanceof JLabel && mod instanceof BeanTableDataModel<?> ) { // Set the cell ToolTip
1183                int modelIndex = table.getColumnModel().getColumn(column).getModelIndex();
1184                String tooltip = ((BeanTableDataModel<?>)mod).getHeaderTooltip(modelIndex);
1185                ((JLabel)rendererComponent).setToolTipText(tooltip);
1186            }
1187            return rendererComponent;
1188        }
1189    }
1190
1191    /**
1192     * Listener class which processes Column Menu button clicks.
1193     * Does not allow the last column to be hidden,
1194     * otherwise there would be no table header to recover the column menu / columns from.
1195     */
1196    static class HeaderActionListener implements ActionListener {
1197
1198        private final TableColumn tc;
1199        private final XTableColumnModel tcm;
1200
1201        HeaderActionListener(TableColumn tc, XTableColumnModel tcm) {
1202            this.tc = tc;
1203            this.tcm = tcm;
1204        }
1205
1206        @Override
1207        public void actionPerformed(ActionEvent e) {
1208            JCheckBoxMenuItem check = (JCheckBoxMenuItem) e.getSource();
1209            //Do not allow the last column to be hidden
1210            if (!check.isSelected() && tcm.getColumnCount(true) == 1) {
1211                return;
1212            }
1213            tcm.setColumnVisible(tc, check.isSelected());
1214        }
1215    }
1216
1217    class DeleteBeanWorker  {
1218
1219        public DeleteBeanWorker(final T bean) {
1220
1221            StringBuilder message = new StringBuilder();
1222            try {
1223                getManager().deleteBean(bean, "CanDelete");  // NOI18N
1224            } catch (PropertyVetoException e) {
1225                if (e.getPropertyChangeEvent().getPropertyName().equals("DoNotDelete")) { // NOI18N
1226                    log.warn("Should not delete {}, {}", bean.getDisplayName((DisplayOptions.USERNAME_SYSTEMNAME)), e.getMessage());
1227                    message.append(Bundle.getMessage("VetoDeleteBean", bean.getBeanType(), bean.getDisplayName(DisplayOptions.USERNAME_SYSTEMNAME), e.getMessage()));
1228                    JmriJOptionPane.showMessageDialog(null, message.toString(),
1229                            Bundle.getMessage("WarningTitle"),
1230                            JmriJOptionPane.ERROR_MESSAGE);
1231                    return;
1232                }
1233                message.append(e.getMessage());
1234            }
1235            int count = bean.getListenerRefs().size();
1236            log.debug("Delete with {}", count);
1237            if (getDisplayDeleteMsg() == 0x02 && message.toString().isEmpty()) {
1238                doDelete(bean);
1239            } else {
1240                JPanel container = new JPanel();
1241                container.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
1242                container.setLayout(new BoxLayout(container, BoxLayout.Y_AXIS));
1243                if (count > 0) { // warn of listeners attached before delete
1244
1245                    JLabel question = new JLabel(Bundle.getMessage("DeletePrompt", bean.getDisplayName(DisplayOptions.USERNAME_SYSTEMNAME)));
1246                    question.setAlignmentX(Component.CENTER_ALIGNMENT);
1247                    container.add(question);
1248
1249                    ArrayList<String> listenerRefs = bean.getListenerRefs();
1250                    if (!listenerRefs.isEmpty()) {
1251                        ArrayList<String> listeners = new ArrayList<>();
1252                        for (String listenerRef : listenerRefs) {
1253                            if (!listeners.contains(listenerRef)) {
1254                                listeners.add(listenerRef);
1255                            }
1256                        }
1257
1258                        message.append("<br>");
1259                        message.append(Bundle.getMessage("ReminderInUse", count));
1260                        message.append("<ul>");
1261                        for (String listener : listeners) {
1262                            message.append("<li>");
1263                            message.append(listener);
1264                            message.append("</li>");
1265                        }
1266                        message.append("</ul>");
1267
1268                        JEditorPane pane = new JEditorPane();
1269                        pane.setContentType("text/html");
1270                        pane.setText("<html>" + message.toString() + "</html>");
1271                        pane.setEditable(false);
1272                        JScrollPane jScrollPane = new JScrollPane(pane);
1273                        container.add(jScrollPane);
1274                    }
1275                } else {
1276                    String msg = MessageFormat.format(
1277                            Bundle.getMessage("DeletePrompt"), bean.getSystemName());
1278                    JLabel question = new JLabel(msg);
1279                    question.setAlignmentX(Component.CENTER_ALIGNMENT);
1280                    container.add(question);
1281                }
1282
1283                final JCheckBox remember = new JCheckBox(Bundle.getMessage("MessageRememberSetting"));
1284                remember.setFont(remember.getFont().deriveFont(10f));
1285                remember.setAlignmentX(Component.CENTER_ALIGNMENT);
1286
1287                container.add(remember);
1288                container.setAlignmentX(Component.CENTER_ALIGNMENT);
1289                container.setAlignmentY(Component.CENTER_ALIGNMENT);
1290                String[] options = new String[]{JmriJOptionPane.YES_STRING, JmriJOptionPane.NO_STRING};
1291                int result = JmriJOptionPane.showOptionDialog(null, container, Bundle.getMessage("WarningTitle"), 
1292                    JmriJOptionPane.DEFAULT_OPTION, JmriJOptionPane.WARNING_MESSAGE, null, 
1293                    options, JmriJOptionPane.NO_STRING);
1294
1295                if ( result == 0 ){ // first item in Array is Yes
1296                    if (remember.isSelected()) {
1297                        setDisplayDeleteMsg(0x02);
1298                    }
1299                    doDelete(bean);
1300                }
1301
1302            }
1303        }
1304    }
1305
1306    /**
1307     * Listener to trigger display of table cell menu.
1308     * Delete / Rename / Move etc.
1309     */
1310    class PopupListener extends JmriMouseAdapter {
1311
1312        /**
1313         * {@inheritDoc}
1314         */
1315        @Override
1316        public void mousePressed(JmriMouseEvent e) {
1317            if (e.isPopupTrigger()) {
1318                showPopup(e);
1319            }
1320        }
1321
1322        /**
1323         * {@inheritDoc}
1324         */
1325        @Override
1326        public void mouseReleased(JmriMouseEvent e) {
1327            if (e.isPopupTrigger()) {
1328                showPopup(e);
1329            }
1330        }
1331    }
1332
1333    /**
1334     * Listener to trigger display of table header column menu.
1335     */
1336    class TableHeaderListener extends JmriMouseAdapter {
1337
1338        private final JTable table;
1339
1340        TableHeaderListener(JTable tbl) {
1341            super();
1342            table = tbl;
1343        }
1344
1345        /**
1346         * {@inheritDoc}
1347         */
1348        @Override
1349        public void mousePressed(JmriMouseEvent e) {
1350            if (e.isPopupTrigger()) {
1351                showTableHeaderPopup(e, table);
1352            }
1353        }
1354
1355        /**
1356         * {@inheritDoc}
1357         */
1358        @Override
1359        public void mouseReleased(JmriMouseEvent e) {
1360            if (e.isPopupTrigger()) {
1361                showTableHeaderPopup(e, table);
1362            }
1363        }
1364
1365        /**
1366         * {@inheritDoc}
1367         */
1368        @Override
1369        public void mouseClicked(JmriMouseEvent e) {
1370            if (e.isPopupTrigger()) {
1371                showTableHeaderPopup(e, table);
1372            }
1373        }
1374    }
1375
1376    private class BtComboboxEditor extends jmri.jmrit.symbolicprog.ValueEditor {
1377
1378        BtComboboxEditor(){
1379            super();
1380        }
1381
1382        @Override
1383        public Component getTableCellEditorComponent(JTable table, Object value,
1384            boolean isSelected,
1385            int row, int column) {
1386            if (value instanceof JComboBox) {
1387                ((JComboBox<?>) value).addActionListener((ActionEvent e1) -> table.getCellEditor().stopCellEditing());
1388            }
1389
1390            if (value instanceof JComponent ) {
1391
1392                int modelcol =  table.convertColumnIndexToModel(column);
1393                int modelrow = table.convertRowIndexToModel(row);
1394
1395                // if cell is not editable, jcombobox not applicable for hardware type
1396                boolean editable = table.getModel().isCellEditable(modelrow, modelcol);
1397
1398                ((JComponent) value).setEnabled(editable);
1399
1400            }
1401
1402            return super.getTableCellEditorComponent(table, value, isSelected, row, column);
1403        }
1404
1405
1406    }
1407
1408    private class BtValueRenderer implements TableCellRenderer {
1409
1410        BtValueRenderer() {
1411            super();
1412        }
1413
1414        @Override
1415        public Component getTableCellRendererComponent(JTable table, Object value,
1416            boolean isSelected, boolean hasFocus, int row, int column) {
1417
1418            if (value instanceof Component) {
1419                return (Component) value;
1420            } else if (value instanceof String) {
1421                return new JLabel((String) value);
1422            } else {
1423                JPanel f = new JPanel();
1424                f.setBackground(isSelected ? table.getSelectionBackground() : table.getBackground() );
1425                return f;
1426            }
1427        }
1428    }
1429
1430    /**
1431     * Set the filter to select which beans to include in the table.
1432     * @param filter the filter
1433     */
1434    public synchronized void setFilter(Predicate<? super T> filter) {
1435        this.filter = filter;
1436        updateNameList();
1437    }
1438
1439    /**
1440     * Get the filter to select which beans to include in the table.
1441     * @return the filter
1442     */
1443    public synchronized Predicate<? super T> getFilter() {
1444        return filter;
1445    }
1446
1447    static class DateRenderer extends DefaultTableCellRenderer {
1448
1449        private final DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM);
1450
1451        @Override
1452        public Component getTableCellRendererComponent( JTable table, Object value,
1453            boolean isSelected, boolean hasFocus, int row, int column) {
1454            JLabel c = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
1455            if ( value instanceof Date) {
1456                c.setText(dateFormat.format(value));
1457            }
1458            return c;
1459        }
1460    }
1461
1462    private final static org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(BeanTableDataModel.class);
1463
1464}