use of com.codename1.rad.processing.Result in project CodenameOne by codenameone.
the class ResourcesMutator method createScreenshots.
/**
* Creates screenshots for the given HTML which was generated by {@link CSSTheme#generateCaptureHtml() }.
* @param web The web View used to render the HTML
* @param html The HTML to render in the webview. Generated by {@link CSSTheme#generateCaptureHtml() }
* @param baseURL The BaseURL - general points to the CSS file location. Used for loading resources from relative paths.
*/
public void createScreenshots(BrowserComponent web, String html, String baseURL) {
// System.out.println("in createScreenshots");
try {
File baseURLFile = new File(new URL(baseURL).toURI());
if (!baseURLFile.isDirectory()) {
baseURLFile = baseURLFile.getParentFile();
}
startWebServer(baseURLFile);
boolean[] waitForServerResult = new boolean[1];
CN.invokeAndBlock(new Runnable() {
public void run() {
waitForServerResult[0] = webServer.waitForServer(2000);
}
});
if (!waitForServerResult[0]) {
throw new RuntimeException("Failed to start webserver after 2 seconds");
}
} catch (Exception ex) {
throw new RuntimeException("Failed to start local webserver for creating screenshots", ex);
}
long timeout = 50000;
// String captureSrc = this.getClass().getResource("capture.js").toExternalForm();
String captureJS = null;
try {
captureJS = Util.readToString(this.getClass().getResourceAsStream("capture.js"));
} catch (IOException ex) {
throw new RuntimeException("Failed to read capture.js file.", ex);
}
// final String modifiedHtml = html.replace("</body>", /*"<script src=\"https://code.jquery.com/jquery-2.1.4.min.js\">"
// + */"</script><script src=\""+captureSrc+"\"></script></body>");
final String modifiedHtml = html.replace("</head>", /*"<script src=\"https://code.jquery.com/jquery-2.1.4.min.js\">"
+ */
"<script>\n" + captureJS + "\n</script></head>");
this.web = web;
screenshotsComplete = false;
CN.callSerially(() -> {
loadListener = (ActionEvent evt) -> {
if (webServer != null) {
webServer.stop();
webServer = null;
}
web.removeWebEventListener(BrowserComponent.onLoad, loadListener);
try {
// System.out.println("In onLoad event");
// Use reflection to retrieve the WebEngine's private 'page' field.
web.addJSCallback("window.app = window.app || {}; window.app.createScreenshotCallback = function(id, x, y, w, h) {" + "callback.onSuccess(JSON.stringify({id:id, x:x, y:y, w:w, h:h}));" + "};", res -> {
try {
Result data = Result.fromContent(new StringReader(res.toString()), Result.JSON);
createScreenshotCallback(data.getAsString("id"), data.getAsInteger("x"), data.getAsInteger("y"), data.getAsInteger("w"), data.getAsInteger("h"));
} catch (Exception ex) {
Log.p("Failed to parse input to createScreenshotsCallback");
Log.e(ex);
}
});
web.addJSCallback("window.app.finishedCaptureScreenshotsCallback = function() {" + "callback.onSuccess(null);" + "};", res -> {
finishedCaptureScreenshotsCallback();
});
web.execute("$(document).ready(function(){ captureScreenshots();});");
// web.getEngine().executeScript("window.onload = function(){window.app.ready()};");
} catch (IllegalArgumentException ex) {
Logger.getLogger(CN1CSSCompiler.class.getName()).log(Level.SEVERE, null, ex);
} catch (SecurityException ex) {
Logger.getLogger(CN1CSSCompiler.class.getName()).log(Level.SEVERE, null, ex);
}
};
web.addWebEventListener(BrowserComponent.onLoad, loadListener);
// CN.setProperty("cef.setPage.useDataURI", "true");
webServer.route("/index.html", () -> {
try {
return modifiedHtml.getBytes("UTF-8");
} catch (Exception ex) {
Log.e(ex);
try {
return ("Error: " + ex.getMessage()).getBytes("UTF-8");
} catch (Exception ex2) {
Log.e(ex2);
return new byte[0];
}
}
});
web.setURL("http://localhost:" + webServer.getPort() + "/index.html");
});
long startTime = System.currentTimeMillis();
while (!screenshotsComplete && System.currentTimeMillis() - startTime < timeout) {
CN.invokeAndBlock(new Runnable() {
public void run() {
Util.wait(screenshotsLock, 50);
}
});
}
if (!screenshotsComplete) {
throw new RuntimeException("Failed to create screenshots for HTML " + html + ". Timeout reached. Likely there was a problem initializing the browser component.");
}
this.web = null;
this.loadListener = null;
}
use of com.codename1.rad.processing.Result in project CodenameOne by codenameone.
the class DatabaseTests method testSimpleQueriesInCustomPath.
private void testSimpleQueriesInCustomPath() throws Exception {
if (Database.isCustomPathSupported()) {
String dbName = new File("somedir/testdb").getAbsolutePath();
new File(dbName).getParentFile().mkdirs();
Database.delete(dbName);
Database db = Database.openOrCreate(dbName);
db.execute("create table tests (name text)");
db.execute("insert into tests values ('Steve'), ('Mike'), ('Ryan')");
Cursor c = db.executeQuery("select count(*) from tests");
c.next();
this.assertEqual(3, c.getRow().getInteger(0), "Expected result of 3 for count(*) after inserting 3 rows");
} else {
Log.p("testSimpleQueriesInCustomPath skipped on this platform");
}
}
use of com.codename1.rad.processing.Result in project CodenameOne by codenameone.
the class DatabaseTests method testCustomPaths.
private void testCustomPaths() throws Exception {
if (Database.isCustomPathSupported()) {
File dbFile = new File("somedir/testdb");
dbFile.getParentFile().mkdirs();
String dbName = dbFile.getAbsolutePath();
// Start out fresh
Database.delete(dbName);
Database db = Database.openOrCreate(dbName);
this.assertNotNull(db, "Failed to open database with custom path " + dbName);
this.assertTrue(Database.exists(dbName), "Database.exists() returns false after openOrCreate with custom path: " + dbName);
String path = Database.getDatabasePath(dbName);
this.assertTrue(FileSystemStorage.getInstance().exists(path), "Database doesn't exist after creation with custom path: " + dbName);
this.assertEqual(dbFile.getAbsolutePath(), path, "Result of getDatabasePath() doesn't match input path with custom path");
db.close();
Database.delete(dbName);
this.assertTrue(!FileSystemStorage.getInstance().exists(path), "Failed to delete database with custom path: " + dbName);
} else {
Throwable ex = null;
File dbFile = new File("somedir/testdb");
dbFile.getParentFile().mkdirs();
String dbName = dbFile.getAbsolutePath();
try {
Database.openOrCreate(dbName);
} catch (Throwable t) {
ex = t;
}
this.assertTrue(ex instanceof IllegalArgumentException, "Platforms that don't support custom paths should throw an illegalArgumentException when trying to open databases with file separators in them");
ex = null;
try {
Database.exists(dbName);
} catch (Throwable t) {
ex = t;
}
this.assertTrue(ex instanceof IllegalArgumentException, "Platforms that don't support custom paths should throw an illegalArgumentException when trying to open databases with file separators in them");
ex = null;
try {
Database.delete(dbName);
} catch (Throwable t) {
ex = t;
}
this.assertTrue(ex instanceof IllegalArgumentException, "Platforms that don't support custom paths should throw an illegalArgumentException when trying to open databases with file separators in them");
ex = null;
try {
Database.getDatabasePath(dbName);
} catch (Throwable t) {
ex = t;
}
this.assertTrue(ex instanceof IllegalArgumentException, "Platforms that don't support custom paths should throw an illegalArgumentException when trying to open databases with file separators in them");
}
}
use of com.codename1.rad.processing.Result in project CodenameOne by codenameone.
the class TimeChart method getXLabels.
@Override
protected List<Double> getXLabels(double min, double max, int count) {
final List<Double> result = new ArrayList<Double>();
if (!mRenderer.isXRoundedLabels()) {
if (mDataset.getSeriesCount() > 0) {
XYSeries series = mDataset.getSeriesAt(0);
int length = series.getItemCount();
int intervalLength = 0;
int startIndex = -1;
for (int i = 0; i < length; i++) {
double value = series.getX(i);
if (min <= value && value <= max) {
intervalLength++;
if (startIndex < 0) {
startIndex = i;
}
}
}
if (intervalLength < count) {
for (int i = startIndex; i < startIndex + intervalLength; i++) {
result.add(series.getX(i));
}
} else {
float step = (float) intervalLength / count;
int intervalCount = 0;
for (int i = 0; i < length && intervalCount < count; i++) {
double value = series.getX(Math.round(i * step));
if (min <= value && value <= max) {
result.add(value);
intervalCount++;
}
}
}
return result;
} else {
return super.getXLabels(min, max, count);
}
}
if (mStartPoint == null) {
TimeZone tz = TimeZone.getDefault();
Calendar cal = Calendar.getInstance(tz);
cal.setTime(new Date(Math.round(min)));
int offset = getDSTOffset(cal);
mStartPoint = min - (min % DAY) + DAY + offset * 60 * 60 * 1000;
}
if (count > 25) {
count = 25;
}
final double cycleMath = (max - min) / count;
if (cycleMath <= 0) {
return result;
}
double cycle = DAY;
if (cycleMath <= DAY) {
while (cycleMath < cycle / 2) {
cycle = cycle / 2;
}
} else {
while (cycleMath > cycle) {
cycle = cycle * 2;
}
}
double val = mStartPoint - Math.floor((mStartPoint - min) / cycle) * cycle;
int i = 0;
while (val < max && i++ <= count) {
result.add(val);
val += cycle;
}
return result;
}
use of com.codename1.rad.processing.Result in project CodenameOne by codenameone.
the class Effects method squareShadow.
/**
* Generates a square shadow and returns it
*
* @param width the width of the shadow image
* @param height the height of the shadow image
* @param blurRadius a shadow is blurred using a gaussian blur when available, a value of 10 is often satisfactory
* @param opacity the opacity of the shadow between 0 - 1 where 1 is completely opaque
* @return an image containing the shadow for source
*/
public static Image squareShadow(int width, int height, int blurRadius, float opacity) {
Image img = Image.createImage(width + blurRadius * 2, height + blurRadius * 2, 0);
Graphics g = img.getGraphics();
int destAlpha = (int) (opacity * 255.0);
g.setColor(0);
if (Display.getInstance().isGaussianBlurSupported()) {
// Note: This is not exactly the same as the result when we don't have gaussian blur
// But it looks better.
g.setAlpha(Math.min(destAlpha * 2, 255));
g.fillRect(blurRadius - 1, blurRadius - 1, width + 2, height + 2);
img = Display.getInstance().gaussianBlurImage(img, blurRadius);
} else {
Motion lin = Motion.createLinearMotion(0, destAlpha, blurRadius);
// draw a gradient of sort for the shadow
for (int iter = blurRadius - 1; iter >= 0; iter--) {
lin.setCurrentMotionTime(iter);
g.setAlpha(Math.max(0, (int) (lin.getValue() * iter / (blurRadius - 1f))));
g.drawRect(iter, iter, width + (blurRadius - iter) * 2, height + (blurRadius - iter) * 2);
}
}
return img;
}
Aggregations