Skip to content

[Java] FPS support for local grid using bidi #236

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion visual-java/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.10.0</version>
<version>4.32.0</version>
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is breaking, as newer versions of Selenium (4.12+ IIRC) have dropped support for Java 8 so our build step will fail.

<scope>provided</scope>
</dependency>
<dependency>
Expand Down
149 changes: 109 additions & 40 deletions visual-java/src/main/java/com/saucelabs/visual/VisualApi.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
import com.saucelabs.visual.utils.*;
import dev.failsafe.Failsafe;
import dev.failsafe.RetryPolicy;
import java.awt.image.BufferedImage;
import java.lang.reflect.Field;
import java.net.URL;
import java.time.Duration;
Expand All @@ -24,6 +23,8 @@
import java.util.stream.Collectors;
import org.apache.http.client.config.RequestConfig;
import org.openqa.selenium.*;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContext;
import org.openqa.selenium.bidi.browsingcontext.CaptureScreenshotParameters;
import org.openqa.selenium.remote.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Expand Down Expand Up @@ -617,36 +618,53 @@ public <D> D execute(GraphQLOperation operation, Class<D> responseType) {
}

private String sauceVisualCheckLocal(String snapshotName, CheckOptions options) {
Capabilities caps = driver.getCapabilities();
Window window = new Window(this.driver);
Rectangle viewport = window.getViewport();

byte[] screenshot;

// clip image if required
Map<String, Object> windowDims =
(Map<String, Object>)
driver.executeScript(
"return { height: window.innerHeight, width: window.innerWidth, dpr: window.devicePixelRatio }");
double devicePixelRatio = formatDevicePixelRatio(windowDims.get("dpr"));
boolean fullPage = options.getFullPageScreenshotConfig() != null;
WebElement clipElement = getClipElement(options);
Point scrollOffset = fullPage ? new Point(0, 0) : window.getViewport().getPoint();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does it make sense to set scrollOffset to window.getViewport().getPoint() if clipElement == null (i.e. as an else statement after if (clipElement != null))? I think it is always overriden if clipElement is not null.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think that'd be necessary since the default is set here (and we'd just be overriding it in the else).

And that's correct on clip front -- at least for non full page screenshots. We will always attempt to scroll the element into view so we update the position here after that call.

Point clipOffset = new Point(0, 0);
Rectangle clipRect = null;

if (clipElement != null) {
Rectangle clipRect = clipElement.getRect();
Rectangle clipElementDims = scrollToAndGetClipElementDims(fullPage, clipElement);

// Scroll to the clipped element
Rectangle newViewport = window.scrollTo(clipRect.getPoint());
screenshot = driver.getScreenshotAs(OutputType.BYTES);
if (!fullPage) {
scrollOffset = window.getViewport().getPoint();
}

// Restore the original scroll
window.scrollTo(viewport.getPoint());
clipRect =
new Rectangle(
(int) Math.round(clipElementDims.getX() * devicePixelRatio),
(int) Math.round(clipElementDims.getY() * devicePixelRatio),
(int) Math.round(clipElementDims.getHeight() * devicePixelRatio),
(int) Math.round(clipElementDims.getWidth() * devicePixelRatio));
Comment on lines +641 to +646
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I feel like this should belong in a helper of some sort, or at least a function in this class.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For what reason? It's only 4 lines, and those lines are pretty readable.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess... it's just that this function is growing very quickly.


Optional<Rectangle> cropRect = CartesianHelpers.intersect(clipRect, newViewport);
if (!cropRect.isPresent()) {
clipOffset = new Point(clipElementDims.getX(), clipElementDims.getY());
}

byte[] screenshot = getScreenshot(fullPage);

// Handle clipping, if rect is present
if (clipRect != null) {
Dimension imageDims = ImageHelpers.getImageDimensions(screenshot);
// bound the clip rect to the image bounds so there is no outside of bounds exception
Optional<Rectangle> offsetRect =
CartesianHelpers.intersect(clipRect, new Rectangle(new Point(0, 0), imageDims));

if (offsetRect.isPresent()) {
screenshot =
ImageHelpers.saveImage(
ImageHelpers.cropImage(ImageHelpers.loadImage(screenshot), offsetRect.get()),
"png");
} else {
throw new VisualApiException("Clipping would result in an empty image");
}

BufferedImage image = ImageHelpers.loadImage(screenshot);
BufferedImage cropped =
ImageHelpers.cropImage(
image, CartesianHelpers.relativeTo(newViewport.getPoint(), cropRect.get()));
screenshot = ImageHelpers.saveImage(cropped, "png");
viewport = cropRect.get();
} else {
screenshot = driver.getScreenshotAs(OutputType.BYTES);
}

// create upload and get urls
Expand All @@ -663,19 +681,30 @@ private String sauceVisualCheckLocal(String snapshotName, CheckOptions options)
Optional.ofNullable(options.getIgnoreElements()).orElse(Collections.emptyList())));
ignoreRegions.addAll(extractIgnoreSelectors(options));

// get adjusted screenshot dimensions
Dimension imageDims = ImageHelpers.getImageDimensions(screenshot);
Rectangle imageDimsDpr =
new Rectangle(
new Point(0, 0),
new Dimension(
(int) Math.round(imageDims.getWidth() / devicePixelRatio),
(int) Math.round(imageDims.getHeight() / devicePixelRatio)));
String deviceName =
String.format("Desktop (%sx%s)", windowDims.get("width"), windowDims.get("height"));

// make regions relative to viewport
List<RegionIn> visibleIgnoreRegions = new ArrayList<>();
for (RegionIn region : ignoreRegions) {
// Update the offset to all ignore regions
Point newPoint =
CartesianHelpers.relativeTo(clipOffset, new Point(region.getX(), region.getY()));
region.setX(newPoint.x - scrollOffset.getX());
region.setY(newPoint.y - scrollOffset.getY());

Rectangle regionRect =
new Rectangle(region.getX(), region.getY(), region.getHeight(), region.getWidth());

if (CartesianHelpers.intersect(regionRect, viewport).isPresent()) {
Point newPoint =
CartesianHelpers.relativeTo(
viewport.getPoint(), new Point(region.getX(), region.getY()));
region.setX(newPoint.x);
region.setY(newPoint.y);

// Only add it if the region is visible inside the new image
if (CartesianHelpers.intersect(regionRect, imageDimsDpr).isPresent()) {
visibleIgnoreRegions.add(region);
}
}
Expand All @@ -695,22 +724,14 @@ private String sauceVisualCheckLocal(String snapshotName, CheckOptions options)
}
}

Capabilities caps = driver.getCapabilities();

Map<String, Object> dims =
(Map<String, Object>)
driver.executeScript(
"return { height: window.innerHeight, width: window.innerWidth, dpr: window.devicePixelRatio }");
String deviceName = String.format("Desktop (%sx%s)", dims.get("width"), dims.get("height"));

// create snapshot using upload id
CreateSnapshotMutation snapshotMutation =
new CreateSnapshotMutation(
SnapshotIn.builder()
.withBrowser(CapabilityUtils.getBrowser(caps))
.withBrowserVersion(caps.getBrowserVersion())
.withDevice(deviceName)
.withDevicePixelRatio(formatDevicePixelRatio(dims.get("dpr")))
.withDevicePixelRatio(devicePixelRatio)
.withOperatingSystem(CapabilityUtils.getOperatingSystem(caps))
.withUploadId(uploadResult.getId())
.withBuildId(this.build.getId())
Expand All @@ -734,6 +755,54 @@ private String sauceVisualCheckLocal(String snapshotName, CheckOptions options)
return result.result.getId();
}

private byte[] getScreenshot(boolean fullPage) {
if (fullPage) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Have you tested it across all major browsers and with various websites?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

BiDi is not currently supported in Safari, but it depends on our target use case whether that might be okay. Otherwise, Diego said this works across Firefox and chromium based browsers.

BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
CaptureScreenshotParameters csp = new CaptureScreenshotParameters();
csp.origin(CaptureScreenshotParameters.Origin.DOCUMENT);
String screenshot = browsingContext.captureScreenshot(csp);
return OutputType.BYTES.convertFromBase64Png(screenshot);
}

return driver.getScreenshotAs(OutputType.BYTES);
}

/**
* Query the browser for the dimensions and offset of the current clip element after scrolling to
* it, if applicable.
*/
private Rectangle scrollToAndGetClipElementDims(boolean fullPage, WebElement clipElement) {
final String getElementDimensions =
"const [clipElement, isFullPage] = arguments;\n"
+ " if (!isFullPage) {\n"
+ " clipElement.scrollIntoView({\n"
+ " behavior: 'instant',\n"
+ " });\n"
+ " }\n"
+ " const rect = clipElement.getBoundingClientRect().toJSON();\n"
+ " return isFullPage ? {\n"
+ " // FPS should use original coordinates of element on page\n"
+ " width: Math.round(rect.width),\n"
+ " height: Math.round(rect.height),\n"
+ " x: Math.round(rect.x + window.scrollX),\n"
+ " y: Math.round(rect.y + window.scrollY),\n"
+ " } : {"
+ " width: Math.round(rect.width),\n"
+ " height: Math.round(rect.height),\n"
+ " x: Math.round(rect.x),\n"
+ " y: Math.round(rect.y),\n"
+ " };";

Map<String, Long> clipMap =
(Map<String, Long>) driver.executeScript(getElementDimensions, clipElement, fullPage);

return new Rectangle(
clipMap.get("x").intValue(),
clipMap.get("y").intValue(),
clipMap.get("height").intValue(),
clipMap.get("width").intValue());
}

/** Parse the Selenium parsed value from window.devicePixelRatio into a Double for our API */
private double formatDevicePixelRatio(Object rawDpr) {
double dpr = 1.0;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.Rectangle;

public class ImageHelpers {
Expand All @@ -31,4 +32,9 @@ public static byte[] saveImage(BufferedImage image, String imageFormat) {
throw new VisualApiException("Failed to save image to bytes", e);
}
}

public static Dimension getImageDimensions(byte[] image) {
BufferedImage bImage = loadImage(image);
return new Dimension(bImage.getWidth(), bImage.getHeight());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public Rectangle scrollTo(Point point) {
}

private final String jsViewportTupleSnippet =
"return [window.scrollX, window.scrollY, window.innerWidth, window.innerHeight];";
"return [Math.round(window.scrollX), Math.round(window.scrollY), Math.round(window.innerWidth), Math.round(window.innerHeight)];";

private Rectangle convertJsTupleToRectangle(Object result) {
if (!(result instanceof List<?>)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ public static void login() {
loginPage.login();
InventoryLongPage inventoryPage = new InventoryLongPage();
inventoryPage.open();
driver.executeScript("window.scrollTo(0, 0)");
}

final By ignoreSelectors = By.cssSelector(".inventory_item_img,.btn_inventory");
Expand All @@ -37,6 +38,20 @@ public void checkDefaultStandardIgnoreRegions() {
expect.toMatchSnapshot(result);
}

@Test
public void checkPositionRegionsWhenScrolledPrior() {
driver.executeScript("window.scrollBy(0, 100)");

String id =
sauceVisualCheck(
"Standard (scrolled)",
new CheckOptions.Builder()
.withIgnoreElements(driver.findElements(ignoreSelectors))
.build());
String result = getSnapshotResult(id);
expect.toMatchSnapshot(result);
}

@Test
public void checkPositionRegionsOnClippedSnapshot() {
String id =
Expand All @@ -50,6 +65,21 @@ public void checkPositionRegionsOnClippedSnapshot() {
expect.toMatchSnapshot(result);
}

@Test
public void checkPositionRegionsWhenScrolledPriorToClip() {
driver.executeScript("window.scrollBy(0, 100)");

String id =
sauceVisualCheck(
"Clipped (scrolled)",
new CheckOptions.Builder()
.withClipElement(driver.findElement(By.cssSelector(".inventory_list")))
.withIgnoreElements(driver.findElements(ignoreSelectors))
.build());
String result = getSnapshotResult(id);
expect.toMatchSnapshot(result);
}

@Test
public void checkPositionRegionsOnFPS() {
String id =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import org.openqa.selenium.MutableCapabilities;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.remote.RemoteWebDriver;

abstract class IntegrationBase {
Expand Down Expand Up @@ -59,7 +60,10 @@ public static void setUp() throws MalformedURLException {
Map<String, Object> sauceOptions = new HashMap<>();
sauceOptions.put("screenResolution", "1600x1200");
caps.setCapability("sauce:options", sauceOptions);
driver = isLocal ? new FirefoxDriver() : new RemoteWebDriver(getDriverUrl(), caps);
FirefoxOptions firefoxOptions = new FirefoxOptions();
firefoxOptions.setCapability("webSocketUrl", true);
driver =
isLocal ? new FirefoxDriver(firefoxOptions) : new RemoteWebDriver(getDriverUrl(), caps);
driver.manage().window().setSize(new Dimension(1400, 1100));
visual =
new VisualApi.Builder(driver, username, accessKey)
Expand Down
Loading
Loading