Search in sources :

Example 21 with Result

use of com.codename1.processing.Result in project CodenameOne by codenameone.

the class IOSImplementation method showNativePicker.

@Override
public Object showNativePicker(final int type, final Component source, final Object currentValue, final Object data) {
    datePickerResult = -2;
    int x = 0, y = 0, w = 20, h = 20, preferredHeight = 0, preferredWidth = 0;
    if (source != null) {
        x = source.getAbsoluteX();
        y = source.getAbsoluteY();
        w = source.getWidth();
        h = source.getHeight();
    }
    if (source instanceof Picker) {
        Picker p = (Picker) source;
        preferredHeight = p.getPreferredPopupHeight();
        preferredWidth = p.getPreferredPopupWidth();
    }
    if (type == Display.PICKER_TYPE_STRINGS) {
        String[] strs = (String[]) data;
        int offset = -1;
        if (currentValue != null) {
            int slen = strs.length;
            for (int iter = 0; iter < slen; iter++) {
                if (strs[iter].equals(currentValue)) {
                    offset = iter;
                    break;
                }
            }
        }
        nativeInstance.openStringPicker(strs, offset, x, y, w, h, preferredWidth, preferredHeight);
    } else if (type == Display.PICKER_TYPE_DURATION) {
        long time;
        if (currentValue instanceof Long) {
            time = (Long) currentValue;
        } else {
            time = 0l;
        }
        int minuteStep = 5;
        if (data instanceof String) {
            String strData = (String) data;
            String[] parts = Util.split(strData, "\n");
            for (String part : parts) {
                if (part.indexOf("minuteStep=") != -1) {
                    minuteStep = Integer.parseInt(part.substring(part.indexOf("=") + 1));
                }
            }
        }
        nativeInstance.openDatePicker(type, time, x, y, w, h, preferredWidth, preferredHeight, minuteStep);
    } else {
        long time;
        if (currentValue instanceof Integer) {
            java.util.Calendar c = java.util.Calendar.getInstance();
            c.set(java.util.Calendar.HOUR_OF_DAY, ((Integer) currentValue).intValue() / 60);
            c.set(java.util.Calendar.MINUTE, ((Integer) currentValue).intValue() % 60);
            time = c.getTime().getTime();
        } else if (currentValue != null) {
            time = ((java.util.Date) currentValue).getTime();
        } else {
            time = new java.util.Date().getTime();
        }
        nativeInstance.openDatePicker(type, time, x, y, w, h, preferredWidth, preferredHeight, 5);
    }
    // wait for the native code to complete
    Display.getInstance().invokeAndBlock(new Runnable() {

        public void run() {
            while (datePickerResult == -2) {
                synchronized (PICKER_LOCK) {
                    try {
                        PICKER_LOCK.wait(100);
                    } catch (InterruptedException err) {
                    }
                }
            }
        }
    }, true);
    if (datePickerResult == -1) {
        // }
        return null;
    }
    if (type == Display.PICKER_TYPE_STRINGS) {
        if (datePickerResult < 0) {
            return null;
        }
        return ((String[]) data)[(int) datePickerResult];
    }
    Object result;
    if (type == Display.PICKER_TYPE_DURATION || type == Display.PICKER_TYPE_DURATION_HOURS || type == Display.PICKER_TYPE_DURATION_MINUTES) {
        if (datePickerResult < 0) {
            return null;
        }
        return new Long(datePickerResult);
    }
    if (type == Display.PICKER_TYPE_TIME) {
        java.util.Calendar c = java.util.Calendar.getInstance();
        c.setTime(new Date(datePickerResult));
        result = new Integer(c.get(java.util.Calendar.HOUR_OF_DAY) * 60 + c.get(java.util.Calendar.MINUTE));
    } else {
        result = new Date(datePickerResult);
    }
    return result;
}
Also used : Date(java.util.Date) Picker(com.codename1.ui.spinner.Picker)

Example 22 with Result

use of com.codename1.processing.Result in project CodenameOne by codenameone.

the class JavaSEPort method getInAppPurchase.

public Purchase getInAppPurchase() {
    return new Purchase() {

        private Vector purchases;

        @Override
        public Product[] getProducts(String[] skus) {
            return null;
        }

        @Override
        public boolean isItemListingSupported() {
            return false;
        }

        @Override
        public boolean isManagedPaymentSupported() {
            return managedPurchaseSupported;
        }

        @Override
        public boolean isManualPaymentSupported() {
            return manualPurchaseSupported;
        }

        @Override
        public boolean isRefundable(String sku) {
            if (!refundSupported) {
                return false;
            }
            int val = JOptionPane.showConfirmDialog(window, "Is " + sku + " refundable?", "Purchase", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
            return val == JOptionPane.YES_OPTION;
        }

        private Vector getPurchases() {
            if (purchases == null) {
                purchases = (Vector) Storage.getInstance().readObject("CN1InAppPurchases");
                if (purchases == null) {
                    purchases = new Vector();
                }
            }
            return purchases;
        }

        private void savePurchases() {
            if (purchases != null) {
                Storage.getInstance().writeObject("CN1InAppPurchases", purchases);
            }
        }

        @Override
        public boolean isSubscriptionSupported() {
            return subscriptionSupported;
        }

        @Override
        public boolean isUnsubscribeSupported() {
            return subscriptionSupported;
        }

        @Override
        public String pay(final double amount, final String currency) {
            try {
                if (Display.getInstance().isEdt()) {
                    final String[] response = new String[1];
                    Display.getInstance().invokeAndBlock(new Runnable() {

                        public void run() {
                            response[0] = pay(amount, currency);
                        }
                    });
                    return response[0];
                }
                if (!manualPurchaseSupported) {
                    throw new RuntimeException("Manual payment isn't supported check the isManualPaymentSupported() method!");
                }
                final String[] result = new String[1];
                final boolean[] completed = new boolean[] { false };
                SwingUtilities.invokeLater(new Runnable() {

                    public void run() {
                        int res = JOptionPane.showConfirmDialog(window, "A payment of " + amount + " was made\nDo you wish to accept it?", "Payment", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
                        if (res == JOptionPane.YES_OPTION) {
                            result[0] = UUID.randomUUID().toString();
                        }
                        completed[0] = true;
                    }
                });
                Display.getInstance().invokeAndBlock(new Runnable() {

                    public void run() {
                        while (!completed[0]) {
                            try {
                                Thread.sleep(20);
                            } catch (InterruptedException err) {
                            }
                        }
                    }
                });
                if (getPurchaseCallback() != null) {
                    Display.getInstance().callSerially(new Runnable() {

                        public void run() {
                            if (result[0] != null) {
                                getPurchaseCallback().paymentSucceeded(result[0], amount, currency);
                            } else {
                                getPurchaseCallback().paymentFailed(UUID.randomUUID().toString(), null);
                            }
                        }
                    });
                }
                return result[0];
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            return null;
        }

        @Override
        public void purchase(final String sku) {
            if (managedPurchaseSupported) {
                SwingUtilities.invokeLater(new Runnable() {

                    public void run() {
                        final int res = JOptionPane.showConfirmDialog(window, "An in-app purchase of " + sku + " was made\nDo you wish to accept it?", "Payment", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
                        Display.getInstance().callSerially(new Runnable() {

                            public void run() {
                                if (res == JOptionPane.YES_OPTION) {
                                    com.codename1.payment.Purchase.postReceipt(Receipt.STORE_CODE_SIMULATOR, sku, "cn1-iap-sim-" + UUID.randomUUID().toString(), System.currentTimeMillis(), "");
                                    getPurchaseCallback().itemPurchased(sku);
                                    getPurchases().addElement(sku);
                                    savePurchases();
                                } else {
                                    getPurchaseCallback().itemPurchaseError(sku, "Purchase failed");
                                }
                            }
                        });
                    }
                });
            } else {
                throw new RuntimeException("In app purchase isn't supported on this platform!");
            }
        }

        @Override
        public void refund(final String sku) {
            if (refundSupported) {
                Display.getInstance().callSerially(new Runnable() {

                    public void run() {
                        getPurchaseCallback().itemRefunded(sku);
                        getPurchases().removeElement(sku);
                        savePurchases();
                    }
                });
            }
        }

        @Override
        public void subscribe(final String sku) {
            if (subscriptionSupported) {
                SwingUtilities.invokeLater(new Runnable() {

                    public void run() {
                        final int res = JOptionPane.showConfirmDialog(window, "An in-app subscription to " + sku + " was made\nDo you wish to accept it?", "Payment", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
                        Display.getInstance().callSerially(new Runnable() {

                            public void run() {
                                if (res == JOptionPane.YES_OPTION) {
                                    getPurchaseCallback().subscriptionStarted(sku);
                                    getPurchases().addElement(sku);
                                    savePurchases();
                                } else {
                                    getPurchaseCallback().itemPurchaseError(sku, "Subscription failed");
                                }
                            }
                        });
                    }
                });
            }
        }

        @Override
        public void unsubscribe(final String sku) {
            if (subscriptionSupported) {
                SwingUtilities.invokeLater(new Runnable() {

                    public void run() {
                        final int res = JOptionPane.showConfirmDialog(window, "In-app unsubscription request for " + sku + " was made\nDo you wish to accept it?", "Payment", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
                        Display.getInstance().callSerially(new Runnable() {

                            public void run() {
                                if (res == JOptionPane.YES_OPTION) {
                                    getPurchaseCallback().subscriptionCanceled(sku);
                                    getPurchases().removeElement(sku);
                                    savePurchases();
                                } else {
                                    getPurchaseCallback().itemPurchaseError(sku, "Error in unsubscribe");
                                }
                            }
                        });
                    }
                });
            }
        }

        @Override
        public boolean wasPurchased(String sku) {
            return getPurchases().contains(sku);
        }
    };
}
Also used : Purchase(com.codename1.payment.Purchase) Product(com.codename1.payment.Product) Vector(java.util.Vector) Point(java.awt.Point) SQLException(java.sql.SQLException) ParseException(java.text.ParseException) EOFException(java.io.EOFException) FontFormatException(java.awt.FontFormatException)

Example 23 with Result

use of com.codename1.processing.Result in project CodenameOne by codenameone.

the class ImageDownloadService method readResponse.

/**
 * {@inheritDoc}
 */
protected void readResponse(InputStream input) throws IOException {
    int imageScaleWidth = -1, imageScaleHeight = -1;
    if (fastScale) {
        if (toScale != null) {
            imageScaleWidth = toScale.getWidth();
            imageScaleHeight = toScale.getHeight();
        } else {
            if (placeholder != null) {
                imageScaleWidth = placeholder.getWidth();
                imageScaleHeight = placeholder.getHeight();
            }
        }
    }
    if (cacheImages) {
        if (destinationFile != null) {
            result = FileEncodedImage.create(destinationFile, input, imageScaleWidth, imageScaleHeight);
        } else {
            EncodedImage e = EncodedImage.create(input);
            if (maintainAspectRatio) {
                float actualW = e.getWidth();
                float actualH = e.getHeight();
                float r2 = Math.min(((float) imageScaleWidth) / actualW, ((float) imageScaleHeight) / actualH);
                imageScaleWidth = (int) (actualW * r2);
                imageScaleHeight = (int) (actualH * r2);
            }
            // workaround for http://stackoverflow.com/questions/35347353/label-image-scale-issue-in-codename-one-library-3-3/35354605
            if (imageScaleWidth > -1 || imageScaleHeight > -1) {
                e = e.scaledEncoded(imageScaleWidth, imageScaleHeight);
            }
            result = StorageImage.create(cacheId, e.getImageData(), imageScaleWidth, imageScaleHeight, keep);
            // if the storage has failed create the image from the stream
            if (result == null) {
                result = e;
            }
        }
    } else {
        result = EncodedImage.create(input);
    }
}
Also used : EncodedImage(com.codename1.ui.EncodedImage) FileEncodedImage(com.codename1.components.FileEncodedImage)

Example 24 with Result

use of com.codename1.processing.Result in project CodenameOne by codenameone.

the class MenuBar method createCommandComponent.

/**
 * Creates the component containing the commands within the given vector
 * used for showing the menu dialog, this method calls the createCommandList
 * method by default however it allows more elaborate menu creation.
 *
 * @param commands list of command objects
 * @return Component that will result in the parent menu dialog recieving a command event
 */
protected Component createCommandComponent(Vector commands) {
    UIManager manager = parent.getUIManager();
    // Create a touch based menu interface
    if (manager.getLookAndFeel().isTouchMenus()) {
        Container menu = new Container();
        menu.setScrollableY(true);
        for (int iter = 0; iter < commands.size(); iter++) {
            Command c = (Command) commands.elementAt(iter);
            menu.addComponent(createTouchCommandButton(c));
        }
        if (!manager.isThemeConstant("touchCommandFlowBool", false)) {
            int cols = calculateTouchCommandGridColumns(menu);
            if (cols > getCommandCount()) {
                cols = getCommandCount();
            }
            int rows = Math.max(1, getCommandCount() / cols + (getCommandCount() % cols != 0 ? 1 : 0));
            if (rows > 1) {
                // try to prevent too many columns concentraiting within a single row
                int remainingColumns = (rows * cols) % getCommandCount();
                int newCols = cols;
                int newRows = rows;
                while (remainingColumns != 0 && remainingColumns > 1 && newCols >= 2) {
                    newCols--;
                    newRows = Math.max(1, getCommandCount() / newCols + (getCommandCount() % newCols != 0 ? 1 : 0));
                    if (newRows != rows) {
                        break;
                    }
                    remainingColumns = (newRows * newCols) % getCommandCount();
                }
                if (newRows == rows) {
                    cols = newCols;
                    rows = newRows;
                }
            }
            GridLayout g = new GridLayout(rows, cols);
            g.setFillLastRow(manager.isThemeConstant("touchCommandFillBool", true));
            menu.setLayout(g);
        } else {
            ((FlowLayout) menu.getLayout()).setFillRows(true);
        }
        menu.setPreferredW(Display.getInstance().getDisplayWidth());
        return menu;
    }
    return createCommandList(commands);
}
Also used : GridLayout(com.codename1.ui.layouts.GridLayout) FlowLayout(com.codename1.ui.layouts.FlowLayout) UIManager(com.codename1.ui.plaf.UIManager)

Example 25 with Result

use of com.codename1.processing.Result in project CodenameOne by codenameone.

the class CodenameOneActivity method onCreate.

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    AndroidImplementation.setActivity(this);
    AndroidNativeUtil.onCreate(savedInstanceState);
    if (android.os.Build.VERSION.SDK_INT >= 11) {
        getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
        getActionBar().hide();
    }
    try {
        if (isBillingEnabled()) {
            String k = getBase64EncodedPublicKey();
            if (k.length() == 0) {
                Log.e("Codename One", "android.licenseKey base64 is not configured");
            }
            mHelper = new IabHelper(this, getBase64EncodedPublicKey());
            mHelper.enableDebugLogging(true);
            mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {

                public void onIabSetupFinished(IabResult result) {
                    if (!result.isSuccess()) {
                        // Oh noes, there was a problem.
                        Log.e("Codename One", "Problem setting up in-app billing: " + result);
                        return;
                    }
                    // Have we been disposed of in the meantime? If so, quit.
                    if (mHelper == null) {
                        return;
                    }
                    // IAB is fully set up. Now, let's get an inventory of stuff we own.
                    mHelper.queryInventoryAsync(mGotInventoryListener);
                }
            });
        }
    } catch (Throwable t) {
        // might happen if billing permissions are missing
        System.out.print("This exception is totally valid and here only for debugging purposes");
        t.printStackTrace();
    }
}
Also used : IabResult(com.codename1.payments.v3.IabResult) IabHelper(com.codename1.payments.v3.IabHelper)

Aggregations

IOException (java.io.IOException)6 ArrayList (java.util.ArrayList)5 EncodedImage (com.codename1.ui.EncodedImage)4 BorderLayout (com.codename1.ui.layouts.BorderLayout)4 Point (java.awt.Point)4 ByteArrayInputStream (java.io.ByteArrayInputStream)4 Hashtable (java.util.Hashtable)4 Component (com.codename1.ui.Component)3 ActionEvent (com.codename1.ui.events.ActionEvent)3 ActionListener (com.codename1.ui.events.ActionListener)3 Intent (android.content.Intent)2 FileEncodedImage (com.codename1.components.FileEncodedImage)2 IntentResultListener (com.codename1.impl.android.IntentResultListener)2 Properties (com.codename1.io.Properties)2 Command (com.codename1.ui.Command)2 Container (com.codename1.ui.Container)2 Image (com.codename1.ui.Image)2 TextArea (com.codename1.ui.TextArea)2 Dimension (com.codename1.ui.geom.Dimension)2 GridLayout (com.codename1.ui.layouts.GridLayout)2