Search in sources :

Example 6 with Result

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

the class GoogleImpl method nativeLoginImpl.

private void nativeLoginImpl(final GoogleApiClient client) {
    Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(client);
    AndroidNativeUtil.startActivityForResult(signInIntent, RC_SIGN_IN, new IntentResultListener() {

        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
            if (requestCode == RC_SIGN_IN) {
                final GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
                if (result.isSuccess()) {
                    // Signed in successfully, show authenticated UI.
                    GoogleSignInAccount acct = result.getSignInAccount();
                    String displayName = acct.getDisplayName();
                    String acctId = acct.getId();
                    String email = acct.getEmail();
                    String requestIdToken = acct.getIdToken();
                    Set<Scope> grantedScopes = acct.getGrantedScopes();
                    String code = acct.getServerAuthCode();
                    String scopeStr = scope;
                    System.out.println("Token is " + acct.getIdToken());
                    if (acct.getIdToken() == null && clientId != null && clientSecret != null) {
                        Log.p("Received null ID token even though clientId and clientSecret are set.");
                    }
                    // otherwise we'll set the token to null.
                    if (clientId != null && clientSecret != null && requestIdToken != null && code != null) {
                        ConnectionRequest req = new ConnectionRequest() {

                            @Override
                            protected void readResponse(InputStream input) throws IOException {
                                Map<String, Object> json = new JSONParser().parseJSON(new InputStreamReader(input, "UTF-8"));
                                if (json.containsKey("access_token")) {
                                    setAccessToken(new AccessToken((String) json.get("access_token"), null));
                                    Display.getInstance().callSerially(new Runnable() {

                                        @Override
                                        public void run() {
                                            callback.loginSuccessful();
                                        }
                                    });
                                } else {
                                    setAccessToken(new AccessToken(null, null));
                                    Log.p("Failed to retrieve the access token from the google auth server.  Login succeeded, but access token is null, so you won't be able to use it to retrieve additional information.");
                                    Log.p("Response was " + json);
                                    Display.getInstance().callSerially(new Runnable() {

                                        @Override
                                        public void run() {
                                            callback.loginSuccessful();
                                        }
                                    });
                                }
                            }
                        };
                        req.setUrl("https://www.googleapis.com/oauth2/v4/token");
                        req.addArgument("grant_type", "authorization_code");
                        // req.addArgument("client_id", "555462747934-iujpd5saj4pjpibo7c6r9tbjfef22rh1.apps.googleusercontent.com");
                        req.addArgument("client_id", clientId);
                        // req.addArgument("client_secret", "650YqplrnAI0KXb9LMUnVNnx");
                        req.addArgument("client_secret", clientSecret);
                        req.addArgument("redirect_uri", "");
                        req.addArgument("code", code);
                        req.addArgument("id_token", requestIdToken);
                        req.setPost(true);
                        req.setReadResponseForErrors(true);
                        NetworkManager.getInstance().addToQueue(req);
                    } else {
                        setAccessToken(new AccessToken(null, null));
                        Log.p("The access token was set to null because one of clientId, clientSecret, requestIdToken, or auth were null");
                        Log.p("The login succeeded, but you won't be able to make any requests to Google's REST apis using the login token.");
                        Log.p("In order to obtain a token that can be used with Google's REST APIs, you need to set the clientId, and clientSecret of" + "the GoogleConnect instance to valid OAuth2.0 Client IDs for Web Clients.");
                        Log.p("See https://console.developers.google.com/apis/credentials");
                        Log.p("You can get the OAuth2.0 client ID for this project in your google-services.json file in the oauth_client section");
                        Display.getInstance().callSerially(new Runnable() {

                            @Override
                            public void run() {
                                callback.loginSuccessful();
                            }
                        });
                    }
                } else {
                    if (callback != null) {
                        if (callback != null) {
                            Display.getInstance().callSerially(new Runnable() {

                                @Override
                                public void run() {
                                    callback.loginFailed(GooglePlayServicesUtil.getErrorString(result.getStatus().getStatusCode()));
                                }
                            });
                        }
                    }
                }
            }
        }
    });
}
Also used : Set(java.util.Set) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) Intent(android.content.Intent) IOException(java.io.IOException) GoogleSignInResult(com.google.android.gms.auth.api.signin.GoogleSignInResult) ConnectionRequest(com.codename1.io.ConnectionRequest) GoogleSignInAccount(com.google.android.gms.auth.api.signin.GoogleSignInAccount) IntentResultListener(com.codename1.impl.android.IntentResultListener) AccessToken(com.codename1.io.AccessToken) JSONParser(com.codename1.io.JSONParser) Map(java.util.Map)

Example 7 with Result

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

the class Capture method capturePhoto.

/**
 * <p>Invokes the camera and takes a photo synchronously while blocking the EDT, the sample below
 * demonstrates a simple usage and applying a mask to the result</p>
 * <script src="https://gist.github.com/codenameone/b18c37dfcc7de752e0e6.js"></script>
 * <img src="https://www.codenameone.com/img/developer-guide/graphics-image-masking.png" alt="Picture after the capture was complete and the resulted image was rounded. The background was set to red so the rounding effect will be more noticeable" />
 *
 * @param width the target width for the image if possible, some platforms don't support scaling. To maintain aspect ratio set to -1
 * @param height the target height for the image if possible, some platforms don't support scaling. To maintain aspect ratio set to -1
 * @return the photo file location or null if the user canceled
 */
public static String capturePhoto(int width, int height) {
    CallBack c = new CallBack();
    if ("ios".equals(Display.getInstance().getPlatformName()) && (width != -1 || height != -1)) {
        // workaround for threading issues in iOS https://github.com/codenameone/CodenameOne/issues/2246
        capturePhoto(c);
        Display.getInstance().invokeAndBlock(c);
        if (c.url == null) {
            return null;
        }
        ImageIO scale = Display.getInstance().getImageIO();
        if (scale != null) {
            try {
                String path = c.url.substring(0, c.url.indexOf(".")) + "s" + c.url.substring(c.url.indexOf("."));
                OutputStream os = FileSystemStorage.getInstance().openOutputStream(path);
                scale.save(c.url, os, ImageIO.FORMAT_JPEG, width, height, 1);
                Util.cleanup(os);
                FileSystemStorage.getInstance().delete(c.url);
                return path;
            } catch (IOException ex) {
                Log.e(ex);
            }
        }
    } else {
        c.targetWidth = width;
        c.targetHeight = height;
        capturePhoto(c);
        Display.getInstance().invokeAndBlock(c);
    }
    return c.url;
}
Also used : OutputStream(java.io.OutputStream) IOException(java.io.IOException) ImageIO(com.codename1.ui.util.ImageIO)

Example 8 with Result

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

the class TimeChart method getXLabels.

@Override
protected List<Double> getXLabels(double min, double max, int count) {
    final List<Double> result = new ArrayList<Double>();
    if (!mRenderer.isXRoundedLabels()) {
        if (mDataset.getSeriesCount() > 0) {
            XYSeries series = mDataset.getSeriesAt(0);
            int length = series.getItemCount();
            int intervalLength = 0;
            int startIndex = -1;
            for (int i = 0; i < length; i++) {
                double value = series.getX(i);
                if (min <= value && value <= max) {
                    intervalLength++;
                    if (startIndex < 0) {
                        startIndex = i;
                    }
                }
            }
            if (intervalLength < count) {
                for (int i = startIndex; i < startIndex + intervalLength; i++) {
                    result.add(series.getX(i));
                }
            } else {
                float step = (float) intervalLength / count;
                int intervalCount = 0;
                for (int i = 0; i < length && intervalCount < count; i++) {
                    double value = series.getX(Math.round(i * step));
                    if (min <= value && value <= max) {
                        result.add(value);
                        intervalCount++;
                    }
                }
            }
            return result;
        } else {
            return super.getXLabels(min, max, count);
        }
    }
    if (mStartPoint == null) {
        TimeZone tz = TimeZone.getDefault();
        Calendar cal = Calendar.getInstance(tz);
        cal.setTime(new Date(Math.round(min)));
        int offset = getDSTOffset(cal);
        mStartPoint = min - (min % DAY) + DAY + offset * 60 * 60 * 1000;
    }
    if (count > 25) {
        count = 25;
    }
    final double cycleMath = (max - min) / count;
    if (cycleMath <= 0) {
        return result;
    }
    double cycle = DAY;
    if (cycleMath <= DAY) {
        while (cycleMath < cycle / 2) {
            cycle = cycle / 2;
        }
    } else {
        while (cycleMath > cycle) {
            cycle = cycle * 2;
        }
    }
    double val = mStartPoint - Math.floor((mStartPoint - min) / cycle) * cycle;
    int i = 0;
    while (val < max && i++ <= count) {
        result.add(val);
        val += cycle;
    }
    return result;
}
Also used : XYSeries(com.codename1.charts.models.XYSeries) TimeZone(java.util.TimeZone) Calendar(java.util.Calendar) ArrayList(java.util.ArrayList) Paint(com.codename1.charts.compat.Paint) Date(java.util.Date)

Example 9 with Result

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

the class JavaSEPort method getProjectBuildHints.

@Override
public Map<String, String> getProjectBuildHints() {
    File cnopFile = new File("codenameone_settings.properties");
    if (cnopFile.exists()) {
        java.util.Properties cnop = new java.util.Properties();
        try (InputStream is = new FileInputStream(cnopFile)) {
            cnop.load(is);
        } catch (IOException err) {
            return null;
        }
        HashMap<String, String> result = new HashMap<>();
        for (Object kk : cnop.keySet()) {
            String key = (String) kk;
            if (key.startsWith("codename1.arg.")) {
                String val = cnop.getProperty(key);
                key = key.substring(14);
                result.put(key, val);
            }
        }
        return Collections.unmodifiableMap(result);
    }
    return null;
}
Also used : java.util(java.util) HashMap(java.util.HashMap) BufferedInputStream(com.codename1.io.BufferedInputStream) MemoryCacheImageInputStream(javax.imageio.stream.MemoryCacheImageInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) ZipInputStream(java.util.zip.ZipInputStream) Properties(com.codename1.io.Properties)

Example 10 with Result

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

the class Dialog method showPopupDialog.

/**
 * A popup dialog is shown with the context of a component and  its selection, it is disposed seamlessly if the back button is pressed
 * or if the user touches outside its bounds. It can optionally provide an arrow in the theme to point at the context component. The popup
 * dialog has the PopupDialog style by default.
 *
 * @param rect the screen rectangle to which the popup should point
 * @return the command that might have been triggered by the user within the dialog if commands are placed in the dialog
 */
public Command showPopupDialog(Rectangle rect) {
    if (getDialogUIID().equals("Dialog")) {
        setDialogUIID("PopupDialog");
        if (getTitleComponent().getUIID().equals("DialogTitle")) {
            getTitleComponent().setUIID("PopupDialogTitle");
        }
        getContentPane().setUIID("PopupContentPane");
    }
    disposeOnRotation = true;
    disposeWhenPointerOutOfBounds = true;
    Command backCommand = null;
    if (getBackCommand() == null) {
        backCommand = new Command("Back");
        setBackCommand(backCommand);
    }
    Component contentPane = super.getContentPane();
    Label title = super.getTitleComponent();
    int menuHeight = calcMenuHeight();
    UIManager manager = getUIManager();
    // preferred size logic of the dialog won't work with large title borders
    if (dialogTitle != null && manager.isThemeConstant("hideEmptyTitleBool", false)) {
        boolean b = getTitle().length() > 0;
        getTitleArea().setVisible(b);
        getTitleComponent().setVisible(b);
        if (!b && manager.isThemeConstant("shrinkPopupTitleBool", true)) {
            getTitleComponent().setPreferredSize(new Dimension(0, 0));
            getTitleComponent().getStyle().setBorder(null);
            getTitleArea().setPreferredSize(new Dimension(0, 0));
            if (getContentPane().getClientProperty("$ENLARGED_POP") == null) {
                getContentPane().putClientProperty("$ENLARGED_POP", Boolean.TRUE);
                int cpPaddingTop = getContentPane().getStyle().getPaddingTop();
                int titlePT = getTitleComponent().getStyle().getPaddingTop();
                byte[] pu = getContentPane().getStyle().getPaddingUnit();
                if (pu == null) {
                    pu = new byte[4];
                }
                pu[0] = Style.UNIT_TYPE_PIXELS;
                getContentPane().getStyle().setPaddingUnit(pu);
                int pop = Display.getInstance().convertToPixels(manager.getThemeConstant("popupNoTitleAddPaddingInt", 1), false);
                getContentPane().getStyle().setPadding(TOP, pop + cpPaddingTop + titlePT);
            }
        }
    }
    // allows a text area to recalculate its preferred size if embedded within a dialog
    revalidate();
    Style contentPaneStyle = getDialogStyle();
    boolean restoreArrow = false;
    if (manager.isThemeConstant(getDialogUIID() + "ArrowBool", false)) {
        Image t = manager.getThemeImageConstant(getDialogUIID() + "ArrowTopImage");
        Image b = manager.getThemeImageConstant(getDialogUIID() + "ArrowBottomImage");
        Image l = manager.getThemeImageConstant(getDialogUIID() + "ArrowLeftImage");
        Image r = manager.getThemeImageConstant(getDialogUIID() + "ArrowRightImage");
        Border border = contentPaneStyle.getBorder();
        if (border != null) {
            border.setImageBorderSpecialTile(t, b, l, r, rect);
            restoreArrow = true;
        }
    }
    int prefHeight = contentPane.getPreferredH();
    int prefWidth = contentPane.getPreferredW();
    if (contentPaneStyle.getBorder() != null) {
        prefWidth = Math.max(contentPaneStyle.getBorder().getMinimumWidth(), prefWidth);
        prefHeight = Math.max(contentPaneStyle.getBorder().getMinimumHeight(), prefHeight);
    }
    prefWidth += getUIManager().getLookAndFeel().getVerticalScrollWidth();
    int availableHeight = Display.getInstance().getDisplayHeight() - menuHeight - title.getPreferredH();
    int availableWidth = Display.getInstance().getDisplayWidth();
    int width = Math.min(availableWidth, prefWidth);
    int x = 0;
    int y = 0;
    Command result;
    boolean showPortrait;
    if (popupDirectionBiasPortrait != null) {
        showPortrait = popupDirectionBiasPortrait.booleanValue();
    } else {
        showPortrait = Display.getInstance().isPortrait();
    }
    // if we don't have enough space then disregard device orientation
    if (showPortrait) {
        if (availableHeight < (availableWidth - rect.getWidth()) / 2) {
            showPortrait = false;
        }
    } else {
        if (availableHeight / 2 > availableWidth - rect.getWidth()) {
            showPortrait = true;
        }
    }
    if (showPortrait) {
        if (width < availableWidth) {
            int idealX = rect.getX() - width / 2 + rect.getSize().getWidth() / 2;
            // if the ideal position is less than 0 just use 0
            if (idealX > 0) {
                // if the idealX is too far to the right just align to the right
                if (idealX + width > availableWidth) {
                    x = availableWidth - width;
                } else {
                    x = idealX;
                }
            }
        }
        if (rect.getY() < availableHeight / 2) {
            // popup downwards
            y = rect.getY() + rect.getSize().getHeight();
            int height = Math.min(prefHeight, availableHeight - y);
            result = show(y, availableHeight - height - y, x, availableWidth - width - x, true, true);
        } else {
            // popup upwards
            int height = Math.min(prefHeight, availableHeight - (availableHeight - rect.getY()));
            y = rect.getY() - height;
            result = show(y, availableHeight - height - y, x, availableWidth - width - x, true, true);
        }
    } else {
        int height = Math.min(prefHeight, availableHeight);
        if (height < availableHeight) {
            int idealY = rect.getY() - height / 2 + rect.getSize().getHeight() / 2;
            // if the ideal position is less than 0 just use 0
            if (idealY > 0) {
                // if the idealY is too far up just align to the top
                if (idealY + height > availableHeight) {
                    y = availableHeight - height;
                } else {
                    y = idealY;
                }
            }
        }
        if (prefWidth > rect.getX()) {
            // popup right
            x = rect.getX() + rect.getSize().getWidth();
            if (x + prefWidth > availableWidth) {
                x = availableWidth - prefWidth;
            }
            width = Math.min(prefWidth, availableWidth - x);
            result = show(y, availableHeight - height - y, Math.max(0, x), Math.max(0, availableWidth - width - x), true, true);
        } else {
            // popup left
            width = Math.min(prefWidth, availableWidth - (availableWidth - rect.getX()));
            x = rect.getX() - width;
            result = show(y, availableHeight - height - y, Math.max(0, x), Math.max(0, availableWidth - width - x), true, true);
        }
    }
    if (restoreArrow) {
        contentPaneStyle.getBorder().clearImageBorderSpecialTile();
    }
    if (result == backCommand) {
        return null;
    }
    return result;
}
Also used : UIManager(com.codename1.ui.plaf.UIManager) Style(com.codename1.ui.plaf.Style) Dimension(com.codename1.ui.geom.Dimension) Border(com.codename1.ui.plaf.Border)

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