blob: bfb14acb6091585ef606d94789c119164deca8a7 [file] [log] [blame]
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.phone;
18
19import android.animation.LayoutTransition;
20import android.content.ContentUris;
21import android.content.Context;
22import android.content.res.Resources;
23import android.graphics.Bitmap;
24import android.graphics.drawable.BitmapDrawable;
25import android.graphics.drawable.Drawable;
26import android.net.Uri;
27import android.os.Handler;
28import android.os.Message;
29import android.provider.ContactsContract.Contacts;
30import android.telephony.PhoneNumberUtils;
31import android.text.TextUtils;
32import android.text.format.DateUtils;
33import android.util.AttributeSet;
34import android.util.Log;
35import android.view.Gravity;
36import android.view.View;
37import android.view.ViewGroup;
38import android.view.ViewStub;
39import android.view.accessibility.AccessibilityEvent;
40import android.widget.ImageView;
41import android.widget.LinearLayout;
42import android.widget.TextView;
43
44import com.android.internal.telephony.Call;
45import com.android.internal.telephony.CallManager;
46import com.android.internal.telephony.CallerInfo;
47import com.android.internal.telephony.CallerInfoAsyncQuery;
48import com.android.internal.telephony.Connection;
49import com.android.internal.telephony.Phone;
50import com.android.internal.telephony.PhoneConstants;
51
52import java.util.List;
53
54
55/**
56 * "Call card" UI element: the in-call screen contains a tiled layout of call
57 * cards, each representing the state of a current "call" (ie. an active call,
58 * a call on hold, or an incoming call.)
59 */
60public class CallCard extends LinearLayout
61 implements CallTime.OnTickListener, CallerInfoAsyncQuery.OnQueryCompleteListener,
62 ContactsAsyncHelper.OnImageLoadCompleteListener {
63 private static final String LOG_TAG = "CallCard";
64 private static final boolean DBG = (PhoneGlobals.DBG_LEVEL >= 2);
65
66 private static final int TOKEN_UPDATE_PHOTO_FOR_CALL_STATE = 0;
67 private static final int TOKEN_DO_NOTHING = 1;
68
69 /**
70 * Used with {@link ContactsAsyncHelper#startObtainPhotoAsync(int, Context, Uri,
71 * ContactsAsyncHelper.OnImageLoadCompleteListener, Object)}
72 */
73 private static class AsyncLoadCookie {
74 public final ImageView imageView;
75 public final CallerInfo callerInfo;
76 public final Call call;
77 public AsyncLoadCookie(ImageView imageView, CallerInfo callerInfo, Call call) {
78 this.imageView = imageView;
79 this.callerInfo = callerInfo;
80 this.call = call;
81 }
82 }
83
84 /**
85 * Reference to the InCallScreen activity that owns us. This may be
86 * null if we haven't been initialized yet *or* after the InCallScreen
87 * activity has been destroyed.
88 */
89 private InCallScreen mInCallScreen;
90
91 // Phone app instance
92 private PhoneGlobals mApplication;
93
94 // Top-level subviews of the CallCard
95 /** Container for info about the current call(s) */
96 private ViewGroup mCallInfoContainer;
97 /** Primary "call info" block (the foreground or ringing call) */
98 private ViewGroup mPrimaryCallInfo;
99 /** "Call banner" for the primary call */
100 private ViewGroup mPrimaryCallBanner;
101 /** Secondary "call info" block (the background "on hold" call) */
102 private ViewStub mSecondaryCallInfo;
103
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700104
105 // "Call state" widgets
106 private TextView mCallStateLabel;
107 private TextView mElapsedTime;
108
109 // Text colors, used for various labels / titles
110 private int mTextColorCallTypeSip;
111
112 // The main block of info about the "primary" or "active" call,
113 // including photo / name / phone number / etc.
114 private ImageView mPhoto;
115 private View mPhotoDimEffect;
116
117 private TextView mName;
118 private TextView mPhoneNumber;
119 private TextView mLabel;
120 private TextView mCallTypeLabel;
121 // private TextView mSocialStatus;
122
123 /**
124 * Uri being used to load contact photo for mPhoto. Will be null when nothing is being loaded,
125 * or a photo is already loaded.
126 */
127 private Uri mLoadingPersonUri;
128
129 // Info about the "secondary" call, which is the "call on hold" when
130 // two lines are in use.
131 private TextView mSecondaryCallName;
132 private ImageView mSecondaryCallPhoto;
133 private View mSecondaryCallPhotoDimEffect;
134
135 // Onscreen hint for the incoming call RotarySelector widget.
136 private int mIncomingCallWidgetHintTextResId;
137 private int mIncomingCallWidgetHintColorResId;
138
139 private CallTime mCallTime;
140
141 // Track the state for the photo.
142 private ContactsAsyncHelper.ImageTracker mPhotoTracker;
143
144 // Cached DisplayMetrics density.
145 private float mDensity;
146
147 /**
148 * Sent when it takes too long (MESSAGE_DELAY msec) to load a contact photo for the given
149 * person, at which we just start showing the default avatar picture instead of the person's
150 * one. Note that we will *not* cancel the ongoing query and eventually replace the avatar
151 * with the person's photo, when it is available anyway.
152 */
153 private static final int MESSAGE_SHOW_UNKNOWN_PHOTO = 101;
154 private static final int MESSAGE_DELAY = 500; // msec
155 private final Handler mHandler = new Handler() {
156 @Override
157 public void handleMessage(Message msg) {
158 switch (msg.what) {
159 case MESSAGE_SHOW_UNKNOWN_PHOTO:
160 showImage(mPhoto, R.drawable.picture_unknown);
161 break;
162 default:
163 Log.wtf(LOG_TAG, "mHandler: unexpected message: " + msg);
164 break;
165 }
166 }
167 };
168
169 public CallCard(Context context, AttributeSet attrs) {
170 super(context, attrs);
171
172 if (DBG) log("CallCard constructor...");
173 if (DBG) log("- this = " + this);
174 if (DBG) log("- context " + context + ", attrs " + attrs);
175
176 mApplication = PhoneGlobals.getInstance();
177
178 mCallTime = new CallTime(this);
179
180 // create a new object to track the state for the photo.
181 mPhotoTracker = new ContactsAsyncHelper.ImageTracker();
182
183 mDensity = getResources().getDisplayMetrics().density;
184 if (DBG) log("- Density: " + mDensity);
185 }
186
187 /* package */ void setInCallScreenInstance(InCallScreen inCallScreen) {
188 mInCallScreen = inCallScreen;
189 }
190
191 @Override
192 public void onTickForCallTimeElapsed(long timeElapsed) {
193 // While a call is in progress, update the elapsed time shown
194 // onscreen.
195 updateElapsedTimeWidget(timeElapsed);
196 }
197
198 /* package */ void stopTimer() {
199 mCallTime.cancelTimer();
200 }
201
202 @Override
203 protected void onFinishInflate() {
204 super.onFinishInflate();
205
206 if (DBG) log("CallCard onFinishInflate(this = " + this + ")...");
207
208 mCallInfoContainer = (ViewGroup) findViewById(R.id.call_info_container);
209 mPrimaryCallInfo = (ViewGroup) findViewById(R.id.primary_call_info);
210 mPrimaryCallBanner = (ViewGroup) findViewById(R.id.primary_call_banner);
211
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700212 mCallStateLabel = (TextView) findViewById(R.id.callStateLabel);
213 mElapsedTime = (TextView) findViewById(R.id.elapsedTime);
214
215 // Text colors
216 mTextColorCallTypeSip = getResources().getColor(R.color.incall_callTypeSip);
217
218 // "Caller info" area, including photo / name / phone numbers / etc
219 mPhoto = (ImageView) findViewById(R.id.photo);
220 mPhotoDimEffect = findViewById(R.id.dim_effect_for_primary_photo);
221
222 mName = (TextView) findViewById(R.id.name);
223 mPhoneNumber = (TextView) findViewById(R.id.phoneNumber);
224 mLabel = (TextView) findViewById(R.id.label);
225 mCallTypeLabel = (TextView) findViewById(R.id.callTypeLabel);
226 // mSocialStatus = (TextView) findViewById(R.id.socialStatus);
227
228 // Secondary info area, for the background ("on hold") call
229 mSecondaryCallInfo = (ViewStub) findViewById(R.id.secondary_call_info);
230 }
231
232 /**
233 * Updates the state of all UI elements on the CallCard, based on the
234 * current state of the phone.
235 */
236 /* package */ void updateState(CallManager cm) {
237 if (DBG) log("updateState(" + cm + ")...");
238
239 // Update the onscreen UI based on the current state of the phone.
240
241 PhoneConstants.State state = cm.getState(); // IDLE, RINGING, or OFFHOOK
242 Call ringingCall = cm.getFirstActiveRingingCall();
243 Call fgCall = cm.getActiveFgCall();
244 Call bgCall = cm.getFirstActiveBgCall();
245
246 // Update the overall layout of the onscreen elements, if in PORTRAIT.
247 // Portrait uses a programatically altered layout, whereas landscape uses layout xml's.
248 // Landscape view has the views side by side, so no shifting of the picture is needed
249 if (!PhoneUtils.isLandscape(this.getContext())) {
250 updateCallInfoLayout(state);
251 }
252
253 // If the FG call is dialing/alerting, we should display for that call
254 // and ignore the ringing call. This case happens when the telephony
255 // layer rejects the ringing call while the FG call is dialing/alerting,
256 // but the incoming call *does* briefly exist in the DISCONNECTING or
257 // DISCONNECTED state.
258 if ((ringingCall.getState() != Call.State.IDLE)
259 && !fgCall.getState().isDialing()) {
260 // A phone call is ringing, call waiting *or* being rejected
261 // (ie. another call may also be active as well.)
262 updateRingingCall(cm);
263 } else if ((fgCall.getState() != Call.State.IDLE)
264 || (bgCall.getState() != Call.State.IDLE)) {
265 // We are here because either:
266 // (1) the phone is off hook. At least one call exists that is
267 // dialing, active, or holding, and no calls are ringing or waiting,
268 // or:
269 // (2) the phone is IDLE but a call just ended and it's still in
270 // the DISCONNECTING or DISCONNECTED state. In this case, we want
271 // the main CallCard to display "Hanging up" or "Call ended".
272 // The normal "foreground call" code path handles both cases.
273 updateForegroundCall(cm);
274 } else {
275 // We don't have any DISCONNECTED calls, which means that the phone
276 // is *truly* idle.
277 if (mApplication.inCallUiState.showAlreadyDisconnectedState) {
278 // showAlreadyDisconnectedState implies the phone call is disconnected
279 // and we want to show the disconnected phone call for a moment.
280 //
281 // This happens when a phone call ends while the screen is off,
282 // which means the user had no chance to see the last status of
283 // the call. We'll turn off showAlreadyDisconnectedState flag
284 // and bail out of the in-call screen soon.
285 updateAlreadyDisconnected(cm);
286 } else {
287 // It's very rare to be on the InCallScreen at all in this
288 // state, but it can happen in some cases:
289 // - A stray onPhoneStateChanged() event came in to the
290 // InCallScreen *after* it was dismissed.
291 // - We're allowed to be on the InCallScreen because
292 // an MMI or USSD is running, but there's no actual "call"
293 // to display.
294 // - We're displaying an error dialog to the user
295 // (explaining why the call failed), so we need to stay on
296 // the InCallScreen so that the dialog will be visible.
297 //
298 // In these cases, put the callcard into a sane but "blank" state:
299 updateNoCall(cm);
300 }
301 }
302 }
303
304 /**
305 * Updates the overall size and positioning of mCallInfoContainer and
306 * the "Call info" blocks, based on the phone state.
307 */
308 private void updateCallInfoLayout(PhoneConstants.State state) {
309 boolean ringing = (state == PhoneConstants.State.RINGING);
310 if (DBG) log("updateCallInfoLayout()... ringing = " + ringing);
311
312 // Based on the current state, update the overall
313 // CallCard layout:
314
315 // - Update the bottom margin of mCallInfoContainer to make sure
316 // the call info area won't overlap with the touchable
317 // controls on the bottom part of the screen.
318
319 int reservedVerticalSpace = mInCallScreen.getInCallTouchUi().getTouchUiHeight();
320 ViewGroup.MarginLayoutParams callInfoLp =
321 (ViewGroup.MarginLayoutParams) mCallInfoContainer.getLayoutParams();
322 callInfoLp.bottomMargin = reservedVerticalSpace; // Equivalent to setting
323 // android:layout_marginBottom in XML
324 if (DBG) log(" ==> callInfoLp.bottomMargin: " + reservedVerticalSpace);
325 mCallInfoContainer.setLayoutParams(callInfoLp);
326 }
327
328 /**
329 * Updates the UI for the state where the phone is in use, but not ringing.
330 */
331 private void updateForegroundCall(CallManager cm) {
332 if (DBG) log("updateForegroundCall()...");
333 // if (DBG) PhoneUtils.dumpCallManager();
334
335 Call fgCall = cm.getActiveFgCall();
336 Call bgCall = cm.getFirstActiveBgCall();
337
338 if (fgCall.getState() == Call.State.IDLE) {
339 if (DBG) log("updateForegroundCall: no active call, show holding call");
340 // TODO: make sure this case agrees with the latest UI spec.
341
342 // Display the background call in the main info area of the
343 // CallCard, since there is no foreground call. Note that
344 // displayMainCallStatus() will notice if the call we passed in is on
345 // hold, and display the "on hold" indication.
346 fgCall = bgCall;
347
348 // And be sure to not display anything in the "on hold" box.
349 bgCall = null;
350 }
351
352 displayMainCallStatus(cm, fgCall);
353
354 Phone phone = fgCall.getPhone();
355
356 int phoneType = phone.getPhoneType();
357 if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
358 if ((mApplication.cdmaPhoneCallState.getCurrentCallState()
359 == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE)
360 && mApplication.cdmaPhoneCallState.IsThreeWayCallOrigStateDialing()) {
361 displaySecondaryCallStatus(cm, fgCall);
362 } else {
363 //This is required so that even if a background call is not present
364 // we need to clean up the background call area.
365 displaySecondaryCallStatus(cm, bgCall);
366 }
367 } else if ((phoneType == PhoneConstants.PHONE_TYPE_GSM)
368 || (phoneType == PhoneConstants.PHONE_TYPE_SIP)) {
369 displaySecondaryCallStatus(cm, bgCall);
370 }
371 }
372
373 /**
374 * Updates the UI for the state where an incoming call is ringing (or
375 * call waiting), regardless of whether the phone's already offhook.
376 */
377 private void updateRingingCall(CallManager cm) {
378 if (DBG) log("updateRingingCall()...");
379
380 Call ringingCall = cm.getFirstActiveRingingCall();
381
382 // Display caller-id info and photo from the incoming call:
383 displayMainCallStatus(cm, ringingCall);
384
385 // And even in the Call Waiting case, *don't* show any info about
386 // the current ongoing call and/or the current call on hold.
387 // (Since the caller-id info for the incoming call totally trumps
388 // any info about the current call(s) in progress.)
389 displaySecondaryCallStatus(cm, null);
390 }
391
392 /**
393 * Updates the UI for the state where an incoming call is just disconnected while we want to
394 * show the screen for a moment.
395 *
396 * This case happens when the whole in-call screen is in background when phone calls are hanged
397 * up, which means there's no way to determine which call was the last call finished. Right now
398 * this method simply shows the previous primary call status with a photo, closing the
399 * secondary call status. In most cases (including conference call or misc call happening in
400 * CDMA) this behaves right.
401 *
402 * If there were two phone calls both of which were hung up but the primary call was the
403 * first, this would behave a bit odd (since the first one still appears as the
404 * "last disconnected").
405 */
406 private void updateAlreadyDisconnected(CallManager cm) {
407 // For the foreground call, we manually set up every component based on previous state.
408 mPrimaryCallInfo.setVisibility(View.VISIBLE);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700409 mCallStateLabel.setVisibility(View.VISIBLE);
410 mCallStateLabel.setText(mContext.getString(R.string.card_title_call_ended));
411 mElapsedTime.setVisibility(View.VISIBLE);
412 mCallTime.cancelTimer();
413
414 // Just hide it.
415 displaySecondaryCallStatus(cm, null);
416 }
417
418 /**
419 * Updates the UI for the state where the phone is not in use.
420 * This is analogous to updateForegroundCall() and updateRingingCall(),
421 * but for the (uncommon) case where the phone is
422 * totally idle. (See comments in updateState() above.)
423 *
424 * This puts the callcard into a sane but "blank" state.
425 */
426 private void updateNoCall(CallManager cm) {
427 if (DBG) log("updateNoCall()...");
428
429 displayMainCallStatus(cm, null);
430 displaySecondaryCallStatus(cm, null);
431 }
432
433 /**
434 * Updates the main block of caller info on the CallCard
435 * (ie. the stuff in the primaryCallInfo block) based on the specified Call.
436 */
437 private void displayMainCallStatus(CallManager cm, Call call) {
438 if (DBG) log("displayMainCallStatus(call " + call + ")...");
439
440 if (call == null) {
441 // There's no call to display, presumably because the phone is idle.
442 mPrimaryCallInfo.setVisibility(View.GONE);
443 return;
444 }
445 mPrimaryCallInfo.setVisibility(View.VISIBLE);
446
447 Call.State state = call.getState();
448 if (DBG) log(" - call.state: " + call.getState());
449
450 switch (state) {
451 case ACTIVE:
452 case DISCONNECTING:
453 // update timer field
454 if (DBG) log("displayMainCallStatus: start periodicUpdateTimer");
455 mCallTime.setActiveCallMode(call);
456 mCallTime.reset();
457 mCallTime.periodicUpdateTimer();
458
459 break;
460
461 case HOLDING:
462 // update timer field
463 mCallTime.cancelTimer();
464
465 break;
466
467 case DISCONNECTED:
468 // Stop getting timer ticks from this call
469 mCallTime.cancelTimer();
470
471 break;
472
473 case DIALING:
474 case ALERTING:
475 // Stop getting timer ticks from a previous call
476 mCallTime.cancelTimer();
477
478 break;
479
480 case INCOMING:
481 case WAITING:
482 // Stop getting timer ticks from a previous call
483 mCallTime.cancelTimer();
484
485 break;
486
487 case IDLE:
488 // The "main CallCard" should never be trying to display
489 // an idle call! In updateState(), if the phone is idle,
490 // we call updateNoCall(), which means that we shouldn't
491 // have passed a call into this method at all.
492 Log.w(LOG_TAG, "displayMainCallStatus: IDLE call in the main call card!");
493
494 // (It is possible, though, that we had a valid call which
495 // became idle *after* the check in updateState() but
496 // before we get here... So continue the best we can,
497 // with whatever (stale) info we can get from the
498 // passed-in Call object.)
499
500 break;
501
502 default:
503 Log.w(LOG_TAG, "displayMainCallStatus: unexpected call state: " + state);
504 break;
505 }
506
507 updateCallStateWidgets(call);
508
509 if (PhoneUtils.isConferenceCall(call)) {
510 // Update onscreen info for a conference call.
511 updateDisplayForConference(call);
512 } else {
513 // Update onscreen info for a regular call (which presumably
514 // has only one connection.)
515 Connection conn = null;
516 int phoneType = call.getPhone().getPhoneType();
517 if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
518 conn = call.getLatestConnection();
519 } else if ((phoneType == PhoneConstants.PHONE_TYPE_GSM)
520 || (phoneType == PhoneConstants.PHONE_TYPE_SIP)) {
521 conn = call.getEarliestConnection();
522 } else {
523 throw new IllegalStateException("Unexpected phone type: " + phoneType);
524 }
525
526 if (conn == null) {
527 if (DBG) log("displayMainCallStatus: connection is null, using default values.");
528 // if the connection is null, we run through the behaviour
529 // we had in the past, which breaks down into trivial steps
530 // with the current implementation of getCallerInfo and
531 // updateDisplayForPerson.
532 CallerInfo info = PhoneUtils.getCallerInfo(getContext(), null /* conn */);
533 updateDisplayForPerson(info, PhoneConstants.PRESENTATION_ALLOWED, false, call,
534 conn);
535 } else {
536 if (DBG) log(" - CONN: " + conn + ", state = " + conn.getState());
537 int presentation = conn.getNumberPresentation();
538
539 // make sure that we only make a new query when the current
540 // callerinfo differs from what we've been requested to display.
541 boolean runQuery = true;
542 Object o = conn.getUserData();
543 if (o instanceof PhoneUtils.CallerInfoToken) {
544 runQuery = mPhotoTracker.isDifferentImageRequest(
545 ((PhoneUtils.CallerInfoToken) o).currentInfo);
546 } else {
547 runQuery = mPhotoTracker.isDifferentImageRequest(conn);
548 }
549
550 // Adding a check to see if the update was caused due to a Phone number update
551 // or CNAP update. If so then we need to start a new query
552 if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
553 Object obj = conn.getUserData();
554 String updatedNumber = conn.getAddress();
555 String updatedCnapName = conn.getCnapName();
556 CallerInfo info = null;
557 if (obj instanceof PhoneUtils.CallerInfoToken) {
558 info = ((PhoneUtils.CallerInfoToken) o).currentInfo;
559 } else if (o instanceof CallerInfo) {
560 info = (CallerInfo) o;
561 }
562
563 if (info != null) {
564 if (updatedNumber != null && !updatedNumber.equals(info.phoneNumber)) {
565 if (DBG) log("- displayMainCallStatus: updatedNumber = "
566 + updatedNumber);
567 runQuery = true;
568 }
569 if (updatedCnapName != null && !updatedCnapName.equals(info.cnapName)) {
570 if (DBG) log("- displayMainCallStatus: updatedCnapName = "
571 + updatedCnapName);
572 runQuery = true;
573 }
574 }
575 }
576
577 if (runQuery) {
578 if (DBG) log("- displayMainCallStatus: starting CallerInfo query...");
579 PhoneUtils.CallerInfoToken info =
580 PhoneUtils.startGetCallerInfo(getContext(), conn, this, call);
581 updateDisplayForPerson(info.currentInfo, presentation, !info.isFinal,
582 call, conn);
583 } else {
584 // No need to fire off a new query. We do still need
585 // to update the display, though (since we might have
586 // previously been in the "conference call" state.)
587 if (DBG) log("- displayMainCallStatus: using data we already have...");
588 if (o instanceof CallerInfo) {
589 CallerInfo ci = (CallerInfo) o;
590 // Update CNAP information if Phone state change occurred
591 ci.cnapName = conn.getCnapName();
592 ci.numberPresentation = conn.getNumberPresentation();
593 ci.namePresentation = conn.getCnapNamePresentation();
594 if (DBG) log("- displayMainCallStatus: CNAP data from Connection: "
595 + "CNAP name=" + ci.cnapName
596 + ", Number/Name Presentation=" + ci.numberPresentation);
597 if (DBG) log(" ==> Got CallerInfo; updating display: ci = " + ci);
598 updateDisplayForPerson(ci, presentation, false, call, conn);
599 } else if (o instanceof PhoneUtils.CallerInfoToken){
600 CallerInfo ci = ((PhoneUtils.CallerInfoToken) o).currentInfo;
601 if (DBG) log("- displayMainCallStatus: CNAP data from Connection: "
602 + "CNAP name=" + ci.cnapName
603 + ", Number/Name Presentation=" + ci.numberPresentation);
604 if (DBG) log(" ==> Got CallerInfoToken; updating display: ci = " + ci);
605 updateDisplayForPerson(ci, presentation, true, call, conn);
606 } else {
607 Log.w(LOG_TAG, "displayMainCallStatus: runQuery was false, "
608 + "but we didn't have a cached CallerInfo object! o = " + o);
609 // TODO: any easy way to recover here (given that
610 // the CallCard is probably displaying stale info
611 // right now?) Maybe force the CallCard into the
612 // "Unknown" state?
613 }
614 }
615 }
616 }
617
618 // In some states we override the "photo" ImageView to be an
619 // indication of the current state, rather than displaying the
620 // regular photo as set above.
621 updatePhotoForCallState(call);
622
623 // One special feature of the "number" text field: For incoming
624 // calls, while the user is dragging the RotarySelector widget, we
625 // use mPhoneNumber to display a hint like "Rotate to answer".
626 if (mIncomingCallWidgetHintTextResId != 0) {
627 // Display the hint!
628 mPhoneNumber.setText(mIncomingCallWidgetHintTextResId);
629 mPhoneNumber.setTextColor(getResources().getColor(mIncomingCallWidgetHintColorResId));
630 mPhoneNumber.setVisibility(View.VISIBLE);
631 mLabel.setVisibility(View.GONE);
632 }
633 // If we don't have a hint to display, just don't touch
634 // mPhoneNumber and mLabel. (Their text / color / visibility have
635 // already been set correctly, by either updateDisplayForPerson()
636 // or updateDisplayForConference().)
637 }
638
639 /**
640 * Implemented for CallerInfoAsyncQuery.OnQueryCompleteListener interface.
641 * refreshes the CallCard data when it called.
642 */
643 @Override
644 public void onQueryComplete(int token, Object cookie, CallerInfo ci) {
645 if (DBG) log("onQueryComplete: token " + token + ", cookie " + cookie + ", ci " + ci);
646
647 if (cookie instanceof Call) {
648 // grab the call object and update the display for an individual call,
649 // as well as the successive call to update image via call state.
650 // If the object is a textview instead, we update it as we need to.
651 if (DBG) log("callerinfo query complete, updating ui from displayMainCallStatus()");
652 Call call = (Call) cookie;
653 Connection conn = null;
654 int phoneType = call.getPhone().getPhoneType();
655 if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
656 conn = call.getLatestConnection();
657 } else if ((phoneType == PhoneConstants.PHONE_TYPE_GSM)
658 || (phoneType == PhoneConstants.PHONE_TYPE_SIP)) {
659 conn = call.getEarliestConnection();
660 } else {
661 throw new IllegalStateException("Unexpected phone type: " + phoneType);
662 }
663 PhoneUtils.CallerInfoToken cit =
664 PhoneUtils.startGetCallerInfo(getContext(), conn, this, null);
665
666 int presentation = PhoneConstants.PRESENTATION_ALLOWED;
667 if (conn != null) presentation = conn.getNumberPresentation();
668 if (DBG) log("- onQueryComplete: presentation=" + presentation
669 + ", contactExists=" + ci.contactExists);
670
671 // Depending on whether there was a contact match or not, we want to pass in different
672 // CallerInfo (for CNAP). Therefore if ci.contactExists then use the ci passed in.
673 // Otherwise, regenerate the CIT from the Connection and use the CallerInfo from there.
674 if (ci.contactExists) {
675 updateDisplayForPerson(ci, PhoneConstants.PRESENTATION_ALLOWED, false, call, conn);
676 } else {
677 updateDisplayForPerson(cit.currentInfo, presentation, false, call, conn);
678 }
679 updatePhotoForCallState(call);
680
681 } else if (cookie instanceof TextView){
682 if (DBG) log("callerinfo query complete, updating ui from ongoing or onhold");
683 ((TextView) cookie).setText(PhoneUtils.getCompactNameFromCallerInfo(ci, mContext));
684 }
685 }
686
687 /**
688 * Implemented for ContactsAsyncHelper.OnImageLoadCompleteListener interface.
689 * make sure that the call state is reflected after the image is loaded.
690 */
691 @Override
692 public void onImageLoadComplete(int token, Drawable photo, Bitmap photoIcon, Object cookie) {
693 mHandler.removeMessages(MESSAGE_SHOW_UNKNOWN_PHOTO);
694 if (mLoadingPersonUri != null) {
695 // Start sending view notification after the current request being done.
696 // New image may possibly be available from the next phone calls.
697 //
698 // TODO: may be nice to update the image view again once the newer one
699 // is available on contacts database.
700 PhoneUtils.sendViewNotificationAsync(mApplication, mLoadingPersonUri);
701 } else {
702 // This should not happen while we need some verbose info if it happens..
703 Log.w(LOG_TAG, "Person Uri isn't available while Image is successfully loaded.");
704 }
705 mLoadingPersonUri = null;
706
707 AsyncLoadCookie asyncLoadCookie = (AsyncLoadCookie) cookie;
708 CallerInfo callerInfo = asyncLoadCookie.callerInfo;
709 ImageView imageView = asyncLoadCookie.imageView;
710 Call call = asyncLoadCookie.call;
711
712 callerInfo.cachedPhoto = photo;
713 callerInfo.cachedPhotoIcon = photoIcon;
714 callerInfo.isCachedPhotoCurrent = true;
715
716 // Note: previously ContactsAsyncHelper has done this job.
717 // TODO: We will need fade-in animation. See issue 5236130.
718 if (photo != null) {
719 showImage(imageView, photo);
720 } else if (photoIcon != null) {
721 showImage(imageView, photoIcon);
722 } else {
723 showImage(imageView, R.drawable.picture_unknown);
724 }
725
726 if (token == TOKEN_UPDATE_PHOTO_FOR_CALL_STATE) {
727 updatePhotoForCallState(call);
728 }
729 }
730
731 /**
732 * Updates the "call state label" and the elapsed time widget based on the
733 * current state of the call.
734 */
735 private void updateCallStateWidgets(Call call) {
736 if (DBG) log("updateCallStateWidgets(call " + call + ")...");
737 final Call.State state = call.getState();
738 final Context context = getContext();
739 final Phone phone = call.getPhone();
740 final int phoneType = phone.getPhoneType();
741
742 String callStateLabel = null; // Label to display as part of the call banner
743 int bluetoothIconId = 0; // Icon to display alongside the call state label
744
745 switch (state) {
746 case IDLE:
747 // "Call state" is meaningless in this state.
748 break;
749
750 case ACTIVE:
751 // We normally don't show a "call state label" at all in
752 // this state (but see below for some special cases).
753 break;
754
755 case HOLDING:
756 callStateLabel = context.getString(R.string.card_title_on_hold);
757 break;
758
759 case DIALING:
760 case ALERTING:
761 callStateLabel = context.getString(R.string.card_title_dialing);
762 break;
763
764 case INCOMING:
765 case WAITING:
766 callStateLabel = context.getString(R.string.card_title_incoming_call);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700767 break;
768
769 case DISCONNECTING:
770 // While in the DISCONNECTING state we display a "Hanging up"
771 // message in order to make the UI feel more responsive. (In
772 // GSM it's normal to see a delay of a couple of seconds while
773 // negotiating the disconnect with the network, so the "Hanging
774 // up" state at least lets the user know that we're doing
775 // something. This state is currently not used with CDMA.)
776 callStateLabel = context.getString(R.string.card_title_hanging_up);
777 break;
778
779 case DISCONNECTED:
780 callStateLabel = getCallFailedString(call);
781 break;
782
783 default:
784 Log.wtf(LOG_TAG, "updateCallStateWidgets: unexpected call state: " + state);
785 break;
786 }
787
788 // Check a couple of other special cases (these are all CDMA-specific).
789
Santos Cordon2c2d3cf2013-08-08 03:53:47 -0700790 // TODO(klp): This code should go into the CallModeler logic instead of the UI.
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700791 if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
792 if ((state == Call.State.ACTIVE)
793 && mApplication.cdmaPhoneCallState.IsThreeWayCallOrigStateDialing()) {
794 // Display "Dialing" while dialing a 3Way call, even
795 // though the foreground call state is actually ACTIVE.
796 callStateLabel = context.getString(R.string.card_title_dialing);
797 } else if (PhoneGlobals.getInstance().notifier.getIsCdmaRedialCall()) {
798 callStateLabel = context.getString(R.string.card_title_redialing);
799 }
800 }
801 if (PhoneUtils.isPhoneInEcm(phone)) {
802 // In emergency callback mode (ECM), use a special label
803 // that shows your own phone number.
804 callStateLabel = getECMCardTitle(context, phone);
805 }
806
807 final InCallUiState inCallUiState = mApplication.inCallUiState;
808 if (DBG) {
809 log("==> callStateLabel: '" + callStateLabel
Santos Cordon69a69192013-08-22 14:25:42 -0700810 + "', bluetoothIconId = " + bluetoothIconId);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700811 }
812
813 // Animation will be done by mCallerDetail's LayoutTransition, but in some cases, we don't
814 // want that.
815 // - DIALING: This is at the beginning of the phone call.
816 // - DISCONNECTING, DISCONNECTED: Screen will disappear soon; we have no time for animation.
817 final boolean skipAnimation = (state == Call.State.DIALING
818 || state == Call.State.DISCONNECTING
819 || state == Call.State.DISCONNECTED);
820 LayoutTransition layoutTransition = null;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700821
822 if (!TextUtils.isEmpty(callStateLabel)) {
823 mCallStateLabel.setVisibility(View.VISIBLE);
824 mCallStateLabel.setText(callStateLabel);
825
826 // ...and display the icon too if necessary.
827 if (bluetoothIconId != 0) {
828 mCallStateLabel.setCompoundDrawablesWithIntrinsicBounds(bluetoothIconId, 0, 0, 0);
829 mCallStateLabel.setCompoundDrawablePadding((int) (mDensity * 5));
830 } else {
831 // Clear out any icons
832 mCallStateLabel.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
833 }
834 } else {
835 mCallStateLabel.setVisibility(View.GONE);
836 // Gravity is aligned left when receiving an incoming call in landscape.
837 // In that rare case, the gravity needs to be reset to the right.
838 // Also, setText("") is used since there is a delay in making the view GONE,
839 // so the user will otherwise see the text jump to the right side before disappearing.
840 if(mCallStateLabel.getGravity() != Gravity.END) {
841 mCallStateLabel.setText("");
842 mCallStateLabel.setGravity(Gravity.END);
843 }
844 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700845
846 // ...and update the elapsed time widget too.
847 switch (state) {
848 case ACTIVE:
849 case DISCONNECTING:
850 // Show the time with fade-in animation.
851 AnimationUtils.Fade.show(mElapsedTime);
852 updateElapsedTimeWidget(call);
853 break;
854
855 case DISCONNECTED:
856 // In the "Call ended" state, leave the mElapsedTime widget
857 // visible, but don't touch it (so we continue to see the
858 // elapsed time of the call that just ended.)
859 // Check visibility to keep possible fade-in animation.
860 if (mElapsedTime.getVisibility() != View.VISIBLE) {
861 mElapsedTime.setVisibility(View.VISIBLE);
862 }
863 break;
864
865 default:
866 // Call state here is IDLE, ACTIVE, HOLDING, DIALING, ALERTING,
867 // INCOMING, or WAITING.
868 // In all of these states, the "elapsed time" is meaningless, so
869 // don't show it.
870 AnimationUtils.Fade.hide(mElapsedTime, View.INVISIBLE);
871
872 // Additionally, in call states that can only occur at the start
873 // of a call, reset the elapsed time to be sure we won't display
874 // stale info later (like if we somehow go straight from DIALING
875 // or ALERTING to DISCONNECTED, which can actually happen in
876 // some failure cases like "line busy").
877 if ((state == Call.State.DIALING) || (state == Call.State.ALERTING)) {
878 updateElapsedTimeWidget(0);
879 }
880
881 break;
882 }
883 }
884
885 /**
886 * Updates mElapsedTime based on the given {@link Call} object's information.
887 *
888 * @see CallTime#getCallDuration(Call)
889 * @see Connection#getDurationMillis()
890 */
891 /* package */ void updateElapsedTimeWidget(Call call) {
892 long duration = CallTime.getCallDuration(call); // msec
893 updateElapsedTimeWidget(duration / 1000);
894 // Also see onTickForCallTimeElapsed(), which updates this
895 // widget once per second while the call is active.
896 }
897
898 /**
899 * Updates mElapsedTime based on the specified number of seconds.
900 */
901 private void updateElapsedTimeWidget(long timeElapsed) {
902 // if (DBG) log("updateElapsedTimeWidget: " + timeElapsed);
903 mElapsedTime.setText(DateUtils.formatElapsedTime(timeElapsed));
904 }
905
906 /**
907 * Updates the "on hold" box in the "other call" info area
908 * (ie. the stuff in the secondaryCallInfo block)
909 * based on the specified Call.
910 * Or, clear out the "on hold" box if the specified call
911 * is null or idle.
912 */
913 private void displaySecondaryCallStatus(CallManager cm, Call call) {
914 if (DBG) log("displayOnHoldCallStatus(call =" + call + ")...");
915
916 if ((call == null) || (PhoneGlobals.getInstance().isOtaCallInActiveState())) {
917 mSecondaryCallInfo.setVisibility(View.GONE);
918 return;
919 }
920
921 Call.State state = call.getState();
922 switch (state) {
923 case HOLDING:
924 // Ok, there actually is a background call on hold.
925 // Display the "on hold" box.
926
927 // Note this case occurs only on GSM devices. (On CDMA,
928 // the "call on hold" is actually the 2nd connection of
929 // that ACTIVE call; see the ACTIVE case below.)
930 showSecondaryCallInfo();
931
932 if (PhoneUtils.isConferenceCall(call)) {
933 if (DBG) log("==> conference call.");
934 mSecondaryCallName.setText(getContext().getString(R.string.confCall));
935 showImage(mSecondaryCallPhoto, R.drawable.picture_conference);
936 } else {
937 // perform query and update the name temporarily
938 // make sure we hand the textview we want updated to the
939 // callback function.
940 if (DBG) log("==> NOT a conf call; call startGetCallerInfo...");
941 PhoneUtils.CallerInfoToken infoToken = PhoneUtils.startGetCallerInfo(
942 getContext(), call, this, mSecondaryCallName);
943 mSecondaryCallName.setText(
944 PhoneUtils.getCompactNameFromCallerInfo(infoToken.currentInfo,
945 getContext()));
946
947 // Also pull the photo out of the current CallerInfo.
948 // (Note we assume we already have a valid photo at
949 // this point, since *presumably* the caller-id query
950 // was already run at some point *before* this call
951 // got put on hold. If there's no cached photo, just
952 // fall back to the default "unknown" image.)
953 if (infoToken.isFinal) {
954 showCachedImage(mSecondaryCallPhoto, infoToken.currentInfo);
955 } else {
956 showImage(mSecondaryCallPhoto, R.drawable.picture_unknown);
957 }
958 }
959
960 AnimationUtils.Fade.show(mSecondaryCallPhotoDimEffect);
961 break;
962
963 case ACTIVE:
964 // CDMA: This is because in CDMA when the user originates the second call,
965 // although the Foreground call state is still ACTIVE in reality the network
966 // put the first call on hold.
967 if (mApplication.phone.getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA) {
968 showSecondaryCallInfo();
969
970 List<Connection> connections = call.getConnections();
971 if (connections.size() > 2) {
972 // This means that current Mobile Originated call is the not the first 3-Way
973 // call the user is making, which in turn tells the PhoneGlobals that we no
974 // longer know which previous caller/party had dropped out before the user
975 // made this call.
976 mSecondaryCallName.setText(
977 getContext().getString(R.string.card_title_in_call));
978 showImage(mSecondaryCallPhoto, R.drawable.picture_unknown);
979 } else {
980 // This means that the current Mobile Originated call IS the first 3-Way
981 // and hence we display the first callers/party's info here.
982 Connection conn = call.getEarliestConnection();
983 PhoneUtils.CallerInfoToken infoToken = PhoneUtils.startGetCallerInfo(
984 getContext(), conn, this, mSecondaryCallName);
985
986 // Get the compactName to be displayed, but then check that against
987 // the number presentation value for the call. If it's not an allowed
988 // presentation, then display the appropriate presentation string instead.
989 CallerInfo info = infoToken.currentInfo;
990
991 String name = PhoneUtils.getCompactNameFromCallerInfo(info, getContext());
992 boolean forceGenericPhoto = false;
993 if (info != null && info.numberPresentation !=
994 PhoneConstants.PRESENTATION_ALLOWED) {
995 name = PhoneUtils.getPresentationString(
996 getContext(), info.numberPresentation);
997 forceGenericPhoto = true;
998 }
999 mSecondaryCallName.setText(name);
1000
1001 // Also pull the photo out of the current CallerInfo.
1002 // (Note we assume we already have a valid photo at
1003 // this point, since *presumably* the caller-id query
1004 // was already run at some point *before* this call
1005 // got put on hold. If there's no cached photo, just
1006 // fall back to the default "unknown" image.)
1007 if (!forceGenericPhoto && infoToken.isFinal) {
1008 showCachedImage(mSecondaryCallPhoto, info);
1009 } else {
1010 showImage(mSecondaryCallPhoto, R.drawable.picture_unknown);
1011 }
1012 }
1013 } else {
1014 // We shouldn't ever get here at all for non-CDMA devices.
1015 Log.w(LOG_TAG, "displayOnHoldCallStatus: ACTIVE state on non-CDMA device");
1016 mSecondaryCallInfo.setVisibility(View.GONE);
1017 }
1018
1019 AnimationUtils.Fade.hide(mSecondaryCallPhotoDimEffect, View.GONE);
1020 break;
1021
1022 default:
1023 // There's actually no call on hold. (Presumably this call's
1024 // state is IDLE, since any other state is meaningless for the
1025 // background call.)
1026 mSecondaryCallInfo.setVisibility(View.GONE);
1027 break;
1028 }
1029 }
1030
1031 private void showSecondaryCallInfo() {
1032 // This will call ViewStub#inflate() when needed.
1033 mSecondaryCallInfo.setVisibility(View.VISIBLE);
1034 if (mSecondaryCallName == null) {
1035 mSecondaryCallName = (TextView) findViewById(R.id.secondaryCallName);
1036 }
1037 if (mSecondaryCallPhoto == null) {
1038 mSecondaryCallPhoto = (ImageView) findViewById(R.id.secondaryCallPhoto);
1039 }
1040 if (mSecondaryCallPhotoDimEffect == null) {
1041 mSecondaryCallPhotoDimEffect = findViewById(R.id.dim_effect_for_secondary_photo);
1042 mSecondaryCallPhotoDimEffect.setOnClickListener(mInCallScreen);
1043 // Add a custom OnTouchListener to manually shrink the "hit target".
1044 mSecondaryCallPhotoDimEffect.setOnTouchListener(new SmallerHitTargetTouchListener());
1045 }
1046 mInCallScreen.updateButtonStateOutsideInCallTouchUi();
1047 }
1048
1049 /**
1050 * Method which is expected to be called from
1051 * {@link InCallScreen#updateButtonStateOutsideInCallTouchUi()}.
1052 */
1053 /* package */ void setSecondaryCallClickable(boolean clickable) {
1054 if (mSecondaryCallPhotoDimEffect != null) {
1055 mSecondaryCallPhotoDimEffect.setEnabled(clickable);
1056 }
1057 }
1058
1059 private String getCallFailedString(Call call) {
1060 Connection c = call.getEarliestConnection();
1061 int resID;
1062
1063 if (c == null) {
1064 if (DBG) log("getCallFailedString: connection is null, using default values.");
1065 // if this connection is null, just assume that the
1066 // default case occurs.
1067 resID = R.string.card_title_call_ended;
1068 } else {
1069
1070 Connection.DisconnectCause cause = c.getDisconnectCause();
1071
1072 // TODO: The card *title* should probably be "Call ended" in all
1073 // cases, but if the DisconnectCause was an error condition we should
1074 // probably also display the specific failure reason somewhere...
1075
1076 switch (cause) {
1077 case BUSY:
1078 resID = R.string.callFailed_userBusy;
1079 break;
1080
1081 case CONGESTION:
1082 resID = R.string.callFailed_congestion;
1083 break;
1084
1085 case TIMED_OUT:
1086 resID = R.string.callFailed_timedOut;
1087 break;
1088
1089 case SERVER_UNREACHABLE:
1090 resID = R.string.callFailed_server_unreachable;
1091 break;
1092
1093 case NUMBER_UNREACHABLE:
1094 resID = R.string.callFailed_number_unreachable;
1095 break;
1096
1097 case INVALID_CREDENTIALS:
1098 resID = R.string.callFailed_invalid_credentials;
1099 break;
1100
1101 case SERVER_ERROR:
1102 resID = R.string.callFailed_server_error;
1103 break;
1104
1105 case OUT_OF_NETWORK:
1106 resID = R.string.callFailed_out_of_network;
1107 break;
1108
1109 case LOST_SIGNAL:
1110 case CDMA_DROP:
1111 resID = R.string.callFailed_noSignal;
1112 break;
1113
1114 case LIMIT_EXCEEDED:
1115 resID = R.string.callFailed_limitExceeded;
1116 break;
1117
1118 case POWER_OFF:
1119 resID = R.string.callFailed_powerOff;
1120 break;
1121
1122 case ICC_ERROR:
1123 resID = R.string.callFailed_simError;
1124 break;
1125
1126 case OUT_OF_SERVICE:
1127 resID = R.string.callFailed_outOfService;
1128 break;
1129
1130 case INVALID_NUMBER:
1131 case UNOBTAINABLE_NUMBER:
1132 resID = R.string.callFailed_unobtainable_number;
1133 break;
1134
1135 default:
1136 resID = R.string.card_title_call_ended;
1137 break;
1138 }
1139 }
1140 return getContext().getString(resID);
1141 }
1142
1143 /**
1144 * Updates the name / photo / number / label fields on the CallCard
1145 * based on the specified CallerInfo.
1146 *
1147 * If the current call is a conference call, use
1148 * updateDisplayForConference() instead.
1149 */
1150 private void updateDisplayForPerson(CallerInfo info,
1151 int presentation,
1152 boolean isTemporary,
1153 Call call,
1154 Connection conn) {
1155 if (DBG) log("updateDisplayForPerson(" + info + ")\npresentation:" +
1156 presentation + " isTemporary:" + isTemporary);
1157
1158 // inform the state machine that we are displaying a photo.
1159 mPhotoTracker.setPhotoRequest(info);
1160 mPhotoTracker.setPhotoState(ContactsAsyncHelper.ImageTracker.DISPLAY_IMAGE);
1161
1162 // The actual strings we're going to display onscreen:
1163 String displayName;
1164 String displayNumber = null;
1165 String label = null;
1166 Uri personUri = null;
1167 // String socialStatusText = null;
1168 // Drawable socialStatusBadge = null;
1169
1170 // Gather missing info unless the call is generic, in which case we wouldn't use
1171 // the gathered information anyway.
1172 if (info != null && !call.isGeneric()) {
1173
1174 // It appears that there is a small change in behaviour with the
1175 // PhoneUtils' startGetCallerInfo whereby if we query with an
1176 // empty number, we will get a valid CallerInfo object, but with
1177 // fields that are all null, and the isTemporary boolean input
1178 // parameter as true.
1179
1180 // In the past, we would see a NULL callerinfo object, but this
1181 // ends up causing null pointer exceptions elsewhere down the
1182 // line in other cases, so we need to make this fix instead. It
1183 // appears that this was the ONLY call to PhoneUtils
1184 // .getCallerInfo() that relied on a NULL CallerInfo to indicate
1185 // an unknown contact.
1186
1187 // Currently, infi.phoneNumber may actually be a SIP address, and
1188 // if so, it might sometimes include the "sip:" prefix. That
1189 // prefix isn't really useful to the user, though, so strip it off
1190 // if present. (For any other URI scheme, though, leave the
1191 // prefix alone.)
1192 // TODO: It would be cleaner for CallerInfo to explicitly support
1193 // SIP addresses instead of overloading the "phoneNumber" field.
1194 // Then we could remove this hack, and instead ask the CallerInfo
1195 // for a "user visible" form of the SIP address.
1196 String number = info.phoneNumber;
1197 if ((number != null) && number.startsWith("sip:")) {
1198 number = number.substring(4);
1199 }
1200
1201 if (TextUtils.isEmpty(info.name)) {
1202 // No valid "name" in the CallerInfo, so fall back to
1203 // something else.
1204 // (Typically, we promote the phone number up to the "name" slot
1205 // onscreen, and possibly display a descriptive string in the
1206 // "number" slot.)
1207 if (TextUtils.isEmpty(number)) {
1208 // No name *or* number! Display a generic "unknown" string
1209 // (or potentially some other default based on the presentation.)
1210 displayName = PhoneUtils.getPresentationString(getContext(), presentation);
1211 if (DBG) log(" ==> no name *or* number! displayName = " + displayName);
1212 } else if (presentation != PhoneConstants.PRESENTATION_ALLOWED) {
1213 // This case should never happen since the network should never send a phone #
1214 // AND a restricted presentation. However we leave it here in case of weird
1215 // network behavior
1216 displayName = PhoneUtils.getPresentationString(getContext(), presentation);
1217 if (DBG) log(" ==> presentation not allowed! displayName = " + displayName);
1218 } else if (!TextUtils.isEmpty(info.cnapName)) {
1219 // No name, but we do have a valid CNAP name, so use that.
1220 displayName = info.cnapName;
1221 info.name = info.cnapName;
1222 displayNumber = number;
1223 if (DBG) log(" ==> cnapName available: displayName '"
1224 + displayName + "', displayNumber '" + displayNumber + "'");
1225 } else {
1226 // No name; all we have is a number. This is the typical
1227 // case when an incoming call doesn't match any contact,
1228 // or if you manually dial an outgoing number using the
1229 // dialpad.
1230
1231 // Promote the phone number up to the "name" slot:
1232 displayName = number;
1233
1234 // ...and use the "number" slot for a geographical description
1235 // string if available (but only for incoming calls.)
1236 if ((conn != null) && (conn.isIncoming())) {
1237 // TODO (CallerInfoAsyncQuery cleanup): Fix the CallerInfo
1238 // query to only do the geoDescription lookup in the first
1239 // place for incoming calls.
1240 displayNumber = info.geoDescription; // may be null
1241 }
1242
1243 if (DBG) log(" ==> no name; falling back to number: displayName '"
1244 + displayName + "', displayNumber '" + displayNumber + "'");
1245 }
1246 } else {
1247 // We do have a valid "name" in the CallerInfo. Display that
1248 // in the "name" slot, and the phone number in the "number" slot.
1249 if (presentation != PhoneConstants.PRESENTATION_ALLOWED) {
1250 // This case should never happen since the network should never send a name
1251 // AND a restricted presentation. However we leave it here in case of weird
1252 // network behavior
1253 displayName = PhoneUtils.getPresentationString(getContext(), presentation);
1254 if (DBG) log(" ==> valid name, but presentation not allowed!"
1255 + " displayName = " + displayName);
1256 } else {
1257 displayName = info.name;
1258 displayNumber = number;
1259 label = info.phoneLabel;
1260 if (DBG) log(" ==> name is present in CallerInfo: displayName '"
1261 + displayName + "', displayNumber '" + displayNumber + "'");
1262 }
1263 }
1264 personUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, info.person_id);
1265 if (DBG) log("- got personUri: '" + personUri
1266 + "', based on info.person_id: " + info.person_id);
1267 } else {
1268 displayName = PhoneUtils.getPresentationString(getContext(), presentation);
1269 }
1270
1271 if (call.isGeneric()) {
1272 updateGenericInfoUi();
1273 } else {
1274 updateInfoUi(displayName, displayNumber, label);
1275 }
1276
1277 // Update mPhoto
1278 // if the temporary flag is set, we know we'll be getting another call after
1279 // the CallerInfo has been correctly updated. So, we can skip the image
1280 // loading until then.
1281
1282 // If the photoResource is filled in for the CallerInfo, (like with the
1283 // Emergency Number case), then we can just set the photo image without
1284 // requesting for an image load. Please refer to CallerInfoAsyncQuery.java
1285 // for cases where CallerInfo.photoResource may be set. We can also avoid
1286 // the image load step if the image data is cached.
1287 if (isTemporary && (info == null || !info.isCachedPhotoCurrent)) {
1288 mPhoto.setTag(null);
1289 mPhoto.setVisibility(View.INVISIBLE);
1290 } else if (info != null && info.photoResource != 0){
1291 showImage(mPhoto, info.photoResource);
1292 } else if (!showCachedImage(mPhoto, info)) {
1293 if (personUri == null) {
1294 Log.w(LOG_TAG, "personPri is null. Just use Unknown picture.");
1295 showImage(mPhoto, R.drawable.picture_unknown);
1296 } else if (personUri.equals(mLoadingPersonUri)) {
1297 if (DBG) {
1298 log("The requested Uri (" + personUri + ") is being loaded already."
1299 + " Ignoret the duplicate load request.");
1300 }
1301 } else {
1302 // Remember which person's photo is being loaded right now so that we won't issue
1303 // unnecessary load request multiple times, which will mess up animation around
1304 // the contact photo.
1305 mLoadingPersonUri = personUri;
1306
1307 // Forget the drawable previously used.
1308 mPhoto.setTag(null);
1309 // Show empty screen for a moment.
1310 mPhoto.setVisibility(View.INVISIBLE);
1311 // Load the image with a callback to update the image state.
1312 // When the load is finished, onImageLoadComplete() will be called.
1313 ContactsAsyncHelper.startObtainPhotoAsync(TOKEN_UPDATE_PHOTO_FOR_CALL_STATE,
1314 getContext(), personUri, this, new AsyncLoadCookie(mPhoto, info, call));
1315
1316 // If the image load is too slow, we show a default avatar icon afterward.
1317 // If it is fast enough, this message will be canceled on onImageLoadComplete().
1318 mHandler.removeMessages(MESSAGE_SHOW_UNKNOWN_PHOTO);
1319 mHandler.sendEmptyMessageDelayed(MESSAGE_SHOW_UNKNOWN_PHOTO, MESSAGE_DELAY);
1320 }
1321 }
1322
1323 // If the phone call is on hold, show it with darker status.
1324 // Right now we achieve it by overlaying opaque View.
1325 // Note: See also layout file about why so and what is the other possibilities.
1326 if (call.getState() == Call.State.HOLDING) {
1327 AnimationUtils.Fade.show(mPhotoDimEffect);
1328 } else {
1329 AnimationUtils.Fade.hide(mPhotoDimEffect, View.GONE);
1330 }
1331
1332 // Other text fields:
1333 updateCallTypeLabel(call);
1334 // updateSocialStatus(socialStatusText, socialStatusBadge, call); // Currently unused
1335 }
1336
1337 /**
1338 * Updates the info portion of the UI to be generic. Used for CDMA 3-way calls.
1339 */
1340 private void updateGenericInfoUi() {
1341 mName.setText(R.string.card_title_in_call);
1342 mPhoneNumber.setVisibility(View.GONE);
1343 mLabel.setVisibility(View.GONE);
1344 }
1345
1346 /**
1347 * Updates the info portion of the call card with passed in values.
1348 */
1349 private void updateInfoUi(String displayName, String displayNumber, String label) {
1350 mName.setText(displayName);
1351 mName.setVisibility(View.VISIBLE);
1352
1353 if (TextUtils.isEmpty(displayNumber)) {
1354 mPhoneNumber.setVisibility(View.GONE);
1355 // We have a real phone number as "mName" so make it always LTR
1356 mName.setTextDirection(View.TEXT_DIRECTION_LTR);
1357 } else {
1358 mPhoneNumber.setText(displayNumber);
1359 mPhoneNumber.setVisibility(View.VISIBLE);
1360 // We have a real phone number as "mPhoneNumber" so make it always LTR
1361 mPhoneNumber.setTextDirection(View.TEXT_DIRECTION_LTR);
1362 }
1363
1364 if (TextUtils.isEmpty(label)) {
1365 mLabel.setVisibility(View.GONE);
1366 } else {
1367 mLabel.setText(label);
1368 mLabel.setVisibility(View.VISIBLE);
1369 }
1370 }
1371
1372 /**
1373 * Updates the name / photo / number / label fields
1374 * for the special "conference call" state.
1375 *
1376 * If the current call has only a single connection, use
1377 * updateDisplayForPerson() instead.
1378 */
1379 private void updateDisplayForConference(Call call) {
1380 if (DBG) log("updateDisplayForConference()...");
1381
1382 int phoneType = call.getPhone().getPhoneType();
1383 if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
1384 // This state corresponds to both 3-Way merged call and
1385 // Call Waiting accepted call.
1386 // In this case we display the UI in a "generic" state, with
1387 // the generic "dialing" icon and no caller information,
1388 // because in this state in CDMA the user does not really know
1389 // which caller party he is talking to.
1390 showImage(mPhoto, R.drawable.picture_dialing);
1391 mName.setText(R.string.card_title_in_call);
1392 } else if ((phoneType == PhoneConstants.PHONE_TYPE_GSM)
1393 || (phoneType == PhoneConstants.PHONE_TYPE_SIP)) {
1394 // Normal GSM (or possibly SIP?) conference call.
1395 // Display the "conference call" image as the contact photo.
1396 // TODO: Better visual treatment for contact photos in a
1397 // conference call (see bug 1313252).
1398 showImage(mPhoto, R.drawable.picture_conference);
1399 mName.setText(R.string.card_title_conf_call);
1400 } else {
1401 throw new IllegalStateException("Unexpected phone type: " + phoneType);
1402 }
1403
1404 mName.setVisibility(View.VISIBLE);
1405
1406 // TODO: For a conference call, the "phone number" slot is specced
1407 // to contain a summary of who's on the call, like "Bill Foldes
1408 // and Hazel Nutt" or "Bill Foldes and 2 others".
1409 // But for now, just hide it:
1410 mPhoneNumber.setVisibility(View.GONE);
1411 mLabel.setVisibility(View.GONE);
1412
1413 // Other text fields:
1414 updateCallTypeLabel(call);
1415 // updateSocialStatus(null, null, null); // socialStatus is never visible in this state
1416
1417 // TODO: for a GSM conference call, since we do actually know who
1418 // you're talking to, consider also showing names / numbers /
1419 // photos of some of the people on the conference here, so you can
1420 // see that info without having to click "Manage conference". We
1421 // probably have enough space to show info for 2 people, at least.
1422 //
1423 // To do this, our caller would pass us the activeConnections
1424 // list, and we'd call PhoneUtils.getCallerInfo() separately for
1425 // each connection.
1426 }
1427
1428 /**
1429 * Updates the CallCard "photo" IFF the specified Call is in a state
1430 * that needs a special photo (like "busy" or "dialing".)
1431 *
1432 * If the current call does not require a special image in the "photo"
1433 * slot onscreen, don't do anything, since presumably the photo image
1434 * has already been set (to the photo of the person we're talking, or
1435 * the generic "picture_unknown" image, or the "conference call"
1436 * image.)
1437 */
1438 private void updatePhotoForCallState(Call call) {
1439 if (DBG) log("updatePhotoForCallState(" + call + ")...");
1440 int photoImageResource = 0;
1441
1442 // Check for the (relatively few) telephony states that need a
1443 // special image in the "photo" slot.
1444 Call.State state = call.getState();
1445 switch (state) {
1446 case DISCONNECTED:
1447 // Display the special "busy" photo for BUSY or CONGESTION.
1448 // Otherwise (presumably the normal "call ended" state)
1449 // leave the photo alone.
1450 Connection c = call.getEarliestConnection();
1451 // if the connection is null, we assume the default case,
1452 // otherwise update the image resource normally.
1453 if (c != null) {
1454 Connection.DisconnectCause cause = c.getDisconnectCause();
1455 if ((cause == Connection.DisconnectCause.BUSY)
1456 || (cause == Connection.DisconnectCause.CONGESTION)) {
1457 photoImageResource = R.drawable.picture_busy;
1458 }
1459 } else if (DBG) {
1460 log("updatePhotoForCallState: connection is null, ignoring.");
1461 }
1462
1463 // TODO: add special images for any other DisconnectCauses?
1464 break;
1465
1466 case ALERTING:
1467 case DIALING:
1468 default:
1469 // Leave the photo alone in all other states.
1470 // If this call is an individual call, and the image is currently
1471 // displaying a state, (rather than a photo), we'll need to update
1472 // the image.
1473 // This is for the case where we've been displaying the state and
1474 // now we need to restore the photo. This can happen because we
1475 // only query the CallerInfo once, and limit the number of times
1476 // the image is loaded. (So a state image may overwrite the photo
1477 // and we would otherwise have no way of displaying the photo when
1478 // the state goes away.)
1479
1480 // if the photoResource field is filled-in in the Connection's
1481 // caller info, then we can just use that instead of requesting
1482 // for a photo load.
1483
1484 // look for the photoResource if it is available.
1485 CallerInfo ci = null;
1486 {
1487 Connection conn = null;
1488 int phoneType = call.getPhone().getPhoneType();
1489 if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
1490 conn = call.getLatestConnection();
1491 } else if ((phoneType == PhoneConstants.PHONE_TYPE_GSM)
1492 || (phoneType == PhoneConstants.PHONE_TYPE_SIP)) {
1493 conn = call.getEarliestConnection();
1494 } else {
1495 throw new IllegalStateException("Unexpected phone type: " + phoneType);
1496 }
1497
1498 if (conn != null) {
1499 Object o = conn.getUserData();
1500 if (o instanceof CallerInfo) {
1501 ci = (CallerInfo) o;
1502 } else if (o instanceof PhoneUtils.CallerInfoToken) {
1503 ci = ((PhoneUtils.CallerInfoToken) o).currentInfo;
1504 }
1505 }
1506 }
1507
1508 if (ci != null) {
1509 photoImageResource = ci.photoResource;
1510 }
1511
1512 // If no photoResource found, check to see if this is a conference call. If
1513 // it is not a conference call:
1514 // 1. Try to show the cached image
1515 // 2. If the image is not cached, check to see if a load request has been
1516 // made already.
1517 // 3. If the load request has not been made [DISPLAY_DEFAULT], start the
1518 // request and note that it has started by updating photo state with
1519 // [DISPLAY_IMAGE].
1520 if (photoImageResource == 0) {
1521 if (!PhoneUtils.isConferenceCall(call)) {
1522 if (!showCachedImage(mPhoto, ci) && (mPhotoTracker.getPhotoState() ==
1523 ContactsAsyncHelper.ImageTracker.DISPLAY_DEFAULT)) {
1524 Uri photoUri = mPhotoTracker.getPhotoUri();
1525 if (photoUri == null) {
1526 Log.w(LOG_TAG, "photoUri became null. Show default avatar icon");
1527 showImage(mPhoto, R.drawable.picture_unknown);
1528 } else {
1529 if (DBG) {
1530 log("start asynchronous load inside updatePhotoForCallState()");
1531 }
1532 mPhoto.setTag(null);
1533 // Make it invisible for a moment
1534 mPhoto.setVisibility(View.INVISIBLE);
1535 ContactsAsyncHelper.startObtainPhotoAsync(TOKEN_DO_NOTHING,
1536 getContext(), photoUri, this,
1537 new AsyncLoadCookie(mPhoto, ci, null));
1538 }
1539 mPhotoTracker.setPhotoState(
1540 ContactsAsyncHelper.ImageTracker.DISPLAY_IMAGE);
1541 }
1542 }
1543 } else {
1544 showImage(mPhoto, photoImageResource);
1545 mPhotoTracker.setPhotoState(ContactsAsyncHelper.ImageTracker.DISPLAY_IMAGE);
1546 return;
1547 }
1548 break;
1549 }
1550
1551 if (photoImageResource != 0) {
1552 if (DBG) log("- overrriding photo image: " + photoImageResource);
1553 showImage(mPhoto, photoImageResource);
1554 // Track the image state.
1555 mPhotoTracker.setPhotoState(ContactsAsyncHelper.ImageTracker.DISPLAY_DEFAULT);
1556 }
1557 }
1558
1559 /**
1560 * Try to display the cached image from the callerinfo object.
1561 *
1562 * @return true if we were able to find the image in the cache, false otherwise.
1563 */
1564 private static final boolean showCachedImage(ImageView view, CallerInfo ci) {
1565 if ((ci != null) && ci.isCachedPhotoCurrent) {
1566 if (ci.cachedPhoto != null) {
1567 showImage(view, ci.cachedPhoto);
1568 } else {
1569 showImage(view, R.drawable.picture_unknown);
1570 }
1571 return true;
1572 }
1573 return false;
1574 }
1575
1576 /** Helper function to display the resource in the imageview AND ensure its visibility.*/
1577 private static final void showImage(ImageView view, int resource) {
1578 showImage(view, view.getContext().getResources().getDrawable(resource));
1579 }
1580
1581 private static final void showImage(ImageView view, Bitmap bitmap) {
1582 showImage(view, new BitmapDrawable(view.getContext().getResources(), bitmap));
1583 }
1584
1585 /** Helper function to display the drawable in the imageview AND ensure its visibility.*/
1586 private static final void showImage(ImageView view, Drawable drawable) {
1587 Resources res = view.getContext().getResources();
1588 Drawable current = (Drawable) view.getTag();
1589
1590 if (current == null) {
1591 if (DBG) log("Start fade-in animation for " + view);
1592 view.setImageDrawable(drawable);
1593 AnimationUtils.Fade.show(view);
1594 view.setTag(drawable);
1595 } else {
1596 AnimationUtils.startCrossFade(view, current, drawable);
1597 view.setVisibility(View.VISIBLE);
1598 }
1599 }
1600
1601 /**
1602 * Returns the special card title used in emergency callback mode (ECM),
1603 * which shows your own phone number.
1604 */
1605 private String getECMCardTitle(Context context, Phone phone) {
1606 String rawNumber = phone.getLine1Number(); // may be null or empty
1607 String formattedNumber;
1608 if (!TextUtils.isEmpty(rawNumber)) {
1609 formattedNumber = PhoneNumberUtils.formatNumber(rawNumber);
1610 } else {
1611 formattedNumber = context.getString(R.string.unknown);
1612 }
1613 String titleFormat = context.getString(R.string.card_title_my_phone_number);
1614 return String.format(titleFormat, formattedNumber);
1615 }
1616
1617 /**
1618 * Updates the "Call type" label, based on the current foreground call.
1619 * This is a special label and/or branding we display for certain
1620 * kinds of calls.
1621 *
1622 * (So far, this is used only for SIP calls, which get an
1623 * "Internet call" label. TODO: But eventually, the telephony
1624 * layer might allow each pluggable "provider" to specify a string
1625 * and/or icon to be displayed here.)
1626 */
1627 private void updateCallTypeLabel(Call call) {
1628 int phoneType = (call != null) ? call.getPhone().getPhoneType() :
1629 PhoneConstants.PHONE_TYPE_NONE;
1630 if (phoneType == PhoneConstants.PHONE_TYPE_SIP) {
1631 mCallTypeLabel.setVisibility(View.VISIBLE);
1632 mCallTypeLabel.setText(R.string.incall_call_type_label_sip);
1633 mCallTypeLabel.setTextColor(mTextColorCallTypeSip);
1634 // If desired, we could also display a "badge" next to the label, as follows:
1635 // mCallTypeLabel.setCompoundDrawablesWithIntrinsicBounds(
1636 // callTypeSpecificBadge, null, null, null);
1637 // mCallTypeLabel.setCompoundDrawablePadding((int) (mDensity * 6));
1638 } else {
1639 mCallTypeLabel.setVisibility(View.GONE);
1640 }
1641 }
1642
1643 /**
1644 * Updates the "social status" label with the specified text and
1645 * (optional) badge.
1646 */
1647 /*private void updateSocialStatus(String socialStatusText,
1648 Drawable socialStatusBadge,
1649 Call call) {
1650 // The socialStatus field is *only* visible while an incoming call
1651 // is ringing, never in any other call state.
1652 if ((socialStatusText != null)
1653 && (call != null)
1654 && call.isRinging()
1655 && !call.isGeneric()) {
1656 mSocialStatus.setVisibility(View.VISIBLE);
1657 mSocialStatus.setText(socialStatusText);
1658 mSocialStatus.setCompoundDrawablesWithIntrinsicBounds(
1659 socialStatusBadge, null, null, null);
1660 mSocialStatus.setCompoundDrawablePadding((int) (mDensity * 6));
1661 } else {
1662 mSocialStatus.setVisibility(View.GONE);
1663 }
1664 }*/
1665
1666 /**
1667 * Hides the top-level UI elements of the call card: The "main
1668 * call card" element representing the current active or ringing call,
1669 * and also the info areas for "ongoing" or "on hold" calls in some
1670 * states.
1671 *
1672 * This is intended to be used in special states where the normal
1673 * in-call UI is totally replaced by some other UI, like OTA mode on a
1674 * CDMA device.
1675 *
1676 * To bring back the regular CallCard UI, just re-run the normal
1677 * updateState() call sequence.
1678 */
1679 public void hideCallCardElements() {
1680 mPrimaryCallInfo.setVisibility(View.GONE);
1681 mSecondaryCallInfo.setVisibility(View.GONE);
1682 }
1683
1684 /*
1685 * Updates the hint (like "Rotate to answer") that we display while
1686 * the user is dragging the incoming call RotarySelector widget.
1687 */
1688 /* package */ void setIncomingCallWidgetHint(int hintTextResId, int hintColorResId) {
1689 mIncomingCallWidgetHintTextResId = hintTextResId;
1690 mIncomingCallWidgetHintColorResId = hintColorResId;
1691 }
1692
1693 // Accessibility event support.
1694 // Since none of the CallCard elements are focusable, we need to manually
1695 // fill in the AccessibilityEvent here (so that the name / number / etc will
1696 // get pronounced by a screen reader, for example.)
1697 @Override
1698 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
1699 if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
1700 dispatchPopulateAccessibilityEvent(event, mName);
1701 dispatchPopulateAccessibilityEvent(event, mPhoneNumber);
1702 return true;
1703 }
1704
1705 dispatchPopulateAccessibilityEvent(event, mCallStateLabel);
1706 dispatchPopulateAccessibilityEvent(event, mPhoto);
1707 dispatchPopulateAccessibilityEvent(event, mName);
1708 dispatchPopulateAccessibilityEvent(event, mPhoneNumber);
1709 dispatchPopulateAccessibilityEvent(event, mLabel);
1710 // dispatchPopulateAccessibilityEvent(event, mSocialStatus);
1711 if (mSecondaryCallName != null) {
1712 dispatchPopulateAccessibilityEvent(event, mSecondaryCallName);
1713 }
1714 if (mSecondaryCallPhoto != null) {
1715 dispatchPopulateAccessibilityEvent(event, mSecondaryCallPhoto);
1716 }
1717 return true;
1718 }
1719
1720 private void dispatchPopulateAccessibilityEvent(AccessibilityEvent event, View view) {
1721 List<CharSequence> eventText = event.getText();
1722 int size = eventText.size();
1723 view.dispatchPopulateAccessibilityEvent(event);
1724 // if no text added write null to keep relative position
1725 if (size == eventText.size()) {
1726 eventText.add(null);
1727 }
1728 }
1729
1730 public void clear() {
1731 // The existing phone design is to keep an instance of call card forever. Until that
1732 // design changes, this method is needed to clear (reset) the call card for the next call
1733 // so old data is not shown.
1734
1735 // Other elements can also be cleared here. Starting with elapsed time to fix a bug.
1736 mElapsedTime.setVisibility(View.GONE);
1737 mElapsedTime.setText(null);
1738 }
1739
1740
1741 // Debugging / testing code
1742
1743 private static void log(String msg) {
1744 Log.d(LOG_TAG, msg);
1745 }
1746}