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    synchronized public void dispose() {
556        getManager().removePropertyChangeListener(this);
557        if (sysNameList != null) {
558            for (String s : sysNameList) {
559                T b = getBySystemName(s);
560                if (b != null) {
561                    b.removePropertyChangeListener(this);
562                }
563            }
564        }
565    }
566
567    /**
568     * Method to self print or print preview the table. Printed in equally sized
569     * columns across the page with headings and vertical lines between each
570     * column. Data is word wrapped within a column. Can handle data as strings,
571     * comboboxes or booleans
572     *
573     * @param w the printer writer
574     */
575    public void printTable(HardcopyWriter w) {
576        // determine the column size - evenly sized, with space between for lines
577        int columnSize = (w.getCharactersPerLine() - this.getColumnCount() - 1) / this.getColumnCount();
578
579        // Draw horizontal dividing line
580        w.write(w.getCurrentLineNumber(), 0, w.getCurrentLineNumber(),
581                (columnSize + 1) * this.getColumnCount());
582
583        // print the column header labels
584        String[] columnStrings = new String[this.getColumnCount()];
585        // Put each column header in the array
586        for (int i = 0; i < this.getColumnCount(); i++) {
587            columnStrings[i] = this.getColumnName(i);
588        }
589        w.setFontStyle(Font.BOLD);
590        printColumns(w, columnStrings, columnSize);
591        w.setFontStyle(0);
592        w.write(w.getCurrentLineNumber(), 0, w.getCurrentLineNumber(),
593                (columnSize + 1) * this.getColumnCount());
594
595        // now print each row of data
596        // create a base string the width of the column
597        StringBuilder spaces = new StringBuilder(); // NOI18N
598        for (int i = 0; i < columnSize; i++) {
599            spaces.append(" "); // NOI18N
600        }
601        for (int i = 0; i < this.getRowCount(); i++) {
602            for (int j = 0; j < this.getColumnCount(); j++) {
603                //check for special, non string contents
604                Object value = this.getValueAt(i, j);
605                if (value == null) {
606                    columnStrings[j] = spaces.toString();
607                } else if (value instanceof JComboBox<?>) {
608                    columnStrings[j] = Objects.requireNonNull(((JComboBox<?>) value).getSelectedItem()).toString();
609                } else {
610                    // Boolean or String
611                    columnStrings[j] = value.toString();
612                }
613            }
614            printColumns(w, columnStrings, columnSize);
615            w.write(w.getCurrentLineNumber(), 0, w.getCurrentLineNumber(),
616                    (columnSize + 1) * this.getColumnCount());
617        }
618        w.close();
619    }
620
621    protected void printColumns(HardcopyWriter w, String[] columnStrings, int columnSize) {
622        // create a base string the width of the column
623        StringBuilder spaces = new StringBuilder(); // NOI18N
624        for (int i = 0; i < columnSize; i++) {
625            spaces.append(" "); // NOI18N
626        }
627        // loop through each column
628        boolean complete = false;
629        while (!complete) {
630            StringBuilder lineString = new StringBuilder(); // NOI18N
631            complete = true;
632            for (int i = 0; i < columnStrings.length; i++) {
633                String columnString = ""; // NOI18N
634                // if the column string is too wide cut it at word boundary (valid delimiters are space, - and _)
635                // use the intial part of the text,pad it with spaces and place the remainder back in the array
636                // for further processing on next line
637                // if column string isn't too wide, pad it to column width with spaces if needed
638                if (columnStrings[i].length() > columnSize) {
639                    boolean noWord = true;
640                    for (int k = columnSize; k >= 1; k--) {
641                        if (columnStrings[i].charAt(k - 1) == ' '
642                                || columnStrings[i].charAt(k - 1) == '-'
643                                || columnStrings[i].charAt(k - 1) == '_') {
644                            columnString = columnStrings[i].substring(0, k)
645                                    + spaces.substring(columnStrings[i].substring(0, k).length());
646                            columnStrings[i] = columnStrings[i].substring(k);
647                            noWord = false;
648                            complete = false;
649                            break;
650                        }
651                    }
652                    if (noWord) {
653                        columnString = columnStrings[i].substring(0, columnSize);
654                        columnStrings[i] = columnStrings[i].substring(columnSize);
655                        complete = false;
656                    }
657
658                } else {
659                    columnString = columnStrings[i] + spaces.substring(columnStrings[i].length());
660                    columnStrings[i] = "";
661                }
662                lineString.append(columnString).append(" "); // NOI18N
663            }
664            try {
665                w.write(lineString.toString());
666                //write vertical dividing lines
667                for (int i = 0; i < w.getCharactersPerLine(); i = i + columnSize + 1) {
668                    w.write(w.getCurrentLineNumber(), i, w.getCurrentLineNumber() + 1, i);
669                }
670                w.write("\n"); // NOI18N
671            } catch (IOException e) {
672                log.warn("error during printing: {}", e.getMessage());
673            }
674        }
675    }
676
677    /**
678     * Create and configure a new table using the given model and row sorter.
679     *
680     * @param name   the name of the table
681     * @param model  the data model for the table
682     * @param sorter the row sorter for the table; if null, the table will not
683     *               be sortable
684     * @return the table
685     * @throws NullPointerException if name or model is null
686     */
687    public JTable makeJTable(@Nonnull String name, @Nonnull TableModel model, @CheckForNull RowSorter<? extends TableModel> sorter) {
688        Objects.requireNonNull(name, "the table name must be nonnull");
689        Objects.requireNonNull(model, "the table model must be nonnull");
690        JTable table = new JTable(model) {
691
692            // TODO: Create base BeanTableJTable.java,
693            // extend TurnoutTableJTable from it as next 2 classes duplicate.
694
695            @Override
696            public String getToolTipText(java.awt.event.MouseEvent e) {
697                java.awt.Point p = e.getPoint();
698                int rowIndex = rowAtPoint(p);
699                int colIndex = columnAtPoint(p);
700                int realRowIndex = convertRowIndexToModel(rowIndex);
701                int realColumnIndex = convertColumnIndexToModel(colIndex);
702                return getCellToolTip(this, realRowIndex, realColumnIndex);
703            }
704
705            /**
706             * Disable Windows Key or Mac Meta Keys being pressed acting
707             * as a trigger for editing the focused cell.
708             * Causes unexpected behaviour, i.e. button presses.
709             * {@inheritDoc}
710             */
711            @Override
712            public boolean editCellAt(int row, int column, EventObject e) {
713                if (e instanceof KeyEvent) {
714                    if ( ((KeyEvent) e).getKeyCode() == KeyEvent.VK_WINDOWS
715                        || ( (KeyEvent) e).getKeyCode() == KeyEvent.VK_META ) {
716                        return false;
717                    }
718                }
719                return super.editCellAt(row, column, e);
720            }
721        };
722        return this.configureJTable(name, table, sorter);
723    }
724
725    /**
726     * Configure a new table using the given model and row sorter.
727     *
728     * @param table  the table to configure
729     * @param name   the table name
730     * @param sorter the row sorter for the table; if null, the table will not
731     *               be sortable
732     * @return the table
733     * @throws NullPointerException if table or the table name is null
734     */
735    protected JTable configureJTable(@Nonnull String name, @Nonnull JTable table, @CheckForNull RowSorter<? extends TableModel> sorter) {
736        Objects.requireNonNull(table, "the table must be nonnull");
737        Objects.requireNonNull(name, "the table name must be nonnull");
738        table.setRowSorter(sorter);
739        table.setName(name);
740        table.getTableHeader().setReorderingAllowed(true);
741        table.setColumnModel(new XTableColumnModel());
742        table.createDefaultColumnsFromModel();
743        addMouseListenerToHeader(table);
744        table.getTableHeader().setDefaultRenderer(new BeanTableTooltipHeaderRenderer(table.getTableHeader().getDefaultRenderer()));
745        return table;
746    }
747
748    /**
749     * Get String of the Single Bean Type.
750     * In many cases the return is Bundle localised
751     * so should not be used for matching Bean types.
752     *
753     * @return Bean Type String.
754     */
755    protected String getBeanType(){
756        return getManager().getBeanTypeHandled(false);
757    }
758
759    /**
760     * Updates the visibility settings of the property columns.
761     *
762     * @param table   the JTable object for the current display.
763     * @param visible true to make the property columns visible, false to hide.
764     */
765    public void setPropertyColumnsVisible(JTable table, boolean visible) {
766        XTableColumnModel columnModel = (XTableColumnModel) table.getColumnModel();
767        for (int i = getColumnCount() - 1; i >= getColumnCount() - getPropertyColumnCount(); --i) {
768            TableColumn column = columnModel.getColumnByModelIndex(i);
769            columnModel.setColumnVisible(column, visible);
770        }
771    }
772
773    /**
774     * Is a bean allowed to have the user name cleared?
775     * @return true if clear is allowed, false otherwise
776     */
777    protected boolean isClearUserNameAllowed() {
778        return true;
779    }
780
781    /**
782     * Display popup menu when right clicked on table cell.
783     * <p>
784     * Copy UserName
785     * Rename
786     * Remove UserName
787     * Move
788     * Edit Comment
789     * Delete
790     * @param e source event.
791     */
792    protected void showPopup(JmriMouseEvent e) {
793        JTable source = (JTable) e.getSource();
794        int row = source.rowAtPoint(e.getPoint());
795        int column = source.columnAtPoint(e.getPoint());
796        if (!source.isRowSelected(row)) {
797            source.changeSelection(row, column, false, false);
798        }
799        final int rowindex = source.convertRowIndexToModel(row);
800
801        JPopupMenu popupMenu = new JPopupMenu();
802        JMenuItem menuItem = new JMenuItem(Bundle.getMessage("CopyName"));
803        menuItem.addActionListener((ActionEvent e1) -> copyName(rowindex, 0));
804        popupMenu.add(menuItem);
805
806        menuItem = new JMenuItem(Bundle.getMessage("Rename"));
807        menuItem.addActionListener((ActionEvent e1) -> renameBean(rowindex, 0));
808        popupMenu.add(menuItem);
809
810        if (isClearUserNameAllowed()) {
811            menuItem = new JMenuItem(Bundle.getMessage("ClearName"));
812            menuItem.addActionListener((ActionEvent e1) -> removeName(rowindex, 0));
813            popupMenu.add(menuItem);
814        }
815
816        menuItem = new JMenuItem(Bundle.getMessage("MoveName"));
817        menuItem.addActionListener((ActionEvent e1) -> moveBean(rowindex, 0));
818        if (getRowCount() == 1) {
819            menuItem.setEnabled(false); // you can't move when there is just 1 item (to other table?
820        }
821        popupMenu.add(menuItem);
822
823        menuItem = new JMenuItem(Bundle.getMessage("EditComment"));
824        menuItem.addActionListener((ActionEvent e1) -> editComment(rowindex, 0));
825        popupMenu.add(menuItem);
826
827        menuItem = new JMenuItem(Bundle.getMessage("ButtonDelete"));
828        menuItem.addActionListener((ActionEvent e1) -> deleteBean(rowindex, 0));
829        popupMenu.add(menuItem);
830
831        popupMenu.show(e.getComponent(), e.getX(), e.getY());
832    }
833
834    public void copyName(int row, int column) {
835        T nBean = getBySystemName(sysNameList.get(row));
836        Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
837        StringSelection name = new StringSelection(nBean.getUserName());
838        clipboard.setContents(name, null);
839    }
840
841    /**
842     * Change the bean User Name in a dialog.
843     *
844     * @param row table model row number of bean
845     * @param column always passed in as 0, not used
846     */
847    public void renameBean(int row, int column) {
848        T nBean = getBySystemName(sysNameList.get(row));
849        String oldName = (nBean.getUserName() == null ? "" : nBean.getUserName());
850        String newName = JmriJOptionPane.showInputDialog(null,
851                Bundle.getMessage("RenameFrom", getBeanType(), "\"" +oldName+"\""), oldName);
852        if (newName == null || newName.equals(nBean.getUserName())) {
853            // name not changed
854            return;
855        } else {
856            T nB = getByUserName(newName);
857            if (nB != null) {
858                log.error("User name is not unique {}", newName);
859                String msg = Bundle.getMessage("WarningUserName", "" + newName);
860                JmriJOptionPane.showMessageDialog(null, msg,
861                        Bundle.getMessage("WarningTitle"),
862                        JmriJOptionPane.ERROR_MESSAGE);
863                return;
864            }
865        }
866
867        if (!allowBlockNameChange("Rename", nBean, newName)) {
868            return;  // NOI18N
869        }
870
871        try {
872            nBean.setUserName(newName);
873        } catch (NamedBean.BadSystemNameException | NamedBean.BadUserNameException ex) {
874            JmriJOptionPane.showMessageDialog(null, ex.getLocalizedMessage(),
875                    Bundle.getMessage("ErrorTitle"), // NOI18N
876                    JmriJOptionPane.ERROR_MESSAGE);
877            return;
878        }
879
880        fireTableRowsUpdated(row, row);
881        if (!newName.isEmpty()) {
882            if (oldName == null || oldName.isEmpty()) {
883                if (!nbMan.inUse(sysNameList.get(row), nBean)) {
884                    return;
885                }
886                String msg = Bundle.getMessage("UpdateToUserName", getBeanType(), newName, sysNameList.get(row));
887                int optionPane = JmriJOptionPane.showConfirmDialog(null,
888                        msg, Bundle.getMessage("UpdateToUserNameTitle"),
889                        JmriJOptionPane.YES_NO_OPTION);
890                if (optionPane == JmriJOptionPane.YES_OPTION) {
891                    //This will update the bean reference from the systemName to the userName
892                    try {
893                        nbMan.updateBeanFromSystemToUser(nBean);
894                    } catch (JmriException ex) {
895                        //We should never get an exception here as we already check that the username is not valid
896                        log.error("Impossible exception renaming Bean", ex);
897                    }
898                }
899            } else {
900                nbMan.renameBean(oldName, newName, nBean);
901            }
902
903        } else {
904            //This will update the bean reference from the old userName to the SystemName
905            nbMan.updateBeanFromUserToSystem(nBean);
906        }
907    }
908
909    public void removeName(int row, int column) {
910        T nBean = getBySystemName(sysNameList.get(row));
911        if (!allowBlockNameChange("Remove", nBean, "")) return;  // NOI18N
912        String msg = Bundle.getMessage("UpdateToSystemName", getBeanType());
913        int optionPane = JmriJOptionPane.showConfirmDialog(null,
914                msg, Bundle.getMessage("UpdateToSystemNameTitle"),
915                JmriJOptionPane.YES_NO_OPTION);
916        if (optionPane == JmriJOptionPane.YES_OPTION) {
917            nbMan.updateBeanFromUserToSystem(nBean);
918        }
919        nBean.setUserName(null);
920        fireTableRowsUpdated(row, row);
921    }
922
923    /**
924     * Determine whether it is safe to rename/remove a Block user name.
925     * <p>The user name is used by the LayoutBlock to link to the block and
926     * by Layout Editor track components to link to the layout block.
927     *
928     * @param changeType This will be Remove or Rename.
929     * @param bean The affected bean.  Only the Block bean is of interest.
930     * @param newName For Remove this will be empty, for Rename it will be the new user name.
931     * @return true to continue with the user name change.
932     */
933    boolean allowBlockNameChange(String changeType, T bean, String newName) {
934        if (!(bean instanceof jmri.Block)) {
935            return true;
936        }
937        // If there is no layout block or the block name is empty, Block rename and remove are ok without notification.
938        String oldName = bean.getUserName();
939        if (oldName == null) return true;
940        LayoutBlock layoutBlock = jmri.InstanceManager.getDefault(LayoutBlockManager.class).getByUserName(oldName);
941        if (layoutBlock == null) return true;
942
943        // Remove is not allowed if there is a layout block
944        if (changeType.equals("Remove")) {
945            log.warn("Cannot remove user name for block {}", oldName);  // NOI18N
946                JmriJOptionPane.showMessageDialog(null,
947                        Bundle.getMessage("BlockRemoveUserNameWarning", oldName),  // NOI18N
948                        Bundle.getMessage("WarningTitle"),  // NOI18N
949                        JmriJOptionPane.WARNING_MESSAGE);
950            return false;
951        }
952
953        // Confirmation dialog
954        int optionPane = JmriJOptionPane.showConfirmDialog(null,
955                Bundle.getMessage("BlockChangeUserName", oldName, newName),  // NOI18N
956                Bundle.getMessage("QuestionTitle"),  // NOI18N
957                JmriJOptionPane.YES_NO_OPTION);
958        return optionPane == JmriJOptionPane.YES_OPTION;
959    }
960
961    public void moveBean(int row, int column) {
962        final T t = getBySystemName(sysNameList.get(row));
963        String currentName = t.getUserName();
964        T oldNameBean = getBySystemName(sysNameList.get(row));
965
966        if ((currentName == null) || currentName.isEmpty()) {
967            JmriJOptionPane.showMessageDialog(null, Bundle.getMessage("MoveDialogErrorMessage"));
968            return;
969        }
970
971        JComboBox<String> box = new JComboBox<>();
972        getManager().getNamedBeanSet().forEach((T b) -> {
973            //Only add items that do not have a username assigned.
974            String userName = b.getUserName();
975            if (userName == null || userName.isEmpty()) {
976                box.addItem(b.getSystemName());
977            }
978        });
979
980        int retval = JmriJOptionPane.showOptionDialog(null,
981                Bundle.getMessage("MoveDialog", getBeanType(), currentName, oldNameBean.getSystemName()),
982                Bundle.getMessage("MoveDialogTitle"),
983                JmriJOptionPane.YES_NO_OPTION, JmriJOptionPane.INFORMATION_MESSAGE, null,
984                new Object[]{Bundle.getMessage("ButtonCancel"), Bundle.getMessage("ButtonOK"), box}, null);
985        log.debug("Dialog value {} selected {}:{}", retval, box.getSelectedIndex(), box.getSelectedItem());
986        if (retval != 1) {
987            return;
988        }
989        String entry = (String) box.getSelectedItem();
990        assert entry != null;
991        T newNameBean = getBySystemName(entry);
992        if (oldNameBean != newNameBean) {
993            oldNameBean.setUserName(null);
994            newNameBean.setUserName(currentName);
995            InstanceManager.getDefault(NamedBeanHandleManager.class).moveBean(oldNameBean, newNameBean, currentName);
996            if (nbMan.inUse(newNameBean.getSystemName(), newNameBean)) {
997                String msg = Bundle.getMessage("UpdateToUserName", getBeanType(), currentName, sysNameList.get(row));
998                int optionPane = JmriJOptionPane.showConfirmDialog(null, msg, Bundle.getMessage("UpdateToUserNameTitle"), JmriJOptionPane.YES_NO_OPTION);
999                if (optionPane == JmriJOptionPane.YES_OPTION) {
1000                    try {
1001                        nbMan.updateBeanFromSystemToUser(newNameBean);
1002                    } catch (JmriException ex) {
1003                        //We should never get an exception here as we already check that the username is not valid
1004                        log.error("Impossible exception moving Bean", ex);
1005                    }
1006                }
1007            }
1008            fireTableRowsUpdated(row, row);
1009            InstanceManager.getDefault(UserPreferencesManager.class).
1010                    showInfoMessage(Bundle.getMessage("ReminderTitle"),
1011                            Bundle.getMessage("UpdateComplete", getBeanType()),
1012                            getMasterClassName(), "remindSaveReLoad");
1013        }
1014    }
1015
1016    public void editComment(int row, int column) {
1017        T nBean = getBySystemName(sysNameList.get(row));
1018        JTextArea commentField = new JTextArea(5, 50);
1019        JScrollPane commentFieldScroller = new JScrollPane(commentField);
1020        commentField.setText(nBean.getComment());
1021        Object[] editCommentOption = {Bundle.getMessage("ButtonCancel"), Bundle.getMessage("ButtonUpdate")};
1022        int retval = JmriJOptionPane.showOptionDialog(null,
1023                commentFieldScroller, Bundle.getMessage("EditComment"),
1024                JmriJOptionPane.YES_NO_OPTION, JmriJOptionPane.INFORMATION_MESSAGE, null,
1025                editCommentOption, editCommentOption[1]);
1026        if (retval != 1) {
1027            return;
1028        }
1029        nBean.setComment(commentField.getText());
1030   }
1031
1032    /**
1033     * Display the comment text for the current row as a tool tip.
1034     *
1035     * Most of the bean tables use the standard model with comments in column 3.
1036     *
1037     * @param table The current table.
1038     * @param row The current row.
1039     * @param col The current column.
1040     * @return a formatted tool tip or null if there is none.
1041     */
1042    public String getCellToolTip(JTable table, int row, int col) {
1043        String tip = null;
1044        int column = COMMENTCOL;
1045        if (table.getName().contains("SignalGroup")) column = 2;
1046        if (col == column) {
1047            T nBean = getBySystemName(sysNameList.get(row));
1048            if (nBean != null) {
1049                tip = formatToolTip(nBean.getComment());
1050            }
1051        }
1052        return tip;
1053    }
1054
1055    /**
1056     * Get a ToolTip for a Table Column Header.
1057     * @param columnModelIndex the model column number.
1058     * @return ToolTip, else null.
1059     */
1060    @OverridingMethodsMustInvokeSuper
1061    protected String getHeaderTooltip(int columnModelIndex) {
1062        return null;
1063    }
1064
1065    /**
1066     * Format a comment field as a tool tip string. Multi line comments are supported.
1067     * @param comment The comment string.
1068     * @return a html formatted string or null if the comment is empty.
1069     */
1070    protected String formatToolTip(String comment) {
1071        String tip = null;
1072        if (comment != null && !comment.isEmpty()) {
1073            tip = "<html>" + comment.replaceAll(System.getProperty("line.separator"), "<br>") + "</html>";
1074        }
1075        return tip;
1076    }
1077
1078    /**
1079     * Show the Table Column Menu.
1080     * @param e Instigating event ( e.g. from Mouse click )
1081     * @param table table to get columns from
1082     */
1083    protected void showTableHeaderPopup(JmriMouseEvent e, JTable table) {
1084        JPopupMenu popupMenu = new JPopupMenu();
1085        XTableColumnModel tcm = (XTableColumnModel) table.getColumnModel();
1086        for (int i = 0; i < tcm.getColumnCount(false); i++) {
1087            TableColumn tc = tcm.getColumnByModelIndex(i);
1088            String columnName = table.getModel().getColumnName(i);
1089            if (columnName != null && !columnName.isEmpty()) {
1090                StayOpenCheckBoxItem menuItem = new StayOpenCheckBoxItem(table.getModel().getColumnName(i), tcm.isColumnVisible(tc));
1091                menuItem.addActionListener(new HeaderActionListener(tc, tcm));
1092                TableModel mod = table.getModel();
1093                if (mod instanceof BeanTableDataModel<?>) {
1094                    menuItem.setToolTipText(((BeanTableDataModel<?>)mod).getHeaderTooltip(i));
1095                }
1096                popupMenu.add(menuItem);
1097            }
1098
1099        }
1100        popupMenu.show(e.getComponent(), e.getX(), e.getY());
1101    }
1102
1103    protected void addMouseListenerToHeader(JTable table) {
1104        JmriMouseListener mouseHeaderListener = new TableHeaderListener(table);
1105        table.getTableHeader().addMouseListener(JmriMouseListener.adapt(mouseHeaderListener));
1106    }
1107
1108    /**
1109     * Persist the state of the table after first setting the table to the last
1110     * persisted state.
1111     *
1112     * @param table the table to persist
1113     * @throws NullPointerException if the name of the table is null
1114     */
1115    public void persistTable(@Nonnull JTable table) throws NullPointerException {
1116        InstanceManager.getOptionalDefault(JTablePersistenceManager.class).ifPresent((manager) -> {
1117            setColumnIdentities(table);
1118            manager.resetState(table); // throws NPE if table name is null
1119            manager.persist(table);
1120        });
1121    }
1122
1123    /**
1124     * Stop persisting the state of the table.
1125     *
1126     * @param table the table to stop persisting
1127     * @throws NullPointerException if the name of the table is null
1128     */
1129    public void stopPersistingTable(@Nonnull JTable table) throws NullPointerException {
1130        InstanceManager.getOptionalDefault(JTablePersistenceManager.class).ifPresent((manager) -> {
1131            manager.stopPersisting(table); // throws NPE if table name is null
1132        });
1133    }
1134
1135    /**
1136     * Set identities for any columns that need an identity.
1137     *
1138     * It is recommended that all columns get a constant identity to
1139     * prevent identities from being subject to changes due to translation.
1140     * <p>
1141     * The default implementation sets column identities to the String
1142     * {@code Column#} where {@code #} is the model index for the column.
1143     * Note that if the TableColumnModel is a {@link jmri.util.swing.XTableColumnModel},
1144     * the index includes hidden columns.
1145     *
1146     * @param table the table to set identities for.
1147     */
1148    protected void setColumnIdentities(JTable table) {
1149        Objects.requireNonNull(table.getModel(), "Table must have data model");
1150        Objects.requireNonNull(table.getColumnModel(), "Table must have column model");
1151        Enumeration<TableColumn> columns;
1152        if (table.getColumnModel() instanceof XTableColumnModel) {
1153            columns = ((XTableColumnModel) table.getColumnModel()).getColumns(false);
1154        } else {
1155            columns = table.getColumnModel().getColumns();
1156        }
1157        int i = 0;
1158        while (columns.hasMoreElements()) {
1159            TableColumn column = columns.nextElement();
1160            if (column.getIdentifier() == null || column.getIdentifier().toString().isEmpty()) {
1161                column.setIdentifier(String.format("Column%d", i));
1162            }
1163            i += 1;
1164        }
1165    }
1166
1167    protected class BeanTableTooltipHeaderRenderer extends DefaultTableCellRenderer  {
1168        private final TableCellRenderer _existingRenderer;
1169
1170        protected BeanTableTooltipHeaderRenderer(TableCellRenderer existingRenderer) {
1171            _existingRenderer = existingRenderer;
1172        }
1173
1174        @Override
1175        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
1176            
1177            Component rendererComponent = _existingRenderer.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
1178            TableModel mod = table.getModel();
1179            if ( rendererComponent instanceof JLabel && mod instanceof BeanTableDataModel<?> ) { // Set the cell ToolTip
1180                int modelIndex = table.getColumnModel().getColumn(column).getModelIndex();
1181                String tooltip = ((BeanTableDataModel<?>)mod).getHeaderTooltip(modelIndex);
1182                ((JLabel)rendererComponent).setToolTipText(tooltip);
1183            }
1184            return rendererComponent;
1185        }
1186    }
1187
1188    /**
1189     * Listener class which processes Column Menu button clicks.
1190     * Does not allow the last column to be hidden,
1191     * otherwise there would be no table header to recover the column menu / columns from.
1192     */
1193    static class HeaderActionListener implements ActionListener {
1194
1195        private final TableColumn tc;
1196        private final XTableColumnModel tcm;
1197
1198        HeaderActionListener(TableColumn tc, XTableColumnModel tcm) {
1199            this.tc = tc;
1200            this.tcm = tcm;
1201        }
1202
1203        @Override
1204        public void actionPerformed(ActionEvent e) {
1205            JCheckBoxMenuItem check = (JCheckBoxMenuItem) e.getSource();
1206            //Do not allow the last column to be hidden
1207            if (!check.isSelected() && tcm.getColumnCount(true) == 1) {
1208                return;
1209            }
1210            tcm.setColumnVisible(tc, check.isSelected());
1211        }
1212    }
1213
1214    class DeleteBeanWorker  {
1215
1216        public DeleteBeanWorker(final T bean) {
1217
1218            StringBuilder message = new StringBuilder();
1219            try {
1220                getManager().deleteBean(bean, "CanDelete");  // NOI18N
1221            } catch (PropertyVetoException e) {
1222                if (e.getPropertyChangeEvent().getPropertyName().equals("DoNotDelete")) { // NOI18N
1223                    log.warn("Should not delete {}, {}", bean.getDisplayName((DisplayOptions.USERNAME_SYSTEMNAME)), e.getMessage());
1224                    message.append(Bundle.getMessage("VetoDeleteBean", bean.getBeanType(), bean.getDisplayName(DisplayOptions.USERNAME_SYSTEMNAME), e.getMessage()));
1225                    JmriJOptionPane.showMessageDialog(null, message.toString(),
1226                            Bundle.getMessage("WarningTitle"),
1227                            JmriJOptionPane.ERROR_MESSAGE);
1228                    return;
1229                }
1230                message.append(e.getMessage());
1231            }
1232            int count = bean.getListenerRefs().size();
1233            log.debug("Delete with {}", count);
1234            if (getDisplayDeleteMsg() == 0x02 && message.toString().isEmpty()) {
1235                doDelete(bean);
1236            } else {
1237                JPanel container = new JPanel();
1238                container.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
1239                container.setLayout(new BoxLayout(container, BoxLayout.Y_AXIS));
1240                if (count > 0) { // warn of listeners attached before delete
1241
1242                    JLabel question = new JLabel(Bundle.getMessage("DeletePrompt", bean.getDisplayName(DisplayOptions.USERNAME_SYSTEMNAME)));
1243                    question.setAlignmentX(Component.CENTER_ALIGNMENT);
1244                    container.add(question);
1245
1246                    ArrayList<String> listenerRefs = bean.getListenerRefs();
1247                    if (!listenerRefs.isEmpty()) {
1248                        ArrayList<String> listeners = new ArrayList<>();
1249                        for (String listenerRef : listenerRefs) {
1250                            if (!listeners.contains(listenerRef)) {
1251                                listeners.add(listenerRef);
1252                            }
1253                        }
1254
1255                        message.append("<br>");
1256                        message.append(Bundle.getMessage("ReminderInUse", count));
1257                        message.append("<ul>");
1258                        for (String listener : listeners) {
1259                            message.append("<li>");
1260                            message.append(listener);
1261                            message.append("</li>");
1262                        }
1263                        message.append("</ul>");
1264
1265                        JEditorPane pane = new JEditorPane();
1266                        pane.setContentType("text/html");
1267                        pane.setText("<html>" + message.toString() + "</html>");
1268                        pane.setEditable(false);
1269                        JScrollPane jScrollPane = new JScrollPane(pane);
1270                        container.add(jScrollPane);
1271                    }
1272                } else {
1273                    String msg = MessageFormat.format(
1274                            Bundle.getMessage("DeletePrompt"), bean.getSystemName());
1275                    JLabel question = new JLabel(msg);
1276                    question.setAlignmentX(Component.CENTER_ALIGNMENT);
1277                    container.add(question);
1278                }
1279
1280                final JCheckBox remember = new JCheckBox(Bundle.getMessage("MessageRememberSetting"));
1281                remember.setFont(remember.getFont().deriveFont(10f));
1282                remember.setAlignmentX(Component.CENTER_ALIGNMENT);
1283
1284                container.add(remember);
1285                container.setAlignmentX(Component.CENTER_ALIGNMENT);
1286                container.setAlignmentY(Component.CENTER_ALIGNMENT);
1287                String[] options = new String[]{JmriJOptionPane.YES_STRING, JmriJOptionPane.NO_STRING};
1288                int result = JmriJOptionPane.showOptionDialog(null, container, Bundle.getMessage("WarningTitle"), 
1289                    JmriJOptionPane.DEFAULT_OPTION, JmriJOptionPane.WARNING_MESSAGE, null, 
1290                    options, JmriJOptionPane.NO_STRING);
1291
1292                if ( result == 0 ){ // first item in Array is Yes
1293                    if (remember.isSelected()) {
1294                        setDisplayDeleteMsg(0x02);
1295                    }
1296                    doDelete(bean);
1297                }
1298
1299            }
1300        }
1301    }
1302
1303    /**
1304     * Listener to trigger display of table cell menu.
1305     * Delete / Rename / Move etc.
1306     */
1307    class PopupListener extends JmriMouseAdapter {
1308
1309        /**
1310         * {@inheritDoc}
1311         */
1312        @Override
1313        public void mousePressed(JmriMouseEvent e) {
1314            if (e.isPopupTrigger()) {
1315                showPopup(e);
1316            }
1317        }
1318
1319        /**
1320         * {@inheritDoc}
1321         */
1322        @Override
1323        public void mouseReleased(JmriMouseEvent e) {
1324            if (e.isPopupTrigger()) {
1325                showPopup(e);
1326            }
1327        }
1328    }
1329
1330    /**
1331     * Listener to trigger display of table header column menu.
1332     */
1333    class TableHeaderListener extends JmriMouseAdapter {
1334
1335        private final JTable table;
1336
1337        TableHeaderListener(JTable tbl) {
1338            super();
1339            table = tbl;
1340        }
1341
1342        /**
1343         * {@inheritDoc}
1344         */
1345        @Override
1346        public void mousePressed(JmriMouseEvent e) {
1347            if (e.isPopupTrigger()) {
1348                showTableHeaderPopup(e, table);
1349            }
1350        }
1351
1352        /**
1353         * {@inheritDoc}
1354         */
1355        @Override
1356        public void mouseReleased(JmriMouseEvent e) {
1357            if (e.isPopupTrigger()) {
1358                showTableHeaderPopup(e, table);
1359            }
1360        }
1361
1362        /**
1363         * {@inheritDoc}
1364         */
1365        @Override
1366        public void mouseClicked(JmriMouseEvent e) {
1367            if (e.isPopupTrigger()) {
1368                showTableHeaderPopup(e, table);
1369            }
1370        }
1371    }
1372
1373    private class BtComboboxEditor extends jmri.jmrit.symbolicprog.ValueEditor {
1374
1375        BtComboboxEditor(){
1376            super();
1377        }
1378
1379        @Override
1380        public Component getTableCellEditorComponent(JTable table, Object value,
1381            boolean isSelected,
1382            int row, int column) {
1383            if (value instanceof JComboBox) {
1384                ((JComboBox<?>) value).addActionListener((ActionEvent e1) -> table.getCellEditor().stopCellEditing());
1385            }
1386
1387            if (value instanceof JComponent ) {
1388
1389                int modelcol =  table.convertColumnIndexToModel(column);
1390                int modelrow = table.convertRowIndexToModel(row);
1391
1392                // if cell is not editable, jcombobox not applicable for hardware type
1393                boolean editable = table.getModel().isCellEditable(modelrow, modelcol);
1394
1395                ((JComponent) value).setEnabled(editable);
1396
1397            }
1398
1399            return super.getTableCellEditorComponent(table, value, isSelected, row, column);
1400        }
1401
1402
1403    }
1404
1405    private class BtValueRenderer implements TableCellRenderer {
1406
1407        BtValueRenderer() {
1408            super();
1409        }
1410
1411        @Override
1412        public Component getTableCellRendererComponent(JTable table, Object value,
1413            boolean isSelected, boolean hasFocus, int row, int column) {
1414
1415            if (value instanceof Component) {
1416                return (Component) value;
1417            } else if (value instanceof String) {
1418                return new JLabel((String) value);
1419            } else {
1420                JPanel f = new JPanel();
1421                f.setBackground(isSelected ? table.getSelectionBackground() : table.getBackground() );
1422                return f;
1423            }
1424        }
1425    }
1426
1427    /**
1428     * Set the filter to select which beans to include in the table.
1429     * @param filter the filter
1430     */
1431    public synchronized void setFilter(Predicate<? super T> filter) {
1432        this.filter = filter;
1433        updateNameList();
1434    }
1435
1436    /**
1437     * Get the filter to select which beans to include in the table.
1438     * @return the filter
1439     */
1440    public synchronized Predicate<? super T> getFilter() {
1441        return filter;
1442    }
1443
1444    static class DateRenderer extends DefaultTableCellRenderer {
1445
1446        private final DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM);
1447
1448        @Override
1449        public Component getTableCellRendererComponent( JTable table, Object value,
1450            boolean isSelected, boolean hasFocus, int row, int column) {
1451            JLabel c = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
1452            if ( value instanceof Date) {
1453                c.setText(dateFormat.format(value));
1454            }
1455            return c;
1456        }
1457    }
1458
1459    private final static org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(BeanTableDataModel.class);
1460
1461}