summaryrefslogtreecommitdiffstats
path: root/src/com/android/contacts/common/ContactPhotoManager.java
blob: c260eea756a69593916f0bdd7ce363edbfa983d6 (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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
/*
 * Copyright (C) 2010 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.contacts.common;

import android.accounts.Account;
import android.app.ActivityManager;
import android.content.ComponentCallbacks2;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.TransitionDrawable;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.net.Uri.Builder;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.HandlerThread;
import android.os.Message;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Contacts.Photo;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.Directory;
import android.support.v4.graphics.drawable.RoundedBitmapDrawable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
import android.text.TextUtils;
import android.util.Log;
import android.util.LruCache;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.android.contacts.common.lettertiles.LetterTileDrawable;
import com.android.contacts.common.util.BitmapUtil;
import com.android.contacts.common.util.UriUtils;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.lang.ref.Reference;
import java.lang.ref.SoftReference;
import java.net.URL;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Asynchronously loads contact photos and maintains a cache of photos.
 */
public abstract class ContactPhotoManager implements ComponentCallbacks2 {
    static final String TAG = "ContactPhotoManager";
    static final boolean DEBUG = false; // Don't submit with true
    static final boolean DEBUG_SIZES = false; // Don't submit with true

    /** Contact type constants used for default letter images */
    public static final int TYPE_PERSON = LetterTileDrawable.TYPE_PERSON;
    public static final int TYPE_BUSINESS = LetterTileDrawable.TYPE_BUSINESS;
    public static final int TYPE_VOICEMAIL = LetterTileDrawable.TYPE_VOICEMAIL;
    public static final int TYPE_DEFAULT = LetterTileDrawable.TYPE_DEFAULT;

    /** Scale and offset default constants used for default letter images */
    public static final float SCALE_DEFAULT = 1.0f;
    public static final float OFFSET_DEFAULT = 0.0f;

    public static final boolean IS_CIRCULAR_DEFAULT = false;

    /** Uri-related constants used for default letter images */
    private static final String DISPLAY_NAME_PARAM_KEY = "display_name";
    private static final String IDENTIFIER_PARAM_KEY = "identifier";
    private static final String CONTACT_TYPE_PARAM_KEY = "contact_type";
    private static final String SCALE_PARAM_KEY = "scale";
    private static final String OFFSET_PARAM_KEY = "offset";
    private static final String IS_CIRCULAR_PARAM_KEY = "is_circular";
    private static final String DEFAULT_IMAGE_URI_SCHEME = "defaultimage";
    private static final Uri DEFAULT_IMAGE_URI = Uri.parse(DEFAULT_IMAGE_URI_SCHEME + "://");

    public static final String CONTACT_PHOTO_SERVICE = "contactPhotos";

    // Static field used to cache the default letter avatar drawable that is created
    // using a null {@link DefaultImageRequest}
    private static Drawable sDefaultLetterAvatar = null;

    /**
     * Given a {@link DefaultImageRequest}, returns a {@link Drawable}, that when drawn, will
     * draw a letter tile avatar based on the request parameters defined in the
     * {@link DefaultImageRequest}.
     */
    public static Drawable getDefaultAvatarDrawableForContact(Context context, boolean hires,
            DefaultImageRequest defaultImageRequest) {
        return getDefaultAvatarDrawableForContact(context, hires, defaultImageRequest, null);
    }

    public static Drawable getDefaultAvatarDrawableForContact(Context context, boolean hires,
            DefaultImageRequest defaultImageRequest, Account account) {
        if (defaultImageRequest == null) {
            if (sDefaultLetterAvatar == null) {
                // Cache and return the letter tile drawable that is created by a null request,
                // so that it doesn't have to be recreated every time it is requested again.
                sDefaultLetterAvatar = LetterTileDefaultImageProvider.getDefaultImageForContact(
                        context, null, account);
            }
            return sDefaultLetterAvatar;
        }
        return LetterTileDefaultImageProvider.getDefaultImageForContact(context,
                defaultImageRequest, account);
    }

    /**
     * Given a {@link DefaultImageRequest}, returns an Uri that can be used to request a
     * letter tile avatar when passed to the {@link ContactPhotoManager}. The internal
     * implementation of this uri is not guaranteed to remain the same across application
     * versions, so the actual uri should never be persisted in long-term storage and reused.
     *
     * @param request A {@link DefaultImageRequest} object with the fields configured
     * to return a
     * @return A Uri that when later passed to the {@link ContactPhotoManager} via
     * {@link #loadPhoto(ImageView, Uri, int, boolean, DefaultImageRequest)}, can be
     * used to request a default contact image, drawn as a letter tile using the
     * parameters as configured in the provided {@link DefaultImageRequest}
     */
    public static Uri getDefaultAvatarUriForContact(DefaultImageRequest request) {
        final Builder builder = DEFAULT_IMAGE_URI.buildUpon();
        if (request != null) {
            if (!TextUtils.isEmpty(request.displayName)) {
                builder.appendQueryParameter(DISPLAY_NAME_PARAM_KEY, request.displayName);
            }
            if (!TextUtils.isEmpty(request.identifier)) {
                builder.appendQueryParameter(IDENTIFIER_PARAM_KEY, request.identifier);
            }
            if (request.contactType != TYPE_DEFAULT) {
                builder.appendQueryParameter(CONTACT_TYPE_PARAM_KEY,
                        String.valueOf(request.contactType));
            }
            if (request.scale != SCALE_DEFAULT) {
                builder.appendQueryParameter(SCALE_PARAM_KEY, String.valueOf(request.scale));
            }
            if (request.offset != OFFSET_DEFAULT) {
                builder.appendQueryParameter(OFFSET_PARAM_KEY, String.valueOf(request.offset));
            }
            if (request.isCircular != IS_CIRCULAR_DEFAULT) {
                builder.appendQueryParameter(IS_CIRCULAR_PARAM_KEY,
                        String.valueOf(request.isCircular));
            }

        }
        return builder.build();
    }

    /**
     * Adds a business contact type encoded fragment to the URL.  Used to ensure photo URLS
     * from Nearby Places can be identified as business photo URLs rather than URLs for personal
     * contact photos.
     *
     * @param photoUrl The photo URL to modify.
     * @return URL with the contact type parameter added and set to TYPE_BUSINESS.
     */
    public static String appendBusinessContactType(String photoUrl) {
        Uri uri = Uri.parse(photoUrl);
        Builder builder = uri.buildUpon();
        builder.encodedFragment(String.valueOf(TYPE_BUSINESS));
        return builder.build().toString();
    }

    /**
     * Removes the contact type information stored in the photo URI encoded fragment.
     *
     * @param photoUri The photo URI to remove the contact type from.
     * @return The photo URI with contact type removed.
     */
    public static Uri removeContactType(Uri photoUri) {
        String encodedFragment = photoUri.getEncodedFragment();
        if (!TextUtils.isEmpty(encodedFragment)) {
            Builder builder = photoUri.buildUpon();
            builder.encodedFragment(null);
            return builder.build();
        }
        return photoUri;
    }

    /**
     * Inspects a photo URI to determine if the photo URI represents a business.
     *
     * @param photoUri The URI to inspect.
     * @return Whether the URI represents a business photo or not.
     */
    public static boolean isBusinessContactUri(Uri photoUri) {
        if (photoUri == null) {
            return false;
        }

        String encodedFragment = photoUri.getEncodedFragment();
        return !TextUtils.isEmpty(encodedFragment)
                && encodedFragment.equals(String.valueOf(TYPE_BUSINESS));
    }

    protected static DefaultImageRequest getDefaultImageRequestFromUri(Uri uri) {
        final DefaultImageRequest request = new DefaultImageRequest(
                uri.getQueryParameter(DISPLAY_NAME_PARAM_KEY),
                uri.getQueryParameter(IDENTIFIER_PARAM_KEY), false);
        try {
            String contactType = uri.getQueryParameter(CONTACT_TYPE_PARAM_KEY);
            if (!TextUtils.isEmpty(contactType)) {
                request.contactType = Integer.valueOf(contactType);
            }

            String scale = uri.getQueryParameter(SCALE_PARAM_KEY);
            if (!TextUtils.isEmpty(scale)) {
                request.scale = Float.valueOf(scale);
            }

            String offset = uri.getQueryParameter(OFFSET_PARAM_KEY);
            if (!TextUtils.isEmpty(offset)) {
                request.offset = Float.valueOf(offset);
            }

            String isCircular = uri.getQueryParameter(IS_CIRCULAR_PARAM_KEY);
            if (!TextUtils.isEmpty(isCircular)) {
                request.isCircular = Boolean.valueOf(isCircular);
            }
        } catch (NumberFormatException e) {
            Log.w(TAG, "Invalid DefaultImageRequest image parameters provided, ignoring and using "
                    + "defaults.");
        }

        return request;
    }

    protected boolean isDefaultImageUri(Uri uri) {
        return DEFAULT_IMAGE_URI_SCHEME.equals(uri.getScheme());
    }

    /**
     * Contains fields used to contain contact details and other user-defined settings that might
     * be used by the ContactPhotoManager to generate a default contact image. This contact image
     * takes the form of a letter or bitmap drawn on top of a colored tile.
     */
    public static class DefaultImageRequest {
        /**
         * The contact's display name. The display name is used to
         */
        public String displayName;

        /**
         * A unique and deterministic string that can be used to identify this contact. This is
         * usually the contact's lookup key, but other contact details can be used as well,
         * especially for non-local or temporary contacts that might not have a lookup key. This
         * is used to determine the color of the tile.
         */
        public String identifier;

        /**
         * The type of this contact. This contact type may be used to decide the kind of
         * image to use in the case where a unique letter cannot be generated from the contact's
         * display name and identifier. See:
         * {@link #TYPE_PERSON}
         * {@link #TYPE_BUSINESS}
         * {@link #TYPE_PERSON}
         * {@link #TYPE_DEFAULT}
         */
        public int contactType = TYPE_DEFAULT;

        /**
         * The amount to scale the letter or bitmap to, as a ratio of its default size (from a
         * range of 0.0f to 2.0f). The default value is 1.0f.
         */
        public float scale = SCALE_DEFAULT;

        /**
         * The amount to vertically offset the letter or image to within the tile.
         * The provided offset must be within the range of -0.5f to 0.5f.
         * If set to -0.5f, the letter will be shifted upwards by 0.5 times the height of the canvas
         * it is being drawn on, which means it will be drawn with the center of the letter starting
         * at the top edge of the canvas.
         * If set to 0.5f, the letter will be shifted downwards by 0.5 times the height of the
         * canvas it is being drawn on, which means it will be drawn with the center of the letter
         * starting at the bottom edge of the canvas.
         * The default is 0.0f, which means the letter is drawn in the exact vertical center of
         * the tile.
         */
        public float offset = OFFSET_DEFAULT;

        /**
         * Whether or not to draw the default image as a circle, instead of as a square/rectangle.
         */
        public boolean isCircular = false;

        /**
         * Used to indicate that a drawable that represents a contact without any contact details
         * should be returned.
         */
        public static DefaultImageRequest EMPTY_DEFAULT_IMAGE_REQUEST = new DefaultImageRequest();

        /**
         * Used to indicate that a drawable that represents a business without a business photo
         * should be returned.
         */
        public static DefaultImageRequest EMPTY_DEFAULT_BUSINESS_IMAGE_REQUEST =
                new DefaultImageRequest(null, null, TYPE_BUSINESS, false);

        /**
         * Used to indicate that a circular drawable that represents a contact without any contact
         * details should be returned.
         */
        public static DefaultImageRequest EMPTY_CIRCULAR_DEFAULT_IMAGE_REQUEST =
                new DefaultImageRequest(null, null, true);

        /**
         * Used to indicate that a circular drawable that represents a business without a business
         * photo should be returned.
         */
        public static DefaultImageRequest EMPTY_CIRCULAR_BUSINESS_IMAGE_REQUEST =
                new DefaultImageRequest(null, null, TYPE_BUSINESS, true);

        public DefaultImageRequest() {
        }

        public DefaultImageRequest(String displayName, String identifier, boolean isCircular) {
            this(displayName, identifier, TYPE_DEFAULT, SCALE_DEFAULT, OFFSET_DEFAULT, isCircular);
        }

        public DefaultImageRequest(String displayName, String identifier, int contactType,
                boolean isCircular) {
            this(displayName, identifier, contactType, SCALE_DEFAULT, OFFSET_DEFAULT, isCircular);
        }

        public DefaultImageRequest(String displayName, String identifier, int contactType,
                float scale, float offset, boolean isCircular) {
            this.displayName = displayName;
            this.identifier = identifier;
            this.contactType = contactType;
            this.scale = scale;
            this.offset = offset;
            this.isCircular = isCircular;
        }
    }

    public static abstract class DefaultImageProvider {
        /**
         * Applies the default avatar to the ImageView. Extent is an indicator for the size (width
         * or height). If darkTheme is set, the avatar is one that looks better on dark background
         *
         * @param defaultImageRequest {@link DefaultImageRequest} object that specifies how a
         * default letter tile avatar should be drawn.
         */
        public abstract void applyDefaultImage(ImageView view, Account account,
                int extent, boolean darkTheme, DefaultImageRequest defaultImageRequest);
    }

    /**
     * A default image provider that applies a letter tile consisting of a colored background
     * and a letter in the foreground as the default image for a contact. The color of the
     * background and the type of letter is decided based on the contact's details.
     */
    private static class LetterTileDefaultImageProvider extends DefaultImageProvider {
        @Override
        public void applyDefaultImage(ImageView view, Account account, int extent,
                boolean darkTheme, DefaultImageRequest defaultImageRequest) {
            final Drawable drawable = getDefaultImageForContact(view.getContext(),
                    defaultImageRequest, account);
            view.setImageDrawable(drawable);
        }

        public static Drawable getDefaultImageForContact(Context context,
                DefaultImageRequest defaultImageRequest, Account account) {
            final LetterTileDrawable drawable = new LetterTileDrawable(
                    context, account);
            if (defaultImageRequest != null) {
                // If the contact identifier is null or empty, fallback to the
                // displayName. In that case, use {@code null} for the contact's
                // display name so that a default bitmap will be used instead of a
                // letter
                if (TextUtils.isEmpty(defaultImageRequest.identifier)) {
                    drawable.setContactDetails(null, defaultImageRequest.displayName);
                } else {
                    drawable.setContactDetails(defaultImageRequest.displayName,
                            defaultImageRequest.identifier);
                }
                drawable.setContactType(defaultImageRequest.contactType);
                drawable.setScale(defaultImageRequest.scale);
                drawable.setOffset(defaultImageRequest.offset);
                drawable.setIsCircular(defaultImageRequest.isCircular);
            }
            return drawable;
        }
    }

    private static class BlankDefaultImageProvider extends DefaultImageProvider {
        private static Drawable sDrawable;

        @Override
        public void applyDefaultImage(ImageView view, Account account, int extent,
                boolean darkTheme, DefaultImageRequest defaultImageRequest) {
            if (sDrawable == null) {
                Context context = view.getContext();
                sDrawable = new ColorDrawable(context.getResources().getColor(
                        R.color.image_placeholder));
            }
            view.setImageDrawable(sDrawable);
        }
    }

    public static DefaultImageProvider DEFAULT_AVATAR = new LetterTileDefaultImageProvider();

    public static final DefaultImageProvider DEFAULT_BLANK = new BlankDefaultImageProvider();

    public static ContactPhotoManager getInstance(Context context) {
        Context applicationContext = context.getApplicationContext();
        ContactPhotoManager service =
                (ContactPhotoManager) applicationContext.getSystemService(CONTACT_PHOTO_SERVICE);
        if (service == null) {
            service = createContactPhotoManager(applicationContext);
            Log.e(TAG, "No contact photo service in context: " + applicationContext);
        }
        return service;
    }

    public static synchronized ContactPhotoManager createContactPhotoManager(Context context) {
        return new ContactPhotoManagerImpl(context);
    }

    public abstract void clear();

    /**
     * Load thumbnail image into the supplied image view. If the photo is already cached,
     * it is displayed immediately.  Otherwise a request is sent to load the photo
     * from the database.
     */
    public abstract void loadThumbnail(ImageView view, long photoId, Account account,
            boolean darkTheme, boolean isCircular, DefaultImageRequest defaultImageRequest,
            DefaultImageProvider defaultProvider);

    /**
     * Calls {@link #loadThumbnail(ImageView, long, boolean, DefaultImageRequest,
     * DefaultImageProvider)} using the {@link DefaultImageProvider} {@link #DEFAULT_AVATAR}.
    */
    public final void loadThumbnail(ImageView view, long photoId, boolean darkTheme,
             boolean isCircular, DefaultImageRequest defaultImageRequest) {
        loadThumbnail(view, photoId, null, darkTheme, isCircular,
                defaultImageRequest, DEFAULT_AVATAR);
    }

    public final void loadThumbnail(ImageView view, long photoId, Account account,
        boolean darkTheme, boolean isCircular, DefaultImageRequest defaultImageRequest) {
        loadThumbnail(view, photoId, account, darkTheme, isCircular,
                defaultImageRequest, DEFAULT_AVATAR);
    }

    public final void loadThumbnail(ImageView view, long photoId, boolean darkTheme,
        boolean isCircular, DefaultImageRequest defaultImageRequest,
        DefaultImageProvider defaultProvider) {
        loadThumbnail(view, photoId, null, darkTheme, isCircular,
                defaultImageRequest, defaultProvider);
    }

    /**
     * Load photo into the supplied image view. If the photo is already cached,
     * it is displayed immediately. Otherwise a request is sent to load the photo
     * from the location specified by the URI.
     *
     * @param view The target view
     * @param photoUri The uri of the photo to load
     * @param requestedExtent Specifies an approximate Max(width, height) of the targetView.
     * This is useful if the source image can be a lot bigger that the target, so that the decoding
     * is done using efficient sampling. If requestedExtent is specified, no sampling of the image
     * is performed
     * @param darkTheme Whether the background is dark. This is used for default avatars
     * @param defaultImageRequest {@link DefaultImageRequest} object that specifies how a default
     * letter tile avatar should be drawn.
     * @param defaultProvider The provider of default avatars (this is used if photoUri doesn't
     * refer to an existing image)
     */
    public abstract void loadPhoto(ImageView view, Uri photoUri,
            Account account, int requestedExtent, boolean darkTheme,
            boolean isCircular, DefaultImageRequest defaultImageRequest,
            DefaultImageProvider defaultProvider);

    /**
     * Calls {@link #loadPhoto(ImageView, Uri, int, boolean, DefaultImageRequest,
     * DefaultImageProvider)} with {@link #DEFAULT_AVATAR} and {@code null} display names and
     * lookup keys.
     *
     * @param defaultImageRequest {@link DefaultImageRequest} object that specifies how a default
     * letter tile avatar should be drawn.
     */

    public final void loadPhoto(ImageView view, Uri photoUri, int requestedExtent,
            boolean darkTheme, boolean isCircular, DefaultImageRequest defaultImageRequest) {
        loadPhoto(view, photoUri, null, requestedExtent, darkTheme, isCircular,
                defaultImageRequest, DEFAULT_AVATAR);
    }

    public final void loadPhoto(ImageView view, Uri photoUri, Account account, int requestedExtent,
            boolean darkTheme, boolean isCircular, DefaultImageRequest defaultImageRequest) {
        loadPhoto(view, photoUri, account, requestedExtent, darkTheme, isCircular,
                defaultImageRequest, DEFAULT_AVATAR);
    }

    public final void loadPhoto(ImageView view, Uri photoUri, int requestedExtent,
        boolean darkTheme, boolean isCircular, DefaultImageRequest defaultImageRequest,
        DefaultImageProvider defaultProvider) {
        loadPhoto(view, photoUri, null, requestedExtent, darkTheme, isCircular,
                defaultImageRequest, defaultProvider);
    }

    /**
     * Used to request bitmap of a Contact photo
     *
     * @param photoUri Uri of the contact's photo
     * @param imgView Sentinel used to triage this request through the existing contact bitmap
     *                loading pipeline. The contact Bitmap won't be loaded into this imageview.
     * @param widthHint suggest bitmap dimensions
     * @param cb Callback via which a contact's bitmap is made available to the requester
     */
    public abstract void getBitmapForContact(Uri photoUri, ImageView imgView, int widthHint,
            PhotoFetcherCallback cb);

    /**
     * Calls {@link #loadPhoto(ImageView, Uri, boolean, boolean, DefaultImageRequest,
     * DefaultImageProvider)} with {@link #DEFAULT_AVATAR} and with the assumption, that
     * the image is a thumbnail.
     *
     * @param defaultImageRequest {@link DefaultImageRequest} object that specifies how a default
     * letter tile avatar should be drawn.
     */
    public final void loadDirectoryPhoto(ImageView view, Uri photoUri, boolean darkTheme,
            boolean isCircular, DefaultImageRequest defaultImageRequest) {
        loadPhoto(view, photoUri, null, -1, darkTheme, isCircular,
                defaultImageRequest, DEFAULT_AVATAR);
    }

    public final void loadDirectoryPhoto(ImageView view, Uri photoUri,
            Account account, boolean darkTheme, boolean isCircular,
            DefaultImageRequest defaultImageRequest) {
        loadPhoto(view, photoUri, account, -1, darkTheme, isCircular,
                defaultImageRequest, DEFAULT_AVATAR);
    }

    /**
     * Remove photo from the supplied image view. This also cancels current pending load request
     * inside this photo manager.
     */
    public abstract void removePhoto(ImageView view);

    /**
     * Cancels all pending requests to load photos asynchronously.
     */
    public abstract void cancelPendingRequests(View fragmentRootView);

    /**
     * Temporarily stops loading photos from the database.
     */
    public abstract void pause();

    /**
     * Resumes loading photos from the database.
     */
    public abstract void resume();

    /**
     * Marks all cached photos for reloading.  We can continue using cache but should
     * also make sure the photos haven't changed in the background and notify the views
     * if so.
     */
    public abstract void refreshCache();

    /**
     * Stores the given bitmap directly in the LRU bitmap cache.
     * @param photoUri The URI of the photo (for future requests).
     * @param bitmap The bitmap.
     * @param photoBytes The bytes that were parsed to create the bitmap.
     */
    public abstract void cacheBitmap(Uri photoUri, Bitmap bitmap, byte[] photoBytes);

    /**
     * Initiates a background process that over time will fill up cache with
     * preload photos.
     */
    public abstract void preloadPhotosInBackground();

    // ComponentCallbacks2
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
    }

    // ComponentCallbacks2
    @Override
    public void onLowMemory() {
    }

    // ComponentCallbacks2
    @Override
    public void onTrimMemory(int level) {
    }

    /**
     * callbacks associated with contact image requests
     */
    public interface PhotoFetcherCallback {
        public void onFetchComplete(Bitmap bitmap);
    }
}

class ContactPhotoManagerImpl extends ContactPhotoManager implements Callback {
    private static final String LOADER_THREAD_NAME = "ContactPhotoLoader";

    private static final int FADE_TRANSITION_DURATION = 200;

    /**
     * Type of message sent by the UI thread to itself to indicate that some photos
     * need to be loaded.
     */
    private static final int MESSAGE_REQUEST_LOADING = 1;

    /**
     * Type of message sent by the loader thread to indicate that some photos have
     * been loaded.
     */
    private static final int MESSAGE_PHOTOS_LOADED = 2;

    private static final String[] EMPTY_STRING_ARRAY = new String[0];

    private static final String[] COLUMNS = new String[] { Photo._ID, Photo.PHOTO };

    /**
     * Maintains the state of a particular photo.
     */
    private static class BitmapHolder {
        final byte[] bytes;
        final int originalSmallerExtent;

        volatile boolean fresh;
        Bitmap bitmap;
        Reference<Bitmap> bitmapRef;
        int decodedSampleSize;

        public BitmapHolder(byte[] bytes, int originalSmallerExtent) {
            this.bytes = bytes;
            this.fresh = true;
            this.originalSmallerExtent = originalSmallerExtent;
        }
    }

    private final Context mContext;

    /**
     * An LRU cache for bitmap holders. The cache contains bytes for photos just
     * as they come from the database. Each holder has a soft reference to the
     * actual bitmap.
     */
    private final LruCache<Object, BitmapHolder> mBitmapHolderCache;

    /**
     * {@code true} if ALL entries in {@link #mBitmapHolderCache} are NOT fresh.
     */
    private volatile boolean mBitmapHolderCacheAllUnfresh = true;

    /**
     * Cache size threshold at which bitmaps will not be preloaded.
     */
    private final int mBitmapHolderCacheRedZoneBytes;

    /**
     * Level 2 LRU cache for bitmaps. This is a smaller cache that holds
     * the most recently used bitmaps to save time on decoding
     * them from bytes (the bytes are stored in {@link #mBitmapHolderCache}.
     */
    private final LruCache<Object, Bitmap> mBitmapCache;

    /**
     * A map from ImageView to the corresponding photo ID or uri, encapsulated in a request.
     * The request may swapped out before the photo loading request is started.
     */
    private final ConcurrentHashMap<ImageView, Request> mPendingRequests =
            new ConcurrentHashMap<ImageView, Request>();

    /**
     * Handler for messages sent to the UI thread.
     */
    private final Handler mMainThreadHandler = new Handler(this);

    /**
     * Thread responsible for loading photos from the database. Created upon
     * the first request.
     */
    private LoaderThread mLoaderThread;

    /**
     * A gate to make sure we only send one instance of MESSAGE_PHOTOS_NEEDED at a time.
     */
    private boolean mLoadingRequested;

    /**
     * Flag indicating if the image loading is paused.
     */
    private boolean mPaused;

    /** Cache size for {@link #mBitmapHolderCache} for devices with "large" RAM. */
    private static final int HOLDER_CACHE_SIZE = 2000000;

    /** Cache size for {@link #mBitmapCache} for devices with "large" RAM. */
    private static final int BITMAP_CACHE_SIZE = 36864 * 48; // 1728K

    /** Height/width of a thumbnail image */
    private static int mThumbnailSize;

    /** For debug: How many times we had to reload cached photo for a stale entry */
    private final AtomicInteger mStaleCacheOverwrite = new AtomicInteger();

    /** For debug: How many times we had to reload cached photo for a fresh entry.  Should be 0. */
    private final AtomicInteger mFreshCacheOverwrite = new AtomicInteger();

    public ContactPhotoManagerImpl(Context context) {
        mContext = context;

        final ActivityManager am = ((ActivityManager) context.getSystemService(
                Context.ACTIVITY_SERVICE));

        final float cacheSizeAdjustment = (am.isLowRamDevice()) ? 0.5f : 1.0f;

        final int bitmapCacheSize = (int) (cacheSizeAdjustment * BITMAP_CACHE_SIZE);
        mBitmapCache = new LruCache<Object, Bitmap>(bitmapCacheSize) {
            @Override protected int sizeOf(Object key, Bitmap value) {
                return value.getByteCount();
            }

            @Override protected void entryRemoved(
                    boolean evicted, Object key, Bitmap oldValue, Bitmap newValue) {
                if (DEBUG) dumpStats();
            }
        };
        final int holderCacheSize = (int) (cacheSizeAdjustment * HOLDER_CACHE_SIZE);
        mBitmapHolderCache = new LruCache<Object, BitmapHolder>(holderCacheSize) {
            @Override protected int sizeOf(Object key, BitmapHolder value) {
                return value.bytes != null ? value.bytes.length : 0;
            }

            @Override protected void entryRemoved(
                    boolean evicted, Object key, BitmapHolder oldValue, BitmapHolder newValue) {
                if (DEBUG) dumpStats();
            }
        };
        mBitmapHolderCacheRedZoneBytes = (int) (holderCacheSize * 0.75);
        Log.i(TAG, "Cache adj: " + cacheSizeAdjustment);
        if (DEBUG) {
            Log.d(TAG, "Cache size: " + btk(mBitmapHolderCache.maxSize())
                    + " + " + btk(mBitmapCache.maxSize()));
        }

        mThumbnailSize = context.getResources().getDimensionPixelSize(
                R.dimen.contact_browser_list_item_photo_size);
    }

    /** Converts bytes to K bytes, rounding up.  Used only for debug log. */
    private static String btk(int bytes) {
        return ((bytes + 1023) / 1024) + "K";
    }

    private static final int safeDiv(int dividend, int divisor) {
        return (divisor  == 0) ? 0 : (dividend / divisor);
    }

    /**
     * Dump cache stats on logcat.
     */
    private void dumpStats() {
        if (!DEBUG) return;
        {
            int numHolders = 0;
            int rawBytes = 0;
            int bitmapBytes = 0;
            int numBitmaps = 0;
            for (BitmapHolder h : mBitmapHolderCache.snapshot().values()) {
                numHolders++;
                if (h.bytes != null) {
                    rawBytes += h.bytes.length;
                }
                Bitmap b = h.bitmapRef != null ? h.bitmapRef.get() : null;
                if (b != null) {
                    numBitmaps++;
                    bitmapBytes += b.getByteCount();
                }
            }
            Log.d(TAG, "L1: " + btk(rawBytes) + " + " + btk(bitmapBytes) + " = "
                    + btk(rawBytes + bitmapBytes) + ", " + numHolders + " holders, "
                    + numBitmaps + " bitmaps, avg: "
                    + btk(safeDiv(rawBytes, numHolders))
                    + "," + btk(safeDiv(bitmapBytes,numBitmaps)));
            Log.d(TAG, "L1 Stats: " + mBitmapHolderCache.toString()
                    + ", overwrite: fresh=" + mFreshCacheOverwrite.get()
                    + " stale=" + mStaleCacheOverwrite.get());
        }

        {
            int numBitmaps = 0;
            int bitmapBytes = 0;
            for (Bitmap b : mBitmapCache.snapshot().values()) {
                numBitmaps++;
                bitmapBytes += b.getByteCount();
            }
            Log.d(TAG, "L2: " + btk(bitmapBytes) + ", " + numBitmaps + " bitmaps"
                    + ", avg: " + btk(safeDiv(bitmapBytes, numBitmaps)));
            // We don't get from L2 cache, so L2 stats is meaningless.
        }
    }

    @Override
    public void onTrimMemory(int level) {
        if (DEBUG) Log.d(TAG, "onTrimMemory: " + level);
        if (level >= ComponentCallbacks2.TRIM_MEMORY_MODERATE) {
            // Clear the caches.  Note all pending requests will be removed too.
            clear();
        }
    }

    @Override
    public void preloadPhotosInBackground() {
        ensureLoaderThread();
        mLoaderThread.requestPreloading();
    }

    @Override
    public void loadThumbnail(ImageView view, long photoId, Account account,
            boolean darkTheme, boolean isCircular, DefaultImageRequest defaultImageRequest,
            DefaultImageProvider defaultProvider) {
        if (photoId == 0) {
            // No photo is needed
            defaultProvider.applyDefaultImage(view, account, -1, darkTheme, defaultImageRequest);
            mPendingRequests.remove(view);
        } else {
            if (DEBUG) Log.d(TAG, "loadPhoto request: " + photoId);
            loadPhotoByIdOrUri(view, Request.createFromThumbnailId(photoId, darkTheme, isCircular,
                    defaultProvider, defaultImageRequest));
        }
    }

    @Override
    public void loadPhoto(ImageView view, Uri photoUri, Account account, int requestedExtent,
            boolean darkTheme, boolean isCircular, DefaultImageRequest defaultImageRequest,
            DefaultImageProvider defaultProvider) {
        if (photoUri == null) {
            // No photo is needed
            defaultProvider.applyDefaultImage(view, account, requestedExtent, darkTheme,
                    defaultImageRequest);
            mPendingRequests.remove(view);
        } else {
            if (DEBUG) Log.d(TAG, "loadPhoto request: " + photoUri);
            if (isDefaultImageUri(photoUri)) {
                createAndApplyDefaultImageForUri(view, account, photoUri, requestedExtent,
                        darkTheme, isCircular, defaultProvider);
            } else {
                loadPhotoByIdOrUri(view, Request.createFromUri(photoUri, requestedExtent,
                        darkTheme, isCircular, defaultProvider, defaultImageRequest));
            }
        }
    }

    private void createAndApplyDefaultImageForUri(ImageView view,
            Account account, Uri uri, int requestedExtent, boolean darkTheme,
            boolean isCircular, DefaultImageProvider defaultProvider) {
        DefaultImageRequest request = getDefaultImageRequestFromUri(uri);
        request.isCircular = isCircular;
        defaultProvider.applyDefaultImage(view, account, requestedExtent, darkTheme, request);
    }

    private void loadPhotoByIdOrUri(ImageView view, Request request) {
        boolean loaded = loadCachedPhoto(view, request, false);
        if (loaded) {
            mPendingRequests.remove(view);
        } else {
            mPendingRequests.put(view, request);
            if (!mPaused) {
                // Send a request to start loading photos
                requestLoading();
            }
        }
    }

    /**
     * Checks the cache to satisfy the bitmap request. If not found, requests the loader for
     * the contact's image.
     */
    @Override
    public void getBitmapForContact(Uri photoUri, ImageView imgView, int widthHint,
            PhotoFetcherCallback cb) {
        // ensure request is for a valid contact uri before checking for bitmap
        // or posting a load request
        if (photoUri == null || isDefaultImageUri(photoUri)) return;

        // formulate the contact bitmap request
        Request request = Request.createBitmapOnly(photoUri, widthHint, cb);
        // check bitmap cache
        boolean done = decodeContactBitmapFromCache(request);

        // if not in cache, put request in loading queue
        if (!done) {
            Request loadRequest = Request.createBitmapOnly(photoUri, widthHint, cb);
            mPendingRequests.put(imgView, loadRequest);
            if (!mPaused) {
                requestLoading();
            }
        }
    }

    /**
     * Checks the cache for the contact bitmap's bytes, decodes those bytes, and sends the
     * decoded bitmap to the requester
     *
     * @return true if the bitmap is present and the cache and has been sent to the requester
     */
    private boolean decodeContactBitmapFromCache(Request request) {
        Uri photoUri = request.getUri();
        PhotoFetcherCallback cb = request.getCallback();

        // check cache for the bitmap bytes
        BitmapHolder holder = mBitmapHolderCache.get(request.getKey());
        if (holder != null && holder.bytes != null && holder.bytes.length != 0) {
            // inflate bitmap from cache bytes
            int sampleSize =
                    BitmapUtil.findOptimalSampleSize(holder.originalSmallerExtent,
                            request.getRequestedExtent());
            if (holder.decodedSampleSize == sampleSize && holder.bitmapRef != null &&
                    holder.bitmapRef.get() != null) {
                // already has a decoded bitmap at the requested size
                cb.onFetchComplete(holder.bitmapRef.get());
            } else {
                Bitmap bitmap = BitmapUtil.decodeBitmapFromBytes(holder.bytes, sampleSize);
                // the decoded bitmap won't be stored in the BitmapHolder cache
                cb.onFetchComplete(bitmap);
            }
            return true;
        }

        // cache doesn't contain the requested bitmap
        return false;
    }

    @Override
    public void removePhoto(ImageView view) {
        view.setImageDrawable(null);
        mPendingRequests.remove(view);
    }


    /**
     * Cancels pending requests to load photos asynchronously for views inside
     * {@param fragmentRootView}. If {@param fragmentRootView} is null, cancels all requests.
     */
    @Override
    public void cancelPendingRequests(View fragmentRootView) {
        if (fragmentRootView == null) {
            mPendingRequests.clear();
            return;
        }
        ImageView[] requestSetCopy = mPendingRequests.keySet().toArray(new ImageView[
                mPendingRequests.size()]);
        for (ImageView imageView : requestSetCopy) {
            // If an ImageView is orphaned (currently scrap) or a child of fragmentRootView, then
            // we can safely remove its request.
            if (imageView.getParent() == null || isChildView(fragmentRootView, imageView)) {
                mPendingRequests.remove(imageView);
            }
        }
    }

    private static boolean isChildView(View parent, View potentialChild) {
        return potentialChild.getParent() != null && (potentialChild.getParent() == parent || (
                potentialChild.getParent() instanceof ViewGroup && isChildView(parent,
                        (ViewGroup) potentialChild.getParent())));
    }

    @Override
    public void refreshCache() {
        if (mBitmapHolderCacheAllUnfresh) {
            if (DEBUG) Log.d(TAG, "refreshCache -- no fresh entries.");
            return;
        }
        if (DEBUG) Log.d(TAG, "refreshCache");
        mBitmapHolderCacheAllUnfresh = true;
        for (BitmapHolder holder : mBitmapHolderCache.snapshot().values()) {
            holder.fresh = false;
        }
    }

    /**
     * Checks if the photo is present in cache.  If so, sets the photo on the view.
     *
     * @return false if the photo needs to be (re)loaded from the provider.
     */
    private boolean loadCachedPhoto(ImageView view, Request request, boolean fadeIn) {
        BitmapHolder holder = mBitmapHolderCache.get(request.getKey());
        if (holder == null) {
            // The bitmap has not been loaded ==> show default avatar
            request.applyDefaultImage(view, request.mIsCircular);
            return false;
        }

        if (holder.bytes == null) {
            request.applyDefaultImage(view, request.mIsCircular);
            return holder.fresh;
        }

        Bitmap cachedBitmap = holder.bitmapRef == null ? null : holder.bitmapRef.get();
        if (cachedBitmap == null) {
            if (holder.bytes.length < 8 * 1024) {
                // Small thumbnails are usually quick to inflate. Let's do that on the UI thread
                inflateBitmap(holder, request.getRequestedExtent());
                cachedBitmap = holder.bitmap;
                if (cachedBitmap == null) return false;
            } else {
                // This is bigger data. Let's send that back to the Loader so that we can
                // inflate this in the background
                request.applyDefaultImage(view, request.mIsCircular);
                return false;
            }
        }

        final Drawable previousDrawable = view.getDrawable();
        if (fadeIn && previousDrawable != null) {
            final Drawable[] layers = new Drawable[2];
            // Prevent cascade of TransitionDrawables.
            if (previousDrawable instanceof TransitionDrawable) {
                final TransitionDrawable previousTransitionDrawable =
                        (TransitionDrawable) previousDrawable;
                layers[0] = previousTransitionDrawable.getDrawable(
                        previousTransitionDrawable.getNumberOfLayers() - 1);
            } else {
                layers[0] = previousDrawable;
            }
            layers[1] = getDrawableForBitmap(mContext.getResources(), cachedBitmap, request);
            TransitionDrawable drawable = new TransitionDrawable(layers);
            view.setImageDrawable(drawable);
            drawable.startTransition(FADE_TRANSITION_DURATION);
        } else {
            view.setImageDrawable(
                    getDrawableForBitmap(mContext.getResources(), cachedBitmap, request));
        }

        // Put the bitmap in the LRU cache. But only do this for images that are small enough
        // (we require that at least six of those can be cached at the same time)
        if (cachedBitmap.getByteCount() < mBitmapCache.maxSize() / 6) {
            mBitmapCache.put(request.getKey(), cachedBitmap);
        }

        // Soften the reference
        holder.bitmap = null;

        return holder.fresh;
    }

    /**
     * Given a bitmap, returns a drawable that is configured to display the bitmap based on the
     * specified request.
     */
    private Drawable getDrawableForBitmap(Resources resources, Bitmap bitmap, Request request) {
        if (request.mIsCircular) {
            final RoundedBitmapDrawable drawable =
                    RoundedBitmapDrawableFactory.create(resources, bitmap);
            drawable.setAntiAlias(true);
            drawable.setCornerRadius(bitmap.getHeight() / 2);
            return drawable;
        } else {
            return new BitmapDrawable(resources, bitmap);
        }
    }

    /**
     * If necessary, decodes bytes stored in the holder to Bitmap.  As long as the
     * bitmap is held either by {@link #mBitmapCache} or by a soft reference in
     * the holder, it will not be necessary to decode the bitmap.
     */
    private static void inflateBitmap(BitmapHolder holder, int requestedExtent) {
        final int sampleSize =
                BitmapUtil.findOptimalSampleSize(holder.originalSmallerExtent, requestedExtent);
        byte[] bytes = holder.bytes;
        if (bytes == null || bytes.length == 0) {
            return;
        }

        if (sampleSize == holder.decodedSampleSize) {
            // Check the soft reference.  If will be retained if the bitmap is also
            // in the LRU cache, so we don't need to check the LRU cache explicitly.
            if (holder.bitmapRef != null) {
                holder.bitmap = holder.bitmapRef.get();
                if (holder.bitmap != null) {
                    return;
                }
            }
        }

        try {
            Bitmap bitmap = BitmapUtil.decodeBitmapFromBytes(bytes, sampleSize);

            // TODO: As a temporary workaround while framework support is being added to
            // clip non-square bitmaps into a perfect circle, manually crop the bitmap into
            // into a square if it will be displayed as a thumbnail so that it can be cropped
            // into a circle.
            final int height = bitmap.getHeight();
            final int width = bitmap.getWidth();

            // The smaller dimension of a scaled bitmap can range from anywhere from 0 to just
            // below twice the length of a thumbnail image due to the way we calculate the optimal
            // sample size.
            if (height != width && Math.min(height, width) <= mThumbnailSize * 2) {
                final int dimension = Math.min(height, width);
                bitmap = ThumbnailUtils.extractThumbnail(bitmap, dimension, dimension);
            }
            // make bitmap mutable and draw size onto it
            if (DEBUG_SIZES) {
                Bitmap original = bitmap;
                bitmap = bitmap.copy(bitmap.getConfig(), true);
                original.recycle();
                Canvas canvas = new Canvas(bitmap);
                Paint paint = new Paint();
                paint.setTextSize(16);
                paint.setColor(Color.BLUE);
                paint.setStyle(Style.FILL);
                canvas.drawRect(0.0f, 0.0f, 50.0f, 20.0f, paint);
                paint.setColor(Color.WHITE);
                paint.setAntiAlias(true);
                canvas.drawText(bitmap.getWidth() + "/" + sampleSize, 0, 15, paint);
            }

            holder.decodedSampleSize = sampleSize;
            holder.bitmap = bitmap;
            holder.bitmapRef = new SoftReference<Bitmap>(bitmap);
            if (DEBUG) {
                Log.d(TAG, "inflateBitmap " + btk(bytes.length) + " -> "
                        + bitmap.getWidth() + "x" + bitmap.getHeight()
                        + ", " + btk(bitmap.getByteCount()));
            }
        } catch (OutOfMemoryError e) {
            // Do nothing - the photo will appear to be missing
        }
    }

    public void clear() {
        if (DEBUG) Log.d(TAG, "clear");
        mPendingRequests.clear();
        mBitmapHolderCache.evictAll();
        mBitmapCache.evictAll();
    }

    @Override
    public void pause() {
        mPaused = true;
    }

    @Override
    public void resume() {
        mPaused = false;
        if (DEBUG) dumpStats();
        if (!mPendingRequests.isEmpty()) {
            requestLoading();
        }
    }

    /**
     * Sends a message to this thread itself to start loading images.  If the current
     * view contains multiple image views, all of those image views will get a chance
     * to request their respective photos before any of those requests are executed.
     * This allows us to load images in bulk.
     */
    private void requestLoading() {
        if (!mLoadingRequested) {
            mLoadingRequested = true;
            mMainThreadHandler.sendEmptyMessage(MESSAGE_REQUEST_LOADING);
        }
    }

    /**
     * Processes requests on the main thread.
     */
    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case MESSAGE_REQUEST_LOADING: {
                mLoadingRequested = false;
                if (!mPaused) {
                    ensureLoaderThread();
                    mLoaderThread.requestLoading();
                }
                return true;
            }

            case MESSAGE_PHOTOS_LOADED: {
                if (!mPaused) {
                    processLoadedImages();
                }
                if (DEBUG) dumpStats();
                return true;
            }
        }
        return false;
    }

    public void ensureLoaderThread() {
        if (mLoaderThread == null) {
            mLoaderThread = new LoaderThread(mContext.getContentResolver());
            mLoaderThread.start();
        }
    }

    /**
     * Goes over pending loading requests and displays loaded photos.  If some of the
     * photos still haven't been loaded, sends another request for image loading.
     */
    private void processLoadedImages() {
        Iterator<ImageView> iterator = mPendingRequests.keySet().iterator();
        while (iterator.hasNext()) {
            ImageView view = iterator.next();
            Request request = mPendingRequests.get(view);
            boolean loaded = false;
            if (request.isBitmapOnly()) {
                decodeContactBitmapFromCache(request);
            } else {
                // TODO: Temporarily disable contact photo fading in, until issues with
                // RoundedBitmapDrawables overlapping the default image drawables are resolved.
                loaded = loadCachedPhoto(view, request, false);
            }
            if (loaded) {
                iterator.remove();
            }
        }

        softenCache();

        if (!mPendingRequests.isEmpty()) {
            requestLoading();
        }
    }

    /**
     * Removes strong references to loaded bitmaps to allow them to be garbage collected
     * if needed.  Some of the bitmaps will still be retained by {@link #mBitmapCache}.
     */
    private void softenCache() {
        for (BitmapHolder holder : mBitmapHolderCache.snapshot().values()) {
            holder.bitmap = null;
        }
    }

    /**
     * Stores the supplied bitmap in cache.
     */
    private void cacheBitmap(Object key, byte[] bytes, boolean preloading, int requestedExtent) {
        if (DEBUG) {
            BitmapHolder prev = mBitmapHolderCache.get(key);
            if (prev != null && prev.bytes != null) {
                Log.d(TAG, "Overwriting cache: key=" + key + (prev.fresh ? " FRESH" : " stale"));
                if (prev.fresh) {
                    mFreshCacheOverwrite.incrementAndGet();
                } else {
                    mStaleCacheOverwrite.incrementAndGet();
                }
            }
            Log.d(TAG, "Caching data: key=" + key + ", " +
                    (bytes == null ? "<null>" : btk(bytes.length)));
        }
        BitmapHolder holder = new BitmapHolder(bytes,
                bytes == null ? -1 : BitmapUtil.getSmallerExtentFromBytes(bytes));

        // Unless this image is being preloaded, decode it right away while
        // we are still on the background thread.
        if (!preloading) {
            inflateBitmap(holder, requestedExtent);
        }

        mBitmapHolderCache.put(key, holder);
        mBitmapHolderCacheAllUnfresh = false;
    }

    @Override
    public void cacheBitmap(Uri photoUri, Bitmap bitmap, byte[] photoBytes) {
        final int smallerExtent = Math.min(bitmap.getWidth(), bitmap.getHeight());
        // We can pretend here that the extent of the photo was the size that we originally
        // requested
        Request request = Request.createFromUri(photoUri, smallerExtent, false /* darkTheme */,
                false /* isCircular */ , DEFAULT_AVATAR);
        BitmapHolder holder = new BitmapHolder(photoBytes, smallerExtent);
        holder.bitmapRef = new SoftReference<Bitmap>(bitmap);
        mBitmapHolderCache.put(request.getKey(), holder);
        mBitmapHolderCacheAllUnfresh = false;
        mBitmapCache.put(request.getKey(), bitmap);
    }

    /**
     * Populates an array of photo IDs that need to be loaded. Also decodes bitmaps that we have
     * already loaded
     */
    private void obtainPhotoIdsAndUrisToLoad(Set<Long> photoIds,
            Set<String> photoIdsAsStrings, Set<Request> uris) {
        photoIds.clear();
        photoIdsAsStrings.clear();
        uris.clear();

        boolean jpegsDecoded = false;

        /*
         * Since the call is made from the loader thread, the map could be
         * changing during the iteration. That's not really a problem:
         * ConcurrentHashMap will allow those changes to happen without throwing
         * exceptions. Since we may miss some requests in the situation of
         * concurrent change, we will need to check the map again once loading
         * is complete.
         */
        Iterator<Request> iterator = mPendingRequests.values().iterator();
        while (iterator.hasNext()) {
            Request request = iterator.next();
            final BitmapHolder holder = mBitmapHolderCache.get(request.getKey());
            if (holder != null && holder.bytes != null && holder.fresh &&
                    (holder.bitmapRef == null || holder.bitmapRef.get() == null)) {
                // This was previously loaded but we don't currently have the inflated Bitmap
                inflateBitmap(holder, request.getRequestedExtent());
                jpegsDecoded = true;
            } else {
                if (holder == null || !holder.fresh) {
                    if (request.isUriRequest()) {
                        uris.add(request);
                    } else {
                        photoIds.add(request.getId());
                        photoIdsAsStrings.add(String.valueOf(request.mId));
                    }
                }
            }
        }

        if (jpegsDecoded) mMainThreadHandler.sendEmptyMessage(MESSAGE_PHOTOS_LOADED);
    }

    /**
     * The thread that performs loading of photos from the database.
     */
    private class LoaderThread extends HandlerThread implements Callback {
        private static final int BUFFER_SIZE = 1024*16;
        private static final int MESSAGE_PRELOAD_PHOTOS = 0;
        private static final int MESSAGE_LOAD_PHOTOS = 1;

        /**
         * A pause between preload batches that yields to the UI thread.
         */
        private static final int PHOTO_PRELOAD_DELAY = 1000;

        /**
         * Number of photos to preload per batch.
         */
        private static final int PRELOAD_BATCH = 25;

        /**
         * Maximum number of photos to preload.  If the cache size is 2Mb and
         * the expected average size of a photo is 4kb, then this number should be 2Mb/4kb = 500.
         */
        private static final int MAX_PHOTOS_TO_PRELOAD = 100;

        private final ContentResolver mResolver;
        private final StringBuilder mStringBuilder = new StringBuilder();
        private final Set<Long> mPhotoIds = Sets.newHashSet();
        private final Set<String> mPhotoIdsAsStrings = Sets.newHashSet();
        private final Set<Request> mPhotoUris = Sets.newHashSet();
        private final List<Long> mPreloadPhotoIds = Lists.newArrayList();

        private Handler mLoaderThreadHandler;
        private byte mBuffer[];

        private static final int PRELOAD_STATUS_NOT_STARTED = 0;
        private static final int PRELOAD_STATUS_IN_PROGRESS = 1;
        private static final int PRELOAD_STATUS_DONE = 2;

        private int mPreloadStatus = PRELOAD_STATUS_NOT_STARTED;

        public LoaderThread(ContentResolver resolver) {
            super(LOADER_THREAD_NAME);
            mResolver = resolver;
        }

        public void ensureHandler() {
            if (mLoaderThreadHandler == null) {
                mLoaderThreadHandler = new Handler(getLooper(), this);
            }
        }

        /**
         * Kicks off preloading of the next batch of photos on the background thread.
         * Preloading will happen after a delay: we want to yield to the UI thread
         * as much as possible.
         * <p>
         * If preloading is already complete, does nothing.
         */
        public void requestPreloading() {
            if (mPreloadStatus == PRELOAD_STATUS_DONE) {
                return;
            }

            ensureHandler();
            if (mLoaderThreadHandler.hasMessages(MESSAGE_LOAD_PHOTOS)) {
                return;
            }

            mLoaderThreadHandler.sendEmptyMessageDelayed(
                    MESSAGE_PRELOAD_PHOTOS, PHOTO_PRELOAD_DELAY);
        }

        /**
         * Sends a message to this thread to load requested photos.  Cancels a preloading
         * request, if any: we don't want preloading to impede loading of the photos
         * we need to display now.
         */
        public void requestLoading() {
            ensureHandler();
            mLoaderThreadHandler.removeMessages(MESSAGE_PRELOAD_PHOTOS);
            mLoaderThreadHandler.sendEmptyMessage(MESSAGE_LOAD_PHOTOS);
        }

        /**
         * Receives the above message, loads photos and then sends a message
         * to the main thread to process them.
         */
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case MESSAGE_PRELOAD_PHOTOS:
                    preloadPhotosInBackground();
                    break;
                case MESSAGE_LOAD_PHOTOS:
                    loadPhotosInBackground();
                    break;
            }
            return true;
        }

        /**
         * The first time it is called, figures out which photos need to be preloaded.
         * Each subsequent call preloads the next batch of photos and requests
         * another cycle of preloading after a delay.  The whole process ends when
         * we either run out of photos to preload or fill up cache.
         */
        private void preloadPhotosInBackground() {
            if (mPreloadStatus == PRELOAD_STATUS_DONE) {
                return;
            }

            if (mPreloadStatus == PRELOAD_STATUS_NOT_STARTED) {
                queryPhotosForPreload();
                if (mPreloadPhotoIds.isEmpty()) {
                    mPreloadStatus = PRELOAD_STATUS_DONE;
                } else {
                    mPreloadStatus = PRELOAD_STATUS_IN_PROGRESS;
                }
                requestPreloading();
                return;
            }

            if (mBitmapHolderCache.size() > mBitmapHolderCacheRedZoneBytes) {
                mPreloadStatus = PRELOAD_STATUS_DONE;
                return;
            }

            mPhotoIds.clear();
            mPhotoIdsAsStrings.clear();

            int count = 0;
            int preloadSize = mPreloadPhotoIds.size();
            while(preloadSize > 0 && mPhotoIds.size() < PRELOAD_BATCH) {
                preloadSize--;
                count++;
                Long photoId = mPreloadPhotoIds.get(preloadSize);
                mPhotoIds.add(photoId);
                mPhotoIdsAsStrings.add(photoId.toString());
                mPreloadPhotoIds.remove(preloadSize);
            }

            loadThumbnails(true);

            if (preloadSize == 0) {
                mPreloadStatus = PRELOAD_STATUS_DONE;
            }

            Log.v(TAG, "Preloaded " + count + " photos.  Cached bytes: "
                    + mBitmapHolderCache.size());

            requestPreloading();
        }

        private void queryPhotosForPreload() {
            Cursor cursor = null;
            try {
                Uri uri = Contacts.CONTENT_URI.buildUpon().appendQueryParameter(
                        ContactsContract.DIRECTORY_PARAM_KEY, String.valueOf(Directory.DEFAULT))
                        .appendQueryParameter(ContactsContract.LIMIT_PARAM_KEY,
                                String.valueOf(MAX_PHOTOS_TO_PRELOAD))
                        .build();
                cursor = mResolver.query(uri, new String[] { Contacts.PHOTO_ID },
                        Contacts.PHOTO_ID + " NOT NULL AND " + Contacts.PHOTO_ID + "!=0",
                        null,
                        Contacts.STARRED + " DESC, " + Contacts.LAST_TIME_CONTACTED + " DESC");

                if (cursor != null) {
                    while (cursor.moveToNext()) {
                        // Insert them in reverse order, because we will be taking
                        // them from the end of the list for loading.
                        mPreloadPhotoIds.add(0, cursor.getLong(0));
                    }
                }
            } finally {
                if (cursor != null) {
                    cursor.close();
                }
            }
        }

        private void loadPhotosInBackground() {
            obtainPhotoIdsAndUrisToLoad(mPhotoIds, mPhotoIdsAsStrings, mPhotoUris);
            loadThumbnails(false);
            loadUriBasedPhotos();
            requestPreloading();
        }

        /** Loads thumbnail photos with ids */
        private void loadThumbnails(boolean preloading) {
            if (mPhotoIds.isEmpty()) {
                return;
            }

            // Remove loaded photos from the preload queue: we don't want
            // the preloading process to load them again.
            if (!preloading && mPreloadStatus == PRELOAD_STATUS_IN_PROGRESS) {
                for (Long id : mPhotoIds) {
                    mPreloadPhotoIds.remove(id);
                }
                if (mPreloadPhotoIds.isEmpty()) {
                    mPreloadStatus = PRELOAD_STATUS_DONE;
                }
            }

            mStringBuilder.setLength(0);
            mStringBuilder.append(Photo._ID + " IN(");
            for (int i = 0; i < mPhotoIds.size(); i++) {
                if (i != 0) {
                    mStringBuilder.append(',');
                }
                mStringBuilder.append('?');
            }
            mStringBuilder.append(')');

            Cursor cursor = null;
            try {
                if (DEBUG) Log.d(TAG, "Loading " + TextUtils.join(",", mPhotoIdsAsStrings));
                cursor = mResolver.query(Data.CONTENT_URI,
                        COLUMNS,
                        mStringBuilder.toString(),
                        mPhotoIdsAsStrings.toArray(EMPTY_STRING_ARRAY),
                        null);

                if (cursor != null) {
                    while (cursor.moveToNext()) {
                        Long id = cursor.getLong(0);
                        byte[] bytes = cursor.getBlob(1);
                        cacheBitmap(id, bytes, preloading, -1);
                        mPhotoIds.remove(id);
                    }
                }
            } finally {
                if (cursor != null) {
                    cursor.close();
                }
            }

            // Remaining photos were not found in the contacts database (but might be in profile).
            for (Long id : mPhotoIds) {
                if (ContactsContract.isProfileId(id)) {
                    Cursor profileCursor = null;
                    try {
                        profileCursor = mResolver.query(
                                ContentUris.withAppendedId(Data.CONTENT_URI, id),
                                COLUMNS, null, null, null);
                        if (profileCursor != null && profileCursor.moveToFirst()) {
                            cacheBitmap(profileCursor.getLong(0), profileCursor.getBlob(1),
                                    preloading, -1);
                        } else {
                            // Couldn't load a photo this way either.
                            cacheBitmap(id, null, preloading, -1);
                        }
                    } finally {
                        if (profileCursor != null) {
                            profileCursor.close();
                        }
                    }
                } else {
                    // Not a profile photo and not found - mark the cache accordingly
                    cacheBitmap(id, null, preloading, -1);
                }
            }

            mMainThreadHandler.sendEmptyMessage(MESSAGE_PHOTOS_LOADED);
        }

        /**
         * Loads photos referenced with Uris. Those can be remote thumbnails
         * (from directory searches), display photos etc
         */
        private void loadUriBasedPhotos() {
            for (Request uriRequest : mPhotoUris) {
                // Keep the original URI and use this to key into the cache.  Failure to do so will
                // result in an image being continually reloaded into cache if the original URI
                // has a contact type encodedFragment (eg nearby places business photo URLs).
                Uri originalUri = uriRequest.getUri();

                // Strip off the "contact type" we added to the URI to ensure it was identifiable as
                // a business photo -- there is no need to pass this on to the server.
                Uri uri = ContactPhotoManager.removeContactType(originalUri);

                if (mBuffer == null) {
                    mBuffer = new byte[BUFFER_SIZE];
                }
                try {
                    if (DEBUG) Log.d(TAG, "Loading " + uri);
                    final String scheme = uri.getScheme();
                    InputStream is = null;
                    if (scheme.equals("http") || scheme.equals("https")) {
                        is = new URL(uri.toString()).openStream();
                    } else {
                        is = mResolver.openInputStream(uri);
                    }
                    if (is != null) {
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        try {
                            int size;
                            while ((size = is.read(mBuffer)) != -1) {
                                baos.write(mBuffer, 0, size);
                            }
                        } finally {
                            is.close();
                        }
                        cacheBitmap(originalUri, baos.toByteArray(), false,
                                uriRequest.getRequestedExtent());
                        mMainThreadHandler.sendEmptyMessage(MESSAGE_PHOTOS_LOADED);
                    } else {
                        Log.v(TAG, "Cannot load photo " + uri);
                        cacheBitmap(originalUri, null, false, uriRequest.getRequestedExtent());
                    }
                } catch (final Exception | OutOfMemoryError ex) {
                    Log.v(TAG, "Cannot load photo " + uri, ex);
                    cacheBitmap(originalUri, null, false, uriRequest.getRequestedExtent());
                }
            }
        }
    }

    /**
     * A holder for either a Uri or an id and a flag whether this was requested for the dark or
     * light theme
     */
    private static final class Request {
        private final long mId;
        private final Uri mUri;
        private final boolean mDarkTheme;
        private final int mRequestedExtent;
        private final DefaultImageProvider mDefaultProvider;
        // Whether or not the contact photo is to be displayed as a circle
        private final boolean mIsCircular;

        // params for bitmap requests
        private boolean mIsBitmapOnly;
        private PhotoFetcherCallback mCallback;
        private DefaultImageRequest mDefaultImageRequest;

        private Request(long id, Uri uri, int requestedExtent, boolean darkTheme,
                boolean isCircular, DefaultImageProvider defaultProvider, DefaultImageRequest defaultImageRequest) {
            mId = id;
            mUri = uri;
            mDarkTheme = darkTheme;
            mIsCircular = isCircular;
            mRequestedExtent = requestedExtent;
            mDefaultProvider = defaultProvider;
            mDefaultImageRequest = defaultImageRequest;
        }

        public static Request createFromThumbnailId(long id, boolean darkTheme, boolean isCircular,
                DefaultImageProvider defaultProvider, DefaultImageRequest defaultImageRequest) {
            return new Request(id, null /* no URI */, -1, darkTheme, isCircular, defaultProvider,
                    defaultImageRequest);
        }

        public static Request createFromUri(Uri uri, int requestedExtent, boolean darkTheme,
                boolean isCircular, DefaultImageProvider defaultProvider) {
            return createFromUri(uri, requestedExtent, darkTheme, isCircular,
                    defaultProvider, null);
        }

        public static Request createFromUri(Uri uri, int requestedExtent, boolean darkTheme,
                boolean isCircular, DefaultImageProvider defaultProvider,
                DefaultImageRequest defaultImageRequest) {
            return new Request(0 /* no ID */, uri, requestedExtent, darkTheme, isCircular,
                    defaultProvider, defaultImageRequest);
        }

        public static Request createBitmapOnly(Uri uri, int requestedExtent,
                                               PhotoFetcherCallback cb) {
            return createBitmapOnly(uri, requestedExtent, cb, null);
        }

        public static Request createBitmapOnly(Uri uri, int requestedExtent,
                PhotoFetcherCallback cb, DefaultImageRequest defaultImageRequest) {
            Request request = new Request(0, uri, requestedExtent, false, false, null,
                    defaultImageRequest);
            request.setBitmapOnly();
            request.mCallback = cb;

            return request;
        }

        public boolean isBitmapOnly() {
            return mIsBitmapOnly;
        }

        public PhotoFetcherCallback getCallback() {
            return mCallback;
        }

        public boolean isUriRequest() {
            return mUri != null;
        }

        public Uri getUri() {
            return mUri;
        }

        public long getId() {
            return mId;
        }

        public int getRequestedExtent() {
            return mRequestedExtent;
        }

        public void setBitmapOnly() {
            mIsBitmapOnly = true;
        }

        @Override
        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + (int) (mId ^ (mId >>> 32));
            result = prime * result + mRequestedExtent;
            result = prime * result + ((mUri == null) ? 0 : mUri.hashCode());
            return result;
        }

        @Override
        public boolean equals(Object obj) {
            if (this == obj) return true;
            if (obj == null) return false;
            if (getClass() != obj.getClass()) return false;
            final Request that = (Request) obj;
            if (mId != that.mId) return false;
            if (mRequestedExtent != that.mRequestedExtent) return false;
            if (!UriUtils.areEqual(mUri, that.mUri)) return false;
            // Don't compare equality of mDarkTheme because it is only used in the default contact
            // photo case. When the contact does have a photo, the contact photo is the same
            // regardless of mDarkTheme, so we shouldn't need to put the photo request on the queue
            // twice.
            return true;
        }

        public Object getKey() {
            return mUri == null ? mId : mUri;
        }

        /**
         * Applies the default image to the current view. The original {@link DefaultImageRequest},
         * if present, will be passed along to the {@link DefaultImageProvider}. Otherwise, a
         * default {@link DefaultImageRequest} is used based on the uri type.
         *
         * @param view The current image view to apply the image to.
         * @param isCircular Whether the image is circular or not.
         */
        public void applyDefaultImage(ImageView view, boolean isCircular) {
            DefaultImageRequest request = mDefaultImageRequest;

            if (request == null) {
                if (isCircular) {
                    request = ContactPhotoManager.isBusinessContactUri(mUri)
                            ? DefaultImageRequest.EMPTY_CIRCULAR_BUSINESS_IMAGE_REQUEST
                            : DefaultImageRequest.EMPTY_CIRCULAR_DEFAULT_IMAGE_REQUEST;
                } else {
                    request = ContactPhotoManager.isBusinessContactUri(mUri)
                            ? DefaultImageRequest.EMPTY_DEFAULT_BUSINESS_IMAGE_REQUEST
                            : DefaultImageRequest.EMPTY_DEFAULT_IMAGE_REQUEST;
                }
            }

            mDefaultProvider.applyDefaultImage(view, null, mRequestedExtent, mDarkTheme, request);
        }
    }
}