diff --git a/admob/src_java/com/google/firebase/admob/internal/cpp/AdRequestHelper.java b/admob/src_java/com/google/firebase/admob/internal/cpp/AdRequestHelper.java index 4fe9faa3cc..94ca85024f 100644 --- a/admob/src_java/com/google/firebase/admob/internal/cpp/AdRequestHelper.java +++ b/admob/src_java/com/google/firebase/admob/internal/cpp/AdRequestHelper.java @@ -25,7 +25,6 @@ * into their (typically more complicated) Java equivalents. */ public class AdRequestHelper { - public AdRequestHelper() {} /** diff --git a/admob/src_java/com/google/firebase/admob/internal/cpp/BannerViewHelper.java b/admob/src_java/com/google/firebase/admob/internal/cpp/BannerViewHelper.java index 80233e212f..e620d85550 100644 --- a/admob/src_java/com/google/firebase/admob/internal/cpp/BannerViewHelper.java +++ b/admob/src_java/com/google/firebase/admob/internal/cpp/BannerViewHelper.java @@ -38,7 +38,6 @@ * game engine-friendly state machine polling. */ public class BannerViewHelper implements ViewTreeObserver.OnPreDrawListener { - // It's possible to attempt to show a popup when an activity doesn't have focus. This value // controls the number of times the BannerViewHelper object checks for activity window focus // before timing out. Assuming 10ms per retry this value attempts to retry for 2 minutes before @@ -139,14 +138,8 @@ public BannerViewHelper(long bannerViewInternalPtr) { * Initializes the {@link BannerView}. This creates the corresponding GMA SDK {@link AdView} * object and sets it up. */ - public void initialize( - final long callbackDataPtr, - Activity activity, - String adUnitID, - int adSizeType, - int width, - int height) { - + public void initialize(final long callbackDataPtr, Activity activity, String adUnitID, + int adSizeType, int width, int height) { // There is only one ad size type right now, which is why that parameter goes unused. mAdSize = new AdSize(width, height); mActivity = activity; @@ -156,27 +149,26 @@ public void initialize( } // Create the AdView on the UI thread. - mActivity.runOnUiThread( - new Runnable() { - @Override - public void run() { - int errorCode; - String errorMessage; - if (mAdView == null) { - errorCode = ConstantsHelper.CALLBACK_ERROR_NONE; - errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_NONE; - mAdView = new AdView(mActivity); - mAdView.setAdUnitId(mAdUnitId); - mAdView.setAdSize(mAdSize); - mAdView.setAdListener(new AdViewListener()); - } else { - errorCode = ConstantsHelper.CALLBACK_ERROR_ALREADY_INITIALIZED; - errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_ALREADY_INITIALIZED; - } + mActivity.runOnUiThread(new Runnable() { + @Override + public void run() { + int errorCode; + String errorMessage; + if (mAdView == null) { + errorCode = ConstantsHelper.CALLBACK_ERROR_NONE; + errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_NONE; + mAdView = new AdView(mActivity); + mAdView.setAdUnitId(mAdUnitId); + mAdView.setAdSize(mAdSize); + mAdView.setAdListener(new AdViewListener()); + } else { + errorCode = ConstantsHelper.CALLBACK_ERROR_ALREADY_INITIALIZED; + errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_ALREADY_INITIALIZED; + } - completeBannerViewFutureCallback(callbackDataPtr, errorCode, errorMessage); - } - }); + completeBannerViewFutureCallback(callbackDataPtr, errorCode, errorMessage); + } + }); } /** Destroy/deallocate the {@link PopupWindow} and {@link AdView}. */ @@ -190,35 +182,31 @@ public void destroy(final long callbackDataPtr) { mPopUpRunnable = null; } - mActivity.runOnUiThread( - new Runnable() { - @Override - public void run() { - if (mAdView != null) { - mAdView.destroy(); - mAdView = null; - } + mActivity.runOnUiThread(new Runnable() { + @Override + public void run() { + if (mAdView != null) { + mAdView.destroy(); + mAdView = null; + } - synchronized (mPopUpLock) { - if (mPopUp != null) { - mPopUp.dismiss(); - mPopUp = null; - } - } + synchronized (mPopUpLock) { + if (mPopUp != null) { + mPopUp.dismiss(); + mPopUp = null; + } + } - mCurrentPresentationState = ConstantsHelper.AD_VIEW_PRESENTATION_STATE_HIDDEN; + mCurrentPresentationState = ConstantsHelper.AD_VIEW_PRESENTATION_STATE_HIDDEN; - notifyStateChanged( - mBannerViewInternalPtr, ConstantsHelper.AD_VIEW_CHANGED_PRESENTATION_STATE); - notifyStateChanged( - mBannerViewInternalPtr, ConstantsHelper.AD_VIEW_CHANGED_BOUNDING_BOX); - completeBannerViewFutureCallback( - callbackDataPtr, - ConstantsHelper.CALLBACK_ERROR_NONE, - ConstantsHelper.CALLBACK_ERROR_MESSAGE_NONE); - mNotifyListenerOnNextDraw.set(true); - } - }); + notifyStateChanged( + mBannerViewInternalPtr, ConstantsHelper.AD_VIEW_CHANGED_PRESENTATION_STATE); + notifyStateChanged(mBannerViewInternalPtr, ConstantsHelper.AD_VIEW_CHANGED_BOUNDING_BOX); + completeBannerViewFutureCallback(callbackDataPtr, ConstantsHelper.CALLBACK_ERROR_NONE, + ConstantsHelper.CALLBACK_ERROR_MESSAGE_NONE); + mNotifyListenerOnNextDraw.set(true); + } + }); } /** Loads an ad for the underlying AdView object. */ @@ -229,8 +217,7 @@ public void loadAd(long callbackDataPtr, final AdRequest request) { synchronized (mLoadAdCallbackDataPtrLock) { if (mLoadAdCallbackDataPtr != CPP_NULLPTR) { - completeBannerViewFutureCallback( - callbackDataPtr, + completeBannerViewFutureCallback(callbackDataPtr, ConstantsHelper.CALLBACK_ERROR_LOAD_IN_PROGRESS, ConstantsHelper.CALLBACK_ERROR_MESSAGE_LOAD_IN_PROGRESS); return; @@ -239,23 +226,21 @@ public void loadAd(long callbackDataPtr, final AdRequest request) { mLoadAdCallbackDataPtr = callbackDataPtr; } - mActivity.runOnUiThread( - new Runnable() { - @Override - public void run() { - if (mAdView == null) { - synchronized (mLoadAdCallbackDataPtrLock) { - completeBannerViewFutureCallback( - mLoadAdCallbackDataPtr, - ConstantsHelper.CALLBACK_ERROR_UNINITIALIZED, - ConstantsHelper.CALLBACK_ERROR_MESSAGE_UNINITIALIZED); - mLoadAdCallbackDataPtr = CPP_NULLPTR; - } - } else { - mAdView.loadAd(request); - } + mActivity.runOnUiThread(new Runnable() { + @Override + public void run() { + if (mAdView == null) { + synchronized (mLoadAdCallbackDataPtrLock) { + completeBannerViewFutureCallback(mLoadAdCallbackDataPtr, + ConstantsHelper.CALLBACK_ERROR_UNINITIALIZED, + ConstantsHelper.CALLBACK_ERROR_MESSAGE_UNINITIALIZED); + mLoadAdCallbackDataPtr = CPP_NULLPTR; } - }); + } else { + mAdView.loadAd(request); + } + } + }); } /** Hides the {@link BannerView}. */ @@ -269,31 +254,30 @@ public void hide(final long callbackDataPtr) { mPopUpRunnable = null; } - mActivity.runOnUiThread( - new Runnable() { - @Override - public void run() { - int errorCode; - String errorMessage; + mActivity.runOnUiThread(new Runnable() { + @Override + public void run() { + int errorCode; + String errorMessage; - synchronized (mPopUpLock) { - if (mAdView == null || mPopUp == null) { - errorCode = ConstantsHelper.CALLBACK_ERROR_UNINITIALIZED; - errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_UNINITIALIZED; - } else { - errorCode = ConstantsHelper.CALLBACK_ERROR_NONE; - errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_NONE; - mPopUp.dismiss(); - mPopUp = null; - mCurrentPresentationState = ConstantsHelper.AD_VIEW_PRESENTATION_STATE_HIDDEN; - } - } - - completeBannerViewFutureCallback(callbackDataPtr, errorCode, errorMessage); - notifyStateChanged( - mBannerViewInternalPtr, ConstantsHelper.AD_VIEW_CHANGED_PRESENTATION_STATE); + synchronized (mPopUpLock) { + if (mAdView == null || mPopUp == null) { + errorCode = ConstantsHelper.CALLBACK_ERROR_UNINITIALIZED; + errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_UNINITIALIZED; + } else { + errorCode = ConstantsHelper.CALLBACK_ERROR_NONE; + errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_NONE; + mPopUp.dismiss(); + mPopUp = null; + mCurrentPresentationState = ConstantsHelper.AD_VIEW_PRESENTATION_STATE_HIDDEN; } - }); + } + + completeBannerViewFutureCallback(callbackDataPtr, errorCode, errorMessage); + notifyStateChanged( + mBannerViewInternalPtr, ConstantsHelper.AD_VIEW_CHANGED_PRESENTATION_STATE); + } + }); } /** Shows the {@link BannerView}. */ @@ -310,20 +294,17 @@ public void pause(final long callbackDataPtr) { if (mActivity == null) { return; } - mActivity.runOnUiThread( - new Runnable() { - @Override - public void run() { - if (mAdView != null) { - mAdView.pause(); - } + mActivity.runOnUiThread(new Runnable() { + @Override + public void run() { + if (mAdView != null) { + mAdView.pause(); + } - completeBannerViewFutureCallback( - callbackDataPtr, - ConstantsHelper.CALLBACK_ERROR_NONE, - ConstantsHelper.CALLBACK_ERROR_MESSAGE_NONE); - } - }); + completeBannerViewFutureCallback(callbackDataPtr, ConstantsHelper.CALLBACK_ERROR_NONE, + ConstantsHelper.CALLBACK_ERROR_MESSAGE_NONE); + } + }); } /** Resume the {@link BannerView} (from a pause). */ @@ -331,20 +312,17 @@ public void resume(final long callbackDataPtr) { if (mActivity == null) { return; } - mActivity.runOnUiThread( - new Runnable() { - @Override - public void run() { - if (mAdView != null) { - mAdView.resume(); - } + mActivity.runOnUiThread(new Runnable() { + @Override + public void run() { + if (mAdView != null) { + mAdView.resume(); + } - completeBannerViewFutureCallback( - callbackDataPtr, - ConstantsHelper.CALLBACK_ERROR_NONE, - ConstantsHelper.CALLBACK_ERROR_MESSAGE_NONE); - } - }); + completeBannerViewFutureCallback(callbackDataPtr, ConstantsHelper.CALLBACK_ERROR_NONE, + ConstantsHelper.CALLBACK_ERROR_MESSAGE_NONE); + } + }); } /** Moves the {@link BannerView} to the provided (x,y) screen coordinates. */ @@ -446,109 +424,105 @@ private boolean updatePopUpLocation(final long callbackDataPtr) { synchronized (mPopUpLock) { if (mPopUp != null) { - mActivity.runOnUiThread( - new Runnable() { - @Override - public void run() { - synchronized (mPopUpLock) { - // Any change in visibility or position results in the dismissal of the popup (if - // one is being displayed) and creation of a fresh one. - mPopUp.dismiss(); - mPopUp = null; - } - } - }); + mActivity.runOnUiThread(new Runnable() { + @Override + public void run() { + synchronized (mPopUpLock) { + // Any change in visibility or position results in the dismissal of the popup (if + // one is being displayed) and creation of a fresh one. + mPopUp.dismiss(); + mPopUp = null; + } + } + }); } mPopUpShowRetryCount = 0; - mPopUpRunnable = - new Runnable() { - @Override - public void run() { - int errorCode = ConstantsHelper.CALLBACK_ERROR_NONE; - String errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_NONE; - // If the Activity's window doesn't currently have focus it's not - // possible to display the popup window. Poll the focus after a delay of 10ms and try - // to show the popup again. - if (!mActivity.hasWindowFocus()) { - synchronized (mPopUpLock) { - if (mPopUpRunnable == null) { - errorCode = ConstantsHelper.CALLBACK_ERROR_UNINITIALIZED; - errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_UNINITIALIZED; - } else { - if (mPopUpShowRetryCount < POPUP_SHOW_RETRY_COUNT) { - mPopUpShowRetryCount++; - new Handler().postDelayed(mPopUpRunnable, 10); - return; - } else { - errorCode = ConstantsHelper.CALLBACK_ERROR_NO_WINDOW_TOKEN; - errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_NO_WINDOW_TOKEN; - } - } - } - } - - if (mAdView == null) { + mPopUpRunnable = new Runnable() { + @Override + public void run() { + int errorCode = ConstantsHelper.CALLBACK_ERROR_NONE; + String errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_NONE; + // If the Activity's window doesn't currently have focus it's not + // possible to display the popup window. Poll the focus after a delay of 10ms and try + // to show the popup again. + if (!mActivity.hasWindowFocus()) { + synchronized (mPopUpLock) { + if (mPopUpRunnable == null) { errorCode = ConstantsHelper.CALLBACK_ERROR_UNINITIALIZED; errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_UNINITIALIZED; + } else { + if (mPopUpShowRetryCount < POPUP_SHOW_RETRY_COUNT) { + mPopUpShowRetryCount++; + new Handler().postDelayed(mPopUpRunnable, 10); + return; + } else { + errorCode = ConstantsHelper.CALLBACK_ERROR_NO_WINDOW_TOKEN; + errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_NO_WINDOW_TOKEN; + } } + } + } - if (errorCode != ConstantsHelper.CALLBACK_ERROR_NONE) { - completeBannerViewFutureCallback(callbackDataPtr, errorCode, errorMessage); - return; - } + if (mAdView == null) { + errorCode = ConstantsHelper.CALLBACK_ERROR_UNINITIALIZED; + errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_UNINITIALIZED; + } - if (mPopUp == null) { - mPopUp = - new PopupWindow(mAdView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); - mPopUp.setBackgroundDrawable(new ColorDrawable(0xFF000000)); // Black - mAdView.getViewTreeObserver().addOnPreDrawListener(BannerViewHelper.this); + if (errorCode != ConstantsHelper.CALLBACK_ERROR_NONE) { + completeBannerViewFutureCallback(callbackDataPtr, errorCode, errorMessage); + return; + } - if (mShouldUseXYForPosition) { - mPopUp.showAtLocation(root, Gravity.NO_GRAVITY, mDesiredX, mDesiredY); - } else { - switch (mDesiredPosition) { - case ConstantsHelper.AD_VIEW_POSITION_TOP: - mPopUp.showAtLocation(root, Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0); - break; - case ConstantsHelper.AD_VIEW_POSITION_BOTTOM: - mPopUp.showAtLocation(root, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); - break; - case ConstantsHelper.AD_VIEW_POSITION_TOP_LEFT: - mPopUp.showAtLocation(root, Gravity.TOP | Gravity.LEFT, 0, 0); - break; - case ConstantsHelper.AD_VIEW_POSITION_TOP_RIGHT: - mPopUp.showAtLocation(root, Gravity.TOP | Gravity.RIGHT, 0, 0); - break; - case ConstantsHelper.AD_VIEW_POSITION_BOTTOM_LEFT: - mPopUp.showAtLocation(root, Gravity.BOTTOM | Gravity.LEFT, 0, 0); - break; - case ConstantsHelper.AD_VIEW_POSITION_BOTTOM_RIGHT: - mPopUp.showAtLocation(root, Gravity.BOTTOM | Gravity.RIGHT, 0, 0); - break; - default: - mPopUp.showAtLocation(root, Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0); - break; - } - } - } + if (mPopUp == null) { + mPopUp = new PopupWindow(mAdView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); + mPopUp.setBackgroundDrawable(new ColorDrawable(0xFF000000)); // Black + mAdView.getViewTreeObserver().addOnPreDrawListener(BannerViewHelper.this); - if (errorCode == ConstantsHelper.CALLBACK_ERROR_NO_WINDOW_TOKEN) { - mCurrentPresentationState = ConstantsHelper.AD_VIEW_PRESENTATION_STATE_HIDDEN; - } else if (mAdViewContainsAd) { - mCurrentPresentationState = - ConstantsHelper.AD_VIEW_PRESENTATION_STATE_VISIBLE_WITH_AD; - } else { - mCurrentPresentationState = - ConstantsHelper.AD_VIEW_PRESENTATION_STATE_VISIBLE_WITHOUT_AD; + if (mShouldUseXYForPosition) { + mPopUp.showAtLocation(root, Gravity.NO_GRAVITY, mDesiredX, mDesiredY); + } else { + switch (mDesiredPosition) { + case ConstantsHelper.AD_VIEW_POSITION_TOP: + mPopUp.showAtLocation(root, Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0); + break; + case ConstantsHelper.AD_VIEW_POSITION_BOTTOM: + mPopUp.showAtLocation(root, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); + break; + case ConstantsHelper.AD_VIEW_POSITION_TOP_LEFT: + mPopUp.showAtLocation(root, Gravity.TOP | Gravity.LEFT, 0, 0); + break; + case ConstantsHelper.AD_VIEW_POSITION_TOP_RIGHT: + mPopUp.showAtLocation(root, Gravity.TOP | Gravity.RIGHT, 0, 0); + break; + case ConstantsHelper.AD_VIEW_POSITION_BOTTOM_LEFT: + mPopUp.showAtLocation(root, Gravity.BOTTOM | Gravity.LEFT, 0, 0); + break; + case ConstantsHelper.AD_VIEW_POSITION_BOTTOM_RIGHT: + mPopUp.showAtLocation(root, Gravity.BOTTOM | Gravity.RIGHT, 0, 0); + break; + default: + mPopUp.showAtLocation(root, Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0); + break; } - - completeBannerViewFutureCallback(callbackDataPtr, errorCode, errorMessage); - notifyStateChanged( - mBannerViewInternalPtr, ConstantsHelper.AD_VIEW_CHANGED_PRESENTATION_STATE); - mNotifyListenerOnNextDraw.set(true); } - }; + } + + if (errorCode == ConstantsHelper.CALLBACK_ERROR_NO_WINDOW_TOKEN) { + mCurrentPresentationState = ConstantsHelper.AD_VIEW_PRESENTATION_STATE_HIDDEN; + } else if (mAdViewContainsAd) { + mCurrentPresentationState = ConstantsHelper.AD_VIEW_PRESENTATION_STATE_VISIBLE_WITH_AD; + } else { + mCurrentPresentationState = + ConstantsHelper.AD_VIEW_PRESENTATION_STATE_VISIBLE_WITHOUT_AD; + } + + completeBannerViewFutureCallback(callbackDataPtr, errorCode, errorMessage); + notifyStateChanged( + mBannerViewInternalPtr, ConstantsHelper.AD_VIEW_CHANGED_PRESENTATION_STATE); + mNotifyListenerOnNextDraw.set(true); + } + }; } // TODO(b/31391149): This delay is a workaround for b/31391149, and should be removed once @@ -613,10 +587,8 @@ public void onAdLeftApplication() { public void onAdLoaded() { mAdViewContainsAd = true; synchronized (mLoadAdCallbackDataPtrLock) { - completeBannerViewFutureCallback( - mLoadAdCallbackDataPtr, - ConstantsHelper.CALLBACK_ERROR_NONE, - ConstantsHelper.CALLBACK_ERROR_MESSAGE_NONE); + completeBannerViewFutureCallback(mLoadAdCallbackDataPtr, + ConstantsHelper.CALLBACK_ERROR_NONE, ConstantsHelper.CALLBACK_ERROR_MESSAGE_NONE); mLoadAdCallbackDataPtr = CPP_NULLPTR; } // Only update the presentation state if the banner view is already visible. diff --git a/admob/src_java/com/google/firebase/admob/internal/cpp/ConstantsHelper.java b/admob/src_java/com/google/firebase/admob/internal/cpp/ConstantsHelper.java index 0687ba7f52..0e95c4b74f 100644 --- a/admob/src_java/com/google/firebase/admob/internal/cpp/ConstantsHelper.java +++ b/admob/src_java/com/google/firebase/admob/internal/cpp/ConstantsHelper.java @@ -18,7 +18,6 @@ /** Helper class containing constants that are shared across the various AdMob ad formats. */ public final class ConstantsHelper { - /** * Error codes used in completing futures. These match the AdMobError enumeration in the C++ API. */ @@ -117,5 +116,4 @@ public final class ConstantsHelper { public static final int AD_VIEW_POSITION_BOTTOM_RIGHT = 5; // LINT.ThenChange(//depot_firebase_cpp/admob/client/cpp/src/include/firebase/admob/banner_view.h, // //depot_firebase_cpp/admob/client/cpp/src/include/firebase/admob/native_express_ad_view.h) - } diff --git a/admob/src_java/com/google/firebase/admob/internal/cpp/InterstitialAdHelper.java b/admob/src_java/com/google/firebase/admob/internal/cpp/InterstitialAdHelper.java index 60b7183de7..1f81b366ff 100644 --- a/admob/src_java/com/google/firebase/admob/internal/cpp/InterstitialAdHelper.java +++ b/admob/src_java/com/google/firebase/admob/internal/cpp/InterstitialAdHelper.java @@ -28,7 +28,6 @@ * convert the Java listener patterns into game engine-friendly state machine polling. */ public class InterstitialAdHelper { - // Presentation states (matches the InterstitialAd::PresentationState // enumeration in the public C++ API). // LINT.IfChange @@ -85,34 +84,32 @@ public void initialize(final long callbackDataPtr, Activity activity, String adU mActivity = activity; mAdUnitId = adUnitID; - mActivity.runOnUiThread( - new Runnable() { - @Override - public void run() { - int errorCode; - String errorMessage; - if (mInterstitial == null) { - try { - mInterstitial = new InterstitialAd(mActivity); - mInterstitial.setAdUnitId(mAdUnitId); - mInterstitial.setAdListener(new InterstitialAdListener()); - errorCode = ConstantsHelper.CALLBACK_ERROR_NONE; - errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_NONE; - } catch (IllegalStateException e) { - mInterstitial = null; - // This exception can be thrown if the ad unit ID was already set. - errorCode = ConstantsHelper.CALLBACK_ERROR_ALREADY_INITIALIZED; - errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_ALREADY_INITIALIZED; - } - } else { - errorCode = ConstantsHelper.CALLBACK_ERROR_ALREADY_INITIALIZED; - errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_ALREADY_INITIALIZED; - - } - - completeInterstitialAdFutureCallback(callbackDataPtr, errorCode, errorMessage); + mActivity.runOnUiThread(new Runnable() { + @Override + public void run() { + int errorCode; + String errorMessage; + if (mInterstitial == null) { + try { + mInterstitial = new InterstitialAd(mActivity); + mInterstitial.setAdUnitId(mAdUnitId); + mInterstitial.setAdListener(new InterstitialAdListener()); + errorCode = ConstantsHelper.CALLBACK_ERROR_NONE; + errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_NONE; + } catch (IllegalStateException e) { + mInterstitial = null; + // This exception can be thrown if the ad unit ID was already set. + errorCode = ConstantsHelper.CALLBACK_ERROR_ALREADY_INITIALIZED; + errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_ALREADY_INITIALIZED; } - }); + } else { + errorCode = ConstantsHelper.CALLBACK_ERROR_ALREADY_INITIALIZED; + errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_ALREADY_INITIALIZED; + } + + completeInterstitialAdFutureCallback(callbackDataPtr, errorCode, errorMessage); + } + }); } /** Disconnect the helper from the interstital ad. */ @@ -121,24 +118,22 @@ public void disconnect() { mInterstitialAdInternalPtr = CPP_NULLPTR; mLoadAdCallbackDataPtr = CPP_NULLPTR; } - mActivity.runOnUiThread( - new Runnable() { - @Override - public void run() { - synchronized (mInterstitialLock) { - mInterstitial.setAdListener(null); - mInterstitial = null; - } - } - }); + mActivity.runOnUiThread(new Runnable() { + @Override + public void run() { + synchronized (mInterstitialLock) { + mInterstitial.setAdListener(null); + mInterstitial = null; + } + } + }); } /** Loads an ad for the underlying {@link InterstitialAd} object. */ public void loadAd(long callbackDataPtr, final AdRequest request) { synchronized (mInterstitialLock) { if (mLoadAdCallbackDataPtr != CPP_NULLPTR) { - completeInterstitialAdFutureCallback( - callbackDataPtr, + completeInterstitialAdFutureCallback(callbackDataPtr, ConstantsHelper.CALLBACK_ERROR_LOAD_IN_PROGRESS, ConstantsHelper.CALLBACK_ERROR_MESSAGE_LOAD_IN_PROGRESS); return; @@ -147,61 +142,57 @@ public void loadAd(long callbackDataPtr, final AdRequest request) { mLoadAdCallbackDataPtr = callbackDataPtr; } - mActivity.runOnUiThread( - new Runnable() { - @Override - public void run() { - if (mInterstitial == null) { - synchronized (mInterstitialLock) { - completeInterstitialAdFutureCallback( - mLoadAdCallbackDataPtr, - ConstantsHelper.CALLBACK_ERROR_UNINITIALIZED, - ConstantsHelper.CALLBACK_ERROR_MESSAGE_UNINITIALIZED); - mLoadAdCallbackDataPtr = CPP_NULLPTR; - } - } else { - try { - mInterstitial.loadAd(request); - } catch (IllegalStateException e) { - synchronized (mInterstitialLock) { - completeInterstitialAdFutureCallback( - mLoadAdCallbackDataPtr, - ConstantsHelper.CALLBACK_ERROR_UNINITIALIZED, - ConstantsHelper.CALLBACK_ERROR_MESSAGE_UNINITIALIZED); - mLoadAdCallbackDataPtr = CPP_NULLPTR; - } - } + mActivity.runOnUiThread(new Runnable() { + @Override + public void run() { + if (mInterstitial == null) { + synchronized (mInterstitialLock) { + completeInterstitialAdFutureCallback(mLoadAdCallbackDataPtr, + ConstantsHelper.CALLBACK_ERROR_UNINITIALIZED, + ConstantsHelper.CALLBACK_ERROR_MESSAGE_UNINITIALIZED); + mLoadAdCallbackDataPtr = CPP_NULLPTR; + } + } else { + try { + mInterstitial.loadAd(request); + } catch (IllegalStateException e) { + synchronized (mInterstitialLock) { + completeInterstitialAdFutureCallback(mLoadAdCallbackDataPtr, + ConstantsHelper.CALLBACK_ERROR_UNINITIALIZED, + ConstantsHelper.CALLBACK_ERROR_MESSAGE_UNINITIALIZED); + mLoadAdCallbackDataPtr = CPP_NULLPTR; } } - }); + } + } + }); } /** Shows a previously loaded ad. */ public void show(final long callbackDataPtr) { - mActivity.runOnUiThread( - new Runnable() { - @Override - public void run() { - synchronized (mInterstitialLock) { - int errorCode; - String errorMessage; - if (mInterstitial == null) { - errorCode = ConstantsHelper.CALLBACK_ERROR_UNINITIALIZED; - errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_UNINITIALIZED; - } else if (!mInterstitial.isLoaded()) { - errorCode = ConstantsHelper.CALLBACK_ERROR_LOAD_IN_PROGRESS; - errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_LOAD_IN_PROGRESS; - } else { - errorCode = ConstantsHelper.CALLBACK_ERROR_NONE; - errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_NONE; - mInterstitial.show(); - mCurrentPresentationState = PRESENTATION_STATE_COVERING_UI; - } - - completeInterstitialAdFutureCallback(callbackDataPtr, errorCode, errorMessage); - } + mActivity.runOnUiThread(new Runnable() { + @Override + public void run() { + synchronized (mInterstitialLock) { + int errorCode; + String errorMessage; + if (mInterstitial == null) { + errorCode = ConstantsHelper.CALLBACK_ERROR_UNINITIALIZED; + errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_UNINITIALIZED; + } else if (!mInterstitial.isLoaded()) { + errorCode = ConstantsHelper.CALLBACK_ERROR_LOAD_IN_PROGRESS; + errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_LOAD_IN_PROGRESS; + } else { + errorCode = ConstantsHelper.CALLBACK_ERROR_NONE; + errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_NONE; + mInterstitial.show(); + mCurrentPresentationState = PRESENTATION_STATE_COVERING_UI; } - }); + + completeInterstitialAdFutureCallback(callbackDataPtr, errorCode, errorMessage); + } + } + }); } /** Retrieves the presentation state of this InterstitialAdHelper. */ @@ -257,10 +248,8 @@ public void onAdFailedToLoad(int errorCode) { @Override public void onAdLoaded() { synchronized (mInterstitialLock) { - completeInterstitialAdFutureCallback( - mLoadAdCallbackDataPtr, - ConstantsHelper.CALLBACK_ERROR_NONE, - ConstantsHelper.CALLBACK_ERROR_MESSAGE_NONE); + completeInterstitialAdFutureCallback(mLoadAdCallbackDataPtr, + ConstantsHelper.CALLBACK_ERROR_NONE, ConstantsHelper.CALLBACK_ERROR_MESSAGE_NONE); mLoadAdCallbackDataPtr = CPP_NULLPTR; } super.onAdLoaded(); diff --git a/admob/src_java/com/google/firebase/admob/internal/cpp/NativeExpressAdViewHelper.java b/admob/src_java/com/google/firebase/admob/internal/cpp/NativeExpressAdViewHelper.java index d194c593c7..a31f50fcd8 100644 --- a/admob/src_java/com/google/firebase/admob/internal/cpp/NativeExpressAdViewHelper.java +++ b/admob/src_java/com/google/firebase/admob/internal/cpp/NativeExpressAdViewHelper.java @@ -38,7 +38,6 @@ * convert the Java listener patterns into game engine-friendly state machine polling. */ public class NativeExpressAdViewHelper implements ViewTreeObserver.OnPreDrawListener { - // It's possible to attempt to show a popup when an activity doesn't have focus. This value // controls the number of times the NativeExpressAdViewHelper object checks for activity window // focus before timing out. Assuming 10ms per retry this value attempts to retry for 2 minutes @@ -140,14 +139,8 @@ public NativeExpressAdViewHelper(long nativeExpressAdViewInternalPtr) { * Initializes the {@link NativeExpressAdView}. This creates the corresponding GMA SDK {@link * NativeExpressAdView} object and sets it up. */ - public void initialize( - final long callbackDataPtr, - Activity activity, - String adUnitID, - int adSizeType, - int width, - int height) { - + public void initialize(final long callbackDataPtr, Activity activity, String adUnitID, + int adSizeType, int width, int height) { // There is only one ad size type right now, which is why that parameter goes unused. mAdSize = new AdSize(width, height); mActivity = activity; @@ -157,27 +150,26 @@ public void initialize( } // Create the NativeExpressAdView on the UI thread. - mActivity.runOnUiThread( - new Runnable() { - @Override - public void run() { - int errorCode; - String errorMessage; - if (mNativeExpressAdView == null) { - errorCode = ConstantsHelper.CALLBACK_ERROR_NONE; - errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_NONE; - mNativeExpressAdView = new NativeExpressAdView(mActivity); - mNativeExpressAdView.setAdUnitId(mAdUnitId); - mNativeExpressAdView.setAdSize(mAdSize); - mNativeExpressAdView.setAdListener(new AdViewListener()); - } else { - errorCode = ConstantsHelper.CALLBACK_ERROR_ALREADY_INITIALIZED; - errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_ALREADY_INITIALIZED; - } + mActivity.runOnUiThread(new Runnable() { + @Override + public void run() { + int errorCode; + String errorMessage; + if (mNativeExpressAdView == null) { + errorCode = ConstantsHelper.CALLBACK_ERROR_NONE; + errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_NONE; + mNativeExpressAdView = new NativeExpressAdView(mActivity); + mNativeExpressAdView.setAdUnitId(mAdUnitId); + mNativeExpressAdView.setAdSize(mAdSize); + mNativeExpressAdView.setAdListener(new AdViewListener()); + } else { + errorCode = ConstantsHelper.CALLBACK_ERROR_ALREADY_INITIALIZED; + errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_ALREADY_INITIALIZED; + } - completeNativeExpressAdViewFutureCallback(callbackDataPtr, errorCode, errorMessage); - } - }); + completeNativeExpressAdViewFutureCallback(callbackDataPtr, errorCode, errorMessage); + } + }); } /** Destroy/deallocate the {@link PopupWindow} and {@link AdView}. */ @@ -191,36 +183,32 @@ public void destroy(final long callbackDataPtr) { mPopUpRunnable = null; } - mActivity.runOnUiThread( - new Runnable() { - @Override - public void run() { - if (mNativeExpressAdView != null) { - mNativeExpressAdView.destroy(); - mNativeExpressAdView = null; - } + mActivity.runOnUiThread(new Runnable() { + @Override + public void run() { + if (mNativeExpressAdView != null) { + mNativeExpressAdView.destroy(); + mNativeExpressAdView = null; + } - synchronized (mPopUpLock) { - if (mPopUp != null) { - mPopUp.dismiss(); - mPopUp = null; - } - } + synchronized (mPopUpLock) { + if (mPopUp != null) { + mPopUp.dismiss(); + mPopUp = null; + } + } - mCurrentPresentationState = ConstantsHelper.AD_VIEW_PRESENTATION_STATE_HIDDEN; + mCurrentPresentationState = ConstantsHelper.AD_VIEW_PRESENTATION_STATE_HIDDEN; - notifyStateChanged( - mNativeExpressAdViewInternalPtr, - ConstantsHelper.AD_VIEW_CHANGED_PRESENTATION_STATE); - notifyStateChanged( - mNativeExpressAdViewInternalPtr, ConstantsHelper.AD_VIEW_CHANGED_BOUNDING_BOX); - completeNativeExpressAdViewFutureCallback( - callbackDataPtr, - ConstantsHelper.CALLBACK_ERROR_NONE, - ConstantsHelper.CALLBACK_ERROR_MESSAGE_NONE); - mNotifyListenerOnNextDraw.set(true); - } - }); + notifyStateChanged( + mNativeExpressAdViewInternalPtr, ConstantsHelper.AD_VIEW_CHANGED_PRESENTATION_STATE); + notifyStateChanged( + mNativeExpressAdViewInternalPtr, ConstantsHelper.AD_VIEW_CHANGED_BOUNDING_BOX); + completeNativeExpressAdViewFutureCallback(callbackDataPtr, + ConstantsHelper.CALLBACK_ERROR_NONE, ConstantsHelper.CALLBACK_ERROR_MESSAGE_NONE); + mNotifyListenerOnNextDraw.set(true); + } + }); } /** Loads an ad for the underlying NativeExpressAdView object. */ @@ -231,8 +219,7 @@ public void loadAd(long callbackDataPtr, final AdRequest request) { synchronized (mLoadAdCallbackDataPtrLock) { if (mLoadAdCallbackDataPtr != CPP_NULLPTR) { - completeNativeExpressAdViewFutureCallback( - callbackDataPtr, + completeNativeExpressAdViewFutureCallback(callbackDataPtr, ConstantsHelper.CALLBACK_ERROR_LOAD_IN_PROGRESS, ConstantsHelper.CALLBACK_ERROR_MESSAGE_LOAD_IN_PROGRESS); return; @@ -241,23 +228,21 @@ public void loadAd(long callbackDataPtr, final AdRequest request) { mLoadAdCallbackDataPtr = callbackDataPtr; } - mActivity.runOnUiThread( - new Runnable() { - @Override - public void run() { - if (mNativeExpressAdView == null) { - synchronized (mLoadAdCallbackDataPtrLock) { - completeNativeExpressAdViewFutureCallback( - mLoadAdCallbackDataPtr, - ConstantsHelper.CALLBACK_ERROR_UNINITIALIZED, - ConstantsHelper.CALLBACK_ERROR_MESSAGE_UNINITIALIZED); - mLoadAdCallbackDataPtr = CPP_NULLPTR; - } - } else { - mNativeExpressAdView.loadAd(request); - } + mActivity.runOnUiThread(new Runnable() { + @Override + public void run() { + if (mNativeExpressAdView == null) { + synchronized (mLoadAdCallbackDataPtrLock) { + completeNativeExpressAdViewFutureCallback(mLoadAdCallbackDataPtr, + ConstantsHelper.CALLBACK_ERROR_UNINITIALIZED, + ConstantsHelper.CALLBACK_ERROR_MESSAGE_UNINITIALIZED); + mLoadAdCallbackDataPtr = CPP_NULLPTR; } - }); + } else { + mNativeExpressAdView.loadAd(request); + } + } + }); } /** Hides the {@link NativeExpressAdView}. */ @@ -271,32 +256,30 @@ public void hide(final long callbackDataPtr) { mPopUpRunnable = null; } - mActivity.runOnUiThread( - new Runnable() { - @Override - public void run() { - int errorCode; - String errorMessage; + mActivity.runOnUiThread(new Runnable() { + @Override + public void run() { + int errorCode; + String errorMessage; - synchronized (mPopUpLock) { - if (mNativeExpressAdView == null || mPopUp == null) { - errorCode = ConstantsHelper.CALLBACK_ERROR_UNINITIALIZED; - errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_UNINITIALIZED; - } else { - errorCode = ConstantsHelper.CALLBACK_ERROR_NONE; - errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_NONE; - mPopUp.dismiss(); - mPopUp = null; - mCurrentPresentationState = ConstantsHelper.AD_VIEW_PRESENTATION_STATE_HIDDEN; - } - } - - completeNativeExpressAdViewFutureCallback(callbackDataPtr, errorCode, errorMessage); - notifyStateChanged( - mNativeExpressAdViewInternalPtr, - ConstantsHelper.AD_VIEW_CHANGED_PRESENTATION_STATE); + synchronized (mPopUpLock) { + if (mNativeExpressAdView == null || mPopUp == null) { + errorCode = ConstantsHelper.CALLBACK_ERROR_UNINITIALIZED; + errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_UNINITIALIZED; + } else { + errorCode = ConstantsHelper.CALLBACK_ERROR_NONE; + errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_NONE; + mPopUp.dismiss(); + mPopUp = null; + mCurrentPresentationState = ConstantsHelper.AD_VIEW_PRESENTATION_STATE_HIDDEN; } - }); + } + + completeNativeExpressAdViewFutureCallback(callbackDataPtr, errorCode, errorMessage); + notifyStateChanged( + mNativeExpressAdViewInternalPtr, ConstantsHelper.AD_VIEW_CHANGED_PRESENTATION_STATE); + } + }); } /** Shows the {@link NativeExpressAdView}. */ @@ -313,20 +296,17 @@ public void pause(final long callbackDataPtr) { if (mActivity == null) { return; } - mActivity.runOnUiThread( - new Runnable() { - @Override - public void run() { - if (mNativeExpressAdView != null) { - mNativeExpressAdView.pause(); - } + mActivity.runOnUiThread(new Runnable() { + @Override + public void run() { + if (mNativeExpressAdView != null) { + mNativeExpressAdView.pause(); + } - completeNativeExpressAdViewFutureCallback( - callbackDataPtr, - ConstantsHelper.CALLBACK_ERROR_NONE, - ConstantsHelper.CALLBACK_ERROR_MESSAGE_NONE); - } - }); + completeNativeExpressAdViewFutureCallback(callbackDataPtr, + ConstantsHelper.CALLBACK_ERROR_NONE, ConstantsHelper.CALLBACK_ERROR_MESSAGE_NONE); + } + }); } /** Resume the {@link NativeExpressAdView} (from a pause). */ @@ -334,20 +314,17 @@ public void resume(final long callbackDataPtr) { if (mActivity == null) { return; } - mActivity.runOnUiThread( - new Runnable() { - @Override - public void run() { - if (mNativeExpressAdView != null) { - mNativeExpressAdView.resume(); - } + mActivity.runOnUiThread(new Runnable() { + @Override + public void run() { + if (mNativeExpressAdView != null) { + mNativeExpressAdView.resume(); + } - completeNativeExpressAdViewFutureCallback( - callbackDataPtr, - ConstantsHelper.CALLBACK_ERROR_NONE, - ConstantsHelper.CALLBACK_ERROR_MESSAGE_NONE); - } - }); + completeNativeExpressAdViewFutureCallback(callbackDataPtr, + ConstantsHelper.CALLBACK_ERROR_NONE, ConstantsHelper.CALLBACK_ERROR_MESSAGE_NONE); + } + }); } /** Moves the {@link NativeExpressAdView} to the provided (x,y) screen coordinates. */ @@ -450,113 +427,107 @@ private boolean updatePopUpLocation(final long callbackDataPtr) { synchronized (mPopUpLock) { if (mPopUp != null) { - mActivity.runOnUiThread( - new Runnable() { - @Override - public void run() { - synchronized (mPopUpLock) { - // Any change in visibility or position results in the dismissal of the popup (if - // one is being displayed) and creation of a fresh one. - mPopUp.dismiss(); - mPopUp = null; - } - } - }); + mActivity.runOnUiThread(new Runnable() { + @Override + public void run() { + synchronized (mPopUpLock) { + // Any change in visibility or position results in the dismissal of the popup (if + // one is being displayed) and creation of a fresh one. + mPopUp.dismiss(); + mPopUp = null; + } + } + }); } mPopUpShowRetryCount = 0; - mPopUpRunnable = - new Runnable() { - @Override - public void run() { - int errorCode = ConstantsHelper.CALLBACK_ERROR_NONE; - String errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_NONE; - // If the Activity's window doesn't currently have focus it's not - // possible to display the popup window. Poll the focus after a delay of 10ms and try - // to show the popup again. - if (!mActivity.hasWindowFocus()) { - synchronized (mPopUpLock) { - if (mPopUpRunnable == null) { - errorCode = ConstantsHelper.CALLBACK_ERROR_UNINITIALIZED; - errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_UNINITIALIZED; - } else { - if (mPopUpShowRetryCount < POPUP_SHOW_RETRY_COUNT) { - mPopUpShowRetryCount++; - new Handler().postDelayed(mPopUpRunnable, 10); - return; - } else { - errorCode = ConstantsHelper.CALLBACK_ERROR_NO_WINDOW_TOKEN; - errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_NO_WINDOW_TOKEN; - } - } - } - } - - if (mNativeExpressAdView == null) { + mPopUpRunnable = new Runnable() { + @Override + public void run() { + int errorCode = ConstantsHelper.CALLBACK_ERROR_NONE; + String errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_NONE; + // If the Activity's window doesn't currently have focus it's not + // possible to display the popup window. Poll the focus after a delay of 10ms and try + // to show the popup again. + if (!mActivity.hasWindowFocus()) { + synchronized (mPopUpLock) { + if (mPopUpRunnable == null) { errorCode = ConstantsHelper.CALLBACK_ERROR_UNINITIALIZED; errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_UNINITIALIZED; - } - - if (errorCode != ConstantsHelper.CALLBACK_ERROR_NONE) { - completeNativeExpressAdViewFutureCallback(callbackDataPtr, errorCode, errorMessage); - return; - } - - if (mPopUp == null) { - mPopUp = - new PopupWindow( - mNativeExpressAdView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); - mPopUp.setBackgroundDrawable(new ColorDrawable(0xFF000000)); // Black - mNativeExpressAdView - .getViewTreeObserver() - .addOnPreDrawListener(NativeExpressAdViewHelper.this); - - if (mShouldUseXYForPosition) { - mPopUp.showAtLocation(root, Gravity.NO_GRAVITY, mDesiredX, mDesiredY); + } else { + if (mPopUpShowRetryCount < POPUP_SHOW_RETRY_COUNT) { + mPopUpShowRetryCount++; + new Handler().postDelayed(mPopUpRunnable, 10); + return; } else { - switch (mDesiredPosition) { - case ConstantsHelper.AD_VIEW_POSITION_TOP: - mPopUp.showAtLocation(root, Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0); - break; - case ConstantsHelper.AD_VIEW_POSITION_BOTTOM: - mPopUp.showAtLocation(root, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); - break; - case ConstantsHelper.AD_VIEW_POSITION_TOP_LEFT: - mPopUp.showAtLocation(root, Gravity.TOP | Gravity.LEFT, 0, 0); - break; - case ConstantsHelper.AD_VIEW_POSITION_TOP_RIGHT: - mPopUp.showAtLocation(root, Gravity.TOP | Gravity.RIGHT, 0, 0); - break; - case ConstantsHelper.AD_VIEW_POSITION_BOTTOM_LEFT: - mPopUp.showAtLocation(root, Gravity.BOTTOM | Gravity.LEFT, 0, 0); - break; - case ConstantsHelper.AD_VIEW_POSITION_BOTTOM_RIGHT: - mPopUp.showAtLocation(root, Gravity.BOTTOM | Gravity.RIGHT, 0, 0); - break; - default: - mPopUp.showAtLocation(root, Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0); - break; - } + errorCode = ConstantsHelper.CALLBACK_ERROR_NO_WINDOW_TOKEN; + errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_NO_WINDOW_TOKEN; } } + } + } - if (errorCode == ConstantsHelper.CALLBACK_ERROR_NO_WINDOW_TOKEN) { - mCurrentPresentationState = ConstantsHelper.AD_VIEW_PRESENTATION_STATE_HIDDEN; - } else if (mNativeExpressAdViewContainsAd) { - mCurrentPresentationState = - ConstantsHelper.AD_VIEW_PRESENTATION_STATE_VISIBLE_WITH_AD; - } else { - mCurrentPresentationState = - ConstantsHelper.AD_VIEW_PRESENTATION_STATE_VISIBLE_WITHOUT_AD; - } + if (mNativeExpressAdView == null) { + errorCode = ConstantsHelper.CALLBACK_ERROR_UNINITIALIZED; + errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_UNINITIALIZED; + } - completeNativeExpressAdViewFutureCallback(callbackDataPtr, errorCode, errorMessage); - notifyStateChanged( - mNativeExpressAdViewInternalPtr, - ConstantsHelper.AD_VIEW_CHANGED_PRESENTATION_STATE); - mNotifyListenerOnNextDraw.set(true); + if (errorCode != ConstantsHelper.CALLBACK_ERROR_NONE) { + completeNativeExpressAdViewFutureCallback(callbackDataPtr, errorCode, errorMessage); + return; + } + + if (mPopUp == null) { + mPopUp = new PopupWindow( + mNativeExpressAdView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); + mPopUp.setBackgroundDrawable(new ColorDrawable(0xFF000000)); // Black + mNativeExpressAdView.getViewTreeObserver().addOnPreDrawListener( + NativeExpressAdViewHelper.this); + + if (mShouldUseXYForPosition) { + mPopUp.showAtLocation(root, Gravity.NO_GRAVITY, mDesiredX, mDesiredY); + } else { + switch (mDesiredPosition) { + case ConstantsHelper.AD_VIEW_POSITION_TOP: + mPopUp.showAtLocation(root, Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0); + break; + case ConstantsHelper.AD_VIEW_POSITION_BOTTOM: + mPopUp.showAtLocation(root, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); + break; + case ConstantsHelper.AD_VIEW_POSITION_TOP_LEFT: + mPopUp.showAtLocation(root, Gravity.TOP | Gravity.LEFT, 0, 0); + break; + case ConstantsHelper.AD_VIEW_POSITION_TOP_RIGHT: + mPopUp.showAtLocation(root, Gravity.TOP | Gravity.RIGHT, 0, 0); + break; + case ConstantsHelper.AD_VIEW_POSITION_BOTTOM_LEFT: + mPopUp.showAtLocation(root, Gravity.BOTTOM | Gravity.LEFT, 0, 0); + break; + case ConstantsHelper.AD_VIEW_POSITION_BOTTOM_RIGHT: + mPopUp.showAtLocation(root, Gravity.BOTTOM | Gravity.RIGHT, 0, 0); + break; + default: + mPopUp.showAtLocation(root, Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0); + break; + } } - }; + } + + if (errorCode == ConstantsHelper.CALLBACK_ERROR_NO_WINDOW_TOKEN) { + mCurrentPresentationState = ConstantsHelper.AD_VIEW_PRESENTATION_STATE_HIDDEN; + } else if (mNativeExpressAdViewContainsAd) { + mCurrentPresentationState = ConstantsHelper.AD_VIEW_PRESENTATION_STATE_VISIBLE_WITH_AD; + } else { + mCurrentPresentationState = + ConstantsHelper.AD_VIEW_PRESENTATION_STATE_VISIBLE_WITHOUT_AD; + } + + completeNativeExpressAdViewFutureCallback(callbackDataPtr, errorCode, errorMessage); + notifyStateChanged( + mNativeExpressAdViewInternalPtr, ConstantsHelper.AD_VIEW_CHANGED_PRESENTATION_STATE); + mNotifyListenerOnNextDraw.set(true); + } + }; } // TODO(b/31391149): This delay is a workaround for b/31391149, and should be removed once @@ -621,10 +592,8 @@ public void onAdLeftApplication() { public void onAdLoaded() { mNativeExpressAdViewContainsAd = true; synchronized (mLoadAdCallbackDataPtrLock) { - completeNativeExpressAdViewFutureCallback( - mLoadAdCallbackDataPtr, - ConstantsHelper.CALLBACK_ERROR_NONE, - ConstantsHelper.CALLBACK_ERROR_MESSAGE_NONE); + completeNativeExpressAdViewFutureCallback(mLoadAdCallbackDataPtr, + ConstantsHelper.CALLBACK_ERROR_NONE, ConstantsHelper.CALLBACK_ERROR_MESSAGE_NONE); mLoadAdCallbackDataPtr = CPP_NULLPTR; } // Only update the presentation state if the native express ad view is already visible. diff --git a/admob/src_java/com/google/firebase/admob/internal/cpp/RewardedVideoHelper.java b/admob/src_java/com/google/firebase/admob/internal/cpp/RewardedVideoHelper.java index ce1c03d6be..bc25c8c889 100644 --- a/admob/src_java/com/google/firebase/admob/internal/cpp/RewardedVideoHelper.java +++ b/admob/src_java/com/google/firebase/admob/internal/cpp/RewardedVideoHelper.java @@ -48,7 +48,6 @@ * still running (in which case the new call gracefully fails). */ public class RewardedVideoHelper { - // Presentation states (matches the rewarded_video::PresentationState // enumeration in the public C++ API). // LINT.IfChange @@ -131,18 +130,15 @@ public RewardedVideoHelper(long rewardedVideoInternalPtr, Activity activity) { * call. */ public void initialize(final long callbackDataPtr) { - mActivity.runOnUiThread( - new Runnable() { - @Override - public void run() { - RewardedVideoAd ad = MobileAds.getRewardedVideoAdInstance(mActivity); - ad.setRewardedVideoAdListener(new RewardedListener()); - completeRewardedVideoFutureCallback( - callbackDataPtr, - ConstantsHelper.CALLBACK_ERROR_NONE, - ConstantsHelper.CALLBACK_ERROR_MESSAGE_NONE); - } - }); + mActivity.runOnUiThread(new Runnable() { + @Override + public void run() { + RewardedVideoAd ad = MobileAds.getRewardedVideoAdInstance(mActivity); + ad.setRewardedVideoAdListener(new RewardedListener()); + completeRewardedVideoFutureCallback(callbackDataPtr, ConstantsHelper.CALLBACK_ERROR_NONE, + ConstantsHelper.CALLBACK_ERROR_MESSAGE_NONE); + } + }); } /** @@ -161,8 +157,7 @@ public void run() { public void loadAd(long callbackDataPtr, final String adUnitId, final AdRequest request) { synchronized (mRewardedVideoLock) { if (mLoadAdCallbackDataPtr != CPP_NULLPTR) { - completeRewardedVideoFutureCallback( - callbackDataPtr, + completeRewardedVideoFutureCallback(callbackDataPtr, ConstantsHelper.CALLBACK_ERROR_LOAD_IN_PROGRESS, ConstantsHelper.CALLBACK_ERROR_MESSAGE_LOAD_IN_PROGRESS); return; @@ -171,14 +166,13 @@ public void loadAd(long callbackDataPtr, final String adUnitId, final AdRequest mLoadAdCallbackDataPtr = callbackDataPtr; } - mActivity.runOnUiThread( - new Runnable() { - @Override - public void run() { - RewardedVideoAd ad = MobileAds.getRewardedVideoAdInstance(mActivity); - ad.loadAd(adUnitId, request); - } - }); + mActivity.runOnUiThread(new Runnable() { + @Override + public void run() { + RewardedVideoAd ad = MobileAds.getRewardedVideoAdInstance(mActivity); + ad.loadAd(adUnitId, request); + } + }); } /** @@ -189,25 +183,24 @@ public void run() { * call. */ public void show(final long callbackDataPtr) { - mActivity.runOnUiThread( - new Runnable() { - @Override - public void run() { - int errorCode; - String errorMessage; - RewardedVideoAd ad = MobileAds.getRewardedVideoAdInstance(mActivity); - if (!ad.isLoaded()) { - errorCode = ConstantsHelper.CALLBACK_ERROR_LOAD_IN_PROGRESS; - errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_LOAD_IN_PROGRESS; - } else { - errorCode = ConstantsHelper.CALLBACK_ERROR_NONE; - errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_NONE; - ad.show(); - } - - completeRewardedVideoFutureCallback(callbackDataPtr, errorCode, errorMessage); - } - }); + mActivity.runOnUiThread(new Runnable() { + @Override + public void run() { + int errorCode; + String errorMessage; + RewardedVideoAd ad = MobileAds.getRewardedVideoAdInstance(mActivity); + if (!ad.isLoaded()) { + errorCode = ConstantsHelper.CALLBACK_ERROR_LOAD_IN_PROGRESS; + errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_LOAD_IN_PROGRESS; + } else { + errorCode = ConstantsHelper.CALLBACK_ERROR_NONE; + errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_NONE; + ad.show(); + } + + completeRewardedVideoFutureCallback(callbackDataPtr, errorCode, errorMessage); + } + }); } /** @@ -223,25 +216,22 @@ public void run() { * call. */ public void destroy(final long callbackDataPtr) { - mActivity.runOnUiThread( - new Runnable() { - @Override - public void run() { - RewardedVideoAd ad = MobileAds.getRewardedVideoAdInstance(mActivity); - ad.destroy(mActivity); - completeRewardedVideoFutureCallback( - callbackDataPtr, - ConstantsHelper.CALLBACK_ERROR_NONE, - ConstantsHelper.CALLBACK_ERROR_MESSAGE_NONE); - - // With this set, there should be no further callbacks made to the - // C++ side. This is synchronized to ensure that all callbacks - // currently running are completed before this method returns. - synchronized (mRewardedVideoLock) { - mDisconnected = true; - } - } - }); + mActivity.runOnUiThread(new Runnable() { + @Override + public void run() { + RewardedVideoAd ad = MobileAds.getRewardedVideoAdInstance(mActivity); + ad.destroy(mActivity); + completeRewardedVideoFutureCallback(callbackDataPtr, ConstantsHelper.CALLBACK_ERROR_NONE, + ConstantsHelper.CALLBACK_ERROR_MESSAGE_NONE); + + // With this set, there should be no further callbacks made to the + // C++ side. This is synchronized to ensure that all callbacks + // currently running are completed before this method returns. + synchronized (mRewardedVideoLock) { + mDisconnected = true; + } + } + }); } /** @@ -252,18 +242,15 @@ public void run() { * call. */ public void pause(final long callbackDataPtr) { - mActivity.runOnUiThread( - new Runnable() { - @Override - public void run() { - RewardedVideoAd ad = MobileAds.getRewardedVideoAdInstance(mActivity); - ad.pause(mActivity); - completeRewardedVideoFutureCallback( - callbackDataPtr, - ConstantsHelper.CALLBACK_ERROR_NONE, - ConstantsHelper.CALLBACK_ERROR_MESSAGE_NONE); - } - }); + mActivity.runOnUiThread(new Runnable() { + @Override + public void run() { + RewardedVideoAd ad = MobileAds.getRewardedVideoAdInstance(mActivity); + ad.pause(mActivity); + completeRewardedVideoFutureCallback(callbackDataPtr, ConstantsHelper.CALLBACK_ERROR_NONE, + ConstantsHelper.CALLBACK_ERROR_MESSAGE_NONE); + } + }); } /** @@ -274,18 +261,15 @@ public void run() { * call. */ public void resume(final long callbackDataPtr) { - mActivity.runOnUiThread( - new Runnable() { - @Override - public void run() { - RewardedVideoAd ad = MobileAds.getRewardedVideoAdInstance(mActivity); - ad.resume(mActivity); - completeRewardedVideoFutureCallback( - callbackDataPtr, - ConstantsHelper.CALLBACK_ERROR_NONE, - ConstantsHelper.CALLBACK_ERROR_MESSAGE_NONE); - } - }); + mActivity.runOnUiThread(new Runnable() { + @Override + public void run() { + RewardedVideoAd ad = MobileAds.getRewardedVideoAdInstance(mActivity); + ad.resume(mActivity); + completeRewardedVideoFutureCallback(callbackDataPtr, ConstantsHelper.CALLBACK_ERROR_NONE, + ConstantsHelper.CALLBACK_ERROR_MESSAGE_NONE); + } + }); } /** Retrieves the presentation state of this RewardedVideoHelper. */ @@ -350,10 +334,8 @@ public void onRewardedVideoAdLeftApplication() { @Override public void onRewardedVideoAdLoaded() { synchronized (mRewardedVideoLock) { - completeRewardedVideoFutureCallback( - mLoadAdCallbackDataPtr, - ConstantsHelper.CALLBACK_ERROR_NONE, - ConstantsHelper.CALLBACK_ERROR_MESSAGE_NONE); + completeRewardedVideoFutureCallback(mLoadAdCallbackDataPtr, + ConstantsHelper.CALLBACK_ERROR_NONE, ConstantsHelper.CALLBACK_ERROR_MESSAGE_NONE); mLoadAdCallbackDataPtr = CPP_NULLPTR; } } diff --git a/admob/tools/ios/testapp/testapp/ViewController.mm b/admob/tools/ios/testapp/testapp/ViewController.mm index fe9446ac0b..f2cf791b66 100644 --- a/admob/tools/ios/testapp/testapp/ViewController.mm +++ b/admob/tools/ios/testapp/testapp/ViewController.mm @@ -52,7 +52,7 @@ - (void)setUpGL { // Set up the UITapGestureRecognizer for the GLKView. UITapGestureRecognizer *tapRecognizer = - [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)]; + [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)]; tapRecognizer.numberOfTapsRequired = 1; [self.view addGestureRecognizer:tapRecognizer]; } @@ -123,7 +123,7 @@ - (void)handleTap:(UITapGestureRecognizer *)recognizer { #pragma mark - Log Message // Log a message that can be viewed in the console. -int LogMessage(const char* format, ...) { +int LogMessage(const char *format, ...) { va_list list; int rc = 0; va_start(list, format); diff --git a/analytics/src/analytics_ios.mm b/analytics/src/analytics_ios.mm index fac7514acc..dd36d1987f 100644 --- a/analytics/src/analytics_ios.mm +++ b/analytics/src/analytics_ios.mm @@ -21,12 +21,12 @@ #include "analytics/src/include/firebase/analytics.h" #include "analytics/src/analytics_common.h" -#include "app/src/include/firebase/version.h" #include "app/src/assert.h" +#include "app/src/include/firebase/version.h" #include "app/src/log.h" #include "app/src/mutex.h" -#include "app/src/time.h" #include "app/src/thread.h" +#include "app/src/time.h" #include "app/src/util.h" #include "app/src/util_ios.h" @@ -41,6 +41,7 @@ kResetStateRequested, kResetStateRetry, }; + public: // Initialize the class. AnalyticsDataResetter() : reset_state_(kResetStateNone), reset_timestamp_(0) {} @@ -114,7 +115,7 @@ uint64_t GetResetTimeElapsedMilliseconds() const { static const double kMillisecondsPerSecond = 1000.0; static Mutex g_mutex; // NOLINT static bool g_initialized = false; -static AnalyticsDataResetter *g_resetter = nullptr; +static AnalyticsDataResetter* g_resetter = nullptr; // Initialize the API. void Initialize(const ::firebase::App& app) { @@ -213,10 +214,9 @@ void LogEvent(const char* name, const Parameter* parameters, size_t number_of_pa [parameters_dict setObject:[NSNumber numberWithLongLong:0] forKey:parameter_name]; } else { // Vector or Map were passed in. - LogError( - "LogEvent(%s): %s is not a valid parameter value type. " - "Container types are not allowed. No event was logged.", - parameter.name, Variant::TypeName(parameter.value.type())); + LogError("LogEvent(%s): %s is not a valid parameter value type. " + "Container types are not allowed. No event was logged.", + parameter.name, Variant::TypeName(parameter.value.type())); } } [FIRAnalytics logEventWithName:@(name) parameters:parameters_dict]; @@ -253,25 +253,26 @@ void ResetAnalyticsData() { MutexLock lock(g_mutex); FIREBASE_ASSERT_RETURN(Future(), internal::IsInitialized()); auto* api = internal::FutureData::Get()->api(); - const auto future_handle = api->SafeAlloc( - internal::kAnalyticsFnGetAnalyticsInstanceId); + const auto future_handle = + api->SafeAlloc(internal::kAnalyticsFnGetAnalyticsInstanceId); static int kPollTimeMs = 100; - Thread get_id_thread([](SafeFutureHandle* handle) { - for ( ; ; ) { - { - MutexLock lock(g_mutex); - if (!internal::IsInitialized()) break; - std::string instance_id = g_resetter->GetInstanceId(); - if (!instance_id.empty()) { - internal::FutureData::Get()->api()->CompleteWithResult( - *handle, 0, "", instance_id); - break; + Thread get_id_thread( + [](SafeFutureHandle* handle) { + for (;;) { + { + MutexLock lock(g_mutex); + if (!internal::IsInitialized()) break; + std::string instance_id = g_resetter->GetInstanceId(); + if (!instance_id.empty()) { + internal::FutureData::Get()->api()->CompleteWithResult(*handle, 0, "", instance_id); + break; + } } + firebase::internal::Sleep(kPollTimeMs); } - firebase::internal::Sleep(kPollTimeMs); - } - delete handle; - }, new SafeFutureHandle(future_handle)); + delete handle; + }, + new SafeFutureHandle(future_handle)); get_id_thread.Detach(); return Future(api, future_handle.get()); } @@ -280,8 +281,7 @@ Thread get_id_thread([](SafeFutureHandle* handle) { MutexLock lock(g_mutex); FIREBASE_ASSERT_RETURN(Future(), internal::IsInitialized()); return static_cast&>( - internal::FutureData::Get()->api()->LastResult( - internal::kAnalyticsFnGetAnalyticsInstanceId)); + internal::FutureData::Get()->api()->LastResult(internal::kAnalyticsFnGetAnalyticsInstanceId)); } } // namespace measurement diff --git a/analytics/src_java/fake/com/google/firebase/analytics/FirebaseAnalytics.java b/analytics/src_java/fake/com/google/firebase/analytics/FirebaseAnalytics.java index 5e212db71e..8be63c473d 100644 --- a/analytics/src_java/fake/com/google/firebase/analytics/FirebaseAnalytics.java +++ b/analytics/src_java/fake/com/google/firebase/analytics/FirebaseAnalytics.java @@ -22,14 +22,12 @@ import com.google.android.gms.tasks.Task; import com.google.firebase.testing.cppsdk.FakeReporter; import com.google.firebase.testing.cppsdk.TickerAndroid; - import java.util.TreeSet; /** * Fake for FirebaseAnalytics. */ public final class FirebaseAnalytics { - public static FirebaseAnalytics getInstance(Context context) { FakeReporter.addReport("FirebaseAnalytics.getInstance"); return new FirebaseAnalytics(); @@ -43,8 +41,8 @@ public Task getAppInstanceId() { } public void setAnalyticsCollectionEnabled(boolean enabled) { - FakeReporter.addReport("FirebaseAnalytics.setAnalyticsCollectionEnabled", - Boolean.toString(enabled)); + FakeReporter.addReport( + "FirebaseAnalytics.setAnalyticsCollectionEnabled", Boolean.toString(enabled)); } public void logEvent(String name, Bundle params) { @@ -73,13 +71,12 @@ public void setUserId(String userId) { } public void setMinimumSessionDuration(long milliseconds) { - FakeReporter.addReport("FirebaseAnalytics.setMinimumSessionDuration", - Long.toString(milliseconds)); + FakeReporter.addReport( + "FirebaseAnalytics.setMinimumSessionDuration", Long.toString(milliseconds)); } public void setSessionTimeoutDuration(long milliseconds) { - FakeReporter.addReport("FirebaseAnalytics.setSessionTimeoutDuration", - Long.toString(milliseconds)); + FakeReporter.addReport( + "FirebaseAnalytics.setSessionTimeoutDuration", Long.toString(milliseconds)); } - } diff --git a/app/src/app_ios.mm b/app/src/app_ios.mm index 11e50d4332..e2c649482d 100644 --- a/app/src/app_ios.mm +++ b/app/src/app_ios.mm @@ -19,10 +19,10 @@ #include #include -#include "app/src/include/firebase/version.h" #include "app/src/app_common.h" #include "app/src/app_ios.h" #include "app/src/assert.h" +#include "app/src/include/firebase/version.h" #include "app/src/log.h" #include "app/src/mutex.h" #include "app/src/util.h" @@ -37,11 +37,10 @@ @interface FIRApp () + (BOOL)isDefaultAppConfigured; // Internal method (should be part of the public API *soon*) that allows registration of a library // at the specified version which is added to the firebaseUserAgent string. -+ (void)registerLibrary:(NSString *)library - withVersion:(NSString *)version; ++ (void)registerLibrary:(NSString*)library withVersion:(NSString*)version; // Use the private method firebaseUserAgent to get propagate the set of register libraries into // the C++ SDK. -+ (NSString *)firebaseUserAgent; ++ (NSString*)firebaseUserAgent; @end namespace firebase { @@ -51,8 +50,7 @@ + (NSString *)firebaseUserAgent; namespace { // Copy values of FIROptions into AppOptions. -static void PlatformOptionsToAppOptions(FIROptions* platform_options, - AppOptions* app_options) { +static void PlatformOptionsToAppOptions(FIROptions* platform_options, AppOptions* app_options) { if (!strlen(app_options->app_id())) { const char* value = platform_options.googleAppID.UTF8String; if (value) app_options->set_app_id(value); @@ -93,8 +91,7 @@ static void PlatformOptionsToAppOptions(FIROptions* platform_options, // Copy AppOptions into a FIROptions instance. static FIROptions* AppOptionsToPlatformOptions(const AppOptions& app_options) { - FIROptions* platform_options = [[FIROptions alloc] initWithGoogleAppID:@"" - GCMSenderID:@""]; + FIROptions* platform_options = [[FIROptions alloc] initWithGoogleAppID:@"" GCMSenderID:@""]; if (strlen(app_options.app_id())) { platform_options.googleAppID = @(app_options.app_id()); } @@ -130,8 +127,8 @@ static void PlatformOptionsToAppOptions(FIROptions* platform_options, // Silence iOS SDKs warnings about FIRApp instances being missing. LogLevel log_level = GetLogLevel(); SetLogLevel(kLogLevelAssert); - FIRApp *platform_app = app_common::IsDefaultAppName(name) ? - [FIRApp defaultApp] : [FIRApp appNamed:@(name)]; + FIRApp* platform_app = + app_common::IsDefaultAppName(name) ? [FIRApp defaultApp] : [FIRApp appNamed:@(name)]; SetLogLevel(log_level); return platform_app; } @@ -175,8 +172,7 @@ static void PlatformOptionsToAppOptions(FIROptions* platform_options, } // Create or get a iOS SDK FIRApp instance. -static FIRApp* CreateOrGetPlatformApp(const AppOptions& options, - const char* name) { +static FIRApp* CreateOrGetPlatformApp(const AppOptions& options, const char* name) { FIRApp* platform_app = GetPlatformAppByName(name); if (platform_app) { // If a FIRApp exists, make sure it has the requested options. @@ -185,17 +181,19 @@ static void PlatformOptionsToAppOptions(FIROptions* platform_options, if (options != existing_options) { LogWarning("Existing instance of App %s found and options do not match " "the requested options. Deleting %s to attempt recreation " - "with requested options.", name, name); + "with requested options.", + name, name); dispatch_semaphore_t block_semaphore = dispatch_semaphore_create(0); [platform_app deleteApp:^(BOOL /*success*/) { - // NOTE: The delete will always succeed if the app previously existed. - dispatch_semaphore_signal(block_semaphore); - }]; + // NOTE: The delete will always succeed if the app previously existed. + dispatch_semaphore_signal(block_semaphore); + }]; dispatch_semaphore_wait(block_semaphore, DISPATCH_TIME_FOREVER); platform_app = nil; } } - return platform_app ? platform_app : CreatePlatformApp(options, name);; + return platform_app ? platform_app : CreatePlatformApp(options, name); + ; } } // namespace @@ -215,7 +213,8 @@ static void PlatformOptionsToAppOptions(FIROptions* platform_options, } else { LogError("Failed to read Firebase options from the app's resources (%s). " "Either make sure GoogleService-Info.plist is included in your build or specify " - "options explicitly.", util::NSStringToString(error_message).c_str()); + "options explicitly.", + util::NSStringToString(error_message).c_str()); } return app_options; } @@ -263,11 +262,9 @@ static void PlatformOptionsToAppOptions(FIROptions* platform_options, util::NSStringToString([FIRApp firebaseUserAgent]).c_str()); } -const char* App::GetUserAgent() { - return app_common::GetUserAgent(); -} +const char* App::GetUserAgent() { return app_common::GetUserAgent(); } -void App::SetDefaultConfigPath(const char* path) { } +void App::SetDefaultConfigPath(const char* path) {} void App::SetDataCollectionDefaultEnabled(bool enabled) { GetPlatformApp().dataCollectionDefaultEnabled = (enabled ? YES : NO); @@ -277,8 +274,6 @@ static void PlatformOptionsToAppOptions(FIROptions* platform_options, return GetPlatformApp().isDataCollectionDefaultEnabled ? true : false; } -FIRApp* App::GetPlatformApp() const { - return internal_->get(); -} +FIRApp* App::GetPlatformApp() const { return internal_->get(); } } // namespace firebase diff --git a/app/src/callback.h b/app/src/callback.h index 2f4f555f2d..3666e9f9e3 100644 --- a/app/src/callback.h +++ b/app/src/callback.h @@ -24,7 +24,6 @@ #include #endif - /// @cond FIREBASE_APP_INTERNAL /// This file is intended for use with the C# interfaces, to allow registration diff --git a/app/src/filesystem_apple.mm b/app/src/filesystem_apple.mm index 71082d102a..5e1727aff6 100644 --- a/app/src/filesystem_apple.mm +++ b/app/src/filesystem_apple.mm @@ -53,11 +53,11 @@ bool Mkdir(const std::string& path, std::string* out_error) { } #if TARGET_OS_IOS || TARGET_OS_OSX - NSArray* directories = NSSearchPathForDirectoriesInDomains( - NSApplicationSupportDirectory, NSUserDomainMask, YES); + NSArray* directories = + NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES); #elif TARGET_OS_TV - NSArray* directories = NSSearchPathForDirectoriesInDomains( - NSCachesDirectory, NSUserDomainMask, YES); + NSArray* directories = + NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); #else #error "Don't know where to store documents on this platform." #endif diff --git a/app/src/include/firebase/app.h b/app/src/include/firebase/app.h index 29c502e2f2..1758703391 100644 --- a/app/src/include/firebase/app.h +++ b/app/src/include/firebase/app.h @@ -51,8 +51,8 @@ class AppInternal; } // namespace internal #if FIREBASE_PLATFORM_ANDROID && defined(__GLIBCXX__) -#warning "Firebase support for gnustl is deprecated and will be removed in \ - the next major release. Please use libc++ instead." +#warning \ + "Firebase support for gnustl is deprecated and will be removed in the next major release. Please use libc++ instead." #endif /// @brief Reports whether a Firebase module initialized successfully. @@ -720,24 +720,25 @@ class App { /// @return Reference to the FIRApp object owned by this app. FIRApp* GetPlatformApp() const; #endif // __OBJC__ -#endif // FIREBASE_PLATFORM_ANDROID, FIREBASE_PLATFORM_IOS, FIREBASE_PLATFORM_TVOS +#endif // FIREBASE_PLATFORM_ANDROID, FIREBASE_PLATFORM_IOS, + // FIREBASE_PLATFORM_TVOS #endif // INTERNAL_EXPERIMENTAL private: /// Construct the object. - App() : + App() + : #if FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) - activity_(nullptr), + activity_(nullptr), #endif - internal_(nullptr) { + internal_(nullptr) { Initialize(); #ifdef FIREBASE_LINUX_BUILD_CONFIG_STRING - CheckCompilerString(FIREBASE_LINUX_BUILD_CONFIG_STRING); + CheckCompilerString(FIREBASE_LINUX_BUILD_CONFIG_STRING); #endif // FIREBASE_LINUX_BUILD_CONFIG_STRING } - /// Initialize internal implementation void Initialize(); diff --git a/app/src/include/firebase/internal/future_impl.h b/app/src/include/firebase/internal/future_impl.h index dd95defc03..86bad3e8d2 100644 --- a/app/src/include/firebase/internal/future_impl.h +++ b/app/src/include/firebase/internal/future_impl.h @@ -27,7 +27,6 @@ #include #endif // defined(FIREBASE_USE_MOVE_OPERATORS) - namespace firebase { class ReferenceCountedFutureImpl; diff --git a/app/src/log_ios.mm b/app/src/log_ios.mm index 0c31d549ad..ddeef37b6e 100644 --- a/app/src/log_ios.mm +++ b/app/src/log_ios.mm @@ -31,14 +31,14 @@ // Maps C++ to iOS SDK log levels. static const FIRLoggerLevel kCppToIOSLogLevel[] = { - FIRLoggerLevelDebug, // kLogLevelVerbose = 0, - // Mapping C++ debug to Obj-C info is intentional. - // Info messages are intended to be shown only for debugging scenarios. - FIRLoggerLevelInfo, // kLogLevelDebug, - FIRLoggerLevelNotice, // kLogLevelInfo, - FIRLoggerLevelWarning, // kLogLevelWarning, - FIRLoggerLevelError, // kLogLevelError, - FIRLoggerLevelError, // kLogLevelAssert, + FIRLoggerLevelDebug, // kLogLevelVerbose = 0, + // Mapping C++ debug to Obj-C info is intentional. + // Info messages are intended to be shown only for debugging scenarios. + FIRLoggerLevelInfo, // kLogLevelDebug, + FIRLoggerLevelNotice, // kLogLevelInfo, + FIRLoggerLevelWarning, // kLogLevelWarning, + FIRLoggerLevelError, // kLogLevelError, + FIRLoggerLevelError, // kLogLevelAssert, }; // Initialize the logging system. @@ -46,8 +46,8 @@ void LogInitialize() { static bool read_log_level_from_plist = false; if (read_log_level_from_plist) return; read_log_level_from_plist = true; - NSNumber* log_level_number = (NSNumber*)( - [[NSBundle mainBundle] objectForInfoDictionaryKey:kLogLevelInfoPlistKey]); + NSNumber* log_level_number = + (NSNumber*)([[NSBundle mainBundle] objectForInfoDictionaryKey:kLogLevelInfoPlistKey]); if (log_level_number) { int log_level_value = log_level_number.intValue; if (log_level_value >= kLogLevelVerbose && log_level_value <= kLogLevelAssert) { diff --git a/app/src/reference_counted_future_impl.h b/app/src/reference_counted_future_impl.h index 0517f6c084..6e4e06043f 100644 --- a/app/src/reference_counted_future_impl.h +++ b/app/src/reference_counted_future_impl.h @@ -22,12 +22,10 @@ #include #include "app/src/cleanup_notifier.h" +#include "app/src/include/firebase/future.h" #include "app/src/include/firebase/internal/common.h" #include "app/src/mutex.h" - -#include "app/src/include/firebase/future.h" - namespace firebase { // FutureBackingData holds the important data for each Future. These are held by diff --git a/app/src/secure/user_secure_darwin_internal.mm b/app/src/secure/user_secure_darwin_internal.mm index 873047addb..c5fe84ed5d 100644 --- a/app/src/secure/user_secure_darwin_internal.mm +++ b/app/src/secure/user_secure_darwin_internal.mm @@ -172,9 +172,7 @@ DeleteData(app_name.c_str(), "DeleteUserData"); } -void UserSecureDarwinInternal::DeleteAllData() { - DeleteData(nullptr, "DeleteAllData"); -} +void UserSecureDarwinInternal::DeleteAllData() { DeleteData(nullptr, "DeleteAllData"); } } // namespace secure } // namespace app diff --git a/app/src/util_ios.h b/app/src/util_ios.h index 00d8161934..f87c4310ed 100644 --- a/app/src/util_ios.h +++ b/app/src/util_ios.h @@ -119,7 +119,7 @@ class ObjCPointer { public: \ class_name() {} \ explicit class_name( \ - const firebase::util::ObjCPointer& obj) \ + const firebase::util::ObjCPointer &obj) \ : firebase::util::ObjCPointer(obj) {} \ explicit class_name(objc_type_name *_Nullable objc_object) \ : firebase::util::ObjCPointer(objc_object) {} \ diff --git a/app/src/uuid_ios_darwin.mm b/app/src/uuid_ios_darwin.mm index 52d3475693..5c3ecf12df 100644 --- a/app/src/uuid_ios_darwin.mm +++ b/app/src/uuid_ios_darwin.mm @@ -28,4 +28,3 @@ } // namespace internal } // namespace firebase - diff --git a/app/src_java/com/google/firebase/app/internal/cpp/GoogleApiAvailabilityHelper.java b/app/src_java/com/google/firebase/app/internal/cpp/GoogleApiAvailabilityHelper.java index 9db5f66b57..b5b13e533b 100644 --- a/app/src_java/com/google/firebase/app/internal/cpp/GoogleApiAvailabilityHelper.java +++ b/app/src_java/com/google/firebase/app/internal/cpp/GoogleApiAvailabilityHelper.java @@ -16,7 +16,6 @@ package com.google.firebase.app.internal.cpp; - import android.app.Activity; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GoogleApiAvailability; @@ -79,29 +78,25 @@ public static boolean makeGooglePlayServicesAvailable(Activity activity) { if (task == null) { return false; } - task.addOnSuccessListener( - new OnSuccessListener() { - @Override - public void onSuccess(Void result) { - GoogleApiAvailabilityHelper.onComplete(SUCCESS, "Success"); - } - }); - task.addOnFailureListener( - new OnFailureListener() { - @Override - public void onFailure(Exception exception) { - GoogleApiAvailabilityHelper.onComplete( - FAILURE_COULD_NOT_UPDATE, - "Couldn't make Google Play services available: " + exception.getMessage()); - } - }); - task.addOnCanceledListener( - new OnCanceledListener() { - @Override - public void onCanceled() { - GoogleApiAvailabilityHelper.onComplete(FAILURE_CANCELED, "User canceled the update"); - } - }); + task.addOnSuccessListener(new OnSuccessListener() { + @Override + public void onSuccess(Void result) { + GoogleApiAvailabilityHelper.onComplete(SUCCESS, "Success"); + } + }); + task.addOnFailureListener(new OnFailureListener() { + @Override + public void onFailure(Exception exception) { + GoogleApiAvailabilityHelper.onComplete(FAILURE_COULD_NOT_UPDATE, + "Couldn't make Google Play services available: " + exception.getMessage()); + } + }); + task.addOnCanceledListener(new OnCanceledListener() { + @Override + public void onCanceled() { + GoogleApiAvailabilityHelper.onComplete(FAILURE_CANCELED, "User canceled the update"); + } + }); return true; } } diff --git a/app/src_java/com/google/firebase/app/internal/cpp/JniResultCallback.java b/app/src_java/com/google/firebase/app/internal/cpp/JniResultCallback.java index f3b2a79a0d..954957e50d 100644 --- a/app/src_java/com/google/firebase/app/internal/cpp/JniResultCallback.java +++ b/app/src_java/com/google/firebase/app/internal/cpp/JniResultCallback.java @@ -156,11 +156,6 @@ public void onCompletion( } /** This function is implemented in the App C++ library (util_android.cc). */ - private native void nativeOnResult( - Object result, - boolean success, - boolean cancelled, - String statusString, - long callbackFn, - long callbackData); + private native void nativeOnResult(Object result, boolean success, boolean cancelled, + String statusString, long callbackFn, long callbackData); } diff --git a/app/src_java/com/google/firebase/app/internal/cpp/Log.java b/app/src_java/com/google/firebase/app/internal/cpp/Log.java index 3aed09bdd6..d2b80d3219 100644 --- a/app/src_java/com/google/firebase/app/internal/cpp/Log.java +++ b/app/src_java/com/google/firebase/app/internal/cpp/Log.java @@ -75,7 +75,6 @@ public static int e(String tag, String msg) { * See android.util.Log.wtf(). */ public static int wtf(String tag, String msg) { - safeNativeLog(android.util.Log.ERROR, tag, msg); return 0; } @@ -125,9 +124,9 @@ private void safeNativeLogInternal(int level, String tag, String msg) { nativeLog(level, tag, msg); } catch (UnsatisfiedLinkError e) { nativeLogAvailable = false; - android.util.Log.w( - TAG, String.format("nativeLog not registered, falling back to android.util.Log (%s)", - e.toString())); + android.util.Log.w(TAG, + String.format( + "nativeLog not registered, falling back to android.util.Log (%s)", e.toString())); } } if (!nativeLogAvailable) { diff --git a/app/src_java/com/google/firebase/dynamiclinks/internal/cpp/DynamicLinksNativeWrapper.java b/app/src_java/com/google/firebase/dynamiclinks/internal/cpp/DynamicLinksNativeWrapper.java index fd07cffa95..e774ac6672 100644 --- a/app/src_java/com/google/firebase/dynamiclinks/internal/cpp/DynamicLinksNativeWrapper.java +++ b/app/src_java/com/google/firebase/dynamiclinks/internal/cpp/DynamicLinksNativeWrapper.java @@ -42,11 +42,10 @@ public class DynamicLinksNativeWrapper { // Message that describes the failure to find a native method and a potential resolution. private static final String NATIVE_METHOD_MISSING_MESSAGE = "Native method not found, unable to send %s message to the application. " - + "Make sure Firebase was not shut down while a Dynamic Links fetch operation " - + "was in progress. (%s)"; + + "Make sure Firebase was not shut down while a Dynamic Links fetch operation " + + "was in progress. (%s)"; public DynamicLinksNativeWrapper(long nativePtr, Activity incomingActivity) { - nativeInternalPtr = nativePtr; // Call our JNI function (passing in 0 as the nativeInternalPtr) so we can verify that // they are all hooked up properly. @@ -69,40 +68,36 @@ public void discardNativePointer() { // Fetch Dynamic Links - this function is called from JNI to trigger checking for dynamic links. public boolean fetchDynamicLink() { try { - activity.runOnUiThread( - new Runnable() { - @Override - public void run() { - FirebaseDynamicLinks.getInstance() - .getDynamicLink(activity.getIntent()) - .addOnSuccessListener( - activity, - new OnSuccessListener() { - @Override - public void onSuccess(PendingDynamicLinkData pendingDynamicLinkData) { - // Get deep link from result (may be null if no link is found) - Uri deepLink = null; - String deepLinkString = null; - if (pendingDynamicLinkData != null) { - deepLink = pendingDynamicLinkData.getLink(); - if (deepLink != null) { - deepLinkString = deepLink.toString(); - } - } - safeReceivedDynamicLinkCallback(nativeInternalPtr, deepLinkString, 0, ""); - } - }) - .addOnFailureListener( - activity, - new OnFailureListener() { - @Override - public void onFailure(Exception e) { - safeReceivedDynamicLinkCallback( - nativeInternalPtr, "", Activity.RESULT_CANCELED, e.toString()); + activity.runOnUiThread(new Runnable() { + @Override + public void run() { + FirebaseDynamicLinks.getInstance() + .getDynamicLink(activity.getIntent()) + .addOnSuccessListener(activity, + new OnSuccessListener() { + @Override + public void onSuccess(PendingDynamicLinkData pendingDynamicLinkData) { + // Get deep link from result (may be null if no link is found) + Uri deepLink = null; + String deepLinkString = null; + if (pendingDynamicLinkData != null) { + deepLink = pendingDynamicLinkData.getLink(); + if (deepLink != null) { + deepLinkString = deepLink.toString(); } - }); - } - }); + } + safeReceivedDynamicLinkCallback(nativeInternalPtr, deepLinkString, 0, ""); + } + }) + .addOnFailureListener(activity, new OnFailureListener() { + @Override + public void onFailure(Exception e) { + safeReceivedDynamicLinkCallback( + nativeInternalPtr, "", Activity.RESULT_CANCELED, e.toString()); + } + }); + } + }); return true; } catch (Exception e) { // Failed to start fetching invites. The client code will handle this when we return false.. @@ -115,10 +110,8 @@ public static void safeReceivedDynamicLinkCallback( try { receivedDynamicLinkCallback(nativeInternalPtr, deepLinkUrl, resultCode, errorString); } catch (UnsatisfiedLinkError e) { - String missingDetails = - String.format( - "received url=%s (code=%d, message=%s)", - String.valueOf(deepLinkUrl), resultCode, errorString); + String missingDetails = String.format("received url=%s (code=%d, message=%s)", + String.valueOf(deepLinkUrl), resultCode, errorString); Log.e(TAG, String.format(NATIVE_METHOD_MISSING_MESSAGE, missingDetails, e.toString())); } } diff --git a/app/src_java/fake/com/google/android/gms/common/GoogleApiAvailability.java b/app/src_java/fake/com/google/android/gms/common/GoogleApiAvailability.java index 9bdfa3ab52..430afb32a0 100644 --- a/app/src_java/fake/com/google/android/gms/common/GoogleApiAvailability.java +++ b/app/src_java/fake/com/google/android/gms/common/GoogleApiAvailability.java @@ -22,7 +22,6 @@ /** Fake gms/common/GoogleApiAvailability.java for unit testing. */ public final class GoogleApiAvailability { - private static final GoogleApiAvailability INSTANCE = new GoogleApiAvailability(); public static GoogleApiAvailability getInstance() { diff --git a/app/src_java/fake/com/google/firebase/FirebaseException.java b/app/src_java/fake/com/google/firebase/FirebaseException.java index 8d430cd072..0d509df859 100644 --- a/app/src_java/fake/com/google/firebase/FirebaseException.java +++ b/app/src_java/fake/com/google/firebase/FirebaseException.java @@ -18,7 +18,6 @@ /** Fake FirebaseException */ public class FirebaseException extends Exception { - public FirebaseException(String message) { super(message); } diff --git a/app/src_java/fake/com/google/firebase/FirebaseOptions.java b/app/src_java/fake/com/google/firebase/FirebaseOptions.java index 7559eee97f..10c252d4b0 100644 --- a/app/src_java/fake/com/google/firebase/FirebaseOptions.java +++ b/app/src_java/fake/com/google/firebase/FirebaseOptions.java @@ -97,14 +97,13 @@ private FirebaseOptions(Builder builder) { } public static FirebaseOptions fromResource(Context context) { - return new FirebaseOptions( - new Builder() - .setApiKey("fake api key from resource") - .setDatabaseUrl("fake database url from resource") - .setApplicationId("fake app id from resource") - .setGcmSenderId("fake messaging sender id from resource") - .setStorageBucket("fake storage bucket from resource") - .setProjectId("fake project id from resource")); + return new FirebaseOptions(new Builder() + .setApiKey("fake api key from resource") + .setDatabaseUrl("fake database url from resource") + .setApplicationId("fake app id from resource") + .setGcmSenderId("fake messaging sender id from resource") + .setStorageBucket("fake storage bucket from resource") + .setProjectId("fake project id from resource")); } public String getApiKey() { diff --git a/app/src_java/fake/com/google/firebase/app/internal/cpp/CppThreadDispatcher.java b/app/src_java/fake/com/google/firebase/app/internal/cpp/CppThreadDispatcher.java index 9837ef421a..44a07f625c 100644 --- a/app/src_java/fake/com/google/firebase/app/internal/cpp/CppThreadDispatcher.java +++ b/app/src_java/fake/com/google/firebase/app/internal/cpp/CppThreadDispatcher.java @@ -22,17 +22,17 @@ /** Runs a native C++ function on an alternate thread. */ public class CppThreadDispatcher { - private static final ExecutorService executor = Executors.newSingleThreadExecutor( - Executors.defaultThreadFactory()); + private static final ExecutorService executor = + Executors.newSingleThreadExecutor(Executors.defaultThreadFactory()); /** Runs a C++ function on the main thread using the executor. */ public static void runOnMainThread(Activity activity, final CppThreadDispatcherContext context) { Object unused = executor.submit(new Runnable() { - @Override - public void run() { - context.execute(); - } - }); + @Override + public void run() { + context.execute(); + } + }); } /** Runs a C++ function on a new Java background thread. */ diff --git a/app/src_java/fake/com/google/firebase/app/internal/cpp/GoogleApiAvailabilityHelper.java b/app/src_java/fake/com/google/firebase/app/internal/cpp/GoogleApiAvailabilityHelper.java index ee34b2e859..0e491fafcf 100644 --- a/app/src_java/fake/com/google/firebase/app/internal/cpp/GoogleApiAvailabilityHelper.java +++ b/app/src_java/fake/com/google/firebase/app/internal/cpp/GoogleApiAvailabilityHelper.java @@ -33,16 +33,15 @@ public static boolean makeGooglePlayServicesAvailable(Activity activity) { final ConfigRow row = ConfigAndroid.get("GoogleApiAvailabilityHelper.makeGooglePlayServicesAvailable"); if (row != null) { - TickerAndroid.register( - new TickerObserver() { - @Override - public void elapse() { - if (TickerAndroid.now() == row.futureint().ticker()) { - int resultCode = row.futureint().value(); - onCompleteNative(resultCode, "result code is " + resultCode); - } - } - }); + TickerAndroid.register(new TickerObserver() { + @Override + public void elapse() { + if (TickerAndroid.now() == row.futureint().ticker()) { + int resultCode = row.futureint().value(); + onCompleteNative(resultCode, "result code is " + resultCode); + } + } + }); return row.futurebool().value() == FutureBoolResult.True; } diff --git a/app/src_java/fake/com/google/firebase/app/internal/cpp/JniResultCallback.java b/app/src_java/fake/com/google/firebase/app/internal/cpp/JniResultCallback.java index 0be47b678f..dff647cd83 100644 --- a/app/src_java/fake/com/google/firebase/app/internal/cpp/JniResultCallback.java +++ b/app/src_java/fake/com/google/firebase/app/internal/cpp/JniResultCallback.java @@ -27,7 +27,8 @@ private interface Callback { public void register(); public void disconnect(); - }; + } + ; private long callbackFn; private long callbackData; @@ -86,18 +87,12 @@ public void cancel() { private void onCompletion( Object result, boolean success, boolean cancelled, String statusMessage) { if (callbackHandler != null) { - nativeOnResult( - result, success, cancelled, statusMessage, callbackFn, callbackData); + nativeOnResult(result, success, cancelled, statusMessage, callbackFn, callbackData); callbackHandler.disconnect(); callbackHandler = null; } } - private native void nativeOnResult( - Object result, - boolean success, - boolean cancelled, - String statusString, - long callbackFn, - long callbackData); + private native void nativeOnResult(Object result, boolean success, boolean cancelled, + String statusString, long callbackFn, long callbackData); } diff --git a/app/tests/util_ios_test.mm b/app/tests/util_ios_test.mm index b9c231f8bc..9d866e2417 100644 --- a/app/tests/util_ios_test.mm +++ b/app/tests/util_ios_test.mm @@ -34,7 +34,7 @@ - (void)testConstructAndGet { NSStringPointer pointer; XCTAssertEqual(cpp.get(), nil); XCTAssertEqual(handle.get(), nil); - XCTAssertEqual(pointer.get(), nil); + XCTAssertEqual(pointer.get(), nil); } - (void)testConstructWithObjectAndGet { @@ -45,12 +45,12 @@ - (void)testConstructWithObjectAndGet { NSStringHandle from_base_type(cpp); XCTAssertEqual(cpp.get(), nsstring); XCTAssertEqual(handle.get(), nsstring); - XCTAssertEqual(pointer.get(), nsstring); + XCTAssertEqual(pointer.get(), nsstring); XCTAssertEqual(from_base_type.get(), nsstring); } - (void)testRelease { - NSString *nsstring = @"hello"; + NSString* nsstring = @"hello"; NSStringCpp cpp(nsstring); XCTAssertEqual(cpp.get(), nsstring); cpp.release(); @@ -297,14 +297,12 @@ - (void)testVector { { // NSArray containing an NSArray and an NSDictionary to an std::vector // holding an std::vector and std::map - id array = @[ @[ @1, @2, @3 ], @{ @4 : @5, @6 : @7, @8 : @9 } ]; + id array = @[ @[ @1, @2, @3 ], @{@4 : @5, @6 : @7, @8 : @9} ]; std::vector vector_element{1, 2, 3}; - std::map map_element{ - std::make_pair(Variant(4), Variant(5)), - std::make_pair(Variant(6), Variant(7)), - std::make_pair(Variant(8), Variant(9))}; - std::vector expected{Variant(vector_element), - Variant(map_element)}; + std::map map_element{std::make_pair(Variant(4), Variant(5)), + std::make_pair(Variant(6), Variant(7)), + std::make_pair(Variant(8), Variant(9))}; + std::vector expected{Variant(vector_element), Variant(map_element)}; Variant variant = IdToVariant(array); XCTAssertTrue(variant.is_vector()); XCTAssertTrue(variant.vector() == expected); @@ -323,18 +321,10 @@ - (void)testMap { { // Check that a NSDictionary of strings to numbers maps to a std::map of // string variants to number variants. - id dictionary = @{ - @"test1" : @1, - @"test2" : @2, - @"test3" : @3, - @"test4" : @4, - @"test5" : @5 - }; + id dictionary = @{@"test1" : @1, @"test2" : @2, @"test3" : @3, @"test4" : @4, @"test5" : @5}; std::map expected{ - std::make_pair(Variant("test1"), Variant(1)), - std::make_pair(Variant("test2"), Variant(2)), - std::make_pair(Variant("test3"), Variant(3)), - std::make_pair(Variant("test4"), Variant(4)), + std::make_pair(Variant("test1"), Variant(1)), std::make_pair(Variant("test2"), Variant(2)), + std::make_pair(Variant("test3"), Variant(3)), std::make_pair(Variant("test4"), Variant(4)), std::make_pair(Variant("test5"), Variant(5))}; Variant variant = IdToVariant(dictionary); XCTAssertTrue(variant.is_map()); @@ -343,11 +333,10 @@ - (void)testMap { { // Check that a NSDictionary of various types maps to a std::map of variants // holding various types. - id dictionary = @{ @20 : @"Different types", @6.28 : @10, @"Blah" : @3.14 }; - std::map expected{ - std::make_pair(Variant(20), Variant("Different types")), - std::make_pair(Variant(6.28), Variant(10)), - std::make_pair(Variant("Blah"), Variant(3.14))}; + id dictionary = @{@20 : @"Different types", @6.28 : @10, @"Blah" : @3.14}; + std::map expected{std::make_pair(Variant(20), Variant("Different types")), + std::make_pair(Variant(6.28), Variant(10)), + std::make_pair(Variant("Blah"), Variant(3.14))}; Variant variant = IdToVariant(dictionary); XCTAssertTrue(variant.is_map()); XCTAssertTrue(variant.map() == expected); @@ -355,12 +344,11 @@ - (void)testMap { { // Check that a NSDictionary of NSArray-to-NSDictionary maps to an std::map // of vector-to-map - id dictionary = @{ @[ @1, @2, @3 ] : @{@4 : @5, @6 : @7, @8 : @9} }; + id dictionary = @{@[ @1, @2, @3 ] : @{@4 : @5, @6 : @7, @8 : @9}}; std::vector vector_element{1, 2, 3}; - std::map map_element{ - std::make_pair(Variant(4), Variant(5)), - std::make_pair(Variant(6), Variant(7)), - std::make_pair(Variant(8), Variant(9))}; + std::map map_element{std::make_pair(Variant(4), Variant(5)), + std::make_pair(Variant(6), Variant(7)), + std::make_pair(Variant(8), Variant(9))}; std::map expected{ std::make_pair(Variant(vector_element), Variant(map_element))}; Variant variant = IdToVariant(dictionary); @@ -550,8 +538,7 @@ - (void)testVector { } { // std::vector of static and mutable strings to NSArray of NSStrings. - std::vector vector{"This", std::string("is"), "a", - std::string("test.")}; + std::vector vector{"This", std::string("is"), "a", std::string("test.")}; id expected = @[ @"This", @"is", @"a", @"test." ]; Variant variant(vector); id array = VariantToId(variant); @@ -571,12 +558,11 @@ - (void)testVector { // std::vector containing a vector and map to an NSArray containing an // NSArray and an NSDictionary. std::vector vector_element{1, 2, 3}; - std::map map_element{ - std::make_pair(Variant(4), Variant(5)), - std::make_pair(Variant(6), Variant(7)), - std::make_pair(Variant(8), Variant(9))}; + std::map map_element{std::make_pair(Variant(4), Variant(5)), + std::make_pair(Variant(6), Variant(7)), + std::make_pair(Variant(8), Variant(9))}; std::vector vector{Variant(vector_element), Variant(map_element)}; - id expected = @[ @[ @1, @2, @3 ], @{ @4 : @5, @6 : @7, @8 : @9 } ]; + id expected = @[ @[ @1, @2, @3 ], @{@4 : @5, @6 : @7, @8 : @9} ]; Variant variant(vector); id array = VariantToId(variant); XCTAssertTrue([array isKindOfClass:[NSArray class]]); @@ -599,18 +585,10 @@ - (void)testMap { // Check that an std::map of strings to numbers maps to an NSDictionary of // NSString to NSNumbers. std::map map{ - std::make_pair(Variant("test1"), Variant(1)), - std::make_pair(Variant("test2"), Variant(2)), - std::make_pair(Variant("test3"), Variant(3)), - std::make_pair(Variant("test4"), Variant(4)), + std::make_pair(Variant("test1"), Variant(1)), std::make_pair(Variant("test2"), Variant(2)), + std::make_pair(Variant("test3"), Variant(3)), std::make_pair(Variant("test4"), Variant(4)), std::make_pair(Variant("test5"), Variant(5))}; - id expected = @{ - @"test1" : @1, - @"test2" : @2, - @"test3" : @3, - @"test4" : @4, - @"test5" : @5 - }; + id expected = @{@"test1" : @1, @"test2" : @2, @"test3" : @3, @"test4" : @4, @"test5" : @5}; Variant variant(map); id dictionary = VariantToId(variant); XCTAssertTrue([dictionary isKindOfClass:[NSDictionary class]]); @@ -621,9 +599,8 @@ - (void)testMap { // various types. std::map map{ std::make_pair(Variant(20), Variant(std::string("Different types"))), - std::make_pair(Variant(6.28), Variant(10)), - std::make_pair(Variant("Blah"), Variant(3.14))}; - id expected = @{ @20 : @"Different types", @6.28 : @10, @"Blah" : @3.14 }; + std::make_pair(Variant(6.28), Variant(10)), std::make_pair(Variant("Blah"), Variant(3.14))}; + id expected = @{@20 : @"Different types", @6.28 : @10, @"Blah" : @3.14}; Variant variant(map); id dictionary = VariantToId(variant); XCTAssertTrue([dictionary isKindOfClass:[NSDictionary class]]); @@ -633,13 +610,11 @@ - (void)testMap { // Check that an std::map of vector-to-map maps to a NSDictionary of // NSArray-to-NSDictionary std::vector vector_element{1, 2, 3}; - std::map map_element{ - std::make_pair(Variant(4), Variant(5)), - std::make_pair(Variant(6), Variant(7)), - std::make_pair(Variant(8), Variant(9))}; - std::map map{ - std::make_pair(Variant(vector_element), Variant(map_element))}; - id expected = @{ @[ @1, @2, @3 ] : @{@4 : @5, @6 : @7, @8 : @9} }; + std::map map_element{std::make_pair(Variant(4), Variant(5)), + std::make_pair(Variant(6), Variant(7)), + std::make_pair(Variant(8), Variant(9))}; + std::map map{std::make_pair(Variant(vector_element), Variant(map_element))}; + id expected = @{@[ @1, @2, @3 ] : @{@4 : @5, @6 : @7, @8 : @9}}; Variant variant(map); id dictionary = VariantToId(variant); XCTAssertTrue([dictionary isKindOfClass:[NSDictionary class]]); diff --git a/auth/src/desktop/user_view.h b/auth/src/desktop/user_view.h index 2c3b2305bc..20f28d685c 100644 --- a/auth/src/desktop/user_view.h +++ b/auth/src/desktop/user_view.h @@ -17,6 +17,7 @@ #include #include + #include "app/src/assert.h" #include "app/src/mutex.h" #include "auth/src/common.h" diff --git a/auth/src/include/firebase/auth.h b/auth/src/include/firebase/auth.h index e307dd0e01..77d46da3cd 100644 --- a/auth/src/include/firebase/auth.h +++ b/auth/src/include/firebase/auth.h @@ -20,9 +20,9 @@ #include #include "firebase/app.h" +#include "firebase/auth/user.h" #include "firebase/future.h" #include "firebase/internal/common.h" -#include "firebase/auth/user.h" #if !defined(DOXYGEN) #ifndef SWIG diff --git a/auth/src/include/firebase/auth/user.h b/auth/src/include/firebase/auth/user.h index 8460ebedd6..32e92de5e8 100644 --- a/auth/src/include/firebase/auth/user.h +++ b/auth/src/include/firebase/auth/user.h @@ -20,11 +20,11 @@ #include #include +#include "firebase/auth/credential.h" +#include "firebase/auth/types.h" #include "firebase/future.h" #include "firebase/internal/common.h" #include "firebase/variant.h" -#include "firebase/auth/credential.h" -#include "firebase/auth/types.h" namespace firebase { namespace auth { diff --git a/auth/src/ios/auth_ios.mm b/auth/src/ios/auth_ios.mm index 17b8236829..b641245e05 100644 --- a/auth/src/ios/auth_ios.mm +++ b/auth/src/ios/auth_ios.mm @@ -17,8 +17,8 @@ #import "FIRAdditionalUserInfo.h" #import "FIRAuthDataResult.h" #import "FIRAuthErrors.h" -#import "FIROptions.h" #import "FIROAuthCredential.h" +#import "FIROptions.h" #include "app/src/app_ios.h" #include "app/src/assert.h" @@ -126,12 +126,10 @@ @implementation FIRCPPAuthListenerHandle public: // Construct a Credential given a preexisting FIRAuthCredential wrapped by a // FIRAuthCredentialPointer. - static Credential GetCredential(FIRAuthCredentialPointer* impl) { - return Credential(impl); - } + static Credential GetCredential(FIRAuthCredentialPointer *impl) { return Credential(impl); } }; -template +template struct ListenerHandleHolder { explicit ListenerHandleHolder(T handle) : handle(handle) {} T handle; @@ -150,7 +148,7 @@ explicit ListenerHandleHolder(T handle) : handle(handle) {} } // Grab the user value from the iOS API and remember it locally. -void UpdateCurrentUser(AuthData* auth_data) { +void UpdateCurrentUser(AuthData *auth_data) { MutexLock lock(auth_data->future_impl.mutex()); FIRUser *user = [AuthImpl(auth_data) currentUser]; SetUserImpl(auth_data, user); @@ -158,36 +156,31 @@ void UpdateCurrentUser(AuthData* auth_data) { // Platform-specific method to initialize AuthData. void Auth::InitPlatformAuth(AuthData *auth_data) { - FIRCPPAuthListenerHandle* listener_cpp_handle = - [[FIRCPPAuthListenerHandle alloc] init]; + FIRCPPAuthListenerHandle *listener_cpp_handle = [[FIRCPPAuthListenerHandle alloc] init]; listener_cpp_handle.authData = auth_data; - reinterpret_cast(auth_data->auth_impl)->listener_handle = listener_cpp_handle; + reinterpret_cast(auth_data->auth_impl)->listener_handle = listener_cpp_handle; // Register a listening block that will notify all the C++ listeners on // auth state change. - FIRAuthStateDidChangeListenerHandle listener_handle = - [AuthImpl(auth_data) - addAuthStateDidChangeListener:^(FIRAuth * _Nonnull __strong, - FIRUser * _Nullable __strong) { - @synchronized (listener_cpp_handle) { - AuthData* data = listener_cpp_handle.authData; - if (data) { - UpdateCurrentUser(data); - NotifyAuthStateListeners(data); - } - } - }]; - FIRIDTokenDidChangeListenerHandle id_token_listener_handle = - [AuthImpl(auth_data) - addIDTokenDidChangeListener:^(FIRAuth * _Nonnull __strong, - FIRUser * _Nullable __strong) { - @synchronized (listener_cpp_handle) { - AuthData* data = listener_cpp_handle.authData; - if (data) { - UpdateCurrentUser(data); - NotifyIdTokenListeners(data); - } - } - }]; + FIRAuthStateDidChangeListenerHandle listener_handle = [AuthImpl(auth_data) + addAuthStateDidChangeListener:^(FIRAuth *_Nonnull __strong, FIRUser *_Nullable __strong) { + @synchronized(listener_cpp_handle) { + AuthData *data = listener_cpp_handle.authData; + if (data) { + UpdateCurrentUser(data); + NotifyAuthStateListeners(data); + } + } + }]; + FIRIDTokenDidChangeListenerHandle id_token_listener_handle = [AuthImpl(auth_data) + addIDTokenDidChangeListener:^(FIRAuth *_Nonnull __strong, FIRUser *_Nullable __strong) { + @synchronized(listener_cpp_handle) { + AuthData *data = listener_cpp_handle.authData; + if (data) { + UpdateCurrentUser(data); + NotifyIdTokenListeners(data); + } + } + }]; auth_data->listener_impl = new ListenerHandleHolder(listener_handle); @@ -203,23 +196,22 @@ void UpdateCurrentUser(AuthData* auth_data) { // Platform-specific method to destroy the wrapped Auth class. void Auth::DestroyPlatformAuth(AuthData *auth_data) { // Remove references from listener blocks. - AuthDataIos* auth_data_ios = reinterpret_cast(auth_data->auth_impl); + AuthDataIos *auth_data_ios = reinterpret_cast(auth_data->auth_impl); FIRCPPAuthListenerHandle *listener_cpp_handle = auth_data_ios->listener_handle.get(); - @synchronized (listener_cpp_handle) { + @synchronized(listener_cpp_handle) { listener_cpp_handle.authData = nullptr; } // Unregister the listeners. - ListenerHandleHolder* handle_holder = - reinterpret_cast< - ListenerHandleHolder*>(auth_data->listener_impl); + ListenerHandleHolder *handle_holder = + reinterpret_cast *>( + auth_data->listener_impl); [AuthImpl(auth_data) removeAuthStateDidChangeListener:handle_holder->handle]; delete handle_holder; auth_data->listener_impl = nullptr; - ListenerHandleHolder* id_token_listener_handle_holder = - reinterpret_cast< - ListenerHandleHolder*>( - auth_data->id_token_listener_impl); + ListenerHandleHolder *id_token_listener_handle_holder = + reinterpret_cast *>( + auth_data->id_token_listener_impl); [AuthImpl(auth_data) removeIDTokenDidChangeListener:id_token_listener_handle_holder->handle]; delete id_token_listener_handle_holder; auth_data->id_token_listener_impl = nullptr; @@ -239,21 +231,21 @@ void UpdateCurrentUser(AuthData* auth_data) { const auto handle = futures.SafeAlloc(kAuthFn_FetchProvidersForEmail, initial_data); - [AuthImpl(auth_data_) - fetchSignInMethodsForEmail:@(email) - completion:^(NSArray *_Nullable providers, - NSError *_Nullable error) { - futures.Complete( - handle, AuthErrorFromNSError(error), - [error.localizedDescription UTF8String], - [providers](FetchProvidersResult* data) { - // Copy data to our result format. - data->providers.resize(providers.count); - for (size_t i = 0; i < providers.count; ++i) { - data->providers[i] = util::StringFromNSString(providers[i]); - } - }); - }]; + [AuthImpl(auth_data_) fetchSignInMethodsForEmail:@(email) + completion:^(NSArray *_Nullable providers, + NSError *_Nullable error) { + futures.Complete( + handle, AuthErrorFromNSError(error), + [error.localizedDescription UTF8String], + [providers](FetchProvidersResult *data) { + // Copy data to our result format. + data->providers.resize(providers.count); + for (size_t i = 0; i < providers.count; ++i) { + data->providers[i] = + util::StringFromNSString(providers[i]); + } + }); + }]; return MakeFuture(&futures, handle); } @@ -272,7 +264,7 @@ void UpdateCurrentUser(AuthData* auth_data) { return user; } -static User* AssignUser(FIRUser *_Nullable user, AuthData *auth_data) { +static User *AssignUser(FIRUser *_Nullable user, AuthData *auth_data) { // Update our pointer to the iOS user that we're wrapping. MutexLock lock(auth_data->future_impl.mutex()); if (user) { @@ -318,14 +310,13 @@ AuthError AuthErrorFromNSError(NSError *_Nullable error) { } void SignInCallback(FIRUser *_Nullable user, NSError *_Nullable error, - SafeFutureHandle handle, AuthData *auth_data) { - User* result = AssignUser(user, auth_data); + SafeFutureHandle handle, AuthData *auth_data) { + User *result = AssignUser(user, auth_data); // Finish off the asynchronous call so that the caller can read it. ReferenceCountedFutureImpl &futures = auth_data->future_impl; futures.CompleteWithResult(handle, AuthErrorFromNSError(error), - util::NSStringToString(error.localizedDescription).c_str(), - result); + util::NSStringToString(error.localizedDescription).c_str(), result); } void SignInResultWithProviderCallback( @@ -340,7 +331,7 @@ void SignInResultWithProviderCallback( void SignInResultCallback(FIRAuthDataResult *_Nullable auth_result, NSError *_Nullable error, SafeFutureHandle handle, AuthData *auth_data) { - User* user = AssignUser(auth_result.user, auth_data); + User *user = AssignUser(auth_result.user, auth_data); SignInResult result; result.user = user; @@ -356,7 +347,7 @@ void SignInResultCallback(FIRAuthDataResult *_Nullable auth_result, NSError *_Nu if (error.userInfo[FIRAuthErrorUserInfoUpdatedCredentialKey] != nullptr) { result.info.updated_credential = ServiceUpdatedCredentialProvider::GetCredential( new FIRAuthCredentialPointer(error.userInfo[FIRAuthErrorUserInfoUpdatedCredentialKey])); - } + } } ReferenceCountedFutureImpl &futures = auth_data->future_impl; @@ -390,22 +381,21 @@ void SignInResultCallback(FIRAuthDataResult *_Nullable auth_result, NSError *_Nu return MakeFuture(&futures, handle); } -Future Auth::SignInAndRetrieveDataWithCredential( - const Credential& credential) { +Future Auth::SignInAndRetrieveDataWithCredential(const Credential &credential) { ReferenceCountedFutureImpl &futures = auth_data_->future_impl; const auto handle = futures.SafeAlloc(kAuthFn_SignInAndRetrieveDataWithCredential, SignInResult()); - [AuthImpl(auth_data_) signInWithCredential:CredentialFromImpl(credential.impl_) - completion:^(FIRAuthDataResult *_Nullable auth_result, - NSError *_Nullable error) { - SignInResultCallback(auth_result, error, handle, auth_data_); - }]; + [AuthImpl(auth_data_) + signInWithCredential:CredentialFromImpl(credential.impl_) + completion:^(FIRAuthDataResult *_Nullable auth_result, NSError *_Nullable error) { + SignInResultCallback(auth_result, error, handle, auth_data_); + }]; return MakeFuture(&futures, handle); } -Future Auth::SignInWithProvider(FederatedAuthProvider* provider) { +Future Auth::SignInWithProvider(FederatedAuthProvider *provider) { FIREBASE_ASSERT_RETURN(Future(), provider); return provider->SignIn(auth_data_); } @@ -442,8 +432,7 @@ void SignInResultCallback(FIRAuthDataResult *_Nullable auth_result, NSError *_Nu Future Auth::CreateUserWithEmailAndPassword(const char *email, const char *password) { ReferenceCountedFutureImpl &futures = auth_data_->future_impl; - const auto handle = - futures.SafeAlloc(kAuthFn_CreateUserWithEmailAndPassword, nullptr); + const auto handle = futures.SafeAlloc(kAuthFn_CreateUserWithEmailAndPassword, nullptr); if (!email || strlen(email) == 0) { futures.Complete(handle, kAuthErrorMissingEmail, "Empty email is not allowed."); } else if (!password || strlen(password) == 0) { @@ -472,17 +461,16 @@ void SignInResultCallback(FIRAuthDataResult *_Nullable auth_result, NSError *_Nu [AuthImpl(auth_data_) sendPasswordResetWithEmail:@(email) completion:^(NSError *_Nullable error) { - futures.Complete( - handle, AuthErrorFromNSError(error), - [error.localizedDescription UTF8String]); - }]; + futures.Complete(handle, AuthErrorFromNSError(error), + [error.localizedDescription UTF8String]); + }]; return MakeFuture(&futures, handle); } // Remap iOS SDK errors reported by the UIDelegate. While these errors seem like // user interaction errors, they are actually caused by bad provider ids. -NSError* RemapBadProviderIDErrors(NSError* _Nonnull error) { +NSError *RemapBadProviderIDErrors(NSError *_Nonnull error) { if (error.code == FIRAuthErrorCodeWebSignInUserInteractionFailure && [error.domain isEqualToString:@"FIRAuthErrorDomain"]) { return [[NSError alloc] initWithDomain:error.domain diff --git a/auth/src/ios/common_ios.h b/auth/src/ios/common_ios.h index 66469392ea..d6d471e811 100644 --- a/auth/src/ios/common_ios.h +++ b/auth/src/ios/common_ios.h @@ -37,8 +37,7 @@ namespace firebase { namespace auth { // No static_assert available without C++11, unfortunately. -#define AUTH_STATIC_ASSERT(x) \ - typedef char AUTH_STATIC_ASSERT_FAILED[(x) ? 1 : -1] +#define AUTH_STATIC_ASSERT(x) typedef char AUTH_STATIC_ASSERT_FAILED[(x) ? 1 : -1] OBJ_C_PTR_WRAPPER(FIRAuth); OBJ_C_PTR_WRAPPER(FIRAuthCredential); @@ -53,13 +52,11 @@ struct AuthDataIos { /// Convert from the platform-independent void* to the Obj-C FIRUser pointer. static inline FIRUser *_Nullable UserImpl(AuthData *_Nonnull auth_data) { - return FIRUserPointer::SafeGet( - static_cast(auth_data->user_impl)); + return FIRUserPointer::SafeGet(static_cast(auth_data->user_impl)); } /// Release the platform-dependent FIRUser object. -static inline void SetUserImpl(AuthData *_Nonnull auth_data, - FIRUser *_Nullable user) { +static inline void SetUserImpl(AuthData *_Nonnull auth_data, FIRUser *_Nullable user) { MutexLock lock(auth_data->future_impl.mutex()); // Delete existing pointer to FIRUser. @@ -81,8 +78,7 @@ static inline FIRAuth *_Nonnull AuthImpl(AuthData *_Nonnull auth_data) { /// Convert from the void* credential implementation pointer into the Obj-C /// FIRAuthCredential pointer. -static inline FIRAuthCredential *_Nonnull CredentialFromImpl( - void *_Nonnull impl) { +static inline FIRAuthCredential *_Nonnull CredentialFromImpl(void *_Nonnull impl) { return static_cast(impl)->get(); } @@ -91,29 +87,26 @@ AuthError AuthErrorFromNSError(NSError *_Nullable error); /// Common code for all API calls that return a User*. /// Initialize `auth_data->current_user` and complete the `future`. void SignInCallback(FIRUser *_Nullable user, NSError *_Nullable error, - SafeFutureHandle handle, - AuthData *_Nonnull auth_data); + SafeFutureHandle handle, AuthData *_Nonnull auth_data); /// Common code for all API calls that return a SignInResult. /// Initialize `auth_data->current_user` and complete the `future`. -void SignInResultCallback(FIRAuthDataResult *_Nullable auth_result, - NSError *_Nullable error, - SafeFutureHandle handle, - AuthData *_Nonnull auth_data); +void SignInResultCallback(FIRAuthDataResult *_Nullable auth_result, NSError *_Nullable error, + SafeFutureHandle handle, AuthData *_Nonnull auth_data); /// Common code for all FederatedOAuth API calls which return a SignInResult and /// must hold a reference to a FIROAuthProvider so that the provider is not /// deallocated by the Objective-C environment. Directly invokes /// SignInResultCallback(). -void SignInResultWithProviderCallback( - FIRAuthDataResult* _Nullable auth_result, NSError* _Nullable error, - SafeFutureHandle handle, AuthData *_Nonnull auth_data, - const FIROAuthProvider *_Nonnull ios_auth_provider); +void SignInResultWithProviderCallback(FIRAuthDataResult *_Nullable auth_result, + NSError *_Nullable error, + SafeFutureHandle handle, + AuthData *_Nonnull auth_data, + const FIROAuthProvider *_Nonnull ios_auth_provider); /// Remap iOS SDK errors reported by the UIDelegate. While these errors seem /// like user interaction errors, they are actually caused by bad provider ids. -NSError* RemapBadProviderIDErrors(NSError* _Nonnull error); - +NSError *RemapBadProviderIDErrors(NSError *_Nonnull error); } // namespace auth } // namespace firebase diff --git a/auth/src/ios/credential_ios.mm b/auth/src/ios/credential_ios.mm index aeb899a0e4..5c271f907c 100644 --- a/auth/src/ios/credential_ios.mm +++ b/auth/src/ios/credential_ios.mm @@ -32,7 +32,7 @@ // PhoneAuth is not supported on non-iOS Apple platforms (eg: tvOS). // We are using stub implementation for these platforms (just like on desktop). #import "FIRPhoneAuthProvider.h" -#endif //FIREBASE_PLATFORM_IOS +#endif // FIREBASE_PLATFORM_IOS #import "FIRTwitterAuthProvider.h" @@ -41,7 +41,7 @@ // @ref VerifyPhoneNumber. It exists for as long as one of those two lives. We use Objective-C // for reference counting. @interface PhoneListenerDataObjC : NSObject { -@public + @public // Back-pointer to the PhoneAuthProvider::Listener, or nullptr if it has been deleted. // This lets the VerifyPhoneNumber block know when its Listener has been deleted so it should // become a no-op. @@ -53,7 +53,7 @@ @interface PhoneListenerDataObjC : NSObject { @end @implementation PhoneListenerDataObjC @end -#endif //FIREBASE_PLATFORM_IOS +#endif // FIREBASE_PLATFORM_IOS namespace firebase { namespace auth { @@ -90,14 +90,14 @@ @implementation PhoneListenerDataObjC bool Credential::is_valid() const { return CredentialFromImpl(impl_) != NULL; } std::string Credential::provider() const { - return impl_ == nullptr ? std::string("") : - util::StringFromNSString(CredentialFromImpl(impl_).provider); + return impl_ == nullptr ? std::string("") + : util::StringFromNSString(CredentialFromImpl(impl_).provider); } // static Credential EmailAuthProvider::GetCredential(const char* email, const char* password) { FIREBASE_ASSERT_RETURN(Credential(), email && password); - FIRAuthCredential *credential = [FIREmailAuthProvider credentialWithEmail:@(email) + FIRAuthCredential* credential = [FIREmailAuthProvider credentialWithEmail:@(email) password:@(password)]; return Credential(new FIRAuthCredentialPointer(credential)); } @@ -105,7 +105,7 @@ @implementation PhoneListenerDataObjC // static Credential FacebookAuthProvider::GetCredential(const char* access_token) { FIREBASE_ASSERT_RETURN(Credential(), access_token); - FIRAuthCredential *credential = + FIRAuthCredential* credential = [FIRFacebookAuthProvider credentialWithAccessToken:@(access_token)]; return Credential(new FIRAuthCredentialPointer(credential)); } @@ -113,7 +113,7 @@ @implementation PhoneListenerDataObjC // static Credential GitHubAuthProvider::GetCredential(const char* token) { FIREBASE_ASSERT_RETURN(Credential(), token); - FIRAuthCredential *credential = [FIRGitHubAuthProvider credentialWithToken:@(token)]; + FIRAuthCredential* credential = [FIRGitHubAuthProvider credentialWithToken:@(token)]; return Credential(new FIRAuthCredentialPointer(credential)); } @@ -121,8 +121,8 @@ @implementation PhoneListenerDataObjC Credential GoogleAuthProvider::GetCredential(const char* id_token, const char* access_token) { NSString* ns_id_token = id_token ? @(id_token) : nil; NSString* ns_access_token = access_token ? @(access_token) : nil; - FIRAuthCredential* credential = - [FIRGoogleAuthProvider credentialWithIDToken:ns_id_token accessToken:ns_access_token]; + FIRAuthCredential* credential = [FIRGoogleAuthProvider credentialWithIDToken:ns_id_token + accessToken:ns_access_token]; return Credential(new FIRAuthCredentialPointer(credential)); } @@ -137,14 +137,14 @@ @implementation PhoneListenerDataObjC // static Credential TwitterAuthProvider::GetCredential(const char* token, const char* secret) { FIREBASE_ASSERT_RETURN(Credential(), token && secret); - FIRAuthCredential *credential = [FIRTwitterAuthProvider credentialWithToken:@(token) + FIRAuthCredential* credential = [FIRTwitterAuthProvider credentialWithToken:@(token) secret:@(secret)]; return Credential(new FIRAuthCredentialPointer(credential)); } // static -Credential OAuthProvider::GetCredential( - const char* provider_id, const char* id_token, const char* access_token) { +Credential OAuthProvider::GetCredential(const char* provider_id, const char* id_token, + const char* access_token) { FIREBASE_ASSERT_RETURN(Credential(), provider_id && id_token && access_token); FIRAuthCredential* credential = (FIRAuthCredential*)[FIROAuthProvider credentialWithProviderID:@(provider_id) @@ -154,10 +154,8 @@ @implementation PhoneListenerDataObjC } // static -Credential OAuthProvider::GetCredential(const char* provider_id, - const char* id_token, - const char* raw_nonce, - const char* access_token) { +Credential OAuthProvider::GetCredential(const char* provider_id, const char* id_token, + const char* raw_nonce, const char* access_token) { FIREBASE_ASSERT_RETURN(Credential(), provider_id && id_token && raw_nonce); NSString* access_token_string = @@ -182,12 +180,12 @@ @implementation PhoneListenerDataObjC checking whether the APP that consuming our SDK has linked GameKit.framework. If not, will complete with kAuthErrorInvalidCredential error. **/ - GKLocalPlayer *_Nullable optionalLocalPlayer = [[NSClassFromString(@"GKLocalPlayer") alloc] init]; + GKLocalPlayer* _Nullable optionalLocalPlayer = [[NSClassFromString(@"GKLocalPlayer") alloc] init]; // Early-out if GameKit is not linked if (!optionalLocalPlayer) { future_api->Complete(handle, kAuthErrorInvalidCredential, - "GameCenter authentication is unavailable - missing GameKit capability."); + "GameCenter authentication is unavailable - missing GameKit capability."); return MakeFuture(future_api, handle); } @@ -195,14 +193,14 @@ @implementation PhoneListenerDataObjC NSError* _Nullable error) { Credential result(new FIRAuthCredentialPointer(credential)); future_api->CompleteWithResult(handle, AuthErrorFromNSError(error), - util::NSStringToString(error.localizedDescription).c_str(), - result); + util::NSStringToString(error.localizedDescription).c_str(), + result); }]; return MakeFuture(future_api, handle); } - // static +// static Future GameCenterAuthProvider::GetCredentialLastResult() { auto future_api = GetCredentialFutureImpl(); FIREBASE_ASSERT(future_api != nullptr); @@ -211,7 +209,6 @@ @implementation PhoneListenerDataObjC return static_cast&>(last_result); } - // static bool GameCenterAuthProvider::IsPlayerAuthenticated() { /** @@ -220,28 +217,31 @@ @implementation PhoneListenerDataObjC checking whether the APP that consuming our SDK has linked GameKit.framework. If not, early out. **/ - GKLocalPlayer *_Nullable optionalLocalPlayer = [[NSClassFromString(@"GKLocalPlayer") alloc] init]; + GKLocalPlayer* _Nullable optionalLocalPlayer = [[NSClassFromString(@"GKLocalPlayer") alloc] init]; // If the GameKit Framework isn't linked - early out. if (!optionalLocalPlayer) { return false; } - __weak GKLocalPlayer *localPlayer = [[optionalLocalPlayer class] localPlayer]; + __weak GKLocalPlayer* localPlayer = [[optionalLocalPlayer class] localPlayer]; return localPlayer.isAuthenticated; } // We skip the implementation of ForceResendingTokenData since it is not needed. // The ForceResendingToken class for iOS is empty. -PhoneAuthProvider::ForceResendingToken::ForceResendingToken() - : data_(nullptr) {} +PhoneAuthProvider::ForceResendingToken::ForceResendingToken() : data_(nullptr) {} PhoneAuthProvider::ForceResendingToken::~ForceResendingToken() {} -PhoneAuthProvider::ForceResendingToken::ForceResendingToken( - const ForceResendingToken&) : data_(nullptr) {} -PhoneAuthProvider::ForceResendingToken& PhoneAuthProvider::ForceResendingToken:: -operator=(const ForceResendingToken&) { return *this; } -bool PhoneAuthProvider::ForceResendingToken::operator==( - const ForceResendingToken&) const { return true; } -bool PhoneAuthProvider::ForceResendingToken::operator!=( - const ForceResendingToken&) const { return false; } +PhoneAuthProvider::ForceResendingToken::ForceResendingToken(const ForceResendingToken&) + : data_(nullptr) {} +PhoneAuthProvider::ForceResendingToken& PhoneAuthProvider::ForceResendingToken::operator=( + const ForceResendingToken&) { + return *this; +} +bool PhoneAuthProvider::ForceResendingToken::operator==(const ForceResendingToken&) const { + return true; +} +bool PhoneAuthProvider::ForceResendingToken::operator!=(const ForceResendingToken&) const { + return false; +} #if FIREBASE_PLATFORM_IOS // This implementation of PhoneListenerData is specific to iOS. @@ -255,10 +255,10 @@ @implementation PhoneListenerDataObjC data_->objc = [[PhoneListenerDataObjC alloc] init]; data_->objc->active_listener = this; } -#else // non-iOS Apple platforms (eg: tvOS) +#else // non-iOS Apple platforms (eg: tvOS) // Stub for tvOS and other non-iOS apple platforms. PhoneAuthProvider::Listener::Listener() : data_(nullptr) {} -#endif // FIREBASE_PLATFORM_IOS +#endif // FIREBASE_PLATFORM_IOS #if FIREBASE_PLATFORM_IOS PhoneAuthProvider::Listener::~Listener() { @@ -271,9 +271,9 @@ @implementation PhoneListenerDataObjC data_->objc = nil; delete data_; } -#else // non-iOS Apple platforms (eg: tvOS) +#else // non-iOS Apple platforms (eg: tvOS) PhoneAuthProvider::Listener::~Listener() {} -#endif // FIREBASE_PLATFORM_IOS +#endif // FIREBASE_PLATFORM_IOS #if FIREBASE_PLATFORM_IOS // This implementation of PhoneAuthProviderData is specific to iOS. @@ -285,42 +285,43 @@ explicit PhoneAuthProviderData(FIRPhoneAuthProvider* objc_provider) // The wrapped provider in Objective-C. FIRPhoneAuthProvider* objc_provider; }; -#endif // FIREBASE_PLATFORM_IOS +#endif // FIREBASE_PLATFORM_IOS PhoneAuthProvider::PhoneAuthProvider() : data_(nullptr) {} #if FIREBASE_PLATFORM_IOS PhoneAuthProvider::~PhoneAuthProvider() { delete data_; } -#else // non-iOS Apple platforms (eg: tvOS) +#else // non-iOS Apple platforms (eg: tvOS) PhoneAuthProvider::~PhoneAuthProvider() {} -#endif // FIREBASE_PLATFORM_IOS +#endif // FIREBASE_PLATFORM_IOS #if FIREBASE_PLATFORM_IOS -void PhoneAuthProvider::VerifyPhoneNumber( - const char* phone_number, uint32_t /*auto_verify_time_out_ms*/, - const ForceResendingToken* /*force_resending_token*/, Listener* listener) { +void PhoneAuthProvider::VerifyPhoneNumber(const char* phone_number, + uint32_t /*auto_verify_time_out_ms*/, + const ForceResendingToken* /*force_resending_token*/, + Listener* listener) { FIREBASE_ASSERT_RETURN_VOID(listener != nullptr); const PhoneAuthProvider::ForceResendingToken invalid_resending_token; PhoneListenerDataObjC* objc_listener_data = listener->data_->objc; - [data_->objc_provider verifyPhoneNumber:@(phone_number) - UIDelegate:nil - completion:^(NSString *_Nullable verificationID, - NSError *_Nullable error) { - MutexLock lock(objc_listener_data->listener_mutex); - - // If the listener has been deleted before this callback, do nothing. - if (objc_listener_data->active_listener == nullptr) return; - - // Call OnVerificationFailed() or OnCodeSent() as appropriate. - if (verificationID == nullptr) { - listener->OnVerificationFailed( - util::StringFromNSString(error.localizedDescription)); - } else { - listener->OnCodeSent(util::StringFromNSString(verificationID), - invalid_resending_token); - } - }]; + [data_->objc_provider + verifyPhoneNumber:@(phone_number) + UIDelegate:nil + completion:^(NSString* _Nullable verificationID, NSError* _Nullable error) { + MutexLock lock(objc_listener_data->listener_mutex); + + // If the listener has been deleted before this callback, do nothing. + if (objc_listener_data->active_listener == nullptr) return; + + // Call OnVerificationFailed() or OnCodeSent() as appropriate. + if (verificationID == nullptr) { + listener->OnVerificationFailed( + util::StringFromNSString(error.localizedDescription)); + } else { + listener->OnCodeSent(util::StringFromNSString(verificationID), + invalid_resending_token); + } + }]; // Only call the callback when protected by the mutex. { @@ -330,10 +331,11 @@ explicit PhoneAuthProviderData(FIRPhoneAuthProvider* objc_provider) } } } -#else // non-iOS Apple platforms (eg: tvOS) -void PhoneAuthProvider::VerifyPhoneNumber( - const char* /*phone_number*/, uint32_t /*auto_verify_time_out_ms*/, - const ForceResendingToken* force_resending_token, Listener* listener) { +#else // non-iOS Apple platforms (eg: tvOS) +void PhoneAuthProvider::VerifyPhoneNumber(const char* /*phone_number*/, + uint32_t /*auto_verify_time_out_ms*/, + const ForceResendingToken* force_resending_token, + Listener* listener) { FIREBASE_ASSERT_RETURN_VOID(listener != nullptr); // Mock the tokens by sending a new one whenever it's unspecified. @@ -345,26 +347,27 @@ explicit PhoneAuthProviderData(FIRPhoneAuthProvider* objc_provider) listener->OnCodeAutoRetrievalTimeOut(kMockVerificationId); listener->OnCodeSent(kMockVerificationId, token); } -#endif // FIREBASE_PLATFORM_IOS +#endif // FIREBASE_PLATFORM_IOS #if FIREBASE_PLATFORM_IOS Credential PhoneAuthProvider::GetCredential(const char* verification_id, const char* verification_code) { FIREBASE_ASSERT_RETURN(Credential(), verification_id && verification_code); - FIRPhoneAuthCredential *credential = + FIRPhoneAuthCredential* credential = [data_->objc_provider credentialWithVerificationID:@(verification_id) verificationCode:@(verification_code)]; return Credential(new FIRAuthCredentialPointer((FIRAuthCredential*)credential)); } -#else // non-iOS Apple platforms (eg: tvOS) +#else // non-iOS Apple platforms (eg: tvOS) Credential PhoneAuthProvider::GetCredential(const char* verification_id, const char* verification_code) { - FIREBASE_ASSERT_MESSAGE_RETURN(Credential(nullptr), false, - "Phone Auth is not supported on non iOS Apple platforms (eg:tvOS)."); + FIREBASE_ASSERT_MESSAGE_RETURN( + Credential(nullptr), false, + "Phone Auth is not supported on non iOS Apple platforms (eg:tvOS)."); return Credential(nullptr); } -#endif // FIREBASE_PLATFORM_IOS +#endif // FIREBASE_PLATFORM_IOS #if FIREBASE_PLATFORM_IOS // static @@ -379,21 +382,21 @@ explicit PhoneAuthProviderData(FIRPhoneAuthProvider* objc_provider) } return provider; } -#else // non-iOS Apple platforms (eg: tvOS) +#else // non-iOS Apple platforms (eg: tvOS) // static PhoneAuthProvider& PhoneAuthProvider::GetInstance(Auth* auth) { return auth->auth_data_->phone_auth_provider; } -#endif // FIREBASE_PLATFORM_IOS +#endif // FIREBASE_PLATFORM_IOS // FederatedAuthHandlers -FederatedOAuthProvider::FederatedOAuthProvider() { } +FederatedOAuthProvider::FederatedOAuthProvider() {} FederatedOAuthProvider::FederatedOAuthProvider(const FederatedOAuthProviderData& provider_data) { provider_data_ = provider_data; } -FederatedOAuthProvider::~FederatedOAuthProvider() { } +FederatedOAuthProvider::~FederatedOAuthProvider() {} void FederatedOAuthProvider::SetProviderData(const FederatedOAuthProviderData& provider_data) { provider_data_ = provider_data; @@ -450,9 +453,8 @@ void ReauthenticateWithProviderGetCredentialCallback(FIRAuthCredential* _Nullabl Future FederatedOAuthProvider::SignIn(AuthData* auth_data) { assert(auth_data); - ReferenceCountedFutureImpl &futures = auth_data->future_impl; - const auto handle = - futures.SafeAlloc(kAuthFn_SignInWithProvider, SignInResult()); + ReferenceCountedFutureImpl& futures = auth_data->future_impl; + const auto handle = futures.SafeAlloc(kAuthFn_SignInWithProvider, SignInResult()); FIROAuthProvider* ios_provider = (FIROAuthProvider*)[FIROAuthProvider providerWithProviderID:@(provider_data_.provider_id.c_str()) auth:AuthImpl(auth_data)]; @@ -470,17 +472,16 @@ void ReauthenticateWithProviderGetCredentialCallback(FIRAuthCredential* _Nullabl } else { Future future = MakeFuture(&futures, handle); futures.CompleteWithResult(handle, kAuthErrorFailure, "Internal error constructing provider.", - SignInResult()); + SignInResult()); return future; } } Future FederatedOAuthProvider::Link(AuthData* auth_data) { assert(auth_data); - ReferenceCountedFutureImpl &futures = auth_data->future_impl; - auto handle = - futures.SafeAlloc(kUserFn_LinkWithProvider, SignInResult()); - #if FIREBASE_PLATFORM_IOS + ReferenceCountedFutureImpl& futures = auth_data->future_impl; + auto handle = futures.SafeAlloc(kUserFn_LinkWithProvider, SignInResult()); +#if FIREBASE_PLATFORM_IOS FIROAuthProvider* ios_provider = (FIROAuthProvider*)[FIROAuthProvider providerWithProviderID:@(provider_data_.provider_id.c_str()) auth:AuthImpl(auth_data)]; @@ -489,13 +490,12 @@ void ReauthenticateWithProviderGetCredentialCallback(FIRAuthCredential* _Nullabl ios_provider.scopes = util::StringVectorToNSMutableArray(provider_data_.scopes); // TODO(b/138788092) invoke FIRUser linkWithProvider instead, once that method is added to the // iOS SDK. - [ios_provider - getCredentialWithUIDelegate:nullptr - completion:^(FIRAuthCredential* _Nullable credential, - NSError* _Nullable error) { - LinkWithProviderGetCredentialCallback( - credential, error, handle, auth_data, ios_provider); - }]; + [ios_provider getCredentialWithUIDelegate:nullptr + completion:^(FIRAuthCredential* _Nullable credential, + NSError* _Nullable error) { + LinkWithProviderGetCredentialCallback( + credential, error, handle, auth_data, ios_provider); + }]; return MakeFuture(&futures, handle); } else { Future future = MakeFuture(&futures, handle); @@ -504,20 +504,18 @@ void ReauthenticateWithProviderGetCredentialCallback(FIRAuthCredential* _Nullabl return future; } - #else // non-iOS Apple platforms (eg: tvOS) +#else // non-iOS Apple platforms (eg: tvOS) Future future = MakeFuture(&futures, handle); futures.Complete(handle, kAuthErrorApiNotAvailable, - "OAuth provider linking is not supported on non-iOS Apple platforms."); - #endif // FIREBASE_PLATFORM_IOS - + "OAuth provider linking is not supported on non-iOS Apple platforms."); +#endif // FIREBASE_PLATFORM_IOS } Future FederatedOAuthProvider::Reauthenticate(AuthData* auth_data) { assert(auth_data); - ReferenceCountedFutureImpl &futures = auth_data->future_impl; - auto handle = - futures.SafeAlloc(kUserFn_LinkWithProvider, SignInResult()); - #if FIREBASE_PLATFORM_IOS + ReferenceCountedFutureImpl& futures = auth_data->future_impl; + auto handle = futures.SafeAlloc(kUserFn_LinkWithProvider, SignInResult()); +#if FIREBASE_PLATFORM_IOS FIROAuthProvider* ios_provider = (FIROAuthProvider*)[FIROAuthProvider providerWithProviderID:@(provider_data_.provider_id.c_str()) auth:AuthImpl(auth_data)]; @@ -526,13 +524,12 @@ void ReauthenticateWithProviderGetCredentialCallback(FIRAuthCredential* _Nullabl ios_provider.scopes = util::StringVectorToNSMutableArray(provider_data_.scopes); // TODO(b/138788092) invoke FIRUser:reuthenticateWithProvider instead, once that method is added // to the iOS SDK. - [ios_provider - getCredentialWithUIDelegate:nullptr - completion:^(FIRAuthCredential* _Nullable credential, - NSError* _Nullable error) { - ReauthenticateWithProviderGetCredentialCallback( - credential, error, handle, auth_data, ios_provider); - }]; + [ios_provider getCredentialWithUIDelegate:nullptr + completion:^(FIRAuthCredential* _Nullable credential, + NSError* _Nullable error) { + ReauthenticateWithProviderGetCredentialCallback( + credential, error, handle, auth_data, ios_provider); + }]; return MakeFuture(&futures, handle); } else { Future future = MakeFuture(&futures, handle); @@ -541,11 +538,11 @@ void ReauthenticateWithProviderGetCredentialCallback(FIRAuthCredential* _Nullabl return future; } - #else // non-iOS Apple platforms (eg: tvOS) +#else // non-iOS Apple platforms (eg: tvOS) Future future = MakeFuture(&futures, handle); futures.Complete(handle, kAuthErrorApiNotAvailable, - "OAuth reauthentication is not supported on non-iOS Apple platforms."); - #endif // FIREBASE_PLATFORM_IOS + "OAuth reauthentication is not supported on non-iOS Apple platforms."); +#endif // FIREBASE_PLATFORM_IOS } } // namespace auth diff --git a/auth/src/ios/user_ios.mm b/auth/src/ios/user_ios.mm index ccbe470199..e4c3817440 100644 --- a/auth/src/ios/user_ios.mm +++ b/auth/src/ios/user_ios.mm @@ -33,33 +33,19 @@ public: explicit IOSWrappedUserInfo(id user_info) : user_info_(user_info) {} - virtual ~IOSWrappedUserInfo() { - user_info_ = nil; - } + virtual ~IOSWrappedUserInfo() { user_info_ = nil; } - virtual std::string uid() const { - return StringFromNSString(user_info_.uid); - } + virtual std::string uid() const { return StringFromNSString(user_info_.uid); } - virtual std::string email() const { - return StringFromNSString(user_info_.email); - } + virtual std::string email() const { return StringFromNSString(user_info_.email); } - virtual std::string display_name() const { - return StringFromNSString(user_info_.displayName); - } + virtual std::string display_name() const { return StringFromNSString(user_info_.displayName); } - virtual std::string phone_number() const { - return StringFromNSString(user_info_.phoneNumber); - } + virtual std::string phone_number() const { return StringFromNSString(user_info_.phoneNumber); } - virtual std::string photo_url() const { - return StringFromNSUrl(user_info_.photoURL); - } + virtual std::string photo_url() const { return StringFromNSUrl(user_info_.photoURL); } - virtual std::string provider_id() const { - return StringFromNSString(user_info_.providerID); - } + virtual std::string provider_id() const { return StringFromNSString(user_info_.providerID); } private: /// Pointer to the main class. @@ -78,21 +64,21 @@ explicit IOSWrappedUserInfo(id user_info) : user_info_(user_info) { if (!ValidUser(auth_data_)) { return Future(); } - ReferenceCountedFutureImpl& futures = auth_data_->future_impl; + ReferenceCountedFutureImpl &futures = auth_data_->future_impl; const auto handle = futures.SafeAlloc(kUserFn_GetToken); [UserImpl(auth_data_) getIDTokenForcingRefresh:force_refresh completion:^(NSString *_Nullable token, NSError *_Nullable error) { - futures.Complete( - handle, AuthErrorFromNSError(error), - [error.localizedDescription UTF8String], [token](std::string* data) { - data->assign(token == nullptr ? "" : [token UTF8String]); - }); - }]; + futures.Complete(handle, AuthErrorFromNSError(error), + [error.localizedDescription UTF8String], + [token](std::string *data) { + data->assign(token == nullptr ? "" : [token UTF8String]); + }); + }]; return MakeFuture(&futures, handle); } -const std::vector& User::provider_data() const { +const std::vector &User::provider_data() const { ClearUserInfos(auth_data_); if (ValidUser(auth_data_)) { @@ -113,13 +99,13 @@ explicit IOSWrappedUserInfo(id user_info) : user_info_(user_info) { if (!ValidUser(auth_data_)) { return Future(); } - ReferenceCountedFutureImpl& futures = auth_data_->future_impl; + ReferenceCountedFutureImpl &futures = auth_data_->future_impl; const auto handle = futures.SafeAlloc(kUserFn_UpdateEmail); [UserImpl(auth_data_) updateEmail:@(email) completion:^(NSError *_Nullable error) { - futures.Complete(handle, AuthErrorFromNSError(error), - [error.localizedDescription UTF8String]); - }]; + futures.Complete(handle, AuthErrorFromNSError(error), + [error.localizedDescription UTF8String]); + }]; return MakeFuture(&futures, handle); } @@ -127,22 +113,21 @@ explicit IOSWrappedUserInfo(id user_info) : user_info_(user_info) { if (!ValidUser(auth_data_)) { return Future(); } - ReferenceCountedFutureImpl& futures = auth_data_->future_impl; + ReferenceCountedFutureImpl &futures = auth_data_->future_impl; const auto handle = futures.SafeAlloc(kUserFn_UpdatePassword); - [UserImpl(auth_data_) - updatePassword:@(password) - completion:^(NSError *_Nullable error) { - futures.Complete(handle, AuthErrorFromNSError(error), - [error.localizedDescription UTF8String]); - }]; + [UserImpl(auth_data_) updatePassword:@(password) + completion:^(NSError *_Nullable error) { + futures.Complete(handle, AuthErrorFromNSError(error), + [error.localizedDescription UTF8String]); + }]; return MakeFuture(&futures, handle); } -Future User::UpdateUserProfile(const UserProfile& profile) { +Future User::UpdateUserProfile(const UserProfile &profile) { if (!ValidUser(auth_data_)) { return Future(); } - ReferenceCountedFutureImpl& futures = auth_data_->future_impl; + ReferenceCountedFutureImpl &futures = auth_data_->future_impl; const auto handle = futures.SafeAlloc(kUserFn_UpdateUserProfile); // Create and populate the change request. FIRUserProfileChangeRequest *request = [UserImpl(auth_data_) profileChangeRequest]; @@ -151,15 +136,15 @@ explicit IOSWrappedUserInfo(id user_info) : user_info_(user_info) { } if (profile.photo_url != nullptr) { NSString *photo_url_string = @(profile.photo_url); - request.photoURL = [NSURL URLWithString:[photo_url_string - stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; + request.photoURL = + [NSURL URLWithString:[photo_url_string + stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; } // Execute the change request. [request commitChangesWithCompletion:^(NSError *_Nullable error) { - futures.Complete(handle, AuthErrorFromNSError(error), - [error.localizedDescription UTF8String]); - }]; + futures.Complete(handle, AuthErrorFromNSError(error), [error.localizedDescription UTF8String]); + }]; return MakeFuture(&futures, handle); } @@ -167,21 +152,20 @@ explicit IOSWrappedUserInfo(id user_info) : user_info_(user_info) { if (!ValidUser(auth_data_)) { return Future(); } - ReferenceCountedFutureImpl& futures = auth_data_->future_impl; + ReferenceCountedFutureImpl &futures = auth_data_->future_impl; const auto handle = futures.SafeAlloc(kUserFn_SendEmailVerification); [UserImpl(auth_data_) sendEmailVerificationWithCompletion:^(NSError *_Nullable error) { - futures.Complete(handle, AuthErrorFromNSError(error), - [error.localizedDescription UTF8String]); + futures.Complete(handle, AuthErrorFromNSError(error), [error.localizedDescription UTF8String]); }]; return MakeFuture(&futures, handle); } -Future User::LinkWithCredential(const Credential &credential) { +Future User::LinkWithCredential(const Credential &credential) { if (!ValidUser(auth_data_)) { - return Future(); + return Future(); } - ReferenceCountedFutureImpl& futures = auth_data_->future_impl; - const auto handle = futures.SafeAlloc(kUserFn_LinkWithCredential); + ReferenceCountedFutureImpl &futures = auth_data_->future_impl; + const auto handle = futures.SafeAlloc(kUserFn_LinkWithCredential); [UserImpl(auth_data_) linkWithCredential:CredentialFromImpl(credential.impl_) completion:^(FIRAuthDataResult *_Nullable auth_result, NSError *_Nullable error) { @@ -194,61 +178,59 @@ explicit IOSWrappedUserInfo(id user_info) : user_info_(user_info) { if (!ValidUser(auth_data_)) { return Future(); } - ReferenceCountedFutureImpl& futures = auth_data_->future_impl; + ReferenceCountedFutureImpl &futures = auth_data_->future_impl; const auto handle = auth_data_->future_impl.SafeAlloc( - kUserFn_LinkAndRetrieveDataWithCredential, SignInResult()); + kUserFn_LinkAndRetrieveDataWithCredential, SignInResult()); [UserImpl(auth_data_) linkWithCredential:CredentialFromImpl(credential.impl_) - completion:^(FIRAuthDataResult *_Nullable auth_result, - NSError *_Nullable error) { - SignInResultCallback(auth_result, error, handle, auth_data_); - }]; + completion:^(FIRAuthDataResult *_Nullable auth_result, NSError *_Nullable error) { + SignInResultCallback(auth_result, error, handle, auth_data_); + }]; return MakeFuture(&futures, handle); } -Future User::LinkWithProvider(FederatedAuthProvider* provider) const { +Future User::LinkWithProvider(FederatedAuthProvider *provider) const { FIREBASE_ASSERT_RETURN(Future(), provider); return provider->Link(auth_data_); } -Future User::Unlink(const char *provider) { +Future User::Unlink(const char *provider) { if (!ValidUser(auth_data_)) { - return Future(); + return Future(); } - ReferenceCountedFutureImpl& futures = auth_data_->future_impl; - const auto handle = futures.SafeAlloc(kUserFn_Unlink); - [UserImpl(auth_data_) - unlinkFromProvider:@(provider) - completion:^(FIRUser *_Nullable user, NSError *_Nullable error) { - SignInCallback(user, error, handle, auth_data_); - }]; + ReferenceCountedFutureImpl &futures = auth_data_->future_impl; + const auto handle = futures.SafeAlloc(kUserFn_Unlink); + [UserImpl(auth_data_) unlinkFromProvider:@(provider) + completion:^(FIRUser *_Nullable user, NSError *_Nullable error) { + SignInCallback(user, error, handle, auth_data_); + }]; return MakeFuture(&futures, handle); } -Future User::UpdatePhoneNumberCredential(const Credential& credential) { +Future User::UpdatePhoneNumberCredential(const Credential &credential) { if (!ValidUser(auth_data_)) { - return Future(); + return Future(); } - ReferenceCountedFutureImpl& futures = auth_data_->future_impl; - const auto handle = futures.SafeAlloc(kUserFn_UpdatePhoneNumberCredential); + ReferenceCountedFutureImpl &futures = auth_data_->future_impl; + const auto handle = futures.SafeAlloc(kUserFn_UpdatePhoneNumberCredential); - #if FIREBASE_PLATFORM_IOS +#if FIREBASE_PLATFORM_IOS FIRAuthCredential *objc_credential = CredentialFromImpl(credential.impl_); if ([objc_credential isKindOfClass:[FIRPhoneAuthCredential class]]) { [UserImpl(auth_data_) - updatePhoneNumberCredential:(FIRPhoneAuthCredential*)objc_credential - completion:^(NSError *_Nullable error) { - futures.Complete(handle, AuthErrorFromNSError(error), - [error.localizedDescription UTF8String]); - }]; + updatePhoneNumberCredential:(FIRPhoneAuthCredential *)objc_credential + completion:^(NSError *_Nullable error) { + futures.Complete(handle, AuthErrorFromNSError(error), + [error.localizedDescription UTF8String]); + }]; } else { futures.Complete(handle, kAuthErrorInvalidCredential, kInvalidCredentialMessage); } - #else // non iOS Apple platforms (eg: tvOS). +#else // non iOS Apple platforms (eg: tvOS). futures.Complete(handle, kAuthErrorApiNotAvailable, "Phone Auth is not supported on non-iOS apple platforms."); - #endif // FIREBASE_PLATFORM_IOS +#endif // FIREBASE_PLATFORM_IOS return MakeFuture(&futures, handle); } @@ -257,21 +239,20 @@ explicit IOSWrappedUserInfo(id user_info) : user_info_(user_info) { if (!ValidUser(auth_data_)) { return Future(); } - ReferenceCountedFutureImpl& futures = auth_data_->future_impl; + ReferenceCountedFutureImpl &futures = auth_data_->future_impl; const auto handle = futures.SafeAlloc(kUserFn_Reload); [UserImpl(auth_data_) reloadWithCompletion:^(NSError *_Nullable error) { - futures.Complete(handle, AuthErrorFromNSError(error), - [error.localizedDescription UTF8String]); + futures.Complete(handle, AuthErrorFromNSError(error), [error.localizedDescription UTF8String]); }]; return MakeFuture(&futures, handle); } -Future User::Reauthenticate(const Credential& credential) { +Future User::Reauthenticate(const Credential &credential) { if (!ValidUser(auth_data_)) { return Future(); } - ReferenceCountedFutureImpl& futures = auth_data_->future_impl; + ReferenceCountedFutureImpl &futures = auth_data_->future_impl; const auto handle = futures.SafeAlloc(kUserFn_Reauthenticate); [UserImpl(auth_data_) @@ -284,11 +265,11 @@ explicit IOSWrappedUserInfo(id user_info) : user_info_(user_info) { return MakeFuture(&futures, handle); } -Future User::ReauthenticateAndRetrieveData(const Credential& credential) { +Future User::ReauthenticateAndRetrieveData(const Credential &credential) { if (!ValidUser(auth_data_)) { return Future(); } - ReferenceCountedFutureImpl& futures = auth_data_->future_impl; + ReferenceCountedFutureImpl &futures = auth_data_->future_impl; const auto handle = auth_data_->future_impl.SafeAlloc( kUserFn_ReauthenticateAndRetrieveData, SignInResult()); @@ -296,12 +277,12 @@ explicit IOSWrappedUserInfo(id user_info) : user_info_(user_info) { reauthenticateWithCredential:CredentialFromImpl(credential.impl_) completion:^(FIRAuthDataResult *_Nullable auth_result, NSError *_Nullable error) { - SignInResultCallback(auth_result, error, handle, auth_data_); - }]; + SignInResultCallback(auth_result, error, handle, auth_data_); + }]; return MakeFuture(&futures, handle); } -Future User::ReauthenticateWithProvider(FederatedAuthProvider* provider) const { +Future User::ReauthenticateWithProvider(FederatedAuthProvider *provider) const { FIREBASE_ASSERT_RETURN(Future(), provider); return provider->Reauthenticate(auth_data_); } @@ -310,7 +291,7 @@ explicit IOSWrappedUserInfo(id user_info) : user_info_(user_info) { if (!ValidUser(auth_data_)) { return Future(); } - ReferenceCountedFutureImpl& futures = auth_data_->future_impl; + ReferenceCountedFutureImpl &futures = auth_data_->future_impl; const auto handle = futures.SafeAlloc(kUserFn_Delete); [UserImpl(auth_data_) deleteWithCompletion:^(NSError *_Nullable error) { diff --git a/auth/src_java/com/google/firebase/auth/internal/cpp/AuthCommon.java b/auth/src_java/com/google/firebase/auth/internal/cpp/AuthCommon.java index 9d1f64364e..37c2500c10 100644 --- a/auth/src_java/com/google/firebase/auth/internal/cpp/AuthCommon.java +++ b/auth/src_java/com/google/firebase/auth/internal/cpp/AuthCommon.java @@ -31,8 +31,10 @@ public static void safeRunNativeMethod(Runnable runnable) { try { runnable.run(); } catch (UnsatisfiedLinkError e) { - Log.e(TAG, String.format("Failed to execute native method, perhaps Auth shut down " - + "prematurely? (%s)", e.toString())); + Log.e(TAG, + String.format("Failed to execute native method, perhaps Auth shut down " + + "prematurely? (%s)", + e.toString())); } } } diff --git a/auth/src_java/com/google/firebase/auth/internal/cpp/JniAuthPhoneListener.java b/auth/src_java/com/google/firebase/auth/internal/cpp/JniAuthPhoneListener.java index ed2e3513f6..700f9b81c6 100644 --- a/auth/src_java/com/google/firebase/auth/internal/cpp/JniAuthPhoneListener.java +++ b/auth/src_java/com/google/firebase/auth/internal/cpp/JniAuthPhoneListener.java @@ -52,11 +52,11 @@ public void onVerificationCompleted(final PhoneAuthCredential credential) { synchronized (lock) { if (cListener != CPP_NULLPTR) { AuthCommon.safeRunNativeMethod(new Runnable() { - @Override - public void run() { - nativeOnVerificationCompleted(cListener, credential); - } - }); + @Override + public void run() { + nativeOnVerificationCompleted(cListener, credential); + } + }); } } } @@ -66,11 +66,11 @@ public void onVerificationFailed(final FirebaseException exception) { synchronized (lock) { if (cListener != CPP_NULLPTR) { AuthCommon.safeRunNativeMethod(new Runnable() { - @Override - public void run() { - nativeOnVerificationFailed(cListener, exception.getMessage()); - } - }); + @Override + public void run() { + nativeOnVerificationFailed(cListener, exception.getMessage()); + } + }); } } } @@ -80,11 +80,11 @@ public void onCodeSent(final String verificationId, final ForceResendingToken to synchronized (lock) { if (cListener != CPP_NULLPTR) { AuthCommon.safeRunNativeMethod(new Runnable() { - @Override - public void run() { - nativeOnCodeSent(cListener, verificationId, token); - } - }); + @Override + public void run() { + nativeOnCodeSent(cListener, verificationId, token); + } + }); } } } @@ -94,11 +94,11 @@ public void onCodeAutoRetrievalTimeOut(final String verificationId) { synchronized (lock) { if (cListener != CPP_NULLPTR) { AuthCommon.safeRunNativeMethod(new Runnable() { - @Override - public void run() { - nativeOnCodeAutoRetrievalTimeOut(cListener, verificationId); - } - }); + @Override + public void run() { + nativeOnCodeAutoRetrievalTimeOut(cListener, verificationId); + } + }); } } } @@ -106,10 +106,9 @@ public void run() { /** * This function is implemented in the Auth C++ library (credential_android.cc). */ - private native void nativeOnVerificationCompleted(long cListener, - PhoneAuthCredential credential); + private native void nativeOnVerificationCompleted(long cListener, PhoneAuthCredential credential); private native void nativeOnVerificationFailed(long cListener, String exceptionMessage); - private native void nativeOnCodeSent(long cListener, String verificationId, - ForceResendingToken forceResendingToken); + private native void nativeOnCodeSent( + long cListener, String verificationId, ForceResendingToken forceResendingToken); private native void nativeOnCodeAutoRetrievalTimeOut(long cListener, String verificationId); } diff --git a/auth/src_java/com/google/firebase/auth/internal/cpp/JniAuthStateListener.java b/auth/src_java/com/google/firebase/auth/internal/cpp/JniAuthStateListener.java index 6ee02bc183..6c354d6260 100644 --- a/auth/src_java/com/google/firebase/auth/internal/cpp/JniAuthStateListener.java +++ b/auth/src_java/com/google/firebase/auth/internal/cpp/JniAuthStateListener.java @@ -22,7 +22,6 @@ * Implements AuthStateListener by redirecting calls into C++. */ public class JniAuthStateListener implements FirebaseAuth.AuthStateListener { - /** * Lock that controls access to authData. */ @@ -54,15 +53,15 @@ public void disconnect() { @Override public void onAuthStateChanged(FirebaseAuth auth) { AuthCommon.safeRunNativeMethod(new Runnable() { - @Override - public void run() { - synchronized (lock) { - if (cppAuthData != 0) { - nativeOnAuthStateChanged(cppAuthData); - } + @Override + public void run() { + synchronized (lock) { + if (cppAuthData != 0) { + nativeOnAuthStateChanged(cppAuthData); } } - }); + } + }); } /** diff --git a/auth/src_java/com/google/firebase/auth/internal/cpp/JniIdTokenListener.java b/auth/src_java/com/google/firebase/auth/internal/cpp/JniIdTokenListener.java index 5abad2fb46..07da7ccbce 100644 --- a/auth/src_java/com/google/firebase/auth/internal/cpp/JniIdTokenListener.java +++ b/auth/src_java/com/google/firebase/auth/internal/cpp/JniIdTokenListener.java @@ -22,7 +22,6 @@ * Implements IdTokenListener by redirecting calls into C++. */ public class JniIdTokenListener implements FirebaseAuth.IdTokenListener { - /** * Lock that controls access to authData. */ @@ -54,15 +53,15 @@ public void disconnect() { @Override public void onIdTokenChanged(FirebaseAuth auth) { AuthCommon.safeRunNativeMethod(new Runnable() { - @Override - public void run() { - synchronized (lock) { - if (cppAuthData != 0) { - nativeOnIdTokenChanged(cppAuthData); - } + @Override + public void run() { + synchronized (lock) { + if (cppAuthData != 0) { + nativeOnIdTokenChanged(cppAuthData); } } - }); + } + }); } /** diff --git a/auth/src_java/fake/com/google/firebase/FirebaseApiNotAvailableException.java b/auth/src_java/fake/com/google/firebase/FirebaseApiNotAvailableException.java index 263e3035e2..d480463fb0 100644 --- a/auth/src_java/fake/com/google/firebase/FirebaseApiNotAvailableException.java +++ b/auth/src_java/fake/com/google/firebase/FirebaseApiNotAvailableException.java @@ -18,7 +18,6 @@ /** Fake FirebaseApiNotAvailableException */ public class FirebaseApiNotAvailableException extends FirebaseException { - public FirebaseApiNotAvailableException(String message) { super(message); } diff --git a/auth/src_java/fake/com/google/firebase/FirebaseNetworkException.java b/auth/src_java/fake/com/google/firebase/FirebaseNetworkException.java index 80571d4871..eda0365450 100644 --- a/auth/src_java/fake/com/google/firebase/FirebaseNetworkException.java +++ b/auth/src_java/fake/com/google/firebase/FirebaseNetworkException.java @@ -18,7 +18,6 @@ /** Fake FirebaseNetworkException */ public class FirebaseNetworkException extends FirebaseException { - public FirebaseNetworkException(String message) { super(message); } diff --git a/auth/src_java/fake/com/google/firebase/FirebaseTooManyRequestsException.java b/auth/src_java/fake/com/google/firebase/FirebaseTooManyRequestsException.java index 339c566a92..ef4aa8a84d 100644 --- a/auth/src_java/fake/com/google/firebase/FirebaseTooManyRequestsException.java +++ b/auth/src_java/fake/com/google/firebase/FirebaseTooManyRequestsException.java @@ -18,7 +18,6 @@ /** Fake FirebaseTooManyRequestsException */ public class FirebaseTooManyRequestsException extends FirebaseException { - public FirebaseTooManyRequestsException(String message) { super(message); } diff --git a/auth/src_java/fake/com/google/firebase/auth/AdditionalUserInfo.java b/auth/src_java/fake/com/google/firebase/auth/AdditionalUserInfo.java index c4eaeb29cf..4761c2c135 100644 --- a/auth/src_java/fake/com/google/firebase/auth/AdditionalUserInfo.java +++ b/auth/src_java/fake/com/google/firebase/auth/AdditionalUserInfo.java @@ -20,7 +20,6 @@ /** Fake AdditionalUserInfo */ public final class AdditionalUserInfo { - public String getProviderId() { return "fake provider id"; } diff --git a/auth/src_java/fake/com/google/firebase/auth/AuthCredential.java b/auth/src_java/fake/com/google/firebase/auth/AuthCredential.java index 8022311410..e52aa30f31 100644 --- a/auth/src_java/fake/com/google/firebase/auth/AuthCredential.java +++ b/auth/src_java/fake/com/google/firebase/auth/AuthCredential.java @@ -20,8 +20,10 @@ public final class AuthCredential { private String provider; - /** C++ code does not rely on any constructor. This is solely for fake to specify provider and - * does not map to a constructor in the real AuthCredential. */ + /** + * C++ code does not rely on any constructor. This is solely for fake to specify provider and + * does not map to a constructor in the real AuthCredential. + */ AuthCredential(String provider) { this.provider = provider; } diff --git a/auth/src_java/fake/com/google/firebase/auth/AuthResult.java b/auth/src_java/fake/com/google/firebase/auth/AuthResult.java index fa3bf9fa92..3d5c6da4af 100644 --- a/auth/src_java/fake/com/google/firebase/auth/AuthResult.java +++ b/auth/src_java/fake/com/google/firebase/auth/AuthResult.java @@ -18,7 +18,6 @@ /** Fake AuthResult */ public final class AuthResult { - FirebaseUser getUser() { return new FirebaseUser(); } diff --git a/auth/src_java/fake/com/google/firebase/auth/EmailAuthProvider.java b/auth/src_java/fake/com/google/firebase/auth/EmailAuthProvider.java index c785cfb7aa..96171dcb49 100644 --- a/auth/src_java/fake/com/google/firebase/auth/EmailAuthProvider.java +++ b/auth/src_java/fake/com/google/firebase/auth/EmailAuthProvider.java @@ -18,7 +18,6 @@ /** Fake EmailAuthProvider */ public final class EmailAuthProvider { - public static AuthCredential getCredential(String email, String password) { return new AuthCredential("password"); } diff --git a/auth/src_java/fake/com/google/firebase/auth/FacebookAuthProvider.java b/auth/src_java/fake/com/google/firebase/auth/FacebookAuthProvider.java index ee9997561b..1973bc4e22 100644 --- a/auth/src_java/fake/com/google/firebase/auth/FacebookAuthProvider.java +++ b/auth/src_java/fake/com/google/firebase/auth/FacebookAuthProvider.java @@ -18,7 +18,6 @@ /** Fake FacebookAuthProvider */ public final class FacebookAuthProvider { - public static AuthCredential getCredential(String accessToken) { return new AuthCredential("facebook.com"); } diff --git a/auth/src_java/fake/com/google/firebase/auth/FirebaseAuth.java b/auth/src_java/fake/com/google/firebase/auth/FirebaseAuth.java index 6a02beeea3..3dabb3aa90 100644 --- a/auth/src_java/fake/com/google/firebase/auth/FirebaseAuth.java +++ b/auth/src_java/fake/com/google/firebase/auth/FirebaseAuth.java @@ -106,15 +106,13 @@ private void randomDelayThread() { public void addAuthStateListener(final AuthStateListener listener) { authStateListeners.add(listener); - new Thread( - new Runnable() { - @Override - public void run() { - randomDelayThread(); - listener.onAuthStateChanged(FirebaseAuth.this); - } - }) - .start(); + new Thread(new Runnable() { + @Override + public void run() { + randomDelayThread(); + listener.onAuthStateChanged(FirebaseAuth.this); + } + }).start(); } public void removeAuthStateListener(AuthStateListener listener) { @@ -123,15 +121,13 @@ public void removeAuthStateListener(AuthStateListener listener) { public void addIdTokenListener(final IdTokenListener listener) { idTokenListeners.add(listener); - new Thread( - new Runnable() { - @Override - public void run() { - randomDelayThread(); - listener.onIdTokenChanged(FirebaseAuth.this); - } - }) - .start(); + new Thread(new Runnable() { + @Override + public void run() { + randomDelayThread(); + listener.onIdTokenChanged(FirebaseAuth.this); + } + }).start(); } public void removeIdTokenListener(IdTokenListener listener) { @@ -152,7 +148,7 @@ public String getLanguageCode() { /** Sets the user-facing language code to be the default app language. */ public void useAppLanguage() { - languageCode = "en-US"; + languageCode = "en-US"; } public Task fetchSignInMethodsForEmail(String email) { diff --git a/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthActionCodeException.java b/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthActionCodeException.java index 30cc2e5398..fc9251d0c7 100644 --- a/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthActionCodeException.java +++ b/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthActionCodeException.java @@ -18,7 +18,6 @@ /** Fake FirebaseAuthActionCodeException */ public class FirebaseAuthActionCodeException extends FirebaseAuthException { - public FirebaseAuthActionCodeException(String code, String message) { super(code, message); } diff --git a/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthEmailException.java b/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthEmailException.java index e1d46ad849..f2cf1aa54c 100644 --- a/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthEmailException.java +++ b/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthEmailException.java @@ -18,7 +18,6 @@ /** Fake FirebaseAuthEmailException */ public class FirebaseAuthEmailException extends FirebaseAuthException { - public FirebaseAuthEmailException(String code, String message) { super(code, message); } diff --git a/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthException.java b/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthException.java index f519095c5a..12850e1916 100644 --- a/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthException.java +++ b/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthException.java @@ -20,7 +20,6 @@ /** Fake FirebaseAuthException */ public class FirebaseAuthException extends FirebaseException { - public FirebaseAuthException(String code, String message) { super(message); code_ = code; diff --git a/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthInvalidCredentialsException.java b/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthInvalidCredentialsException.java index 8e37cda351..75f5a611d3 100644 --- a/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthInvalidCredentialsException.java +++ b/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthInvalidCredentialsException.java @@ -18,7 +18,6 @@ /** Fake FirebaseAuthInvalidCredentialsException */ public class FirebaseAuthInvalidCredentialsException extends FirebaseAuthException { - public FirebaseAuthInvalidCredentialsException(String code, String message) { super(code, message); } diff --git a/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthInvalidUserException.java b/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthInvalidUserException.java index 30566fa193..b3d298603b 100644 --- a/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthInvalidUserException.java +++ b/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthInvalidUserException.java @@ -18,7 +18,6 @@ /** Fake FirebaseAuthInvalidUserException */ public final class FirebaseAuthInvalidUserException extends FirebaseAuthException { - public FirebaseAuthInvalidUserException(String code, String message) { super(code, message); } diff --git a/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthRecentLoginRequiredException.java b/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthRecentLoginRequiredException.java index e1a7cecd13..36b47b7821 100644 --- a/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthRecentLoginRequiredException.java +++ b/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthRecentLoginRequiredException.java @@ -18,7 +18,6 @@ /** Fake FirebaseAuthRecentLoginRequiredException */ public class FirebaseAuthRecentLoginRequiredException extends FirebaseAuthException { - public FirebaseAuthRecentLoginRequiredException(String code, String message) { super(code, message); } diff --git a/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthUserCollisionException.java b/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthUserCollisionException.java index 63e94ce39d..0e0b1df30d 100644 --- a/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthUserCollisionException.java +++ b/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthUserCollisionException.java @@ -18,7 +18,6 @@ /** Fake FirebaseAuthUserCollisionException */ public class FirebaseAuthUserCollisionException extends FirebaseAuthException { - public FirebaseAuthUserCollisionException(String code, String message) { super(code, message); } diff --git a/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthWeakPasswordException.java b/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthWeakPasswordException.java index acfb84ebc5..4f31f28efe 100644 --- a/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthWeakPasswordException.java +++ b/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthWeakPasswordException.java @@ -18,7 +18,6 @@ /** Fake FirebaseAuthWeakPasswordException */ public class FirebaseAuthWeakPasswordException extends FirebaseAuthInvalidCredentialsException { - public FirebaseAuthWeakPasswordException(String code, String message) { super(code, message); } diff --git a/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthWebException.java b/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthWebException.java index 8260a51a76..94f12e68b0 100644 --- a/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthWebException.java +++ b/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthWebException.java @@ -18,7 +18,6 @@ /** Fake FirebaseAuthWebException */ public class FirebaseAuthWebException extends FirebaseAuthException { - public FirebaseAuthWebException(String code, String message) { super(code, message); } diff --git a/auth/src_java/fake/com/google/firebase/auth/FirebaseUser.java b/auth/src_java/fake/com/google/firebase/auth/FirebaseUser.java index 753371f789..94dcc3a997 100644 --- a/auth/src_java/fake/com/google/firebase/auth/FirebaseUser.java +++ b/auth/src_java/fake/com/google/firebase/auth/FirebaseUser.java @@ -46,13 +46,12 @@ public Task updateEmail(String email) { ConfigRow row = ConfigAndroid.get(configKey); if (!row.futuregeneric().throwexception()) { - result.addListener( - new FakeListener() { - @Override - public void onSuccess(Void res) { - FirebaseUser.this.email = email; - } - }); + result.addListener(new FakeListener() { + @Override + public void onSuccess(Void res) { + FirebaseUser.this.email = email; + } + }); } TickerAndroid.register(result); @@ -181,7 +180,6 @@ public Task startActivityForReauthenticateWithProvider( return result; } - public Task delete() { Task result = Task.forResult("FirebaseUser.delete", null); TickerAndroid.register(result); diff --git a/auth/src_java/fake/com/google/firebase/auth/FirebaseUserMetadata.java b/auth/src_java/fake/com/google/firebase/auth/FirebaseUserMetadata.java index 6f214cad5b..2ada88e1f0 100644 --- a/auth/src_java/fake/com/google/firebase/auth/FirebaseUserMetadata.java +++ b/auth/src_java/fake/com/google/firebase/auth/FirebaseUserMetadata.java @@ -18,7 +18,6 @@ /** Holds the user metadata for the current {@link FirebaseUser} */ public class FirebaseUserMetadata { - /** Fake timestamp returned that's non-zero. */ public long getLastSignInTimestamp() { return 1; diff --git a/auth/src_java/fake/com/google/firebase/auth/GetTokenResult.java b/auth/src_java/fake/com/google/firebase/auth/GetTokenResult.java index b925fc7627..2afac9255f 100644 --- a/auth/src_java/fake/com/google/firebase/auth/GetTokenResult.java +++ b/auth/src_java/fake/com/google/firebase/auth/GetTokenResult.java @@ -18,7 +18,6 @@ /** Fake GetTokenResult */ public final class GetTokenResult { - public String getToken() { return "a fake token"; } diff --git a/auth/src_java/fake/com/google/firebase/auth/GithubAuthProvider.java b/auth/src_java/fake/com/google/firebase/auth/GithubAuthProvider.java index 8f08b9df4c..58d1b6c422 100644 --- a/auth/src_java/fake/com/google/firebase/auth/GithubAuthProvider.java +++ b/auth/src_java/fake/com/google/firebase/auth/GithubAuthProvider.java @@ -18,7 +18,6 @@ /** Fake GithubAuthProvider */ public final class GithubAuthProvider { - public static AuthCredential getCredential(String accessToken) { return new AuthCredential("github.com"); } diff --git a/auth/src_java/fake/com/google/firebase/auth/GoogleAuthProvider.java b/auth/src_java/fake/com/google/firebase/auth/GoogleAuthProvider.java index ad9b327934..9bf9d20011 100644 --- a/auth/src_java/fake/com/google/firebase/auth/GoogleAuthProvider.java +++ b/auth/src_java/fake/com/google/firebase/auth/GoogleAuthProvider.java @@ -18,7 +18,6 @@ /** Fake GoogleAuthProvider */ public final class GoogleAuthProvider { - public static AuthCredential getCredential(String idToken, String accessToken) { return new AuthCredential("google.com"); } diff --git a/auth/src_java/fake/com/google/firebase/auth/OAuthProvider.java b/auth/src_java/fake/com/google/firebase/auth/OAuthProvider.java index 32867a4aca..b14d85326f 100644 --- a/auth/src_java/fake/com/google/firebase/auth/OAuthProvider.java +++ b/auth/src_java/fake/com/google/firebase/auth/OAuthProvider.java @@ -21,7 +21,6 @@ /** Fake FakeOAuthProvider */ public final class OAuthProvider extends FederatedAuthProvider { - public static AuthCredential getCredential( String providerId, String idToken, String accessToken) { return new AuthCredential(providerId); @@ -37,7 +36,6 @@ public static OAuthProvider.Builder newBuilder(String providerId, FirebaseAuth f /** Class used to create instances of {@link OAuthProvider}. */ public static class Builder { - /* Fake constructor */ private Builder() {} @@ -91,7 +89,6 @@ public static CredentialBuilder newCredentialBuilder(String providerId) { /** Builder class to initialize {@link AuthCredential}'s. */ public static class CredentialBuilder { - private final String providerId; /** diff --git a/auth/src_java/fake/com/google/firebase/auth/PhoneAuthProvider.java b/auth/src_java/fake/com/google/firebase/auth/PhoneAuthProvider.java index 84b10a73a9..9f89725282 100644 --- a/auth/src_java/fake/com/google/firebase/auth/PhoneAuthProvider.java +++ b/auth/src_java/fake/com/google/firebase/auth/PhoneAuthProvider.java @@ -22,7 +22,6 @@ /** Fake PhoneAuthProvider */ public class PhoneAuthProvider { - /** Fake OnVerificationStateChangedCallbacks */ public abstract static class OnVerificationStateChangedCallbacks { public abstract void onVerificationCompleted(PhoneAuthCredential credential); @@ -41,16 +40,10 @@ public static PhoneAuthProvider getInstance(FirebaseAuth firebaseAuth) { return null; } - public static PhoneAuthCredential getCredential( - String verificationId, String smsCode) { + public static PhoneAuthCredential getCredential(String verificationId, String smsCode) { return null; } - public void verifyPhoneNumber( - String phoneNumber, - long timeout, - TimeUnit unit, - Activity activity, - OnVerificationStateChangedCallbacks callbacks, - ForceResendingToken forceResendingToken) {} + public void verifyPhoneNumber(String phoneNumber, long timeout, TimeUnit unit, Activity activity, + OnVerificationStateChangedCallbacks callbacks, ForceResendingToken forceResendingToken) {} } diff --git a/auth/src_java/fake/com/google/firebase/auth/PlayGamesAuthProvider.java b/auth/src_java/fake/com/google/firebase/auth/PlayGamesAuthProvider.java index b5da4c3cf2..4ba6a0b54b 100644 --- a/auth/src_java/fake/com/google/firebase/auth/PlayGamesAuthProvider.java +++ b/auth/src_java/fake/com/google/firebase/auth/PlayGamesAuthProvider.java @@ -16,9 +16,8 @@ package com.google.firebase.auth; -/** Fake PlayGamesAuthProvider */ +/** Fake PlayGamesAuthProvider */ class PlayGamesAuthProvider { - public static AuthCredential getCredential(String authCode) { return new AuthCredential("playgames.google.com"); } diff --git a/auth/src_java/fake/com/google/firebase/auth/SignInMethodQueryResult.java b/auth/src_java/fake/com/google/firebase/auth/SignInMethodQueryResult.java index d0ba463a8f..1828098932 100644 --- a/auth/src_java/fake/com/google/firebase/auth/SignInMethodQueryResult.java +++ b/auth/src_java/fake/com/google/firebase/auth/SignInMethodQueryResult.java @@ -20,7 +20,6 @@ /** Fake SignInMethodQueryResult */ public final class SignInMethodQueryResult { - List getSignInMethods() { return null; } diff --git a/auth/src_java/fake/com/google/firebase/auth/TwitterAuthProvider.java b/auth/src_java/fake/com/google/firebase/auth/TwitterAuthProvider.java index c3358e7c20..34afac07bb 100644 --- a/auth/src_java/fake/com/google/firebase/auth/TwitterAuthProvider.java +++ b/auth/src_java/fake/com/google/firebase/auth/TwitterAuthProvider.java @@ -18,7 +18,6 @@ /** Fake TwitterAuthProvider */ public final class TwitterAuthProvider { - public static AuthCredential getCredential(String token, String secret) { return new AuthCredential("twitter.com"); } diff --git a/auth/src_java/fake/com/google/firebase/auth/UserProfileChangeRequest.java b/auth/src_java/fake/com/google/firebase/auth/UserProfileChangeRequest.java index dfab7c05b0..4afe8fce1d 100644 --- a/auth/src_java/fake/com/google/firebase/auth/UserProfileChangeRequest.java +++ b/auth/src_java/fake/com/google/firebase/auth/UserProfileChangeRequest.java @@ -20,7 +20,6 @@ /** Fake UserProfileChangeRequest$Builder */ public final class UserProfileChangeRequest { - /** Builder */ public static class Builder { public Builder setDisplayName(String displayName) { diff --git a/database/src/include/firebase/database/database_reference.h b/database/src/include/firebase/database/database_reference.h index f403dc24d8..3e746541a1 100644 --- a/database/src/include/firebase/database/database_reference.h +++ b/database/src/include/firebase/database/database_reference.h @@ -17,12 +17,13 @@ #include #include -#include "firebase/future.h" -#include "firebase/internal/common.h" -#include "firebase/variant.h" + #include "firebase/database/disconnection.h" #include "firebase/database/query.h" #include "firebase/database/transaction.h" +#include "firebase/future.h" +#include "firebase/internal/common.h" +#include "firebase/variant.h" namespace firebase { namespace database { diff --git a/database/src/include/firebase/database/query.h b/database/src/include/firebase/database/query.h index 8611f4d147..861bdd505a 100644 --- a/database/src/include/firebase/database/query.h +++ b/database/src/include/firebase/database/query.h @@ -16,9 +16,10 @@ #define FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_QUERY_H_ #include + +#include "firebase/database/listener.h" #include "firebase/future.h" #include "firebase/internal/common.h" -#include "firebase/database/listener.h" namespace firebase { namespace database { diff --git a/database/src_java/com/google/firebase/database/internal/cpp/CppTransactionHandler.java b/database/src_java/com/google/firebase/database/internal/cpp/CppTransactionHandler.java index aadf0d5dee..56025c8df1 100644 --- a/database/src_java/com/google/firebase/database/internal/cpp/CppTransactionHandler.java +++ b/database/src_java/com/google/firebase/database/internal/cpp/CppTransactionHandler.java @@ -74,10 +74,6 @@ private static native MutableData nativeDoTransaction( long databaseObject, long transactionObject, MutableData currentData); /** This native function is implemented in the Firebase Database C++ library (util_android.cc). */ - private static native void nativeOnComplete( - long databaseObject, - long transactionObject, - DatabaseError error, - boolean committed, - DataSnapshot currentData); + private static native void nativeOnComplete(long databaseObject, long transactionObject, + DatabaseError error, boolean committed, DataSnapshot currentData); } diff --git a/dynamic_links/src/dynamic_links_ios.mm b/dynamic_links/src/dynamic_links_ios.mm index b86b861b2b..5e707fcfa7 100644 --- a/dynamic_links/src/dynamic_links_ios.mm +++ b/dynamic_links/src/dynamic_links_ios.mm @@ -64,42 +64,42 @@ void Terminate() { // Encode a URL from a C string. If this fails, nil is returned. static NSURL* EncodeUrlFromString(const char* url_string) { // Try encoding without escaping as the URL may already be escaped correctly. - NSURL*url = [NSURL URLWithString:@(url_string)]; + NSURL* url = [NSURL URLWithString:@(url_string)]; if (url) return url; // If encoding without escaping fails, try again with percent encoding. - return [NSURL URLWithString:[@(url_string) - stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; + return [NSURL + URLWithString:[@(url_string) stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; } // Add a warning to the list of warnings regarding failure to encode the specified // URL. -static void AddUrlEncodingWarning( - std::vector* warnings, const char* url, const char* field_description) { - warnings->push_back(std::string("Failed to encode URL for ") + - std::string(field_description) + ", URL: " + url); +static void AddUrlEncodingWarning(std::vector* warnings, const char* url, + const char* field_description) { + warnings->push_back(std::string("Failed to encode URL for ") + std::string(field_description) + + ", URL: " + url); } // Set a URL field of an iOS dynamic link components object from a C++ structure string field. #define FIR_DYNAMIC_LINK_PARAMS_SET_URL(fir_params_object, field, cpp_params_object, cpp_field, \ - field_description, generated_link_warnings) \ - { \ - if ((cpp_params_object)->cpp_field) { \ - NSURL* ns_url = EncodeUrlFromString((cpp_params_object)->cpp_field); \ - if (ns_url) { \ - (fir_params_object).field = ns_url; \ - } else { \ - AddUrlEncodingWarning(generated_link_warnings, (cpp_params_object)->cpp_field, \ - field_description); \ - } \ - } \ + field_description, generated_link_warnings) \ + { \ + if ((cpp_params_object)->cpp_field) { \ + NSURL* ns_url = EncodeUrlFromString((cpp_params_object)->cpp_field); \ + if (ns_url) { \ + (fir_params_object).field = ns_url; \ + } else { \ + AddUrlEncodingWarning(generated_link_warnings, (cpp_params_object)->cpp_field, \ + field_description); \ + } \ + } \ } // Set a string field of an iOS dynamic link components object from a C++ structure string field. #define FIR_DYNAMIC_LINK_PARAMS_SET_STRING(fir_params_object, field, cpp_params_object, cpp_field) \ - { \ - if ((cpp_params_object)->cpp_field) { \ - (fir_params_object).field = @((cpp_params_object)->cpp_field); \ - } \ + { \ + if ((cpp_params_object)->cpp_field) { \ + (fir_params_object).field = @((cpp_params_object)->cpp_field); \ + } \ } // Construct FIRDynamicLinkComponents and populate GeneratedDynamicLink from DynamicLinkComponents. @@ -111,11 +111,10 @@ static void AddUrlEncodingWarning( return nil; } if (!components.domain_uri_prefix || !*components.domain_uri_prefix) { - generated_link->error = - std::string("Domain URI Prefix ") + kMissingFieldPostfix; + generated_link->error = std::string("Domain URI Prefix ") + kMissingFieldPostfix; return nil; } - NSURL *link_url = EncodeUrlFromString(components.link); + NSURL* link_url = EncodeUrlFromString(components.link); if (!link_url) { generated_link->error = kUrlEncodingError; return nil; @@ -172,8 +171,8 @@ static void AddUrlEncodingWarning( auto* cpp_params = components.android_parameters; if (cpp_params) { if (!cpp_params->package_name) { - generated_link->error = std::string("Android parameters package name ") + - kMissingFieldPostfix; + generated_link->error = + std::string("Android parameters package name ") + kMissingFieldPostfix; return nil; } FIRDynamicLinkAndroidParameters* fir_params = @@ -232,75 +231,68 @@ GeneratedDynamicLink GetLongLink(const DynamicLinkComponents& components) { } // Generate a short link from a long dynamic link. -static Future GetShortLink(NSURL *long_link_url, +static Future GetShortLink(NSURL* long_link_url, const GeneratedDynamicLink& generated_link, const DynamicLinkOptions& dynamic_link_options) { - FIREBASE_ASSERT_RETURN(Future(), - internal::IsInitialized()); + FIREBASE_ASSERT_RETURN(Future(), internal::IsInitialized()); ReferenceCountedFutureImpl* api = FutureData::Get()->api(); const SafeFutureHandle handle = api->SafeAlloc(kDynamicLinksFnGetShortLink); if (long_link_url) { GeneratedDynamicLink* output_generated_link = new GeneratedDynamicLink(); *output_generated_link = generated_link; - [FIRDynamicLinkComponents shortenURL:long_link_url - options:ToFIRDynamicLinkComponentsOptions(dynamic_link_options) - completion:^(NSURL * _Nullable shortURL, - NSArray * _Nullable warnings, - NSError * _Nullable error) { - int error_code = kErrorCodeSuccess; - if (error) { - error_code = error.code ? static_cast(error.code) : kErrorCodeFailed; - output_generated_link->error = util::NSStringToString(error.localizedDescription); - } else { - if (warnings) { - for (NSString* warning in warnings) { - output_generated_link->warnings.push_back(warning.UTF8String); - } - } - if (shortURL) { - output_generated_link->url = util::NSStringToString(shortURL.absoluteString); + [FIRDynamicLinkComponents + shortenURL:long_link_url + options:ToFIRDynamicLinkComponentsOptions(dynamic_link_options) + completion:^(NSURL* _Nullable shortURL, NSArray* _Nullable warnings, + NSError* _Nullable error) { + int error_code = kErrorCodeSuccess; + if (error) { + error_code = error.code ? static_cast(error.code) : kErrorCodeFailed; + output_generated_link->error = util::NSStringToString(error.localizedDescription); } else { - error_code = kErrorCodeFailed; - output_generated_link->error = std::string("Failed to shorten link ") + - output_generated_link->url; + if (warnings) { + for (NSString* warning in warnings) { + output_generated_link->warnings.push_back(warning.UTF8String); + } + } + if (shortURL) { + output_generated_link->url = util::NSStringToString(shortURL.absoluteString); + } else { + error_code = kErrorCodeFailed; + output_generated_link->error = + std::string("Failed to shorten link ") + output_generated_link->url; + } } - } - FutureData::Get()->api()->CompleteWithResult( - handle, error_code, output_generated_link->error.c_str(), *output_generated_link); - delete output_generated_link; - }]; + FutureData::Get()->api()->CompleteWithResult( + handle, error_code, output_generated_link->error.c_str(), *output_generated_link); + delete output_generated_link; + }]; } else { - api->CompleteWithResult(handle, kErrorCodeFailed, generated_link.error.c_str(), - generated_link); + api->CompleteWithResult(handle, kErrorCodeFailed, generated_link.error.c_str(), generated_link); } return MakeFuture(api, handle); } -Future GetShortLink( - const DynamicLinkComponents& components, - const DynamicLinkOptions& dynamic_link_options) { - FIREBASE_ASSERT_RETURN(Future(), - internal::IsInitialized()); +Future GetShortLink(const DynamicLinkComponents& components, + const DynamicLinkOptions& dynamic_link_options) { + FIREBASE_ASSERT_RETURN(Future(), internal::IsInitialized()); GeneratedDynamicLink generated_link; - FIRDynamicLinkComponents* fir_components = GetFIRComponentsAndGeneratedLink(components, - &generated_link); + FIRDynamicLinkComponents* fir_components = + GetFIRComponentsAndGeneratedLink(components, &generated_link); return GetShortLink(fir_components ? fir_components.url : nil, generated_link, dynamic_link_options); } -Future GetShortLink( - const DynamicLinkComponents& components) { +Future GetShortLink(const DynamicLinkComponents& components) { return GetShortLink(components, DynamicLinkOptions()); } -Future GetShortLink( - const char* long_dynamic_link, - const DynamicLinkOptions& dynamic_link_options) { - FIREBASE_ASSERT_RETURN(Future(), - internal::IsInitialized()); +Future GetShortLink(const char* long_dynamic_link, + const DynamicLinkOptions& dynamic_link_options) { + FIREBASE_ASSERT_RETURN(Future(), internal::IsInitialized()); GeneratedDynamicLink generated_link; - NSURL *link_url = EncodeUrlFromString(long_dynamic_link); + NSURL* link_url = EncodeUrlFromString(long_dynamic_link); if (!link_url) generated_link.error = kUrlEncodingError; return GetShortLink(link_url, generated_link, dynamic_link_options); } @@ -310,8 +302,7 @@ GeneratedDynamicLink GetLongLink(const DynamicLinkComponents& components) { } Future GetShortLinkLastResult() { - FIREBASE_ASSERT_RETURN(Future(), - internal::IsInitialized()); + FIREBASE_ASSERT_RETURN(Future(), internal::IsInitialized()); ReferenceCountedFutureImpl* api = FutureData::Get()->api(); return static_cast&>( api->LastResult(kDynamicLinksFnGetShortLink)); diff --git a/firestore/src/common/settings_apple.mm b/firestore/src/common/settings_apple.mm index 7a1deb2a4d..57856d16fc 100644 --- a/firestore/src/common/settings_apple.mm +++ b/firestore/src/common/settings_apple.mm @@ -18,8 +18,8 @@ #include -#include "absl/memory/memory.h" #include "Firestore/core/src/util/executor_libdispatch.h" +#include "absl/memory/memory.h" namespace firebase { namespace firestore { @@ -35,7 +35,8 @@ Settings::Settings() : host_(kDefaultHost), - executor_(Executor::CreateSerial("com.google.firebase.firestore.callback")) {} + executor_( + Executor::CreateSerial("com.google.firebase.firestore.callback")) {} std::unique_ptr Settings::CreateExecutor() const { return absl::make_unique(dispatch_queue()); @@ -45,7 +46,8 @@ if (!executor_) { return dispatch_get_main_queue(); } - auto* executor_libdispatch = static_cast(executor_.get()); + auto* executor_libdispatch = + static_cast(executor_.get()); return executor_libdispatch->dispatch_queue(); } diff --git a/firestore/src/main/create_credentials_provider_ios.mm b/firestore/src/main/create_credentials_provider_ios.mm index 7e50f6f489..c8eee6e0c3 100644 --- a/firestore/src/main/create_credentials_provider_ios.mm +++ b/firestore/src/main/create_credentials_provider_ios.mm @@ -16,12 +16,12 @@ #include "firestore/src/main/create_credentials_provider.h" -#import "FirebaseCoreInternal.h" #import "FIRAuthInterop.h" +#import "FirebaseCoreInternal.h" -#include "app/src/include/firebase/app.h" -#include "absl/memory/memory.h" #include "Firestore/core/src/credentials/firebase_auth_credentials_provider_apple.h" +#include "absl/memory/memory.h" +#include "app/src/include/firebase/app.h" namespace firebase { namespace firestore { diff --git a/firestore/src/main/create_firebase_metadata_provider_ios.mm b/firestore/src/main/create_firebase_metadata_provider_ios.mm index 904bf406e3..1161bcb836 100644 --- a/firestore/src/main/create_firebase_metadata_provider_ios.mm +++ b/firestore/src/main/create_firebase_metadata_provider_ios.mm @@ -16,9 +16,9 @@ #include "firestore/src/main/create_firebase_metadata_provider.h" -#include "app/src/include/firebase/app.h" #include "Firestore/core/src/remote/firebase_metadata_provider_apple.h" #include "absl/memory/memory.h" +#include "app/src/include/firebase/app.h" namespace firebase { namespace firestore { @@ -26,7 +26,8 @@ using remote::FirebaseMetadataProvider; using remote::FirebaseMetadataProviderApple; -std::unique_ptr CreateFirebaseMetadataProvider(App& app) { +std::unique_ptr CreateFirebaseMetadataProvider( + App& app) { return absl::make_unique(app.GetPlatformApp()); } diff --git a/firestore/src_java/com/google/firebase/firestore/internal/cpp/DocumentEventListener.java b/firestore/src_java/com/google/firebase/firestore/internal/cpp/DocumentEventListener.java index 85eb3e8358..e72595d96b 100644 --- a/firestore/src_java/com/google/firebase/firestore/internal/cpp/DocumentEventListener.java +++ b/firestore/src_java/com/google/firebase/firestore/internal/cpp/DocumentEventListener.java @@ -23,44 +23,47 @@ /** * Implements Firestore {@code - * firebase::firestore::EventListener} by redirecting calls - * into the C++ equivalent. + * firebase::firestore::EventListener} by + * redirecting calls into the C++ equivalent. */ -public class DocumentEventListener extends CppEventListener - implements EventListener { +public class DocumentEventListener + extends CppEventListener implements EventListener { /** - * Constructs a DocumentEventListener. Ownership of the underlying EventListener can be - * transferred when creating the {@code ListenerRegistration}. If the ListenerRegistration owns - * the EventListener, it will de-allocate the EventListener in its destructor. + * Constructs a DocumentEventListener. Ownership of the underlying + * EventListener can be transferred when creating the {@code + * ListenerRegistration}. If the ListenerRegistration owns the EventListener, + * it will de-allocate the EventListener in its destructor. * - *

Passing in 0 is considered a null pointer and will result in {@code onEvent} becoming a - * no-op. + *

Passing in 0 is considered a null pointer and will result in {@code + * onEvent} becoming a no-op. * - * @param cppFirestoreObject Pointer to a {@code firebase::firestore::Firestore}. + * @param cppFirestoreObject Pointer to a {@code + * firebase::firestore::Firestore}. * @param cppListenerObject Pointer to a {@code * firebase::firestore::EventListener}. */ - public DocumentEventListener(long cppFirestoreObject, long cppListenerObject) { + public DocumentEventListener( + long cppFirestoreObject, long cppListenerObject) { super(cppFirestoreObject, cppListenerObject); } @Override - public synchronized void onEvent( - @Nullable DocumentSnapshot value, @Nullable FirebaseFirestoreException error) { - nativeOnEvent(cppFirestoreObject, cppListenerObject, value, error); + public synchronized void onEvent(@Nullable DocumentSnapshot value, + @Nullable FirebaseFirestoreException error) { + nativeOnEvent(cppFirestoreObject, cppListenerObject, value, error); } /** * Interprets the {@code listenerObject} as a {@code - * firebase::firestore::EventListener} and invokes the listener's {@code - * OnEvent} method with the {@code error} and {@code DocumentSnapshot} created by interpreting the + * firebase::firestore::EventListener} and invokes the + * listener's {@code OnEvent} method with the {@code error} and {@code + * DocumentSnapshot} created by interpreting the * {@code firestoreObject} as a {@code firebase::firestore::Firestore}. * *

This native method is implemented in the Firestore C++ library {@code * event_listener_android.cc}. */ - private static native void nativeOnEvent( - long firestoreObject, + private static native void nativeOnEvent(long firestoreObject, long listenerObject, @Nullable Object value, @Nullable FirebaseFirestoreException error); diff --git a/firestore/src_java/com/google/firebase/firestore/internal/cpp/Dummy.java b/firestore/src_java/com/google/firebase/firestore/internal/cpp/Dummy.java index 4a4b69e52c..a42a85692e 100644 --- a/firestore/src_java/com/google/firebase/firestore/internal/cpp/Dummy.java +++ b/firestore/src_java/com/google/firebase/firestore/internal/cpp/Dummy.java @@ -17,7 +17,8 @@ package com.google.firebase.firestore.internal.cpp; /** - * Place-holder dummy Java class for Firestore C++ Android clients. This is currently being used to - * prevent Tricorder errors since we do not have desktop support yet. + * Place-holder dummy Java class for Firestore C++ Android clients. This is + * currently being used to prevent Tricorder errors since we do not have desktop + * support yet. */ public class Dummy {} diff --git a/firestore/src_java/com/google/firebase/firestore/internal/cpp/FirestoreTasks.java b/firestore/src_java/com/google/firebase/firestore/internal/cpp/FirestoreTasks.java index 2d44804737..856c9e4120 100644 --- a/firestore/src_java/com/google/firebase/firestore/internal/cpp/FirestoreTasks.java +++ b/firestore/src_java/com/google/firebase/firestore/internal/cpp/FirestoreTasks.java @@ -28,56 +28,61 @@ * Helper methods for working with {@link Task} objects from C++. */ public final class FirestoreTasks { - - private FirestoreTasks() { - } + private FirestoreTasks() {} /** - * Takes a {@link Task} and returns a new Task, whose result will be the same as the incoming Task, - * if the result is not null, otherwise fails the returned Task with given error message. + * Takes a {@link Task} and returns a new Task, whose result will be the same + * as the incoming Task, if the result is not null, otherwise fails the + * returned Task with given error message. */ - public static Task failTaskWhenResultIsNull(Task task, final String message) { - Continuation continuation = - new Continuation() { - @Override - public T then(Task task) throws Exception { - T result = task.getResult(); - if (result == null) { - throw new FirebaseFirestoreException(message, FirebaseFirestoreException.Code.NOT_FOUND); - } - return result; + public static Task failTaskWhenResultIsNull( + Task task, final String message) { + Continuation continuation = new Continuation() { + @Override + public T then(Task task) throws Exception { + T result = task.getResult(); + if (result == null) { + throw new FirebaseFirestoreException( + message, FirebaseFirestoreException.Code.NOT_FOUND); } - }; + return result; + } + }; return task.continueWith(continuation); } /** * Blocks the calling thread until the given {@link Task} has completed. * - *

This method is identical to {@link com.google.android.gms.tasks.Tasks#await} except that it - * does not throw an exception if invoked from the main thread. Since it is technically - * possible to wait for a {@link Task} from any thread in C++, throwing is undesirable if called - * from the main thread. + *

This method is identical to {@link + * com.google.android.gms.tasks.Tasks#await} except that it does not + * throw an exception if invoked from the main thread. Since it is technically + * possible to wait for a {@link Task} from any thread in C++, throwing is + * undesirable if called from the main thread. * - *

The result of the given {@link Task} (i.e. success or failure) is not considered by this - * method; whenever the task completes, either successfully or unsuccessfully, this method will - * return. + *

The result of the given {@link Task} (i.e. success or failure) is not + * considered by this method; whenever the task completes, either successfully + * or unsuccessfully, this method will return. * * @param task The task whose completion to await. - * @throws InterruptedException if waiting for the task to complete is interrupted. + * @throws InterruptedException if waiting for the task to complete is + * interrupted. */ - public static void awaitCompletion(Task task) throws InterruptedException { + public static void awaitCompletion(Task task) + throws InterruptedException { CountDownLatch countDownLatch = new CountDownLatch(1); ExecutorService executor = Executors.newSingleThreadExecutor(); try { - task.addOnCompleteListener(executor, new CountDownOnCompleteListener(countDownLatch)); + task.addOnCompleteListener( + executor, new CountDownOnCompleteListener(countDownLatch)); countDownLatch.await(); } finally { executor.shutdown(); } } - private static final class CountDownOnCompleteListener implements OnCompleteListener { + private static final class CountDownOnCompleteListener + implements OnCompleteListener { private final CountDownLatch countDownLatch; CountDownOnCompleteListener(CountDownLatch countDownLatch) { diff --git a/firestore/src_java/com/google/firebase/firestore/internal/cpp/JniRunnable.java b/firestore/src_java/com/google/firebase/firestore/internal/cpp/JniRunnable.java index d27ba170c1..30e519f386 100644 --- a/firestore/src_java/com/google/firebase/firestore/internal/cpp/JniRunnable.java +++ b/firestore/src_java/com/google/firebase/firestore/internal/cpp/JniRunnable.java @@ -23,7 +23,6 @@ /** A {@link Runnable} whose {@link #run} method calls a native function. */ public final class JniRunnable implements Runnable { - private final Object lock = new Object(); private long data; @@ -37,7 +36,7 @@ public JniRunnable(long data) { if (data == 0) { throw new IllegalArgumentException( "data==0 is forbidden because 0 is reserved to indicate that we are detached from the" - + " C++ function"); + + " C++ function"); } this.data = data; } @@ -45,15 +44,16 @@ public JniRunnable(long data) { /** * Invokes the C++ function encapsulated by this object. * - *

If {@link #detach} has been invoked then this method does nothing and returns as if - * successful. + *

If {@link #detach} has been invoked then this method does nothing and + * returns as if successful. */ @Override public void run() { - // NOTE: Because of the `synchronized` block below, the native function will not be called - // concurrently. If concurrent invocations are desired, then this class can be modified with a - // more complicated synchronization mechanism. - // e.g. https://gist.github.com/dconeybe/2d95fbc75f88de58a49804df5c55157b + // NOTE: Because of the `synchronized` block below, the native function will + // not be called concurrently. If concurrent invocations are desired, then + // this class can be modified with a more complicated synchronization + // mechanism. e.g. + // https://gist.github.com/dconeybe/2d95fbc75f88de58a49804df5c55157b synchronized (lock) { if (data == 0) { return; @@ -65,15 +65,16 @@ public void run() { /** * Releases the reference to native data. * - *

After this method returns, all future invocations of {@link #run} will do nothing and return - * as if successful. + *

After this method returns, all future invocations of {@link #run} will + * do nothing and return as if successful. * - *

This method blocks until all invocations of the native function called from {@link #run} - * complete; therefore, when this method returns it is safe to delete any data that would be - * referenced by the native function. + *

This method blocks until all invocations of the native function called + * from {@link #run} complete; therefore, when this method returns it is safe + * to delete any data that would be referenced by the native function. * - *

This method may be safely invoked multiple times. Subsequent invocations have no side - * effects but will still block while there are active invocations of the native function. + *

This method may be safely invoked multiple times. Subsequent invocations + * have no side effects but will still block while there are active + * invocations of the native function. */ public void detach() { synchronized (lock) { @@ -84,10 +85,12 @@ public void detach() { /** * Invokes {@link #run} on the main event thread. * - *

If the calling thread is the main event thread then {@link #run} is called synchronously. + *

If the calling thread is the main event thread then {@link #run} is + * called synchronously. * - * @return A {@link Task} that will complete after {@link #run} returns; if {@link #run} throws an - * exception, then that exception will be set as the exception of the task. + * @return A {@link Task} that will complete after {@link #run} returns; if + * {@link #run} throws an exception, then that exception will be set as + * the exception of the task. */ Task runOnMainThread() { TaskRunnable runnable = new TaskRunnable(); @@ -98,7 +101,8 @@ Task runOnMainThread() { Handler handler = new Handler(mainLooper); boolean postSucceeded = handler.post(runnable); if (!postSucceeded) { - runnable.setException(new RuntimeException("Handler.post() returned false")); + runnable.setException( + new RuntimeException("Handler.post() returned false")); } } return runnable.getTask(); @@ -107,8 +111,9 @@ Task runOnMainThread() { /** * Invokes {@link #run} on a newly-created thread. * - * @return A {@link Task} that will complete after {@link #run} returns; if {@link #run} throws an - * exception, then that exception will be set as the exception of the task. + * @return A {@link Task} that will complete after {@link #run} returns; if + * {@link #run} throws an exception, then that exception will be set as + * the exception of the task. */ Task runOnNewThread() { TaskRunnable runnable = new TaskRunnable(); @@ -119,14 +124,15 @@ Task runOnNewThread() { /** * Invokes the encapsulated C++ function. * - * @param data The data that was specified to the constructor, or {@code 0} if {@link #detach} has - * been called, in which case the native function should do nothing and return immediately. + * @param data The data that was specified to the constructor, or {@code 0} if + * {@link #detach} has been called, in which case the native function + * should do nothing and return immediately. */ private static native void nativeRun(long data); private final class TaskRunnable implements Runnable { - - private final TaskCompletionSource taskCompletionSource = new TaskCompletionSource<>(); + private final TaskCompletionSource taskCompletionSource = + new TaskCompletionSource<>(); @Override public void run() { diff --git a/firestore/src_java/com/google/firebase/firestore/internal/cpp/LoadBundleProgressListener.java b/firestore/src_java/com/google/firebase/firestore/internal/cpp/LoadBundleProgressListener.java index a16b4a6be0..af5c28a7b9 100644 --- a/firestore/src_java/com/google/firebase/firestore/internal/cpp/LoadBundleProgressListener.java +++ b/firestore/src_java/com/google/firebase/firestore/internal/cpp/LoadBundleProgressListener.java @@ -18,47 +18,48 @@ import androidx.annotation.Nullable; import com.google.firebase.firestore.EventListener; +import com.google.firebase.firestore.FirebaseFirestoreException; import com.google.firebase.firestore.LoadBundleTaskProgress; import com.google.firebase.firestore.OnProgressListener; -import com.google.firebase.firestore.FirebaseFirestoreException; /** * Implements Firestore {@code - * firebase::firestore::EventListener} by redirecting calls - * into the C++ equivalent. + * firebase::firestore::EventListener} + * by redirecting calls into the C++ equivalent. */ public class LoadBundleProgressListener extends CppEventListener implements OnProgressListener { /** * Constructs a ProgressEventListener. * - *

Passing in 0 is considered a null pointer and will result in {@code onEvent} becoming a - * no-op. + *

Passing in 0 is considered a null pointer and will result in {@code + * onEvent} becoming a no-op. * - * @param cppFirestoreObject Pointer to a {@code firebase::firestore::Firestore}. + * @param cppFirestoreObject Pointer to a {@code + * firebase::firestore::Firestore}. * @param cppListenerObject Pointer to a {@code * firebase::firestore::EventListener}. */ - public LoadBundleProgressListener(long cppFirestoreObject, long cppListenerObject) { + public LoadBundleProgressListener( + long cppFirestoreObject, long cppListenerObject) { super(cppFirestoreObject, cppListenerObject); } @Override public synchronized void onProgress( @Nullable LoadBundleTaskProgress progress) { - nativeOnProgress(cppFirestoreObject, cppListenerObject, progress); + nativeOnProgress(cppFirestoreObject, cppListenerObject, progress); } /** * Interprets the {@code listenerObject} as a {@code - * firebase::firestore::EventListener} and invokes the listener's {@code - * OnEvent} method with {@code value} interpreted as (@code LoadBundleTaskProgress). + * firebase::firestore::EventListener} and invokes the + * listener's {@code OnEvent} method with {@code value} interpreted as (@code + * LoadBundleTaskProgress). * *

This native method is implemented in the Firestore C++ library {@code * event_listener_android.cc}. */ private static native void nativeOnProgress( - long firestoreObject, - long listenerObject, - @Nullable Object value); + long firestoreObject, long listenerObject, @Nullable Object value); } diff --git a/firestore/src_java/com/google/firebase/firestore/internal/cpp/QueryEventListener.java b/firestore/src_java/com/google/firebase/firestore/internal/cpp/QueryEventListener.java index f812d8f9c5..83306b8799 100644 --- a/firestore/src_java/com/google/firebase/firestore/internal/cpp/QueryEventListener.java +++ b/firestore/src_java/com/google/firebase/firestore/internal/cpp/QueryEventListener.java @@ -23,19 +23,22 @@ /** * Implements Firestore {@code - * firebase::firestore::EventListener} by redirecting calls into - * the C++ equivalent. + * firebase::firestore::EventListener} by + * redirecting calls into the C++ equivalent. */ -public class QueryEventListener extends CppEventListener implements EventListener { +public class QueryEventListener + extends CppEventListener implements EventListener { /** - * Constructs a QueryEventListener. Ownership of the underlying EventListener can be transferred - * when creating the {@code ListenerRegistration}. If the ListenerRegistration owns the - * EventListener, it will de-allocate the EventListener in its destructor. + * Constructs a QueryEventListener. Ownership of the underlying EventListener + * can be transferred when creating the {@code ListenerRegistration}. If the + * ListenerRegistration owns the EventListener, it will de-allocate the + * EventListener in its destructor. * - *

Passing in 0 is considered a null pointer and will result in {@code onEvent} becoming a - * no-op. + *

Passing in 0 is considered a null pointer and will result in {@code + * onEvent} becoming a no-op. * - * @param cppFirestoreObject Pointer to a {@code firebase::firestore::Firestore}. + * @param cppFirestoreObject Pointer to a {@code + * firebase::firestore::Firestore}. * @param cppListenerObject Pointer to a {@code * firebase::firestore::EventListener}. */ @@ -44,22 +47,22 @@ public QueryEventListener(long cppFirestoreObject, long cppListenerObject) { } @Override - public synchronized void onEvent( - @Nullable QuerySnapshot value, @Nullable FirebaseFirestoreException error) { - nativeOnEvent(cppFirestoreObject, cppListenerObject, value, error); + public synchronized void onEvent(@Nullable QuerySnapshot value, + @Nullable FirebaseFirestoreException error) { + nativeOnEvent(cppFirestoreObject, cppListenerObject, value, error); } /** * Interprets the {@code listenerObject} as a {@code - * firebase::firestore::EventListener} and invokes the listener's {@code OnEvent} - * method with the {@code error} and {@code QuerySnapshot} created by interpreting the {@code - * firestoreObject} as a {@code firebase::firestore::Firestore}. + * firebase::firestore::EventListener} and invokes the + * listener's {@code OnEvent} method with the {@code error} and {@code + * QuerySnapshot} created by interpreting the {@code firestoreObject} as a + * {@code firebase::firestore::Firestore}. * *

This native method is implemented in the Firestore C++ library {@code * event_listener_android.cc}. */ - private static native void nativeOnEvent( - long firestoreObject, + private static native void nativeOnEvent(long firestoreObject, long listenerObject, @Nullable Object value, @Nullable FirebaseFirestoreException error); diff --git a/firestore/src_java/com/google/firebase/firestore/internal/cpp/SilentRejectionSingleThreadExecutor.java b/firestore/src_java/com/google/firebase/firestore/internal/cpp/SilentRejectionSingleThreadExecutor.java index 2fdf02a376..5a0fffe684 100644 --- a/firestore/src_java/com/google/firebase/firestore/internal/cpp/SilentRejectionSingleThreadExecutor.java +++ b/firestore/src_java/com/google/firebase/firestore/internal/cpp/SilentRejectionSingleThreadExecutor.java @@ -22,19 +22,22 @@ import java.util.concurrent.RejectedExecutionException; /** - * Simple {@code Executor} implementation wraps around a single threaded executor and swallows + * Simple {@code Executor} implementation wraps around a single threaded + * executor and swallows * {@code RejectedExecutionException} when executing commands. * - *

During shutdown, the C++ API must be able to prevent user callbacks from running after the - * Firestore object has been disposed. To do so, it shuts down its executors, accepting that new - * callbacks may be rejected, and if there is work already scheduled, they will not be executed. + *

During shutdown, the C++ API must be able to prevent user callbacks from + * running after the Firestore object has been disposed. To do so, it shuts down + * its executors, accepting that new callbacks may be rejected, and if there is + * work already scheduled, they will not be executed. * * This class catches and discards the {@code RejectedExecutionException} - * that is thrown by the underlying Java executor after shutdown, bridging the gap between C++ - * expectations and the Java implementation. + * that is thrown by the underlying Java executor after shutdown, bridging the + * gap between C++ expectations and the Java implementation. */ public final class SilentRejectionSingleThreadExecutor implements Executor { - private final ExecutorService internalExecutor = Executors.newSingleThreadExecutor(); + private final ExecutorService internalExecutor = + Executors.newSingleThreadExecutor(); @Override public void execute(Runnable command) { diff --git a/firestore/src_java/com/google/firebase/firestore/internal/cpp/TransactionFunction.java b/firestore/src_java/com/google/firebase/firestore/internal/cpp/TransactionFunction.java index 7ac8966dff..0c23f7371e 100644 --- a/firestore/src_java/com/google/firebase/firestore/internal/cpp/TransactionFunction.java +++ b/firestore/src_java/com/google/firebase/firestore/internal/cpp/TransactionFunction.java @@ -22,21 +22,25 @@ import com.google.firebase.firestore.Transaction; /** - * Implements Firestore TransactionFunction by redirecting calls into C++. This shares the same - * logic as a listener but there is difference. A listener implements onEvent() while Transaction - * Function implements apply(). + * Implements Firestore TransactionFunction by redirecting calls into C++. This + * shares the same logic as a listener but there is difference. A listener + * implements onEvent() while Transaction Function implements apply(). */ -public class TransactionFunction extends CppEventListener implements Transaction.Function { +public class TransactionFunction + extends CppEventListener implements Transaction.Function { /** Construct a TransactionFunction. Parameters are C++ pointers. */ - public TransactionFunction(long cppFirestoreObject, long cppTransactionFunctionObject) { + public TransactionFunction( + long cppFirestoreObject, long cppTransactionFunctionObject) { super(cppFirestoreObject, cppTransactionFunctionObject); } @Override - public Object apply(Transaction transaction) throws FirebaseFirestoreException { + public Object apply(Transaction transaction) + throws FirebaseFirestoreException { if (cppFirestoreObject != 0 && cppListenerObject != 0) { try { - Exception exception = nativeApply(cppFirestoreObject, cppListenerObject, transaction); + Exception exception = + nativeApply(cppFirestoreObject, cppListenerObject, transaction); if (exception != null) { throw exception; } @@ -54,8 +58,12 @@ public Object apply(Transaction transaction) throws FirebaseFirestoreException { return null; } - /** This native function is implemented in the Firestore C++ library (transaction_android.cc). */ + /** + * This native function is implemented in the Firestore C++ library + * (transaction_android.cc). + */ @Nullable - private static native Exception nativeApply( - long firestoreObject, long transactionFunctionObject, Transaction transaction); + private static native Exception nativeApply(long firestoreObject, + long transactionFunctionObject, + Transaction transaction); } diff --git a/firestore/src_java/com/google/firebase/firestore/internal/cpp/VoidEventListener.java b/firestore/src_java/com/google/firebase/firestore/internal/cpp/VoidEventListener.java index ec2bfada9c..29078e4934 100644 --- a/firestore/src_java/com/google/firebase/firestore/internal/cpp/VoidEventListener.java +++ b/firestore/src_java/com/google/firebase/firestore/internal/cpp/VoidEventListener.java @@ -18,18 +18,21 @@ /** * An implementation of {@code Runnable} that delegates to a {@code - * firebase::firestore::EventListener}. This is useful for getting callbacks from Java APIs - * that cannot fail, like addSnapshotsInSyncListener. + * firebase::firestore::EventListener}. This is useful for getting + * callbacks from Java APIs that cannot fail, like addSnapshotsInSyncListener. */ public class VoidEventListener extends CppEventListener implements Runnable { /** - * Constructs a VoidEventListener. Ownership of the underlying EventListener can be transferred - * when creating the {@code ListenerRegistration}. If the ListenerRegistration owns the - * EventListener, it will de-allocate the EventListener in its destructor. + * Constructs a VoidEventListener. Ownership of the underlying EventListener + * can be transferred when creating the {@code ListenerRegistration}. If the + * ListenerRegistration owns the EventListener, it will de-allocate the + * EventListener in its destructor. * - *

Passing in 0 is considered a null pointer and will result in {@code run} becoming a no-op. + *

Passing in 0 is considered a null pointer and will result in {@code run} + * becoming a no-op. * - * @param cppListenerObject Pointer to a {@code firebase::firestore::EventListener}. + * @param cppListenerObject Pointer to a {@code + * firebase::firestore::EventListener}. */ public VoidEventListener(long cppListenerObject) { super(0, cppListenerObject); @@ -41,9 +44,10 @@ public void run() { } /** - * Interprets the {@code listenerObject} as a {@code firebase::firestore::EventListener} and - * invokes the listener's {@code OnEvent} method with {@code Error::kOk}. The EventListener will - * never be passed anything other than Ok because VoidEventListener can only be used in + * Interprets the {@code listenerObject} as a {@code + * firebase::firestore::EventListener} and invokes the listener's {@code + * OnEvent} method with {@code Error::kOk}. The EventListener will never be + * passed anything other than Ok because VoidEventListener can only be used in * circumstances where the callback can't fail. * *

This native method is implemented in the Firestore C++ library {@code diff --git a/functions/src/include/firebase/functions/callable_result.h b/functions/src/include/firebase/functions/callable_result.h index 84cf870df1..5186377ae8 100644 --- a/functions/src/include/firebase/functions/callable_result.h +++ b/functions/src/include/firebase/functions/callable_result.h @@ -15,8 +15,8 @@ #ifndef FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_CALLABLE_RESULT_H_ #define FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_CALLABLE_RESULT_H_ -#include "firebase/variant.h" #include "firebase/functions/common.h" +#include "firebase/variant.h" namespace firebase { namespace functions { diff --git a/functions/src/include/firebase/functions/common.h b/functions/src/include/firebase/functions/common.h index aa4b864dab..133fe14aa4 100644 --- a/functions/src/include/firebase/functions/common.h +++ b/functions/src/include/firebase/functions/common.h @@ -25,7 +25,7 @@ namespace functions { /// https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto enum Error { #ifdef INTERNAL_EXPERIMENTAL - // LINT.IfChange +// LINT.IfChange #endif // INTERNAL_EXPERIMENTAL // Not an error; returned on success @@ -182,7 +182,7 @@ enum Error { kErrorDataLoss = 15, #ifdef INTERNAL_EXPERIMENTAL - // LINT.ThenChange(//depot_firebase_cpp/functions/client/cpp/src/ios/\ +// LINT.ThenChange(//depot_firebase_cpp/functions/client/cpp/src/ios/\ // callable_reference_ios.mm) #endif // INTERNAL_EXPERIMENTAL }; diff --git a/installations/src_java/fake/com/google/firebase/installations/FirebaseInstallations.java b/installations/src_java/fake/com/google/firebase/installations/FirebaseInstallations.java index 0953547218..1ff8762a15 100644 --- a/installations/src_java/fake/com/google/firebase/installations/FirebaseInstallations.java +++ b/installations/src_java/fake/com/google/firebase/installations/FirebaseInstallations.java @@ -21,7 +21,6 @@ /** Mock FirebaseInstallations. */ public class FirebaseInstallations { - private static final String FN_GET_ID = "FirebaseInstallations.getId"; private static final String FN_GEI_TOKEN = "FirebaseInstallations.getToken"; private static final String FN_DELETE = "FirebaseInstallations.delete"; diff --git a/installations/src_java/fake/com/google/firebase/installations/InstallationTokenResult.java b/installations/src_java/fake/com/google/firebase/installations/InstallationTokenResult.java index 67ddd19621..7ae6933611 100644 --- a/installations/src_java/fake/com/google/firebase/installations/InstallationTokenResult.java +++ b/installations/src_java/fake/com/google/firebase/installations/InstallationTokenResult.java @@ -16,7 +16,6 @@ /** Mock InstallationTokenResult */ public class InstallationTokenResult { - private InstallationTokenResult() {} public static synchronized InstallationTokenResult getInstance() { diff --git a/messaging/samples/src/java/com/google/firebase/messaging/cpp/samples/MyActivity.java b/messaging/samples/src/java/com/google/firebase/messaging/cpp/samples/MyActivity.java index 6a97c0ad3f..8bc173fae6 100644 --- a/messaging/samples/src/java/com/google/firebase/messaging/cpp/samples/MyActivity.java +++ b/messaging/samples/src/java/com/google/firebase/messaging/cpp/samples/MyActivity.java @@ -23,7 +23,6 @@ import android.app.Activity; import android.content.Intent; import android.util.Log; - // [START messaging_on_new_intent] import com.google.firebase.messaging.MessageForwardingService; diff --git a/messaging/samples/src/java/com/google/firebase/messaging/cpp/samples/MyListenerService.java b/messaging/samples/src/java/com/google/firebase/messaging/cpp/samples/MyListenerService.java index af9063eced..e65270532a 100644 --- a/messaging/samples/src/java/com/google/firebase/messaging/cpp/samples/MyListenerService.java +++ b/messaging/samples/src/java/com/google/firebase/messaging/cpp/samples/MyListenerService.java @@ -22,12 +22,11 @@ import android.util.Log; import com.google.firebase.messaging.RemoteMessage; - // [START messaging_extend_listener_service] import com.google.firebase.messaging.cpp.ListenerService; class MyListenerService extends ListenerService { -// [END messaging_extend_listener_service] + // [END messaging_extend_listener_service] private static final String TAG = "MyListenerService"; // [START messaging_on_message_received_override] diff --git a/messaging/src/android/java/com/google/firebase/messaging/JobIds.java b/messaging/src/android/java/com/google/firebase/messaging/JobIds.java index 9cfca6fb1e..cff5f7f9e0 100644 --- a/messaging/src/android/java/com/google/firebase/messaging/JobIds.java +++ b/messaging/src/android/java/com/google/firebase/messaging/JobIds.java @@ -16,7 +16,6 @@ /** Unique ids for JobIntentServices. */ public final class JobIds { - private JobIds() {} public static final int MESSAGE_FORWARDING_SERVICE = 1000; diff --git a/messaging/src/android/java/com/google/firebase/messaging/MessageForwardingService.java b/messaging/src/android/java/com/google/firebase/messaging/MessageForwardingService.java index a5b35f30a2..81d4b32bfc 100644 --- a/messaging/src/android/java/com/google/firebase/messaging/MessageForwardingService.java +++ b/messaging/src/android/java/com/google/firebase/messaging/MessageForwardingService.java @@ -30,9 +30,9 @@ public class MessageForwardingService extends JobIntentService { public static final String ACTION_REMOTE_INTENT = "com.google.android.c2dm.intent.RECEIVE"; /** - * Convenience wrapper over enqueueWork to either directly start the service (when running on - * pre-O platforms) or enqueue work for it as a job (when running on Android O and later). - */ + * Convenience wrapper over enqueueWork to either directly start the service (when running on + * pre-O platforms) or enqueue work for it as a job (when running on Android O and later). + */ public static void enqueueWork(Context context, Intent intent) { enqueueWork(context, MessageForwardingService.class, JobIds.MESSAGE_FORWARDING_SERVICE, intent); } @@ -46,14 +46,11 @@ protected void onHandleWork(Intent intent) { // TODO(b/79994182): see go/objecttostring-lsc @SuppressWarnings("ObjectToString") static void handleIntent(Context context, Intent intent, MessageWriter messageWriter) { - DebugLogging.log( - TAG, + DebugLogging.log(TAG, "onHandleIntent " - + (intent == null - ? "null intent" - : (intent.getAction() == null ? "(null)" : intent.getAction()))); - if (intent != null - && intent.getAction() != null + + (intent == null ? "null intent" + : (intent.getAction() == null ? "(null)" : intent.getAction()))); + if (intent != null && intent.getAction() != null && intent.getAction().equals(ACTION_REMOTE_INTENT)) { Bundle extras = intent.getExtras(); DebugLogging.log(TAG, "extras: " + (extras == null ? "(null)" : extras.toString())); diff --git a/messaging/src/android/java/com/google/firebase/messaging/cpp/ListenerService.java b/messaging/src/android/java/com/google/firebase/messaging/cpp/ListenerService.java index 5dfe5cda43..243af4a3b0 100644 --- a/messaging/src/android/java/com/google/firebase/messaging/cpp/ListenerService.java +++ b/messaging/src/android/java/com/google/firebase/messaging/cpp/ListenerService.java @@ -22,7 +22,6 @@ * OnMessage function. */ public class ListenerService extends FirebaseMessagingService { - // TODO(amablue): Add an IfChange/ThenChange block around this, and the other copy of these // variables in com.google.firebase.messaging.RemoteMessageBuilder. public static final String MESSAGE_TYPE_DELETED = "deleted_messages"; @@ -61,8 +60,7 @@ public void onMessageSent(String messageId) { @Override public void onSendError(String messageId, Exception exception) { - DebugLogging.log( - TAG, + DebugLogging.log(TAG, String.format("onSendError messageId=%s exception=%s", messageId, exception.toString())); messageWriter.writeMessageEventToInternalStorage( this, messageId, MESSAGE_TYPE_SEND_ERROR, exception.toString()); diff --git a/messaging/src/android/java/com/google/firebase/messaging/cpp/MessageWriter.java b/messaging/src/android/java/com/google/firebase/messaging/cpp/MessageWriter.java index 937b89b3fb..bb7a4c437e 100644 --- a/messaging/src/android/java/com/google/firebase/messaging/cpp/MessageWriter.java +++ b/messaging/src/android/java/com/google/firebase/messaging/cpp/MessageWriter.java @@ -64,53 +64,20 @@ public void writeMessage( linkUri = notification.getLink(); } String link = (linkUri != null) ? linkUri.toString() : null; - DebugLogging.log( - TAG, - String.format( - "onMessageReceived from=%s message_id=%s, data=%s, notification=%s", - from, - messageId, - (data == null ? "(null)" : data.toString()), + DebugLogging.log(TAG, + String.format("onMessageReceived from=%s message_id=%s, data=%s, notification=%s", from, + messageId, (data == null ? "(null)" : data.toString()), (notification == null ? "(null)" : notification.toString()))); - writeMessageToInternalStorage( - context, - from, - to, - messageId, - messageType, - null, - data, - rawData, - notification, - notificationOpened, - link, - collapseKey, - priority, - originalPriority, - sentTime, + writeMessageToInternalStorage(context, from, to, messageId, messageType, null, data, rawData, + notification, notificationOpened, link, collapseKey, priority, originalPriority, sentTime, timeToLive); } /** Writes an event associated with a message to internal storage. */ void writeMessageEventToInternalStorage( Context context, String messageId, String messageType, String error) { - writeMessageToInternalStorage( - context, - null, - null, - messageId, - messageType, - null, - null, - null, - null, - false, - null, - null, - 0, - 0, - 0, - 0); + writeMessageToInternalStorage(context, null, null, messageId, messageType, null, null, null, + null, false, null, null, 0, 0, 0, 0); } /** @@ -122,40 +89,13 @@ void writeMessageEventToInternalStorage( * whenever it gets around to it. */ @SuppressWarnings("CatchAndPrintStackTrace") - void writeMessageToInternalStorage( - Context context, - String from, - String to, - String messageId, - String messageType, - String error, - Map data, - byte[] rawData, - Notification notification, - boolean notificationOpened, - String link, - String collapseKey, - int priority, - int originalPriority, - long sentTime, - int timeToLive) { - byte[] buffer = - generateMessageByteBuffer( - from, - to, - messageId, - messageType, - error, - data, - rawData, - notification, - notificationOpened, - link, - collapseKey, - priority, - originalPriority, - sentTime, - timeToLive); + void writeMessageToInternalStorage(Context context, String from, String to, String messageId, + String messageType, String error, Map data, byte[] rawData, + Notification notification, boolean notificationOpened, String link, String collapseKey, + int priority, int originalPriority, long sentTime, int timeToLive) { + byte[] buffer = generateMessageByteBuffer(from, to, messageId, messageType, error, data, + rawData, notification, notificationOpened, link, collapseKey, priority, originalPriority, + sentTime, timeToLive); ByteBuffer sizeBuffer = ByteBuffer.allocate(4); // Write out the buffer length into the first four bytes. sizeBuffer.order(ByteOrder.LITTLE_ENDIAN); @@ -202,22 +142,10 @@ private static String priorityToString(int priority) { } } - private static byte[] generateMessageByteBuffer( - String from, - String to, - String messageId, - String messageType, - String error, - Map data, - byte[] rawData, - Notification notification, - boolean notificationOpened, - String link, - String collapseKey, - int priority, - int originalPriority, - long sentTime, - int timeToLive) { + private static byte[] generateMessageByteBuffer(String from, String to, String messageId, + String messageType, String error, Map data, byte[] rawData, + Notification notification, boolean notificationOpened, String link, String collapseKey, + int priority, int originalPriority, long sentTime, int timeToLive) { FlatBufferBuilder builder = new FlatBufferBuilder(0); int fromOffset = builder.createString(emptyIfNull(from)); int toOffset = builder.createString(emptyIfNull(to)); diff --git a/messaging/src/android/java/com/google/firebase/messaging/cpp/RegistrationIntentService.java b/messaging/src/android/java/com/google/firebase/messaging/cpp/RegistrationIntentService.java index d296000c02..912ff38f4a 100644 --- a/messaging/src/android/java/com/google/firebase/messaging/cpp/RegistrationIntentService.java +++ b/messaging/src/android/java/com/google/firebase/messaging/cpp/RegistrationIntentService.java @@ -18,10 +18,10 @@ import android.content.Intent; import android.util.Log; import androidx.annotation.NonNull; +import androidx.core.app.JobIntentService; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.messaging.FirebaseMessaging; -import androidx.core.app.JobIntentService; import com.google.flatbuffers.FlatBufferBuilder; import java.io.FileOutputStream; import java.nio.ByteBuffer; @@ -39,24 +39,24 @@ public class RegistrationIntentService extends JobIntentService { @Override protected void onHandleWork(Intent intent) { final Context context = this; - FirebaseMessaging.getInstance().getToken() - .addOnCompleteListener(new OnCompleteListener() { - @Override - public void onComplete(@NonNull Task task) { - if (!task.isSuccessful()) { - Log.w(TAG, "Fetching FCM registration token failed", task.getException()); - return; - } + FirebaseMessaging.getInstance().getToken().addOnCompleteListener( + new OnCompleteListener() { + @Override + public void onComplete(@NonNull Task task) { + if (!task.isSuccessful()) { + Log.w(TAG, "Fetching FCM registration token failed", task.getException()); + return; + } - // Get new FCM registration token - String token = task.getResult(); + // Get new FCM registration token + String token = task.getResult(); - DebugLogging.log(TAG, String.format("onHandleWork token=%s", token)); - if (token != null) { - writeTokenToInternalStorage(context, token); + DebugLogging.log(TAG, String.format("onHandleWork token=%s", token)); + if (token != null) { + writeTokenToInternalStorage(context, token); + } } - } - }); + }); } /** Write token to internal storage so it can be accessed by the C++ layer. */ diff --git a/messaging/src/android/javatests/com/google/firebase/messaging/MessageForwardingServiceTest.java b/messaging/src/android/javatests/com/google/firebase/messaging/MessageForwardingServiceTest.java index 05e86e6466..765857bd6b 100644 --- a/messaging/src/android/javatests/com/google/firebase/messaging/MessageForwardingServiceTest.java +++ b/messaging/src/android/javatests/com/google/firebase/messaging/MessageForwardingServiceTest.java @@ -33,7 +33,6 @@ @RunWith(GoogleRobolectricTestRunner.class) public final class MessageForwardingServiceTest { - @Mock private Context context; @Mock private MessageWriter messageWriter; diff --git a/messaging/src/android/javatests/com/google/firebase/messaging/RemoteMessageUtil.java b/messaging/src/android/javatests/com/google/firebase/messaging/RemoteMessageUtil.java index 64ce0ad5c2..55033e6f67 100644 --- a/messaging/src/android/javatests/com/google/firebase/messaging/RemoteMessageUtil.java +++ b/messaging/src/android/javatests/com/google/firebase/messaging/RemoteMessageUtil.java @@ -18,7 +18,6 @@ /** */ public class RemoteMessageUtil { - private RemoteMessageUtil() {} // Utility class. public static RemoteMessage remoteMessage(Bundle bundle) { diff --git a/messaging/src/android/javatests/com/google/firebase/messaging/cpp/ListenerServiceTest.java b/messaging/src/android/javatests/com/google/firebase/messaging/cpp/ListenerServiceTest.java index ff7db3b4ed..4fc47a7691 100644 --- a/messaging/src/android/javatests/com/google/firebase/messaging/cpp/ListenerServiceTest.java +++ b/messaging/src/android/javatests/com/google/firebase/messaging/cpp/ListenerServiceTest.java @@ -32,7 +32,6 @@ @RunWith(GoogleRobolectricTestRunner.class) public final class ListenerServiceTest { - @Mock private MessageWriter messageWriter; private ListenerService listenerService; @@ -47,11 +46,8 @@ public void setUp() { public void testOnDeletedMessages() throws Exception { listenerService.onDeletedMessages(); verify(messageWriter) - .writeMessageEventToInternalStorage( - eq(listenerService), - (String) isNull(), - eq(ListenerService.MESSAGE_TYPE_DELETED), - (String) isNull()); + .writeMessageEventToInternalStorage(eq(listenerService), (String) isNull(), + eq(ListenerService.MESSAGE_TYPE_DELETED), (String) isNull()); } @Test @@ -65,11 +61,8 @@ public void testOnMessageReceived() { public void testOnMessageSent() { listenerService.onMessageSent("message_id"); verify(messageWriter) - .writeMessageEventToInternalStorage( - eq(listenerService), - eq("message_id"), - eq(ListenerService.MESSAGE_TYPE_SEND_EVENT), - (String) isNull()); + .writeMessageEventToInternalStorage(eq(listenerService), eq("message_id"), + eq(ListenerService.MESSAGE_TYPE_SEND_EVENT), (String) isNull()); } @Test @@ -77,9 +70,7 @@ public void testOnSendError() { listenerService.onSendError( "message_id", RemoteMessageUtil.sendException("service_not_available")); verify(messageWriter) - .writeMessageEventToInternalStorage( - eq(listenerService), - eq("message_id"), + .writeMessageEventToInternalStorage(eq(listenerService), eq("message_id"), eq(ListenerService.MESSAGE_TYPE_SEND_ERROR), eq("com.google.firebase.messaging.SendException: service_not_available")); } diff --git a/messaging/src/android/javatests/com/google/firebase/messaging/cpp/MessageWriterTest.java b/messaging/src/android/javatests/com/google/firebase/messaging/cpp/MessageWriterTest.java index 7621a0b0be..4c33f27744 100644 --- a/messaging/src/android/javatests/com/google/firebase/messaging/cpp/MessageWriterTest.java +++ b/messaging/src/android/javatests/com/google/firebase/messaging/cpp/MessageWriterTest.java @@ -40,7 +40,6 @@ @RunWith(GoogleRobolectricTestRunner.class) public final class MessageWriterTest { - private static final Path STORAGE_FILE_PATH = Paths.get("/tmp/" + MessageWriter.STORAGE_FILE); @Mock private Context context; @@ -71,7 +70,7 @@ public void testMessageWriter() throws Exception { RemoteMessage message = RemoteMessageUtil.remoteMessage(bundle); messageWriter.writeMessage(context, message, false, null); ByteBuffer byteBuffer = ByteBuffer.wrap(readStorageFile()).order(ByteOrder.LITTLE_ENDIAN); - byteBuffer.getInt(); // Discard size. + byteBuffer.getInt(); // Discard size. SerializedEvent event = SerializedEvent.getRootAsSerializedEvent(byteBuffer); SerializedMessage result = (SerializedMessage) event.event(new SerializedMessage()); assertThat(result.from()).isEqualTo("my_from"); diff --git a/messaging/src_java/fake/com/google/firebase/messaging/FirebaseMessaging.java b/messaging/src_java/fake/com/google/firebase/messaging/FirebaseMessaging.java index e4f91e7ef2..d3099ae6d0 100644 --- a/messaging/src_java/fake/com/google/firebase/messaging/FirebaseMessaging.java +++ b/messaging/src_java/fake/com/google/firebase/messaging/FirebaseMessaging.java @@ -24,7 +24,6 @@ * Fake FirebaseMessaging class. */ public class FirebaseMessaging { - private static final String FN_GET_TOKEN = "FirebaseMessaging.getToken"; private static final String FN_DELETE_TOKEN = "FirebaseMessaging.deleteToken"; diff --git a/messaging/src_java/fake/com/google/firebase/messaging/RemoteMessage.java b/messaging/src_java/fake/com/google/firebase/messaging/RemoteMessage.java index b65cd5e9b5..5abb8d3b2e 100644 --- a/messaging/src_java/fake/com/google/firebase/messaging/RemoteMessage.java +++ b/messaging/src_java/fake/com/google/firebase/messaging/RemoteMessage.java @@ -20,7 +20,6 @@ * Fake RemoteMessage class. */ public class RemoteMessage { - public final String from; public final String to; public final Map data; @@ -40,7 +39,6 @@ private RemoteMessage( * Fake Builder class. */ public static class Builder { - private final String to; private Map data; private Integer ttl; diff --git a/messaging/src_java/fake/com/google/firebase/messaging/cpp/RegistrationIntentService.java b/messaging/src_java/fake/com/google/firebase/messaging/cpp/RegistrationIntentService.java index d7a7efc6ae..ed2f8afcb2 100644 --- a/messaging/src_java/fake/com/google/firebase/messaging/cpp/RegistrationIntentService.java +++ b/messaging/src_java/fake/com/google/firebase/messaging/cpp/RegistrationIntentService.java @@ -17,5 +17,4 @@ /** * Fake RegistrationIntentService class. */ -public class RegistrationIntentService { -} +public class RegistrationIntentService {} diff --git a/messaging/tests/ios/messaging_test_util.mm b/messaging/tests/ios/messaging_test_util.mm index 106381b769..9e4004b5d8 100644 --- a/messaging/tests/ios/messaging_test_util.mm +++ b/messaging/tests/ios/messaging_test_util.mm @@ -44,14 +44,11 @@ // Dual purpose body text or data dictionary. static NSString *const kAlert = @"alert"; - void InitializeMessagingTest() {} -void TerminateMessagingTest() { - [FIRMessaging messaging].FCMToken = nil; -} +void TerminateMessagingTest() { [FIRMessaging messaging].FCMToken = nil; } -void OnTokenReceived(const char* tokenstr) { +void OnTokenReceived(const char *tokenstr) { [FIRMessaging messaging].FCMToken = @(tokenstr); [[FIRMessaging messaging].delegate messaging:[FIRMessaging messaging] didReceiveRegistrationToken:@(tokenstr)]; @@ -62,8 +59,8 @@ void SleepMessagingTest(double seconds) { [[NSRunLoop mainRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:seconds]]; } -void OnMessageReceived(const Message& message) { - NSMutableDictionary* userData = [NSMutableDictionary dictionary]; +void OnMessageReceived(const Message &message) { + NSMutableDictionary *userData = [NSMutableDictionary dictionary]; userData[kMessageID] = @(message.message_id.c_str()); userData[kTo] = @(message.to.c_str()); userData[kFrom] = @(message.from.c_str()); @@ -73,15 +70,15 @@ void OnMessageReceived(const Message& message) { userData[kTimeToLive] = @(message.time_to_live); userData[kError] = @(message.error.c_str()); userData[kErrorDescription] = @(message.error_description.c_str()); - for (const auto& entry : message.data) { + for (const auto &entry : message.data) { userData[@(entry.first.c_str())] = @(entry.second.c_str()); } if (message.notification) { - NSMutableDictionary* alert = [NSMutableDictionary dictionary]; + NSMutableDictionary *alert = [NSMutableDictionary dictionary]; alert[kTitle] = @(message.notification->title.c_str()); alert[kBody] = @(message.notification->body.c_str()); - NSMutableDictionary* aps = [NSMutableDictionary dictionary]; + NSMutableDictionary *aps = [NSMutableDictionary dictionary]; aps[kSound] = @(message.notification->sound.c_str()); aps[kBadge] = @(message.notification->badge.c_str()); aps[kAlert] = alert; @@ -91,9 +88,9 @@ void OnMessageReceived(const Message& message) { didReceiveRemoteNotification:userData]; } -void OnMessageSent(const char* message_id) {} +void OnMessageSent(const char *message_id) {} -void OnMessageSentError(const char* message_id, const char* error) {} +void OnMessageSentError(const char *message_id, const char *error) {} } // namespace messaging } // namespace firebase diff --git a/performance/src_java/fake/com/google/firebase/perf/FirebasePerformance.java b/performance/src_java/fake/com/google/firebase/perf/FirebasePerformance.java index d5c25b384b..70fd28a70d 100644 --- a/performance/src_java/fake/com/google/firebase/perf/FirebasePerformance.java +++ b/performance/src_java/fake/com/google/firebase/perf/FirebasePerformance.java @@ -13,17 +13,8 @@ public class FirebasePerformance { private static boolean performanceCollectionEnabled = true; /** Valid HttpMethods for manual network APIs */ - @StringDef({ - HttpMethod.GET, - HttpMethod.PUT, - HttpMethod.POST, - HttpMethod.DELETE, - HttpMethod.HEAD, - HttpMethod.PATCH, - HttpMethod.OPTIONS, - HttpMethod.TRACE, - HttpMethod.CONNECT - }) + @StringDef({HttpMethod.GET, HttpMethod.PUT, HttpMethod.POST, HttpMethod.DELETE, HttpMethod.HEAD, + HttpMethod.PATCH, HttpMethod.OPTIONS, HttpMethod.TRACE, HttpMethod.CONNECT}) @Retention(RetentionPolicy.SOURCE) public @interface HttpMethod { String GET = "GET"; diff --git a/performance/src_java/fake/com/google/firebase/perf/FirebasePerformanceAttributable.java b/performance/src_java/fake/com/google/firebase/perf/FirebasePerformanceAttributable.java index fc38e5f714..e157804bb5 100644 --- a/performance/src_java/fake/com/google/firebase/perf/FirebasePerformanceAttributable.java +++ b/performance/src_java/fake/com/google/firebase/perf/FirebasePerformanceAttributable.java @@ -6,7 +6,6 @@ /** Attribute functions needed for Traces and HttpMetrics */ public interface FirebasePerformanceAttributable { - /** Maximum allowed number of attributes allowed in a trace. */ int MAX_TRACE_CUSTOM_ATTRIBUTES = 5; /** Maximum allowed length of the Key of the {@link Trace} attribute */ @@ -35,8 +34,7 @@ public interface FirebasePerformanceAttributable { * @param attribute name of the attribute to fetch the value for * @return The value of the attribute if it exists or null otherwise. */ - @Nullable - String getAttribute(String attribute); + @Nullable String getAttribute(String attribute); /** * Removes the attribute from the list of attributes. diff --git a/performance/src_java/fake/com/google/firebase/perf/metrics/HttpMetric.java b/performance/src_java/fake/com/google/firebase/perf/metrics/HttpMetric.java index 18b305224d..2350eb3518 100644 --- a/performance/src_java/fake/com/google/firebase/perf/metrics/HttpMetric.java +++ b/performance/src_java/fake/com/google/firebase/perf/metrics/HttpMetric.java @@ -1,7 +1,7 @@ package com.google.firebase.perf.metrics; -import androidx.annotation.Nullable; import android.util.Log; +import androidx.annotation.Nullable; import com.google.apps.tiktok.testing.errorprone.SuppressViolation; import com.google.firebase.perf.FirebasePerformance.HttpMethod; import com.google.firebase.perf.FirebasePerformanceAttributable; @@ -15,7 +15,6 @@ * request/response. This class is not thread safe. */ public class HttpMetric implements FirebasePerformanceAttributable { - private static final String LOG_TAG = "FirebasePerformanceFake"; private final Map attributes; diff --git a/performance/src_java/fake/com/google/firebase/perf/metrics/Trace.java b/performance/src_java/fake/com/google/firebase/perf/metrics/Trace.java index 5fbbd90546..c9cb476b69 100644 --- a/performance/src_java/fake/com/google/firebase/perf/metrics/Trace.java +++ b/performance/src_java/fake/com/google/firebase/perf/metrics/Trace.java @@ -1,8 +1,8 @@ package com.google.firebase.perf.metrics; import android.support.annotation.Keep; -import androidx.annotation.Nullable; import android.util.Log; +import androidx.annotation.Nullable; import com.google.firebase.perf.FirebasePerformanceAttributable; import com.google.firebase.testing.cppsdk.FakeReporter; import java.util.Date; @@ -117,18 +117,14 @@ public long getLongMetric(String metricName) { public void putMetric(String metricName, long value) { FakeReporter.addReport("Trace.putMetric", metricName, Long.toString(value)); if (!hasStarted()) { - Log.w( - LOG_TAG, - String.format( - "Cannot set value for metric '%s' for trace '%s' because it's not started", + Log.w(LOG_TAG, + String.format("Cannot set value for metric '%s' for trace '%s' because it's not started", metricName, name)); return; } if (isStopped()) { - Log.w( - LOG_TAG, - String.format( - "Cannot set value for metric '%s' for trace '%s' because it's been stopped", + Log.w(LOG_TAG, + String.format("Cannot set value for metric '%s' for trace '%s' because it's been stopped", metricName, name)); return; } @@ -144,8 +140,7 @@ protected void finalize() throws Throwable { try { // If trace is started but not stopped when it reaches finalize(), log a warning msg. if (isActive()) { - Log.w( - LOG_TAG, + Log.w(LOG_TAG, String.format("Trace '%s' is started but not stopped when it is destructed!", name)); } } finally { @@ -199,8 +194,7 @@ public void putAttribute(String attribute, String value) { attribute = attribute.trim(); value = value.trim(); } catch (Exception e) { - Log.e( - LOG_TAG, + Log.e(LOG_TAG, String.format( "Can not set attribute %s with value %s (%s)", attribute, value, e.getMessage())); noError = false; diff --git a/remote_config/src_java/fake/com/google/firebase/remoteconfig/FirebaseRemoteConfig.java b/remote_config/src_java/fake/com/google/firebase/remoteconfig/FirebaseRemoteConfig.java index 8339d2670c..6d58412f76 100644 --- a/remote_config/src_java/fake/com/google/firebase/remoteconfig/FirebaseRemoteConfig.java +++ b/remote_config/src_java/fake/com/google/firebase/remoteconfig/FirebaseRemoteConfig.java @@ -30,7 +30,6 @@ /** Fake FirebaseRemoteConfig */ public class FirebaseRemoteConfig { - private static final String FN_GET_LONG = "FirebaseRemoteConfig.getLong"; private static final String FN_GET_STRING = "FirebaseRemoteConfig.getString"; private static final String FN_GET_BOOLEAN = "FirebaseRemoteConfig.getBoolean"; @@ -216,5 +215,4 @@ private static List stringToStringList(String s) { } return Arrays.asList(arr); } - } diff --git a/remote_config/src_java/fake/com/google/firebase/remoteconfig/FirebaseRemoteConfigFetchThrottledException.java b/remote_config/src_java/fake/com/google/firebase/remoteconfig/FirebaseRemoteConfigFetchThrottledException.java index 8e72f08587..b2f5ab8be7 100644 --- a/remote_config/src_java/fake/com/google/firebase/remoteconfig/FirebaseRemoteConfigFetchThrottledException.java +++ b/remote_config/src_java/fake/com/google/firebase/remoteconfig/FirebaseRemoteConfigFetchThrottledException.java @@ -16,9 +16,7 @@ /** Fake FirebaseRemoteConfigFetchThrottledException */ public class FirebaseRemoteConfigFetchThrottledException { - - public long getThrottleEndTimeMillis() { - return 0; - } - + public long getThrottleEndTimeMillis() { + return 0; + } } diff --git a/remote_config/src_java/fake/com/google/firebase/remoteconfig/FirebaseRemoteConfigInfo.java b/remote_config/src_java/fake/com/google/firebase/remoteconfig/FirebaseRemoteConfigInfo.java index 5c61295168..1eefcac044 100644 --- a/remote_config/src_java/fake/com/google/firebase/remoteconfig/FirebaseRemoteConfigInfo.java +++ b/remote_config/src_java/fake/com/google/firebase/remoteconfig/FirebaseRemoteConfigInfo.java @@ -20,7 +20,6 @@ /** Fake FirebaseRemoteConfigInfo */ public class FirebaseRemoteConfigInfo { - public long getFetchTimeMillis() { ConfigRow row = ConfigAndroid.get("FirebaseRemoteConfigInfo.getFetchTimeMillis"); long result = row.returnvalue().tlong(); diff --git a/remote_config/src_java/fake/com/google/firebase/remoteconfig/FirebaseRemoteConfigSettings.java b/remote_config/src_java/fake/com/google/firebase/remoteconfig/FirebaseRemoteConfigSettings.java index da32edfb49..0cd609025e 100644 --- a/remote_config/src_java/fake/com/google/firebase/remoteconfig/FirebaseRemoteConfigSettings.java +++ b/remote_config/src_java/fake/com/google/firebase/remoteconfig/FirebaseRemoteConfigSettings.java @@ -20,7 +20,6 @@ /** Fake FirebaseRemoteConfigSettings */ public class FirebaseRemoteConfigSettings { - private static final String FN_GET_FETCH_TIMEOUT = "FirebaseRemoteConfig.getFetchTimeoutInSeconds"; private static final String FN_GET_MIN_FETCH_INTERVAL = diff --git a/remote_config/src_java/fake/com/google/firebase/remoteconfig/FirebaseRemoteConfigValue.java b/remote_config/src_java/fake/com/google/firebase/remoteconfig/FirebaseRemoteConfigValue.java index 1095739e48..dcb5bc44c8 100644 --- a/remote_config/src_java/fake/com/google/firebase/remoteconfig/FirebaseRemoteConfigValue.java +++ b/remote_config/src_java/fake/com/google/firebase/remoteconfig/FirebaseRemoteConfigValue.java @@ -22,7 +22,6 @@ /** Fake FirebaseRemoteConfigValue */ public class FirebaseRemoteConfigValue { - public FirebaseRemoteConfigValue() {} public long asLong() { diff --git a/scripts/format_code.py b/scripts/format_code.py index ac58fa8b11..49db3cabcb 100755 --- a/scripts/format_code.py +++ b/scripts/format_code.py @@ -54,7 +54,7 @@ flags.DEFINE_boolean("github_log", False, 'Pring special github log format items.') # Constants: -FILE_TYPE_EXTENSIONS = ('.cpp', '.cc', '.c', '.h') +FILE_TYPE_EXTENSIONS = ('.cpp', '.cc', '.c', '.h', '.m', '.mm', '.java') """Tuple: The file types to run clang-format on. Used to filter out results when searching across directories or git diffs. """ @@ -202,30 +202,6 @@ def validate_arguments(): return False return True -def is_file_objc_header(filename): - """Checks the contents of the file to determine if it contains language - constructs that appear in obj-c but not in C/C++. - - Args: - filename (string): the name of the file to check - - Returns: - bool: True if the header file contains known obj-c language definitions. - Returns False otherwise. - """ - _, ext = os.path.splitext(filename) - if ext != '.h': - return False - objective_c_tags = ('@end', '@class', '#import') - - with open(filename) as header_file: - lines = header_file.readlines() - for line in lines: - for tag in objective_c_tags: - if tag in line: - return True - return False - def main(argv): if not validate_arguments(): sys.exit(2) @@ -252,14 +228,10 @@ def main(argv): count = 0 for filename in filenames: if does_file_need_formatting(filename): - if is_file_objc_header(filename): - if FLAGS.verbose: - print(' - IGNORE OBJC: "{0}"'.format(filename)) - else: - if FLAGS.verbose: - print(' - FRMT: "{0}"'.format(filename)) - format_file(filename) - count += 1 + if FLAGS.verbose: + print(' - FRMT: "{0}"'.format(filename)) + format_file(filename) + count += 1 else: if FLAGS.verbose: print(' - OK: "{0}"'.format(filename)) @@ -268,7 +240,7 @@ def main(argv): github_log = ['::error ::FILE FORMATTING ERRORS:',''] count = 0 for filename in filenames: - if does_file_need_formatting(filename) and not is_file_objc_header(filename): + if does_file_need_formatting(filename): exit_code = 1 count += 1 github_log.append('- Requires reformatting: "{0}"'.format(filename)) diff --git a/scripts/gha/lint_commenter.py b/scripts/gha/lint_commenter.py index a08ef70964..d5560c98fc 100755 --- a/scripts/gha/lint_commenter.py +++ b/scripts/gha/lint_commenter.py @@ -41,6 +41,7 @@ 'build/include_subdir', 'readability/casting', 'whitespace/indent', + 'whitespace/line_length' ] # Exclude files within the following paths (specified as regexes) EXCLUDE_PATH_REGEX = [ diff --git a/storage/src_java/com/google/firebase/storage/internal/cpp/CppByteUploader.java b/storage/src_java/com/google/firebase/storage/internal/cpp/CppByteUploader.java index 9a56331acc..977cfbcb9c 100644 --- a/storage/src_java/com/google/firebase/storage/internal/cpp/CppByteUploader.java +++ b/storage/src_java/com/google/firebase/storage/internal/cpp/CppByteUploader.java @@ -102,8 +102,7 @@ public int read(byte[] bytes, int bytesOffset, int numBytes) throws IOException int spaceAvailable = bytes.length - bytesOffset; if (numBytes < 0 || bytesOffset < 0 || numBytes > spaceAvailable) { throw new IndexOutOfBoundsException( - String.format( - "Attempt to read %d bytes into byte array with %d bytes in space available", + String.format("Attempt to read %d bytes into byte array with %d bytes in space available", numBytes, spaceAvailable)); } // Clamp the number of bytes to read by the data remaining in C++ buffer. @@ -153,11 +152,6 @@ public long skip(long bytesToSkip) throws IOException { *

This method should return the number of bytes copied into the Java byte array, -1 if at the * of the stream or < -1 if an error occurred or streaming was aborted. */ - private static native int readBytes( - long cppBufferPointer, - long cppBufferSize, - long cppBufferOffset, - byte[] bytes, - int bytesOffset, - int numBytesToRead); + private static native int readBytes(long cppBufferPointer, long cppBufferSize, + long cppBufferOffset, byte[] bytes, int bytesOffset, int numBytesToRead); }; diff --git a/testing/com/google/firebase/testing/cppsdk/FakeReporter.java b/testing/com/google/firebase/testing/cppsdk/FakeReporter.java index c0427eccc1..9a369daa02 100644 --- a/testing/com/google/firebase/testing/cppsdk/FakeReporter.java +++ b/testing/com/google/firebase/testing/cppsdk/FakeReporter.java @@ -21,7 +21,6 @@ /** Report what function was called and with wich arguments. */ public final class FakeReporter { - private static Map reports = new HashMap(); public static void reset() { @@ -64,7 +63,6 @@ public static String getFakeResult(String fake) { /** Report for each fake calling */ public static class ReportRow { - private String fake; private List args; diff --git a/testing/com/google/firebase/testing/cppsdk/TickerObserver.java b/testing/com/google/firebase/testing/cppsdk/TickerObserver.java index 70e29e9569..13819a626d 100644 --- a/testing/com/google/firebase/testing/cppsdk/TickerObserver.java +++ b/testing/com/google/firebase/testing/cppsdk/TickerObserver.java @@ -16,7 +16,6 @@ /** Observes the ticker and handle callbacks. */ public interface TickerObserver { - // After registered with TickerAndroid, this will be called per each ticker elapses. public void elapse(); } diff --git a/testing/config_ios.mm b/testing/config_ios.mm index d501e319b2..eddb8566bc 100644 --- a/testing/config_ios.mm +++ b/testing/config_ios.mm @@ -17,9 +17,9 @@ #include +#include "flatbuffers/idl.h" #include "testing/testdata_config_generated.h" #include "testing/testdata_config_resource.h" -#include "flatbuffers/idl.h" #import @@ -38,8 +38,7 @@ void ConfigSet(const char* test_data_in_json) { NSCAssert(parser.Parse(test_data_in_json), @"Invalid JSON:%s", parser.error_.c_str()); // Assign - internal::ConfigSetImpl(parser.builder_.GetBufferPointer(), - parser.builder_.GetSize()); + internal::ConfigSetImpl(parser.builder_.GetBufferPointer(), parser.builder_.GetSize()); } void ConfigReset() { internal::ConfigSetImpl(nullptr, 0); } @@ -60,8 +59,7 @@ void ConfigSet(const char* test_data_in_json) { } namespace internal { -void ConfigSetImpl(const uint8_t* test_data_binary, - flatbuffers::uoffset_t size) { +void ConfigSetImpl(const uint8_t* test_data_binary, flatbuffers::uoffset_t size) { delete[] g_test_data_config; if (test_data_binary != nullptr && size > 0) { g_test_data_config = new uint8_t[size]; diff --git a/testing/run_all_tests.mm b/testing/run_all_tests.mm index 78c7b9e068..069696806d 100644 --- a/testing/run_all_tests.mm +++ b/testing/run_all_tests.mm @@ -33,10 +33,8 @@ - (void)testAll { testing::UnitTest* unit_test = testing::UnitTest::GetInstance(); NSLog(@"Tests finished.\n passed tests: %d\n failed tests: %d\n" " disabled tests: %d\n total tests: %d", - unit_test->successful_test_count(), - unit_test->failed_test_count(), - unit_test->disabled_test_count(), - unit_test->total_test_count()); + unit_test->successful_test_count(), unit_test->failed_test_count(), + unit_test->disabled_test_count(), unit_test->total_test_count()); // Run test could succeed trivially if the test case is not linked. XCTAssertGreaterThan(unit_test->total_test_count(), 0); diff --git a/testing/sample_framework/src/android/java/com/google/firebase/example/LoggingUtils.java b/testing/sample_framework/src/android/java/com/google/firebase/example/LoggingUtils.java index 4ff20e8965..a8fabf28b1 100644 --- a/testing/sample_framework/src/android/java/com/google/firebase/example/LoggingUtils.java +++ b/testing/sample_framework/src/android/java/com/google/firebase/example/LoggingUtils.java @@ -71,37 +71,33 @@ public static void initLogWindow(Activity activity, boolean monospace) { window.setContentView(linearLayout); // Force the TextView to stay scrolled to the bottom. - textView.addTextChangedListener( - new TextWatcher() { - @Override - public void afterTextChanged(Editable e) { - // If the user never interacted with the screen, scroll to bottom. - if (scrollView != null && !didTouch) { - new Handler(Looper.getMainLooper()) - .post( - new Runnable() { - @Override - public void run() { - scrollView.fullScroll(View.FOCUS_DOWN); - } - }); + textView.addTextChangedListener(new TextWatcher() { + @Override + public void afterTextChanged(Editable e) { + // If the user never interacted with the screen, scroll to bottom. + if (scrollView != null && !didTouch) { + new Handler(Looper.getMainLooper()).post(new Runnable() { + @Override + public void run() { + scrollView.fullScroll(View.FOCUS_DOWN); } - } + }); + } + } - @Override - public void beforeTextChanged(CharSequence s, int start, int count, int after) {} + @Override + public void beforeTextChanged(CharSequence s, int start, int count, int after) {} - @Override - public void onTextChanged(CharSequence s, int start, int count, int after) {} - }); - textView.setOnTouchListener( - new View.OnTouchListener() { - @Override - public boolean onTouch(View v, MotionEvent event) { - didTouch = true; - return false; - } - }); + @Override + public void onTextChanged(CharSequence s, int start, int count, int after) {} + }); + textView.setOnTouchListener(new View.OnTouchListener() { + @Override + public boolean onTouch(View v, MotionEvent event) { + didTouch = true; + return false; + } + }); Intent launchIntent = activity.getIntent(); // Check if we are running on Firebase Test Lab, and set up a log file if we are. @@ -112,23 +108,21 @@ public boolean onTouch(View v, MotionEvent event) { /** Adds some text to the log window. */ public static void addLogText(final String text) { - new Handler(Looper.getMainLooper()) - .post( - new Runnable() { - @Override - public void run() { - if (textView != null) { - textView.append(text); - if (logFileStream != null) { - try { - logFileStream.writeBytes(text); - } catch (IOException e) { - // It doesn't really matter if something went wrong writing to the test log. - } - } - } - } - }); + new Handler(Looper.getMainLooper()).post(new Runnable() { + @Override + public void run() { + if (textView != null) { + textView.append(text); + if (logFileStream != null) { + try { + logFileStream.writeBytes(text); + } catch (IOException e) { + // It doesn't really matter if something went wrong writing to the test log. + } + } + } + } + }); } /** diff --git a/testing/sample_framework/src/android/java/com/google/firebase/example/TextEntryField.java b/testing/sample_framework/src/android/java/com/google/firebase/example/TextEntryField.java index 34c59fa55d..940b5e19ca 100644 --- a/testing/sample_framework/src/android/java/com/google/firebase/example/TextEntryField.java +++ b/testing/sample_framework/src/android/java/com/google/firebase/example/TextEntryField.java @@ -35,53 +35,47 @@ public static String readText( final Activity activity, final String title, final String message, final String placeholder) { resultText = null; // Show the alert dialog on the main thread. - activity.runOnUiThread( - new Runnable() { - @Override - public void run() { - AlertDialog.Builder alertBuilder = new AlertDialog.Builder(activity); - alertBuilder.setTitle(title); - alertBuilder.setMessage(message); + activity.runOnUiThread(new Runnable() { + @Override + public void run() { + AlertDialog.Builder alertBuilder = new AlertDialog.Builder(activity); + alertBuilder.setTitle(title); + alertBuilder.setMessage(message); - // Set up and add the text field. - final EditText textField = new EditText(activity); - textField.setHint(placeholder); - alertBuilder.setView(textField); + // Set up and add the text field. + final EditText textField = new EditText(activity); + textField.setHint(placeholder); + alertBuilder.setView(textField); - alertBuilder.setPositiveButton( - "OK", - new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int whichButton) { - synchronized (lock) { - resultText = textField.getText().toString(); - } - } - }); + alertBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int whichButton) { + synchronized (lock) { + resultText = textField.getText().toString(); + } + } + }); - alertBuilder.setNegativeButton( - "Cancel", - new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int whichButton) { - synchronized (lock) { - resultText = ""; - } - } - }); + alertBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int whichButton) { + synchronized (lock) { + resultText = ""; + } + } + }); - alertBuilder.setOnCancelListener( - new DialogInterface.OnCancelListener() { - @Override - public void onCancel(DialogInterface dialog) { - synchronized (lock) { - resultText = ""; - } - } - }); - alertBuilder.show(); + alertBuilder.setOnCancelListener(new DialogInterface.OnCancelListener() { + @Override + public void onCancel(DialogInterface dialog) { + synchronized (lock) { + resultText = ""; + } } }); + alertBuilder.show(); + } + }); // In our original thread, wait for the dialog to finish, then return its result. while (true) { diff --git a/testing/sample_framework/src/ios/ios_app_framework.mm b/testing/sample_framework/src/ios/ios_app_framework.mm old mode 100755 new mode 100644 index c692491fa8..b7a32a1bc3 --- a/testing/sample_framework/src/ios/ios_app_framework.mm +++ b/testing/sample_framework/src/ios/ios_app_framework.mm @@ -24,12 +24,12 @@ #include #include #include -#include #include +#include #include "app_framework.h" -@interface AppDelegate : UIResponder +@interface AppDelegate : UIResponder @property(nonatomic, strong) UIWindow *window; @@ -41,18 +41,14 @@ @interface FTAViewController : UIViewController @end -static NSString * const kGameLoopUrlPrefix= @"firebase-game-loop"; -static NSString * const kGameLoopCompleteUrlScheme= @"firebase-game-loop-complete://"; +static NSString *const kGameLoopUrlPrefix = @"firebase-game-loop"; +static NSString *const kGameLoopCompleteUrlScheme = @"firebase-game-loop-complete://"; static const float kGameLoopSecondsToPauseBeforeQuitting = 5.0f; // Test Loop on iOS doesn't provide the app under test a path to save logs to, so set it here. #define GAMELOOP_DEFAULT_LOG_FILE "Results1.json" -enum class RunningState { - kRunning, - kShuttingDown, - kShutDown -}; +enum class RunningState { kRunning, kShuttingDown, kShutDown }; // Note: g_running_state and g_exit_status must only be accessed while holding the lock from // g_running_state_condition; also, any changes to these values should be followed up with a @@ -103,7 +99,7 @@ - (void)viewDidLoad { namespace app_framework { bool ProcessEvents(int msec) { - NSDate* endDate = [NSDate dateWithTimeIntervalSinceNow:static_cast(msec) / 1000.0f]; + NSDate *endDate = [NSDate dateWithTimeIntervalSinceNow:static_cast(msec) / 1000.0f]; [g_running_state_condition lock]; if (g_running_state == RunningState::kRunning) { @@ -125,9 +121,7 @@ bool ProcessEvents(int msec) { [[documentsDirectory stringByStandardizingPath] stringByAppendingString:@"/"].UTF8String); } -WindowContext GetWindowContext() { - return g_parent_view; -} +WindowContext GetWindowContext() { return g_parent_view; } // Log a message that can be viewed in the console. void LogMessageV(bool suppress, const char *format, va_list list) { @@ -155,7 +149,7 @@ void LogMessage(const char *format, ...) { static bool g_save_full_log = false; static std::vector g_full_logs; // NOLINT -void AddToFullLog(const char* str) { g_full_logs.push_back(std::string(str)); } +void AddToFullLog(const char *str) { g_full_logs.push_back(std::string(str)); } bool GetPreserveFullLog() { return g_save_full_log; } void SetPreserveFullLog(bool b) { g_save_full_log = b; } @@ -191,7 +185,6 @@ void AddToTextView(const char *str) { [data writeToFile:g_file_url_path atomically:YES]; } } - } // Remove all lines starting with these strings. @@ -225,10 +218,10 @@ bool should_filter(const char *str) { return nullptr; } -void RunOnBackgroundThread(void* (*func)(void*), void* data) { +void RunOnBackgroundThread(void *(*func)(void *), void *data) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ - func(data); - }); + func(data); + }); } // Create an alert dialog via UIAlertController, and prompt the user to enter a line of text. @@ -305,7 +298,7 @@ bool StartLoggingToFile(const char *file_path) { } // namespace app_framework -int main(int argc, char* argv[]) { +int main(int argc, char *argv[]) { // Pipe stdout to call LogToTextView so we can see the gtest output. int filedes[2]; assert(pipe(filedes) != -1); @@ -335,7 +328,7 @@ - (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary *)options { #if TARGET_OS_SIMULATOR - setenv("USE_FIRESTORE_EMULATOR","true",1); + setenv("USE_FIRESTORE_EMULATOR", "true", 1); #endif if ([url.scheme isEqual:kGameLoopUrlPrefix]) { @@ -348,8 +341,8 @@ - (BOOL)application:(UIApplication *)app return NO; } -- (BOOL)application:(UIApplication*)application - didFinishLaunchingWithOptions:(NSDictionary*)launchOptions { +- (BOOL)application:(UIApplication *)application + didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { g_running_state_condition = [[NSCondition alloc] init]; self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds]; @@ -362,7 +355,7 @@ - (BOOL)application:(UIApplication*)application g_text_view.accessibilityIdentifier = @"Logger"; #if TARGET_OS_IOS g_text_view.editable = NO; -#endif //TARGET_OS_IOS +#endif // TARGET_OS_IOS g_text_view.scrollEnabled = YES; g_text_view.userInteractionEnabled = YES; g_text_view.font = [UIFont fontWithName:@"Courier" size:10]; diff --git a/testing/util_ios.h b/testing/util_ios.h index 03c18c2af1..c20c06657f 100644 --- a/testing/util_ios.h +++ b/testing/util_ios.h @@ -20,8 +20,8 @@ #include #include -#include "testing/ticker_ios.h" #include "testing/config_ios.h" +#include "testing/ticker_ios.h" NS_ASSUME_NONNULL_BEGIN @@ -35,11 +35,9 @@ typedef void (^Callback)(NSError* _Nullable error); // A test helper class to make tickers which call back at certain ticks. class CallbackTicker : public firebase::testing::cppsdk::TickerObserver { public: - explicit CallbackTicker(NSString* config_key, ParamCallback completion, - id param, int error_code); + explicit CallbackTicker(NSString* config_key, ParamCallback completion, id param, int error_code); - explicit CallbackTicker(NSString* config_key, Callback completion, - int error_code); + explicit CallbackTicker(NSString* config_key, Callback completion, int error_code); void Elapse() override; diff --git a/testing/util_ios.mm b/testing/util_ios.mm index 5c529846f3..35b554bf90 100644 --- a/testing/util_ios.mm +++ b/testing/util_ios.mm @@ -85,7 +85,7 @@ [NSString stringWithUTF8String:row->futuregeneric()->exceptionmsg()->c_str()]; error_ = [NSError errorWithDomain:config_key code:error_code_ - userInfo:@{@"Error reason":errorMsg}]; + userInfo:@{@"Error reason" : errorMsg}]; return false; } else { return true; @@ -103,19 +103,16 @@ std::shared_ptr(new CallbackTicker(config_key, completion, error))); } - // Deprecated. void CallbackTickerManager::Add(NSString* config_key, ParamCallback completion, id param) { - tickers_.push_back( - std::shared_ptr(new CallbackTicker(config_key, completion, param, - DEPRECATED_DEFAULT_ERROR_VALUE))); + tickers_.push_back(std::shared_ptr( + new CallbackTicker(config_key, completion, param, DEPRECATED_DEFAULT_ERROR_VALUE))); } // Deprecated. void CallbackTickerManager::Add(NSString* config_key, Callback completion) { - tickers_.push_back( - std::shared_ptr(new CallbackTicker(config_key, completion, - DEPRECATED_DEFAULT_ERROR_VALUE))); + tickers_.push_back(std::shared_ptr( + new CallbackTicker(config_key, completion, DEPRECATED_DEFAULT_ERROR_VALUE))); } } // namespace cppsdk } // namespace testing diff --git a/testing/util_ios_test.mm b/testing/util_ios_test.mm index cc1197769b..b17b58b716 100644 --- a/testing/util_ios_test.mm +++ b/testing/util_ios_test.mm @@ -16,11 +16,11 @@ #include +#include "gmock/gmock.h" +#include "gtest/gtest.h" #include "testing/config.h" #include "testing/ticker.h" #include "testing/util_ios.h" -#include "gmock/gmock.h" -#include "gtest/gtest.h" namespace firebase { namespace testing { @@ -28,25 +28,38 @@ TEST(TickerTest, TestCallbackTicker) { TickerReset(); - ConfigSet( - "{" - " config:[" - " {fake:'a',futuregeneric:{throwexception:false,ticker:1}}," - " {fake:'b',futuregeneric:{throwexception:true,exceptionmsg:'failed',ticker:2}}," - " {fake:'c',futuregeneric:{throwexception:false,ticker:3}}," - " {fake:'d',futuregeneric:{throwexception:true,exceptionmsg:'failed',ticker:4}}" - " ]" - "}"); + ConfigSet("{" + " config:[" + " {fake:'a',futuregeneric:{throwexception:false,ticker:1}}," + " {fake:'b',futuregeneric:{throwexception:true,exceptionmsg:'failed',ticker:2}}," + " {fake:'c',futuregeneric:{throwexception:false,ticker:3}}," + " {fake:'d',futuregeneric:{throwexception:true,exceptionmsg:'failed',ticker:4}}" + " ]" + "}"); __block int count = 0; // Now we create four fake objects on the fly; all are managed by manager. CallbackTickerManager manager; // Without param. - manager.Add(@"a", ^(NSError* _Nullable error) { if (!error) count++; }); - manager.Add(@"b", ^(NSError* _Nullable error) { if (!error) count++; }); + manager.Add(@"a", ^(NSError* _Nullable error) { + if (!error) count++; + }); + manager.Add(@"b", ^(NSError* _Nullable error) { + if (!error) count++; + }); // With param. - manager.Add(@"c", ^(NSString* param, NSError* _Nullable error) { if (!error) count++; }, @"par"); - manager.Add(@"d", ^(NSString* param, NSError* _Nullable error) { if (!error) count++; }, @"par"); + manager.Add( + @"c", + ^(NSString* param, NSError* _Nullable error) { + if (!error) count++; + }, + @"par"); + manager.Add( + @"d", + ^(NSString* param, NSError* _Nullable error) { + if (!error) count++; + }, + @"par"); // nothing happens so far. EXPECT_EQ(0, count);