SendersView.java revision 6a4c4f62db0ddf6660d889bf1f21e37d25a99363
1/* 2 * Copyright (C) 2012 Google Inc. 3 * Licensed to The Android Open Source Project. 4 * 5 * Licensed under the Apache License, Version 2.0 (the "License"); 6 * you may not use this file except in compliance with the License. 7 * You may obtain a copy of the License at 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 */ 17 18package com.android.mail.browse; 19 20import android.content.BroadcastReceiver; 21import android.content.Context; 22import android.content.Intent; 23import android.content.IntentFilter; 24import android.content.res.Resources; 25import android.graphics.Typeface; 26import android.text.Spannable; 27import android.text.SpannableString; 28import android.text.SpannableStringBuilder; 29import android.text.TextUtils; 30import android.text.style.CharacterStyle; 31import android.text.style.TextAppearanceSpan; 32import android.text.util.Rfc822Token; 33import android.text.util.Rfc822Tokenizer; 34 35import com.android.mail.R; 36import com.android.mail.providers.Address; 37import com.android.mail.providers.Conversation; 38import com.android.mail.providers.ConversationInfo; 39import com.android.mail.providers.MessageInfo; 40import com.android.mail.providers.UIProvider; 41import com.android.mail.ui.DividedImageCanvas; 42import com.android.mail.utils.ObjectCache; 43import com.google.common.base.Objects; 44import com.google.common.collect.Maps; 45 46import java.util.ArrayList; 47import java.util.Locale; 48import java.util.Map; 49 50import java.util.regex.Pattern; 51 52public class SendersView { 53 public static final int DEFAULT_FORMATTING = 0; 54 public static final int MERGED_FORMATTING = 1; 55 private static final Integer DOES_NOT_EXIST = -5; 56 private static String sSendersSplitToken; 57 public static String SENDERS_VERSION_SEPARATOR = "^**^"; 58 public static Pattern SENDERS_VERSION_SEPARATOR_PATTERN = Pattern.compile("\\^\\*\\*\\^"); 59 private static CharSequence sDraftSingularString; 60 private static CharSequence sDraftPluralString; 61 private static CharSequence sSendingString; 62 private static String sDraftCountFormatString; 63 private static CharacterStyle sDraftsStyleSpan; 64 private static CharacterStyle sSendingStyleSpan; 65 private static TextAppearanceSpan sUnreadStyleSpan; 66 private static CharacterStyle sReadStyleSpan; 67 private static String sMeString; 68 private static Locale sMeStringLocale; 69 private static String sMessageCountSpacerString; 70 public static CharSequence sElidedString; 71 private static BroadcastReceiver sConfigurationChangedReceiver; 72 private static TextAppearanceSpan sMessageInfoReadStyleSpan; 73 private static TextAppearanceSpan sMessageInfoUnreadStyleSpan; 74 75 // We only want to have at most 2 Priority to length maps. This will handle the case where 76 // there is a widget installed on the launcher while the user is scrolling in the app 77 private static final int MAX_PRIORITY_LENGTH_MAP_LIST = 2; 78 79 // Cache of priority to length maps. We can't just use a single instance as it may be 80 // modified from different threads 81 private static final ObjectCache<Map<Integer, Integer>> PRIORITY_LENGTH_MAP_CACHE = 82 new ObjectCache<Map<Integer, Integer>>( 83 new ObjectCache.Callback<Map<Integer, Integer>>() { 84 @Override 85 public Map<Integer, Integer> newInstance() { 86 return Maps.newHashMap(); 87 } 88 @Override 89 public void onObjectReleased(Map<Integer, Integer> object) { 90 object.clear(); 91 } 92 }, MAX_PRIORITY_LENGTH_MAP_LIST); 93 94 public static Typeface getTypeface(boolean isUnread) { 95 return isUnread ? Typeface.DEFAULT_BOLD : Typeface.DEFAULT; 96 } 97 98 private static void getSenderResources(Context context) { 99 if (sConfigurationChangedReceiver == null) { 100 sConfigurationChangedReceiver = new BroadcastReceiver() { 101 @Override 102 public void onReceive(Context context, Intent intent) { 103 sDraftSingularString = null; 104 getSenderResources(context); 105 } 106 }; 107 context.registerReceiver(sConfigurationChangedReceiver, new IntentFilter( 108 Intent.ACTION_CONFIGURATION_CHANGED)); 109 } 110 if (sDraftSingularString == null) { 111 Resources res = context.getResources(); 112 sSendersSplitToken = res.getString(R.string.senders_split_token); 113 sElidedString = res.getString(R.string.senders_elided); 114 sDraftSingularString = res.getQuantityText(R.plurals.draft, 1); 115 sDraftPluralString = res.getQuantityText(R.plurals.draft, 2); 116 sDraftCountFormatString = res.getString(R.string.draft_count_format); 117 sMessageInfoUnreadStyleSpan = new TextAppearanceSpan(context, 118 R.style.MessageInfoUnreadTextAppearance); 119 sMessageInfoReadStyleSpan = new TextAppearanceSpan(context, 120 R.style.MessageInfoReadTextAppearance); 121 sDraftsStyleSpan = new TextAppearanceSpan(context, R.style.DraftTextAppearance); 122 sUnreadStyleSpan = new TextAppearanceSpan(context, R.style.SendersUnreadTextAppearance); 123 sSendingStyleSpan = new TextAppearanceSpan(context, R.style.SendingTextAppearance); 124 sReadStyleSpan = new TextAppearanceSpan(context, R.style.SendersReadTextAppearance); 125 sMessageCountSpacerString = res.getString(R.string.message_count_spacer); 126 sSendingString = res.getString(R.string.sending); 127 } 128 } 129 130 public static SpannableStringBuilder createMessageInfo(Context context, Conversation conv) { 131 ConversationInfo conversationInfo = conv.conversationInfo; 132 int sendingStatus = conv.sendingState; 133 SpannableStringBuilder messageInfo = new SpannableStringBuilder(); 134 boolean hasSenders = false; 135 // This covers the case where the sender is "me" and this is a draft 136 // message, which means this will only run once most of the time. 137 for (MessageInfo m : conversationInfo.messageInfos) { 138 if (!TextUtils.isEmpty(m.sender)) { 139 hasSenders = true; 140 break; 141 } 142 } 143 getSenderResources(context); 144 if (conversationInfo != null) { 145 int count = conversationInfo.messageCount; 146 int draftCount = conversationInfo.draftCount; 147 boolean showSending = sendingStatus == UIProvider.ConversationSendingState.SENDING; 148 if (count > 1) { 149 messageInfo.append(count + ""); 150 } 151 messageInfo.setSpan(CharacterStyle.wrap( 152 conv.read ? sMessageInfoReadStyleSpan : sMessageInfoUnreadStyleSpan), 153 0, messageInfo.length(), 0); 154 if (draftCount > 0) { 155 // If we are showing a message count or any draft text and there 156 // is at least 1 sender, prepend the sending state text with a 157 // comma. 158 if (hasSenders || count > 1) { 159 messageInfo.append(sSendersSplitToken); 160 } 161 SpannableStringBuilder draftString = new SpannableStringBuilder(); 162 if (draftCount == 1) { 163 draftString.append(sDraftSingularString); 164 } else { 165 draftString.append(sDraftPluralString 166 + String.format(sDraftCountFormatString, draftCount)); 167 } 168 draftString.setSpan(CharacterStyle.wrap(sDraftsStyleSpan), 0, draftString.length(), 169 Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 170 messageInfo.append(draftString); 171 } 172 if (showSending) { 173 // If we are showing a message count or any draft text, prepend 174 // the sending state text with a comma. 175 if (count > 1 || draftCount > 0) { 176 messageInfo.append(sSendersSplitToken); 177 } 178 SpannableStringBuilder sending = new SpannableStringBuilder(); 179 sending.append(sSendingString); 180 sending.setSpan(sSendingStyleSpan, 0, sending.length(), 0); 181 messageInfo.append(sending); 182 } 183 // Prepend a space if we are showing other message info text. 184 if (count > 1 || (draftCount > 0 && hasSenders) || showSending) { 185 messageInfo = new SpannableStringBuilder(sMessageCountSpacerString) 186 .append(messageInfo); 187 } 188 } 189 return messageInfo; 190 } 191 192 public static void format(Context context, ConversationInfo conversationInfo, 193 String messageInfo, int maxChars, ArrayList<SpannableString> styledSenders, 194 ArrayList<String> displayableSenderNames, ArrayList<String> displayableSenderEmails, 195 String account) { 196 getSenderResources(context); 197 handlePriority(context, maxChars, messageInfo, conversationInfo, styledSenders, 198 displayableSenderNames, displayableSenderEmails, account); 199 } 200 201 public static void handlePriority(Context context, int maxChars, String messageInfoString, 202 ConversationInfo conversationInfo, ArrayList<SpannableString> styledSenders, 203 ArrayList<String> displayableSenderNames, ArrayList<String> displayableSenderEmails, 204 String account) { 205 boolean shouldAddPhotos = displayableSenderEmails != null; 206 int maxPriorityToInclude = -1; // inclusive 207 int numCharsUsed = messageInfoString.length(); // draft, number drafts, 208 // count 209 int numSendersUsed = 0; 210 int numCharsToRemovePerWord = 0; 211 int maxFoundPriority = 0; 212 if (numCharsUsed > maxChars) { 213 numCharsToRemovePerWord = numCharsUsed - maxChars; 214 } 215 216 final Map<Integer, Integer> priorityToLength = PRIORITY_LENGTH_MAP_CACHE.get(); 217 try { 218 priorityToLength.clear(); 219 int senderLength; 220 for (MessageInfo info : conversationInfo.messageInfos) { 221 senderLength = !TextUtils.isEmpty(info.sender) ? info.sender.length() : 0; 222 priorityToLength.put(info.priority, senderLength); 223 maxFoundPriority = Math.max(maxFoundPriority, info.priority); 224 } 225 while (maxPriorityToInclude < maxFoundPriority) { 226 if (priorityToLength.containsKey(maxPriorityToInclude + 1)) { 227 int length = numCharsUsed + priorityToLength.get(maxPriorityToInclude + 1); 228 if (numCharsUsed > 0) 229 length += 2; 230 // We must show at least two senders if they exist. If we don't 231 // have space for both 232 // then we will truncate names. 233 if (length > maxChars && numSendersUsed >= 2) { 234 break; 235 } 236 numCharsUsed = length; 237 numSendersUsed++; 238 } 239 maxPriorityToInclude++; 240 } 241 } finally { 242 PRIORITY_LENGTH_MAP_CACHE.release(priorityToLength); 243 } 244 // We want to include this entry if 245 // 1) The onlyShowUnread flags is not set 246 // 2) The above flag is set, and the message is unread 247 MessageInfo currentMessage; 248 SpannableString spannableDisplay; 249 String nameString; 250 CharacterStyle style; 251 boolean appendedElided = false; 252 Map<String, Integer> displayHash = Maps.newHashMap(); 253 String firstDisplayableSenderEmail = null; 254 String firstDisplayableSender = null; 255 for (int i = 0; i < conversationInfo.messageInfos.size(); i++) { 256 currentMessage = conversationInfo.messageInfos.get(i); 257 nameString = !TextUtils.isEmpty(currentMessage.sender) ? currentMessage.sender : ""; 258 if (nameString.length() == 0) { 259 nameString = getMe(context); 260 } 261 if (numCharsToRemovePerWord != 0) { 262 nameString = nameString.substring(0, 263 Math.max(nameString.length() - numCharsToRemovePerWord, 0)); 264 } 265 final int priority = currentMessage.priority; 266 style = !currentMessage.read ? getUnreadStyleSpan() : getReadStyleSpan(); 267 if (priority <= maxPriorityToInclude) { 268 spannableDisplay = new SpannableString(nameString); 269 // Don't duplicate senders; leave the first instance, unless the 270 // current instance is also unread. 271 int oldPos = displayHash.containsKey(currentMessage.sender) ? displayHash 272 .get(currentMessage.sender) : DOES_NOT_EXIST; 273 // If this sender doesn't exist OR the current message is 274 // unread, add the sender. 275 if (oldPos == DOES_NOT_EXIST || !currentMessage.read) { 276 // If the sender entry already existed, and is right next to the 277 // current sender, remove the old entry. 278 if (oldPos != DOES_NOT_EXIST && i > 0 && oldPos == i - 1 279 && oldPos < styledSenders.size()) { 280 // Remove the old one! 281 styledSenders.set(oldPos, null); 282 if (shouldAddPhotos && !TextUtils.isEmpty(currentMessage.senderEmail)) { 283 displayableSenderEmails.remove(currentMessage.senderEmail); 284 displayableSenderNames.remove(currentMessage.sender); 285 } 286 } 287 displayHash.put(currentMessage.sender, i); 288 spannableDisplay.setSpan(style, 0, spannableDisplay.length(), 0); 289 styledSenders.add(spannableDisplay); 290 } 291 } else { 292 if (!appendedElided) { 293 spannableDisplay = new SpannableString(sElidedString); 294 spannableDisplay.setSpan(style, 0, spannableDisplay.length(), 0); 295 appendedElided = true; 296 styledSenders.add(spannableDisplay); 297 } 298 } 299 if (shouldAddPhotos) { 300 String senderEmail = TextUtils.isEmpty(currentMessage.sender) ? 301 account : currentMessage.senderEmail; 302 if (i == 0) { 303 // Always add the first sender! 304 firstDisplayableSenderEmail = senderEmail; 305 firstDisplayableSender = currentMessage.sender; 306 } else { 307 if (!Objects.equal(firstDisplayableSenderEmail, senderEmail)) { 308 int indexOf = displayableSenderEmails.indexOf(senderEmail); 309 if (indexOf > -1) { 310 displayableSenderEmails.remove(indexOf); 311 displayableSenderNames.remove(indexOf); 312 } 313 displayableSenderEmails.add(senderEmail); 314 displayableSenderNames.add(currentMessage.sender); 315 if (displayableSenderEmails.size() > DividedImageCanvas.MAX_DIVISIONS) { 316 displayableSenderEmails.remove(0); 317 displayableSenderNames.remove(0); 318 } 319 } 320 } 321 } 322 } 323 if (shouldAddPhotos && !TextUtils.isEmpty(firstDisplayableSenderEmail)) { 324 if (displayableSenderEmails.size() < DividedImageCanvas.MAX_DIVISIONS) { 325 displayableSenderEmails.add(0, firstDisplayableSenderEmail); 326 displayableSenderNames.add(0, firstDisplayableSender); 327 } else { 328 displayableSenderEmails.set(0, firstDisplayableSenderEmail); 329 displayableSenderNames.set(0, firstDisplayableSender); 330 } 331 } 332 } 333 334 private static CharacterStyle getUnreadStyleSpan() { 335 return CharacterStyle.wrap(sUnreadStyleSpan); 336 } 337 338 private static CharacterStyle getReadStyleSpan() { 339 return CharacterStyle.wrap(sReadStyleSpan); 340 } 341 342 static String getMe(Context context) { 343 final Resources resources = context.getResources(); 344 final Locale locale = resources.getConfiguration().locale; 345 346 if (sMeString == null || !locale.equals(sMeStringLocale)) { 347 sMeString = resources.getString(R.string.me); 348 sMeStringLocale = locale; 349 } 350 return sMeString; 351 } 352 353 private static void formatDefault(ConversationItemViewModel header, String sendersString, 354 Context context) { 355 getSenderResources(context); 356 // Clear any existing sender fragments; we must re-make all of them. 357 header.senderFragments.clear(); 358 String[] senders = TextUtils.split(sendersString, Address.ADDRESS_DELIMETER); 359 String[] namesOnly = new String[senders.length]; 360 Rfc822Token[] senderTokens; 361 String display; 362 for (int i = 0; i < senders.length; i++) { 363 senderTokens = Rfc822Tokenizer.tokenize(senders[i]); 364 if (senderTokens != null && senderTokens.length > 0) { 365 display = senderTokens[0].getName(); 366 if (TextUtils.isEmpty(display)) { 367 display = senderTokens[0].getAddress(); 368 } 369 namesOnly[i] = display; 370 } 371 } 372 generateSenderFragments(header, namesOnly); 373 } 374 375 private static void generateSenderFragments(ConversationItemViewModel header, String[] names) { 376 header.sendersText = TextUtils.join(Address.ADDRESS_DELIMETER + " ", names); 377 header.addSenderFragment(0, header.sendersText.length(), getReadStyleSpan(), true); 378 } 379 380 public static void formatSenders(ConversationItemViewModel header, Context context) { 381 formatDefault(header, header.conversation.senders, context); 382 } 383} 384