-
Notifications
You must be signed in to change notification settings - Fork 0
/
ImageRecognition.java
1641 lines (1455 loc) · 71.9 KB
/
ImageRecognition.java
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
/*
* Copyright 2021 to Joel Amundberg and Martin Moberg
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package plugin;
import com.sun.istack.internal.NotNull;
import eye.Eye;
import eye.Match;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.jnativehook.GlobalScreen;
import org.jnativehook.NativeHookException;
import org.jnativehook.keyboard.NativeKeyEvent;
import org.jnativehook.keyboard.NativeKeyListener;
import scout.Action;
import scout.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ImageRecognition {
private static final Eye EYE = new Eye();
private static AppState currentState = null;
private static int selectedScreen = -1;
private static Rectangle selectedArea;
private static Rectangle selectedMonitor;
private static BufferedImage currentScreenshot;
private static final Logger LOGGER = Logger.getLogger(ImageRecognition.class.getName());
private static Widget.WidgetType currentWidgetType = Widget.WidgetType.ACTION;
private static Widget.WidgetSubtype currentWidgetSubtype = Widget.WidgetSubtype.DOUBLE_CLICK_ACTION;
protected static boolean isControlClicked = false;
protected static boolean isShiftClicked = false;
private static long startTypeTime = 0;
private static Point dragStartPoint = null;
private static Point dragCurrentPoint = null;
private static final Color overlayColor = new Color(0, 0, 0, 80);
private static final Color circleColor = new Color(255, 0, 0, 255);
private static final Properties keyBindings = new Properties();
private static int defaultDimensionWidth = 150;
private static int defaultDimensionHeight = 150;
private static long mayInsertDragDrop = 0;
private static final float ONE_MILLION = 1000000.0f;
private static final LinkedList<AppState> previousState = new LinkedList<>();
private static boolean shouldInsertState = true;
private static boolean firstSelected = false;
private static boolean secondSelected = false;
private static Point upperLeft = null;
private static Point lowerRight = null;
private static Widget latestTypeWidget = null;
private static Robot robot = null;
private static ArrayList<GraphicsDevice> graphicDevices = new ArrayList<>();
private static Widget repairWidget = null;
private static int minimumMatchPercent = 100;
/**
* Delegate method that Scout calls on to start a session.
*/
public void startSession() {
/*
NOTE: We had to manually set SessionState to running.
*/
StateController.setSessionState(StateController.SessionState.RUNNING);
currentState = StateController.getCurrentState();
// Default logging level
LOGGER.setLevel(Level.INFO);
// RecognitionMode.EXACT has better performance on larger images.
EYE.setRecognitionMode(Eye.RecognitionMode.EXACT);
// Attempt to get the key bindings and apply them.
getOrCreateKeybindings();
// Set up the application runtime values.
minimumMatchPercent = trySetDefaultIntegers("minmatchpercent", 100);
defaultDimensionWidth = trySetDefaultIntegers("defaultwidgetwidth", 150);
defaultDimensionHeight = trySetDefaultIntegers("defaultwidgetheight", 150);
LOGGER.info("Minimum match = " + minimumMatchPercent + "% | Default widget size = [w="
+ defaultDimensionWidth + ",h=" + defaultDimensionHeight +"]");
try {
GlobalScreen.registerNativeHook();
// GlobalScreen does INFO logs of every action on the system. Remove that by
// changing the minimum logging level of the class to WARNING
Logger logger = Logger.getLogger(GlobalScreen.class.getPackage().getName());
logger.setLevel(Level.WARNING);
logger.setUseParentHandlers(false);
}
catch (NativeHookException ex) {
LOGGER.warning("Failed to add global hook? | " + ExceptionUtils.getStackTrace(ex));
StateController.displayMessage("Failed to register global hook, stopping session.", 5000);
StateController.stopSession();
}
// Add global key listener.
GlobalScreen.addNativeKeyListener(new GlobalKeyboardListener());
// Push the monitor selection prompt.
try{
ArrayList<BufferedImage> screenShots = getMonitorScreenshots();
displayScreenshots(screenShots);
// Selection prompt within screenshot (monitor)
}
catch (Exception e){
LOGGER.severe("Failed to select screen, dying. | " + ExceptionUtils.getStackTrace(e));
StateController.displayMessage("Failed to select a screen, session terminated.", 5000);
StateController.stopSession(); // Let the session die if you can't select a monitor.
}
}
/**
* Delegate method of Scout that draws shapes on the main canvas.
* @param g A {@link java.awt.Graphics Graphics} object to be used to draw with.
*/
public void paintCaptureForeground(Graphics g) {
if(StateController.isOngoingSession() && !StateController.isToolbarVisible()) {
if(isControlClicked && isShiftClicked) {
// early kill, no need to draw.
if (dragStartPoint == null)
return;
else if (dragCurrentPoint == null) // have gotten the start drag point, but not the current. create min size.
dragCurrentPoint = new Point(dragStartPoint.x + 1, dragStartPoint.y + 1);
// Get the rectangle to draw.
Rectangle draw = getRectangleFromPoints(dragStartPoint, dragCurrentPoint, true);
// set rendering hints, color. draw rectangle.
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(overlayColor);
g2d.fillRect(draw.x, draw.y, draw.width, draw.height);
g2d.setColor(circleColor);
g2d.drawOval(draw.x + (draw.width / 2), draw.y + (draw.height / 2), 3, 3);
}
else {
dragStartPoint = null;
dragCurrentPoint = null;
}
}
}
/**
* Helper method to create the {@link java.awt.Rectangle Rectangle} from two points provided.
* @param scaled Boolean to determine if the coordinates should be scaled to match the main scout window.
* @return A {@link java.awt.Rectangle Rectangle} with the coordinates to draw the overlay on.
*/
private Rectangle getRectangleFromPoints(Point p1, Point p2, boolean scaled) {
int minX = Math.min(p1.x, p2.x);
int minY = Math.min(p1.y, p2.y);
int width = Math.abs(p1.x - p2.x);
int height = Math.abs(p1.y - p2.y);
if(width == 0)
width = 1;
if(height == 0)
height = 1;
if(scaled) {
minX = StateController.getScaledX(minX);
minY = StateController.getScaledY(minY);
width = StateController.getScaledX(width);
height = StateController.getScaledY(height);
}
return new Rectangle(minX, minY, width, height);
}
/**
* Helper method to select a sub-region of a screenshot to be displayed.
* @param screenshot The {@link java.awt.image.BufferedImage screenshot} to make the selection on.
*/
public void promptSelection(BufferedImage screenshot) {
JFrame screenShotFrame = new JFrame();
//BufferedImage minimizedScreenshot = resizeImage(screenshot,StateController.getProductViewWidth(),StateController.getProductViewHeight());
JLabel temp = new JLabel(new ImageIcon(screenshot));
screenShotFrame.setLayout(new GridBagLayout());
screenShotFrame.setSize(screenshot.getWidth(),screenshot.getHeight());
centreWindow(screenShotFrame);
temp.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
if(!firstSelected) {
upperLeft = MouseInfo.getPointerInfo().getLocation();
firstSelected = true;
}
else if (!secondSelected) {
lowerRight = MouseInfo.getPointerInfo().getLocation();
secondSelected = true;
screenShotFrame.setVisible(false);
selectedArea = getRectangleFromPoints(upperLeft, lowerRight, false);
}
}
});
screenShotFrame.add(temp);
screenShotFrame.setVisible(true);
}
/**
* Helper method that handles the sleep call and its throws to not have to do it multiple times.
* @param amountOfMS the amount of milliseconds to sleep for.
*/
private void sleepForAmountMS(long amountOfMS) {
long startSleep = System.currentTimeMillis();
try {
TimeUnit.MILLISECONDS.sleep(amountOfMS);
}catch (InterruptedException ex) {
long amountLeft = System.currentTimeMillis() - startSleep;
// if it's 10 ms more left to sleep, sleep again.
if(amountLeft > 10)
sleepForAmountMS(amountLeft);
// else fall through and return a bit early
}
}
private Match tryAllThreeModes(Widget toFind) {
Match match = null;
Eye.RecognitionMode savedRecognitionMode = EYE.getRecognitionMode();
EYE.setRecognitionMode(Eye.RecognitionMode.EXACT);
match = findWidget(toFind);
if(match == null){
EYE.setRecognitionMode(Eye.RecognitionMode.COLOR);
match = findWidget(toFind);
if(match == null){
EYE.setRecognitionMode(Eye.RecognitionMode.TOLERANT);
match = findWidget(toFind);
}
}
else if(match.getMatchPercent() < minimumMatchPercent)
LOGGER.info("match% tryallthree = " + match.getMatchPercent());
EYE.setRecognitionMode(savedRecognitionMode);
return match;
}
/**
* The method that locates, and performs, the actions of the image widgets.
* @param w The ImageRecognition plugin widget to be performed.
* @return true if performed, false otherwise.
*/
private boolean performImageWidget(Widget w) {
// Init variables
long startx = System.nanoTime();
Match match = tryAllThreeModes(w);
boolean found = true;
// Handle the matched widgets and perform them.
if(match != null && match.getMatchPercent() >= minimumMatchPercent) {
LOGGER.info("Match %"+ match.getMatchPercent());
w.setLocationArea(new Rectangle(match.getX(), match.getY(), match.getWidth(), match.getHeight()));
if(w.getWidgetType() == Widget.WidgetType.ACTION && w.getWidgetSubtype() == Widget.WidgetSubtype.DOUBLE_CLICK_ACTION){
LOGGER.info("Action & Double Click");
moveMouseAction(w,match.getCenterLocation());
}
else if(w.getWidgetType() == Widget.WidgetType.ACTION && w.getWidgetSubtype() == Widget.WidgetSubtype.LEFT_CLICK_ACTION){
LOGGER.info("Action & Left click");
moveMouseAction(w,match.getCenterLocation());
}
else if(w.getWidgetType() == Widget.WidgetType.ACTION && w.getWidgetSubtype() == Widget.WidgetSubtype.RIGHT_CLICK_ACTION){
LOGGER.info("Action & Left click");
moveMouseAction(w,match.getCenterLocation());
}
else if(w.getWidgetType() == Widget.WidgetType.ACTION && w.getWidgetSubtype() == Widget.WidgetSubtype.TYPE_ACTION){
LOGGER.info("Action & Type action");
moveMouseAction(w,match.getCenterLocation());
}
// TODO WE ARE SO SORRY ABOUT THIS - NEED TO REPLACE PASTE_ACTION - TEMPORARY SOLUTION
else if(w.getWidgetType() == Widget.WidgetType.ACTION && w.getWidgetSubtype() == Widget.WidgetSubtype.PASTE_ACTION) {
moveMouseAction(w,match.getCenterLocation());
}
else if(w.getWidgetType() == Widget.WidgetType.CHECK){
w.setWidgetStatus(Widget.WidgetStatus.VALID);
}
}
else{
LOGGER.fine("Didn't find match for widget with image path: " + w.getMetadata("IR_imageName"));
w.setWidgetStatus(Widget.WidgetStatus.UNLOCATED);
found = false;
}
LOGGER.finer("TIME: [" + ((System.nanoTime() - startx) / ONE_MILLION) + " ms]");
return found;
}
/**
* Action performer helper method used by {@link #performImageWidget(Widget)}.
*
* Determines what action to perform through the widget sent in. The action will be
* performed at the point specified, and then the mouse will be returned where it
* started so that the user does not notice the action.
*
* @param w The {@link scout.Widget Widget} that is being performed, used to determine what action to take.
* @param p The {@link java.awt.Point Point} at where the widget should be performed.
*/
private void moveMouseAction(Widget w, Point p) {
Point absoluteMousePoint = MouseInfo.getPointerInfo().getLocation();
robot.mouseMove(p.x + selectedMonitor.x,p.y + selectedMonitor.y);
if(w.getWidgetSubtype() == Widget.WidgetSubtype.LEFT_CLICK_ACTION)
singleLeftClick();
else if(w.getWidgetSubtype() == Widget.WidgetSubtype.RIGHT_CLICK_ACTION)
singleRightClick();
else if(w.getWidgetSubtype() == Widget.WidgetSubtype.DOUBLE_CLICK_ACTION)
doubleClick();
else if(w.getWidgetSubtype() == Widget.WidgetSubtype.TYPE_ACTION){
if(w.getMetadata("IR_amountClicksType") != null) {
int amount = (int)w.getMetadata("IR_amountClicksType");
if (amount == 1)
singleLeftClick();
else if (amount == 2)
doubleClick();
else if (amount == 3)
tripleClick();
else {
LOGGER.warning("Failed to get the amount of clicks?");
singleLeftClick();
}
typeComment(w);
}
else {
LOGGER.warning("WARNING: ENTERING DEFAULT CASE FOR TYPE ACTION!");
singleLeftClick();
typeComment(w);
}
}
else if(w.getWidgetSubtype() == Widget.WidgetSubtype.PASTE_ACTION){
singleLeftClick(); // Perform first widget click.
sleepForAmountMS(1500);
String fileName = (String) w.getMetadata("IR_secondImageWidget");
if (fileName != null)
{
BufferedImage secondImage = EYE.loadImage(getProjectFileLocationForName(fileName));
Match match = EYE.findImage(currentScreenshot, secondImage);
if(match != null){
robot.mouseMove(match.getCenterLocation().x + selectedMonitor.x,
match.getCenterLocation().y + selectedMonitor.y);
singleLeftClick(); // Perform second widget click.
}
else {
LOGGER.info("Failed to find second image of our MENU_CLICK_ACTION (paste_action)");
}
}
}
else {
LOGGER.warning("Could not handle subtype: " + w.getWidgetSubtype().toString());
}
// Return mouse to original point.
robot.mouseMove(absoluteMousePoint.x,absoluteMousePoint.y);
}
/**
* Delegate method that Scout calls on to get the image to display in the main window.
* @return A {@link java.awt.image.BufferedImage BufferedImage} screenshot of the selected monitor/region.
*/
public BufferedImage getCapture() {
if(selectedScreen < 0)
return null;
else {
selectedMonitor = graphicDevices.get(selectedScreen).getDefaultConfiguration().getBounds();
}
if(isControlClicked && isShiftClicked){
return currentScreenshot;
}
if (lowerRight != null && upperLeft != null && false) { // TODO: Intentionally disabled for now.
BufferedImage imgTemp = getMonitorScreenshot(selectedMonitor);
currentScreenshot = EYE.getSubimage(imgTemp,selectedArea.x,selectedArea.y,selectedArea.width,selectedArea.height);
return currentScreenshot;
}
else{
currentScreenshot = getMonitorScreenshot(selectedMonitor);
return currentScreenshot;
}
}
/**
* Delegate method used by Scout to notify the plugins that the state has changed.
*/
public void changeState() {
LOGGER.finer("Changed state");
// Preserve history of previous states.
// TODO: This is not perfect if manual back/forwards/home-commands are used.
if(shouldInsertState)
previousState.push(currentState);
else
shouldInsertState = true;
currentState = StateController.getCurrentState();
// Force re-check of all widgets on the new state.
for(Widget w : currentState.getAllWidgets()){
w.setWidgetStatus(Widget.WidgetStatus.UNLOCATED);
}
performAllStateWidgets(MAX_DEPTH, currentState, false);
}
private Match findWidget(Widget w){
String filePath = (String) w.getMetadata("IR_imageName");
BufferedImage find = EYE.loadImage(getProjectFileLocationForName(filePath));
if(find != null)
{
Match match = EYE.findImage(currentScreenshot, find);
if(match != null && match.getMatchPercent() >= minimumMatchPercent)
return match;
else if(match != null)
LOGGER.info("Match was not null, but " + match.getMatchPercent() + "% instead of the minimum " +
minimumMatchPercent + "%");
}
return null;
}
/**
* Helper method to retrieve Type action widgets from
* @param location The {@link java.awt.Point Point} to look for Type action widgets at.
* @return The located widget, or null.
*/
private Widget getTypeWidget(Point location)
{
List<Widget> locatedWidgets = StateController.getWidgetsAt(location);
for(Widget locatedWidget : locatedWidgets)
{
if(locatedWidget.getWidgetType() == Widget.WidgetType.ACTION &&
locatedWidget.getWidgetSubtype() == Widget.WidgetSubtype.TYPE_ACTION &&
locatedWidget.getWidgetVisibility() != Widget.WidgetVisibility.HIDDEN
)
return locatedWidget;
}
return null;
}
/**
* Helper method to delete all {@link scout.Widget Widgets} after a specific point on
* the state graph.
* @param appState The {@link scout.AppState AppState} to start the deletion from.
* @param depth Sanity blocker variable to ensure that the recursion does not overflow.
*/
private void resetFromNode(AppState appState,int depth){
List <Widget> stateWidgets = appState.getAllWidgets();
if(depth > 100) // Sanity blocker.
return;
for(Widget w: stateWidgets){
if(w.getNextState() != null && w.getNextState().getAllWidgets().size() > 0)
resetFromNode(w.getNextState(),++depth);
deleteFileWithName((String) w.getMetadata("IR_imageName"));
appState.removeWidget(w);
}
}
/**
* Helper method to perform Type actions.
* @param location The {@link java.awt.Point Point} on which to perform the Type action.
*/
private void performTypeAction(Point location) {
Widget existingTypeWidget = getTypeWidget(location);
if(existingTypeWidget != null &&
StateController.getKeyboardInput().length() > 0 &&
existingTypeWidget.getWidgetVisibility() == Widget.WidgetVisibility.VISIBLE)
{
// Keyboard input on visible widget - add a comment
if(StateController.getKeyboardInput().endsWith("[ENTER]"))
{
StateController.removeLastKeyboardInput();
StateController.setCurrentState(existingTypeWidget.getNextState());
existingTypeWidget.setComment(StateController.getKeyboardInput().trim());
StateController.clearKeyboardInput();
displayTypeWidgetClickSelection(existingTypeWidget);
if(latestTypeWidget == existingTypeWidget)
latestTypeWidget = null;
}
}
else{
StateController.displayMessage("Couldn't perform typeAction",1000);
LOGGER.warning("Failed to perform Type action at " + location.toString());
}
}
/**
* Helper method that provides a display window to select the amount of clicks to perform when
* a TYPE widget is being executed.
* @param w the {@link scout.Widget Widget} that should have the amount of clicks associated.
*/
private void displayTypeWidgetClickSelection(Widget w) {
JFrame performFrame = new JFrame();
performFrame.setLayout(new BoxLayout(performFrame.getContentPane(), BoxLayout.Y_AXIS));
JLabel attentionTxt = new JLabel("ATTENTION!");
JLabel infoText = new JLabel("Please select the amount of clicks to perform");
JButton oneClick = new JButton("ONE CLICK");
oneClick.setSize(40,40);
oneClick.addActionListener( x -> handleTypeWidgetClickSelection(x, w, performFrame));
JButton twoClick = new JButton("TWO CLICKS");
twoClick.setSize(40,40);
twoClick.addActionListener( x -> handleTypeWidgetClickSelection(x, w, performFrame));
JButton threeClick = new JButton("THREE CLICKS");
threeClick.setSize(40,40);
threeClick.addActionListener( x -> handleTypeWidgetClickSelection(x, w, performFrame));
attentionTxt.setAlignmentX(Component.CENTER_ALIGNMENT);
infoText.setAlignmentX(Component.CENTER_ALIGNMENT);
oneClick.setAlignmentX(Component.CENTER_ALIGNMENT);
twoClick.setAlignmentX(Component.CENTER_ALIGNMENT);
threeClick.setAlignmentX(Component.CENTER_ALIGNMENT);
performFrame.add(Box.createRigidArea(new Dimension(0, 25)));
performFrame.add(attentionTxt);
performFrame.add(infoText);
performFrame.add(Box.createRigidArea(new Dimension(0, 25)));
performFrame.add(oneClick);
performFrame.add(Box.createRigidArea(new Dimension(0, 25)));
performFrame.add(twoClick);
performFrame.add(Box.createRigidArea(new Dimension(0, 25)));
performFrame.add(threeClick);
performFrame.setSize(250 , 250);
centreWindow(performFrame);
performFrame.setVisible(true);
}
/**
* Action handler from amount of clicks selection.
* @param x The {@link java.awt.event.ActionEvent ActionEvent} that triggered.
* @param w The {@link scout.Widget Widget} to attach the amount of clicks to.
* @param f The {@link javax.swing.JFrame JFrame} to dispose of.
*/
private void handleTypeWidgetClickSelection(ActionEvent x, Widget w, JFrame f) {
f.dispose();
JButton source = (JButton) x.getSource();
if (source != null) {
switch (source.getText()) {
case "ONE CLICK":
w.putMetadata("IR_amountClicksType", 1);
break;
case "TWO CLICKS":
w.putMetadata("IR_amountClicksType", 2);
break;
case "THREE CLICKS":
w.putMetadata("IR_amountClicksType", 3);
break;
default:
LOGGER.warning("Could not match text to amount clicks, text was: " + source.getText());
break;
}
performImageWidget(w);
}
}
/**
* Helper method that manually types strings of text of a widget.
* @param w The {@link scout.Widget Widget} to use to get the string to type.
*/
private void typeComment(Widget w){
String widgetComment = w.getComment();
if(widgetComment != null)
{
for(char c : widgetComment.toCharArray()){
int keyCode = java.awt.event.KeyEvent.getExtendedKeyCodeForChar(c);
if(keyCode != KeyEvent.VK_UNDEFINED)
{
robot.keyPress(keyCode);
sleepForAmountMS(50); // TODO: Is this really necessary?
robot.keyRelease(keyCode);
}
else
LOGGER.info("Failed to type the char [" + c + "]");
}
}
else
LOGGER.warning("Widget comment was null?");
}
/**
* Helper method to get the full path to the image saving directory with the image name provided.
* @param fileName The name of the image to be saved.
* @return Full {@link java.lang.String String} of the path if successful, otherwise null.
*/
private String getProjectFileLocationForName(String fileName) {
try {
String path = "./data/";
path += StateController.getProduct();
path += "/images/";
if(!Files.exists(Paths.get(path)))
Files.createDirectories(Paths.get(path));
return path + fileName;
} catch (Exception e) {
LOGGER.warning("Could not access/create path - error: " + ExceptionUtils.getStackTrace(e));
return null;
}
}
/**
* Helper method to delete a specific file from the project image directory.
* @param fileName The name of the file to delete.
* @return True if successfully deleted, otherwise False.
*/
private boolean deleteFileWithName(String fileName) {
if(fileName.contains("..")) {
LOGGER.severe("Do not manipulate the path structure with the file name!");
return false;
}
String fullPath = getProjectFileLocationForName(fileName);
if(fullPath != null) {
File toDelete = new File(fullPath);
try {
if(toDelete.delete()) {
LOGGER.fine("Deleted file with path - " + fullPath);
return true;
}
else {
LOGGER.warning("Failed to delete file with path - " + fullPath);
return false;
}
} catch (Exception e) {
LOGGER.warning("Failed to delete file with path - Security exception - "
+ fullPath + " - " + ExceptionUtils.getStackTrace(e));
return false;
}
}
else {
LOGGER.warning("Failed to get full path?");
return false;
}
}
/**
* Helper method to execute having confirmed the choice to delete a widget.
* @param w The {@link scout.Widget Widget} to delete the tree from.
* @param f The {@link javax.swing.JFrame JFrame} to dispose after making the selection.
*/
private void confirmDeleteSelection(Widget w, JFrame f){
if(w == latestTypeWidget)
latestTypeWidget = null;
else if (w == repairWidget)
repairWidget = null;
resetFromNode(w.getNextState(),0);
deleteFileWithName((String) w.getMetadata("IR_imageName"));
StateController.getCurrentState().removeWidget(w);
f.dispose();
}
/**
* Helper method to get the KeyCode for a property with the name of {@link java.lang.String key}.
* @param key The {@link java.lang.String String} name of the key to get.
* @return The {@link java.awt.event.KeyEvent KeyEvent} integer ID code.
*/
private int getKeybindingKeyCode(String key){
String keyBindingString = keyBindings.getProperty(key);
if(keyBindingString != null)
return java.awt.event.KeyEvent.getExtendedKeyCodeForChar(keyBindingString.charAt(0));
else {
LOGGER.warning("Failed to get property with the name: [" + key + "]");
return KeyEvent.VK_UNDEFINED;
}
}
/**
* Method for handling the delegated actions from the main Scout application.
* This is the main workhorse of the plugin as it reacts to all events from Scout.
* @param action The {@link scout.Action action} that has been delegated.
*/
public void performAction(Action action) {
if (!StateController.isRunningSession() || action.isToolbarAction())
return;
if (action instanceof TypeAction) {
TypeAction typeAction = (TypeAction) action;
KeyEvent keyEvent = typeAction.getKeyEvent();
int keyCode = keyEvent.getKeyCode();
char keyChar = keyEvent.getKeyChar();
if (keyCode == KeyEvent.VK_ENTER) {
/* Send keyboardInput to hovered widget (if any) */
StateController.addKeyboardInput("[ENTER]");
performTypeAction(typeAction.getLocation());
} else if (keyCode == KeyEvent.VK_ESCAPE) {
/* Cancel text input */
if (StateController.getKeyboardInput().length() > 0) {
StateController.clearKeyboardInput();
}
if (repairWidget != null) {
repairWidget = null;
} else if(menuWidget != null) {
StateController.getCurrentState().removeWidget(menuWidget);
menuWidget = null;
} else if(latestTypeWidget != null) {
StateController.getCurrentState().removeWidget(latestTypeWidget);
latestTypeWidget = null;
}
} else if (!isControlClicked && keyCode == KeyEvent.VK_BACK_SPACE) {
if(StateController.getKeyboardInput().length() > 0)
StateController.removeLastKeyboardInput();
} else if (!isControlClicked && keyCode == KeyEvent.VK_SPACE) {
StateController.addKeyboardInput(" ");
}
else if (isControlClicked && keyCode == getKeybindingKeyCode("performwidgets")) {
/* Perform the entire state tree automatically from where you are */
LOGGER.info("Performing every widget automatically from the current app state.");
displayPerformWidgets(currentState);
} else if (isControlClicked && keyCode == getKeybindingKeyCode("type")) {
/* Keybinding for the Type action widget */
currentWidgetSubtype = Widget.WidgetSubtype.TYPE_ACTION;
currentWidgetType = Widget.WidgetType.ACTION;
announceCurrentWidgetTypes();
LOGGER.info("Type: " + currentWidgetType + "\nAction: " + currentWidgetSubtype);
} else if (isControlClicked && keyCode == getKeybindingKeyCode("leftclick")) {
/* Keybinding for the Left Click action widget */
currentWidgetSubtype = Widget.WidgetSubtype.LEFT_CLICK_ACTION;
currentWidgetType = Widget.WidgetType.ACTION;
announceCurrentWidgetTypes();
LOGGER.info("Type: " + currentWidgetType + "\nAction: " + currentWidgetSubtype);
} else if (isControlClicked && keyCode == getKeybindingKeyCode("rightclick")) {
/* Keybinding for the right click action widget */
currentWidgetSubtype = Widget.WidgetSubtype.RIGHT_CLICK_ACTION;
currentWidgetType = Widget.WidgetType.ACTION;
announceCurrentWidgetTypes();
LOGGER.info("Type: " + currentWidgetType + "\nAction: " + currentWidgetSubtype);
} else if (isControlClicked && keyCode == getKeybindingKeyCode("check")) {
/* Keybinding for the Check widget */
currentWidgetType = Widget.WidgetType.CHECK;
currentWidgetSubtype = null; // Check has no subtype.
announceCurrentWidgetTypes();
LOGGER.info("Type: " + currentWidgetType + "\nAction: " + currentWidgetSubtype);
} else if (isControlClicked && keyCode == getKeybindingKeyCode("doubleclick")) {
/* Keybinding for the Double Click action widget */
//NOTE: Creates unknown hover action due to not being implemented in the HoverAction plugin
currentWidgetSubtype = Widget.WidgetSubtype.DOUBLE_CLICK_ACTION;
currentWidgetType = Widget.WidgetType.ACTION;
announceCurrentWidgetTypes();
LOGGER.info("Type: " + currentWidgetType.toString() + "\nAction: " + currentWidgetSubtype.toString());
} else if (isControlClicked && keyCode == getKeybindingKeyCode("menuaction")) {
/* Keybinding for Menu Click actions */
currentWidgetSubtype = Widget.WidgetSubtype.PASTE_ACTION; // TODO WE ARE SORRY ABOUT THIS, TEMPORARY SOLUTION
currentWidgetType = Widget.WidgetType.ACTION;
announceCurrentWidgetTypes();
LOGGER.info("Type: " + currentWidgetType.toString() + "\nAction: " + currentWidgetSubtype.toString());
}
else if(isControlClicked && keyCode == KeyEvent.VK_K) {
LOGGER.info("Displaying Keybinding form");
showKeybindingForm();
}
else if(isControlClicked && keyCode == getKeybindingKeyCode("forcerepair")) {
LOGGER.info("Force repair widget");
Point location = ((TypeAction) action).getLocation();
List<Widget> foundWidgets = StateController.getWidgetsAt(location);
if (!foundWidgets.isEmpty()) {
for (Widget w : foundWidgets) {
if (w.getWidgetVisibility() == Widget.WidgetVisibility.VISIBLE && w.getWidgetStatus() == Widget.WidgetStatus.LOCATED) {
BufferedImage img = EYE.loadImage(getProjectFileLocationForName((String)w.getMetadata("IR_imageName")));
displayImageFrame(w, img);
}
}
} // else
// Do nothing, did not click on a widget.
}
else if(isControlClicked && keyCode == getKeybindingKeyCode("home")){
LOGGER.info("Went to the Home node.");
currentState = StateController.getStateTree();
previousState.clear(); // Reset the previous states when you go home.
StateController.setCurrentState(currentState);
StateController.displayMessage("Went to Home node.", 1000);
}
else if(isControlClicked && keyCode == KeyEvent.VK_BACK_SPACE){
/* Remove widget at mouse pointer and all branches underneath it */
Point location = ((TypeAction) action).getLocation();
List<Widget> foundWidgets = StateController.getWidgetsAt(location);
if(!foundWidgets.isEmpty()) {
Widget selected = foundWidgets.get(StateController.getSelectedWidgetNo());
String filePath = (String) selected.getMetadata("IR_imageName");
displayDeletePrompt(selected, filePath);
}
else
LOGGER.fine("Failed to locate widgets to delete at point: " + location.toString());
}
else if(isControlClicked && keyCode == getKeybindingKeyCode("previousstate")){
/* Go back a step in the state graph. Utilize pre-built list of actions for this purpose. */
if(!previousState.isEmpty()){
shouldInsertState = false;
StateController.setCurrentState(previousState.pop());
StateController.displayMessage("Went to previous node.", 1000);
}
else
LOGGER.info("previousState was empty, going back failed.");
}
else if(isControlClicked && keyCode == getKeybindingKeyCode("nextstate")){
/* Go forward a step in the state graph. Utilize pre-built list of actions for this purpose. */
Widget w = currentState.getAllWidgets().get(0);
if(w.getNextState() != null){
currentState = w.getNextState();
shouldInsertState = false;
StateController.setCurrentState(currentState);
StateController.displayMessage("Went to next node.", 1000);
}
else
LOGGER.info("nextState was empty, going forward failed.");
}
else {
/* Catch-all for all other typing actions */
if (StateController.getKeyboardInput().length() == 0)
startTypeTime = System.currentTimeMillis(); // First typed char - remember the time
StateController.addKeyboardInput(getKeyText(keyChar));
}
} else if (action instanceof LeftClickAction && isControlClicked) {
long startAddWidget = System.nanoTime();
// Create widgetImage location rectangle
Point p = ((MoveAction) action).getLocation();
int minX = Math.max((int)(p.x - (defaultDimensionWidth /2.0f)), 0);
int minY = Math.max((int)(p.y - (defaultDimensionHeight /2.0f)), 0);
BufferedImage find = getWidgetImage(new Rectangle(minX, minY, defaultDimensionWidth, defaultDimensionHeight));
// Attempt to locate the image (for verification purposes)
Match match = EYE.findImage(currentScreenshot, find);
if (match != null) {
//robot.mouseMove(upperLeft.x + p.x + selectedMonitor.x,lowerRight.y + p.y + selectedMonitor.y);
if(!createAndAddWidget(match, find)) {
StateController.displayMessage("Failed to add widget");
LOGGER.warning("Failed to add widget? Match was not null.");
}
else
LOGGER.info("Inserted widget, it took [" + ((System.nanoTime() - startAddWidget) / ONE_MILLION) + "ms]");
} else {
LOGGER.info("CLICK: Match is null!");
}
} else if (action instanceof LeftClickAction) {
Point location = ((MoveAction) action).getLocation();
List<Widget> foundWidgets = StateController.getWidgetsAt(location);
if (!foundWidgets.isEmpty()) {
for (Widget w : foundWidgets) {
if (w.getWidgetVisibility() == Widget.WidgetVisibility.VISIBLE && w.getWidgetStatus() == Widget.WidgetStatus.LOCATED && w.getWidgetType() == Widget.WidgetType.ACTION) {
int findWidgetIterations;
try {
findWidgetIterations = Integer.parseInt(keyBindings.getProperty("widgetfindretries","5"));
} catch (NumberFormatException e) {
LOGGER.warning("Int parse error in widgetfindretries");
findWidgetIterations = 5;
}
for(int i = 0; i < findWidgetIterations; i++) {
if(performImageWidget(w)) {
StateController.setCurrentState(w.getNextState());
break;
}
else {
LOGGER.info("Fail, retry after sleep.");
sleepForAmountMS(400);
}
}
break; // Only perform one action widget in a stack.
} else if (w.getWidgetVisibility() == Widget.WidgetVisibility.VISIBLE && w.getWidgetStatus() == Widget.WidgetStatus.UNLOCATED) {
String fileName = (String) w.getMetadata("IR_imageName");
BufferedImage widgetImage = EYE.loadImage(getProjectFileLocationForName(fileName));
if(widgetImage != null)
displayImageFrame(w, widgetImage);
else
LOGGER.info("Stored file path [" + fileName + "] returned null for image.");
}
}
} // else
// Do nothing, did not click on a widget.
}
else if (action instanceof DragStartAction && isControlClicked) {
if(dragStartPoint == null)
dragStartPoint = ((MoveAction)action).getLocation();
else
LOGGER.info("DragStartPoint wasn't null...");
}
else if (action instanceof DragAction) {
if(isControlClicked){
dragCurrentPoint = ((MoveAction)action).getLocation();
}
else{
dragCurrentPoint = null;
dragStartPoint = null;
}
}
else if (action instanceof DragDropAction && isControlClicked) {
if(System.currentTimeMillis() < mayInsertDragDrop + 500)
return;
long startInsert = System.nanoTime();
mayInsertDragDrop = System.currentTimeMillis(); // Blocking variable to prevent multiple inserts.
// Get sub-image of screenshot
Rectangle area = getRectangleFromPoints(dragStartPoint, dragCurrentPoint, false);
BufferedImage find = getWidgetImage(area);
if (find != null) {
// Locate the sub-image for verification purposes
Match match = EYE.findImage(currentScreenshot, find);
if(match != null && match.getMatchPercent() >= minimumMatchPercent) {
// Add widget
if(!createAndAddWidget(match, find)) {
StateController.displayMessage("Failed to add widget?", 1000);
LOGGER.warning("Failed to add widget from rectangle even if match != null?");
}
else
LOGGER.info("Inserted widget, it took [" + ((System.nanoTime() - startInsert) / ONE_MILLION) + "ms]");
}
else if(match != null) {
LOGGER.info("DragDrop: Match was not null, but match percent was [" + match.getMatchPercent() + "]");
}
else {
LOGGER.info("DragDrop: Match was null on rectangle!");
}
}
// null out the drag points as the action is completed
dragStartPoint = null;
dragCurrentPoint = null;
} else if (action instanceof MouseScrollAction) {
MouseScrollAction mouseScrollAction = (MouseScrollAction) action;
StateController.setSelectedWidgetNo(StateController.getSelectedWidgetNo() + mouseScrollAction.getRotation());
} else {
LOGGER.finest("Error in handling action [" + action.toString() +"]");
}
}
/**
* Helper method to display an image in a window.
* @param widgetImage The {@link java.awt.image.BufferedImage BufferedImage} to display.
*/
private void displayImageFrame(Widget w,BufferedImage widgetImage) {
JFrame imageFrame = new JFrame();
JLabel image = new JLabel(new ImageIcon(widgetImage));
JButton repairBtn = new JButton("Repair");
repairBtn.setSize(40,40);
repairBtn.addActionListener( x -> attemptRepairWidget(imageFrame,w));
GridBagConstraints gbc = new GridBagConstraints();
imageFrame.setLayout(new GridBagLayout());