use of com.codename1.ui in project CodenameOne by codenameone.
the class BorderEditor method updateBorder.
private void updateBorder(boolean updateEnabled) {
if (updateEnabled) {
okButton.setEnabled(true);
for (JComponent c : comboSelectionEnabled[0]) {
c.setEnabled(false);
}
if (borderType.getSelectedIndex() > 1) {
List<JComponent> colorElements = colorComponents;
if (borderType.getSelectedIndex() == 6 && !imageMode.isSelected()) {
colorElements = new ArrayList<JComponent>();
} else {
if (borderType.getSelectedIndex() < 6 && !themeColors.isSelected()) {
colorElements = new ArrayList<JComponent>();
} else {
if (borderType.getSelectedIndex() > 6) {
colorElements = new ArrayList<JComponent>();
}
}
}
for (JComponent c : comboSelectionEnabled[borderType.getSelectedIndex()]) {
// if colors arrive from the theme then don't enable any color related element
c.setEnabled(!colorElements.contains(c));
}
}
}
if (borderType.getSelectedIndex() == borderType.getItemCount() - 2) {
// we need to use a special case because a theme with no images will have a different offset for the border
currentBorder = RoundBorder.create().color(getColor(backgroundColor)).opacity(((Number) opacity.getValue()).intValue()).rectangle(isRectangle.isSelected()).shadowBlur(((Number) shadowBlur.getValue()).floatValue()).shadowOpacity(((Number) shadowOpacity.getValue()).intValue()).shadowSpread(((Number) shadowSpread.getValue()).intValue()).shadowX(((Number) shadowX.getValue()).floatValue()).shadowY(((Number) shadowY.getValue()).floatValue()).stroke(((Number) strokeThickness.getValue()).floatValue(), strokeMillimeter.isSelected()).strokeColor(getColor(strokeColor)).strokeOpacity(((Number) strokeOpacity.getValue()).intValue());
} else {
if (borderType.getSelectedIndex() == borderType.getItemCount() - 1) {
// we need to use a special case because a theme with no images will have a different offset for the border
currentBorder = RoundRectBorder.create().shadowBlur(((Number) rrShadowBlur.getValue()).floatValue()).shadowOpacity(((Number) rrShadowOpacity.getValue()).intValue()).shadowSpread(((Number) rrShadowSpread.getValue()).floatValue()).shadowX(((Number) rrShadowX.getValue()).floatValue()).shadowY(((Number) rrShadowY.getValue()).floatValue()).stroke(((Number) rrStrokeThickness.getValue()).floatValue(), rrStrokeMillimeter.isSelected()).strokeColor(getColor(rrStrokeColor)).strokeOpacity(((Number) rrStrokeOpacity.getValue()).intValue()).bezierCorners(rrBezier.isSelected()).cornerRadius(((Number) rrRadius.getValue()).floatValue()).bottomOnlyMode(rrMode.getSelectedIndex() == 1).topOnlyMode(rrMode.getSelectedIndex() == 2);
} else {
switch(borderType.getSelectedIndex()) {
case 0:
// null border
currentBorder = null;
break;
case 1:
// empty border
currentBorder = Border.getEmpty();
break;
case 2:
// bevel border
if (themeColors.isSelected()) {
if (raisedBorder.isSelected()) {
currentBorder = Border.createBevelRaised();
} else {
currentBorder = Border.createBevelLowered();
}
} else {
if (raisedBorder.isSelected()) {
currentBorder = Border.createBevelRaised(getColor(highlightColor), getColor(secondaryHighlightColor), getColor(shadowColor), getColor(secondaryShadowColor));
} else {
currentBorder = Border.createBevelLowered(getColor(highlightColor), getColor(secondaryHighlightColor), getColor(shadowColor), getColor(secondaryShadowColor));
}
}
break;
case 3:
// etched border
if (themeColors.isSelected()) {
if (raisedBorder.isSelected()) {
currentBorder = Border.createEtchedRaised();
} else {
currentBorder = Border.createEtchedLowered();
}
} else {
if (raisedBorder.isSelected()) {
currentBorder = Border.createEtchedRaised(getColor(highlightColor), getColor(shadowColor));
} else {
currentBorder = Border.createEtchedLowered(getColor(highlightColor), getColor(shadowColor));
}
}
break;
case 7:
{
// this is a theme with no images
if (borderType.getItemCount() < 8) {
break;
}
// image border
Image c = getButtonImageBorderIcon(this.center);
if (imageMode.isSelected()) {
currentBorder = Border.createImageBorder(getButtonImageBorderIconNotNull(top), getButtonImageBorderIconNotNull(topLeft), c);
} else {
currentBorder = Border.createImageBorder(getButtonImageBorderIconNotNull(top), getButtonImageBorderIconNotNull(bottom), getButtonImageBorderIconNotNull(left), getButtonImageBorderIconNotNull(right), getButtonImageBorderIconNotNull(topLeft), getButtonImageBorderIconNotNull(topRight), getButtonImageBorderIconNotNull(bottomLeft), getButtonImageBorderIconNotNull(bottomRight), c);
}
break;
}
case 8:
{
Image c = getButtonImageBorderIcon(this.center);
currentBorder = Border.createHorizonalImageBorder(getButtonImageBorderIconNotNull(left), getButtonImageBorderIconNotNull(right), c);
break;
}
case 9:
{
Image c = getButtonImageBorderIcon(this.center);
currentBorder = Border.createVerticalImageBorder(getButtonImageBorderIconNotNull(top), getButtonImageBorderIconNotNull(bottom), c);
break;
}
case 4:
// line border
if (thicknessMillimeters.isSelected()) {
if (themeColors.isSelected()) {
currentBorder = Border.createLineBorder(((Number) thickness.getValue()).floatValue());
} else {
currentBorder = Border.createLineBorder(((Number) thickness.getValue()).floatValue(), getColor(lineColor));
}
} else {
if (themeColors.isSelected()) {
currentBorder = Border.createLineBorder(((Number) thickness.getValue()).intValue());
} else {
currentBorder = Border.createLineBorder(((Number) thickness.getValue()).intValue(), getColor(lineColor));
}
}
break;
case 5:
// underline border
if (thicknessMillimeters.isSelected()) {
if (themeColors.isSelected()) {
currentBorder = Border.createUndelineBorder(((Number) thickness.getValue()).floatValue());
} else {
currentBorder = Border.createUnderlineBorder(((Number) thickness.getValue()).floatValue(), getColor(lineColor));
}
} else {
if (themeColors.isSelected()) {
currentBorder = Border.createUndelineBorder(((Number) thickness.getValue()).intValue());
} else {
currentBorder = Border.createUnderlineBorder(((Number) thickness.getValue()).intValue(), getColor(lineColor));
}
}
break;
case 6:
// rounded border
if (themeColors.isSelected()) {
currentBorder = Border.createRoundBorder(((Number) arcWidth.getValue()).intValue(), ((Number) arcHeight.getValue()).intValue());
} else {
currentBorder = Border.createRoundBorder(((Number) arcWidth.getValue()).intValue(), ((Number) arcHeight.getValue()).intValue(), getColor(lineColor));
}
break;
}
}
}
final CodenameOneComponentWrapper w = (CodenameOneComponentWrapper) imageBorderPreview;
final Border finalBorder = currentBorder;
final Button b = (Button) w.getCodenameOneComponent();
Display.getInstance().callSerially(new Runnable() {
@Override
public void run() {
b.clearClientProperties();
b.setPreferredSize(new com.codename1.ui.geom.Dimension(200, 100));
b.getAllStyles().setPadding(20, 20, 20, 20);
b.getAllStyles().setBorder(finalBorder);
b.getParent().revalidate();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
w.revalidate();
}
});
}
});
}
use of com.codename1.ui in project CodenameOne by codenameone.
the class CodenameOneImplementation method downloadImageToCache.
/**
* Downloads an image from a URL to the cache. Platforms
* that support a native image cache {@link #supportsNativeImageCache() } (e.g. Javascript) override this method to defer to the
* platform's handling of cached images. Platforms that have a caches directory ({@link FileSystemStorage#hasCachesDir() }
* will use that directory to cache the image. Other platforms will just download to storage.
*
* @param url The URL of the image to download.
* @param onSuccess Callback on success.
* @param onFail Callback on fail.
*
* @see URLImage#createToCache(com.codename1.ui.EncodedImage, java.lang.String, com.codename1.ui.URLImage.ImageAdapter)
*/
public void downloadImageToCache(String url, SuccessCallback<Image> onSuccess, final FailureCallback<Image> onFail) {
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;
// We use Util.downloadImageToFileSystem rather than CodenameOneImplementation.downloadImageToFileSystem
// because we want it to try to load from file system first.
Util.downloadImageToFileSystem(url, filePath, onSuccess, onFail);
} else {
// We use Util.downloadImageToStorage rather than CodenameOneImplementation.downloadImageToStorage
// because we want it to try to load from storage first.
Util.downloadImageToStorage(url, "cn1_image_cache[" + url + "]", onSuccess, onFail);
}
}
use of com.codename1.ui in project CodenameOne by codenameone.
the class Util method readObject.
/**
* <p>Reads an object from the stream, notice that this is the inverse of the
* {@link #writeObject(java.lang.Object, java.io.DataOutputStream)}.</p>
*
* <p>
* The sample below demonstrates the usage and registration of the {@link com.codename1.io.Externalizable} interface:
* </p>
* <script src="https://gist.github.com/codenameone/858d8634e3cf1a82a1eb.js"></script>
*
* @param input the source input stream
* @throws IOException thrown by the stream
*/
public static Object readObject(DataInputStream input) throws IOException {
try {
if (!input.readBoolean()) {
return null;
}
String type = input.readUTF();
if ("int".equals(type)) {
return new Integer(input.readInt());
}
if ("byte".equals(type)) {
return new Byte(input.readByte());
}
if ("short".equals(type)) {
return new Short(input.readShort());
}
if ("long".equals(type)) {
return new Long(input.readLong());
}
if ("float".equals(type)) {
return new Float(input.readFloat());
}
if ("double".equals(type)) {
return new Double(input.readDouble());
}
if ("bool".equals(type)) {
return new Boolean(input.readBoolean());
}
if ("String".equals(type)) {
return input.readUTF();
}
if ("Date".equals(type)) {
return new Date(input.readLong());
}
if ("ObjectArray".equals(type)) {
Object[] v = new Object[input.readInt()];
int vlen = v.length;
for (int iter = 0; iter < vlen; iter++) {
v[iter] = readObject(input);
}
return v;
}
if ("ByteArray".equals(type)) {
byte[] v = new byte[input.readInt()];
input.readFully(v);
return v;
}
if ("LongArray".equals(type)) {
long[] v = new long[input.readInt()];
int vlen = v.length;
for (int iter = 0; iter < vlen; iter++) {
v[iter] = input.readLong();
}
return v;
}
if ("ShortArray".equals(type)) {
short[] v = new short[input.readInt()];
int vlen = v.length;
for (int iter = 0; iter < vlen; iter++) {
v[iter] = input.readShort();
}
return v;
}
if ("DoubleArray".equals(type)) {
double[] v = new double[input.readInt()];
int vlen = v.length;
for (int iter = 0; iter < vlen; iter++) {
v[iter] = input.readDouble();
}
return v;
}
if ("FloatArray".equals(type)) {
float[] v = new float[input.readInt()];
int vlen = v.length;
for (int iter = 0; iter < vlen; iter++) {
v[iter] = input.readFloat();
}
return v;
}
if ("IntArray".equals(type)) {
int[] v = new int[input.readInt()];
int vlen = v.length;
for (int iter = 0; iter < vlen; iter++) {
v[iter] = input.readInt();
}
return v;
}
if ("java.util.Vector".equals(type)) {
Vector v = new Vector();
int size = input.readInt();
for (int iter = 0; iter < size; iter++) {
v.addElement(readObject(input));
}
return v;
}
if ("java.util.Hashtable".equals(type)) {
Hashtable v = new Hashtable();
int size = input.readInt();
for (int iter = 0; iter < size; iter++) {
v.put(readObject(input), readObject(input));
}
return v;
}
if ("java.util.Collection".equals(type)) {
Collection v = new ArrayList();
int size = input.readInt();
for (int iter = 0; iter < size; iter++) {
v.add(readObject(input));
}
return v;
}
if ("java.util.Map".equals(type)) {
Map v = new HashMap();
int size = input.readInt();
for (int iter = 0; iter < size; iter++) {
v.put(readObject(input), readObject(input));
}
return v;
}
if ("EncodedImage".equals(type)) {
int width = input.readInt();
int height = input.readInt();
boolean op = input.readBoolean();
byte[] data = new byte[input.readInt()];
input.readFully(data);
return EncodedImage.create(data, width, height, op);
}
Class cls = (Class) externalizables.get(type);
if (cls != null) {
Object o = cls.newInstance();
if (o instanceof Externalizable) {
Externalizable ex = (Externalizable) o;
ex.internalize(input.readInt(), input);
return ex;
} else {
PropertyBusinessObject pb = (PropertyBusinessObject) o;
pb.getPropertyIndex().asExternalizable().internalize(input.readInt(), input);
return pb;
}
}
throw new IOException("Object type not supported: " + type);
} catch (InstantiationException ex1) {
Log.e(ex1);
throw new IOException(ex1.getClass().getName() + ": " + ex1.getMessage());
} catch (IllegalAccessException ex1) {
Log.e(ex1);
throw new IOException(ex1.getClass().getName() + ": " + ex1.getMessage());
}
}
use of com.codename1.ui in project CodenameOne by codenameone.
the class RequestBuilder method createRequest.
private ConnectionRequest createRequest(boolean parseJson) {
ConnectionRequest req = new Connection(parseJson);
for (String key : pathParams.keySet()) {
url = com.codename1.util.StringUtil.replaceAll(url, "{" + key + "}", pathParams.get(key));
}
if (contentType != null) {
req.setContentType(contentType);
}
req.setReadResponseForErrors(true);
req.setDuplicateSupported(true);
req.setUrl(url);
req.setHttpMethod(method);
req.setPost(method.equalsIgnoreCase("POST") || method.equalsIgnoreCase("PUT") || method.equalsIgnoreCase("PATCH"));
if (body != null) {
req.setRequestBody(body);
req.setWriteRequest(true);
}
if (timeout != null) {
req.setTimeout(timeout);
}
for (String key : queryParams.keySet()) {
req.addArgument(key, queryParams.get(key));
}
for (String key : headers.keySet()) {
req.addRequestHeader(key, headers.get(key));
}
return req;
}
use of com.codename1.ui in project CodenameOne by codenameone.
the class ResetableTextWatcher method edit.
/**
* Entry point for using this class
* @param impl The current running activity
* @param component Any subclass of com.codename1.ui.TextArea
* @param inputType One of the TextArea's input-type constants
*/
public static void edit(final AndroidImplementation impl, final Component component, final int inputType) {
if (impl.getActivity() == null) {
throw new IllegalArgumentException("activity is null");
}
if (component == null) {
throw new IllegalArgumentException("component is null");
}
if (!(component instanceof TextArea)) {
throw new IllegalArgumentException("component must be instance of TextArea");
}
final TextArea textArea = (TextArea) component;
final String initialText = textArea.getText();
textArea.putClientProperty("InPlaceEditView.initialText", initialText);
// 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.
String defaultAsyncEditingSetting = Display.getInstance().getProperty("android.VKBAlwaysOpen", null);
if (defaultAsyncEditingSetting == null) {
defaultAsyncEditingSetting = impl.isAsyncEditMode() ? "true" : "false";
Display.getInstance().setProperty("android.VKBAlwaysOpen", defaultAsyncEditingSetting);
}
boolean asyncEdit = "true".equals(defaultAsyncEditingSetting) ? true : false;
// Check if the form has any setting for asyncEditing that should override
// the application defaults.
final Form parentForm = component.getComponentForm();
if (parentForm == null) {
com.codename1.io.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("android.asyncEditing") != null) {
Object async = parentForm.getClientProperty("android.asyncEditing");
if (async instanceof Boolean) {
asyncEdit = ((Boolean) async).booleanValue();
// Log.p("Form overriding asyncEdit due to ios.asyncEditing client property: "+asyncEdit);
}
}
if (parentForm.isFormBottomPaddingEditingMode()) {
asyncEdit = true;
}
// then this will override all other settings.
if (component.getClientProperty("asyncEditing") != null) {
Object async = component.getClientProperty("asyncEditing");
if (async instanceof Boolean) {
asyncEdit = ((Boolean) async).booleanValue();
// Log.p("Overriding asyncEdit due to field asyncEditing client property: "+asyncEdit);
}
}
if (component.getClientProperty("android.asyncEditing") != null) {
Object async = component.getClientProperty("android.asyncEditing");
if (async instanceof Boolean) {
asyncEdit = ((Boolean) async).booleanValue();
// Log.p("Overriding asyncEdit due to field ios.asyncEditing client property: "+asyncEdit);
}
}
// if true, then in async mode we are currently editing and are switching to another field
final boolean isEditedFieldSwitch;
// If we are already editing, we need to finish that up before we proceed to edit the next field.
synchronized (editingLock) {
if (mIsEditing) {
if (impl.isAsyncEditMode()) {
// Using isEditedFieldSwitch was causing issues with cursors not showing up.
// https://github.com/codenameone/CodenameOne/issues/2353
// https://stackoverflow.com/questions/49004370/focus-behaviour-in-textarea-in-cn1
// Disabling this feature by default now, but can be re-enabled by setting
// Display.getInstance().setProperty("android.reuseTextEditorOnSwitch", "true");
// This editedFieldSwitch feature was added a while back to improve experience on older
// Android devices where the field switching was going too slow.
// https://github.com/codenameone/CodenameOne/issues/2012
// This issue was resolved in this commit (https://github.com/jaanushansen/CodenameOne/commit/f3e53a80704149e4d7cde276d01c1368bcdcfe2c)
// which was submitted as part of a pull request. This fix has been the source of several
// regressions, mostly related to properties not being propagated properly when a text field is changed
// However, this issue (with the cursor not showing up), doesn't appear to have a simple solution
// so, I'm disabling this feature for now.
isEditedFieldSwitch = "true".equals(Display.getInstance().getProperty("android.reuseTextEditorOnSwitch", "false"));
final String[] out = new String[1];
TextArea prevTextArea = null;
if (sInstance != null && sInstance.mLastEditText != null) {
prevTextArea = sInstance.mLastEditText.getTextArea();
}
if (prevTextArea != null) {
final TextArea fPrevTextArea = prevTextArea;
final String retVal = sInstance.mLastEditText.getText().toString();
Display.getInstance().callSerially(new Runnable() {
public void run() {
Display.getInstance().onEditingComplete(fPrevTextArea, retVal);
}
});
}
InPlaceEditView.setEditedTextField(textArea);
nextTextArea = null;
} else {
isEditedFieldSwitch = false;
final InPlaceEditView instance = sInstance;
if (instance != null && instance.mEditText != null && instance.mEditText.mTextArea == textArea) {
instance.showTextEditorAgain();
return;
}
if (!isClosing && sInstance != null && sInstance.mEditText != null) {
isClosing = true;
impl.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
instance.endEditing(REASON_UNDEFINED, true, 0);
}
});
}
afterClose = new Runnable() {
@Override
public void run() {
impl.callHideTextEditor();
Display.getInstance().editString(component, textArea.getMaxSize(), inputType, textArea.getText());
}
};
return;
}
} else {
isEditedFieldSwitch = false;
}
mIsEditing = true;
isClosing = false;
afterClose = null;
}
impl.setAsyncEditMode(asyncEdit);
// textArea.setPreferredSize(prefSize);
if (!impl.isAsyncEditMode() && textArea instanceof TextField) {
((TextField) textArea).setEditable(false);
}
final boolean scrollableParent = isScrollableParent(textArea);
// We wrap the text area so that we can safely pass data across to the
// android UI thread.
final TextAreaData textAreaData = new TextAreaData(textArea);
impl.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
if (!isEditedFieldSwitch) {
releaseEdit();
if (sInstance == null) {
sInstance = new InPlaceEditView(impl);
impl.relativeLayout.addView(sInstance);
}
// Let's try something new here
// We'll ALWAYS try resize edit mode (since it just works better)
// But we'll detect whether the field is still covered by the keyboard
// and switch to pan mode if necessary.
}
if (scrollableParent || parentForm.isFormBottomPaddingEditingMode()) {
setEditMode(true);
} else {
trySetEditMode(true);
}
sInstance.startEditing(impl.getActivity(), textAreaData, initialText, inputType, isEditedFieldSwitch);
}
});
final String[] out = new String[1];
// In order to reuse the code the runs after edit completion, we will wrap it in a runnable
// For sync edit mode, we will just run onComplete.run() at the end of this method. For
// Async mode we add the Runnable to the textarea as a client property, then run it
// when editing eventually completes.
Runnable onComplete = new Runnable() {
public void run() {
if (!impl.isAsyncEditMode() && textArea instanceof TextField) {
((TextField) textArea).setEditable(true);
}
textArea.setPreferredSize(null);
if (sInstance != null && sInstance.mLastEditText != null && sInstance.mLastEditText.mTextArea == textArea) {
String retVal = sInstance.mLastEditText.getText().toString();
if (!impl.isAsyncEditMode()) {
sInstance.mLastEditText = null;
impl.getActivity().runOnUiThread(new Runnable() {
public void run() {
releaseEdit();
}
});
}
out[0] = retVal;
} else {
out[0] = initialText;
}
Display.getInstance().onEditingComplete(component, out[0]);
if (impl.isAsyncEditMode()) {
impl.callHideTextEditor();
} else {
// lock.
if (sInstance != null) {
Display.getInstance().invokeAndBlock(new Runnable() {
public void run() {
while (sInstance != null) {
com.codename1.io.Util.sleep(5);
}
}
});
}
}
// Release the editing flag
synchronized (editingLock) {
mIsEditing = false;
}
// as a runnable ... this should take priority over the "nextTextArea" setting
if (afterClose != null) {
Display.getInstance().callSerially(afterClose);
} else if (nextTextArea != null) {
final TextArea next = nextTextArea;
nextTextArea = null;
next.requestFocus();
Display.getInstance().callSerially(new Runnable() {
public void run() {
Display.getInstance().editString(next, next.getMaxSize(), next.getConstraint(), next.getText());
}
});
}
}
};
textArea.requestFocus();
textArea.repaint();
if (impl.isAsyncEditMode()) {
component.putClientProperty("android.onAsyncEditingComplete", onComplete);
return;
}
// Make this call synchronous
// We set this flag so that waitForEditCompletion can block on it.
// The flag will be released inside the endEditing method which will
// allow the method to proceed.
waitingForSynchronousEditingCompletion = true;
waitForEditCompletion();
onComplete.run();
}
Aggregations