Update Dialer source to latest internal Google revision.

Previously, Android's Dialer app was developed in an internal Google
source control system and only exported to public during AOSP drops.

The Dialer team is now switching to a public development model similar
to the telephony team.

This CL represents all internal Google changes that were committed to
Dialer between the public O release and today's tip of tree on internal
master. This CL squashes those changes into a single commit.
In subsequent changes, changes will be exported on a per-commit basis.

Test: make, flash install, run
Merged-In: I45270eaa8ce732d71a1bd84b08c7fa0e99af3160
Change-Id: I529aaeb88535b9533c0ae4ef4e6c1222d4e0f1c8
PiperOrigin-RevId: 167068436
diff --git a/java/com/android/incallui/call/DialerCall.java b/java/com/android/incallui/call/DialerCall.java
index acedf41..1a99809 100644
--- a/java/com/android/incallui/call/DialerCall.java
+++ b/java/com/android/incallui/call/DialerCall.java
@@ -41,16 +41,20 @@
 import android.telephony.PhoneNumberUtils;
 import android.text.TextUtils;
 import com.android.contacts.common.compat.CallCompat;
-import com.android.contacts.common.compat.TelephonyManagerCompat;
 import com.android.contacts.common.compat.telecom.TelecomManagerCompat;
 import com.android.dialer.callintent.CallInitiationType;
 import com.android.dialer.callintent.CallIntentParser;
 import com.android.dialer.callintent.CallSpecificAppData;
 import com.android.dialer.common.Assert;
-import com.android.dialer.common.ConfigProviderBindings;
 import com.android.dialer.common.LogUtil;
+import com.android.dialer.compat.telephony.TelephonyManagerCompat;
+import com.android.dialer.configprovider.ConfigProviderBindings;
 import com.android.dialer.enrichedcall.EnrichedCallCapabilities;
 import com.android.dialer.enrichedcall.EnrichedCallComponent;
+import com.android.dialer.enrichedcall.EnrichedCallManager;
+import com.android.dialer.enrichedcall.EnrichedCallManager.CapabilitiesListener;
+import com.android.dialer.enrichedcall.EnrichedCallManager.Filter;
+import com.android.dialer.enrichedcall.EnrichedCallManager.StateChangedListener;
 import com.android.dialer.enrichedcall.Session;
 import com.android.dialer.lightbringer.LightbringerComponent;
 import com.android.dialer.logging.ContactLookupResult;
@@ -77,7 +81,7 @@
 import java.util.concurrent.TimeUnit;
 
 /** Describes a single call and its state. */
-public class DialerCall implements VideoTechListener {
+public class DialerCall implements VideoTechListener, StateChangedListener, CapabilitiesListener {
 
   public static final int CALL_HISTORY_STATUS_UNKNOWN = 0;
   public static final int CALL_HISTORY_STATUS_PRESENT = 1;
@@ -143,6 +147,13 @@
   private EnrichedCallCapabilities mEnrichedCallCapabilities;
   private Session mEnrichedCallSession;
 
+  private int answerAndReleaseButtonDisplayedTimes = 0;
+  private boolean releasedByAnsweringSecondCall = false;
+  // Times when a second call is received but AnswerAndRelease button is not shown
+  // since it's not supported.
+  private int secondCallWithoutAnswerAndReleasedButtonTimes = 0;
+  private VideoTech videoTech;
+
   public static String getNumberFromHandle(Uri handle) {
     return handle == null ? "" : handle.getSchemeSpecificPart();
   }
@@ -153,6 +164,9 @@
    */
   private boolean isRemotelyHeld;
 
+  /** Indicates whether this call is currently in the process of being merged into a conference. */
+  private boolean isMergeInProcess;
+
   /**
    * Indicates whether the phone account associated with this call supports specifying a call
    * subject.
@@ -181,14 +195,15 @@
 
         @Override
         public void onDetailsChanged(Call call, Call.Details details) {
-          LogUtil.v("TelecomCallCallback.onStateChanged", " call=" + call + " details=" + details);
+          LogUtil.v(
+              "TelecomCallCallback.onDetailsChanged", " call=" + call + " details=" + details);
           update();
         }
 
         @Override
         public void onCannedTextResponsesLoaded(Call call, List<String> cannedTextResponses) {
           LogUtil.v(
-              "TelecomCallCallback.onStateChanged",
+              "TelecomCallCallback.onCannedTextResponsesLoaded",
               "call=" + call + " cannedTextResponses=" + cannedTextResponses);
           for (CannedTextResponsesLoadedListener listener : mCannedTextResponsesLoadedListeners) {
             listener.onCannedTextResponsesLoaded(DialerCall.this);
@@ -198,7 +213,7 @@
         @Override
         public void onPostDialWait(Call call, String remainingPostDialSequence) {
           LogUtil.v(
-              "TelecomCallCallback.onStateChanged",
+              "TelecomCallCallback.onPostDialWait",
               "call=" + call + " remainingPostDialSequence=" + remainingPostDialSequence);
           update();
         }
@@ -206,20 +221,20 @@
         @Override
         public void onVideoCallChanged(Call call, VideoCall videoCall) {
           LogUtil.v(
-              "TelecomCallCallback.onStateChanged", "call=" + call + " videoCall=" + videoCall);
+              "TelecomCallCallback.onVideoCallChanged", "call=" + call + " videoCall=" + videoCall);
           update();
         }
 
         @Override
         public void onCallDestroyed(Call call) {
-          LogUtil.v("TelecomCallCallback.onStateChanged", "call=" + call);
+          LogUtil.v("TelecomCallCallback.onCallDestroyed", "call=" + call);
           unregisterCallback();
         }
 
         @Override
         public void onConferenceableCallsChanged(Call call, List<Call> conferenceableCalls) {
           LogUtil.v(
-              "DialerCall.onConferenceableCallsChanged",
+              "TelecomCallCallback.onConferenceableCallsChanged",
               "call %s, conferenceable calls: %d",
               call,
               conferenceableCalls.size());
@@ -229,7 +244,7 @@
         @Override
         public void onConnectionEvent(android.telecom.Call call, String event, Bundle extras) {
           LogUtil.v(
-              "DialerCall.onConnectionEvent",
+              "TelecomCallCallback.onConnectionEvent",
               "Call: " + call + ", Event: " + event + ", Extras: " + extras);
           switch (event) {
               // The Previous attempt to Merge two calls together has failed in Telecom. We must
@@ -255,6 +270,14 @@
             case TelephonyManagerCompat.EVENT_NOTIFY_INTERNATIONAL_CALL_ON_WFC:
               notifyInternationalCallOnWifi();
               break;
+            case TelephonyManagerCompat.EVENT_MERGE_START:
+              LogUtil.i("DialerCall.onConnectionEvent", "merge start");
+              isMergeInProcess = true;
+              break;
+            case TelephonyManagerCompat.EVENT_MERGE_COMPLETE:
+              LogUtil.i("DialerCall.onConnectionEvent", "merge complete");
+              isMergeInProcess = false;
+              break;
             default:
               break;
           }
@@ -292,6 +315,8 @@
 
     mTimeAddedMs = System.currentTimeMillis();
     parseCallSpecificAppData();
+
+    updateEnrichedCallSession();
   }
 
   private static int translateState(int state) {
@@ -404,15 +429,27 @@
     }
   }
 
+  public boolean wasParentCall() {
+    return mLogState.conferencedCalls != 0;
+  }
+
   private void update() {
-    Trace.beginSection("Update");
+    Trace.beginSection("DialerCall.update");
     int oldState = getState();
+    // Clear any cache here that could potentially change on update.
+    videoTech = null;
     // We want to potentially register a video call callback here.
     updateFromTelecomCall();
     if (oldState != getState() && getState() == DialerCall.State.DISCONNECTED) {
       for (DialerCallListener listener : mListeners) {
         listener.onDialerCallDisconnect();
       }
+      EnrichedCallComponent.get(mContext)
+          .getEnrichedCallManager()
+          .unregisterCapabilitiesListener(this);
+      EnrichedCallComponent.get(mContext)
+          .getEnrichedCallManager()
+          .unregisterStateChangedListener(this);
     } else {
       for (DialerCallListener listener : mListeners) {
         listener.onDialerCallUpdate();
@@ -422,6 +459,7 @@
   }
 
   private void updateFromTelecomCall() {
+    Trace.beginSection("DialerCall.updateFromTelecomCall");
     LogUtil.v("DialerCall.updateFromTelecomCall", mTelecomCall.toString());
 
     mVideoTechManager.dispatchCallStateChanged(mTelecomCall.getState());
@@ -470,6 +508,7 @@
         }
       }
     }
+    Trace.endSection();
   }
 
   /**
@@ -647,13 +686,23 @@
   }
 
   public void setState(int state) {
-    mState = state;
-    if (mState == State.INCOMING) {
+    if (state == State.INCOMING) {
       mLogState.isIncoming = true;
-    } else if (mState == State.DISCONNECTED) {
-      mLogState.duration =
+    } else if (state == State.DISCONNECTED) {
+      long newDuration =
           getConnectTimeMillis() == 0 ? 0 : System.currentTimeMillis() - getConnectTimeMillis();
+      if (mState != state) {
+        mLogState.duration = newDuration;
+      } else {
+        LogUtil.i(
+            "DialerCall.setState",
+            "ignoring state transition from DISCONNECTED to DISCONNECTED."
+                + " Duration would have changed from %s to %s",
+            mLogState.duration,
+            newDuration);
+      }
     }
+    mState = state;
   }
 
   public int getNumberPresentation() {
@@ -952,14 +1001,49 @@
     return isRemotelyHeld;
   }
 
+  public boolean isMergeInProcess() {
+    return isMergeInProcess;
+  }
+
   public boolean isIncoming() {
     return mLogState.isIncoming;
   }
 
+  public boolean isAssistedDialed() {
+    if (getIntentExtras() != null) {
+      return getIntentExtras().getBoolean(TelephonyManagerCompat.IS_ASSISTED_DIALED, false);
+    }
+    return false;
+  }
+
   public LatencyReport getLatencyReport() {
     return mLatencyReport;
   }
 
+  public int getAnswerAndReleaseButtonDisplayedTimes() {
+    return answerAndReleaseButtonDisplayedTimes;
+  }
+
+  public void increaseAnswerAndReleaseButtonDisplayedTimes() {
+    answerAndReleaseButtonDisplayedTimes++;
+  }
+
+  public boolean getReleasedByAnsweringSecondCall() {
+    return releasedByAnsweringSecondCall;
+  }
+
+  public void setReleasedByAnsweringSecondCall(boolean releasedByAnsweringSecondCall) {
+    this.releasedByAnsweringSecondCall = releasedByAnsweringSecondCall;
+  }
+
+  public int getSecondCallWithoutAnswerAndReleasedButtonTimes() {
+    return secondCallWithoutAnswerAndReleasedButtonTimes;
+  }
+
+  public void increaseSecondCallWithoutAnswerAndReleasedButtonTimes() {
+    secondCallWithoutAnswerAndReleasedButtonTimes++;
+  }
+
   @Nullable
   public EnrichedCallCapabilities getEnrichedCallCapabilities() {
     return mEnrichedCallCapabilities;
@@ -1057,7 +1141,10 @@
   }
 
   public VideoTech getVideoTech() {
-    return mVideoTechManager.getVideoTech();
+    if (videoTech == null) {
+      videoTech = mVideoTechManager.getVideoTech();
+    }
+    return videoTech;
   }
 
   public String getCallbackNumber() {
@@ -1172,6 +1259,76 @@
     TelecomAdapter.getInstance().setAudioRoute(CallAudioState.ROUTE_SPEAKER);
   }
 
+  @Override
+  public void onCapabilitiesUpdated() {
+    if (getNumber() == null) {
+      return;
+    }
+    EnrichedCallCapabilities capabilities =
+        EnrichedCallComponent.get(mContext).getEnrichedCallManager().getCapabilities(getNumber());
+    if (capabilities != null) {
+      setEnrichedCallCapabilities(capabilities);
+      update();
+    }
+  }
+
+  @Override
+  public void onEnrichedCallStateChanged() {
+    updateEnrichedCallSession();
+  }
+
+  @Override
+  public void onImpressionLoggingNeeded(DialerImpression.Type impressionType) {
+    Logger.get(mContext).logCallImpression(impressionType, getUniqueCallId(), getTimeAddedMs());
+  }
+
+  private void updateEnrichedCallSession() {
+    if (getNumber() == null) {
+      return;
+    }
+    if (getEnrichedCallSession() != null) {
+      // State changes to existing sessions are currently handled by the UI components (which have
+      // their own listeners). Someday instead we could remove those and just call update() here and
+      // have the usual onDialerCallUpdate update the UI.
+      dispatchOnEnrichedCallSessionUpdate();
+      return;
+    }
+
+    EnrichedCallManager manager = EnrichedCallComponent.get(mContext).getEnrichedCallManager();
+
+    Filter filter =
+        isIncoming()
+            ? manager.createIncomingCallComposerFilter()
+            : manager.createOutgoingCallComposerFilter();
+
+    Session session = manager.getSession(getUniqueCallId(), getNumber(), filter);
+    if (session == null) {
+      return;
+    }
+
+    session.setUniqueDialerCallId(getUniqueCallId());
+    setEnrichedCallSession(session);
+
+    LogUtil.i(
+        "DialerCall.updateEnrichedCallSession",
+        "setting session %d's dialer id to %s",
+        session.getSessionId(),
+        getUniqueCallId());
+
+    dispatchOnEnrichedCallSessionUpdate();
+  }
+
+  private void dispatchOnEnrichedCallSessionUpdate() {
+    for (DialerCallListener listener : mListeners) {
+      listener.onEnrichedCallSessionUpdate();
+    }
+  }
+
+  void onRemovedFromCallList() {
+    // Ensure we clean up when this call is removed.
+    mVideoTechManager.dispatchRemovedFromCallList();
+  }
+
   /**
    * Specifies whether a number is in the call history or not. {@link #CALL_HISTORY_STATUS_UNKNOWN}
    * means there is no result.
@@ -1203,6 +1360,7 @@
     public static final int CONNECTING = 13; /* Waiting for Telecom broadcast to finish */
     public static final int BLOCKED = 14; /* The number was found on the block list */
     public static final int PULLING = 15; /* An external call being pulled to the device */
+    public static final int CALL_PENDING = 16; /* A call is pending on a long process to finish */
 
     public static boolean isConnectingOrConnected(int state) {
       switch (state) {
@@ -1372,6 +1530,7 @@
 
       String phoneNumber = call.getNumber();
       phoneNumber = phoneNumber != null ? phoneNumber : "";
+      phoneNumber = phoneNumber.replaceAll("[^+0-9]", "");
 
       // Insert order here determines the priority of that video tech option
       videoTechs = new ArrayList<>();
@@ -1390,7 +1549,10 @@
 
       videoTechs.add(
           new LightbringerTech(
-              LightbringerComponent.get(call.mContext).getLightbringer(), call, phoneNumber));
+              LightbringerComponent.get(call.mContext).getLightbringer(),
+              call,
+              call.mTelecomCall,
+              phoneNumber));
     }
 
     VideoTech getVideoTech() {
@@ -1402,6 +1564,7 @@
         if (tech.isAvailable(context)) {
           // Remember the first VideoTech that becomes available and always use it
           savedTech = tech;
+          savedTech.becomePrimary();
           return savedTech;
         }
       }
@@ -1414,6 +1577,12 @@
         videoTech.onCallStateChanged(context, newState);
       }
     }
+
+    void dispatchRemovedFromCallList() {
+      for (VideoTech videoTech : videoTechs) {
+        videoTech.onRemovedFromCallList();
+      }
+    }
   }
 
   /** Called when canned text responses have been loaded. */