summaryrefslogtreecommitdiff
path: root/java/com/android/dialer/speeddial/DisambigDialog.java
blob: ca02f41eb09fae1fbf3c0ad233afbe51c7b1236e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
/*
 * Copyright (C) 2017 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License
 */

package com.android.dialer.speeddial;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.FragmentManager;
import android.content.ContentResolver;
import android.content.res.Resources;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.support.annotation.Nullable;
import android.support.annotation.VisibleForTesting;
import android.text.TextUtils;
import android.util.ArraySet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.android.dialer.callintent.CallInitiationType;
import com.android.dialer.callintent.CallIntentBuilder;
import com.android.dialer.common.LogUtil;
import com.android.dialer.common.concurrent.DialerExecutor.Worker;
import com.android.dialer.common.concurrent.DialerExecutorComponent;
import com.android.dialer.duo.DuoComponent;
import com.android.dialer.precall.PreCall;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Set;

/** Disambiguation dialog for favorite contacts in {@link SpeedDialFragment}. */
public class DisambigDialog extends DialogFragment {

  @VisibleForTesting public static final String DISAMBIG_DIALOG_TAG = "disambig_dialog";
  private static final String DISAMBIG_DIALOG_WORKER_TAG = "disambig_dialog_worker";

  private final Set<String> phoneNumbers = new ArraySet<>();
  private LinearLayout container;
  private String lookupKey;

  /** Show a disambiguation dialog for a starred contact without a favorite communication avenue. */
  public static DisambigDialog show(String lookupKey, FragmentManager manager) {
    DisambigDialog dialog = new DisambigDialog();
    dialog.lookupKey = lookupKey;
    dialog.show(manager, DISAMBIG_DIALOG_TAG);
    return dialog;
  }

  @Override
  public Dialog onCreateDialog(Bundle savedInstanceState) {
    LayoutInflater inflater = getActivity().getLayoutInflater();
    View view = inflater.inflate(R.layout.disambig_dialog_layout, null, false);
    container = view.findViewById(R.id.communication_avenue_container);
    return new AlertDialog.Builder(getActivity()).setView(view).create();
  }

  @Override
  public void onResume() {
    super.onResume();
    lookupContactInfo();
  }

  @Override
  public void onPause() {
    super.onPause();
    // TODO(calderwoodra): for simplicity, just dismiss the dialog on configuration change and
    // consider changing this later.
    dismiss();
  }

  private void lookupContactInfo() {
    DialerExecutorComponent.get(getContext())
        .dialerExecutorFactory()
        .createUiTaskBuilder(
            getFragmentManager(),
            DISAMBIG_DIALOG_WORKER_TAG,
            new LookupContactInfoWorker(getContext().getContentResolver()))
        .onSuccess(this::insertOptions)
        .onFailure(this::onLookupFailed)
        .build()
        .executeParallel(lookupKey);
  }

  /**
   * Inflates and inserts the following in the dialog:
   *
   * <ul>
   *   <li>Header for each unique phone number
   *   <li>Clickable video option if the phone number is video reachable (ViLTE, Duo)
   *   <li>Clickable voice option
   * </ul>
   */
  private void insertOptions(Cursor cursor) {
    if (!cursorIsValid(cursor)) {
      dismiss();
      return;
    }

    do {
      String number = cursor.getString(LookupContactInfoWorker.NUMBER_INDEX);
      // TODO(calderwoodra): improve this to include fuzzy matching
      if (phoneNumbers.add(number)) {
        insertOption(
            number,
            getLabel(getContext().getResources(), cursor),
            isVideoReachable(cursor, number));
      }
    } while (cursor.moveToNext());
    cursor.close();
    // TODO(calderwoodra): set max height of the scrollview. Might need to override onMeasure.
  }

  /** Returns true if the given number is ViLTE reachable or Duo reachable. */
  private boolean isVideoReachable(Cursor cursor, String number) {
    boolean isVideoReachable = cursor.getInt(LookupContactInfoWorker.PHONE_PRESENCE_INDEX) == 1;
    if (!isVideoReachable) {
      isVideoReachable = DuoComponent.get(getContext()).getDuo().isReachable(getContext(), number);
    }
    return isVideoReachable;
  }

  /** Inserts a group of options for a specific phone number. */
  private void insertOption(String number, String phoneType, boolean isVideoReachable) {
    View view =
        getActivity()
            .getLayoutInflater()
            .inflate(R.layout.disambig_option_layout, container, false);
    ((TextView) view.findViewById(R.id.phone_type)).setText(phoneType);
    ((TextView) view.findViewById(R.id.phone_number)).setText(number);

    if (isVideoReachable) {
      View videoOption = view.findViewById(R.id.video_call_container);
      videoOption.setOnClickListener(v -> onVideoOptionClicked(number));
      videoOption.setVisibility(View.VISIBLE);
    }
    View voiceOption = view.findViewById(R.id.voice_call_container);
    voiceOption.setOnClickListener(v -> onVoiceOptionClicked(number));
    container.addView(view);
  }

  private void onVideoOptionClicked(String number) {
    // TODO(calderwoodra): save this option if remember is checked
    // TODO(calderwoodra): place a duo call if possible
    PreCall.start(
        getContext(),
        new CallIntentBuilder(number, CallInitiationType.Type.SPEED_DIAL).setIsVideoCall(true));
  }

  private void onVoiceOptionClicked(String number) {
    // TODO(calderwoodra): save this option if remember is checked
    PreCall.start(getContext(), new CallIntentBuilder(number, CallInitiationType.Type.SPEED_DIAL));
  }

  // TODO(calderwoodra): handle CNAP and cequint types.
  // TODO(calderwoodra): unify this into a utility method with CallLogAdapter#getNumberType
  private static String getLabel(Resources resources, Cursor cursor) {
    int numberType = cursor.getInt(LookupContactInfoWorker.PHONE_TYPE_INDEX);
    String numberLabel = cursor.getString(LookupContactInfoWorker.PHONE_LABEL_INDEX);

    // Returns empty label instead of "custom" if the custom label is empty.
    if (numberType == Phone.TYPE_CUSTOM && TextUtils.isEmpty(numberLabel)) {
      return "";
    }
    return (String) Phone.getTypeLabel(resources, numberType, numberLabel);
  }

  // Checks if the cursor is valid and logs an error if there are any issues.
  private static boolean cursorIsValid(Cursor cursor) {
    if (cursor == null) {
      LogUtil.e("DisambigDialog.insertOptions", "cursor null.");
      return false;
    } else if (cursor.isClosed()) {
      LogUtil.e("DisambigDialog.insertOptions", "cursor closed.");
      cursor.close();
      return false;
    } else if (!cursor.moveToFirst()) {
      LogUtil.e("DisambigDialog.insertOptions", "cursor empty.");
      cursor.close();
      return false;
    }
    return true;
  }

  private void onLookupFailed(Throwable throwable) {
    LogUtil.e("DisambigDialog.onLookupFailed", null, throwable);
    insertOptions(null);
  }

  private static class LookupContactInfoWorker implements Worker<String, Cursor> {

    static final int NUMBER_INDEX = 0;
    static final int PHONE_TYPE_INDEX = 1;
    static final int PHONE_LABEL_INDEX = 2;
    static final int PHONE_PRESENCE_INDEX = 3;

    private static final String[] projection =
        new String[] {Phone.NUMBER, Phone.TYPE, Phone.LABEL, Phone.CARRIER_PRESENCE};
    private final ContentResolver resolver;

    LookupContactInfoWorker(ContentResolver resolver) {
      this.resolver = resolver;
    }

    @Nullable
    @Override
    public Cursor doInBackground(@Nullable String lookupKey) throws Throwable {
      if (TextUtils.isEmpty(lookupKey)) {
        LogUtil.e("LookupConctactInfoWorker.doInBackground", "contact id unsest.");
        return null;
      }
      return resolver.query(
          Phone.CONTENT_URI, projection, Phone.LOOKUP_KEY + " = ?", new String[] {lookupKey}, null);
    }
  }

  @VisibleForTesting
  public static String[] getProjectionForTesting() {
    ArrayList<String> projection =
        new ArrayList<>(Arrays.asList(LookupContactInfoWorker.projection));
    projection.add(Phone.LOOKUP_KEY);
    return projection.toArray(new String[projection.size()]);
  }

  @VisibleForTesting
  public LinearLayout getContainer() {
    return container;
  }
}