use of com.codename1.io.URL in project CodenameOne by codenameone.
the class CSSTheme method getBackgroundImage.
public Image getBackgroundImage(Map<String, LexicalUnit> styles, ScaledUnit bgImage) {
try {
// ScaledUnit bgImage = (ScaledUnit)styles.get("background-image");
if (bgImage == null) {
return null;
}
String url = bgImage.getStringValue();
String fileName = url;
if (fileName.indexOf("/") != -1) {
fileName = fileName.substring(fileName.lastIndexOf("/") + 1);
}
if (loadedImages.containsKey(url)) {
return loadedImages.get(url);
}
LexicalUnit imageId = styles.get("cn1-image-id");
String imageIdStr = fileName;
if (imageId != null) {
imageIdStr = imageId.getStringValue();
} else {
/*
int i=1;
while (res.getImage(imageIdStr) != null) {
if (i == 1) {
imageIdStr += "_"+(++i);
} else {
imageIdStr = imageIdStr.substring(0, imageIdStr.lastIndexOf("_")) + "_"+(++i);
}
}
*/
}
Image resimg = res.getImage(imageIdStr);
Integer defaultSourceDpi = null;
if (constants.containsKey("defaultSourceDPIInt")) {
Object v = constants.get("defaultSourceDPIInt");
if (v instanceof String) {
defaultSourceDpi = Integer.parseInt((String) v);
} else if (v instanceof Number) {
defaultSourceDpi = ((Number) v).intValue();
} else if (v instanceof ScaledUnit) {
ScaledUnit su = (ScaledUnit) v;
defaultSourceDpi = su.getIntegerValue();
} else {
throw new IllegalArgumentException("defaultSourceDPIInt constant should be a String or a number but found " + v.getClass());
}
}
if (resimg != null) {
ImageMetadata md = imagesMetadata.get(imageIdStr);
int srcDpi = (int) currentDpi;
if (defaultSourceDpi != null) {
srcDpi = defaultSourceDpi;
}
if (styles.containsKey("cn1-source-dpi")) {
srcDpi = (int) ((ScaledUnit) styles.get("cn1-source-dpi")).getNumericValue();
}
if (refreshImages || (md != null && md.sourceDpi != srcDpi)) {
//
res.remove(imageIdStr);
} else {
loadedImages.put(imageIdStr, resimg);
return res.getImage(imageIdStr);
}
}
URL imgURL = null;
if (url.startsWith("http://") || url.startsWith("https://")) {
imgURL = new URL(url);
} else {
imgURL = new URL(baseURL, url);
}
if (false && isFileURL(imgURL)) {
// This section is switched off because loading multi-images via url()
// will cause unexpected results in cases where image borders are generated.
// In order for this approach to work, we need take into account multi-images when
// producing snapshots in the webview so that the correct size of image is used.
// You can still load multi-images as theme constants.
// See https://github.com/codenameone/CodenameOne/issues/2569#issuecomment-426730539
File imgDir = new File(imgURL.toURI());
if (imgDir.isDirectory()) {
try {
Image im = getResourceImage(imgDir.getName(), imgDir.getParentFile());
if (im != null) {
loadedImages.put(url, im);
return im;
}
} catch (Throwable t) {
System.err.println("Failed to load Multi-image from " + imgURL);
t.printStackTrace();
throw t;
}
}
}
InputStream is = imgURL.openStream();
EncodedImage encImg = EncodedImage.create(is);
is.close();
ResourcesMutator resm = new ResourcesMutator(res, com.codename1.ui.Display.DENSITY_VERY_HIGH, minDpi, maxDpi);
int[] dpis = getDpi(encImg);
int sourceDpi = (int) Math.round(currentDpi);
if (styles.containsKey("cn1-source-dpi")) {
double densityVal = ((ScaledUnit) styles.get("cn1-source-dpi")).getNumericValue();
sourceDpi = (int) Math.round(densityVal);
if (Math.abs(densityVal) < 0.5) {
resm.targetDensity = 0;
} else {
resm.targetDensity = getDensityForDpi(densityVal);
}
} else if (defaultSourceDpi != null) {
sourceDpi = defaultSourceDpi;
if (Math.abs(sourceDpi) < 0.5) {
resm.targetDensity = 0;
} else {
resm.targetDensity = getDensityForDpi(sourceDpi);
}
} else if (dpis[0] > 0) {
resm.targetDensity = getImageDensity(encImg);
} else {
resm.targetDensity = getDensityForDpi(bgImage.dpi);
}
if (styles.containsKey("cn1-densities")) {
ScaledUnit densities = (ScaledUnit) styles.get("cn1-densities");
if (densities.getLexicalUnitType() == LexicalUnit.SAC_IDENT && "none".equals(densities.getStringValue())) {
// Not a multi-image
resm.setMultiImage(false);
}
} else if (sourceDpi == 0) {
resm.setMultiImage(false);
}
Image im = resm.storeImage(encImg, imageIdStr, false);
im.setImageName(imageIdStr);
loadedImages.put(url, im);
ImageMetadata md = new ImageMetadata(imageIdStr, sourceDpi);
imagesMetadata.addImageMetadata(md);
return im;
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
use of com.codename1.io.URL in project CodenameOne by codenameone.
the class CSSTheme method load.
public static CSSTheme load(URL uri) throws IOException {
try {
System.setProperty("org.w3c.css.sac.parser", "org.w3c.flute.parser.Parser");
InputSource source = new InputSource();
InputStream stream = uri.openStream();
String stringContents = Util.readToString(stream);
// The flute parser chokes on properties beginning with -- so we need to replace these with cn1 prefix
// for CSS variable support.
stringContents = stringContents.replaceAll("([\\(\\W])(--[a-zA-Z0-9\\-]+)", "$1cn1$2");
// Flute chokes on embedded var() functions inside an rgb or rgba function. Hoping to support it by changing the
// function name to cn1rgb() and cn1rgba() respectively.
stringContents = stringContents.replaceAll("\\brgb\\(", "cn1rgb(");
stringContents = stringContents.replaceAll("\\brgba\\(", "cn1rgba(");
source.setCharacterStream(new CharArrayReader(stringContents.toCharArray()));
source.setURI(uri.toString());
source.setEncoding("UTF-8");
ParserFactory parserFactory = new ParserFactory();
Parser parser = parserFactory.makeParser();
final CSSTheme theme = new CSSTheme();
theme.baseURL = uri;
parser.setErrorHandler(new ErrorHandler() {
@Override
public void warning(CSSParseException csspe) throws CSSException {
System.out.println("CSS Warning: " + csspe.getLocalizedMessage() + " on line " + csspe.getLineNumber() + " col: " + csspe.getColumnNumber() + " of file " + csspe.getURI());
}
@Override
public void error(CSSParseException csspe) throws CSSException {
System.out.println("CSS Error: " + csspe.getLocalizedMessage() + " on line " + csspe.getLineNumber() + " col: " + csspe.getColumnNumber() + " of file " + csspe.getURI());
}
@Override
public void fatalError(CSSParseException csspe) throws CSSException {
System.out.println("CSS Fatal Error: " + csspe.getLocalizedMessage() + " on line " + csspe.getLineNumber() + " col: " + csspe.getColumnNumber() + " of file " + csspe.getURI());
}
});
// parser.setLocale(Locale.getDefault());
parser.setDocumentHandler(new DocumentHandler() {
Map<String, LexicalUnit> variables = new LinkedHashMap<>();
SelectorList currSelectors;
FontFace currFontFace;
SACMediaList currMediaList;
// double currentTargetDpi = 320;
// double currentMinDpi = 120;
// double currentMaxDpi = 640;
// int currentScreenWidth = 1280;
// int currentScreenHeight = 1920;
@Override
public void startDocument(InputSource is) throws CSSException {
// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void endDocument(InputSource is) throws CSSException {
// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void comment(String string) throws CSSException {
}
@Override
public void ignorableAtRule(String string) throws CSSException {
// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void namespaceDeclaration(String string, String string1) throws CSSException {
// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void importStyle(String string, SACMediaList sacml, String string1) throws CSSException {
// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void startMedia(SACMediaList sacml) throws CSSException {
currMediaList = sacml;
}
@Override
public void endMedia(SACMediaList sacml) throws CSSException {
currMediaList = null;
}
@Override
public void startPage(String string, String string1) throws CSSException {
// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void endPage(String string, String string1) throws CSSException {
// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void startFontFace() throws CSSException {
currFontFace = theme.createFontFace();
}
@Override
public void endFontFace() throws CSSException {
currFontFace = null;
}
@Override
public void startSelector(SelectorList sl) throws CSSException {
// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
currSelectors = sl;
}
@Override
public void endSelector(SelectorList sl) throws CSSException {
currSelectors = null;
}
@Override
public void property(String string, LexicalUnit lu, boolean bln) throws CSSException {
try {
property_(string, lu, bln);
} catch (Throwable t) {
if (t instanceof CSSException) {
throw (CSSException) t;
} else {
System.out.println("Exception occurred while parsing property " + string + " " + lu);
t.printStackTrace();
throw new ParseException(t.getMessage());
}
}
}
private ScaledUnit last(LexicalUnit lu) {
while (lu.getNextLexicalUnit() != null) {
lu = lu.getNextLexicalUnit();
}
return (lu instanceof ScaledUnit) ? (ScaledUnit) lu : new ScaledUnit(lu, theme.currentDpi, theme.getPreviewScreenWidth(), theme.getPreviewScreenHeight());
}
/**
* Evaluates a LexicalUnit in the current parser position. This will expand any variables. It will
* continue to evaluate the next lexical unit, until it reaches the end of the current lexical unit chain.
* @param lu The lexical unit to evaluate.
* @return
* @throws CSSException
*/
private ScaledUnit evaluate(LexicalUnit lu) throws CSSException {
if (lu.getLexicalUnitType() == LexicalUnit.SAC_FUNCTION && "var".equals(lu.getFunctionName())) {
LexicalUnit parameters = lu.getParameters();
String varname = parameters.getStringValue();
LexicalUnit varVal = variables.get(varname);
ScaledUnit su;
if (varVal == null && parameters.getNextLexicalUnit() != null) {
varVal = parameters.getNextLexicalUnit();
su = evaluate(new ScaledUnit(varVal, theme.currentDpi, theme.getPreviewScreenWidth(), theme.getPreviewScreenHeight()));
} else if (varVal == null) {
su = new ScaledUnit(lu, theme.currentDpi, theme.getPreviewScreenWidth(), theme.getPreviewScreenHeight());
} else {
su = evaluate(new ScaledUnit(varVal, theme.currentDpi, theme.getPreviewScreenWidth(), theme.getPreviewScreenHeight()));
}
// Evaluate the variable value in case it also includes other variables that need to be evaluated.
// ScaledUnit su = evaluate(new ScaledUnit(varVal, theme.currentDpi, theme.getPreviewScreenWidth(), theme.getPreviewScreenHeight()));
LexicalUnit toAppend = lu.getNextLexicalUnit();
ScaledUnit last = last(su);
if (toAppend != null) {
toAppend = evaluate(toAppend);
last.setNextLexicalUnit(toAppend);
((ScaledUnit) toAppend).setPrevLexicalUnit(last);
} else {
last.setNextLexicalUnit(null);
}
return su;
} else {
ScaledUnit su = new ScaledUnit(lu, theme.currentDpi, theme.getPreviewScreenWidth(), theme.getPreviewScreenHeight());
LexicalUnit nex = su.getNextLexicalUnit();
if (su.getParameters() != null) {
su.setParameters(evaluate(su.getParameters()));
}
if (nex != null) {
ScaledUnit snex = evaluate(nex);
su.setNextLexicalUnit(snex);
snex.setPrevLexicalUnit(su);
}
return su;
}
}
private void property_(String string, LexicalUnit _lu, boolean bln) throws CSSException {
if (string.startsWith("cn1--")) {
variables.put(string, _lu);
return;
}
ScaledUnit su = evaluate(_lu);
if (currFontFace != null) {
switch(string) {
case "font-family":
currFontFace.fontFamily = su;
break;
case "font-style":
currFontFace.fontStyle = su;
break;
case "font-stretch":
currFontFace.fontStretch = su;
break;
case "src":
currFontFace.src = su;
break;
case "font-weight":
currFontFace.fontWeight = su;
break;
}
} else {
int len = currSelectors.getLength();
for (int i = 0; i < len; i++) {
Selector sel = currSelectors.item(i);
if (currMediaList != null) {
for (String mediaPrefix : getMediaPrefixes(currMediaList)) {
theme.apply(mediaPrefix, sel, string, su);
}
} else {
theme.apply(null, sel, string, su);
}
}
}
}
});
parser.parseStyleSheet(source);
stream.close();
return theme;
} catch (ClassNotFoundException ex) {
Logger.getLogger(CSSTheme.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(CSSTheme.class.getName()).log(Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
Logger.getLogger(CSSTheme.class.getName()).log(Level.SEVERE, null, ex);
} catch (NullPointerException ex) {
if (ex.getMessage().contains("encoding properties")) {
// This error always happens and there doesn't seem to be a way to fix it... so let's just hide
// it . Doesn't seem to hurt anything.
} else {
// Logger.getLogger(CSSTheme.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (ClassCastException ex) {
Logger.getLogger(CSSTheme.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
use of com.codename1.io.URL 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.io.URL in project CodenameOne by codenameone.
the class URITests method runTest.
@Override
public boolean runTest() throws Exception {
FileSystemStorage fs = FileSystemStorage.getInstance();
String home = fs.getAppHomePath();
if (!home.endsWith(fs.getFileSystemSeparator() + "")) {
home += fs.getFileSystemSeparator();
}
String homePath = home.substring(6);
homePath = StringUtil.replaceAll(homePath, "\\", "/");
while (homePath.startsWith("/")) {
homePath = homePath.substring(1);
}
homePath = "/" + homePath;
com.codename1.io.URL url = new com.codename1.io.File("hello world.txt").toURL();
// https://en.wikipedia.org/wiki/File_URI_scheme
assertTrue(url.toString().startsWith("file:/"), "URL should start with file:///");
assertEqual("file:" + homePath + "hello%20world.txt", url.toString(), "URL failed to encode space in file name");
URI uri = new com.codename1.io.File("hello world.txt").toURI();
assertEqual("file:" + homePath + "hello%20world.txt", uri.toString(), "URI failed to encode space in file name");
assertEqual(homePath + "hello world.txt", uri.getPath(), "Incorrect URI path");
return true;
}
use of com.codename1.io.URL in project CodenameOne by codenameone.
the class SignIn method showGoogleUser.
private void showGoogleUser(String token) {
ConnectionRequest req = new ConnectionRequest();
req.addRequestHeader("Authorization", "Bearer " + token);
req.setUrl("https://www.googleapis.com/plus/v1/people/me");
req.setPost(false);
InfiniteProgress ip = new InfiniteProgress();
Dialog d = ip.showInifiniteBlocking();
NetworkManager.getInstance().addToQueueAndWait(req);
d.dispose();
byte[] data = req.getResponseData();
JSONParser parser = new JSONParser();
Map map = null;
try {
map = parser.parseJSON(new InputStreamReader(new ByteArrayInputStream(data), "UTF-8"));
} catch (IOException ex) {
ex.printStackTrace();
}
String name = (String) map.get("displayName");
Map im = (Map) map.get("image");
String url = (String) im.get("url");
Form userForm = new UserForm(name, (EncodedImage) theme.getImage("user.png"), url);
userForm.show();
}
Aggregations