1 /*
2  * Copyright (C) 2016 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 android.annotation.Nullable;
20 import android.content.Context;
21 import android.content.res.TypedArray;
22 import android.graphics.Canvas;
23 import android.util.AttributeSet;
24 import android.view.RemotableViewMethod;
25 import android.view.View;
26 import android.view.ViewGroup;
27 import android.view.ViewParent;
28 import android.widget.RemoteViews;
29 
30 import com.android.internal.R;
31 
32 /**
33  * A custom-built layout for the Notification.MessagingStyle.
34  *
35  * Evicts children until they all fit.
36  */
37 @RemoteViews.RemoteView
38 public class MessagingLinearLayout extends ViewGroup {
39 
40     /**
41      * Spacing to be applied between views.
42      */
43     private int mSpacing;
44 
45     private int mMaxDisplayedLines = Integer.MAX_VALUE;
46 
MessagingLinearLayout(Context context, @Nullable AttributeSet attrs)47     public MessagingLinearLayout(Context context, @Nullable AttributeSet attrs) {
48         super(context, attrs);
49 
50         final TypedArray a = context.obtainStyledAttributes(attrs,
51                 R.styleable.MessagingLinearLayout, 0,
52                 0);
53 
54         final int N = a.getIndexCount();
55         for (int i = 0; i < N; i++) {
56             int attr = a.getIndex(i);
57             switch (attr) {
58                 case R.styleable.MessagingLinearLayout_spacing:
59                     mSpacing = a.getDimensionPixelSize(i, 0);
60                     break;
61             }
62         }
63 
64         a.recycle();
65     }
66 
67     @Override
onMeasure(int widthMeasureSpec, int heightMeasureSpec)68     protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
69         // This is essentially a bottom-up linear layout that only adds children that fit entirely
70         // up to a maximum height.
71         int targetHeight = MeasureSpec.getSize(heightMeasureSpec);
72         switch (MeasureSpec.getMode(heightMeasureSpec)) {
73             case MeasureSpec.UNSPECIFIED:
74                 targetHeight = Integer.MAX_VALUE;
75                 break;
76         }
77 
78         // Now that we know which views to take, fix up the indents and see what width we get.
79         int measuredWidth = mPaddingLeft + mPaddingRight;
80         final int count = getChildCount();
81         int totalHeight;
82         for (int i = 0; i < count; ++i) {
83             final View child = getChildAt(i);
84             final LayoutParams lp = (LayoutParams) child.getLayoutParams();
85             lp.hide = true;
86             if (child instanceof MessagingChild) {
87                 MessagingChild messagingChild = (MessagingChild) child;
88                 // Whenever we encounter the message first, it's always first in the layout
89                 messagingChild.setIsFirstInLayout(true);
90             }
91         }
92 
93         totalHeight = mPaddingTop + mPaddingBottom;
94         boolean first = true;
95         int linesRemaining = mMaxDisplayedLines;
96         // Starting from the bottom: we measure every view as if it were the only one. If it still
97         // fits, we take it, otherwise we stop there.
98         MessagingChild previousChild = null;
99         View previousView = null;
100         int previousChildHeight = 0;
101         int previousTotalHeight = 0;
102         int previousLinesConsumed = 0;
103         for (int i = count - 1; i >= 0 && totalHeight < targetHeight; i--) {
104             if (getChildAt(i).getVisibility() == GONE) {
105                 continue;
106             }
107             final View child = getChildAt(i);
108             LayoutParams lp = (LayoutParams) getChildAt(i).getLayoutParams();
109             MessagingChild messagingChild = null;
110             int spacing = mSpacing;
111             int previousChildIncrease = 0;
112             if (child instanceof MessagingChild) {
113                 // We need to remeasure the previous child again if it's not the first anymore
114                 if (previousChild != null && previousChild.hasDifferentHeightWhenFirst()) {
115                     previousChild.setIsFirstInLayout(false);
116                     measureChildWithMargins(previousView, widthMeasureSpec, 0, heightMeasureSpec,
117                             previousTotalHeight - previousChildHeight);
118                     previousChildIncrease = previousView.getMeasuredHeight() - previousChildHeight;
119                     linesRemaining -= previousChild.getConsumedLines() - previousLinesConsumed;
120                 }
121                 messagingChild = (MessagingChild) child;
122                 messagingChild.setMaxDisplayedLines(linesRemaining);
123                 spacing += messagingChild.getExtraSpacing();
124             }
125             spacing = first ? 0 : spacing;
126             measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, totalHeight
127                     - mPaddingTop - mPaddingBottom + spacing);
128 
129             final int childHeight = child.getMeasuredHeight();
130             int newHeight = Math.max(totalHeight, totalHeight + childHeight + lp.topMargin +
131                     lp.bottomMargin + spacing + previousChildIncrease);
132             int measureType = MessagingChild.MEASURED_NORMAL;
133             if (messagingChild != null) {
134                 measureType = messagingChild.getMeasuredType();
135             }
136 
137             // We never measure the first item as too small, we want to at least show something.
138             boolean isTooSmall = measureType == MessagingChild.MEASURED_TOO_SMALL && !first;
139             boolean isShortened = measureType == MessagingChild.MEASURED_SHORTENED
140                     || measureType == MessagingChild.MEASURED_TOO_SMALL && first;
141             boolean showView = newHeight <= targetHeight && !isTooSmall;
142             if (showView) {
143                 if (messagingChild != null) {
144                     previousLinesConsumed = messagingChild.getConsumedLines();
145                     linesRemaining -= previousLinesConsumed;
146                     previousChild = messagingChild;
147                     previousView = child;
148                     previousChildHeight = childHeight;
149                     previousTotalHeight = totalHeight;
150                 }
151                 totalHeight = newHeight;
152                 measuredWidth = Math.max(measuredWidth,
153                         child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin
154                                 + mPaddingLeft + mPaddingRight);
155                 lp.hide = false;
156                 if (isShortened || linesRemaining <= 0) {
157                     break;
158                 }
159             } else {
160                 // We now became too short, let's make sure to reset any previous views to be first
161                 // and remeasure it.
162                 if (previousChild != null && previousChild.hasDifferentHeightWhenFirst()) {
163                     previousChild.setIsFirstInLayout(true);
164                     // We need to remeasure the previous child again since it became first
165                     measureChildWithMargins(previousView, widthMeasureSpec, 0, heightMeasureSpec,
166                             previousTotalHeight - previousChildHeight);
167                     // The totalHeight is already correct here since we only set it during the
168                     // first pass
169                 }
170                 break;
171             }
172             first = false;
173         }
174 
175         setMeasuredDimension(
176                 resolveSize(Math.max(getSuggestedMinimumWidth(), measuredWidth),
177                         widthMeasureSpec),
178                 Math.max(getSuggestedMinimumHeight(), totalHeight));
179     }
180 
181     @Override
onLayout(boolean changed, int left, int top, int right, int bottom)182     protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
183         final int paddingLeft = mPaddingLeft;
184 
185         int childTop;
186 
187         // Where right end of child should go
188         final int width = right - left;
189         final int childRight = width - mPaddingRight;
190 
191         final int layoutDirection = getLayoutDirection();
192         final int count = getChildCount();
193 
194         childTop = mPaddingTop;
195 
196         boolean first = true;
197         final boolean shown = isShown();
198         for (int i = 0; i < count; i++) {
199             final View child = getChildAt(i);
200             if (child.getVisibility() == GONE) {
201                 continue;
202             }
203             final LayoutParams lp = (LayoutParams) child.getLayoutParams();
204             MessagingChild messagingChild = (MessagingChild) child;
205 
206             final int childWidth = child.getMeasuredWidth();
207             final int childHeight = child.getMeasuredHeight();
208 
209             int childLeft;
210             if (layoutDirection == LAYOUT_DIRECTION_RTL) {
211                 childLeft = childRight - childWidth - lp.rightMargin;
212             } else {
213                 childLeft = paddingLeft + lp.leftMargin;
214             }
215             if (lp.hide) {
216                 if (shown && lp.visibleBefore) {
217                     // We still want to lay out the child to have great animations
218                     child.layout(childLeft, childTop, childLeft + childWidth,
219                             childTop + lp.lastVisibleHeight);
220                     messagingChild.hideAnimated();
221                 }
222                 lp.visibleBefore = false;
223                 continue;
224             } else {
225                 lp.visibleBefore = true;
226                 lp.lastVisibleHeight = childHeight;
227             }
228 
229             if (!first) {
230                 childTop += mSpacing;
231             }
232 
233             childTop += lp.topMargin;
234             child.layout(childLeft, childTop, childLeft + childWidth, childTop + childHeight);
235 
236             childTop += childHeight + lp.bottomMargin;
237 
238             first = false;
239         }
240     }
241 
242     @Override
drawChild(Canvas canvas, View child, long drawingTime)243     protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
244         final LayoutParams lp = (LayoutParams) child.getLayoutParams();
245         if (lp.hide) {
246             MessagingChild messagingChild = (MessagingChild) child;
247             if (!messagingChild.isHidingAnimated()) {
248                 return true;
249             }
250         }
251         return super.drawChild(canvas, child, drawingTime);
252     }
253 
254     @Override
generateLayoutParams(AttributeSet attrs)255     public LayoutParams generateLayoutParams(AttributeSet attrs) {
256         return new LayoutParams(mContext, attrs);
257     }
258 
259     @Override
generateDefaultLayoutParams()260     protected LayoutParams generateDefaultLayoutParams() {
261         return new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
262 
263     }
264 
265     @Override
generateLayoutParams(ViewGroup.LayoutParams lp)266     protected LayoutParams generateLayoutParams(ViewGroup.LayoutParams lp) {
267         LayoutParams copy = new LayoutParams(lp.width, lp.height);
268         if (lp instanceof MarginLayoutParams) {
269             copy.copyMarginsFrom((MarginLayoutParams) lp);
270         }
271         return copy;
272     }
273 
isGone(View view)274     public static boolean isGone(View view) {
275         if (view.getVisibility() == View.GONE) {
276             return true;
277         }
278         final ViewGroup.LayoutParams lp = view.getLayoutParams();
279         if (lp instanceof MessagingLinearLayout.LayoutParams
280                 && ((MessagingLinearLayout.LayoutParams) lp).hide) {
281             return true;
282         }
283         return false;
284     }
285 
286     /**
287      * Sets how many lines should be displayed at most
288      */
289     @RemotableViewMethod
setMaxDisplayedLines(int numberLines)290     public void setMaxDisplayedLines(int numberLines) {
291         mMaxDisplayedLines = numberLines;
292     }
293 
getMessagingLayout()294     public IMessagingLayout getMessagingLayout() {
295         View view = this;
296         while (true) {
297             ViewParent p = view.getParent();
298             if (p instanceof View) {
299                 view = (View) p;
300                 if (view instanceof IMessagingLayout) {
301                     return (IMessagingLayout) view;
302                 }
303             } else {
304                 return null;
305             }
306         }
307     }
308 
309     @Override
getBaseline()310     public int getBaseline() {
311         // When placed in a horizontal linear layout (as is the case in a single-line MessageGroup),
312         // align with the last visible child (which is the one that will be displayed in the single-
313         // line group.
314         int childCount = getChildCount();
315         for (int i = childCount - 1; i >= 0; i--) {
316             final View child = getChildAt(i);
317             if (isGone(child)) {
318                 continue;
319             }
320             final int childBaseline = child.getBaseline();
321             if (childBaseline == -1) {
322                 return -1;
323             }
324             MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
325             return lp.topMargin + childBaseline;
326         }
327         return super.getBaseline();
328     }
329 
330     public interface MessagingChild {
331         int MEASURED_NORMAL = 0;
332         int MEASURED_SHORTENED = 1;
333         int MEASURED_TOO_SMALL = 2;
334 
getMeasuredType()335         int getMeasuredType();
getConsumedLines()336         int getConsumedLines();
setMaxDisplayedLines(int lines)337         void setMaxDisplayedLines(int lines);
hideAnimated()338         void hideAnimated();
isHidingAnimated()339         boolean isHidingAnimated();
340 
341         /**
342          * Set that this view is first in layout. Relevant and only set if
343          * {@link #hasDifferentHeightWhenFirst()}.
344          * @param first is this first?
345          */
setIsFirstInLayout(boolean first)346         default void setIsFirstInLayout(boolean first) {}
347 
348         /**
349          * @return if this layout has different height it is first in the layout
350          */
hasDifferentHeightWhenFirst()351         default boolean hasDifferentHeightWhenFirst() {
352             return false;
353         }
getExtraSpacing()354         default int getExtraSpacing() {
355             return 0;
356         }
357     }
358 
359     public static class LayoutParams extends MarginLayoutParams {
360 
361         public boolean hide = false;
362         public boolean visibleBefore = false;
363         public int lastVisibleHeight;
364 
LayoutParams(Context c, AttributeSet attrs)365         public LayoutParams(Context c, AttributeSet attrs) {
366             super(c, attrs);
367         }
368 
LayoutParams(int width, int height)369         public LayoutParams(int width, int height) {
370             super(width, height);
371         }
372     }
373 }
374