Debian Codegraph @

core/java/com/android/internal/widget/MessagingLayout.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2017 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
17 package com.android.internal.widget;
18
19 import static com.android.internal.widget.MessagingGroup.IMAGE_DISPLAY_LOCATION_EXTERNAL;
20 import static com.android.internal.widget.MessagingGroup.IMAGE_DISPLAY_LOCATION_INLINE;
21
22 import android.annotation.AttrRes;
23 import android.annotation.NonNull;
24 import android.annotation.Nullable;
25 import android.annotation.StyleRes;
26 import android.app.Notification;
27 import android.app.Person;
28 import android.app.RemoteInputHistoryItem;
29 import android.content.Context;
30 import android.graphics.Rect;
31 import android.graphics.drawable.Icon;
32 import android.os.Bundle;
33 import android.os.Parcelable;
34 import android.text.TextUtils;
35 import android.util.ArrayMap;
36 import android.util.AttributeSet;
37 import android.util.DisplayMetrics;
38 import android.view.RemotableViewMethod;
39 import android.view.View;
40 import android.view.ViewGroup;
41 import android.view.ViewTreeObserver;
42 import android.view.animation.Interpolator;
43 import android.view.animation.PathInterpolator;
44 import android.widget.FrameLayout;
45 import android.widget.ImageView;
46 import android.widget.RemoteViews;
47
48 import com.android.internal.R;
49 import com.android.internal.util.ContrastColorUtil;
50
51 import java.util.ArrayList;
52 import java.util.List;
53 import java.util.Map;
54
55 /**
56 * A custom-built layout for the Notification.MessagingStyle allows dynamic addition and removal
57 * messages and adapts the layout accordingly.
58 */
59 @RemoteViews.RemoteView
60 public class MessagingLayout extends FrameLayout
61 implements ImageMessageConsumer, IMessagingLayout {
62
63 private static final float COLOR_SHIFT_AMOUNT = 60;
64 public static final Interpolator LINEAR_OUT_SLOW_IN = new PathInterpolator(0f, 0f, 0.2f, 1f);
65 public static final Interpolator FAST_OUT_LINEAR_IN = new PathInterpolator(0.4f, 0f, 1f, 1f);
66 public static final Interpolator FAST_OUT_SLOW_IN = new PathInterpolator(0.4f, 0f, 0.2f, 1f);
67 public static final OnLayoutChangeListener MESSAGING_PROPERTY_ANIMATOR
68 = new MessagingPropertyAnimator();
69 private final PeopleHelper mPeopleHelper = new PeopleHelper();
70 private List<MessagingMessage> mMessages = new ArrayList<>();
71 private List<MessagingMessage> mHistoricMessages = new ArrayList<>();
72 private MessagingLinearLayout mMessagingLinearLayout;
73 private boolean mShowHistoricMessages;
74 private ArrayList<MessagingGroup> mGroups = new ArrayList<>();
75 private MessagingLinearLayout mImageMessageContainer;
76 private ImageView mRightIconView;
77 private Rect mMessagingClipRect;
78 private int mLayoutColor;
79 private int mSenderTextColor;
80 private int mMessageTextColor;
81 private Icon mAvatarReplacement;
82 private boolean mIsOneToOne;
83 private ArrayList<MessagingGroup> mAddedGroups = new ArrayList<>();
84 private Person mUser;
85 private CharSequence mNameReplacement;
86 private boolean mIsCollapsed;
87 private ImageResolver mImageResolver;
88 private CharSequence mConversationTitle;
89 private ArrayList<MessagingLinearLayout.MessagingChild> mToRecycle = new ArrayList<>();
90
91 public MessagingLayout(@NonNull Context context) {
92 super(context);
93 }
94
95 public MessagingLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
96 super(context, attrs);
97 }
98
99 public MessagingLayout(@NonNull Context context, @Nullable AttributeSet attrs,
100 @AttrRes int defStyleAttr) {
101 super(context, attrs, defStyleAttr);
102 }
103
104 public MessagingLayout(@NonNull Context context, @Nullable AttributeSet attrs,
105 @AttrRes int defStyleAttr, @StyleRes int defStyleRes) {
106 super(context, attrs, defStyleAttr, defStyleRes);
107 }
108
109 @Override
110 protected void onFinishInflate() {
111 super.onFinishInflate();
112 mPeopleHelper.init(getContext());
113 mMessagingLinearLayout = findViewById(R.id.notification_messaging);
114 mImageMessageContainer = findViewById(R.id.conversation_image_message_container);
115 mRightIconView = findViewById(R.id.right_icon);
116 // We still want to clip, but only on the top, since views can temporarily out of bounds
117 // during transitions.
118 DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
119 int size = Math.max(displayMetrics.widthPixels, displayMetrics.heightPixels);
120 mMessagingClipRect = new Rect(0, 0, size, size);
121 setMessagingClippingDisabled(false);
122 }
123
124 @RemotableViewMethod
125 public void setAvatarReplacement(Icon icon) {
126 mAvatarReplacement = icon;
127 }
128
129 @RemotableViewMethod
130 public void setNameReplacement(CharSequence nameReplacement) {
131 mNameReplacement = nameReplacement;
132 }
133
134 /**
135 * Set this layout to show the collapsed representation.
136 *
137 * @param isCollapsed is it collapsed
138 */
139 @RemotableViewMethod
140 public void setIsCollapsed(boolean isCollapsed) {
141 mIsCollapsed = isCollapsed;
142 }
143
144 @RemotableViewMethod
145 public void setLargeIcon(Icon largeIcon) {
146 // Unused
147 }
148
149 /**
150 * Sets the conversation title of this conversation.
151 *
152 * @param conversationTitle the conversation title
153 */
154 @RemotableViewMethod
155 public void setConversationTitle(CharSequence conversationTitle) {
156 mConversationTitle = conversationTitle;
157 }
158
159 @RemotableViewMethod
160 public void setData(Bundle extras) {
161 Parcelable[] messages = extras.getParcelableArray(Notification.EXTRA_MESSAGES);
162 List<Notification.MessagingStyle.Message> newMessages
163 = Notification.MessagingStyle.Message.getMessagesFromBundleArray(messages);
164 Parcelable[] histMessages = extras.getParcelableArray(Notification.EXTRA_HISTORIC_MESSAGES);
165 List<Notification.MessagingStyle.Message> newHistoricMessages
166 = Notification.MessagingStyle.Message.getMessagesFromBundleArray(histMessages);
167 setUser(extras.getParcelable(Notification.EXTRA_MESSAGING_PERSON));
168 RemoteInputHistoryItem[] history = (RemoteInputHistoryItem[])
169 extras.getParcelableArray(Notification.EXTRA_REMOTE_INPUT_HISTORY_ITEMS);
170 addRemoteInputHistoryToMessages(newMessages, history);
171 boolean showSpinner =
172 extras.getBoolean(Notification.EXTRA_SHOW_REMOTE_INPUT_SPINNER, false);
173 bind(newMessages, newHistoricMessages, showSpinner);
174 }
175
176 @Override
177 public void setImageResolver(ImageResolver resolver) {
178 mImageResolver = resolver;
179 }
180
181 private void addRemoteInputHistoryToMessages(
182 List<Notification.MessagingStyle.Message> newMessages,
183 RemoteInputHistoryItem[] remoteInputHistory) {
184 if (remoteInputHistory == null || remoteInputHistory.length == 0) {
185 return;
186 }
187 for (int i = remoteInputHistory.length - 1; i >= 0; i--) {
188 RemoteInputHistoryItem historyMessage = remoteInputHistory[i];
189 Notification.MessagingStyle.Message message = new Notification.MessagingStyle.Message(
190 historyMessage.getText(), 0, (Person) null, true /* remoteHistory */);
191 if (historyMessage.getUri() != null) {
192 message.setData(historyMessage.getMimeType(), historyMessage.getUri());
193 }
194 newMessages.add(message);
195 }
196 }
197
198 private void bind(List<Notification.MessagingStyle.Message> newMessages,
199 List<Notification.MessagingStyle.Message> newHistoricMessages,
200 boolean showSpinner) {
201
202 List<MessagingMessage> historicMessages = createMessages(newHistoricMessages,
203 true /* isHistoric */);
204 List<MessagingMessage> messages = createMessages(newMessages, false /* isHistoric */);
205
206 ArrayList<MessagingGroup> oldGroups = new ArrayList<>(mGroups);
207 addMessagesToGroups(historicMessages, messages, showSpinner);
208
209 // Let's first check which groups were removed altogether and remove them in one animation
210 removeGroups(oldGroups);
211
212 // Let's remove the remaining messages
213 for (MessagingMessage message : mMessages) {
214 message.removeMessage(mToRecycle);
215 }
216 for (MessagingMessage historicMessage : mHistoricMessages) {
217 historicMessage.removeMessage(mToRecycle);
218 }
219
220 mMessages = messages;
221 mHistoricMessages = historicMessages;
222
223 updateHistoricMessageVisibility();
224 updateTitleAndNamesDisplay();
225 // after groups are finalized, hide the first sender name if it's showing as the title
226 mPeopleHelper.maybeHideFirstSenderName(mGroups, mIsOneToOne, mConversationTitle);
227 updateImageMessages();
228
229 // Recycle everything at the end of the update, now that we know it's no longer needed.
230 for (MessagingLinearLayout.MessagingChild child : mToRecycle) {
231 child.recycle();
232 }
233 mToRecycle.clear();
234 }
235
236 private void updateImageMessages() {
237 View newMessage = null;
238 if (mImageMessageContainer == null) {
239 return;
240 }
241 if (mIsCollapsed && !mGroups.isEmpty()) {
242 // When collapsed, we're displaying the image message in a dedicated container
243 // on the right of the layout instead of inline. Let's add the isolated image there
244 MessagingGroup messagingGroup = mGroups.get(mGroups.size() - 1);
245 MessagingImageMessage isolatedMessage = messagingGroup.getIsolatedMessage();
246 if (isolatedMessage != null) {
247 newMessage = isolatedMessage.getView();
248 }
249 }
250 // Remove all messages that don't belong into the image layout
251 View previousMessage = mImageMessageContainer.getChildAt(0);
252 if (previousMessage != newMessage) {
253 mImageMessageContainer.removeView(previousMessage);
254 if (newMessage != null) {
255 mImageMessageContainer.addView(newMessage);
256 }
257 }
258 mImageMessageContainer.setVisibility(newMessage != null ? VISIBLE : GONE);
259
260 // When showing an image message, do not show the large icon. Removing the drawable
261 // prevents it from being shown in the left_icon view (by the grouping util).
262 if (newMessage != null && mRightIconView != null && mRightIconView.getDrawable() != null) {
263 mRightIconView.setImageDrawable(null);
264 mRightIconView.setVisibility(GONE);
265 }
266 }
267
268 private void removeGroups(ArrayList<MessagingGroup> oldGroups) {
269 int size = oldGroups.size();
270 for (int i = 0; i < size; i++) {
271 MessagingGroup group = oldGroups.get(i);
272 if (!mGroups.contains(group)) {
273 List<MessagingMessage> messages = group.getMessages();
274
275 boolean wasShown = group.isShown();
276 mMessagingLinearLayout.removeView(group);
277 if (wasShown && !MessagingLinearLayout.isGone(group)) {
278 mMessagingLinearLayout.addTransientView(group, 0);
279 group.removeGroupAnimated(() -> {
280 mMessagingLinearLayout.removeTransientView(group);
281 group.recycle();
282 });
283 } else {
284 mToRecycle.add(group);
285 }
286 mMessages.removeAll(messages);
287 mHistoricMessages.removeAll(messages);
288 }
289 }
290 }
291
292 private void updateTitleAndNamesDisplay() {
293 Map<CharSequence, String> uniqueNames = mPeopleHelper.mapUniqueNamesToPrefix(mGroups);
294
295 // Now that we have the correct symbols, let's look what we have cached
296 ArrayMap<CharSequence, Icon> cachedAvatars = new ArrayMap<>();
297 for (int i = 0; i < mGroups.size(); i++) {
298 // Let's now set the avatars
299 MessagingGroup group = mGroups.get(i);
300 boolean isOwnMessage = group.getSender() == mUser;
301 CharSequence senderName = group.getSenderName();
302 if (!group.needsGeneratedAvatar() || TextUtils.isEmpty(senderName)
303 || (mIsOneToOne && mAvatarReplacement != null && !isOwnMessage)) {
304 continue;
305 }
306 String symbol = uniqueNames.get(senderName);
307 Icon cachedIcon = group.getAvatarSymbolIfMatching(senderName,
308 symbol, mLayoutColor);
309 if (cachedIcon != null) {
310 cachedAvatars.put(senderName, cachedIcon);
311 }
312 }
313
314 for (int i = 0; i < mGroups.size(); i++) {
315 // Let's now set the avatars
316 MessagingGroup group = mGroups.get(i);
317 CharSequence senderName = group.getSenderName();
318 if (!group.needsGeneratedAvatar() || TextUtils.isEmpty(senderName)) {
319 continue;
320 }
321 if (mIsOneToOne && mAvatarReplacement != null && group.getSender() != mUser) {
322 group.setAvatar(mAvatarReplacement);
323 } else {
324 Icon cachedIcon = cachedAvatars.get(senderName);
325 if (cachedIcon == null) {
326 cachedIcon = createAvatarSymbol(senderName, uniqueNames.get(senderName),
327 mLayoutColor);
328 cachedAvatars.put(senderName, cachedIcon);
329 }
330 group.setCreatedAvatar(cachedIcon, senderName, uniqueNames.get(senderName),
331 mLayoutColor);
332 }
333 }
334 }
335
336 public Icon createAvatarSymbol(CharSequence senderName, String symbol, int layoutColor) {
337 return mPeopleHelper.createAvatarSymbol(senderName, symbol, layoutColor);
338 }
339
340 private int findColor(CharSequence senderName, int layoutColor) {
341 double luminance = ContrastColorUtil.calculateLuminance(layoutColor);
342 float shift = Math.abs(senderName.hashCode()) % 5 / 4.0f - 0.5f;
343
344 // we need to offset the range if the luminance is too close to the borders
345 shift += Math.max(COLOR_SHIFT_AMOUNT / 2.0f / 100 - luminance, 0);
346 shift -= Math.max(COLOR_SHIFT_AMOUNT / 2.0f / 100 - (1.0f - luminance), 0);
347 return ContrastColorUtil.getShiftedColor(layoutColor,
348 (int) (shift * COLOR_SHIFT_AMOUNT));
349 }
350
351 private String findNameSplit(String existingName) {
352 String[] split = existingName.split(" ");
353 if (split.length > 1) {
354 return Character.toString(split[0].charAt(0))
355 + Character.toString(split[1].charAt(0));
356 }
357 return existingName.substring(0, 1);
358 }
359
360 @RemotableViewMethod
361 public void setLayoutColor(int color) {
362 mLayoutColor = color;
363 }
364
365 @RemotableViewMethod
366 public void setIsOneToOne(boolean oneToOne) {
367 mIsOneToOne = oneToOne;
368 }
369
370 @RemotableViewMethod
371 public void setSenderTextColor(int color) {
372 mSenderTextColor = color;
373 }
374
375
376 /**
377 * @param color the color of the notification background
378 */
379 @RemotableViewMethod
380 public void setNotificationBackgroundColor(int color) {
381 // Nothing to do with this
382 }
383
384 @RemotableViewMethod
385 public void setMessageTextColor(int color) {
386 mMessageTextColor = color;
387 }
388
389 public void setUser(Person user) {
390 mUser = user;
391 if (mUser.getIcon() == null) {
392 Icon userIcon = Icon.createWithResource(getContext(),
393 com.android.internal.R.drawable.messaging_user);
394 userIcon.setTint(mLayoutColor);
395 mUser = mUser.toBuilder().setIcon(userIcon).build();
396 }
397 }
398
399 private void addMessagesToGroups(List<MessagingMessage> historicMessages,
400 List<MessagingMessage> messages, boolean showSpinner) {
401 // Let's first find our groups!
402 List<List<MessagingMessage>> groups = new ArrayList<>();
403 List<Person> senders = new ArrayList<>();
404
405 // Lets first find the groups
406 findGroups(historicMessages, messages, groups, senders);
407
408 // Let's now create the views and reorder them accordingly
409 createGroupViews(groups, senders, showSpinner);
410 }
411
412 private void createGroupViews(List<List<MessagingMessage>> groups,
413 List<Person> senders, boolean showSpinner) {
414 mGroups.clear();
415 for (int groupIndex = 0; groupIndex < groups.size(); groupIndex++) {
416 List<MessagingMessage> group = groups.get(groupIndex);
417 MessagingGroup newGroup = null;
418 // we'll just take the first group that exists or create one there is none
419 for (int messageIndex = group.size() - 1; messageIndex >= 0; messageIndex--) {
420 MessagingMessage message = group.get(messageIndex);
421 newGroup = message.getGroup();
422 if (newGroup != null) {
423 break;
424 }
425 }
426 if (newGroup == null) {
427 newGroup = MessagingGroup.createGroup(mMessagingLinearLayout);
428 mAddedGroups.add(newGroup);
429 } else if (newGroup.getParent() != mMessagingLinearLayout) {
430 throw new IllegalStateException(
431 "group parent was " + newGroup.getParent() + " but expected "
432 + mMessagingLinearLayout);
433 }
434 newGroup.setImageDisplayLocation(mIsCollapsed
435 ? IMAGE_DISPLAY_LOCATION_EXTERNAL
436 : IMAGE_DISPLAY_LOCATION_INLINE);
437 newGroup.setIsInConversation(false);
438 newGroup.setLayoutColor(mLayoutColor);
439 newGroup.setTextColors(mSenderTextColor, mMessageTextColor);
440 Person sender = senders.get(groupIndex);
441 CharSequence nameOverride = null;
442 if (sender != mUser && mNameReplacement != null) {
443 nameOverride = mNameReplacement;
444 }
445 newGroup.setSingleLine(mIsCollapsed);
446 newGroup.setShowingAvatar(!mIsCollapsed);
447 newGroup.setSender(sender, nameOverride);
448 newGroup.setSending(groupIndex == (groups.size() - 1) && showSpinner);
449 mGroups.add(newGroup);
450
451 if (mMessagingLinearLayout.indexOfChild(newGroup) != groupIndex) {
452 mMessagingLinearLayout.removeView(newGroup);
453 mMessagingLinearLayout.addView(newGroup, groupIndex);
454 }
455 newGroup.setMessages(group);
456 }
457 }
458
459 private void findGroups(List<MessagingMessage> historicMessages,
460 List<MessagingMessage> messages, List<List<MessagingMessage>> groups,
461 List<Person> senders) {
462 CharSequence currentSenderKey = null;
463 List<MessagingMessage> currentGroup = null;
464 int histSize = historicMessages.size();
465 for (int i = 0; i < histSize + messages.size(); i++) {
466 MessagingMessage message;
467 if (i < histSize) {
468 message = historicMessages.get(i);
469 } else {
470 message = messages.get(i - histSize);
471 }
472 boolean isNewGroup = currentGroup == null;
473 Person sender =
474 message.getMessage() == null ? null : message.getMessage().getSenderPerson();
475 CharSequence key = sender == null ? null
476 : sender.getKey() == null ? sender.getName() : sender.getKey();
477 isNewGroup |= !TextUtils.equals(key, currentSenderKey);
478 if (isNewGroup) {
479 currentGroup = new ArrayList<>();
480 groups.add(currentGroup);
481 if (sender == null) {
482 sender = mUser;
483 }
484 senders.add(sender);
485 currentSenderKey = key;
486 }
487 currentGroup.add(message);
488 }
489 }
490
491 /**
492 * Creates new messages, reusing existing ones if they are available.
493 *
494 * @param newMessages the messages to parse.
495 */
496 private List<MessagingMessage> createMessages(
497 List<Notification.MessagingStyle.Message> newMessages, boolean historic) {
498 List<MessagingMessage> result = new ArrayList<>();
499 for (int i = 0; i < newMessages.size(); i++) {
500 Notification.MessagingStyle.Message m = newMessages.get(i);
501 MessagingMessage message = findAndRemoveMatchingMessage(m);
502 if (message == null) {
503 message = MessagingMessage.createMessage(this, m, mImageResolver);
504 }
505 message.setIsHistoric(historic);
506 result.add(message);
507 }
508 return result;
509 }
510
511 private MessagingMessage findAndRemoveMatchingMessage(Notification.MessagingStyle.Message m) {
512 for (int i = 0; i < mMessages.size(); i++) {
513 MessagingMessage existing = mMessages.get(i);
514 if (existing.sameAs(m)) {
515 mMessages.remove(i);
516 return existing;
517 }
518 }
519 for (int i = 0; i < mHistoricMessages.size(); i++) {
520 MessagingMessage existing = mHistoricMessages.get(i);
521 if (existing.sameAs(m)) {
522 mHistoricMessages.remove(i);
523 return existing;
524 }
525 }
526 return null;
527 }
528
529 public void showHistoricMessages(boolean show) {
530 mShowHistoricMessages = show;
531 updateHistoricMessageVisibility();
532 }
533
534 private void updateHistoricMessageVisibility() {
535 int numHistoric = mHistoricMessages.size();
536 for (int i = 0; i < numHistoric; i++) {
537 MessagingMessage existing = mHistoricMessages.get(i);
538 existing.setVisibility(mShowHistoricMessages ? VISIBLE : GONE);
539 }
540 int numGroups = mGroups.size();
541 for (int i = 0; i < numGroups; i++) {
542 MessagingGroup group = mGroups.get(i);
543 int visibleChildren = 0;
544 List<MessagingMessage> messages = group.getMessages();
545 int numGroupMessages = messages.size();
546 for (int j = 0; j < numGroupMessages; j++) {
547 MessagingMessage message = messages.get(j);
548 if (message.getVisibility() != GONE) {
549 visibleChildren++;
550 }
551 }
552 if (visibleChildren > 0 && group.getVisibility() == GONE) {
553 group.setVisibility(VISIBLE);
554 } else if (visibleChildren == 0 && group.getVisibility() != GONE) {
555 group.setVisibility(GONE);
556 }
557 }
558 }
559
560 @Override
561 protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
562 super.onLayout(changed, left, top, right, bottom);
563 if (!mAddedGroups.isEmpty()) {
564 getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
565 @Override
566 public boolean onPreDraw() {
567 for (MessagingGroup group : mAddedGroups) {
568 if (!group.isShown()) {
569 continue;
570 }
571 MessagingPropertyAnimator.fadeIn(group.getAvatar());
572 MessagingPropertyAnimator.fadeIn(group.getSenderView());
573 MessagingPropertyAnimator.startLocalTranslationFrom(group,
574 group.getHeight(), LINEAR_OUT_SLOW_IN);
575 }
576 mAddedGroups.clear();
577 getViewTreeObserver().removeOnPreDrawListener(this);
578 return true;
579 }
580 });
581 }
582 }
583
584 public MessagingLinearLayout getMessagingLinearLayout() {
585 return mMessagingLinearLayout;
586 }
587
588 @Nullable
589 public ViewGroup getImageMessageContainer() {
590 return mImageMessageContainer;
591 }
592
593 public ArrayList<MessagingGroup> getMessagingGroups() {
594 return mGroups;
595 }
596
597 @Override
598 public void setMessagingClippingDisabled(boolean clippingDisabled) {
599 mMessagingLinearLayout.setClipBounds(clippingDisabled ? null : mMessagingClipRect);
600 }
601 }