summaryrefslogtreecommitdiff
path: root/InCallUI/src/com/android/incallui/CallCardPresenter.java
blob: cc2e3bf54cdf1fea867f0554a9601f0ec96f36b6 (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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
/*
 * Copyright (C) 2013 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.incallui;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.text.TextUtils;
import android.text.format.DateUtils;

import com.android.incallui.AudioModeProvider.AudioModeListener;
import com.android.incallui.ContactInfoCache.ContactCacheEntry;
import com.android.incallui.ContactInfoCache.ContactInfoCacheCallback;
import com.android.incallui.InCallPresenter.InCallState;
import com.android.incallui.InCallPresenter.InCallStateListener;
import com.android.incallui.service.PhoneNumberService;
import com.android.services.telephony.common.AudioMode;
import com.android.services.telephony.common.Call;

/**
 * Presenter for the Call Card Fragment.
 * <p>
 * This class listens for changes to InCallState and passes it along to the fragment.
 */
public class CallCardPresenter extends Presenter<CallCardPresenter.CallCardUi>
        implements InCallStateListener, AudioModeListener, ContactInfoCacheCallback {

    private static final String TAG = CallCardPresenter.class.getSimpleName();
    private static final long CALL_TIME_UPDATE_INTERVAL = 1000; // in milliseconds

    private PhoneNumberService mPhoneNumberService;
    private AudioModeProvider mAudioModeProvider;
    private ContactInfoCache mContactInfoCache;
    private Call mPrimary;
    private Call mSecondary;
    private ContactCacheEntry mPrimaryContactInfo;
    private ContactCacheEntry mSecondaryContactInfo;
    private CallTimer mCallTimer;
    private Context mContext;

    public CallCardPresenter() {
        // create the call timer
        mCallTimer = new CallTimer(new Runnable() {
            @Override
            public void run() {
                updateCallTime();
            }
        });
    }

    public void init(Context context, PhoneNumberService phoneNumberService) {
        mContext = context;
        mPhoneNumberService = phoneNumberService;
    }

    @Override
    public void onUiReady(CallCardUi ui) {
        super.onUiReady(ui);

        if (mAudioModeProvider != null) {
            mAudioModeProvider.addListener(this);
        }
    }

    @Override
    public void onUiUnready(CallCardUi ui) {
        super.onUiUnready(ui);

        if (mAudioModeProvider != null) {
            mAudioModeProvider.removeListener(this);
        }
        mPrimary = null;
        mPrimaryContactInfo = null;
        mSecondaryContactInfo = null;
    }

    @Override
    public void onStateChange(InCallState state, CallList callList) {
        Log.d(TAG, "onStateChange()");
        final CallCardUi ui = getUi();
        if (ui == null) {
            return;
        }

        Call primary = null;
        Call secondary = null;

        if (state == InCallState.INCOMING) {
            primary = callList.getIncomingCall();
        } else if (state == InCallState.OUTGOING) {
            primary = callList.getOutgoingCall();

            // getCallToDisplay doesn't go through outgoing or incoming calls. It will return the
            // highest priority call to display as the secondary call.
            secondary = getCallToDisplay(callList, null, true);
        } else if (state == InCallState.INCALL) {
            primary = getCallToDisplay(callList, null, false);
            secondary = getCallToDisplay(callList, primary, true);
        }

        Log.d(this, "Primary call: " + primary);
        Log.d(this, "Secondary call: " + secondary);

        mPrimary = primary;
        mSecondary = secondary;

        // Query for contact data. This will call back on onContactInfoComplete at least once
        // synchronously, and potentially a second time asynchronously if it needs to make
        // a full query for the data.
        // It is in that callback that we set the values into the Ui.
        startContactInfoSearch();

        // Start/Stop the call time update timer
        if (mPrimary != null && mPrimary.getState() == Call.State.ACTIVE) {
            Log.d(this, "Starting the calltime timer");
            mCallTimer.start(CALL_TIME_UPDATE_INTERVAL);
        } else {
            Log.d(this, "Canceling the calltime timer");
            mCallTimer.cancel();
            ui.setPrimaryCallElapsedTime(false, null);
        }

        // Set the call state
        if (mPrimary != null) {
            final boolean bluetoothOn = mAudioModeProvider != null &&
                    mAudioModeProvider.getAudioMode() == AudioMode.BLUETOOTH;
            ui.setCallState(mPrimary.getState(), mPrimary.getDisconnectCause(), bluetoothOn);
        } else {
            ui.setCallState(Call.State.IDLE, Call.DisconnectCause.UNKNOWN, false);
        }
    }

    @Override
    public void onAudioMode(int mode) {
        if (mPrimary != null && getUi() != null) {
            final boolean bluetoothOn = (AudioMode.BLUETOOTH == mode);

            getUi().setCallState(mPrimary.getState(), mPrimary.getDisconnectCause(), bluetoothOn);
        }
    }

    @Override
    public void onSupportedAudioMode(int mask) {
    }

    public void updateCallTime() {
        final CallCardUi ui = getUi();

        if (ui == null || mPrimary == null || mPrimary.getState() != Call.State.ACTIVE) {
            if (ui != null) {
                ui.setPrimaryCallElapsedTime(false, null);
            }
            mCallTimer.cancel();
        } else {
            final long callStart = mPrimary.getConnectTime();
            final long duration = System.currentTimeMillis() - callStart;
            ui.setPrimaryCallElapsedTime(true, DateUtils.formatElapsedTime(duration / 1000));
        }
    }


    public void setContactInfoCache(ContactInfoCache cache) {
        mContactInfoCache = cache;
        startContactInfoSearch();
    }

    /**
     * Starts a query for more contact data for the save primary and secondary calls.
     */
    private void startContactInfoSearch() {
        if (mPrimary != null && mContactInfoCache != null) {
            mContactInfoCache.findInfo(mPrimary, this);
        } else {
            mPrimaryContactInfo = null;
            updatePrimaryDisplayInfo();
        }

        if (mSecondary != null && mContactInfoCache != null) {
            mContactInfoCache.findInfo(mSecondary, this);
        } else {
            mSecondaryContactInfo = null;
            updateSecondaryDisplayInfo();
        }
    }

    /**
     * Get the highest priority call to display.
     * Goes through the calls and chooses which to return based on priority of which type of call
     * to display to the user. Callers can use the "ignore" feature to get the second best call
     * by passing a previously found primary call as ignore.
     *
     * @param ignore A call to ignore if found.
     */
    private Call getCallToDisplay(CallList callList, Call ignore, boolean skipDisconnected) {

        // Active calls come second.  An active call always gets precedent.
        Call retval = callList.getActiveCall();
        if (retval != null && retval != ignore) {
            return retval;
        }

        // Disconnected calls get primary position if there are no active calls
        // to let user know quickly what call has disconnected. Disconnected
        // calls are very short lived.
        if (!skipDisconnected) {
            retval = callList.getDisconnectedCall();
            if (retval != null && retval != ignore) {
                return retval;
            }
        }

        // Then we go to background call (calls on hold)
        retval = callList.getBackgroundCall();
        if (retval != null && retval != ignore) {
            return retval;
        }

        // Lastly, we go to a second background call.
        retval = callList.getSecondBackgroundCall();

        return retval;
    }

    /**
     * Callback received when Contact info data query completes.
     */
    @Override
    public void onContactInfoComplete(int callId, ContactCacheEntry entry) {
        if (mPrimary != null && mPrimary.getCallId() == callId) {
            mPrimaryContactInfo = entry;
            updatePrimaryDisplayInfo();
            lookupPhoneNumber(mPrimary.getNumber());
        }
        if (mSecondary != null && mSecondary.getCallId() == callId) {
            mSecondaryContactInfo = entry;
            updateSecondaryDisplayInfo();
            // TODO(klp): investigate reverse lookup for secondary call.
        }

    }

    private void updatePrimaryDisplayInfo() {
        final CallCardUi ui = getUi();
        if (ui == null) {
            return;
        }

        if (mPrimaryContactInfo != null) {
            final String name = getNameForCall(mPrimaryContactInfo);
            final String number = getNumberForCall(mPrimaryContactInfo);
            final boolean nameIsNumber = name != null && name.equals(mPrimaryContactInfo.number);
            final String gatewayLabel = getGatewayLabel();
            final String gatewayNumber = getGatewayNumber();
            ui.setPrimary(number, name, nameIsNumber, mPrimaryContactInfo.label,
                    mPrimaryContactInfo.photo, mPrimary.isConferenceCall(), gatewayLabel,
                    gatewayNumber);
        } else {
            // reset to nothing (like at end of call)
            ui.setPrimary(null, null, false, null, null, false, null, null);
        }

    }

    public void lookupPhoneNumber(String phoneNumber) {
        if (mPhoneNumberService != null) {
            mPhoneNumberService.getPhoneNumberInfo(phoneNumber,
                    new PhoneNumberService.PhoneNumberServiceListener() {
                        @Override
                        public void onPhoneNumberInfoComplete(
                                final PhoneNumberService.PhoneNumberInfo info) {
                            if (info == null) {
                                return;
                            }
                            // TODO(klp): Ui is sometimes null due to something being shutdown.
                            if (getUi() != null) {
                                if (info.getName() != null) {
                                    getUi().setName(info.getName());
                                }

                                if (info.getImageUrl() != null) {
                                    fetchImage(info.getImageUrl());
                                }
                            }
                        }
                    });
        }
    }

    /**
     * Returns the gateway number for any existing outgoing call.
     */
    private String getGatewayNumber() {
        if (hasOutgoingGatewayCall()) {
            return mPrimary.getGatewayNumber();
        }

        return null;
    }

    /**
     * Returns the label for the gateway app for any existing outgoing call.
     */
    private String getGatewayLabel() {
        if (hasOutgoingGatewayCall() && getUi() != null) {
            final PackageManager pm = mContext.getPackageManager();
            try {
                final ApplicationInfo info = pm.getApplicationInfo(mPrimary.getGatewayPackage(), 0);
                return mContext.getString(R.string.calling_via_template,
                        pm.getApplicationLabel(info).toString());
            } catch (PackageManager.NameNotFoundException e) {
            }
        }
        return null;
    }

    private boolean hasOutgoingGatewayCall() {
        // We only display the gateway information while DIALING so return false for any othe
        // call state.
        return (mPrimary.getState() == Call.State.DIALING &&
                !TextUtils.isEmpty(mPrimary.getGatewayNumber()) &&
                !TextUtils.isEmpty(mPrimary.getGatewayPackage()));
    }

    private void fetchImage(final String url) {
        if (url != null) {
            new AsyncTask<Void, Void, Bitmap>() {

                @Override
                protected Bitmap doInBackground(Void... params) {
                    // Fetch the image
                    return mPhoneNumberService.fetchImage(url);
                }

                @Override
                protected void onPostExecute(Bitmap bitmap) {
                    // TODO(klp): same as above, figure out why it's null.
                    if (getUi() != null) {
                        getUi().setImage(bitmap);
                    }
                }

            }.execute();
        }
    }

    /**
     * Gets the name to display for the call.
     */
    private static String getNameForCall(ContactCacheEntry contactInfo) {
        if (TextUtils.isEmpty(contactInfo.name)) {
            return contactInfo.number;
        }
        return contactInfo.name;
    }

    /**
     * Gets the number to display for a call.
     */
    private static String getNumberForCall(ContactCacheEntry contactInfo) {
        // If the name is empty, we use the number for the name...so dont show a second
        // number in the number field
        if (TextUtils.isEmpty(contactInfo.name)) {
            return null;
        }
        return contactInfo.number;
    }

    private void updateSecondaryDisplayInfo() {
        final CallCardUi ui = getUi();
        if (ui == null) {
            return;
        }

        if (mSecondaryContactInfo != null) {
            final String name = getNameForCall(mSecondaryContactInfo);
            ui.setSecondary(true, getNameForCall(mSecondaryContactInfo),
                    mSecondaryContactInfo.label, mSecondaryContactInfo.photo);
        } else {
            // reset to nothing so that it starts off blank next time we use it.
            ui.setSecondary(false, null, null, null);
        }
    }

    public void setAudioModeProvider(AudioModeProvider audioModeProvider) {
        mAudioModeProvider = audioModeProvider;
        mAudioModeProvider.addListener(this);
    }

    public interface CallCardUi extends Ui {
        void setVisible(boolean on);
        void setPrimary(String number, String name, boolean nameIsNumber, String label,
                Drawable photo, boolean isConference, String gatewayLabel, String gatewayNumber);
        void setSecondary(boolean show, String name, String label, Drawable photo);
        void setCallState(int state, Call.DisconnectCause cause, boolean bluetoothOn);
        void setPrimaryCallElapsedTime(boolean show, String duration);
        void setName(String name);
        void setImage(Bitmap bitmap);
    }
}