Repository navigation
Expand file tree
/
Copy pathGraphController.java
More file actions
3010 lines (2498 loc) · 122 KB
/
Copy pathGraphController.java
File metadata and controls
3010 lines (2498 loc) · 122 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
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package com.simulator;
import javafx.animation.*;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Line;
import javafx.scene.text.Text;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javafx.util.Duration;
import javafx.scene.layout.VBox;
import java.io.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
public class GraphController {
// ==================== FXML COMPONENTS ====================
@FXML private TextField addVertexField, searchVertexField;
@FXML private TextField sourceField, destinationField, weightField;
@FXML private TextField startVertexField, endVertexField;
@FXML private ComboBox<String> algorithmComboBox;
@FXML private CheckBox directedCheckBox, weightedCheckBox, showLabelsCheckBox, showWeightsCheckBox;
// Buttons
@FXML private Button addVertexButton, removeVertexButton, searchButton, highlightButton;
@FXML private Button addEdgeButton, removeEdgeButton;
@FXML private Button traverseButton, clearButton, randomButton;
@FXML private Button undoButton, redoButton, saveButton, loadButton;
@FXML private Button zoomInButton, zoomOutButton, resetZoomButton;
@FXML private Button circularLayoutButton, forceLayoutButton, resetLayoutButton;
// Display components
@FXML private Pane graphCanvas;
@FXML private ScrollPane canvasScrollPane;
@FXML private Label statusLabel, vertexCountLabel, edgeCountLabel, densityLabel;
@FXML private TextArea resultArea, operationHistory, algorithmCodeViewer;
@FXML private ProgressBar operationProgress;
// ==================== PRIVATE FIELDS ====================
private GraphModel graphModel;
private Map<Integer, VertexElement> vertexElements;
private List<EdgeElement> edgeElements;
private AnimationService animationService;
private Timeline currentAnimation;
// State management
private boolean isTraversing = false;
private boolean isDragging = false;
private double zoomLevel = 1.0;
private final double MIN_ZOOM = 0.3;
private final double MAX_ZOOM = 3.0;
// Undo/Redo system
private Stack<GraphState> undoStack;
private Stack<GraphState> redoStack;
// ==================== ENHANCED DRAG AND DROP FIELDS ====================
// Enhanced drag and drop with double-click detection
private VertexElement draggedVertex = null;
private double dragStartX, dragStartY;
// Double-click detection system
private long lastClickTime = 0;
private VertexElement lastClickedVertex = null;
private final long DOUBLE_CLICK_THRESHOLD = 500; // milliseconds
private final long HOLD_THRESHOLD = 200; // milliseconds for hold detection
// Enhanced drag states
private boolean isEnhancedDragging = false; // Double-click drag mode
private boolean isDragHoldActive = false;
private Timeline dragHoldTimer = null;
// Visual feedback for dragging
private Timeline dragFeedbackAnimation = null;
private String originalVertexStyle = "";
// Canvas boundaries for drag constraints
private final double BOUNDARY_PADDING = 50.0;
// ==================== INITIALIZATION ====================
@FXML
public void initialize() {
System.out.println("Enhanced GraphController initialized");
graphModel = new GraphModel(false); // Start with undirected
vertexElements = new HashMap<>();
edgeElements = new ArrayList<>();
animationService = AnimationService.getInstance();
undoStack = new Stack<>();
redoStack = new Stack<>();
setupComponents();
setupEventHandlers();
setupDragAndDrop();
// **FIX: Ensure canvas is properly sized and visible**
Platform.runLater(() -> {
setupCanvasSize();
// addTestVisualization(); // Debug visualization
updateDisplay();
updateAlgorithmCode();
});
System.out.println("Enhanced Graph module ready with advanced features");
// Add keyboard shortcut for copy (Ctrl+C)
if (algorithmCodeViewer != null) {
algorithmCodeViewer.setOnKeyPressed(event -> {
if (event.isControlDown() && event.getCode() == javafx.scene.input.KeyCode.C) {
copyCodeToClipboard();
event.consume();
}
});
}
}
private void setupCanvasSize() {
if (graphCanvas != null) {
// Set explicit sizes for reliable rendering
graphCanvas.setMinSize(800, 600);
graphCanvas.setPrefSize(800, 600);
graphCanvas.setMaxSize(Double.MAX_VALUE, Double.MAX_VALUE);
System.out.println("Canvas size set: " + graphCanvas.getPrefWidth() + "x" + graphCanvas.getPrefHeight());
}
if (canvasScrollPane != null) {
canvasScrollPane.setFitToWidth(false);
canvasScrollPane.setFitToHeight(false);
canvasScrollPane.setPannable(true);
}
}
private void addTestVisualization() {
// **DEBUG: Add test circle to verify canvas works**
Circle testCircle = new Circle(100, 100, 15);
testCircle.setFill(Color.RED);
testCircle.setStroke(Color.BLACK);
testCircle.setStrokeWidth(2);
Text testLabel = new Text(90, 105, "TEST");
testLabel.setFill(Color.WHITE);
testLabel.setStyle("-fx-font-weight: bold;");
graphCanvas.getChildren().addAll(testCircle, testLabel);
System.out.println("Test visualization added - Canvas children count: " + graphCanvas.getChildren().size());
}
private void setupComponents() {
// Enhanced algorithm selection
algorithmComboBox.setItems(FXCollections.observableArrayList(
"BFS (Breadth-First Search)",
"DFS (Depth-First Search)",
"Shortest Path",
"Dijkstra's Algorithm",
"A* Pathfinding",
"Topological Sort",
"Find All Paths",
"Detect Cycles"
));
algorithmComboBox.setValue("BFS (Breadth-First Search)");
// Input validation
setupInputValidation();
// Canvas scroll and zoom
if (canvasScrollPane != null) {
canvasScrollPane.setPannable(true);
canvasScrollPane.setOnScroll(event -> {
if (event.isControlDown()) {
double zoomFactor = event.getDeltaY() > 0 ? 1.1 : 0.9;
adjustZoom(zoomFactor);
event.consume();
}
});
}
// Setup text areas
if (operationHistory != null) {
operationHistory.setText("=== Enhanced Graph Operations History ===\n");
operationHistory.setEditable(false);
}
if (resultArea != null) {
resultArea.setEditable(false);
}
if (algorithmCodeViewer != null) {
algorithmCodeViewer.setStyle("-fx-font-family: 'Courier New', monospace; -fx-font-size: 12px;");
algorithmCodeViewer.setEditable(false);
}
}
private void setupInputValidation() {
// Vertex ID validation (integers only)
addVertexField.textProperty().addListener((obs, oldText, newText) -> {
if (!newText.matches("\\d*")) {
addVertexField.setText(newText.replaceAll("[^\\d]", ""));
}
});
searchVertexField.textProperty().addListener((obs, oldText, newText) -> {
if (!newText.matches("\\d*")) {
searchVertexField.setText(newText.replaceAll("[^\\d]", ""));
}
});
// Edge fields validation
sourceField.textProperty().addListener((obs, oldText, newText) -> {
if (!newText.matches("\\d*")) {
sourceField.setText(newText.replaceAll("[^\\d]", ""));
}
});
destinationField.textProperty().addListener((obs, oldText, newText) -> {
if (!newText.matches("\\d*")) {
destinationField.setText(newText.replaceAll("[^\\d]", ""));
}
});
// Weight validation (decimal numbers)
weightField.textProperty().addListener((obs, oldText, newText) -> {
if (!newText.matches("\\d*\\.?\\d*")) {
weightField.setText(oldText);
}
});
// Traversal fields validation
startVertexField.textProperty().addListener((obs, oldText, newText) -> {
if (!newText.matches("\\d*")) {
startVertexField.setText(newText.replaceAll("[^\\d]", ""));
}
});
endVertexField.textProperty().addListener((obs, oldText, newText) -> {
if (!newText.matches("\\d*")) {
endVertexField.setText(newText.replaceAll("[^\\d]", ""));
}
});
}
private void setupEventHandlers() {
// Enter key handling for quick operations
addVertexField.setOnAction(e -> addVertex());
sourceField.setOnAction(e -> addEdge());
destinationField.setOnAction(e -> addEdge());
startVertexField.setOnAction(e -> performTraversal());
searchVertexField.setOnAction(e -> searchVertex());
// Checkbox handlers
directedCheckBox.setOnAction(e -> toggleGraphType());
weightedCheckBox.setOnAction(e -> toggleWeightSupport());
showLabelsCheckBox.setOnAction(e -> toggleLabelsVisibility());
showWeightsCheckBox.setOnAction(e -> toggleWeightsVisibility());
// Algorithm selection handler
algorithmComboBox.setOnAction(e -> updateAlgorithmCode());
}
/**
* Enhanced drag and drop setup with double-click detection and real-time edge updates
*/
private void setupDragAndDrop() {
// Clear any existing handlers
graphCanvas.setOnMousePressed(null);
graphCanvas.setOnMouseDragged(null);
graphCanvas.setOnMouseReleased(null);
// Set up enhanced mouse handlers
graphCanvas.setOnMousePressed(this::handleEnhancedMousePressed);
graphCanvas.setOnMouseDragged(this::handleEnhancedMouseDragged);
graphCanvas.setOnMouseReleased(this::handleEnhancedMouseReleased);
System.out.println("✅ Enhanced drag and drop system initialized");
}
/**
* Enhanced mouse pressed handler with double-click detection
*/
private void handleEnhancedMousePressed(MouseEvent event) {
if (isTraversing) return;
long currentTime = System.currentTimeMillis();
VertexElement clickedVertex = findVertexAtPosition(event.getX(), event.getY());
if (clickedVertex != null) {
// Check for double-click
boolean isDoubleClick = (currentTime - lastClickTime) < DOUBLE_CLICK_THRESHOLD
&& clickedVertex == lastClickedVertex;
if (isDoubleClick) {
// Start enhanced drag mode
startEnhancedDrag(clickedVertex, event);
logOperation("ENHANCED_DRAG_START vertex " + clickedVertex.getId() + " | Double-click detected");
} else {
// Start hold detection for potential enhanced drag
startHoldDetection(clickedVertex, event);
}
lastClickTime = currentTime;
lastClickedVertex = clickedVertex;
} else {
// Clear selection if clicking on empty space
clearDragState();
}
}
/**
* Enhanced mouse dragged handler with real-time edge updates
*/
private void handleEnhancedMouseDragged(MouseEvent event) {
if (draggedVertex == null) return;
// Calculate new position with boundary constraints
double newX = constrainToCanvasBounds(event.getX(), true);
double newY = constrainToCanvasBounds(event.getY(), false);
// Update vertex position
draggedVertex.setPosition(newX, newY);
// Real-time edge updates during drag
updateEdgesForVertexRealtime(draggedVertex.getId());
// Update drag feedback visual effects
updateDragFeedback(draggedVertex);
// Update status with current position
if (statusLabel != null && isEnhancedDragging) {
statusLabel.setText("🎯 Dragging vertex " + draggedVertex.getId() +
" to (" + String.format("%.0f", newX) + ", " + String.format("%.0f", newY) + ")");
}
}
/**
* Enhanced mouse released handler
*/
private void handleEnhancedMouseReleased(MouseEvent event) {
if (draggedVertex != null) {
// Finalize drag operation
finalizeDrag(draggedVertex);
logOperation("ENHANCED_DRAG_END vertex " + draggedVertex.getId() +
" | Final position: (" + String.format("%.1f", draggedVertex.getX()) +
", " + String.format("%.1f", draggedVertex.getY()) + ")");
}
// Clear all drag states
clearDragState();
}
/**
* Find vertex at the given position
*/
private VertexElement findVertexAtPosition(double x, double y) {
for (VertexElement vertex : vertexElements.values()) {
if (vertex.contains(x, y)) {
return vertex;
}
}
return null;
}
/**
* Start hold detection timer for enhanced drag
*/
private void startHoldDetection(VertexElement vertex, MouseEvent event) {
draggedVertex = vertex;
dragStartX = event.getX();
dragStartY = event.getY();
// Start hold timer
if (dragHoldTimer != null) {
dragHoldTimer.stop();
}
dragHoldTimer = new Timeline(new KeyFrame(Duration.millis(HOLD_THRESHOLD), e -> {
if (draggedVertex == vertex && !isDragging) {
startEnhancedDrag(vertex, event);
}
}));
dragHoldTimer.play();
}
/**
* Start enhanced drag mode with visual feedback
*/
private void startEnhancedDrag(VertexElement vertex, MouseEvent event) {
if (vertex == null) return;
isEnhancedDragging = true;
isDragging = true;
isDragHoldActive = true;
draggedVertex = vertex;
dragStartX = event.getX();
dragStartY = event.getY();
// Stop hold timer if running
if (dragHoldTimer != null) {
dragHoldTimer.stop();
}
// Apply visual feedback
applyDragVisualFeedback(vertex);
// Update status
if (statusLabel != null) {
statusLabel.setText("🎯 Enhanced drag mode: Vertex " + vertex.getId());
}
System.out.println("🎯 Enhanced drag started for vertex " + vertex.getId());
}
/**
* Apply visual feedback during drag
*/
private void applyDragVisualFeedback(VertexElement vertex) {
Circle circle = vertex.getCircle();
// Store original style
originalVertexStyle = circle.getStyle();
// Apply enhanced drag styling
String dragStyle = "-fx-fill: #10b981; -fx-stroke: #059669; -fx-stroke-width: 4; " +
"-fx-effect: dropshadow(gaussian, #10b981, 15, 0.8, 0, 0);";
circle.setStyle(dragStyle);
// Create pulsing animation
ScaleTransition pulseAnimation = new ScaleTransition(Duration.millis(800), circle);
pulseAnimation.setFromX(1.0);
pulseAnimation.setFromY(1.0);
pulseAnimation.setToX(1.15);
pulseAnimation.setToY(1.15);
pulseAnimation.setAutoReverse(true);
pulseAnimation.setCycleCount(Timeline.INDEFINITE);
pulseAnimation.setInterpolator(Interpolator.EASE_BOTH);
// Store animation reference
dragFeedbackAnimation = new Timeline();
pulseAnimation.play();
vertex.setHighlightAnimation(pulseAnimation);
}
/**
* Update drag feedback during movement
*/
private void updateDragFeedback(VertexElement vertex) {
// Optional: Add trail effect or position indicator
// This could include temporary visual elements showing the drag path
}
/**
* Constrain position to canvas bounds
*/
private double constrainToCanvasBounds(double position, boolean isX) {
if (isX) {
double maxX = graphCanvas.getPrefWidth() - BOUNDARY_PADDING;
return Math.max(BOUNDARY_PADDING, Math.min(position, maxX));
} else {
double maxY = graphCanvas.getPrefHeight() - BOUNDARY_PADDING;
return Math.max(BOUNDARY_PADDING, Math.min(position, maxY));
}
}
/**
* Real-time edge updates during drag (optimized for performance)
*/
private void updateEdgesForVertexRealtime(int vertexId) {
VertexElement vertex = vertexElements.get(vertexId);
if (vertex == null) return;
double x = vertex.getX();
double y = vertex.getY();
// Update connected edges in real-time
for (EdgeElement edge : edgeElements) {
if (edge.getSource() == vertexId) {
edge.getLine().setStartX(x);
edge.getLine().setStartY(y);
}
if (edge.getDestination() == vertexId) {
edge.getLine().setEndX(x);
edge.getLine().setEndY(y);
}
// Update weight label position if exists
if ((edge.getSource() == vertexId || edge.getDestination() == vertexId)
&& edge.getWeightLabel() != null) {
Line line = edge.getLine();
double midX = (line.getStartX() + line.getEndX()) / 2;
double midY = (line.getStartY() + line.getEndY()) / 2;
edge.getWeightLabel().setX(midX);
edge.getWeightLabel().setY(midY);
}
}
}
/**
* Finalize drag operation with smooth animation
*/
private void finalizeDrag(VertexElement vertex) {
if (vertex == null) return;
Circle circle = vertex.getCircle();
// Stop any running animations
if (vertex.getHighlightAnimation() != null) {
vertex.getHighlightAnimation().stop();
vertex.setHighlightAnimation(null);
}
// Smooth transition back to normal appearance
Timeline finalizeAnimation = new Timeline(
new KeyFrame(Duration.ZERO,
new KeyValue(circle.styleProperty(), circle.getStyle())),
new KeyFrame(Duration.millis(400),
new KeyValue(circle.styleProperty(), originalVertexStyle, Interpolator.EASE_OUT))
);
// Add a final "settle" effect
ScaleTransition settleEffect = new ScaleTransition(Duration.millis(200), circle);
settleEffect.setFromX(1.15);
settleEffect.setFromY(1.15);
settleEffect.setToX(1.0);
settleEffect.setToY(1.0);
settleEffect.setInterpolator(Interpolator.EASE_OUT);
ParallelTransition finalTransition = new ParallelTransition(finalizeAnimation, settleEffect);
finalTransition.play();
// Update final display state
updateDisplay();
System.out.println("✅ Drag finalized for vertex " + vertex.getId());
}
/**
* Clear all drag-related states
*/
private void clearDragState() {
// Stop any running timers
if (dragHoldTimer != null) {
dragHoldTimer.stop();
dragHoldTimer = null;
}
if (dragFeedbackAnimation != null) {
dragFeedbackAnimation.stop();
dragFeedbackAnimation = null;
}
// Reset states
isDragging = false;
isEnhancedDragging = false;
isDragHoldActive = false;
draggedVertex = null;
lastClickedVertex = null;
// Reset status
if (statusLabel != null && !statusLabel.getText().contains("vertices") && !statusLabel.getText().contains("Empty")) {
updateDisplay(); // This will reset status to normal
}
}
// ==================== GRAPH OPERATIONS ====================
@FXML
private void addVertex() {
if (isTraversing) return;
String input = addVertexField.getText().trim();
if (input.isEmpty()) {
showAlert("Invalid Input", "Please enter a vertex ID.");
return;
}
try {
int vertexId = Integer.parseInt(input);
if (graphModel.containsVertex(vertexId)) {
showAlert("Vertex Exists", "Vertex " + vertexId + " already exists in the graph.");
return;
}
// Save state for undo
saveState("ADD_VERTEX_" + vertexId);
// Add to model
graphModel.addVertex(vertexId);
// Create visual element
VertexElement vertexElement = createVertexElement(vertexId);
vertexElements.put(vertexId, vertexElement);
// **FIX: Add to canvas with animation safely**
Platform.runLater(() -> {
animateAddVertex(vertexElement);
// **FIX: Apply layout after adding vertex**
if (vertexElements.size() > 1) {
applyCircularLayout();
}
updateDisplay();
System.out.println("Added vertex " + vertexId + " - Total canvas children: " + graphCanvas.getChildren().size());
});
addVertexField.clear();
logOperation("ADD_VERTEX " + vertexId + " | Total: " + graphModel.getVertexCount() + " vertices");
} catch (NumberFormatException e) {
showAlert("Invalid Input", "Please enter a valid integer for vertex ID.");
}
}
@FXML
private void removeVertex() {
if (isTraversing) return;
String input = addVertexField.getText().trim();
if (input.isEmpty()) {
showAlert("Invalid Input", "Please enter a vertex ID to remove.");
return;
}
try {
int vertexId = Integer.parseInt(input);
if (!graphModel.containsVertex(vertexId)) {
showAlert("Vertex Not Found", "Vertex " + vertexId + " does not exist in the graph.");
return;
}
// Save state for undo
saveState("REMOVE_VERTEX_" + vertexId);
// Remove from model
graphModel.removeVertex(vertexId);
// Remove visual elements
VertexElement vertexElement = vertexElements.remove(vertexId);
if (vertexElement != null) {
animateRemoveVertex(vertexElement);
}
// Remove associated edges
edgeElements.removeIf(edge ->
edge.getSource() == vertexId || edge.getDestination() == vertexId);
addVertexField.clear();
updateDisplay();
redrawGraph();
logOperation("REMOVE_VERTEX " + vertexId + " | Remaining: " + graphModel.getVertexCount() + " vertices");
} catch (NumberFormatException e) {
showAlert("Invalid Input", "Please enter a valid integer for vertex ID.");
}
}
@FXML
private void addEdge() {
if (isTraversing) return;
String sourceInput = sourceField.getText().trim();
String destInput = destinationField.getText().trim();
String weightInput = weightField.getText().trim();
if (sourceInput.isEmpty() || destInput.isEmpty()) {
showAlert("Invalid Input", "Please enter both source and destination vertices.");
return;
}
double weight = 1.0;
if (weightedCheckBox.isSelected()) {
if (weightInput.isEmpty()) {
showAlert("Invalid Input", "Please enter edge weight for weighted graph.");
return;
}
try {
weight = Double.parseDouble(weightInput);
if (weight <= 0) {
showAlert("Invalid Weight", "Weight must be positive.");
return;
}
} catch (NumberFormatException e) {
showAlert("Invalid Input", "Please enter a valid weight.");
return;
}
}
try {
int source = Integer.parseInt(sourceInput);
int destination = Integer.parseInt(destInput);
if (!graphModel.containsVertex(source)) {
showAlert("Vertex Not Found", "Source vertex " + source + " does not exist.");
return;
}
if (!graphModel.containsVertex(destination)) {
showAlert("Vertex Not Found", "Destination vertex " + destination + " does not exist.");
return;
}
if (graphModel.containsEdge(source, destination)) {
showAlert("Edge Exists", "Edge from " + source + " to " + destination + " already exists.");
return;
}
// Save state for undo
saveState("ADD_EDGE_" + source + "_" + destination);
// Add to model
graphModel.addEdge(source, destination, weight);
// **FIX: Create and add visual element safely**
double finalWeight = weight;
Platform.runLater(() -> {
EdgeElement edgeElement = createEdgeElement(source, destination, finalWeight);
if (edgeElement != null) {
edgeElements.add(edgeElement);
animateAddEdge(edgeElement);
updateAllEdges();
updateDisplay();
System.out.println("Added edge " + source + "->" + destination + " - Total canvas children: " + graphCanvas.getChildren().size());
}
});
sourceField.clear();
destinationField.clear();
weightField.clear();
logOperation("ADD_EDGE " + source + " -> " + destination +
(weightedCheckBox.isSelected() ? " (weight: " + weight + ")" : "") +
" | Total: " + graphModel.getEdgeCount() + " edges");
} catch (NumberFormatException e) {
showAlert("Invalid Input", "Please enter valid integers for vertex IDs.");
}
}
@FXML
private void removeEdge() {
if (isTraversing) return;
String sourceInput = sourceField.getText().trim();
String destInput = destinationField.getText().trim();
if (sourceInput.isEmpty() || destInput.isEmpty()) {
showAlert("Invalid Input", "Please enter both source and destination vertices.");
return;
}
try {
int source = Integer.parseInt(sourceInput);
int destination = Integer.parseInt(destInput);
if (!graphModel.containsEdge(source, destination)) {
showAlert("Edge Not Found", "Edge from " + source + " to " + destination + " does not exist.");
return;
}
// Save state for undo
saveState("REMOVE_EDGE_" + source + "_" + destination);
// Remove from model
graphModel.removeEdge(source, destination);
// Remove visual element
edgeElements.removeIf(edge ->
edge.getSource() == source && edge.getDestination() == destination);
sourceField.clear();
destinationField.clear();
updateDisplay();
redrawGraph();
logOperation("REMOVE_EDGE " + source + " -> " + destination +
" | Remaining: " + graphModel.getEdgeCount() + " edges");
} catch (NumberFormatException e) {
showAlert("Invalid Input", "Please enter valid integers for vertex IDs.");
}
}
// ==================== SEARCH AND HIGHLIGHT OPERATIONS ====================
@FXML
private void searchVertex() {
if (isTraversing) return;
String input = searchVertexField.getText().trim();
if (input.isEmpty()) {
showAlert("Invalid Input", "Please enter a vertex ID to search.");
return;
}
try {
int vertexId = Integer.parseInt(input);
if (!graphModel.containsVertex(vertexId)) {
showAlert("Vertex Not Found", "Vertex " + vertexId + " does not exist in the graph.");
return;
}
// FIND: Only show popup and zoom effect, NO color change
VertexElement vertexElement = vertexElements.get(vertexId);
if (vertexElement != null) {
// Show popup effect with vertex information
showVertexPopup(vertexElement, vertexId);
// Apply zoom/pulse effect without color change
applyFindEffect(vertexElement);
// Update result area
if (resultArea != null) {
resultArea.setText("🔍 FOUND: Vertex " + vertexId + "\n" +
"Position: (" + String.format("%.1f", vertexElement.getCircle().getCenterX()) +
", " + String.format("%.1f", vertexElement.getCircle().getCenterY()) + ")\n" +
"Degree: " + graphModel.getDegree(vertexId) + "\n" +
"Neighbors: " + graphModel.getNeighbors(vertexId));
}
}
searchVertexField.clear();
logOperation("FIND_VERTEX " + vertexId + " | Found and zoomed to location");
} catch (NumberFormatException e) {
showAlert("Invalid Input", "Please enter a valid integer for vertex ID.");
}
}
@FXML
private void highlightVertex() {
if (isTraversing) return;
String input = searchVertexField.getText().trim();
if (input.isEmpty()) {
showAlert("Invalid Input", "Please enter a vertex ID to highlight.");
return;
}
try {
int vertexId = Integer.parseInt(input);
if (!graphModel.containsVertex(vertexId)) {
showAlert("Vertex Not Found", "Vertex " + vertexId + " does not exist in the graph.");
return;
}
// HIGHLIGHT: Apply color highlighting effect
VertexElement vertexElement = vertexElements.get(vertexId);
if (vertexElement != null) {
// Clear any previous highlights
clearAllHighlights();
// Apply color highlight effect
applyHighlightEffect(vertexElement, vertexId);
// Also highlight connected edges
highlightConnectedEdges(vertexId);
// Update result area
if (resultArea != null) {
resultArea.setText("✨ HIGHLIGHTED: Vertex " + vertexId + "\n" +
"Status: Currently highlighted in the graph\n" +
"Degree: " + graphModel.getDegree(vertexId) + "\n" +
"Connected to: " + graphModel.getNeighbors(vertexId));
}
}
searchVertexField.clear();
logOperation("HIGHLIGHT_VERTEX " + vertexId + " | Applied visual highlight");
} catch (NumberFormatException e) {
showAlert("Invalid Input", "Please enter a valid integer for vertex ID.");
}
}
// ==================== VISUAL EFFECTS METHODS ====================
/**
* Apply FIND effect: Popup + zoom/pulse effect WITHOUT color change
*/
private void applyFindEffect(VertexElement vertexElement) {
Circle circle = vertexElement.getCircle();
// Store original style to restore later
String originalStyle = circle.getStyle();
// Create zoom-in effect to draw attention
ScaleTransition zoomIn = new ScaleTransition(Duration.millis(300), circle);
zoomIn.setFromX(1.0);
zoomIn.setFromY(1.0);
zoomIn.setToX(1.4);
zoomIn.setToY(1.4);
zoomIn.setInterpolator(Interpolator.EASE_OUT);
// Create zoom-out effect to return to normal
ScaleTransition zoomOut = new ScaleTransition(Duration.millis(300), circle);
zoomOut.setFromX(1.4);
zoomOut.setFromY(1.4);
zoomOut.setToX(1.0);
zoomOut.setToY(1.0);
zoomOut.setInterpolator(Interpolator.EASE_IN);
// Add subtle shadow effect during zoom
Timeline shadowEffect = new Timeline(
new KeyFrame(Duration.ZERO,
new KeyValue(circle.styleProperty(), originalStyle)),
new KeyFrame(Duration.millis(300),
new KeyValue(circle.styleProperty(), originalStyle +
"-fx-effect: dropshadow(gaussian, #4f46e5, 15, 0.7, 0, 0);")),
new KeyFrame(Duration.millis(600),
new KeyValue(circle.styleProperty(), originalStyle))
);
// Combine animations
SequentialTransition findAnimation = new SequentialTransition(zoomIn, zoomOut);
ParallelTransition fullEffect = new ParallelTransition(findAnimation, shadowEffect);
fullEffect.play();
// Also scroll to center the vertex if it's outside viewport
Platform.runLater(() -> centerVertexInView(vertexElement));
}
/**
* Apply HIGHLIGHT effect: Color change and persistent highlighting
*/
/**
* Apply HIGHLIGHT effect: Color change and persistent highlighting with 3-second auto-reset
*/
private void applyHighlightEffect(VertexElement vertexElement, int vertexId) {
Circle circle = vertexElement.getCircle();
Text label = vertexElement.getLabel();
// Store original styles for restoration
String originalCircleStyle = "-fx-fill: #3b82f6; -fx-stroke: #1d4ed8; -fx-stroke-width: 2;";
String originalLabelStyle = "-fx-fill: white; -fx-font-weight: bold;";
// Apply highlight colors
String highlightStyle = "-fx-fill: #fbbf24; -fx-stroke: #f59e0b; -fx-stroke-width: 3; " +
"-fx-effect: dropshadow(gaussian, #f59e0b, 10, 0.6, 0, 0);";
circle.setStyle(highlightStyle);
if (label != null) {
label.setStyle("-fx-fill: #92400e; -fx-font-weight: bold; " +
"-fx-effect: dropshadow(gaussian, #fef3c7, 2, 0.5, 0, 0);");
}
// Add pulsing animation for highlighted vertex
ScaleTransition pulse = new ScaleTransition(Duration.millis(1000), circle);
pulse.setFromX(1.0);
pulse.setFromY(1.0);
pulse.setToX(1.1);
pulse.setToY(1.1);
pulse.setAutoReverse(true);
pulse.setCycleCount(6); // 3 seconds total (6 half-cycles * 0.5s each)
pulse.setInterpolator(Interpolator.EASE_BOTH);
// Store animation reference to stop it if needed
vertexElement.setHighlightAnimation(pulse);
pulse.play();
// ⭐ AUTO-RESET AFTER 3 SECONDS
Timeline autoReset = new Timeline(
new KeyFrame(Duration.seconds(3), e -> {
// Stop the pulsing animation
if (vertexElement.getHighlightAnimation() != null) {
vertexElement.getHighlightAnimation().stop();
vertexElement.setHighlightAnimation(null);
}
// Smooth transition back to original colors
Timeline fadeBack = new Timeline(
new KeyFrame(Duration.ZERO,
new KeyValue(circle.styleProperty(), highlightStyle)),
new KeyFrame(Duration.millis(500),
new KeyValue(circle.styleProperty(), originalCircleStyle, Interpolator.EASE_OUT))
);
if (label != null) {
Timeline labelFadeBack = new Timeline(
new KeyFrame(Duration.ZERO,
new KeyValue(label.styleProperty(), label.getStyle())),