summaryrefslogtreecommitdiffstats
path: root/src/com/android/mail/ui/DividedImageCanvas.java
blob: 2880ea4d34c544d54aa29898ecf8927c4c096c06 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.mail.ui;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;

import com.android.mail.R;
import com.android.mail.utils.Utils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * DividedImageCanvas creates a canvas that can display into a minimum of 1
 * and maximum of 4 images. As images are added, they
 * are laid out according to the following algorithm:
 * 1 Image: Draw the bitmap filling the entire canvas.
 * 2 Images: Draw 2 bitmaps split vertically down the middle.
 * 3 Images: Draw 3 bitmaps: the first takes up all vertical space; the 2nd and 3rd are stacked in
 *           the second vertical position.
 * 4 Images: Divide the Canvas into 4 equal quadrants and draws 1 bitmap in each.
 */
public class DividedImageCanvas implements ImageCanvas {
    public static final int MAX_DIVISIONS = 4;

    private final Map<String, Integer> mDivisionMap = Maps
            .newHashMapWithExpectedSize(MAX_DIVISIONS);
    private Bitmap mDividedBitmap;
    private Canvas mCanvas;
    private int mWidth;
    private int mHeight;

    private final Context mContext;
    private final InvalidateCallback mCallback;
    private final ArrayList<Bitmap> mDivisionImages = new ArrayList<Bitmap>(MAX_DIVISIONS);

    /**
     * Ignore any request to draw final output when not yet ready. This prevents partially drawn
     * canvases from appearing.
     */
    private boolean mBitmapValid = false;

    private int mGeneration;

    private static final Paint sPaint = new Paint();
    private static final Paint sClearPaint = new Paint();
    private static final Rect sSrc = new Rect();
    private static final Rect sDest = new Rect();

    private static int sDividerLineWidth = -1;
    private static int sDividerColor;

    static {
        sClearPaint.setXfermode(new PorterDuffXfermode(Mode.CLEAR));
    }

    public DividedImageCanvas(Context context, InvalidateCallback callback) {
        mContext = context;
        mCallback = callback;
        setupDividerLines();
    }

    /**
     * Get application context for this object.
     */
    public Context getContext() {
        return mContext;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("{");
        sb.append(super.toString());
        sb.append(" mDivisionMap=");
        sb.append(mDivisionMap);
        sb.append(" mDivisionImages=");
        sb.append(mDivisionImages);
        sb.append(" mWidth=");
        sb.append(mWidth);
        sb.append(" mHeight=");
        sb.append(mHeight);
        sb.append("}");
        return sb.toString();
    }

    /**
     * Set the id associated with each quadrant. The quadrants are laid out:
     * TopLeft, TopRight, Bottom Left, Bottom Right
     * @param keys
     */
    public void setDivisionIds(List<Object> keys) {
        if (keys.size() > MAX_DIVISIONS) {
            throw new IllegalArgumentException("too many divisionIds: " + keys);
        }

        boolean needClear = getDivisionCount() != keys.size();
        if (!needClear) {
            for (int i = 0; i < keys.size(); i++) {
                String divisionId = transformKeyToDivisionId(keys.get(i));
                // different item or different place
                if (!mDivisionMap.containsKey(divisionId) || mDivisionMap.get(divisionId) != i) {
                    needClear = true;
                    break;
                }
            }
        }

        if (needClear) {
            mDivisionMap.clear();
            mDivisionImages.clear();
            int i = 0;
            for (Object key : keys) {
                String divisionId = transformKeyToDivisionId(key);
                mDivisionMap.put(divisionId, i);
                mDivisionImages.add(null);
                i++;
            }
        }
    }

    private void draw(Bitmap b, int left, int top, int right, int bottom) {
        if (b != null) {
            // Some times we load taller images compared to the destination rect on the canvas
            int srcTop = 0;
            int srcBottom = b.getHeight();
            int destHeight = bottom - top;
            if (b.getHeight() > bottom - top) {
                srcTop = b.getHeight() / 2 - destHeight/2;
                srcBottom = b.getHeight() / 2 + destHeight/2;
            }

//            todo:markwei do not scale very small bitmaps
            // l t r b
            sSrc.set(0, srcTop, b.getWidth(), srcBottom);
            sDest.set(left, top, right, bottom);
            mCanvas.drawRect(sDest, sClearPaint);
            mCanvas.drawBitmap(b, sSrc, sDest, sPaint);
        } else {
            // clear
            mCanvas.drawRect(left, top, right, bottom, sClearPaint);
        }
    }

    /**
     * Get the desired dimensions and scale for the bitmap to be placed in the
     * location corresponding to id. Caller must allocate the Dimensions object.
     * @param key
     * @param outDim a {@link ImageCanvas.Dimensions} object to write results into
     */
    @Override
    public void getDesiredDimensions(Object key, Dimensions outDim) {
        Utils.traceBeginSection("get desired dimensions");
        int w = 0, h = 0;
        float scale = 0;
        final Integer pos = mDivisionMap.get(transformKeyToDivisionId(key));
        if (pos != null && pos >= 0) {
            final int size = mDivisionMap.size();
            switch (size) {
                case 0:
                    break;
                case 1:
                    w = mWidth;
                    h = mHeight;
                    scale = Dimensions.SCALE_ONE;
                    break;
                case 2:
                    w = mWidth / 2;
                    h = mHeight;
                    scale = Dimensions.SCALE_HALF;
                    break;
                case 3:
                    switch (pos) {
                        case 0:
                            w = mWidth / 2;
                            h = mHeight;
                            scale = Dimensions.SCALE_HALF;
                            break;
                        default:
                            w = mWidth / 2;
                            h = mHeight / 2;
                            scale = Dimensions.SCALE_QUARTER;
                    }
                    break;
                case 4:
                    w = mWidth / 2;
                    h = mHeight / 2;
                    scale = Dimensions.SCALE_QUARTER;
                    break;
            }
        }
        outDim.width = w;
        outDim.height = h;
        outDim.scale = scale;
        Utils.traceEndSection();
    }

    @Override
    public void drawImage(Bitmap b, Object key) {
        addDivisionImage(b, key);
    }

    /**
     * Add a bitmap to this view in the quadrant matching its id.
     * @param b Bitmap
     * @param key Id to look for that was previously set in setDivisionIds.
     */
    public void addDivisionImage(Bitmap b, Object key) {
        if (b != null) {
            addOrClearDivisionImage(b, key);
        }
    }

    public void clearDivisionImage(Object key) {
        addOrClearDivisionImage(null, key);
    }
    private void addOrClearDivisionImage(Bitmap b, Object key) {
        Utils.traceBeginSection("add or clear division image");
        final Integer pos = mDivisionMap.get(transformKeyToDivisionId(key));
        if (pos != null && pos >= 0) {
            mDivisionImages.set(pos, b);
            boolean complete = false;
            final int width = mWidth;
            final int height = mHeight;
            // Different layouts depending on count.
            final int size = mDivisionMap.size();
            switch (size) {
                case 0:
                    // Do nothing.
                    break;
                case 1:
                    // Draw the bitmap filling the entire canvas.
                    draw(mDivisionImages.get(0), 0, 0, width, height);
                    complete = true;
                    break;
                case 2:
                    // Draw 2 bitmaps split vertically down the middle
                    switch (pos) {
                        case 0:
                            draw(mDivisionImages.get(0), 0, 0, width / 2, height);
                            break;
                        case 1:
                            draw(mDivisionImages.get(1), width / 2, 0, width, height);
                            break;
                    }
                    complete = mDivisionImages.get(0) != null && mDivisionImages.get(1) != null
                            || isPartialBitmapComplete();
                    if (complete) {
                        // Draw dividers
                        drawVerticalDivider(width, height);
                    }
                    break;
                case 3:
                    // Draw 3 bitmaps: the first takes up all vertical
                    // space, the 2nd and 3rd are stacked in the second vertical
                    // position.
                    switch (pos) {
                        case 0:
                            draw(mDivisionImages.get(0), 0, 0, width / 2, height);
                            break;
                        case 1:
                            draw(mDivisionImages.get(1), width / 2, 0, width, height / 2);
                            break;
                        case 2:
                            draw(mDivisionImages.get(2), width / 2, height / 2, width, height);
                            break;
                    }
                    complete = mDivisionImages.get(0) != null && mDivisionImages.get(1) != null
                            && mDivisionImages.get(2) != null || isPartialBitmapComplete();
                    if (complete) {
                        // Draw dividers
                        drawVerticalDivider(width, height);
                        drawHorizontalDivider(width / 2, height / 2, width, height / 2);
                    }
                    break;
                default:
                    // Draw all 4 bitmaps in a grid
                    switch (pos) {
                        case 0:
                            draw(mDivisionImages.get(0), 0, 0, width / 2, height / 2);
                            break;
                        case 1:
                            draw(mDivisionImages.get(1), width / 2, 0, width, height / 2);
                            break;
                        case 2:
                            draw(mDivisionImages.get(2), 0, height / 2, width / 2, height);
                            break;
                        case 3:
                            draw(mDivisionImages.get(3), width / 2, height / 2, width, height);
                            break;
                    }
                    complete = mDivisionImages.get(0) != null && mDivisionImages.get(1) != null
                            && mDivisionImages.get(2) != null && mDivisionImages.get(3) != null
                            || isPartialBitmapComplete();
                    if (complete) {
                        // Draw dividers
                        drawVerticalDivider(width, height);
                        drawHorizontalDivider(0, height / 2, width, height / 2);
                    }
                    break;
            }
            // Create the new image bitmap.
            if (complete) {
                mBitmapValid = true;
                mCallback.invalidate();
            }
        }
        Utils.traceEndSection();
    }

    public boolean hasImageFor(Object key) {
        final Integer pos = mDivisionMap.get(transformKeyToDivisionId(key));
        return pos != null && mDivisionImages.get(pos) != null;
    }

    private void setupDividerLines() {
        if (sDividerLineWidth == -1) {
            Resources res = getContext().getResources();
            sDividerLineWidth = res
                    .getDimensionPixelSize(R.dimen.tile_divider_width);
            sDividerColor = res.getColor(R.color.tile_divider_color);
        }
    }

    private static void setupPaint() {
        sPaint.setStrokeWidth(sDividerLineWidth);
        sPaint.setColor(sDividerColor);
    }

    protected void drawVerticalDivider(int width, int height) {
        int x1 = width / 2, y1 = 0, x2 = width/2, y2 = height;
        setupPaint();
        mCanvas.drawLine(x1, y1, x2, y2, sPaint);
    }

    protected void drawHorizontalDivider(int x1, int y1, int x2, int y2) {
        setupPaint();
        mCanvas.drawLine(x1, y1, x2, y2, sPaint);
    }

    protected boolean isPartialBitmapComplete() {
        return false;
    }

    protected String transformKeyToDivisionId(Object key) {
        return key.toString();
    }

    /**
     * Draw the contents of the DividedImageCanvas to the supplied canvas.
     */
    public void draw(Canvas canvas) {
        if (mDividedBitmap != null && mBitmapValid) {
            canvas.drawBitmap(mDividedBitmap, 0, 0, null);
        }
    }

    @Override
    public void reset() {
        if (mCanvas != null && mDividedBitmap != null) {
            mBitmapValid = false;
        }
        mDivisionMap.clear();
        mDivisionImages.clear();
        mGeneration++;
    }

    @Override
    public int getGeneration() {
        return mGeneration;
    }

    /**
     * Set the width and height of the canvas.
     * @param width
     * @param height
     */
    public void setDimensions(int width, int height) {
        Utils.traceBeginSection("set dimensions");
        if (mWidth == width && mHeight == height) {
            Utils.traceEndSection();
            return;
        }

        mWidth = width;
        mHeight = height;

        // todo:ath this bitmap is creating a GC which is killing CIV.loadAttachmentPreviews()
        mDividedBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        mCanvas = new Canvas(mDividedBitmap);
        mBitmapValid = true;
        Utils.traceEndSection();
    }

    /**
     * Get the resulting canvas width.
     */
    public int getWidth() {
        return mWidth;
    }

    /**
     * Get the resulting canvas height.
     */
    public int getHeight() {
        return mHeight;
    }

    /**
     * The class that will provided the canvas to which the DividedImageCanvas
     * should render its contents must implement this interface.
     */
    public interface InvalidateCallback {
        public void invalidate();
    }

    public int getDivisionCount() {
        return mDivisionMap.size();
    }

    /**
     * Get the division ids currently associated with this DivisionImageCanvas.
     */
    public ArrayList<String> getDivisionIds() {
        return Lists.newArrayList(mDivisionMap.keySet());
    }
}