use of com.codename1.components.Switch in project CodenameOne by codenameone.
the class URLImage method createCachedImage.
/**
* Creates an image that will be downloaded on the fly as necessary. On platforms that support a native
* image cache (e.g. Javascript), the image will be loaded directly from the native cache (i.e. it defers to the
* platform to handle all caching considerations. On platforms that don't have a native image cache but
* do have a caches directory {@link FileSystemStorage#hasCachesDir()}, this will call {@link #createToFileSystem(com.codename1.ui.EncodedImage, java.lang.String, java.lang.String, com.codename1.ui.URLImage.ImageAdapter) }
* with a file location in the caches directory. In all other cases, this will call {@link #createToStorage(com.codename1.ui.EncodedImage, java.lang.String, java.lang.String) }.
*
* @param imageName The name of the image.
* @param url the URL from which the image is fetched
* @param placeholder the image placeholder is shown as the image is loading/downloading
* and serves as the guideline to the size of the downloaded image.
* @param resizeRule One of {@link #FLAG_RESIZE_FAIL}, {@link #FLAG_RESIZE_SCALE}, or {@link #FLAG_RESIZE_SCALE_TO_FILL}.
* @return a Image that will initially just delegate to the placeholder
*/
public static Image createCachedImage(String imageName, String url, Image placeholder, int resizeRule) {
if (Display.getInstance().supportsNativeImageCache()) {
CachedImage im = new CachedImage(placeholder, url, resizeRule);
im.setImageName(imageName);
return im;
} else {
ImageAdapter adapter = null;
switch(resizeRule) {
case FLAG_RESIZE_FAIL:
adapter = RESIZE_FAIL;
break;
case FLAG_RESIZE_SCALE:
adapter = RESIZE_SCALE;
break;
case FLAG_RESIZE_SCALE_TO_FILL:
adapter = RESIZE_SCALE_TO_FILL;
break;
default:
adapter = RESIZE_SCALE_TO_FILL;
break;
}
FileSystemStorage fs = FileSystemStorage.getInstance();
if (fs.hasCachesDir()) {
String name = "cn1_image_cache[" + url + "]";
name = StringUtil.replaceAll(name, "/", "_");
name = StringUtil.replaceAll(name, "\\", "_");
name = StringUtil.replaceAll(name, "%", "_");
name = StringUtil.replaceAll(name, "?", "_");
name = StringUtil.replaceAll(name, "*", "_");
name = StringUtil.replaceAll(name, ":", "_");
name = StringUtil.replaceAll(name, "=", "_");
String filePath = fs.getCachesDir() + fs.getFileSystemSeparator() + name;
// System.out.println("Creating to file system "+filePath);
URLImage im = createToFileSystem(EncodedImage.createFromImage(placeholder, false), filePath, url, adapter);
im.setImageName(imageName);
return im;
} else {
// System.out.println("Creating to storage ");
URLImage im = createToStorage(EncodedImage.createFromImage(placeholder, false), "cn1_image_cache[" + url + "@" + placeholder.getWidth() + "x" + placeholder.getHeight(), url, adapter);
im.setImageName(imageName);
return im;
}
}
}
use of com.codename1.components.Switch in project CodenameOne by codenameone.
the class List method calculateComponentPosition.
/**
* Calculates the desired bounds for the component and returns them within the
* given rectangle.
*/
private void calculateComponentPosition(int index, int defaultWidth, Rectangle rect, Dimension rendererSize, Dimension selectedSize, boolean beforeSelected) {
Style style = getStyle();
int initialY = style.getPaddingTop();
int initialX = style.getPaddingLeftNoRTL();
boolean rtl = isRTL();
if (rtl) {
initialX += getSideGap();
}
int selection = getCurrentSelected();
Dimension d = rect.getSize();
int selectedDiff;
// which will cause the bottom elements to "return" from the top.
if (orientation != HORIZONTAL) {
int height = rendererSize.getHeight();
selectedDiff = selectedSize.getHeight() - height;
rect.setX(initialX);
d.setHeight(height);
d.setWidth(defaultWidth);
int y = 0;
int listHeight = getHeight() - style.getVerticalPadding();
int totalHeight = (height + itemGap) * getModel().getSize() + selectedDiff;
switch(fixedSelection) {
case FIXED_CENTER:
y = listHeight / 2 - (height + itemGap + selectedDiff) / 2 + (index - selection) * (height + itemGap);
if (!beforeSelected) {
y += selectedDiff;
}
y = recalcOffset(y, totalHeight, listHeight, height + itemGap);
break;
case FIXED_TRAIL:
y = listHeight - (height + itemGap + selectedDiff);
case FIXED_LEAD:
y += (index - selection) * (height + itemGap);
if (index - selection > 0) {
y += selectedDiff;
}
y = recalcOffset(y, totalHeight, listHeight, height + itemGap);
break;
default:
y = index * (height + itemGap);
if (!beforeSelected) {
y += selectedDiff;
}
break;
}
rect.setY(y + initialY);
if (index == selection) {
d.setHeight(d.getHeight() + selectedDiff);
}
} else {
int width = rendererSize.getWidth();
selectedDiff = selectedSize.getWidth() - width;
rect.setY(initialY);
d.setHeight(getHeight() - style.getVerticalPadding());
d.setWidth(width);
int x = 0;
int listWidth = getWidth() - style.getHorizontalPadding();
int totalWidth = (width + itemGap) * getModel().getSize() + selectedDiff;
switch(fixedSelection) {
case FIXED_CENTER:
x = listWidth / 2 - (width + itemGap + selectedDiff) / 2 + (index - selection) * (width + itemGap);
if (!beforeSelected) {
x += selectedDiff;
}
if (rtl) {
x = listWidth - x - width;
}
x = recalcOffset(x, totalWidth, listWidth, width + itemGap);
break;
case FIXED_TRAIL:
x = listWidth - (width + itemGap + selectedDiff);
case FIXED_LEAD:
x += (index - selection) * (width + itemGap);
if (index - selection > 0) {
x += selectedDiff;
}
if (rtl) {
x = listWidth - x - width;
}
x = recalcOffset(x, totalWidth, listWidth, width + itemGap);
break;
default:
x = index * (width + itemGap);
if (!beforeSelected) {
x += selectedDiff;
}
break;
}
int rectX = initialX + x;
if ((rtl) && (fixedSelection < FIXED_NONE_BOUNDRY)) {
rectX = initialX + totalWidth - (x - initialX) - (width + itemGap);
if (index == getCurrentSelected()) {
rectX -= selectedDiff;
}
if (totalWidth < listWidth) {
rectX += (listWidth - totalWidth);
}
}
rect.setX(rectX);
if (index == selection) {
d.setWidth(d.getWidth() + selectedDiff);
}
}
}
use of com.codename1.components.Switch in project CodenameOne by codenameone.
the class Sheet method updateBorderForPosition.
private void updateBorderForPosition() {
Border border = getStyle().getBorder();
if (border instanceof RoundRectBorder) {
RoundRectBorder b = (RoundRectBorder) border;
RoundRectBorder nb = RoundRectBorder.create();
nb.bezierCorners(b.isBezierCorners());
nb.bottomLeftMode(b.isBottomLeft());
nb.bottomRightMode(b.isBottomRight());
nb.topRightMode(b.isTopRight());
nb.topLeftMode(b.isTopLeft());
nb.cornerRadius(b.getCornerRadius());
nb.shadowBlur(b.getShadowBlur());
nb.shadowColor(b.getShadowColor());
nb.shadowOpacity(b.getShadowOpacity());
nb.shadowSpread(b.getShadowSpread());
nb.shadowX(b.getShadowX());
nb.shadowY(b.getShadowY());
nb.strokeColor(b.getStrokeColor());
nb.strokeOpacity(b.getStrokeOpacity());
nb.stroke(b.getStrokeThickness(), b.isStrokeMM());
b = nb;
switch(getPositionInt()) {
case C:
b.bottomRightMode(true);
b.bottomLeftMode(true);
b.topLeftMode(true);
b.topRightMode(true);
break;
case E:
b.bottomLeftMode(true);
b.topLeftMode(true);
b.topRightMode(false);
b.bottomRightMode(false);
break;
case W:
b.bottomLeftMode(false);
b.bottomRightMode(true);
b.topLeftMode(false);
b.topRightMode(true);
break;
case S:
b.topLeftMode(true);
b.topRightMode(true);
b.bottomLeftMode(false);
b.bottomRightMode(false);
break;
case N:
b.topLeftMode(false);
b.topRightMode(false);
b.bottomLeftMode(true);
b.bottomRightMode(true);
break;
}
getStyle().setBorder(b);
}
}
use of com.codename1.components.Switch in project CodenameOne by codenameone.
the class Image method exifRotation.
/**
* <p>
* The main use case of this method is the automatic rotation and flipping
* of an image returned from the camera or from the gallery, preserving the
* original format (jpeg or png); it detects the Exif Orientation Tag, if
* available (all the possible Exif Orientation Tag values are
* supported); transparency is not preserved.</p>
* <p>
* However, rotating and/or flipping an hi-res image is very inefficient,
* that's why you should consider to pass a maxSize value as small as
* possible: it makes this method working faster.</p>
* <p>
* If there is no rotation or flipping, the image is only copied or scaled
* if necessary; if the capturedImage has a format different from jpeg and
* png, it is copied as it is.<br>Note that this method doesn't rely on the
* file extension, but on the mime type of the capturedImage, since some
* devices don't give appropriate extension to images returned from the
* gallery.</p>
* <p>
* You can test all the possible orientation values downloading the images
* from the repository
* <a href="https://github.com/recurser/exif-orientation-examples">EXIF
* Orientation-flag example images</a></p>
* <p>
* Code example:</p>
* <script src="https://gist.github.com/jsfan3/7fc101523955e8179fadd2c713a09e05.js"></script>
*
* @param capturedImage is the FileSystemStorage path of a captured photo,
* usually inside a temporary directory
* @param rotatedImage is the FileSystemStorage path in which the rotated
* photo is stored, normally this should be inside the
* FileSystemStorage.getAppHomePath(); it can be null if you don't want to
* save the rotated image to the FileSystemStorage.
* @param maxSize is the maximum value of the width and height of the
* rotated images, that is scaled if necessary, keeping the ratio.
* @return the com.codename1.ui.Image
* @throws java.io.IOException
*/
public static Image exifRotation(String capturedImage, String rotatedImage, int maxSize) throws IOException {
FileSystemStorage fss = FileSystemStorage.getInstance();
boolean isJpeg = isJPEG(fss.openInputStream(capturedImage));
boolean isPNG = isPNG(fss.openInputStream(capturedImage));
String format;
// because some Android devices return images from the gallery without extension!
if (!isJpeg && !isPNG) {
// In this case, we simply copy the file.
if (rotatedImage != null) {
Util.copy(fss.openInputStream(capturedImage), fss.openOutputStream(rotatedImage));
}
return EncodedImage.create(fss.openInputStream(capturedImage), (int) fss.getLength(capturedImage));
} else if (isJpeg) {
format = ImageIO.FORMAT_JPEG;
} else {
format = ImageIO.FORMAT_PNG;
}
int orientation = getExifOrientationTag(fss.openInputStream(capturedImage));
Image img = EncodedImage.create(fss.openInputStream(capturedImage), (int) fss.getLength(capturedImage));
img.lock();
if (maxSize > 0 && (img.getWidth() > maxSize || img.getHeight() > maxSize)) {
// Tested that scaling the image before rotating is a lot more efficient than rotating before scaling
Image scaled = img.scaledSmallerRatio(maxSize, maxSize);
img.unlock();
img = scaled;
img.lock();
}
Image result, temp;
switch(orientation) {
case 0:
case 1:
// no rotation (but the image may have been scaled)
result = img;
break;
case 2:
// action required: flip horizontally
result = img.flipHorizontally(false);
break;
case 3:
// action required: rotate 180 degrees
result = img.rotate180Degrees(false);
break;
case 4:
// action required: flip vertically
result = img.flipVertically(false);
break;
case 5:
// action required: rotate 270 degrees
result = img.rotate270Degrees(false);
break;
case 6:
// action required: rotate 90 degrees
result = img.rotate90Degrees(false);
break;
case 7:
// action required: flip horizontally and rotate 90 degrees
temp = img.flipHorizontally(false);
temp.lock();
result = temp.rotate90Degrees(false);
temp.unlock();
break;
case 8:
// action required: flip horizontally and rotate 270 degrees
temp = img.flipHorizontally(false);
temp.lock();
result = temp.rotate270Degrees(false);
temp.unlock();
break;
default:
// this never should happen
throw new IllegalStateException("Unsupported rotation");
}
img.unlock();
if (rotatedImage != null) {
OutputStream out = fss.openOutputStream(rotatedImage);
ImageIO.getImageIO().save(result, out, format, 0.9f);
Util.cleanup(out);
}
return EncodedImage.createFromImage(result, isJpeg);
}
use of com.codename1.components.Switch in project CodenameOne by codenameone.
the class IOSImplementation method editString.
public void editString(final Component cmp, final int maxSize, final int constraint, final String text, final int i) {
// The very first time we try to edit a string, let's determine if the
// system default is to do async editing. If the system default
// is not yet set, we set it here, and it will be used as the default from now on
// We do this because the nativeInstance.isAsyncEditMode() value changes
// to reflect the currently edited field so it isn't a good way to keep a
// system default.
pendingEditingText = false;
String defaultAsyncEditingSetting = Display.getInstance().getProperty("ios.VKBAlwaysOpen", null);
if (defaultAsyncEditingSetting == null) {
defaultAsyncEditingSetting = nativeInstance.isAsyncEditMode() ? "true" : "false";
Display.getInstance().setProperty("ios.VKBAlwaysOpen", defaultAsyncEditingSetting);
}
boolean asyncEdit = "true".equals(defaultAsyncEditingSetting) ? true : false;
try {
if (currentEditing != cmp && currentEditing != null && currentEditing instanceof TextArea) {
Display.getInstance().onEditingComplete(currentEditing, ((TextArea) currentEditing).getText());
currentEditing = null;
callHideTextEditor();
if (nativeInstance.isAsyncEditMode()) {
nativeInstance.setNativeEditingComponentVisible(false);
}
synchronized (EDITING_LOCK) {
EDITING_LOCK.notify();
}
Display.getInstance().callSerially(new Runnable() {
public void run() {
pendingEditingText = true;
Display.getInstance().editString(cmp, maxSize, constraint, text, i);
}
});
return;
}
if (cmp.isFocusable() && !cmp.hasFocus()) {
doNotHideTextEditorSemaphore++;
try {
cmp.requestFocus();
} finally {
doNotHideTextEditorSemaphore--;
}
// of our upcoming field.
if (isAsyncEditMode()) {
// flush the EDT so the focus will work...
Display.getInstance().callSerially(new Runnable() {
public void run() {
pendingEditingText = true;
Display.getInstance().editString(cmp, maxSize, constraint, text, i);
}
});
return;
}
}
// Check if the form has any setting for asyncEditing that should override
// the application defaults.
Form parentForm = cmp.getComponentForm();
if (parentForm == null) {
// Log.p("Attempt to edit text area that is not on a form. This is not supported");
return;
}
if (parentForm.getClientProperty("asyncEditing") != null) {
Object async = parentForm.getClientProperty("asyncEditing");
if (async instanceof Boolean) {
asyncEdit = ((Boolean) async).booleanValue();
// Log.p("Form overriding asyncEdit due to asyncEditing client property: "+asyncEdit);
}
}
if (parentForm.getClientProperty("ios.asyncEditing") != null) {
Object async = parentForm.getClientProperty("ios.asyncEditing");
if (async instanceof Boolean) {
asyncEdit = ((Boolean) async).booleanValue();
// Log.p("Form overriding asyncEdit due to ios.asyncEditing client property: "+asyncEdit);
}
}
// editing - and should instead revert to legacy editing mode.
if (asyncEdit && !parentForm.isFormBottomPaddingEditingMode()) {
Container p = cmp.getParent();
// A crude estimate of how far the component needs to be able to scroll to make
// async editing viable. We start with half-way down the screen.
int keyboardClippingThresholdY = Display.getInstance().getDisplayWidth() / 2;
while (p != null) {
if (Accessor.scrollableYFlag(p) && p.getAbsoluteY() < keyboardClippingThresholdY) {
break;
}
p = p.getParent();
}
// no scrollabel parent automatically configure the text field for legacy mode
// nativeInstance.setAsyncEditMode(p != null);
asyncEdit = p != null;
// Log.p("Overriding asyncEdit due to form scrollability: "+asyncEdit);
} else if (parentForm.isFormBottomPaddingEditingMode()) {
// If form uses bottom padding mode, then we will always
// use async edit (unless the field explicitly overrides it).
asyncEdit = true;
// Log.p("Overriding asyncEdit due to form bottom padding edit mode: "+asyncEdit);
}
// then this will override all other settings.
if (cmp.getClientProperty("asyncEditing") != null) {
Object async = cmp.getClientProperty("asyncEditing");
if (async instanceof Boolean) {
asyncEdit = ((Boolean) async).booleanValue();
// Log.p("Overriding asyncEdit due to field asyncEditing client property: "+asyncEdit);
}
}
if (cmp.getClientProperty("ios.asyncEditing") != null) {
Object async = cmp.getClientProperty("ios.asyncEditing");
if (async instanceof Boolean) {
asyncEdit = ((Boolean) async).booleanValue();
// Log.p("Overriding asyncEdit due to field ios.asyncEditing client property: "+asyncEdit);
}
}
// Finally we set the async edit mode for this field.
// System.out.println("Async edit mode is "+asyncEdit);
nativeInstance.setAsyncEditMode(asyncEdit);
textEditorHidden = false;
currentEditing = (TextArea) cmp;
// register the edited TextArea to support moving to the next field
TextEditUtil.setCurrentEditComponent(cmp);
final NativeFont fnt = f(cmp.getStyle().getFont().getNativeFont());
boolean forceSlideUpTmp = false;
final Form current = Display.getInstance().getCurrent();
if (current instanceof Dialog && !isTablet()) {
// special case, if we are editing a small dialog we want to move it
// so the bottom of the dialog shows within the screen. This is
// described in issue 505
Dialog dlg = (Dialog) current;
Component c = dlg.getDialogComponent();
if (c.getHeight() < Display.getInstance().getDisplayHeight() / 2 && c.getAbsoluteY() + c.getHeight() > Display.getInstance().getDisplayHeight() / 2) {
forceSlideUpTmp = true;
}
}
final boolean forceSlideUp = forceSlideUpTmp;
cmp.repaint();
// give the repaint one cycle to "do its magic...
final Style stl = currentEditing.getStyle();
final boolean rtl = UIManager.getInstance().getLookAndFeel().isRTL();
final Style hintStyle = currentEditing.getHintLabel() != null ? currentEditing.getHintLabel().getStyle() : stl;
if (current != null) {
Component nextComponent = current.getNextComponent(cmp);
TextEditUtil.setNextEditComponent(nextComponent);
}
Display.getInstance().callSerially(new Runnable() {
@Override
public void run() {
int x = cmp.getAbsoluteX() + cmp.getScrollX();
int y = cmp.getAbsoluteY() + cmp.getScrollY();
int w = cmp.getWidth();
int h = cmp.getHeight();
int pt = stl.getPaddingTop();
int pb = stl.getPaddingBottom();
int pl = stl.getPaddingLeft(rtl);
int pr = stl.getPaddingRight(rtl);
/*
if(currentEditing != null && currentEditing.isSingleLineTextArea()) {
switch(currentEditing.getVerticalAlignment()) {
case TextArea.CENTER:
if(h > cmp.getPreferredH()) {
y += (h / 2 - cmp.getPreferredH() / 2);
}
break;
case TextArea.BOTTOM:
if(h > cmp.getPreferredH()) {
y += (h - cmp.getPreferredH());
}
break;
}
}
*/
String hint = null;
if (currentEditing != null && currentEditing.getUIManager().isThemeConstant("nativeHintBool", true) && currentEditing.getHint() != null) {
hint = currentEditing.getHint();
}
int hintColor = hintStyle.getFgColor();
if (isAsyncEditMode()) {
// request focus triggers a scroll which flicks the textEditorHidden flag
doNotHideTextEditorSemaphore++;
try {
cmp.requestFocus();
} finally {
doNotHideTextEditorSemaphore--;
}
textEditorHidden = false;
}
boolean showToolbar = cmp.getClientProperty("iosHideToolbar") == null;
if (showToolbar && Display.getInstance().getProperty("iosHideToolbar", "false").equalsIgnoreCase("true")) {
showToolbar = false;
}
if (currentEditing != null) {
nativeInstance.editStringAt(x, y, w, h, fnt.peer, currentEditing.isSingleLineTextArea(), currentEditing.getRows(), maxSize, constraint, text, forceSlideUp, // peer,
stl.getFgColor(), // peer,
0, pt, pb, pl, pr, hint, hintColor, showToolbar, Boolean.TRUE.equals(cmp.getClientProperty("blockCopyPaste")), currentEditing.getStyle().getAlignment(), currentEditing.getVerticalAlignment());
}
}
});
if (isAsyncEditMode()) {
return;
}
editNext = false;
Display.getInstance().invokeAndBlock(new Runnable() {
@Override
public void run() {
synchronized (EDITING_LOCK) {
while (instance.currentEditing == cmp) {
try {
EDITING_LOCK.wait(20);
} catch (InterruptedException ex) {
}
}
}
}
});
if (cmp instanceof TextArea && !((TextArea) cmp).isSingleLineTextArea()) {
Form form = cmp.getComponentForm();
if (form != null) {
form.revalidate();
}
}
if (editNext) {
editNext = false;
TextEditUtil.editNextTextArea();
}
} finally {
}
}
Aggregations