-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWorkListController.java
More file actions
890 lines (763 loc) · 28.7 KB
/
WorkListController.java
File metadata and controls
890 lines (763 loc) · 28.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
package com.enventek.plant.worklist.newlist;
import com.enventek.plant.components.ButtonPopup;
import com.enventek.plant.components.MainComponent;
import com.enventek.plant.components.MsgBox;
import com.enventek.plant.datasource.DataSource;
import com.enventek.plant.datasource.DataSourceChangeListenerWeb;
import com.enventek.plant.datasource.FileObject;
import com.enventek.plant.datasource.file.FileBaseDataSource;
import com.enventek.plant.datasource.file.objects.FSItem;
import com.enventek.plant.hibernate.objects.Batch;
import com.enventek.plant.hibernate.objects.Board;
import com.enventek.plant.hibernate.objects.Cutting;
import com.enventek.plant.hibernate.objects.Truss;
import com.enventek.plant.utils.ErrorHandler;
import com.enventek.plant.utils.Globals;
import com.enventek.plant.utils.Item;
import com.enventek.plant.utils.configuration.AppConfig;
import com.enventek.plant.utils.savedState.FileMetadataManager;
import com.enventek.plant.utils.savedState.SavedStateUtils;
import com.enventek.plant.worklist.DataSourceTableModel;
import com.enventek.plant.worklist.WorkListSearch;
import com.enventek.plant.worklist.WorkListUtils;
import com.enventek.plant.worklist.WorkOrderUtils;
import com.enventek.plant.worklist.newlist.NewWorkList.StateProviderListener;
import org.apache.commons.configuration2.HierarchicalConfiguration;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import java.awt.*;
import java.awt.event.*;
import java.util.List;
import javax.swing.Timer;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
@SuppressWarnings("unchecked")
public class WorkListController implements DataSourceChangeListenerWeb {
static final Logger logger = LogManager.getLogger(WorkListController.class);
private final WorkListUI ui;
final WorkListState state;
private final WorkListUtilities utils;
private WorkListBackupManager wlBackupManager;
private WorkOrderController woController;
private List<DataSource> allDataSources = new ArrayList<>();
private DataSource currentDataSource;
private final List<WorkListBehaviorListener> workListBehaviorlisteners = new ArrayList<>();
private StateProviderListener stateProviderListener;
final MainComponent main = MainComponent.getInstance();
private HierarchicalConfiguration settings;
private WorkOrderUtils workOrderUtils; // optional
public static String fileName;
public static boolean configHidden = false;
private Timer delayTimer;
private static WorkListUtils workListUtils;
private DefaultListModel unfilteredList;
private int selectedIndexForSimple = 0;
private final AtomicInteger programmaticSelectDepth = new AtomicInteger(0);
// NEW: navigation stack (history of list models)
private final Deque<DefaultListModel> history = new ArrayDeque<>();
private final ExecutorService refreshPool = Executors.newSingleThreadExecutor(r -> {
Thread t = new Thread(r, "WorkList-Refresh");
t.setDaemon(true);
return t;
});
public WorkListController(WorkListUI ui, WorkListState state, WorkListUtilities utils) {
this.ui = ui;
this.state = state;
this.utils = utils;
}
public List<DataSource> getAllDataSources() {
return allDataSources;
}
// Add this method to create the backup manager
public void setWorkListBackupManager(WorkListBackupManager backupManager) {
this.wlBackupManager = backupManager;
}
// ============ Lifecycle ============
public void init() {
// selection model that blocks while process is running
ui.itemList.setSelectionModel(new DefaultListSelectionModel() {
@Override
public void setSelectionInterval(int i0, int i1) {
if (!state.isProcessInProgress())
super.setSelectionInterval(i0, i1);
}
@Override
public void addSelectionInterval(int i0, int i1) {
if (!state.isProcessInProgress())
super.addSelectionInterval(i0, i1);
}
});
// delayed re-enable (touchscreen)
delayTimer = new Timer(100, e -> {
delayTimer.stop();
ui.itemList.setEnabled(true);
});
delayTimer.setRepeats(false);
// selection listener (main brain)
// component resize trick to invalidate cell sizes (like old)
ui.itemList.addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
ui.itemList.setFixedCellHeight(10);
ui.itemList.setFixedCellHeight(-1);
}
});
// top/back button
ui.backButton.addActionListener(evt -> {
// NEW: if we have history, go back. Otherwise keep old Search
// behavior.
if (canGoBack()) {
goBack();
ui.getMainPanel().firePropertyChange("backToBatch", true, false);
return;
}
if ("Search".equals(ui.backButton.getText())) {
search();
}
DataSource ds = getDataSource();
if (ds != null) {
clearHistory(); // back to top level view
DefaultListModel model = ds.getModel(null);
ui.itemList.setModel(model);
}
ui.backButton.setText("Search");
ui.backButton.setIcon(ui.searchIcon);
ui.getMainPanel().firePropertyChange("backToBatch", true, false);
});
// config button
ui.configButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent evt) {
if (state.isProcessInProgress()) {
evt.consume();
return;
}
if (ui.configPanel.isVisible()) {
if (workOrderUtils != null && !workOrderUtils.checkAndHandleActiveWorkStream()) {
refresh();
}
DataSourceTableModel model = (DataSourceTableModel) ui.configPanel.tableData.getModel();
int row = ui.configPanel.tableData.getSelectedRow();
model.setDefaultIndex(row);
settings.setProperty("dataSource.defaultIdx", row);
AppConfig.save(settings, fileName);
notifyDataSourceChanged();
if (workOrderUtils != null && workOrderUtils.getWorkOrder() != null) {
workOrderUtils.getWorkOrder().refresh();
}
Map<String, Object> extra = new HashMap<>();
extra.put("eventType", "datasourceChange");
DataSource ds = getDataSource();
extra.put("dataSourceName", ds != null ? ds.getName() : "null");
// workListUtils.sendUpdateToWeb("Datasource changed",
// extra);
hideConfigPanel();
} else
showConfigPanel();
updateRefreshButtonState();
}
});
// refresh button
ui.refreshButton.addActionListener(e -> refresh());
// done button toggle
ui.doneButton.addActionListener(e -> {
DataSource ds = getDataSource();
if (ds == null)
return;
if (ui.doneButton.getModel().isSelected())
refreshDone();
else
refresh();
});
}
// ============ Setup ============
public void setup(HierarchicalConfiguration cfg, String postfix) throws Exception {
this.settings = cfg;
// workListUtils = new WorkListUtilsProxy(this).delegate(); // (proxy
// keeps references tidy)
ui.configPanel.setTableData(settings);
selectDefaultDataSource();
if (getDataSource() != null) {
logger.debug("datasource: {}", getDataSource().getName());
}
refresh();
// Setup work order if enabled
setupWorkOrderIfEnabled();
if (ui.itemList.getVisibleRowCount() == 0) {
ui.topText.setText("Select a Datasource");
} else if (SavedStateUtils.isInitialized() && !"-1".equals(SavedStateUtils.getJobName())
&& workOrderUtils != null && workOrderUtils.hasWorkStreamSaved()) {
if (state.isSavedStateActive()) {
refresh();
workOrderUtils.loadWorkStreamSaved();
}
} else if (SavedStateUtils.isInitialized() && !"-1".equals(SavedStateUtils.getJobName())
&& !state.hasWorkStreamSaved()) {
wlBackupManager.loadWorkListSavedAsync();
}
}
private void setupWorkOrderIfEnabled() throws Exception {
// If Workorder is enabled on the worklist.
if (settings.getBoolean("workOrder", true) && SavedStateUtils.isInitialized()
&& FileMetadataManager.isInitialized()) {
// Initialize WorkOrderUtils and WorkOrderController
this.woController = new WorkOrderController(ui, state, workOrderUtils);
// Get the icon and setup the button
ImageIcon workOrderIcon = workOrderUtils.getIcon();
ui.setupWorkOrderButton(workOrderIcon);
// Add action listener to the work order button
ui.getWorkOrderButton().addActionListener(e -> {
workOrderUtils.WorkOrderButtonAction();
});
// Initialize the work order controller
}
}
public WorkOrderController getWorkOrderController() {
return woController;
}
// Helper to pick default datasource
private void selectDefaultDataSource() {
DataSource ds = getDataSource();
if (ds != null) {
int idx = DataSource.getDefaultIdx(settings);
if ((idx >= ui.configPanel.tableData.getRowCount()) || idx < 0) {
ui.configPanel.setSelectedDataSourceIdx(0);
} else {
ui.configPanel.setSelectedDataSourceIdx(idx);
}
}
}
// ============ Public API ============
public DataSource getDataSource() {
DataSource ds = ui.configPanel.getDataSource();
if (ds != null && ds.workList == null) {
ds.workList = null;
}
return ds;
}
public void refresh() {
if (!state.refreshInProgress.compareAndSet(false, true))
return;
final long t0 = System.currentTimeMillis();
state.setDoneList(false);
ui.doneButton.getModel().setSelected(false);
clearHistory(); // NEW: start fresh
final DataSource current = getDataSource();
if (current == null) {
state.refreshInProgress.set(false);
return;
}
refreshPool.submit(() -> {
try {
long a0 = System.nanoTime();
current.refresh();
DefaultListModel model = current.getModel(null);
long a1 = System.nanoTime();
SwingUtilities.invokeLater(() -> {
try {
// === Set model and restore custom renderer ===
ui.itemList.setModel(model);
ui.itemList.setFixedCellHeight(-1);
ui.itemList.setCellRenderer(ui.renderer); // critical
// for
// proper
// rendering
ui.itemList.revalidate();
ui.itemList.repaint();
// === Select first item if needed ===
if (model != null && model.getSize() > 0) {
Object first = model.getElementAt(0);
if (first != null && "Default Job".equals(String.valueOf(first))) {
ui.itemList.setSelectedIndex(0);
} else if (state.isSimple()) {
ui.itemList.setSelectedIndex(0);
}
}
// === Visual/layout controls ===
if (!state.isSimple()) {
hideConfigPanel();
ui.backButton.setText("Search");
ui.backButton.setIcon(ui.searchIcon);
ui.configButton.setIcon(current.getConfigIcon());
ui.doneButton.setVisible(true);
ui.doneButton.setEnabled(true);
}
ui.doneButton.setVisible(current.isCompletable());
logger.debug("Refresh took {}ms (build={}ms)", (System.currentTimeMillis() - t0),
Math.round((a1 - a0) / 1e6));
} finally {
if (SavedStateUtils.isInitialized() && FileMetadataManager.isInitialized()) {
FileMetadataManager.scanDataSourceFilesAsyncDebounced(current, 250);
}
state.refreshInProgress.set(false);
}
});
} catch (Throwable t) {
try {
ErrorHandler.HandleError(t, "WorkList refresh failed", true);
} finally {
state.refreshInProgress.set(false);
}
}
});
}
public synchronized void refreshDone() {
DataSource current = getDataSource();
if (current == null)
return;
if (current instanceof FileBaseDataSource) {
if (!ensureDoneFolderExistsForCurrentSource((FileBaseDataSource) current))
return;
}
clearHistory(); // NEW: viewing "Done" resets navigation
current.refreshCompleted();
DefaultListModel model = current.getModel(null);
ui.itemList.setModel(model);
state.setDoneList(true);
ui.doneButton.setSelected(true);
}
public boolean loadNextItem(Object currentJob) {
logger.debug("load next item");
DataSource dataSource = getDataSource();
if (dataSource == null)
return false;
refresh(); // see new files
DefaultListModel<Item> model = dataSource.getModel(null);
for (int i = 0; i < model.size(); i++) {
if (utils.jobNameCompare(String.valueOf(model.get(i)), String.valueOf(currentJob))) {
ui.itemList.setSelectedIndex(Math.min(i + 1, model.size() - 1));
break;
}
}
return true;
}
public boolean loadItem(String dataSouceName, String jobName, String itemName) {
logger.debug("Entering loadItem2 Loading: {} - {}", jobName, itemName);
if (jobName != null)
jobName = jobName.trim();
if (itemName != null)
itemName = itemName.trim();
List<DataSource> datasources = ui.configPanel.getAllDataSource();
if (dataSouceName == null)
dataSouceName = datasources.get(0).getName();
dataSouceName = dataSouceName.trim();
for (int i = 0; i < datasources.size(); i++) {
DataSource dS = datasources.get(i);
if (dS.getName().trim().equalsIgnoreCase(dataSouceName)) {
ui.configPanel.setSelectedDataSourceIdx(i);
clearHistory(); // NEW: explicit navigation replaces stack
DefaultListModel model = dS.getModel(null);
ui.itemList.setModel(model);
boolean found = loadItemFromDataSource(ui.itemList, dS, jobName, itemName);
if (!found) {
logger.debug("first search unsuccessful; refreshing datasource");
refresh();
return loadItemFromDataSource(ui.itemList, dS, jobName, itemName);
}
return true;
}
}
logger.debug("datasource or item not found. Jobname:{} itemName:{}", jobName, itemName);
return false;
}
public void loadItem(String dataSouceName, String jobName, int itemOffset) {
logger.debug("entering loadItem (offset)");
if (jobName != null)
jobName = jobName.trim();
if (dataSouceName != null)
dataSouceName = dataSouceName.trim();
List<DataSource> dataSources = ui.configPanel.getAllDataSource();
for (int i = 0; i < dataSources.size(); i++) {
DataSource dS = dataSources.get(i);
if (dS.getName().trim().equalsIgnoreCase(dataSouceName)) {
if (i != ui.configPanel.getSelectedDataSourceIdx()) {
ui.configPanel.setSelectedDataSourceIdx(i);
refresh();
}
DefaultListModel model = (DefaultListModel) ui.itemList.getModel();
for (int j = 0; j < model.getSize(); j++) {
Object job = model.getElementAt(j);
if (utils.jobNameCompare(job.toString(), jobName)) {
if (itemOffset == -1) {
ui.itemList.setSelectedIndex(j);
return;
}
// dS.getModel(job) already returns a ListModel<Item>
DefaultListModel lm = dS.getModel(job);
if (lm != null) {
// NEW: entering sublist uses stack
enterFolder(lm);
if (itemOffset < lm.getSize()) {
ui.itemList.setSelectedIndex(itemOffset);
logger.debug("Item found and loaded");
return;
} else {
logger.debug("Offset incorrect: {} / {}", itemOffset, lm.getSize());
}
}
}
}
}
}
logger.debug("datasource or item not found");
}
// ============ Filtering/Search ============
private JDialog searchDialog;
WorkListSearch wls;
public void enableSearch() {
ui.manualButton.setVisible(true);
ui.manualButton.setIcon(ui.searchIcon);
ui.manualButton.setText("Search");
ui.manualButton.addActionListener(e -> search());
}
public void search() {
unfilteredList = null;
Frame frm = (Frame) SwingUtilities.getWindowAncestor(ui.getMainPanel());
if (wls == null)
wls = new WorkListSearch(main, null);
wls.setSize((int) ((frm.getWidth() - ui.getMainPanel().getWidth() * 1.1)), (int) (frm.getHeight() * 0.6));
Point loc = wls.getLocation();
wls.setLocation(loc.x - (frm.getWidth() - wls.getWidth()) / 2 + 10, loc.y);
wls.setVisible(true);
loc = wls.getLocation();
wls.setLocation(loc.x - (frm.getWidth() - wls.getWidth()) / 2 + 10, loc.y);
main.displayAlert("", wls, wls.getSize(), false, new Point(0, 0));
}
public void setFilterString(String filter) {
filter = filter.toLowerCase(Locale.ROOT);
if (filter.length() == 0 && unfilteredList != null) {
ui.itemList.setModel(unfilteredList);
unfilteredList = null;
return;
}
if (unfilteredList == null)
unfilteredList = (DefaultListModel) ui.itemList.getModel();
DefaultListModel filtered = new DefaultListModel<>();
for (int i = 0; i < unfilteredList.getSize(); i++) {
String info = String.valueOf(unfilteredList.getElementAt(i)).toLowerCase(Locale.ROOT);
if (info.contains(filter))
filtered.addElement(unfilteredList.getElementAt(i));
}
ui.itemList.setModel(filtered);
}
// ============ UI helpers ============
public void setSimpleWorkList(boolean issimple) {
state.setSimple(issimple);
if (issimple) {
ui.buttonPanel.setVisible(false);
ui.topPanel.setVisible(false);
ui.configButton.setVisible(false);
ui.getMainPanel().add(ui.scrollPane, "0,1,1,6");
} else {
ui.buttonPanel.setVisible(true);
ui.topPanel.setVisible(true);
ui.configButton.setVisible(true);
ui.getMainPanel().add(ui.scrollPane, "0,3,1,4");
}
}
private void showConfigPanel() {
logger.info("showConfigPanel");
ui.configPanel.setVisible(true);
ui.topPanel.setVisible(false);
ui.scrollPane.setVisible(false);
ui.buttonPanel.setVisible(false);
configHidden = false;
ui.getMainPanel().revalidate();
}
private void hideConfigPanel() {
logger.info("hideConfigPanel");
ui.configPanel.setVisible(false);
ui.topPanel.setVisible(true);
ui.scrollPane.setVisible(true);
ui.buttonPanel.setVisible(true);
configHidden = true;
ui.getMainPanel().revalidate();
}
public void updateRefreshButtonState() {
ui.refreshButton.setEnabled(!isWorkOrderStreamActive());
}
public void setIgnoreAdjusting(boolean ignoreAdjusting) {
state.setIgnoreAdjusting(ignoreAdjusting);
}
// ============ Swipe popup ============
public void handleSwipePopup() {
final DataSource current = getDataSource();
if (current == null)
return;
ArrayList<Item> optionList = current.getSwipeItems(state.isDoneList(), ui.itemList.getSelectedValue());
if (optionList.isEmpty()
|| (optionList.size() == 1 && "Cancel".equals(String.valueOf(optionList.get(0).getValue()))))
return;
final MouseMotionListener[] saved = ui.itemList.getMouseMotionListeners();
for (MouseMotionListener l : saved)
ui.itemList.removeMouseMotionListener(l);
ui.itemList.setEnabled(false);
boolean disableDelete = isWorkOrderStreamActive() && workOrderUtils.hasWorkStreamSaved();
if (disableDelete)
optionList.removeIf(it -> "Delete".equalsIgnoreCase(String.valueOf(it.getValue())));
ButtonPopup bp = new ButtonPopup(
"<html><h3><center>" + ui.itemList.getSelectedValue().toString() + "</center></h3></html>", optionList,
false);
final AWTEventListener[] holder = new AWTEventListener[1];
AWTEventListener outsideClick = new AWTEventListener() {
@Override
public void eventDispatched(AWTEvent event) {
if (!(event instanceof MouseEvent me) || me.getID() != MouseEvent.MOUSE_PRESSED)
return;
Object src = me.getSource();
if (src instanceof Component clicked) {
if (!SwingUtilities.isDescendingFrom(clicked, ui.getMainPanel())
&& !SwingUtilities.isDescendingFrom(clicked, bp)) {
bp.forceClose();
Toolkit.getDefaultToolkit().removeAWTEventListener(holder[0]);
}
}
}
};
holder[0] = outsideClick;
Toolkit.getDefaultToolkit().addAWTEventListener(outsideClick, AWTEvent.MOUSE_EVENT_MASK);
bp.addPopupMenuListener(new PopupMenuListener() {
@Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
Toolkit.getDefaultToolkit().removeAWTEventListener(outsideClick);
for (MouseMotionListener l : saved)
ui.itemList.addMouseMotionListener(l);
ui.itemList.setEnabled(true);
try {
ui.itemList.setSelectedIndex(Globals.selectedDrag);
if (ui.itemList.getModel().getSize() == 0 || bp.choosenValue == null)
return;
int selectedIndex = ui.itemList.getSelectedIndex();
boolean refreshList = current.handleSwipe(state.isDoneList(), String.valueOf(bp.choosenValue),
ui.itemList.getSelectedValue(), isWorkOrderStreamActive(),
workOrderUtils != null && workOrderUtils.hasWorkStreamSaved(), selectedIndex);
if (refreshList) {
Item objItem = (Item) ui.itemList.getSelectedValue();
if (objItem.getValue() instanceof FSItem || objItem.getValue() instanceof Cutting
|| objItem.getValue() instanceof Batch) {
DefaultListModel<Item> modelC = current.getModel(null);
modelC.removeElementAt(Globals.selectedDrag);
}
}
if (Globals.DELETE_ITEM) {
DefaultListModel model = (DefaultListModel) ui.itemList.getModel();
model.removeElementAt(Globals.selectedDrag);
}
} catch (Exception ex) {
ErrorHandler.HandleError(ex, "handle swipe exception");
} finally {
bp.choosenValue = null;
ui.itemList.repaint();
}
}
@Override
public void popupMenuCanceled(PopupMenuEvent e) {
Toolkit.getDefaultToolkit().removeAWTEventListener(outsideClick);
}
@Override
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
Globals.selectedDrag = ui.itemList.getSelectedIndex();
}
});
int popSize = (int) (ui.getMainPanel().getWidth() * 0.7);
bp.setPopupSize(popSize, popSize);
bp.setOpaque(false);
bp.setBackground(new Color(30, 30, 30, 200));
bp.show(ui.getMainPanel(), (ui.getMainPanel().getWidth() - popSize) / 2,
(ui.getMainPanel().getHeight() - popSize) / 2);
bp.setVisible(true);
}
// ============ Internals ============
private boolean ensureDoneFolderExistsForCurrentSource(FileBaseDataSource fileDs) {
List<String> allowed = Arrays.asList("File", "SMBJ", "JCIFS");
boolean match = fileDs.getConnectionTypes().stream()
.anyMatch(type -> allowed.stream().anyMatch(allowedType -> allowedType.equalsIgnoreCase(type)));
if (!match)
return true;
String path = fileDs.getRootCompletedDirectory().getPath();
if (!fileDs.getRootCompletedDirectory().isExisting()) {
String response = MsgBox.askQuestion(
"The Done folder does not exist:\n\n" + path + "\n\nWould you like to create it now?", "Yes,No");
if ("Yes".equals(response)) {
try {
fileDs.getRootCompletedDirectory().createEmpty(true);
logger.info("Created done folder: {}", path);
int index = ui.configPanel.getSelectedDataSourceIdx();
String prefix = "dataSource.source(" + index + ")";
settings.setProperty(prefix + ".donePath", path);
AppConfig.save(settings, fileName);
return true;
} catch (Exception e) {
MsgBox.displayError("Failed to create the Done folder:\n" + e.getMessage(), "Error");
logger.error("Failed to create done folder: {}", e.getMessage(), e);
return false;
}
} else {
MsgBox.displayError("Done folder does not exist.", "Done Folder Missing");
return false;
}
}
return true;
}
private boolean loadItemFromDataSource(JList itemlist, DataSource dataSource, String jobName, String itemName) {
ListModel model = itemlist.getModel();
for (int j = 0; j < model.getSize(); j++) {
Item job = (Item) model.getElementAt(j);
if (utils.jobNameCompare(job.toString(), jobName)) {
Object og = dataSource.getModel(job);
if (og instanceof ListModel) {
ListModel lm = (ListModel) og;
itemlist.setModel(lm);
for (int k = 0; k < lm.getSize(); k++) {
Item trussItem = (Item) lm.getElementAt(k);
Object value = trussItem.getValue();
if (itemName == null) {
// load first item always
ui.itemList.setSelectedIndex(0);
logger.debug("First item selected");
} else if (value instanceof Truss) {
Truss t = (Truss) value;
if (c4SoftwareNameCompare(t.getName().trim(), itemName)
|| t.getName().trim().equalsIgnoreCase(itemName)
|| t.tpsName.trim().equalsIgnoreCase(itemName)
|| t.getName().trim().equalsIgnoreCase(itemName + "#")) {
ui.itemList.setSelectedIndex(k);
logger.debug("Item found and loaded");
return true;
}
} else {
if (trussItem.toString().trim().equalsIgnoreCase(itemName)) {
ui.itemList.setSelectedIndex(k);
logger.debug("Item found and loaded");
return true;
}
}
}
}
}
}
return false;
}
private static boolean c4SoftwareNameCompare(String parsedName, String slString) {
parsedName = parsedName.replace("*", "");
slString = slString.replace("*", "");
String testName = parsedName.replace("\"", "''");
boolean pass = testName.equalsIgnoreCase(slString);
pass = pass | (parsedName.replace("'", "-")).equalsIgnoreCase(slString);
pass = pass | (parsedName.replace("'", "-").replace("\"", "-")).equalsIgnoreCase(slString);
pass = pass | (parsedName.replace(" ", "")).equalsIgnoreCase(slString.replace(" ", ""));
return pass;
}
// -------- Navigation helpers (NEW) --------
void enterFolder(DefaultListModel newModel) {
// Push current model
DefaultListModel current = (DefaultListModel) ui.itemList.getModel();
if (current != null)
history.push(current);
// Swap model
ui.itemList.setModel(newModel);
// UI affordances
ui.backButton.setText("Back");
ui.backButton.setIcon(ui.backIcon);
}
boolean canGoBack() {
return !history.isEmpty();
}
private void goBack() {
if (!history.isEmpty()) {
ui.itemList.setModel(history.pop());
}
if (history.isEmpty()) {
ui.backButton.setText("Search");
ui.backButton.setIcon(ui.searchIcon);
} else {
ui.backButton.setText("Back");
ui.backButton.setIcon(ui.backIcon);
}
}
private void clearHistory() {
history.clear();
ui.backButton.setText("Search");
ui.backButton.setIcon(ui.searchIcon);
}
void finalizeBackHeader(String nameHtml) {
// Keep the back button consistent when in a sublist.
if (canGoBack()) {
ui.backButton.setText("Back");
ui.backButton.setIcon(ui.backIcon);
}
ui.backButton.setText(nameHtml);
}
// Small proxy to reuse your existing WorkListUtils with this controller
private static class WorkListUtilsProxy {
private final WorkListController ctl;
WorkListUtilsProxy(WorkListController ctl) {
this.ctl = ctl;
}
WorkListUtils delegate() {
return new WorkListUtils(new WorkListFacade(ctl));
}
// Minimal facade exposing what WorkListUtils expects from WorkList
static class WorkListFacade extends com.enventek.plant.worklist.WorkList {
private final WorkListController ctl;
WorkListFacade(WorkListController ctl) {
this.ctl = ctl;
}
@Override
public DataSource getDataSource() {
return ctl.getDataSource();
}
@Override
public void triggerItemUpdateFromSelection() {
Object sel = ctl.ui.itemList.getSelectedValue();
if (sel != null)
ctl.workListUtils.sendItemUpdate(sel);
}
}
}
// DataSourceChangeListenerWeb
@Override
public void onWebDataSourceChanged(HierarchicalConfiguration updatedSettings, DataSource ds) throws Exception {
logger.info("DataSource has changed from Web");
ui.changeDataSource(updatedSettings);
}
public void addWorkListBehaviorListener(WorkListBehaviorListener listener) {
workListBehaviorlisteners.add(listener);
}
public void removeWorkListBehaviorListener(WorkListBehaviorListener listener) {
workListBehaviorlisteners.remove(listener);
}
void notifyDataSourceChanged() {
for (WorkListBehaviorListener listener : workListBehaviorlisteners) {
try {
listener.onWorkListDataSourceChanged();
} catch (Exception e) {
e.printStackTrace(); // Or log it properly
}
}
}
private boolean isWorkOrderStreamActive() {
return workOrderUtils != null && workOrderUtils.isActiveWorkStream();
}
void notifySelectionListeners(Object selected) {
for (WorkListBehaviorListener l : workListBehaviorlisteners)
l.onWorkListSelectionChanged(selected);
}
public Timer getDelayTimer() {
return delayTimer;
}
public DefaultListModel getUnfilteredList() {
return unfilteredList;
}
public void setUnfilteredList(DefaultListModel model) {
this.unfilteredList = model;
}
}