001package jmri.jmrit.roster.swing;
002
003import com.fasterxml.jackson.databind.util.StdDateFormat;
004
005import java.awt.Component;
006import java.awt.Rectangle;
007import java.awt.event.ActionEvent;
008import java.awt.event.ActionListener;
009import java.awt.event.MouseEvent;
010import java.text.DateFormat;
011import java.text.SimpleDateFormat;
012import java.text.ParseException;
013import java.util.ArrayList;
014import java.util.Arrays;
015import java.util.Date;
016import java.util.Enumeration;
017import java.util.List;
018
019import javax.swing.BoxLayout;
020import javax.swing.DefaultCellEditor;
021import javax.swing.JCheckBoxMenuItem;
022import javax.swing.JPopupMenu;
023import javax.swing.JScrollPane;
024import javax.swing.JTable;
025import javax.swing.JTextField;
026import javax.swing.ListSelectionModel;
027import javax.swing.RowSorter;
028import javax.swing.SortOrder;
029import javax.swing.border.Border;
030import javax.swing.event.ListSelectionEvent;
031import javax.swing.event.ListSelectionListener;
032import javax.swing.event.RowSorterEvent;
033import javax.swing.table.DefaultTableCellRenderer;
034import javax.swing.table.TableColumn;
035import javax.swing.table.TableRowSorter;
036
037import jmri.InstanceManager;
038import jmri.jmrit.roster.Roster;
039import jmri.jmrit.roster.RosterEntry;
040import jmri.jmrit.roster.RosterEntrySelector;
041import jmri.jmrit.roster.rostergroup.RosterGroupSelector;
042import jmri.util.gui.GuiLafPreferencesManager;
043import jmri.util.swing.JmriPanel;
044import jmri.util.swing.JmriMouseAdapter;
045import jmri.util.swing.JmriMouseEvent;
046import jmri.util.swing.JmriMouseListener;
047import jmri.util.swing.XTableColumnModel;
048
049/**
050 * Provide a table of roster entries as a JmriJPanel.
051 *
052 * @author Bob Jacobsen Copyright (C) 2003, 2010
053 * @author Randall Wood Copyright (C) 2013
054 */
055public class RosterTable extends JmriPanel implements RosterEntrySelector, RosterGroupSelector {
056
057    private RosterTableModel dataModel;
058    private TableRowSorter<RosterTableModel> sorter;
059    private JTable dataTable;
060    private JScrollPane dataScroll;
061    private final XTableColumnModel columnModel = new XTableColumnModel();
062    private RosterGroupSelector rosterGroupSource = null;
063    protected transient ListSelectionListener tableSelectionListener;
064    private RosterEntry[] selectedRosterEntries = null;
065    private RosterEntry[] sortedRosterEntries = null;
066    private RosterEntry re = null;
067
068    public RosterTable() {
069        this(false);
070    }
071
072    public RosterTable(boolean editable) {
073        // set to single selection
074        this(editable, ListSelectionModel.SINGLE_SELECTION);
075    }
076
077    public RosterTable(boolean editable, int selectionMode) {
078        super();
079        dataModel = new RosterTableModel(editable);
080        sorter = new TableRowSorter<>(dataModel);
081        sorter.addRowSorterListener(rowSorterEvent -> {
082            if (rowSorterEvent.getType() ==  RowSorterEvent.Type.SORTED) {
083                // clear sorted cache
084                sortedRosterEntries = null;
085            }
086        });
087        dataTable = new JTable(dataModel);
088        dataTable.setRowSorter(sorter);
089        dataScroll = new JScrollPane(dataTable);
090        dataTable.setRowHeight(InstanceManager.getDefault(GuiLafPreferencesManager.class).getFontSize() + 4);
091
092        sorter.setComparator(RosterTableModel.IDCOL, new jmri.util.AlphanumComparator());
093
094        // set initial sort
095        List<RowSorter.SortKey> sortKeys = new ArrayList<>();
096        sortKeys.add(new RowSorter.SortKey(RosterTableModel.ADDRESSCOL, SortOrder.ASCENDING));
097        sorter.setSortKeys(sortKeys);
098
099        // allow reordering of the columns
100        dataTable.getTableHeader().setReorderingAllowed(true);
101
102        // have to shut off autoResizeMode to get horizontal scroll to work (JavaSwing p 541)
103        dataTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
104
105        dataTable.setColumnModel(columnModel);
106        dataTable.createDefaultColumnsFromModel();
107        dataTable.setAutoCreateColumnsFromModel(false);
108
109        // format the last updated date time, last operated date time.
110        dataTable.setDefaultRenderer(Date.class, new DateTimeCellRenderer());
111
112        TableColumn tc = columnModel.getColumnByModelIndex(RosterTableModel.PROTOCOL);
113        columnModel.setColumnVisible(tc, false);
114
115        // if the total time operated column exists, set it to DurationRenderer
116        var columns = columnModel.getColumns();
117        while (columns.hasMoreElements()) {
118            TableColumn column = columns.nextElement();
119            if ( Bundle.getMessage(RosterEntry.ATTRIBUTE_OPERATING_DURATION)
120                .equals( column.getHeaderValue().toString())) {
121                column.setCellRenderer( new DurationRenderer() );
122                column.setCellEditor(new DurationCellEditor());
123            }
124        }
125
126        // resize columns as requested
127        resetColumnWidths();
128
129        // general GUI config
130        setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
131
132        // install items in GUI
133        add(dataScroll);
134
135        // set Viewport preferred size from size of table
136        java.awt.Dimension dataTableSize = dataTable.getPreferredSize();
137        // width is right, but if table is empty, it's not high
138        // enough to reserve much space.
139        dataTableSize.height = Math.max(dataTableSize.height, 400);
140        dataTableSize.width = Math.max(dataTableSize.width, 400);
141        dataScroll.getViewport().setPreferredSize(dataTableSize);
142
143        dataTable.setSelectionMode(selectionMode);
144        JmriMouseListener mouseHeaderListener = new TableHeaderListener();
145        dataTable.getTableHeader().addMouseListener(JmriMouseListener.adapt(mouseHeaderListener));
146
147        dataTable.setDefaultEditor(Object.class, new RosterCellEditor());
148        dataTable.setDefaultEditor(Date.class, new DateTimeCellEditor());
149
150        tableSelectionListener = (ListSelectionEvent e) -> {
151            if (!e.getValueIsAdjusting()) {
152                selectedRosterEntries = null; // clear cached list of selections
153                if (dataTable.getSelectedRowCount() == 1) {
154                    re = Roster.getDefault().getEntryForId(dataModel.getValueAt(sorter
155                        .convertRowIndexToModel(dataTable.getSelectedRow()), RosterTableModel.IDCOL).toString());
156                } else if (dataTable.getSelectedRowCount() > 1) {
157                    re = null;
158                } // leave last selected item visible if no selection
159            } else if (e.getFirstIndex() == -1) {
160                // A reorder of the table may have occurred so ensure the selected item is still in view
161                moveTableViewToSelected();
162            }
163        };
164        dataTable.getSelectionModel().addListSelectionListener(tableSelectionListener);
165    }
166
167    public JTable getTable() {
168        return dataTable;
169    }
170
171    public RosterTableModel getModel() {
172        return dataModel;
173    }
174
175    public final void resetColumnWidths() {
176        Enumeration<TableColumn> en = columnModel.getColumns(false);
177        while (en.hasMoreElements()) {
178            TableColumn tc = en.nextElement();
179            int width = dataModel.getPreferredWidth(tc.getModelIndex());
180            tc.setPreferredWidth(width);
181        }
182        dataTable.sizeColumnsToFit(-1);
183    }
184
185    @Override
186    public void dispose() {
187        this.setRosterGroupSource(null);
188        if (dataModel != null) {
189            dataModel.dispose();
190        }
191        dataModel = null;
192        dataTable.getSelectionModel().removeListSelectionListener(tableSelectionListener);
193        dataTable = null;
194        super.dispose();
195    }
196
197    public void setRosterGroup(String rosterGroup) {
198        this.dataModel.setRosterGroup(rosterGroup);
199    }
200
201    public String getRosterGroup() {
202        return this.dataModel.getRosterGroup();
203    }
204
205    /**
206     * @return the rosterGroupSource
207     */
208    public RosterGroupSelector getRosterGroupSource() {
209        return this.rosterGroupSource;
210    }
211
212    /**
213     * @param rosterGroupSource the rosterGroupSource to set
214     */
215    public void setRosterGroupSource(RosterGroupSelector rosterGroupSource) {
216        if (this.rosterGroupSource != null) {
217            this.rosterGroupSource.removePropertyChangeListener(SELECTED_ROSTER_GROUP, dataModel);
218        }
219        this.rosterGroupSource = rosterGroupSource;
220        if (this.rosterGroupSource != null) {
221            this.rosterGroupSource.addPropertyChangeListener(SELECTED_ROSTER_GROUP, dataModel);
222        }
223    }
224
225    protected void showTableHeaderPopup(JmriMouseEvent e) {
226        JPopupMenu popupMenu = new JPopupMenu();
227        for (int i = 0; i < columnModel.getColumnCount(false); i++) {
228            TableColumn tc = columnModel.getColumnByModelIndex(i);
229            JCheckBoxMenuItem menuItem = new JCheckBoxMenuItem(dataTable.getModel()
230                .getColumnName(i), columnModel.isColumnVisible(tc));
231            menuItem.addActionListener(new HeaderActionListener(tc));
232            popupMenu.add(menuItem);
233
234        }
235        popupMenu.show(e.getComponent(), e.getX(), e.getY());
236    }
237
238    protected void moveTableViewToSelected() {
239        if (re == null) {
240            return;
241        }
242        //Remove the listener as this change will re-activate it and we end up in a loop!
243        dataTable.getSelectionModel().removeListSelectionListener(tableSelectionListener);
244        dataTable.clearSelection();
245        int entires = dataTable.getRowCount();
246        for (int i = 0; i < entires; i++) {
247            if (dataModel.getValueAt(sorter.convertRowIndexToModel(i), RosterTableModel.IDCOL).equals(re.getId())) {
248                dataTable.addRowSelectionInterval(i, i);
249                dataTable.scrollRectToVisible(new Rectangle(dataTable.getCellRect(i, 0, true)));
250            }
251        }
252        dataTable.getSelectionModel().addListSelectionListener(tableSelectionListener);
253    }
254
255    @Override
256    public String getSelectedRosterGroup() {
257        return dataModel.getRosterGroup();
258    }
259
260    // cache selectedRosterEntries so that multiple calls to this
261    // between selection changes will not require the creation of a new array
262    @Override
263    public RosterEntry[] getSelectedRosterEntries() {
264        if (selectedRosterEntries == null) {
265            int[] rows = dataTable.getSelectedRows();
266            selectedRosterEntries = new RosterEntry[rows.length];
267            for (int idx = 0; idx < rows.length; idx++) {
268                selectedRosterEntries[idx] = Roster.getDefault().getEntryForId(
269                    dataModel.getValueAt(sorter.convertRowIndexToModel(rows[idx]), RosterTableModel.IDCOL).toString());
270            }
271        }
272        return Arrays.copyOf(selectedRosterEntries, selectedRosterEntries.length);
273    }
274
275    // cache getSortedRosterEntries so that multiple calls to this
276    // between selection changes will not require the creation of a new array
277    public RosterEntry[] getSortedRosterEntries() {
278        if (sortedRosterEntries == null) {
279            sortedRosterEntries = new RosterEntry[sorter.getModelRowCount()];
280            for (int idx = 0; idx < sorter.getModelRowCount(); idx++) {
281                sortedRosterEntries[idx] = Roster.getDefault().getEntryForId(
282                    dataModel.getValueAt(sorter.convertRowIndexToModel(idx), RosterTableModel.IDCOL).toString());
283            }
284        }
285        return Arrays.copyOf(sortedRosterEntries, sortedRosterEntries.length);
286    }
287
288    public void setEditable(boolean editable) {
289        this.dataModel.editable = editable;
290    }
291
292    public boolean getEditable() {
293        return this.dataModel.editable;
294    }
295
296    public void setSelectionMode(int selectionMode) {
297        dataTable.setSelectionMode(selectionMode);
298    }
299
300    public int getSelectionMode() {
301        return dataTable.getSelectionModel().getSelectionMode();
302    }
303
304    public boolean setSelection(RosterEntry... selection) {
305        //Remove the listener as this change will re-activate it and we end up in a loop!
306        dataTable.getSelectionModel().removeListSelectionListener(tableSelectionListener);
307        dataTable.clearSelection();
308        boolean foundIt = false;
309        if (selection != null) {
310            for (RosterEntry entry : selection) {
311                re = entry;
312                int entries = dataTable.getRowCount();
313                for (int i = 0; i < entries; i++) {
314                    if (dataModel.getValueAt(sorter
315                        .convertRowIndexToModel(i), RosterTableModel.IDCOL).equals(re.getId())) {
316                        dataTable.addRowSelectionInterval(i, i);
317                        foundIt = true;
318                    }
319                }
320            }
321            if (selection.length > 1 || !foundIt) {
322                re = null;
323            } else {
324                this.moveTableViewToSelected();
325            }
326        } else {
327            re = null;
328        }
329        dataTable.getSelectionModel().addListSelectionListener(tableSelectionListener);
330        return foundIt;
331    }
332
333    private class HeaderActionListener implements ActionListener {
334
335        TableColumn tc;
336
337        HeaderActionListener(TableColumn tc) {
338            this.tc = tc;
339        }
340
341        @Override
342        public void actionPerformed(ActionEvent e) {
343            JCheckBoxMenuItem check = (JCheckBoxMenuItem) e.getSource();
344            //Do not allow the last column to be hidden
345            if (!check.isSelected() && columnModel.getColumnCount(true) == 1) {
346                return;
347            }
348            columnModel.setColumnVisible(tc, check.isSelected());
349        }
350    }
351
352    private class TableHeaderListener extends JmriMouseAdapter {
353
354        @Override
355        public void mousePressed(JmriMouseEvent e) {
356            if (e.isPopupTrigger()) {
357                showTableHeaderPopup(e);
358            }
359        }
360
361        @Override
362        public void mouseReleased(JmriMouseEvent e) {
363            if (e.isPopupTrigger()) {
364                showTableHeaderPopup(e);
365            }
366        }
367
368        @Override
369        public void mouseClicked(JmriMouseEvent e) {
370            if (e.isPopupTrigger()) {
371                showTableHeaderPopup(e);
372            }
373        }
374    }
375
376    public class RosterCellEditor extends DefaultCellEditor {
377
378        public RosterCellEditor() {
379            super(new JTextField() {
380
381                @Override
382                public void setBorder(Border border) {
383                    //No border required
384                }
385            });
386        }
387
388        //This allows the cell to be edited using a single click if the row was previously selected, this allows a double on an unselected row to launch the programmer
389        @Override
390        public boolean isCellEditable(java.util.EventObject e) {
391            if (re == null) {
392                //No previous roster entry selected so will take this as a select so no return false to prevent editing
393                return false;
394            }
395
396            if (e instanceof MouseEvent) {
397                MouseEvent me = (MouseEvent) e;
398                //If the click count is not equal to 1 then return false.
399                if (me.getClickCount() != 1) {
400                    return false;
401                }
402            }
403            return re.getId().equals(dataModel.getValueAt(sorter.convertRowIndexToModel(dataTable.getSelectedRow()), RosterTableModel.IDCOL));
404        }
405    }
406
407    private static class DurationRenderer extends DefaultTableCellRenderer {
408
409        @Override
410        public void setValue(Object value) {
411            try {
412                int duration = Integer.parseInt(value.toString());
413                if ( duration != 0 ) {
414                    super.setValue(jmri.util.DateUtil.userDurationFromSeconds(duration));
415                    super.setToolTipText(Bundle.getMessage("DurationViewTip"));
416                    return;
417                }
418            }
419            catch (NumberFormatException e) {
420                log.debug("could not format duration ( String integer of total seconds ) in {}", value, e);
421            }
422            super.setValue(null);
423        }
424    }
425
426    private static class DateTimeCellRenderer extends DefaultTableCellRenderer {
427        @Override
428        protected void setValue(Object value) {
429            if ( value instanceof Date) {
430                super.setValue(DateFormat.getDateTimeInstance().format((Date) value));
431            } else {
432                super.setValue(value);
433            }
434        }
435    }
436
437    private class DateTimeCellEditor extends RosterCellEditor {
438
439        DateTimeCellEditor() {
440            super();
441        }
442
443        private static final String EDITOR_DATE_FORMAT =  "yyyy-MM-dd hh:mm";
444        private Date startDate = new Date();
445
446        @Override
447        public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int col) {
448            if (!(value instanceof Date) ) {
449                value = new Date(); // field pre-populated if currently empty to show entry format
450            }
451            startDate = (Date)value;
452            String formatted = new SimpleDateFormat(EDITOR_DATE_FORMAT).format((Date)value);
453            ((JTextField)editorComponent).setText(formatted);
454            editorComponent.setToolTipText("e.g. 2022-12-25 12:34");
455            return editorComponent;
456        }
457
458        @Override
459        public Object getCellEditorValue() {
460            String o = (String)super.getCellEditorValue();
461            if ( o.isBlank() ) { // user cancels the date / time
462                return null;
463            }
464            SimpleDateFormat fm = new SimpleDateFormat(EDITOR_DATE_FORMAT);
465            try {
466                // get Date in local time before passing to StdDateFormat
467                startDate = fm.parse(o.trim());
468            } catch (ParseException e) {
469            } // return value unchanged in case of user mis-type
470            return new StdDateFormat().format(startDate);
471        }
472
473    }
474
475    private class DurationCellEditor extends RosterCellEditor {
476
477        @Override
478        public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int col) {
479            editorComponent.setToolTipText(Bundle.getMessage("DurationEditTip"));
480            return editorComponent;
481        }
482
483        @Override
484        public Object getCellEditorValue() {
485            return String.valueOf(super.getCellEditorValue());
486        }
487
488    }
489
490    private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(RosterTable.class);
491
492}