use of com.codename1.ui.util.xml.comps.Custom in project CodenameOne by codenameone.
the class LazyValueC method restoreComponentState.
/**
* By default Codename One stores the states of components in the navigation graph
* as it moves between forms. However, some components aren't recognized by Codename One
* by default to enable smaller executable size. This method can be overriden to enable
* storing the state of custom components
*
* @param c the component whose state should be restored
* @param destination the hashtable containing the state
*/
protected void restoreComponentState(Component c, Hashtable destination) {
if (shouldAutoStoreState()) {
Enumeration e = destination.keys();
while (e.hasMoreElements()) {
String currentKey = (String) e.nextElement();
Component cmp = findByName(currentKey, c);
if (cmp != null) {
Object value = destination.get(currentKey);
if (value instanceof Integer) {
if (cmp instanceof List) {
((List) cmp).setSelectedIndex(((Integer) value).intValue());
continue;
}
if (cmp instanceof Tabs) {
int val = ((Integer) value).intValue();
Tabs t = (Tabs) cmp;
if (t.getTabCount() > val) {
t.setSelectedIndex(val);
}
continue;
}
}
cmp.setComponentState(value);
}
}
}
}
use of com.codename1.ui.util.xml.comps.Custom in project CodenameOne by codenameone.
the class InstantUI method createEditUI.
/**
* Creates editing UI for the given business object
* @param bo the business object
* @param autoCommit true if the bindings used should be auto-committed
* @return a UI container that can be used to edit the business object
*/
public Container createEditUI(PropertyBusinessObject bo, boolean autoCommit) {
Container cnt;
if (Display.getInstance().isTablet()) {
TableLayout tl = new TableLayout(1, 2);
tl.setGrowHorizontally(true);
cnt = new Container(tl);
} else {
cnt = new Container(BoxLayout.y());
}
UiBinding uib = new UiBinding();
ArrayList<UiBinding.Binding> allBindings = new ArrayList<UiBinding.Binding>();
for (PropertyBase b : bo.getPropertyIndex()) {
if (isExcludedProperty(b)) {
continue;
}
Class cls = (Class) b.getClientProperty("cn1$cmpCls");
if (cls != null) {
try {
Component cmp = (Component) cls.newInstance();
cmp.setName(b.getName());
cnt.add(b.getLabel()).add(cmp);
allBindings.add(uib.bind(b, cmp));
} catch (Exception err) {
Log.e(err);
throw new RuntimeException("Custom property instant UI failed for " + b.getName() + " " + err);
}
continue;
}
String[] multiLabels = (String[]) b.getClientProperty("cn1$multiChceLbl");
if (multiLabels != null) {
// multi choice component
final Object[] multiValues = (Object[]) b.getClientProperty("cn1$multiChceVal");
if (multiLabels.length < 5) {
// toggle buttons
ButtonGroup bg = new ButtonGroup();
RadioButton[] rbs = new RadioButton[multiLabels.length];
cnt.add(b.getLabel());
Container radioBox = new Container(new GridLayout(multiLabels.length));
for (int iter = 0; iter < multiLabels.length; iter++) {
rbs[iter] = RadioButton.createToggle(multiLabels[iter], bg);
radioBox.add(rbs[iter]);
}
cnt.add(radioBox);
allBindings.add(uib.bindGroup(b, multiValues, rbs));
} else {
Picker stringPicker = new Picker();
stringPicker.setStrings(multiLabels);
Map<Object, Object> m1 = new HashMap<Object, Object>();
Map<Object, Object> m2 = new HashMap<Object, Object>();
for (int iter = 0; iter < multiLabels.length; iter++) {
m1.put(multiLabels[iter], multiValues[iter]);
m2.put(multiValues[iter], multiLabels[iter]);
}
cnt.add(b.getLabel()).add(stringPicker);
allBindings.add(uib.bind(b, stringPicker, new UiBinding.PickerAdapter<Object>(new UiBinding.MappingConverter(m1), new UiBinding.MappingConverter(m2))));
}
continue;
}
Class t = b.getGenericType();
if (t != null) {
if (t == Boolean.class) {
CheckBox cb = new CheckBox();
uib.bind(b, cb);
cnt.add(b.getLabel()).add(cb);
continue;
}
if (t == Date.class) {
Picker dp = new Picker();
dp.setType(Display.PICKER_TYPE_DATE);
uib.bind(b, dp);
cnt.add(b.getLabel()).add(dp);
continue;
}
}
TextField tf = new TextField();
tf.setConstraint(getTextFieldConstraint(b));
uib.bind(b, tf);
cnt.add(b.getLabel()).add(tf);
}
cnt.putClientProperty("cn1$iui-binding", uib.createGroupBinding(allBindings));
return cnt;
}
use of com.codename1.ui.util.xml.comps.Custom in project CodenameOne by codenameone.
the class UIBuilderOverride method createInstance.
/**
* Create a component instance from XML
*/
private Component createInstance(final ComponentEntry root, final EditableResources res, Container rootCnt, final Container parentContainer, final ArrayList<Runnable> postCreateTasks) {
try {
final Component c = createComponentType(root.getType());
if (rootCnt == null) {
rootCnt = (Container) c;
}
final Container rootContainer = rootCnt;
if (root.getBaseForm() != null) {
c.putClientProperty("%base_form%", root.getBaseForm());
}
c.putClientProperty(TYPE_KEY, root.getType());
c.setName(root.getName());
String clientProps = root.getClientProperties();
if (clientProps != null && clientProps.length() > 0) {
String[] props = clientProps.split(",");
StringBuilder b = new StringBuilder();
for (String p : props) {
String[] keyVal = p.split("=");
c.putClientProperty(keyVal[0], keyVal[1]);
if (b.length() > 0) {
b.append(",");
}
b.append(keyVal[0]);
}
c.putClientProperty("cn1$Properties", b.toString());
}
rootContainer.putClientProperty("%" + root.getName() + "%", c);
// layout must be first since we might need to rely on it later on with things such as constraints
if (root.getLayout() != null) {
modifyingProperty(c, PROPERTY_LAYOUT);
Layout l;
if (root.getLayout().equals("BorderLayout")) {
l = new BorderLayout();
if (root.isBorderLayoutAbsoluteCenter() != null) {
((BorderLayout) l).setAbsoluteCenter(root.isBorderLayoutAbsoluteCenter().booleanValue());
}
if (root.getBorderLayoutSwapCenter() != null) {
((BorderLayout) l).defineLandscapeSwap(BorderLayout.CENTER, root.getBorderLayoutSwapCenter());
}
if (root.getBorderLayoutSwapNorth() != null) {
((BorderLayout) l).defineLandscapeSwap(BorderLayout.NORTH, root.getBorderLayoutSwapNorth());
}
if (root.getBorderLayoutSwapSouth() != null) {
((BorderLayout) l).defineLandscapeSwap(BorderLayout.SOUTH, root.getBorderLayoutSwapSouth());
}
if (root.getBorderLayoutSwapEast() != null) {
((BorderLayout) l).defineLandscapeSwap(BorderLayout.EAST, root.getBorderLayoutSwapEast());
}
if (root.getBorderLayoutSwapWest() != null) {
((BorderLayout) l).defineLandscapeSwap(BorderLayout.WEST, root.getBorderLayoutSwapWest());
}
} else {
if (root.getLayout().equals("FlowLayout")) {
l = new FlowLayout();
((FlowLayout) l).setFillRows(root.isFlowLayoutFillRows());
((FlowLayout) l).setAlign(root.getFlowLayoutAlign());
((FlowLayout) l).setValign(root.getFlowLayoutValign());
} else {
if (root.getLayout().equals("GridLayout")) {
l = new GridLayout(root.getGridLayoutRows().intValue(), root.getGridLayoutColumns().intValue());
} else {
if (root.getLayout().equals("BoxLayout")) {
if (root.getBoxLayoutAxis().equals("X")) {
l = new BoxLayout(BoxLayout.X_AXIS);
} else {
l = new BoxLayout(BoxLayout.Y_AXIS);
}
} else {
if (root.getLayout().equals("TableLayout")) {
l = new TableLayout(root.getTableLayoutRows(), root.getTableLayoutColumns());
} else {
l = new LayeredLayout();
}
}
}
}
}
((Container) c).setLayout(l);
}
if (parentContainer != null && root.getLayoutConstraint() != null) {
modifyingProperty(c, PROPERTY_LAYOUT_CONSTRAINT);
if (parentContainer.getLayout() instanceof BorderLayout) {
c.putClientProperty("layoutConstraint", root.getLayoutConstraint().getValue());
} else {
TableLayout tl = (TableLayout) parentContainer.getLayout();
TableLayout.Constraint con = tl.createConstraint(root.getLayoutConstraint().getRow(), root.getLayoutConstraint().getColumn());
con.setHeightPercentage(root.getLayoutConstraint().getHeight());
con.setWidthPercentage(root.getLayoutConstraint().getWidth());
con.setHorizontalAlign(root.getLayoutConstraint().getAlign());
con.setHorizontalSpan(root.getLayoutConstraint().getSpanHorizontal());
con.setVerticalAlign(root.getLayoutConstraint().getValign());
con.setVerticalSpan(root.getLayoutConstraint().getSpanVertical());
c.putClientProperty("layoutConstraint", con);
}
}
if (root.getEmbed() != null && root.getEmbed().length() > 0) {
modifyingProperty(c, PROPERTY_EMBED);
rootContainer.putClientProperty(EMBEDDED_FORM_FLAG, "");
((EmbeddedContainer) c).setEmbed(root.getEmbed());
Container embed = createContainer(res, root.getEmbed(), (EmbeddedContainer) c);
if (embed != null) {
if (embed instanceof Form) {
embed = formToContainer((Form) embed);
}
((EmbeddedContainer) c).addComponent(BorderLayout.CENTER, embed);
// this isn't exactly the "right thing" but its the best we can do to make all
// use cases work
beforeShowContainer(embed);
postShowContainer(embed);
}
}
if (root.isToggle() != null) {
modifyingProperty(c, PROPERTY_TOGGLE_BUTTON);
((Button) c).setToggle(root.isToggle().booleanValue());
}
if (root.getGroup() != null) {
modifyingProperty(c, PROPERTY_RADIO_GROUP);
((RadioButton) c).setGroup(root.getGroup());
}
if (root.isSelected() != null) {
modifyingProperty(c, PROPERTY_SELECTED);
if (c instanceof RadioButton) {
((RadioButton) c).setSelected(root.isSelected().booleanValue());
} else {
((CheckBox) c).setSelected(root.isSelected().booleanValue());
}
}
if (root.isScrollableX() != null) {
modifyingProperty(c, PROPERTY_SCROLLABLE_X);
((Container) c).setScrollableX(root.isScrollableX().booleanValue());
}
if (root.isScrollableY() != null) {
modifyingProperty(c, PROPERTY_SCROLLABLE_Y);
((Container) c).setScrollableY(root.isScrollableY().booleanValue());
}
if (root.isTensileDragEnabled() != null) {
modifyingProperty(c, PROPERTY_TENSILE_DRAG_ENABLED);
c.setTensileDragEnabled(root.isTensileDragEnabled().booleanValue());
}
if (root.isTactileTouch() != null) {
modifyingProperty(c, PROPERTY_TACTILE_TOUCH);
c.setTactileTouch(root.isTactileTouch().booleanValue());
}
if (root.isSnapToGrid() != null) {
modifyingProperty(c, PROPERTY_SNAP_TO_GRID);
c.setSnapToGrid(root.isSnapToGrid().booleanValue());
}
if (root.isFlatten() != null) {
modifyingProperty(c, PROPERTY_FLATTEN);
c.setFlatten(root.isFlatten().booleanValue());
}
if (root.getText() != null) {
modifyingProperty(c, PROPERTY_TEXT);
if (c instanceof Label) {
((Label) c).setText(root.getText());
} else {
((TextArea) c).setText(root.getText());
}
}
if (root.getMaxSize() != null) {
modifyingProperty(c, PROPERTY_TEXT_MAX_LENGTH);
((TextArea) c).setMaxSize(root.getMaxSize().intValue());
}
if (root.getConstraint() != null) {
modifyingProperty(c, PROPERTY_TEXT_CONSTRAINT);
((TextArea) c).setConstraint(root.getConstraint().intValue());
}
if (root.getAlignment() != null) {
modifyingProperty(c, PROPERTY_ALIGNMENT);
if (c instanceof Label) {
((Label) c).setAlignment(root.getAlignment().intValue());
} else {
((TextArea) c).setAlignment(root.getAlignment().intValue());
}
}
if (root.isGrowByContent() != null) {
modifyingProperty(c, PROPERTY_TEXT_AREA_GROW);
((TextArea) c).setGrowByContent(root.isGrowByContent().booleanValue());
}
if (root.getTabPlacement() != null) {
modifyingProperty(c, PROPERTY_TAB_PLACEMENT);
((Tabs) c).setTabPlacement(root.getTabPlacement().intValue());
}
if (root.getTabTextPosition() != null) {
modifyingProperty(c, PROPERTY_TAB_TEXT_POSITION);
((Tabs) c).setTabTextPosition(root.getTabTextPosition().intValue());
}
if (root.getUiid() != null) {
modifyingProperty(c, PROPERTY_UIID);
c.setUIID(root.getUiid());
}
if (root.getDialogUIID() != null) {
modifyingProperty(c, PROPERTY_DIALOG_UIID);
((Dialog) c).setDialogUIID(root.getDialogUIID());
}
if (root.isDisposeWhenPointerOutOfBounds() != null) {
modifyingProperty(c, PROPERTY_DISPOSE_WHEN_POINTER_OUT);
((Dialog) c).setDisposeWhenPointerOutOfBounds(root.isDisposeWhenPointerOutOfBounds());
}
if (root.getCloudBoundProperty() != null) {
modifyingProperty(c, PROPERTY_CLOUD_BOUND_PROPERTY);
c.setCloudBoundProperty(root.getCloudBoundProperty());
}
if (root.getCloudDestinationProperty() != null) {
modifyingProperty(c, PROPERTY_CLOUD_DESTINATION_PROPERTY);
c.setCloudDestinationProperty(root.getCloudDestinationProperty());
}
if (root.getDialogPosition() != null && root.getDialogPosition().length() > 0) {
modifyingProperty(c, PROPERTY_DIALOG_POSITION);
((Dialog) c).setDialogPosition(root.getDialogPosition());
}
if (root.isFocusable() != null) {
modifyingProperty(c, PROPERTY_FOCUSABLE);
c.setFocusable(root.isFocusable().booleanValue());
}
if (root.isEnabled() != null) {
modifyingProperty(c, PROPERTY_ENABLED);
c.setEnabled(root.isEnabled().booleanValue());
}
if (root.isScrollVisible() != null) {
modifyingProperty(c, PROPERTY_SCROLL_VISIBLE);
c.setScrollVisible(root.isScrollVisible().booleanValue());
}
if (root.getIcon() != null) {
modifyingProperty(c, PROPERTY_ICON);
((Label) c).setIcon(res.getImage(root.getIcon()));
}
if (root.getRolloverIcon() != null) {
modifyingProperty(c, PROPERTY_ROLLOVER_ICON);
((Button) c).setRolloverIcon(res.getImage(root.getRolloverIcon()));
}
if (root.getPressedIcon() != null) {
modifyingProperty(c, PROPERTY_PRESSED_ICON);
((Button) c).setPressedIcon(res.getImage(root.getPressedIcon()));
}
if (root.getDisabledIcon() != null) {
modifyingProperty(c, PROPERTY_DISABLED_ICON);
((Button) c).setDisabledIcon(res.getImage(root.getDisabledIcon()));
}
if (root.getGap() != null) {
modifyingProperty(c, PROPERTY_GAP);
((Label) c).setGap(root.getGap().intValue());
}
if (root.getVerticalAlignment() != null) {
modifyingProperty(c, PROPERTY_VERTICAL_ALIGNMENT);
if (c instanceof Label) {
((Label) c).setVerticalAlignment(root.getVerticalAlignment().intValue());
} else {
((TextArea) c).setVerticalAlignment(root.getVerticalAlignment().intValue());
}
}
if (root.getTextPosition() != null) {
modifyingProperty(c, PROPERTY_TEXT_POSITION);
((Label) c).setTextPosition(root.getTextPosition().intValue());
}
if (root.getTitle() != null) {
modifyingProperty(c, PROPERTY_TITLE);
((Form) c).setTitle(root.getTitle());
}
// components should be added when we've set everything else up
if (root.getComponent() != null) {
modifyingProperty(c, PROPERTY_COMPONENTS);
if (c instanceof Tabs) {
for (ComponentEntry ent : root.getComponent()) {
Component newCmp = createInstance(ent, res, rootContainer, (Container) c, postCreateTasks);
((Tabs) c).addTab(ent.getTabTitle(), newCmp);
}
} else {
for (ComponentEntry ent : root.getComponent()) {
Component newCmp = createInstance(ent, res, rootContainer, (Container) c, postCreateTasks);
Object cons = newCmp.getClientProperty("layoutConstraint");
if (cons != null) {
modifyingProperty(c, PROPERTY_LAYOUT_CONSTRAINT);
((Container) c).addComponent(cons, newCmp);
} else {
((Container) c).addComponent(newCmp);
}
}
}
}
if (root.getColumns() != null) {
modifyingProperty(c, PROPERTY_COLUMNS);
((TextArea) c).setColumns(root.getColumns().intValue());
}
if (root.getRows() != null) {
modifyingProperty(c, PROPERTY_ROWS);
((TextArea) c).setRows(root.getRows().intValue());
}
if (root.getHint() != null) {
modifyingProperty(c, PROPERTY_HINT);
if (c instanceof List) {
((List) c).setHint(root.getHint());
} else {
((TextArea) c).setHint(root.getHint());
}
}
if (root.getHintIcon() != null) {
modifyingProperty(c, PROPERTY_HINT_ICON);
if (c instanceof List) {
((List) c).setHintIcon(res.getImage(root.getHint()));
} else {
((TextArea) c).setHintIcon(res.getImage(root.getHint()));
}
}
if (root.getItemGap() != null) {
modifyingProperty(c, PROPERTY_ITEM_GAP);
((List) c).setItemGap(root.getItemGap().intValue());
}
if (root.getFixedSelection() != null) {
modifyingProperty(c, PROPERTY_LIST_FIXED);
((List) c).setFixedSelection(root.getFixedSelection().intValue());
}
if (root.getOrientation() != null) {
modifyingProperty(c, PROPERTY_LIST_ORIENTATION);
((List) c).setOrientation(root.getOrientation().intValue());
}
if (c instanceof com.codename1.ui.List && !(c instanceof com.codename1.components.RSSReader)) {
modifyingProperty(c, PROPERTY_LIST_ITEMS);
if (root.getStringItem() != null && root.getStringItem().length > 0) {
String[] arr = new String[root.getStringItem().length];
for (int iter = 0; iter < arr.length; iter++) {
arr[iter] = root.getStringItem()[iter].getValue();
}
((List) c).setModel(new DefaultListModel<String>(arr));
} else {
if (root.getMapItems() != null && root.getMapItems().length > 0) {
Hashtable[] arr = new Hashtable[root.getMapItems().length];
for (int iter = 0; iter < arr.length; iter++) {
arr[iter] = new Hashtable();
if (root.getMapItems()[iter].getActionItem() != null) {
for (Val v : root.getMapItems()[iter].getActionItem()) {
Command cmd = createCommandImpl((String) v.getValue(), null, -1, v.getValue(), false, "");
cmd.putClientProperty(COMMAND_ACTION, (String) v.getValue());
arr[iter].put(v.getKey(), cmd);
}
}
if (root.getMapItems()[iter].getStringItem() != null) {
for (Val v : root.getMapItems()[iter].getActionItem()) {
arr[iter].put(v.getKey(), v.getValue());
}
}
if (root.getMapItems()[iter].getImageItem() != null) {
for (Val v : root.getMapItems()[iter].getActionItem()) {
arr[iter].put(v.getKey(), res.getImage(v.getValue()));
}
}
}
((List) c).setModel(new DefaultListModel<java.util.Map>(arr));
}
}
}
if (root.getSelectedRenderer() != null) {
modifyingProperty(c, PROPERTY_LIST_RENDERER);
GenericListCellRenderer g;
if (root.getSelectedRendererEven() == null) {
Component selected = createContainer(res, root.getSelectedRenderer());
Component unselected = createContainer(res, root.getUnselectedRenderer());
g = new GenericListCellRenderer(selected, unselected);
g.setFisheye(!root.getSelectedRenderer().equals(root.getUnselectedRenderer()));
} else {
Component selected = createContainer(res, root.getSelectedRenderer());
Component unselected = createContainer(res, root.getUnselectedRenderer());
Component even = createContainer(res, root.getSelectedRendererEven());
Component evenU = createContainer(res, root.getUnselectedRendererEven());
g = new GenericListCellRenderer(selected, unselected, even, evenU);
g.setFisheye(!root.getSelectedRenderer().equals(root.getUnselectedRenderer()));
}
if (c instanceof ContainerList) {
((ContainerList) c).setRenderer(g);
} else {
((List) c).setRenderer(g);
}
}
if (root.getNextForm() != null && root.getNextForm().length() > 0) {
modifyingProperty(c, PROPERTY_NEXT_FORM);
setNextForm(c, root.getNextForm(), res, rootContainer);
}
if (root.getCommand() != null) {
modifyingProperty(c, PROPERTY_COMMANDS);
for (CommandEntry cmd : root.getCommand()) {
Command currentCommand = createCommandImpl(cmd.getName(), res.getImage(cmd.getIcon()), cmd.getId(), cmd.getAction(), cmd.isBackCommand(), cmd.getArgument());
if (cmd.getRolloverIcon() != null && cmd.getRolloverIcon().length() > 0) {
currentCommand.setRolloverIcon(res.getImage(cmd.getRolloverIcon()));
}
if (cmd.getPressedIcon() != null && cmd.getPressedIcon().length() > 0) {
currentCommand.setPressedIcon(res.getImage(cmd.getPressedIcon()));
}
if (cmd.getDisabledIcon() != null && cmd.getDisabledIcon().length() > 0) {
currentCommand.setDisabledIcon(res.getImage(cmd.getDisabledIcon()));
}
if (cmd.isBackCommand()) {
((Form) c).setBackCommand(currentCommand);
}
((Form) c).addCommand(currentCommand);
currentCommand.putClientProperty(COMMAND_ARGUMENTS, cmd.getArgument());
currentCommand.putClientProperty(COMMAND_ACTION, cmd.getAction());
}
}
if (root.isCyclicFocus() != null) {
modifyingProperty(c, PROPERTY_CYCLIC_FOCUS);
((Form) c).setCyclicFocus(root.isCyclicFocus().booleanValue());
}
if (root.isRtl() != null) {
modifyingProperty(c, PROPERTY_RTL);
c.setRTL(root.isRtl().booleanValue());
}
if (root.getThumbImage() != null) {
modifyingProperty(c, PROPERTY_SLIDER_THUMB);
((Slider) c).setThumbImage(res.getImage(root.getThumbImage()));
}
if (root.isInfinite() != null) {
modifyingProperty(c, PROPERTY_INFINITE);
((Slider) c).setInfinite(root.isInfinite().booleanValue());
}
if (root.getProgress() != null) {
modifyingProperty(c, PROPERTY_PROGRESS);
((Slider) c).setProgress(root.getProgress().intValue());
}
if (root.isVertical() != null) {
modifyingProperty(c, PROPERTY_VERTICAL);
((Slider) c).setVertical(root.isVertical().booleanValue());
}
if (root.isEditable() != null) {
modifyingProperty(c, PROPERTY_EDITABLE);
if (c instanceof TextArea) {
((TextArea) c).setEditable(root.isEditable().booleanValue());
} else {
((Slider) c).setEditable(root.isEditable().booleanValue());
}
}
if (root.getIncrements() != null) {
modifyingProperty(c, PROPERTY_INCREMENTS);
((Slider) c).setIncrements(root.getIncrements().intValue());
}
if (root.isRenderPercentageOnTop() != null) {
modifyingProperty(c, PROPERTY_RENDER_PERCENTAGE_ON_TOP);
((Slider) c).setRenderPercentageOnTop(root.isRenderPercentageOnTop().booleanValue());
}
if (root.getMaxValue() != null) {
modifyingProperty(c, PROPERTY_MAX_VALUE);
((Slider) c).setMaxValue(root.getMaxValue().intValue());
}
if (root.getMinValue() != null) {
modifyingProperty(c, PROPERTY_MIN_VALUE);
((Slider) c).setMinValue(root.getMinValue().intValue());
}
if (root.getCommandName() != null) {
modifyingProperty(c, PROPERTY_COMMAND);
postCreateTasks.add(new Runnable() {
public void run() {
Command cmd = createCommandImpl(root.getCommandName(), res.getImage(root.getCommandIcon()), root.getCommandId().intValue(), root.getCommandAction(), root.isCommandBack().booleanValue(), root.getCommandArgument());
if (c instanceof Container) {
Button b = (Button) ((Container) c).getLeadComponent();
b.setCommand(cmd);
return;
}
((Button) c).setCommand(cmd);
}
});
}
if (root.getLabelFor() != null) {
modifyingProperty(c, PROPERTY_LABEL_FOR);
postCreateTasks.add(new Runnable() {
public void run() {
((Label) c).setLabelForComponent((Label) findByName(root.getLabelFor(), rootContainer));
}
});
}
if (root.getLeadComponent() != null) {
modifyingProperty(c, PROPERTY_LEAD_COMPONENT);
postCreateTasks.add(new Runnable() {
public void run() {
((Container) c).setLeadComponent(findByName(root.getLeadComponent(), rootContainer));
}
});
}
if (root.getNextFocusUp() != null) {
modifyingProperty(c, PROPERTY_NEXT_FOCUS_UP);
postCreateTasks.add(new Runnable() {
public void run() {
c.setNextFocusUp(findByName(root.getNextFocusUp(), rootContainer));
}
});
}
if (root.getNextFocusDown() != null) {
modifyingProperty(c, PROPERTY_NEXT_FOCUS_DOWN);
postCreateTasks.add(new Runnable() {
public void run() {
c.setNextFocusDown(findByName(root.getNextFocusDown(), rootContainer));
}
});
}
if (root.getNextFocusLeft() != null) {
modifyingProperty(c, PROPERTY_NEXT_FOCUS_LEFT);
postCreateTasks.add(new Runnable() {
public void run() {
c.setNextFocusLeft(findByName(root.getNextFocusLeft(), rootContainer));
}
});
}
if (root.getNextFocusRight() != null) {
modifyingProperty(c, PROPERTY_NEXT_FOCUS_RIGHT);
postCreateTasks.add(new Runnable() {
public void run() {
c.setNextFocusRight(findByName(root.getNextFocusRight(), rootContainer));
}
});
}
// custom settings are always last after all other properties
if (root.getCustom() != null && root.getCustom().length > 0) {
modifyingProperty(c, PROPERTY_CUSTOM);
for (Custom cust : root.getCustom()) {
modifyingCustomProperty(c, cust.getName());
Object value = null;
Class customType = UserInterfaceEditor.getPropertyCustomType(c, cust.getName());
if (customType.isArray()) {
if (customType == String[].class) {
if (cust.getStr() != null) {
String[] arr = new String[cust.getStr().length];
for (int iter = 0; iter < arr.length; iter++) {
arr[iter] = cust.getStr()[iter].getValue();
}
c.setPropertyValue(cust.getName(), arr);
} else {
c.setPropertyValue(cust.getName(), null);
}
continue;
}
if (customType == String[][].class) {
if (cust.getArr() != null) {
String[][] arr = new String[cust.getArr().length][];
for (int iter = 0; iter < arr.length; iter++) {
if (cust.getArr()[iter] != null && cust.getArr()[iter].getValue() != null) {
arr[iter] = new String[cust.getArr()[iter].getValue().length];
for (int inter = 0; inter < arr[iter].length; inter++) {
arr[iter][inter] = cust.getArr()[iter].getValue()[inter].getValue();
}
}
}
c.setPropertyValue(cust.getName(), arr);
} else {
c.setPropertyValue(cust.getName(), null);
}
continue;
}
if (customType == com.codename1.ui.Image[].class) {
if (cust.getStr() != null) {
com.codename1.ui.Image[] arr = new com.codename1.ui.Image[cust.getStr().length];
for (int iter = 0; iter < arr.length; iter++) {
arr[iter] = res.getImage(cust.getStr()[iter].getValue());
}
c.setPropertyValue(cust.getName(), arr);
} else {
c.setPropertyValue(cust.getName(), null);
}
continue;
}
if (customType == Object[].class) {
if (cust.getStringItem() != null) {
String[] arr = new String[cust.getStringItem().length];
for (int iter = 0; iter < arr.length; iter++) {
arr[iter] = cust.getStringItem()[iter].getValue();
}
c.setPropertyValue(cust.getName(), arr);
continue;
} else {
if (cust.getMapItems() != null) {
Hashtable[] arr = new Hashtable[cust.getMapItems().length];
for (int iter = 0; iter < arr.length; iter++) {
arr[iter] = new Hashtable();
if (cust.getMapItems()[iter].getActionItem() != null) {
for (Val v : cust.getMapItems()[iter].getActionItem()) {
Command cmd = createCommandImpl(v.getValue(), null, -1, v.getValue(), false, "");
cmd.putClientProperty(COMMAND_ACTION, v.getValue());
value = cmd;
arr[iter].put(v.getKey(), cmd);
}
}
if (cust.getMapItems()[iter].getStringItem() != null) {
for (Val v : cust.getMapItems()[iter].getActionItem()) {
arr[iter].put(v.getKey(), v.getValue());
}
}
if (cust.getMapItems()[iter].getImageItem() != null) {
for (Val v : cust.getMapItems()[iter].getActionItem()) {
arr[iter].put(v.getKey(), res.getImage(v.getValue()));
}
}
}
c.setPropertyValue(cust.getName(), arr);
continue;
}
}
c.setPropertyValue(cust.getName(), null);
continue;
}
}
if (customType == String.class) {
c.setPropertyValue(cust.getName(), cust.getValue());
continue;
}
if (customType == Integer.class) {
if (cust.getValue() != null) {
c.setPropertyValue(cust.getName(), Integer.valueOf(cust.getValue()));
} else {
c.setPropertyValue(cust.getName(), null);
}
continue;
}
if (customType == Long.class) {
if (cust.getValue() != null) {
c.setPropertyValue(cust.getName(), Long.valueOf(cust.getValue()));
} else {
c.setPropertyValue(cust.getName(), null);
}
continue;
}
if (customType == Double.class) {
if (cust.getValue() != null) {
c.setPropertyValue(cust.getName(), Double.valueOf(cust.getValue()));
} else {
c.setPropertyValue(cust.getName(), null);
}
continue;
}
if (customType == Date.class) {
if (cust.getValue() != null) {
c.setPropertyValue(cust.getName(), new Date(Long.parseLong(cust.getValue())));
} else {
c.setPropertyValue(cust.getName(), null);
}
continue;
}
if (customType == Float.class) {
if (cust.getValue() != null) {
c.setPropertyValue(cust.getName(), Float.valueOf(cust.getValue()));
} else {
c.setPropertyValue(cust.getName(), null);
}
continue;
}
if (customType == Byte.class) {
if (cust.getValue() != null) {
c.setPropertyValue(cust.getName(), Byte.valueOf(cust.getValue()));
} else {
c.setPropertyValue(cust.getName(), null);
}
continue;
}
if (customType == Character.class) {
if (cust.getValue() != null && ((String) cust.getValue()).length() > 0) {
c.setPropertyValue(cust.getName(), new Character(((String) cust.getValue()).charAt(0)));
} else {
c.setPropertyValue(cust.getName(), null);
}
continue;
}
if (customType == Boolean.class) {
if (cust.getValue() != null) {
c.setPropertyValue(cust.getName(), Boolean.valueOf(cust.getValue()));
} else {
c.setPropertyValue(cust.getName(), null);
}
continue;
}
if (customType == com.codename1.ui.Image.class) {
if (cust.getValue() != null) {
c.setPropertyValue(cust.getName(), res.getImage(cust.getValue()));
} else {
c.setPropertyValue(cust.getName(), null);
}
continue;
}
if (customType == com.codename1.ui.Container.class) {
// resource might have been removed we need to fail gracefully
String[] uiNames = res.getUIResourceNames();
for (int iter = 0; iter < uiNames.length; iter++) {
if (uiNames[iter].equals(cust.getName())) {
c.setPropertyValue(cust.getName(), createContainer(res, cust.getName()));
continue;
}
}
c.setPropertyValue(cust.getName(), null);
continue;
}
if (customType == com.codename1.ui.list.CellRenderer.class) {
if (cust.getUnselectedRenderer() != null) {
GenericListCellRenderer g;
if (cust.getSelectedRendererEven() == null) {
Component selected = createContainer(res, cust.getSelectedRenderer());
Component unselected = createContainer(res, cust.getUnselectedRenderer());
g = new GenericListCellRenderer(selected, unselected);
g.setFisheye(!cust.getSelectedRenderer().equals(cust.getUnselectedRenderer()));
} else {
Component selected = createContainer(res, cust.getSelectedRenderer());
Component unselected = createContainer(res, cust.getUnselectedRenderer());
Component even = createContainer(res, cust.getSelectedRendererEven());
Component evenU = createContainer(res, cust.getUnselectedRendererEven());
g = new GenericListCellRenderer(selected, unselected, even, evenU);
g.setFisheye(!cust.getSelectedRenderer().equals(cust.getUnselectedRenderer()));
}
c.setPropertyValue(cust.getName(), g);
continue;
}
c.setPropertyValue(cust.getName(), null);
continue;
}
}
}
return c;
} catch (Throwable t) {
t.printStackTrace();
JOptionPane.showMessageDialog(java.awt.Frame.getFrames()[0], "Error creating component: " + root.getName() + "\n" + t.toString() + "\ntrying to recover...", "Error", JOptionPane.ERROR_MESSAGE);
return null;
}
}
use of com.codename1.ui.util.xml.comps.Custom in project CodenameOne by codenameone.
the class UserInterfaceEditor method appendComponentXMLBody.
private static void appendComponentXMLBody(com.codename1.ui.Container containerInstance, com.codename1.ui.Component cmp, StringBuilder build, EditableResources res, String indent) {
if (isPropertyModified(cmp, PROPERTY_LAYOUT_CONSTRAINT) || (cmp.getParent() != null && cmp.getParent().getLayout() instanceof com.codename1.ui.layouts.BorderLayout)) {
if (cmp.getParent() != null && cmp != containerInstance && cmp.getClientProperty("%base_form%") == null) {
com.codename1.ui.layouts.Layout l = cmp.getParent().getLayout();
if (l instanceof com.codename1.ui.layouts.BorderLayout) {
build.append(indent);
build.append("<layoutConstraint value=\"");
build.append((String) l.getComponentConstraint(cmp));
build.append("\" />\n");
} else {
if (l instanceof com.codename1.ui.table.TableLayout) {
build.append(indent);
com.codename1.ui.table.TableLayout.Constraint con = (com.codename1.ui.table.TableLayout.Constraint) l.getComponentConstraint(cmp);
build.append("<layoutConstraint row=\"");
build.append(getInt("row", con.getClass(), con));
build.append("\" column=\"");
build.append(getInt("column", con.getClass(), con));
build.append("\" height=\"");
build.append(getInt("height", con.getClass(), con));
build.append("\" width=\"");
build.append(getInt("width", con.getClass(), con));
build.append("\" align=\"");
build.append(getInt("align", con.getClass(), con));
build.append("\" spanHorizontal=\"");
build.append(getInt("spanHorizontal", con.getClass(), con));
build.append("\" valign=\"");
build.append(getInt("valign", con.getClass(), con));
build.append("\" spanVertical=\"");
build.append(getInt("spanVertical", con.getClass(), con));
build.append("\" />\n");
}
}
}
}
// don't persist children of subclasses like Table etc.
if (cmp.getClass() == com.codename1.ui.Container.class || cmp instanceof com.codename1.ui.Form || cmp instanceof com.codename1.ui.ComponentGroup) {
com.codename1.ui.Container cnt = (com.codename1.ui.Container) cmp;
if (cnt instanceof com.codename1.ui.Form) {
cnt = ((com.codename1.ui.Form) cnt).getContentPane();
}
for (int iter = 0; iter < cnt.getComponentCount(); iter++) {
persistToXML(containerInstance, cnt.getComponentAt(iter), build, res, indent);
}
}
if (cmp instanceof com.codename1.ui.List && !(cmp instanceof com.codename1.components.RSSReader)) {
com.codename1.ui.List lst = (com.codename1.ui.List) cmp;
for (int iter = 0; iter < lst.getModel().getSize(); iter++) {
Object o = lst.getModel().getItemAt(iter);
appendMapOrString(o, build, indent, res);
}
}
if (isPropertyModified(cmp, PROPERTY_CUSTOM)) {
for (String propName : cmp.getPropertyNames()) {
if (isCustomPropertyModified(cmp, propName) && !propName.startsWith("$")) {
build.append(indent);
build.append("<custom name=\"");
build.append(propName);
Class type = getPropertyCustomType(cmp, propName);
Object value = cmp.getPropertyValue(propName);
if (value == null) {
build.append("\" />\n");
continue;
}
if (type.isArray()) {
// 2d array
if (type.getComponentType().isArray()) {
build.append("\" type=\"");
build.append(type.getComponentType().getComponentType().getName());
build.append("\" array=\"true\" dimensions=\"2");
} else {
build.append("\" type=\"");
build.append(type.getComponentType().getName());
build.append("\" array=\"true\" dimensions=\"1");
}
} else {
build.append("\" type=\"");
build.append(type.getName());
}
build.append("\" ");
if (type == String.class) {
build.append("value=\"");
build.append(xmlize((String) value));
build.append("\" />\n");
continue;
}
if (type == String[].class) {
build.append(">\n");
String[] result = (String[]) value;
for (int i = 0; i < result.length; i++) {
build.append(indent);
build.append(" ");
build.append("<str>");
build.append(xmlize(result[i]));
build.append("</str>\n");
}
build.append(indent);
build.append("</custom>\n");
continue;
}
if (type == String[][].class) {
String[][] result = (String[][]) value;
build.append(">\n");
for (int i = 0; i < result.length; i++) {
build.append(indent);
build.append(" ");
build.append("<arr>");
for (int j = 0; j < result[i].length; j++) {
build.append(indent);
build.append(" ");
build.append("<str>");
build.append(xmlize(result[i][j]));
build.append("</str>\n");
}
build.append(indent);
build.append(" ");
build.append("</arr>\n");
}
build.append(indent);
build.append("</custom>\n");
continue;
}
if (type == Integer.class) {
build.append("value=\"");
build.append(((Number) value).intValue());
build.append("\" />\n");
continue;
}
if (type == Long.class) {
build.append("value=\"");
build.append(((Number) value).longValue());
build.append("\" />\n");
continue;
}
if (type == Double.class) {
build.append("value=\"");
build.append(((Number) value).doubleValue());
build.append("\" />\n");
continue;
}
if (type == Date.class) {
build.append("value=\"");
build.append(((Date) value).getTime());
build.append("\" />\n");
continue;
}
if (type == Float.class) {
build.append("value=\"");
build.append(((Number) value).floatValue());
build.append("\" />\n");
continue;
}
if (type == Byte.class) {
build.append("value=\"");
build.append(((Number) value).byteValue());
build.append("\" />\n");
continue;
}
if (type == Boolean.class) {
build.append("value=\"");
build.append(((Boolean) value).booleanValue());
build.append("\" />\n");
continue;
}
if (type == com.codename1.ui.Image[].class) {
com.codename1.ui.Image[] result = (com.codename1.ui.Image[]) value;
build.append(">\n");
for (int i = 0; i < result.length; i++) {
build.append(indent);
build.append(" ");
if (result[i] == null) {
build.append("<str/>\n");
} else {
String id = res.findId(result[i]);
if (id == null) {
build.append("<str/>\n");
} else {
build.append("<str>");
build.append(xmlize(id));
build.append("</str>\n");
}
}
}
build.append(indent);
build.append("</custom>\n");
continue;
}
if (type == com.codename1.ui.Image.class) {
com.codename1.ui.Image result = (com.codename1.ui.Image) value;
String id = res.findId(result);
if (id != null) {
build.append("value=\"");
build.append(xmlize(id));
}
build.append("\" />\n");
continue;
}
if (type == com.codename1.ui.Container.class) {
build.append("value=\"");
build.append(xmlize(((com.codename1.ui.Container) value).getName()));
build.append("\" />\n");
continue;
}
if (type == com.codename1.ui.list.CellRenderer.class) {
com.codename1.ui.list.GenericListCellRenderer g = (com.codename1.ui.list.GenericListCellRenderer) value;
if (g.getSelectedEven() == null) {
build.append(" selectedRenderer=\"");
build.append(xmlize(g.getSelected().getName()));
build.append("\" unselectedRenderer=\"");
build.append(xmlize(g.getUnselected().getName()));
build.append("\" ");
} else {
build.append(" selectedRenderer=\"");
build.append(xmlize(g.getSelected().getName()));
build.append("\" unselectedRenderer=\"");
build.append(xmlize(g.getUnselected().getName()));
build.append(" selectedRendererEven=\"");
build.append(xmlize(g.getSelectedEven().getName()));
build.append("\" unselectedRendererEven=\"");
build.append(xmlize(g.getUnselectedEven().getName()));
build.append("\" ");
}
build.append("\" />\n");
continue;
}
if (type == Object[].class) {
build.append(">\n");
Object[] arr = (Object[]) value;
for (int iter = 0; iter < arr.length; iter++) {
Object o = arr[iter];
appendMapOrString(o, build, indent, res);
}
build.append(indent);
build.append("</custom>\n");
continue;
}
// none of the above then its a char
build.append("value=\"");
build.append(xmlize("" + ((Character) value).charValue()));
build.append("\" />\n");
}
}
}
}
use of com.codename1.ui.util.xml.comps.Custom in project CodenameOne by codenameone.
the class BytecodeMethod method optimize.
boolean optimize() {
int instructionCount = instructions.size();
// optimize away a method that only contains the void return instruction e.g. blank constructors etc.
if (instructionCount < 6) {
int realCount = instructionCount;
Instruction actual = null;
for (int iter = 0; iter < instructionCount; iter++) {
Instruction current = instructions.get(iter);
if (current instanceof LabelInstruction) {
realCount--;
continue;
}
if (current instanceof LineNumber) {
realCount--;
continue;
}
actual = current;
}
if (realCount == 1 && actual != null && actual.getOpcode() == Opcodes.RETURN) {
return false;
}
}
boolean astoreCalls = false;
boolean hasInstructions = false;
boolean hasTryCatch = false;
for (int iter = 0; iter < instructionCount - 1; iter++) {
Instruction current = instructions.get(iter);
if (current instanceof TryCatch) {
hasTryCatch = true;
}
current.setMethod(this);
if (current.isOptimized()) {
continue;
}
int currentOpcode = current.getOpcode();
switch(currentOpcode) {
case Opcodes.CHECKCAST:
{
// Remove the check cast for now as it gets in the way of other optimizations
instructions.remove(iter);
iter--;
instructionCount--;
break;
}
}
}
for (int iter = 0; iter < instructionCount - 1; iter++) {
Instruction current = instructions.get(iter);
if (current.isOptimized()) {
// we should skip it and proceed to the next one
continue;
}
Instruction next = instructions.get(iter + 1);
int currentOpcode = current.getOpcode();
int nextOpcode = next.getOpcode();
if (ArithmeticExpression.isArithmeticOp(current)) {
int addedIndex = ArithmeticExpression.tryReduce(instructions, iter);
if (addedIndex >= 0) {
iter = addedIndex;
instructionCount = instructions.size();
continue;
}
}
if (current instanceof Field) {
int newIter = Field.tryReduce(instructions, iter);
if (newIter >= 0) {
iter = newIter;
instructionCount = instructions.size();
continue;
}
}
switch(currentOpcode) {
case Opcodes.ARRAYLENGTH:
{
if (!dependentClasses.contains("java_lang_NullPointerException")) {
dependentClasses.add("java_lang_NullPointerException");
}
int newIter = ArrayLengthExpression.tryReduce(instructions, iter);
if (newIter >= 0) {
instructionCount = instructions.size();
iter = newIter;
continue;
}
break;
}
case Opcodes.DUP:
{
int newIter = DupExpression.tryReduce(instructions, iter);
if (newIter >= 0) {
iter = newIter;
instructionCount = instructions.size();
continue;
}
break;
}
case Opcodes.POP:
{
if (iter > 0) {
Instruction prev = instructions.get(iter - 1);
if (prev instanceof CustomInvoke) {
CustomInvoke inv = (CustomInvoke) prev;
if (inv.methodHasReturnValue()) {
inv.setNoReturn(true);
instructions.remove(iter);
iter--;
instructionCount--;
continue;
}
}
}
break;
}
case Opcodes.ASTORE:
case Opcodes.ISTORE:
case Opcodes.DSTORE:
case Opcodes.LSTORE:
case Opcodes.FSTORE:
{
if (iter > 0 && current instanceof VarOp) {
VarOp currentVarOp = (VarOp) current;
Instruction prev = instructions.get(iter - 1);
if (prev instanceof AssignableExpression) {
AssignableExpression expr = (AssignableExpression) prev;
StringBuilder sb = new StringBuilder();
if (currentVarOp.assignFrom(expr, sb)) {
instructions.remove(iter - 1);
instructions.remove(iter - 1);
instructions.add(iter - 1, new CustomIntruction(sb.toString(), sb.toString(), dependentClasses));
iter = iter - 1;
instructionCount = instructions.size();
continue;
}
} else if (prev instanceof CustomInvoke) {
CustomInvoke inv = (CustomInvoke) prev;
StringBuilder sb = new StringBuilder();
if (currentVarOp.assignFrom(inv, sb)) {
instructions.remove(iter - 1);
instructions.remove(iter - 1);
instructions.add(iter - 1, new CustomIntruction(sb.toString(), sb.toString(), dependentClasses));
iter = iter - 1;
instructionCount = instructions.size();
continue;
}
}
}
break;
}
case Opcodes.IRETURN:
case Opcodes.FRETURN:
case Opcodes.ARETURN:
case Opcodes.LRETURN:
case Opcodes.DRETURN:
{
if (iter > 0 && current instanceof BasicInstruction) {
Instruction prev = instructions.get(iter - 1);
if (prev instanceof AssignableExpression) {
AssignableExpression expr = (AssignableExpression) prev;
StringBuilder sb = new StringBuilder();
if (expr.assignTo(null, sb)) {
instructions.remove(iter - 1);
instructions.remove(iter - 1);
String exprString = sb.toString().trim();
String retVal = exprString;
sb.setLength(0);
if (!prev.isConstant()) {
sb.append("\n{\n ");
switch(currentOpcode) {
case Opcodes.IRETURN:
sb.append("JAVA_INT");
break;
case Opcodes.FRETURN:
sb.append("JAVA_FLOAT");
break;
case Opcodes.ARETURN:
sb.append("JAVA_OBJECT");
break;
case Opcodes.LRETURN:
sb.append("JAVA_LONG");
break;
case Opcodes.DRETURN:
sb.append("JAVA_DOUBLE");
break;
}
sb.append(" ___returnValue=").append(exprString).append(";\n");
retVal = "___returnValue";
}
if (synchronizedMethod) {
if (staticMethod) {
sb.append(" monitorExit(threadStateData, (JAVA_OBJECT)&class__");
sb.append(getClsName());
sb.append(");\n");
} else {
sb.append(" monitorExit(threadStateData, __cn1ThisObject);\n");
}
}
if (hasTryCatch) {
sb.append(" releaseForReturnInException(threadStateData, cn1LocalsBeginInThread, methodBlockOffset); return ").append(retVal).append(";\n");
} else {
sb.append(" releaseForReturn(threadStateData, cn1LocalsBeginInThread); return ").append(retVal).append(";\n");
}
if (!prev.isConstant()) {
sb.append("}\n");
}
instructions.add(iter - 1, new CustomIntruction(sb.toString(), sb.toString(), dependentClasses));
iter--;
instructionCount = instructions.size();
continue;
}
} else if (prev instanceof CustomInvoke) {
CustomInvoke expr = (CustomInvoke) prev;
String returnType = expr.getReturnValue();
if (returnType != null && !"JAVA_OBJECT".equals(returnType)) {
// We can't safely return a JAVA_OBJECT directly because it needs to be added
// to the stack for the GC
StringBuilder sb = new StringBuilder();
if (expr.appendExpression(sb)) {
instructions.remove(iter - 1);
instructions.remove(iter - 1);
String exprString = sb.toString().trim();
String retVal = exprString;
sb.setLength(0);
if (!expr.isConstant()) {
sb.append("\n{\n ");
switch(currentOpcode) {
case Opcodes.IRETURN:
sb.append("JAVA_INT");
break;
case Opcodes.FRETURN:
sb.append("JAVA_FLOAT");
break;
case Opcodes.ARETURN:
sb.append("JAVA_OBJECT");
break;
case Opcodes.LRETURN:
sb.append("JAVA_LONG");
break;
case Opcodes.DRETURN:
sb.append("JAVA_DOUBLE");
break;
}
sb.append(" ___returnValue=").append(exprString).append(";\n");
retVal = "___returnValue";
}
if (synchronizedMethod) {
if (staticMethod) {
sb.append(" monitorExit(threadStateData, (JAVA_OBJECT)&class__");
sb.append(getClsName());
sb.append(");\n");
} else {
sb.append(" monitorExit(threadStateData, __cn1ThisObject);\n");
}
}
if (hasTryCatch) {
sb.append(" releaseForReturnInException(threadStateData, cn1LocalsBeginInThread, methodBlockOffset); return ").append(retVal).append(";\n");
} else {
sb.append(" releaseForReturn(threadStateData, cn1LocalsBeginInThread); return ").append(retVal).append(";\n");
}
if (!expr.isConstant()) {
sb.append("}\n");
}
instructions.add(iter - 1, new CustomIntruction(sb.toString(), sb.toString(), dependentClasses));
iter--;
instructionCount = instructions.size();
continue;
}
}
}
}
break;
}
case Opcodes.BASTORE:
case Opcodes.SASTORE:
case Opcodes.CASTORE:
case Opcodes.AASTORE:
case Opcodes.IASTORE:
case Opcodes.DASTORE:
case Opcodes.LASTORE:
case Opcodes.FASTORE:
{
if (iter > 2 && current instanceof BasicInstruction) {
StringBuilder devNull = new StringBuilder();
String arrayLiteral = null;
String indexLiteral = null;
String valueLiteral = null;
Instruction prev3 = instructions.get(iter - 3);
if (prev3 instanceof AssignableExpression) {
if (((AssignableExpression) prev3).assignTo(null, devNull)) {
arrayLiteral = devNull.toString().trim();
}
}
devNull.setLength(0);
Instruction prev2 = instructions.get(iter - 2);
if (prev2 instanceof AssignableExpression) {
if (((AssignableExpression) prev2).assignTo(null, devNull)) {
indexLiteral = devNull.toString().trim();
}
}
devNull.setLength(0);
Instruction prev1 = instructions.get(iter - 1);
if (prev1 instanceof AssignableExpression) {
if (((AssignableExpression) prev1).assignTo(null, devNull)) {
valueLiteral = devNull.toString().trim();
}
} else if (prev1 instanceof CustomInvoke) {
devNull.setLength(0);
if (((CustomInvoke) prev1).appendExpression(devNull)) {
valueLiteral = devNull.toString().trim();
}
}
if (arrayLiteral != null && indexLiteral != null && valueLiteral != null) {
String elementType = null;
switch(current.getOpcode()) {
case Opcodes.AASTORE:
elementType = "OBJECT";
break;
case Opcodes.IASTORE:
elementType = "INT";
break;
case Opcodes.DASTORE:
elementType = "DOUBLE";
break;
case Opcodes.LASTORE:
elementType = "LONG";
break;
case Opcodes.FASTORE:
elementType = "FLOAT";
break;
case Opcodes.CASTORE:
elementType = "CHAR";
break;
case Opcodes.BASTORE:
elementType = "BYTE";
break;
case Opcodes.SASTORE:
elementType = "SHORT";
break;
}
if (elementType == null) {
break;
}
instructions.remove(iter - 3);
instructions.remove(iter - 3);
instructions.remove(iter - 3);
instructions.remove(iter - 3);
String code = " CN1_SET_ARRAY_ELEMENT_" + elementType + "(" + arrayLiteral + ", " + indexLiteral + ", " + valueLiteral + ");\n";
instructions.add(iter - 3, new CustomIntruction(code, code, dependentClasses));
iter = iter - 3;
instructionCount = instructions.size();
continue;
}
}
break;
}
case Opcodes.FALOAD:
case Opcodes.BALOAD:
case Opcodes.IALOAD:
case Opcodes.LALOAD:
case Opcodes.DALOAD:
case Opcodes.AALOAD:
case Opcodes.SALOAD:
case Opcodes.CALOAD:
{
int newIter = ArrayLoadExpression.tryReduce(instructions, iter);
if (newIter >= 0) {
iter = newIter;
instructionCount = instructions.size();
continue;
}
break;
}
/* Try to optimize if statements that just use constants
and local variables so that they don't need the intermediate
push and pop from the stack.
*/
case Opcodes.IF_ACMPEQ:
case Opcodes.IF_ACMPNE:
case Opcodes.IF_ICMPLE:
case Opcodes.IF_ICMPLT:
case Opcodes.IF_ICMPNE:
case Opcodes.IF_ICMPGT:
case Opcodes.IF_ICMPEQ:
case Opcodes.IF_ICMPGE:
{
if (iter > 1) {
Instruction leftArg = instructions.get(iter - 2);
Instruction rightArg = instructions.get(iter - 1);
String leftLiteral = null;
String rightLiteral = null;
if (leftArg instanceof AssignableExpression) {
StringBuilder sb = new StringBuilder();
if (((AssignableExpression) leftArg).assignTo(null, sb)) {
leftLiteral = sb.toString().trim();
}
} else if (leftArg instanceof CustomInvoke) {
CustomInvoke inv = (CustomInvoke) leftArg;
StringBuilder sb = new StringBuilder();
if (!"JAVA_OBJECT".equals(inv.getReturnValue()) && inv.appendExpression(sb)) {
leftLiteral = sb.toString().trim();
}
}
if (rightArg instanceof AssignableExpression) {
StringBuilder sb = new StringBuilder();
if (((AssignableExpression) rightArg).assignTo(null, sb)) {
rightLiteral = sb.toString().trim();
}
} else if (rightArg instanceof CustomInvoke) {
CustomInvoke inv = (CustomInvoke) rightArg;
StringBuilder sb = new StringBuilder();
if (!"JAVA_OBJECT".equals(inv.getReturnValue()) && inv.appendExpression(sb)) {
rightLiteral = sb.toString().trim();
}
}
if (rightLiteral != null && leftLiteral != null) {
Jump jmp = (Jump) current;
instructions.remove(iter - 2);
instructions.remove(iter - 2);
instructions.remove(iter - 2);
// instructions.remove(iter-2);
iter -= 2;
// instructionCount -= 2;
StringBuilder sb = new StringBuilder();
String operator = null;
String opName = null;
switch(currentOpcode) {
case Opcodes.IF_ICMPLE:
operator = "<=";
opName = "IF_ICMPLE";
break;
case Opcodes.IF_ICMPLT:
operator = "<";
opName = "IF_IMPLT";
break;
case Opcodes.IF_ICMPNE:
operator = "!=";
opName = "IF_ICMPNE";
break;
case Opcodes.IF_ICMPGT:
operator = ">";
opName = "IF_ICMPGT";
break;
case Opcodes.IF_ICMPGE:
operator = ">=";
opName = "IF_ICMPGE";
break;
case Opcodes.IF_ICMPEQ:
operator = "==";
opName = "IF_ICMPEQ";
break;
case Opcodes.IF_ACMPEQ:
operator = "==";
opName = "IF_ACMPEQ";
break;
case Opcodes.IF_ACMPNE:
operator = "!=";
opName = "IF_ACMPNE";
break;
default:
throw new RuntimeException("Invalid operator during optimization of integer comparison");
}
sb.append("if (").append(leftLiteral).append(operator).append(rightLiteral).append(") /* ").append(opName).append(" CustomJump */ ");
CustomJump newJump = CustomJump.create(jmp, sb.toString());
// jmp.setCustomCompareCode(sb.toString());
newJump.setOptimized(true);
instructions.add(iter, newJump);
instructionCount = instructions.size();
}
}
break;
}
case Opcodes.IFNONNULL:
case Opcodes.IFNULL:
case Opcodes.IFLE:
case Opcodes.IFLT:
case Opcodes.IFNE:
case Opcodes.IFGT:
case Opcodes.IFEQ:
case Opcodes.IFGE:
{
String rightArg = "0";
if (currentOpcode == Opcodes.IFNONNULL || currentOpcode == Opcodes.IFNULL) {
rightArg = "JAVA_NULL";
}
if (iter > 0) {
Instruction leftArg = instructions.get(iter - 1);
String leftLiteral = null;
if (leftArg instanceof AssignableExpression) {
StringBuilder sb = new StringBuilder();
if (((AssignableExpression) leftArg).assignTo(null, sb)) {
leftLiteral = sb.toString().trim();
}
} else if (leftArg instanceof CustomInvoke) {
CustomInvoke inv = (CustomInvoke) leftArg;
StringBuilder sb = new StringBuilder();
if (inv.appendExpression(sb)) {
leftLiteral = sb.toString().trim();
}
}
if (leftLiteral != null) {
Jump jmp = (Jump) current;
instructions.remove(iter - 1);
instructions.remove(iter - 1);
// instructions.remove(iter-2);
iter -= 1;
// instructionCount -= 2;
StringBuilder sb = new StringBuilder();
String operator = null;
String opName = null;
switch(currentOpcode) {
case Opcodes.IFLE:
operator = "<=";
opName = "IFLE";
break;
case Opcodes.IFLT:
operator = "<";
opName = "IFLT";
break;
case Opcodes.IFNE:
operator = "!=";
opName = "IFNE";
break;
case Opcodes.IFGT:
operator = ">";
opName = "IFGT";
break;
case Opcodes.IFGE:
operator = ">=";
opName = "IFGE";
break;
case Opcodes.IFEQ:
operator = "==";
opName = "IFEQ";
break;
case Opcodes.IFNULL:
operator = "==";
opName = "IFNULL";
break;
case Opcodes.IFNONNULL:
operator = "!=";
opName = "IFNONNULL";
break;
default:
throw new RuntimeException("Invalid operator during optimization of integer comparison");
}
sb.append("if (").append(leftLiteral).append(operator).append(rightArg).append(") /* ").append(opName).append(" CustomJump */ ");
CustomJump newJump = CustomJump.create(jmp, sb.toString());
// jmp.setCustomCompareCode(sb.toString());
newJump.setOptimized(true);
instructions.add(iter, newJump);
instructionCount = instructions.size();
}
}
break;
}
case Opcodes.INVOKEVIRTUAL:
case Opcodes.INVOKESTATIC:
case Opcodes.INVOKESPECIAL:
case Opcodes.INVOKEINTERFACE:
{
if (current instanceof Invoke) {
Invoke inv = (Invoke) current;
List<ByteCodeMethodArg> invocationArgs = inv.getArgs();
int numArgs = invocationArgs.size();
// }
if (iter >= numArgs) {
String[] argLiterals = new String[numArgs];
StringBuilder devNull = new StringBuilder();
for (int i = 0; i < numArgs; i++) {
devNull.setLength(0);
Instruction instr = instructions.get(iter - numArgs + i);
if (instr instanceof AssignableExpression && ((AssignableExpression) instr).assignTo(null, devNull)) {
argLiterals[i] = devNull.toString().trim();
} else if (instr instanceof CustomInvoke) {
CustomInvoke cinv = (CustomInvoke) instr;
devNull.setLength(0);
if (!"JAVA_OBJECT".equals(cinv.getReturnValue()) && cinv.appendExpression(devNull)) {
// We can't add invocations that return objects directly
// because they need to be added to the stack for GC
argLiterals[i] = devNull.toString().trim();
}
} else if (instr instanceof ArithmeticExpression) {
argLiterals[i] = ((ArithmeticExpression) instr).getExpressionAsString().trim();
} else if (instr instanceof VarOp) {
VarOp var = (VarOp) instr;
switch(instr.getOpcode()) {
case Opcodes.ALOAD:
{
if (!isStatic() && var.getIndex() == 0) {
argLiterals[i] = "__cn1ThisObject";
} else {
argLiterals[i] = "locals[" + var.getIndex() + "].data.o";
}
break;
}
case Opcodes.ILOAD:
{
argLiterals[i] = "ilocals_" + var.getIndex() + "_";
break;
}
case Opcodes.ACONST_NULL:
{
argLiterals[i] = "JAVA_NULL";
break;
}
case Opcodes.DLOAD:
{
argLiterals[i] = "dlocals_" + var.getIndex() + "_";
break;
}
case Opcodes.FLOAD:
{
argLiterals[i] = "flocals_" + var.getIndex() + "_";
break;
}
case Opcodes.LLOAD:
{
argLiterals[i] = "llocals_" + var.getIndex() + "_";
break;
}
case Opcodes.ICONST_0:
{
argLiterals[i] = "0";
break;
}
case Opcodes.ICONST_1:
{
argLiterals[i] = "1";
break;
}
case Opcodes.ICONST_2:
{
argLiterals[i] = "2";
break;
}
case Opcodes.ICONST_3:
{
argLiterals[i] = "3";
break;
}
case Opcodes.ICONST_4:
{
argLiterals[i] = "4";
break;
}
case Opcodes.ICONST_5:
{
argLiterals[i] = "5";
break;
}
case Opcodes.ICONST_M1:
{
argLiterals[i] = "-1";
break;
}
case Opcodes.LCONST_0:
{
argLiterals[i] = "(JAVA_LONG)0";
break;
}
case Opcodes.LCONST_1:
{
argLiterals[i] = "(JAVA_LONG)1";
break;
}
case Opcodes.BIPUSH:
case Opcodes.SIPUSH:
{
argLiterals[i] = String.valueOf(var.getIndex());
break;
}
}
} else {
switch(instr.getOpcode()) {
case Opcodes.ACONST_NULL:
{
argLiterals[i] = "JAVA_NULL";
break;
}
case Opcodes.ICONST_0:
{
argLiterals[i] = "0";
break;
}
case Opcodes.ICONST_1:
{
argLiterals[i] = "1";
break;
}
case Opcodes.ICONST_2:
{
argLiterals[i] = "2";
break;
}
case Opcodes.ICONST_3:
{
argLiterals[i] = "3";
break;
}
case Opcodes.ICONST_4:
{
argLiterals[i] = "4";
break;
}
case Opcodes.ICONST_5:
{
argLiterals[i] = "5";
break;
}
case Opcodes.ICONST_M1:
{
argLiterals[i] = "-1";
break;
}
case Opcodes.LCONST_0:
{
argLiterals[i] = "(JAVA_LONG)0";
break;
}
case Opcodes.LCONST_1:
{
argLiterals[i] = "(JAVA_LONG)1";
break;
}
case Opcodes.BIPUSH:
{
if (instr instanceof BasicInstruction) {
argLiterals[i] = String.valueOf(((BasicInstruction) instr).getValue());
}
break;
}
case Opcodes.LDC:
{
if (instr instanceof Ldc) {
Ldc ldc = (Ldc) instr;
argLiterals[i] = ldc.getValueAsString();
}
break;
}
}
}
}
// Check to make sure that we have all the args as literals.
boolean missingLiteral = false;
for (String lit : argLiterals) {
if (lit == null) {
missingLiteral = true;
break;
}
}
// add them to our invoke instruction.
if (!missingLiteral) {
CustomInvoke newInvoke = CustomInvoke.create(inv);
instructions.remove(iter);
instructions.add(iter, newInvoke);
int newIter = iter;
for (int i = 0; i < numArgs; i++) {
instructions.remove(iter - numArgs);
newIter--;
newInvoke.setLiteralArg(i, argLiterals[i]);
}
if (inv.getOpcode() != Opcodes.INVOKESTATIC) {
Instruction ldTarget = instructions.get(iter - numArgs - 1);
if (ldTarget instanceof AssignableExpression) {
StringBuilder targetExprStr = new StringBuilder();
if (((AssignableExpression) ldTarget).assignTo(null, targetExprStr)) {
newInvoke.setTargetObjectLiteral(targetExprStr.toString().trim());
instructions.remove(iter - numArgs - 1);
newIter--;
}
} else if (ldTarget instanceof CustomInvoke) {
// WE Can't pass a custom invoke as the target directly
// because it the return value needs to be added to the
// stack for the GC
} else {
switch(ldTarget.getOpcode()) {
case Opcodes.ALOAD:
{
VarOp v = (VarOp) ldTarget;
if (isStatic() && v.getIndex() == 0) {
newInvoke.setTargetObjectLiteral("__cn1ThisObject");
} else {
newInvoke.setTargetObjectLiteral("locals[" + v.getIndex() + "].data.o");
}
instructions.remove(iter - numArgs - 1);
newIter--;
break;
}
}
}
}
newInvoke.setOptimized(true);
// iter = 0;
instructionCount = instructions.size();
iter = newIter;
}
}
}
break;
}
}
astoreCalls = astoreCalls || currentOpcode == Opcodes.ASTORE || currentOpcode == Opcodes.ISTORE || currentOpcode == Opcodes.LSTORE || currentOpcode == Opcodes.DSTORE || currentOpcode == Opcodes.FSTORE;
hasInstructions = hasInstructions | current.getOpcode() != -1;
}
return hasInstructions;
}
Aggregations