org.sikuli.basics.Settings Java Examples

The following examples show how to use org.sikuli.basics.Settings. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Region.java    From SikuliX1 with MIT License 6 votes vote down vote up
/**
 * waits until target vanishes or timeout (in seconds) is passed
 *
 * @param <PSI>   Pattern, String or Image
 * @param target  Pattern, String or Image
 * @param timeout time in seconds
 * @return true if target vanishes, false otherwise and if imagefile is missing.
 */
public <PSI> boolean waitVanish(PSI target, double timeout) {
  if (Settings.NewAPI) { //TODO waitVanish()
    return super.waitVanish(target, timeout);
  }
  RepeatableVanish rv = new RepeatableVanish(target);
  Image img = rv._image;
  String targetStr = img.getName();
  Boolean response = true;
  if (!img.isValid()) {
    response = handleImageMissing(img, false);//waitVanish
  }
  if (null != response && response) {
    log(logLevel, "waiting for " + targetStr + " to vanish within %.1f secs", timeout);
    if (rv.repeat(timeout)) {
      log(logLevel, "%s vanished", targetStr);
      return true;
    }
    log(logLevel, "%s did not vanish before timeout", targetStr);
    return false;
  }
  return false;
}
 
Example #2
Source File: ElementRegionOldTest.java    From SikuliX1 with MIT License 6 votes vote down vote up
@Test
public void test200_RegionFind() {
  testIntro(testBase);
  Assume.assumeFalse("Running headless - ignoring test", RunTime.isHeadless());
  Settings.NewAPI = false;
  Region reg = getDefaultRegion();
  Match match = null;
  try {
    match = reg.find(testName);
  } catch (FindFailed findFailed) {
  }
  if (null != match) {
    if (showImage) {
      match.highlight(2);
    }
  }
  testOutro("%s in %s is %s", testName, reg, match);
  Assert.assertTrue("Not found!", checkMatch(match, 0.95));
}
 
Example #3
Source File: ElementRegionOldTest.java    From SikuliX1 with MIT License 6 votes vote down vote up
@Test
public void test210_RegionFindTrans() {
  testIntro(testBase);
  Assume.assumeFalse("Running headless - ignoring test", RunTime.isHeadless());
  Settings.NewAPI = false;
  Region reg = getDefaultRegion();
  Match match = null;
  try {
    match = reg.find(testNameTrans);
  } catch (FindFailed findFailed) {
  }
  if (null != match) {
    if (showImage) {
      match.highlight(2);
    }
  }
  testOutro("%s in %s is %s", testName, reg, match);
  Assert.assertTrue("Not found!", checkMatch(match, 0.95));
}
 
Example #4
Source File: Guide.java    From SikuliX1 with MIT License 6 votes vote down vote up
public void focusBelow() {
  if (Settings.isMac()) {
    // TODO: replace this hack with a more robust method

    // Mac's hack to bring focus to the window directly underneath
    // this hack works on the assumption that the caller has
    // the input focus but no interaction area at the current
    // mouse cursor position
    // This hack does not work well with applications that
    // can receive mouse clicks without having the input focus
    // (e.g., finder, system preferences)
    //         robot.mousePress(InputEvent.BUTTON1_MASK);
    //         robot.mouseRelease(InputEvent.BUTTON1_MASK);

    // Another temporary hack to switch to the previous window on Mac
    robot.keyPress(KeyEvent.VK_META);
    robot.keyPress(KeyEvent.VK_TAB);
    robot.keyRelease(KeyEvent.VK_META);
    robot.keyRelease(KeyEvent.VK_TAB);

    // wait a little bit for the switch to complete
    robot.delay(1000);
  }

}
 
Example #5
Source File: JythonSupport.java    From SikuliX1 with MIT License 6 votes vote down vote up
public boolean prepareRobot() {
  if (runTime.isRunningFromJar()) {
    File fLibRobot = new File(runTime.fSikulixLib, "robot");
    if (!fLibRobot.exists()) {
      log(-1, "prepareRobot: not available: %s", fLibRobot);
      return false;
    }
    if (!hasSysPath(runTime.fSikulixLib.getAbsolutePath())) {
      insertSysPath(runTime.fSikulixLib);
    }
  }
  if (!hasSysPath(new File(Settings.BundlePath).getParent())) {
    appendSysPath(new File(Settings.BundlePath).getParent());
  }
  interpreterExecString("import robot");
  return true;
}
 
Example #6
Source File: RobotRunner.java    From SikuliX1 with MIT License 6 votes vote down vote up
@Override
protected void doInit(String[] args) {
  super.doInit(args);

  if (null != Settings.BundlePath) {
    jythonSupport.appendSysPath(new File(Settings.BundlePath).getParent());
  }
  try {
    jythonSupport.interpreterExecString("import robot");
  } catch (Exception e) {
    if (e.getClass().getSimpleName().contains("PyException")) {
      String pyException = e.toString();
      String[] trace = pyException.split("\n");
      String error = trace[trace.length - 1].trim();
      Debug.error(this.getName() + ": init: import robot: " + error);
    }
    throw e;
  }
}
 
Example #7
Source File: ScreenImage.java    From SikuliX1 with MIT License 6 votes vote down vote up
/**
 * stores the image as PNG file in the given path
 * with the given filename
 *
 * @param path valid path string
 * @param name filename (.png is added if not present)
 * @return absolute path to stored file
 */
public String getFile(String path, String name) {
  if (name == null) {
    name = Settings.getTimestamp() + ".png";
  } else if (!name.endsWith(".png")) {
    name += ".png";
  }
  try {
    File imageFile = new File(path, name);
    storeImage(imageFile);
    Debug.log(3, "ScreenImage.store: %s", imageFile);
  } catch (IOException iOException) {
    Debug.error("ScreenImage.store: IOException", iOException);
    return null;
  }
  return _filename;
}
 
Example #8
Source File: Recorder.java    From SikuliX1 with MIT License 6 votes vote down vote up
private static void unregisterNativeHook() {
  try {
    /*
     * We unregister the native hook on Windows because it blocks some special keys
     * in AWT while registered (e.g. AltGr).
     *
     * We do not unregister on Linux because this terminates the whole JVM.
     * Interestingly, the special keys are not blocked on Linux at all.
     *
     * TODO: Has to be checked on Mac OS, but I guess that not unregistering is
     * the better option here.
     *
     * Re-registering doesn't hurt anyway, because JNativeHook checks the register
     * state before registering again. So unregister is only really needed on Windows.
     */
    if (Settings.isWindows()) {
      GlobalScreen.unregisterNativeHook();
    }
  } catch (NativeHookException e) {
    Debug.error("Error unregistering native hook: %s", e.getMessage());
  }
}
 
Example #9
Source File: RobotDesktop.java    From SikuliX1 with MIT License 6 votes vote down vote up
private void doKeyRelease(int keyCode) {
  logRobot(stdAutoDelay, "KeyRelease: WaitForIdle: %s - Delay: %d");
  setAutoDelay(stdAutoDelay);
  // on Windows we detect the current layout in KeyboardLayout.
  // Since this layout is not compatible to AWT Robot, we have to use
  // the User32 API to simulate the key release
  if (Settings.AutoDetectKeyboardLayout && Settings.isWindows()) {
    int scanCode =  SXUser32.INSTANCE.MapVirtualKeyW(keyCode, 0);
    SXUser32.INSTANCE.keybd_event((byte)keyCode, (byte)scanCode, new WinDef.DWORD(WinUser.KEYBDINPUT.KEYEVENTF_KEYUP), new BaseTSD.ULONG_PTR(0));
  }else{
    keyRelease(keyCode);
  }

  if (stdAutoDelay == 0) {
    delay(stdDelay);
  }
  logRobot("KeyRelease: extended delay: %d", stdMaxElapsed);
}
 
Example #10
Source File: RobotDesktop.java    From SikuliX1 with MIT License 6 votes vote down vote up
@Override
public void typeKey(int key) {
  Debug.log(4, "Robot: doType: %s ( %d )", KeyEvent.getKeyText(key), key);
  if (Settings.isMac()) {
    if (key == Key.toJavaKeyCodeFromText("#N.")) {
      doType(KeyMode.PRESS_ONLY, Key.toJavaKeyCodeFromText("#C."));
      doType(KeyMode.PRESS_RELEASE, key);
      doType(KeyMode.RELEASE_ONLY, Key.toJavaKeyCodeFromText("#C."));
      return;
    } else if (key == Key.toJavaKeyCodeFromText("#T.")) {
      doType(KeyMode.PRESS_ONLY, Key.toJavaKeyCodeFromText("#C."));
      doType(KeyMode.PRESS_ONLY, Key.toJavaKeyCodeFromText("#A."));
      doType(KeyMode.PRESS_RELEASE, key);
      doType(KeyMode.RELEASE_ONLY, Key.toJavaKeyCodeFromText("#A."));
      doType(KeyMode.RELEASE_ONLY, Key.toJavaKeyCodeFromText("#C."));
      return;
    } else if (key == Key.toJavaKeyCodeFromText("#X.")) {
      key = Key.toJavaKeyCodeFromText("#T.");
      doType(KeyMode.PRESS_ONLY, Key.toJavaKeyCodeFromText("#A."));
      doType(KeyMode.PRESS_RELEASE, key);
      doType(KeyMode.RELEASE_ONLY, Key.toJavaKeyCodeFromText("#A."));
      return;
    }
  }
  doType(KeyMode.PRESS_RELEASE, key);
}
 
Example #11
Source File: RobotDesktop.java    From SikuliX1 with MIT License 6 votes vote down vote up
private void checkMousePosition(Location p) {
  PointerInfo mp = MouseInfo.getPointerInfo();
  Point pc;
  if (mp == null) {
    Debug.error("RobotDesktop: checkMousePosition: MouseInfo.getPointerInfo invalid\nafter move to %s", p);
  } else {
    pc = mp.getLocation();
    if (pc.x != p.x || pc.y != p.y) {
      if (isMouseInitialized) {
        if (Settings.checkMousePosition) {
          Debug.error("RobotDesktop: checkMousePosition: should be %s\nbut after move is %s"
                          + "\nPossible cause in case you did not touch the mouse while script was running:\n"
                          + " Mouse actions are blocked generally or by the frontmost application."
                          + (Settings.isWindows() ? "\nYou might try to run the SikuliX stuff as admin." : ""),
                  p, new Location(pc));
        }
      }
    }
  }
  if (!isMouseInitialized) {
    isMouseInitialized = true;
  }
}
 
Example #12
Source File: Finder.java    From SikuliX1 with MIT License 6 votes vote down vote up
/**
 * do a findAll op with the given image in the Finder's image
 * (hasNext() and next() will reveal possible match results)
 *
 * @param img Image
 * @return null. if find setup not possible
 */
public String findAll(Image img) {
  if (img.isValid()) {
    _image = img;
    _findInput.setTarget(possibleImageResizeOrCallback(img));
    _findInput.setSimilarity(Settings.MinSimilarity);
    _findInput.setFindAll();
    Debug timing = Debug.startTimer("Finder.findAll");
    _results = Finder2.find(_findInput);
    //currentMatchIndex = 0;
    timing.end();
    return img.getFilename();
  } else {
    return null;
  }
}
 
Example #13
Source File: Finder.java    From SikuliX1 with MIT License 6 votes vote down vote up
private Mat possibleImageResizeOrCallback(Image img, float oneTimeResize) {
  double factor = oneTimeResize;
  if (factor == 0 && Settings.AlwaysResize > 0 && Settings.AlwaysResize != 1) {
    factor = Settings.AlwaysResize;
  }
  Mat mat = SXOpenCV.makeMat(img.getBufferedImage(), false);
  if (factor > 0 && factor != 1) {
    Debug.log(3, "Finder::possibleImageResizeOrCallback: resize");
    if (!mat.empty()) {
      SXOpenCV.resize(mat, factor);
    }
  } else if (Settings.ImageCallback != null) {
    Debug.log(3, "Finder::possibleImageResizeOrCallback: callback");
    BufferedImage newBimg = Settings.ImageCallback.callback(img);
    mat = SXOpenCV.makeMat(newBimg, false);
  }
  if (mat.empty()) {
    log(-1, "%s: conversion error --- find will fail", img);
  }
  return mat;
}
 
Example #14
Source File: Region.java    From SikuliX1 with MIT License 6 votes vote down vote up
/**
 * finalize a drag action with a drop: move mouse to given target.
 * <br> wait Settings.DelayBeforeDrop before releasing the left mouse button
 *
 * @param <PFRML> Pattern, Filename, Text, Region, Match or Location
 * @param target  Pattern, Filename, Text, Region, Match or Location
 * @return 1 if possible, 0 otherwise
 * @throws FindFailed if not found
 */
public <PFRML> int dropAt(PFRML target) throws FindFailed {
  Location loc = getLocationFromTarget(target);
  int retVal = 0;
  if (loc != null) {
    IRobot r = loc.getRobotForPoint("drag");
    if (r != null) {
      Mouse.use(this);
      r.smoothMove(loc);
      r.delay((int) (Settings.DelayBeforeDrop * 1000));
      r.mouseUp(InputEvent.BUTTON1_MASK);
      r.waitForIdle();
      Mouse.let(this);
      retVal = 1;
    }
  }
  Settings.DelayBeforeMouseDown = Settings.DelayValue;
  Settings.DelayAfterDrag = Settings.DelayValue;
  Settings.DelayBeforeDrag = -Settings.DelayValue;
  Settings.DelayBeforeDrop = Settings.DelayValue;
  return retVal;
}
 
Example #15
Source File: ScreenKeywords.java    From robotframework-SikuliLibrary with Apache License 2.0 6 votes vote down vote up
private Pattern getPattern(String locator) {
    /**
     * Parse locator string. It can be either of the following:
     * - Image.png
     * - Text
     * - Image.png = 0.9
     * This will return pattern and similarity by parsing above.
     */
    Pattern pattern = null;
    if (locator.contains(".png")) {
        if (locator.contains("=")) {
            locator = locator.replace(" ", "");
            pattern = new Pattern(locator.substring(0, locator.indexOf("="))).similar(Float.parseFloat(locator.substring(locator.indexOf("=") + 1)));
        } else {
            pattern = new Pattern(locator).similar((float)Settings.MinSimilarity);
        }
    } else {
        pattern = new Pattern(locator);
    }



    return pattern;
}
 
Example #16
Source File: ElementRegionOldTest.java    From SikuliX1 with MIT License 6 votes vote down vote up
@Test
public void test211_RegionFindMask() {
  testIntro(testBase);
  Assume.assumeFalse("Running headless - ignoring test", RunTime.isHeadless());
  Settings.NewAPI = false;
  Region reg = getDefaultRegion();
  Match match = null;
  try {
    Image imageMasked = new Image(testName).mask(testNameMask);
    match = reg.find(imageMasked);
  } catch (FindFailed findFailed) {
  }
  if (null != match) {
    if (showImage) {
      match.highlight(2);
    }
  }
  testOutro("%s in %s is %s", testName, reg, match);
  Assert.assertTrue("Not found!", checkMatch(match, 0.95));
}
 
Example #17
Source File: SXTest.java    From SikuliX1 with MIT License 5 votes vote down vote up
public void startUpBase() {
  if (!RunTime.isHeadless()) {
    Region region = new Region(100, 200, 300, 400);
    Image image = new Image(region);
  }
  useScreen = false;
  showImage = false;
  Settings.ProfileLogs = false;
}
 
Example #18
Source File: Highlight.java    From SikuliX1 with MIT License 5 votes vote down vote up
private JPanel initAsFrame() {
  int lineWidth = 3;
  frameX = locx - lineWidth;
  frameY = locy - lineWidth;
  int frameW = sidey + 2 * lineWidth;
  int frameH = sidex + 2 * lineWidth;
  setSize(frameW, frameH);
  if (Settings.HighlightTransparent) {
    return null;
  }
  JPanel panel = new JPanel() {
    @Override
    protected void paintComponent(Graphics g) {
      if (g instanceof Graphics2D) {
        Point2D.Float center = new Point2D.Float(frameW / 2.0f, frameH / 2.0f);
        Color colorFull = getColor();
        Color colorTrans = new Color(colorFull.getRed(), colorFull.getGreen(), colorFull.getBlue(), 0);
        float radius = Math.max(center.x, center.y);
        float[] dist = {0.0f, 1.0f};
        Color[] colors = {colorTrans, colorFull};
        Graphics2D g2d = (Graphics2D) g;
        g2d.setPaint(new RadialGradientPaint(center, radius, dist, colors));
        g2d.fillRect(0, 0, frameW, frameH);
      }
    }
  };
  panel.setBorder(BorderFactory.createLineBorder(givenColor, 3));
  return panel;
}
 
Example #19
Source File: Observer.java    From SikuliX1 with MIT License 5 votes vote down vote up
private <PSC> double getSimiliarity(PSC ptn) {
  double similarity = -1;
  if (ptn instanceof Pattern) {
    similarity = ((Pattern) ptn).getSimilar();
  }
  if (similarity < 0) {
    similarity = Settings.MinSimilarity;
  }
  return similarity;
}
 
Example #20
Source File: FindAttributes.java    From SikuliX1 with MIT License 5 votes vote down vote up
private Mat possibleImageResizeOrCallback(Image image, Mat what) {
  Mat originalContent = what;
  if (Settings.ImageCallback != null) {
    Mat contentResized = SXOpenCV.makeMat(Settings.ImageCallback.callback(image), false);
    if (!contentResized.empty()) {
      return contentResized;
    }
  } else {
    double factor = image.resize() == 1 ? Settings.AlwaysResize : image.resize();
    if (factor > 0.1 && factor != 1) {
      return SXOpenCV.cvResize(originalContent.clone(), factor, Image.Interpolation.CUBIC);
    }
  }
  return originalContent;
}
 
Example #21
Source File: SXTest.java    From SikuliX1 with MIT License 5 votes vote down vote up
public void setUpBase() {
  Settings.NewAPI = true;
  Settings.AlwaysResize = 1;
  Settings.CheckLastSeen = false;
  if (null == bundlePath) {
    setUpTime = new Date().getTime();
    File bundleFile = new File(runTime.fWorkDir, "src/main/resources/images");
    ImagePath.setBundleFolder(bundleFile);
    bundlePath = ImagePath.getBundlePath();
    setUpTime = new Date().getTime() - setUpTime;
  }
}
 
Example #22
Source File: RobotDesktop.java    From SikuliX1 with MIT License 5 votes vote down vote up
private void doKeyPress(int keyCode) {
  Highlight fakeHighlight = null;
  if (RunTime.get().needsRobotFake()) {
    fakeHighlight = Highlight.fakeHighlight();
  }
  logRobot(stdAutoDelay, "KeyPress: WaitForIdle: %s - Delay: %d");
  setAutoDelay(stdAutoDelay);
  if (null != fakeHighlight) {
    delay(20);
    fakeHighlight.close();
    delay(20);
  }

  // on Windows we detect the current layout in KeyboardLayout.
  // Since this layout is not compatible to AWT Robot, we have to use
  // the User32 API to simulate the key press
  if (Settings.AutoDetectKeyboardLayout && Settings.isWindows()) {
      int scanCode =  SXUser32.INSTANCE.MapVirtualKeyW(keyCode, 0);
      SXUser32.INSTANCE.keybd_event((byte)keyCode, (byte)scanCode, new WinDef.DWORD(0), new BaseTSD.ULONG_PTR(0));
  }else{
    keyPress(keyCode);
  }


  if (stdAutoDelay == 0) {
    delay(stdDelay);
  }
  logRobot("KeyPress: extended delay: %d", stdMaxElapsed);
}
 
Example #23
Source File: Region.java    From SikuliX1 with MIT License 5 votes vote down vote up
/**
 * Drag from a position and drop to another using left mouse button.
 * <br>applying Settings.DelayAfterDrag and DelayBeforeDrop
 *
 * @param <PFRML> Pattern, Filename, Text, Region, Match or Location
 * @param t1      source position
 * @param t2      destination position
 * @return 1 if possible, 0 otherwise
 * @throws FindFailed if the Find operation failed
 */
public <PFRML> int dragDrop(PFRML t1, PFRML t2) throws FindFailed {
  Location loc1 = getLocationFromTarget(t1);
  Location loc2 = getLocationFromTarget(t2);
  int retVal = 0;
  if (loc1 != null && loc2 != null) {
    IRobot r1 = loc1.getRobotForPoint("drag");
    IRobot r2 = loc2.getRobotForPoint("drop");
    if (r1 != null && r2 != null) {
      Mouse.use(this);
      r1.smoothMove(loc1);
      r1.delay((int) (Settings.DelayBeforeMouseDown * 1000));
      r1.mouseDown(InputEvent.BUTTON1_MASK);
      double DelayBeforeDrag = Settings.DelayBeforeDrag;
      if (DelayBeforeDrag < 0.0) {
        DelayBeforeDrag = Settings.DelayAfterDrag;
      }
      r1.delay((int) (DelayBeforeDrag * 1000));
      r2.smoothMove(loc2);
      r2.delay((int) (Settings.DelayBeforeDrop * 1000));
      r2.mouseUp(InputEvent.BUTTON1_MASK);
      Mouse.let(this);
      retVal = 1;
    }
  }
  Settings.DelayBeforeMouseDown = Settings.DelayValue;
  Settings.DelayAfterDrag = Settings.DelayValue;
  Settings.DelayBeforeDrag = -Settings.DelayValue;
  Settings.DelayBeforeDrop = Settings.DelayValue;
  return retVal;
}
 
Example #24
Source File: ElementImageTest.java    From SikuliX1 with MIT License 5 votes vote down vote up
@Test
  public void test090_ImageFindResizeUp() {
    testIntro();
    Image shot = new Image(testBaseX2);
    Assert.assertTrue("", shot.isValid());
    Match match = null;
    Settings.AlwaysResize = 2;
    try {
      match = shot.find(testName);
    } catch (FindFailed findFailed) {
    }
//    Image.resetCache();
    testOutro("%s in %s is %s", testName, shot, match);
    Assert.assertNotNull(testName + " not found in " + testBaseX2, match);
  }
 
Example #25
Source File: Region.java    From SikuliX1 with MIT License 5 votes vote down vote up
public List<Match> findAnyList(List<Object> pList) {
  if (Settings.NewAPI) { //TODO findAny(List)
    return super.findAnyList(pList);
  }
  Debug.log(logLevel, "findAny: enter");
  if (pList == null || pList.size() == 0) {
    return new ArrayList<Match>();
  }
  List<Match> mList = findAnyCollect(pList);
  return mList;
}
 
Example #26
Source File: Region.java    From SikuliX1 with MIT License 5 votes vote down vote up
public List<Match> findAny(Object... args) {
  if (Settings.NewAPI) { //TODO findAny(Object...)
    return super.findAny(args);
  }
  if (args.length == 0) {
    return new ArrayList<Match>();
  }
  List<Object> pList = new ArrayList<>();
  pList.addAll(Arrays.asList(args));
  return findAnyList(pList);
}
 
Example #27
Source File: Region.java    From SikuliX1 with MIT License 5 votes vote down vote up
/**
   * finds all occurences of the given Pattern, String or Image in the region and returns an Iterator of Matches.
   *
   * @param <PSI>  Pattern, String or Image
   * @param target A search criteria
   * @return All elements matching
   * @throws FindFailed if the Find operation failed
   */
  public <PSI> Matches findAll(PSI target) throws FindFailed {
//  public <PSI> Iterator<Match> findAll(PSI target) throws FindFailed {
    if (Settings.NewAPI) { //TODO findAll()
      return super.findAll(target);
    }
    lastMatches = null;
    RepeatableFindAll rf = new RepeatableFindAll(target, null);
    Image img = rf._image;
    String targetStr = img.getName();
    Boolean response = true;
    if (!img.isValid()) {
      response = handleImageMissing(img, false);//findAll
      if (response == null) {
        throw new RuntimeException(String.format("SikuliX: findAll: ImageMissing: %s", target));
      }
    }
    while (null != response && response) {
      log(logLevel, "findAll: waiting %.1f secs for (multiple) %s to appear in %s",
              getAutoWaitTimeout(), targetStr, this.toStringShort());
      if (getAutoWaitTimeout() > 0) {
        rf.repeat(getAutoWaitTimeout());
        lastMatches = rf.getMatches();
      } else {
        lastMatches = doFindAll(target, null);
      }
      if (lastMatches != null) {
        log(logLevel, "findAll: %s has appeared", targetStr);
        break;
      } else {
        log(logLevel, "findAll: %s did not appear", targetStr);
        response = handleFindFailed(target, img);
      }
    }
    if (null == response) {
      throw new FindFailed(FindFailed.createErrorMessage(this, img));
    }
    return lastMatches;
  }
 
Example #28
Source File: Region.java    From SikuliX1 with MIT License 5 votes vote down vote up
private Finder doCheckLastSeenAndCreateFinder(ScreenImage base, Image img, double findTimeout, Pattern ptn) {
  if (base == null) {
    base = getScreen().capture(this);
  }
  boolean shouldCheckLastSeen = false;
  double score = 0;
  if (Settings.CheckLastSeen && null != img.getLastSeen()) {
    score = img.getLastSeenScore() - 0.01;
    if (ptn != null) {
      if (!(ptn.getSimilar() > score)) {
        shouldCheckLastSeen = true;
      }
    }
  }
  if (shouldCheckLastSeen) {
    Region r = Region.create(img.getLastSeen());
    if (this.contains(r)) {
      Finder f = new Finder(base.getSub(r.getRect()), r);
      if (Debug.shouldHighlight()) {
        if (getScreen().getW() > w + 10 && getScreen().getH() > h + 10) {
          highlight(2, "#000255000");
        }
      }

      if (ptn == null) {
        f.find(new Pattern(img).similar(score));
      } else {
        f.find(new Pattern(ptn).similar(score));
      }
      if (f.hasNext()) {
        log(logLevel, "checkLastSeen: still there");
        return f;
      }
      log(logLevel, "checkLastSeen: not there");
    }
  }
  return new Finder(base, this);
}
 
Example #29
Source File: Region.java    From SikuliX1 with MIT License 5 votes vote down vote up
/**
 * Check if target exists with a specified timeout.
 * <br>
 * timout = 0: returns immediately after first search,
 * does not raise FindFailed
 *
 * @param <PSI>   Pattern, String or Image
 * @param target  The target to search for
 * @param timeout Timeout in seconds
 * @return the match (null if not found or image file missing)
 */
public <PSI> Match exists(PSI target, double timeout) {
  if (Settings.NewAPI) { //TODO exists()
    return super.exists(target, timeout);
  }
  lastMatch = null;
  RepeatableFind rf = new RepeatableFind(target, null);
  Image img = rf._image;
  Boolean response = true;
  if (!img.isText() && !img.isValid()) {
    response = handleImageMissing(img, false);//exists
    if (response == null) {
      if (Settings.SwitchToText) {
        log(logLevel, "Exists: image missing: switching to text search (deprecated - use text methods)");
        response = true;
        img.asText(true);
        rf.setTarget("\t" + target + "\t");
      } else {
        throw new RuntimeException(String.format("SikuliX: exists: ImageMissing: %s", target));
      }
    }
  }
  String targetStr = img.getName();
  log(logLevel, "exists: waiting %.1f secs for %s to appear in %s", timeout, targetStr, this.toStringShort());
  if (rf.repeat(timeout)) {
    lastMatch = rf.getMatch();
    //lastMatch.setImage(img);
    if (isOtherScreen()) {
      lastMatch.setOtherScreenOf(this);
    } else if (img != null) {
      img.setLastSeen(lastMatch.getRect(), lastMatch.score());
    }
    log(logLevel, "exists: %s has appeared (%s)", targetStr, lastMatch);
    return lastMatch;
  }
  log(logLevel, "exists: %s did not appear [%d msec]", targetStr, new Date().getTime() - lastFindTime);
  return null;
}
 
Example #30
Source File: Highlight.java    From SikuliX1 with MIT License 5 votes vote down vote up
public Highlight doShow(double secs) {
  if (isShowable()) {
    setLocation(frameX, frameY);
    addMouseListener(new MouseAdapter() {
      @Override
      public void mouseReleased(MouseEvent e) {
        setVisible(false);
        dispose();
      }
    });
    synchronized (Highlight.class) {
      if (!highlights.contains(this)) {
        highlights.add(this);
      }
    }
    SwingUtilities.invokeLater(new Runnable() {
      @Override
      public void run() {
        setVisible(true);
      }
    });
    if (secs > 0) {
      try {
        Thread.sleep((int) (1000 * (secs + Settings.WaitAfterHighlight)));
      } catch (InterruptedException ex) {
      }
      close();
    }
  }
  return this;
}