From 12d1097a2443a2d233af92910b198a6377ce0683 Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Sun, 6 Feb 2011 17:09:48 -0500 Subject: [PATCH] Big, scary massive "ant astyle" to get us back to something approximating AOSP coding standards. --- src/com/fsck/k9/Account.java | 736 ++--- src/com/fsck/k9/AccountStats.java | 3 +- src/com/fsck/k9/BaseAccount.java | 3 +- src/com/fsck/k9/EmailAddressAdapter.java | 21 +- src/com/fsck/k9/EmailAddressValidator.java | 12 +- src/com/fsck/k9/EmailReceivedIntent.java | 3 +- src/com/fsck/k9/FontSizes.java | 169 +- src/com/fsck/k9/Identity.java | 42 +- src/com/fsck/k9/K9.java | 420 +-- src/com/fsck/k9/NotificationSetting.java | 99 +- src/com/fsck/k9/Preferences.java | 100 +- src/com/fsck/k9/SearchAccount.java | 74 +- src/com/fsck/k9/SearchSpecification.java | 3 +- .../AccessibleEmailContentActivity.java | 35 +- src/com/fsck/k9/activity/Accounts.java | 694 ++-- .../fsck/k9/activity/ActivityListener.java | 92 +- src/com/fsck/k9/activity/ChooseAccount.java | 89 +- src/com/fsck/k9/activity/ChooseFolder.java | 238 +- src/com/fsck/k9/activity/ChooseIdentity.java | 34 +- .../fsck/k9/activity/ColorPickerDialog.java | 63 +- src/com/fsck/k9/activity/EditIdentity.java | 61 +- .../fsck/k9/activity/FolderInfoHolder.java | 84 +- src/com/fsck/k9/activity/FolderList.java | 909 ++---- .../fsck/k9/activity/FolderListFilter.java | 50 +- .../k9/activity/InsertableHtmlContent.java | 49 +- src/com/fsck/k9/activity/K9Activity.java | 92 +- .../k9/activity/K9ExpandableListActivity.java | 6 +- src/com/fsck/k9/activity/K9ListActivity.java | 87 +- .../k9/activity/K9PreferenceActivity.java | 21 +- .../fsck/k9/activity/LauncherShortcuts.java | 53 +- .../fsck/k9/activity/ManageIdentities.java | 133 +- src/com/fsck/k9/activity/MessageCompose.java | 1505 +++------ .../fsck/k9/activity/MessageInfoHolder.java | 21 +- src/com/fsck/k9/activity/MessageList.java | 2323 +++++--------- .../fsck/k9/activity/MessageReference.java | 62 +- src/com/fsck/k9/activity/MessageView.java | 1288 +++----- .../fsck/k9/activity/ProgressListener.java | 3 +- src/com/fsck/k9/activity/Search.java | 3 +- src/com/fsck/k9/activity/SearchModifier.java | 6 +- .../k9/activity/setup/AccountSettings.java | 385 +-- .../setup/AccountSetupAccountType.java | 66 +- .../k9/activity/setup/AccountSetupBasics.java | 210 +- .../setup/AccountSetupCheckSettings.java | 185 +- .../setup/AccountSetupComposition.java | 53 +- .../activity/setup/AccountSetupIncoming.java | 244 +- .../k9/activity/setup/AccountSetupNames.java | 48 +- .../activity/setup/AccountSetupOptions.java | 54 +- .../activity/setup/AccountSetupOutgoing.java | 165 +- .../k9/activity/setup/FolderSettings.java | 65 +- .../k9/activity/setup/FontSizeSettings.java | 18 +- src/com/fsck/k9/activity/setup/Prefs.java | 93 +- .../fsck/k9/activity/setup/SpinnerHelper.java | 53 +- .../fsck/k9/activity/setup/SpinnerOption.java | 18 +- .../k9/controller/MessageDateComparator.java | 23 +- .../k9/controller/MessageRemovalListener.java | 3 +- .../controller/MessageRetrievalListener.java | 3 +- .../k9/controller/MessagingController.java | 2835 ++++++----------- .../MessagingControllerPushReceiver.java | 69 +- .../fsck/k9/controller/MessagingListener.java | 135 +- src/com/fsck/k9/crypto/Apg.java | 296 +- src/com/fsck/k9/crypto/CryptoProvider.java | 9 +- src/com/fsck/k9/crypto/None.java | 42 +- src/com/fsck/k9/crypto/PgpData.java | 51 +- src/com/fsck/k9/helper/AutoSyncHelper.java | 56 +- src/com/fsck/k9/helper/AutoSyncSdk3.java | 23 +- src/com/fsck/k9/helper/AutoSyncSdk4.java | 23 +- src/com/fsck/k9/helper/AutoSyncSdk5.java | 9 +- src/com/fsck/k9/helper/Contacts.java | 54 +- src/com/fsck/k9/helper/ContactsSdk3_4.java | 79 +- src/com/fsck/k9/helper/ContactsSdk5.java | 72 +- src/com/fsck/k9/helper/ContactsSdk5p.java | 28 +- src/com/fsck/k9/helper/DateFormatter.java | 50 +- src/com/fsck/k9/helper/DomainNameChecker.java | 176 +- src/com/fsck/k9/helper/HtmlConverter.java | 1808 +++++------ src/com/fsck/k9/helper/IAutoSync.java | 3 +- .../fsck/k9/helper/MediaScannerNotifier.java | 22 +- src/com/fsck/k9/helper/MessageHelper.java | 49 +- src/com/fsck/k9/helper/Regex.java | 21 +- src/com/fsck/k9/helper/SizeFormatter.java | 15 +- src/com/fsck/k9/helper/Utility.java | 319 +- .../k9/helper/power/TracingPowerManager.java | 118 +- src/com/fsck/k9/mail/Address.java | 218 +- .../mail/AuthenticationFailedException.java | 9 +- src/com/fsck/k9/mail/Body.java | 3 +- src/com/fsck/k9/mail/BodyPart.java | 9 +- .../mail/CertificateValidationException.java | 9 +- src/com/fsck/k9/mail/FetchProfile.java | 6 +- src/com/fsck/k9/mail/Flag.java | 3 +- src/com/fsck/k9/mail/Folder.java | 78 +- src/com/fsck/k9/mail/Message.java | 82 +- src/com/fsck/k9/mail/MessagingException.java | 21 +- src/com/fsck/k9/mail/Multipart.java | 52 +- src/com/fsck/k9/mail/Part.java | 3 +- src/com/fsck/k9/mail/PushReceiver.java | 3 +- src/com/fsck/k9/mail/Pusher.java | 3 +- src/com/fsck/k9/mail/Store.java | 64 +- src/com/fsck/k9/mail/Transport.java | 17 +- src/com/fsck/k9/mail/filter/Base64.java | 306 +- .../k9/mail/filter/Base64OutputStream.java | 65 +- .../k9/mail/filter/CountingOutputStream.java | 12 +- .../filter/EOLConvertingOutputStream.java | 21 +- .../mail/filter/FixedLengthInputStream.java | 42 +- .../k9/mail/filter/LineWrapOutputStream.java | 41 +- .../k9/mail/filter/PeekableInputStream.java | 45 +- .../fsck/k9/mail/filter/SmtpDataStuffing.java | 24 +- .../k9/mail/filter/StatusOutputStream.java | 15 +- .../k9/mail/internet/BinaryTempFileBody.java | 37 +- .../fsck/k9/mail/internet/DecoderUtil.java | 99 +- .../Iso2022JpToShiftJisInputStream.java | 61 +- .../fsck/k9/mail/internet/MimeBodyPart.java | 100 +- src/com/fsck/k9/mail/internet/MimeHeader.java | 84 +- .../fsck/k9/mail/internet/MimeMessage.java | 393 +-- .../fsck/k9/mail/internet/MimeMultipart.java | 52 +- .../fsck/k9/mail/internet/MimeUtility.java | 2208 ++++++------- src/com/fsck/k9/mail/internet/TextBody.java | 57 +- .../k9/mail/store/ImapResponseParser.java | 415 +-- src/com/fsck/k9/mail/store/ImapStore.java | 2049 ++++-------- src/com/fsck/k9/mail/store/LocalStore.java | 2349 +++++--------- .../fsck/k9/mail/store/LockableDatabase.java | 276 +- src/com/fsck/k9/mail/store/Pop3Store.java | 635 ++-- .../fsck/k9/mail/store/StorageManager.java | 250 +- .../k9/mail/store/TrustManagerFactory.java | 166 +- .../store/UnavailableAccountException.java | 15 +- .../store/UnavailableStorageException.java | 15 +- src/com/fsck/k9/mail/store/WebDavStore.java | 1172 +++---- .../fsck/k9/mail/transport/SmtpTransport.java | 319 +- .../mail/transport/TrustedSocketFactory.java | 21 +- .../k9/mail/transport/WebDavTransport.java | 22 +- .../k9/mail/transport/imap/ImapSettings.java | 3 +- .../preferences/CheckBoxListPreference.java | 33 +- src/com/fsck/k9/preferences/Editor.java | 89 +- src/com/fsck/k9/preferences/Storage.java | 237 +- .../k9/preferences/TimePickerPreference.java | 49 +- .../fsck/k9/provider/AttachmentProvider.java | 167 +- src/com/fsck/k9/provider/MessageProvider.java | 494 +-- .../k9/remotecontrol/AccountReceiver.java | 15 +- .../k9/remotecontrol/K9AccountReceptor.java | 3 +- .../k9/remotecontrol/K9RemoteControl.java | 9 +- src/com/fsck/k9/service/BootReceiver.java | 67 +- src/com/fsck/k9/service/CoreReceiver.java | 45 +- src/com/fsck/k9/service/CoreService.java | 85 +- src/com/fsck/k9/service/MailService.java | 284 +- src/com/fsck/k9/service/PollService.java | 73 +- src/com/fsck/k9/service/PushService.java | 22 +- .../k9/service/RemoteControlReceiver.java | 23 +- .../fsck/k9/service/RemoteControlService.java | 87 +- src/com/fsck/k9/service/ShutdownReceiver.java | 9 +- src/com/fsck/k9/service/SleepService.java | 84 +- .../fsck/k9/service/StorageGoneReceiver.java | 19 +- src/com/fsck/k9/service/StorageReceiver.java | 15 +- src/com/fsck/k9/view/AccessibleWebView.java | 42 +- src/com/fsck/k9/view/AttachmentView.java | 143 +- src/com/fsck/k9/view/ColorChip.java | 20 +- src/com/fsck/k9/view/ColorPickerBox.java | 21 +- src/com/fsck/k9/view/MessageHeader.java | 128 +- src/com/fsck/k9/view/MessageWebView.java | 53 +- src/com/fsck/k9/view/ToggleScrollView.java | 41 +- 157 files changed, 11287 insertions(+), 20753 deletions(-) diff --git a/src/com/fsck/k9/Account.java b/src/com/fsck/k9/Account.java index e70af5890..cf8a9be84 100644 --- a/src/com/fsck/k9/Account.java +++ b/src/com/fsck/k9/Account.java @@ -32,8 +32,7 @@ import java.util.concurrent.ConcurrentHashMap; * Account stores all of the settings for a single account defined by the user. It is able to save * and delete itself given a Preferences to work with. Each account is defined by a UUID. */ -public class Account implements BaseAccount -{ +public class Account implements BaseAccount { public static final String EXPUNGE_IMMEDIATELY = "EXPUNGE_IMMEDIATELY"; public static final String EXPUNGE_MANUALLY = "EXPUNGE_MANUALLY"; public static final String EXPUNGE_ON_POLL = "EXPUNGE_ON_POLL"; @@ -136,38 +135,31 @@ public class Account implements BaseAccount private NotificationSetting mNotificationSetting = new NotificationSetting(); - public enum FolderMode - { + public enum FolderMode { NONE, ALL, FIRST_CLASS, FIRST_AND_SECOND_CLASS, NOT_SECOND_CLASS } - public enum ScrollButtons - { + public enum ScrollButtons { NEVER, ALWAYS, KEYBOARD_AVAILABLE } - public enum ShowPictures - { + public enum ShowPictures { NEVER, ALWAYS, ONLY_FROM_CONTACTS } - public enum Searchable - { + public enum Searchable { ALL, DISPLAYABLE, NONE } - public enum QuoteStyle - { + public enum QuoteStyle { PREFIX, HEADER } - public enum MessageFormat - { + public enum MessageFormat { TEXT, HTML } - protected Account(Context context) - { + protected Account(Context context) { mUuid = UUID.randomUUID().toString(); mLocalStorageProviderId = StorageManager.getInstance(K9.app).getDefaultProviderId(); mAutomaticCheckIntervalMinutes = -1; @@ -224,8 +216,7 @@ public class Account implements BaseAccount mNotificationSetting.setLedColor(mChipColor); } - protected Account(Preferences preferences, String uuid) - { + protected Account(Preferences preferences, String uuid) { this.mUuid = uuid; loadAccount(preferences); } @@ -233,8 +224,7 @@ public class Account implements BaseAccount /** * Load stored settings for this account. */ - private synchronized void loadAccount(Preferences preferences) - { + private synchronized void loadAccount(Preferences preferences) { SharedPreferences prefs = preferences.getPreferences(); @@ -248,12 +238,11 @@ public class Account implements BaseAccount mSaveAllHeaders = prefs.getBoolean(mUuid + ".saveAllHeaders", true); mPushPollOnConnect = prefs.getBoolean(mUuid + ".pushPollOnConnect", true); mDisplayCount = prefs.getInt(mUuid + ".displayCount", K9.DEFAULT_VISIBLE_LIMIT); - if (mDisplayCount < 0) - { + if (mDisplayCount < 0) { mDisplayCount = K9.DEFAULT_VISIBLE_LIMIT; } mLastAutomaticCheckTime = prefs.getLong(mUuid + ".lastAutomaticCheckTime", 0); - mLatestOldMessageSeenTime = prefs.getLong(mUuid +".latestOldMessageSeenTime",0); + mLatestOldMessageSeenTime = prefs.getLong(mUuid + ".latestOldMessageSeenTime", 0); mNotifyNewMail = prefs.getBoolean(mUuid + ".notifyNewMail", false); mNotifySelfNewMail = prefs.getBoolean(mUuid + ".notifySelfNewMail", true); mNotifySync = prefs.getBoolean(mUuid + ".notifyMailCheck", false); @@ -277,8 +266,7 @@ public class Account implements BaseAccount mQuoteStyle = QuoteStyle.valueOf(prefs.getString(mUuid + ".quoteStyle", DEFAULT_QUOTE_STYLE.name())); mQuotePrefix = prefs.getString(mUuid + ".quotePrefix", DEFAULT_QUOTE_PREFIX); mReplyAfterQuote = prefs.getBoolean(mUuid + ".replyAfterQuote", DEFAULT_REPLY_AFTER_QUOTE); - for (String type : networkTypes) - { + for (String type : networkTypes) { Boolean useCompression = prefs.getBoolean(mUuid + ".useCompression." + type, true); compressionMap.put(type, useCompression); @@ -289,41 +277,32 @@ public class Account implements BaseAccount mAccountNumber = prefs.getInt(mUuid + ".accountNumber", 0); - Random random = new Random((long)mAccountNumber+4); + Random random = new Random((long)mAccountNumber + 4); - mChipColor = prefs.getInt(mUuid+".chipColor", + mChipColor = prefs.getInt(mUuid + ".chipColor", (random.nextInt(0x70)) + (random.nextInt(0x70) * 0xff) + (random.nextInt(0x70) * 0xffff) + 0xff000000); - try - { + try { mScrollMessageViewButtons = ScrollButtons.valueOf(prefs.getString(mUuid + ".hideButtonsEnum", ScrollButtons.NEVER.name())); - } - catch (Exception e) - { + } catch (Exception e) { mScrollMessageViewButtons = ScrollButtons.NEVER; } - try - { + try { mScrollMessageViewMoveButtons = ScrollButtons.valueOf(prefs.getString(mUuid + ".hideMoveButtonsEnum", ScrollButtons.NEVER.name())); - } - catch (Exception e) - { + } catch (Exception e) { mScrollMessageViewMoveButtons = ScrollButtons.NEVER; } - try - { + try { mShowPictures = ShowPictures.valueOf(prefs.getString(mUuid + ".showPicturesEnum", ShowPictures.NEVER.name())); - } - catch (Exception e) - { + } catch (Exception e) { mShowPictures = ShowPictures.NEVER; } @@ -336,55 +315,40 @@ public class Account implements BaseAccount mNotificationSetting.setRingtone(prefs.getString(mUuid + ".ringtone", "content://settings/system/notification_sound")); mNotificationSetting.setLed(prefs.getBoolean(mUuid + ".led", true)); - mNotificationSetting.setLedColor(prefs.getInt(mUuid+".ledColor", mChipColor)); + mNotificationSetting.setLedColor(prefs.getInt(mUuid + ".ledColor", mChipColor)); - try - { + try { mFolderDisplayMode = FolderMode.valueOf(prefs.getString(mUuid + ".folderDisplayMode", FolderMode.NOT_SECOND_CLASS.name())); - } - catch (Exception e) - { + } catch (Exception e) { mFolderDisplayMode = FolderMode.NOT_SECOND_CLASS; } - try - { + try { mFolderSyncMode = FolderMode.valueOf(prefs.getString(mUuid + ".folderSyncMode", FolderMode.FIRST_CLASS.name())); - } - catch (Exception e) - { + } catch (Exception e) { mFolderSyncMode = FolderMode.FIRST_CLASS; } - try - { + try { mFolderPushMode = FolderMode.valueOf(prefs.getString(mUuid + ".folderPushMode", FolderMode.FIRST_CLASS.name())); - } - catch (Exception e) - { + } catch (Exception e) { mFolderPushMode = FolderMode.FIRST_CLASS; } - try - { + try { mFolderTargetMode = FolderMode.valueOf(prefs.getString(mUuid + ".folderTargetMode", FolderMode.NOT_SECOND_CLASS.name())); - } - catch (Exception e) - { + } catch (Exception e) { mFolderTargetMode = FolderMode.NOT_SECOND_CLASS; } - try - { + try { searchableFolders = Searchable.valueOf(prefs.getString(mUuid + ".searchableFolders", Searchable.ALL.name())); - } - catch (Exception e) - { + } catch (Exception e) { searchableFolders = Searchable.ALL; } @@ -396,16 +360,12 @@ public class Account implements BaseAccount } - protected synchronized void delete(Preferences preferences) - { + protected synchronized void delete(Preferences preferences) { String[] uuids = preferences.getPreferences().getString("accountUuids", "").split(","); StringBuffer sb = new StringBuffer(); - for (int i = 0, length = uuids.length; i < length; i++) - { - if (!uuids[i].equals(mUuid)) - { - if (sb.length() > 0) - { + for (int i = 0, length = uuids.length; i < length; i++) { + if (!uuids[i].equals(mUuid)) { + if (sb.length() > 0) { sb.append(','); } sb.append(uuids[i]); @@ -471,20 +431,17 @@ public class Account implements BaseAccount editor.remove(mUuid + ".cryptoAutoSignature"); editor.remove(mUuid + ".enableMoveButtons"); editor.remove(mUuid + ".hideMoveButtonsEnum"); - for (String type : networkTypes) - { + for (String type : networkTypes) { editor.remove(mUuid + ".useCompression." + type); } deleteIdentities(preferences.getPreferences(), editor); editor.commit(); } - public synchronized void save(Preferences preferences) - { + public synchronized void save(Preferences preferences) { SharedPreferences.Editor editor = preferences.getPreferences().edit(); - if (!preferences.getPreferences().getString("accountUuids", "").contains(mUuid)) - { + if (!preferences.getPreferences().getString("accountUuids", "").contains(mUuid)) { /* * When the account is first created we assign it a unique account number. The * account number will be unique to that account for the lifetime of the account. @@ -498,15 +455,12 @@ public class Account implements BaseAccount */ Account[] accounts = preferences.getAccounts(); int[] accountNumbers = new int[accounts.length]; - for (int i = 0; i < accounts.length; i++) - { + for (int i = 0; i < accounts.length; i++) { accountNumbers[i] = accounts[i].getAccountNumber(); } Arrays.sort(accountNumbers); - for (int accountNumber : accountNumbers) - { - if (accountNumber > mAccountNumber + 1) - { + for (int accountNumber : accountNumbers) { + if (accountNumber > mAccountNumber + 1) { break; } mAccountNumber = accountNumber; @@ -576,11 +530,9 @@ public class Account implements BaseAccount editor.putBoolean(mUuid + ".led", mNotificationSetting.isLed()); editor.putInt(mUuid + ".ledColor", mNotificationSetting.getLedColor()); - for (String type : networkTypes) - { + for (String type : networkTypes) { Boolean useCompression = compressionMap.get(type); - if (useCompression != null) - { + if (useCompression != null) { editor.putBoolean(mUuid + ".useCompression." + type, useCompression); } } @@ -590,14 +542,10 @@ public class Account implements BaseAccount } - public void resetVisibleLimits() - { - try - { + public void resetVisibleLimits() { + try { getLocalStore().resetVisibleLimits(getDisplayCount()); - } - catch (MessagingException e) - { + } catch (MessagingException e) { Log.e(K9.LOG_TAG, "Unable to reset visible limits", e); } @@ -609,17 +557,14 @@ public class Account implements BaseAccount * @throws MessagingException * @see {@link #isAvailable(Context)} */ - public AccountStats getStats(Context context) throws MessagingException - { - if (!isAvailable(context)) - { + public AccountStats getStats(Context context) throws MessagingException { + if (!isAvailable(context)) { return null; } long startTime = System.currentTimeMillis(); AccountStats stats = new AccountStats(); LocalStore localStore = getLocalStore(); - if (K9.measureAccounts()) - { + if (K9.measureAccounts()) { stats.size = localStore.getSize(); } localStore.getMessageCounts(stats); @@ -630,149 +575,117 @@ public class Account implements BaseAccount } - public synchronized void setChipColor(int color) - { + public synchronized void setChipColor(int color) { mChipColor = color; } - public synchronized int getChipColor() - { + public synchronized int getChipColor() { return mChipColor; } - public ColorChip generateColorChip() - { - return new ColorChip( mChipColor); + public ColorChip generateColorChip() { + return new ColorChip(mChipColor); } - public String getUuid() - { + public String getUuid() { return mUuid; } - public Uri getContentUri() - { + public Uri getContentUri() { return Uri.parse("content://accounts/" + getUuid()); } - public synchronized String getStoreUri() - { + public synchronized String getStoreUri() { return mStoreUri; } - public synchronized void setStoreUri(String storeUri) - { + public synchronized void setStoreUri(String storeUri) { this.mStoreUri = storeUri; } - public synchronized String getTransportUri() - { + public synchronized String getTransportUri() { return mTransportUri; } - public synchronized void setTransportUri(String transportUri) - { + public synchronized void setTransportUri(String transportUri) { this.mTransportUri = transportUri; } - public synchronized String getDescription() - { + public synchronized String getDescription() { return mDescription; } - public synchronized void setDescription(String description) - { + public synchronized void setDescription(String description) { this.mDescription = description; } - public synchronized String getName() - { + public synchronized String getName() { return identities.get(0).getName(); } - public synchronized void setName(String name) - { + public synchronized void setName(String name) { identities.get(0).setName(name); } - public synchronized boolean getSignatureUse() - { + public synchronized boolean getSignatureUse() { return identities.get(0).getSignatureUse(); } - public synchronized void setSignatureUse(boolean signatureUse) - { + public synchronized void setSignatureUse(boolean signatureUse) { identities.get(0).setSignatureUse(signatureUse); } - public synchronized String getSignature() - { + public synchronized String getSignature() { return identities.get(0).getSignature(); } - public synchronized void setSignature(String signature) - { + public synchronized void setSignature(String signature) { identities.get(0).setSignature(signature); } - public synchronized String getEmail() - { + public synchronized String getEmail() { return identities.get(0).getEmail(); } - public synchronized void setEmail(String email) - { + public synchronized void setEmail(String email) { identities.get(0).setEmail(email); } - public synchronized String getAlwaysBcc() - { + public synchronized String getAlwaysBcc() { return mAlwaysBcc; } - public synchronized void setAlwaysBcc(String alwaysBcc) - { + public synchronized void setAlwaysBcc(String alwaysBcc) { this.mAlwaysBcc = alwaysBcc; } /* Have we sent a new mail notification on this account */ - public boolean isRingNotified() - { + public boolean isRingNotified() { return mRingNotified; } - public void setRingNotified(boolean ringNotified) - { + public void setRingNotified(boolean ringNotified) { mRingNotified = ringNotified; } - public String getLocalStorageProviderId() - { + public String getLocalStorageProviderId() { return mLocalStorageProviderId; } - public void setLocalStorageProviderId(String id) - { + public void setLocalStorageProviderId(String id) { - if (!mLocalStorageProviderId.equals(id)) - { + if (!mLocalStorageProviderId.equals(id)) { boolean successful = false; - try - { + try { switchLocalStorage(id); successful = true; - } - catch (MessagingException e) - { - } - finally - { + } catch (MessagingException e) { + } finally { // if migration to/from SD-card failed once, it will fail again. - if (!successful) - { + if (!successful) { return; } } @@ -790,394 +703,318 @@ public class Account implements BaseAccount /** * Returns -1 for never. */ - public synchronized int getAutomaticCheckIntervalMinutes() - { + public synchronized int getAutomaticCheckIntervalMinutes() { return mAutomaticCheckIntervalMinutes; } /** * @param automaticCheckIntervalMinutes or -1 for never. */ - public synchronized boolean setAutomaticCheckIntervalMinutes(int automaticCheckIntervalMinutes) - { + public synchronized boolean setAutomaticCheckIntervalMinutes(int automaticCheckIntervalMinutes) { int oldInterval = this.mAutomaticCheckIntervalMinutes; this.mAutomaticCheckIntervalMinutes = automaticCheckIntervalMinutes; return (oldInterval != automaticCheckIntervalMinutes); } - public synchronized int getDisplayCount() - { + public synchronized int getDisplayCount() { return mDisplayCount; } - public synchronized void setDisplayCount(int displayCount) - { - if (displayCount != -1) - { + public synchronized void setDisplayCount(int displayCount) { + if (displayCount != -1) { this.mDisplayCount = displayCount; - } - else - { + } else { this.mDisplayCount = K9.DEFAULT_VISIBLE_LIMIT; } resetVisibleLimits(); } - public synchronized long getLastAutomaticCheckTime() - { + public synchronized long getLastAutomaticCheckTime() { return mLastAutomaticCheckTime; } - public synchronized void setLastAutomaticCheckTime(long lastAutomaticCheckTime) - { + public synchronized void setLastAutomaticCheckTime(long lastAutomaticCheckTime) { this.mLastAutomaticCheckTime = lastAutomaticCheckTime; } - public synchronized long getLatestOldMessageSeenTime() - { + public synchronized long getLatestOldMessageSeenTime() { return mLatestOldMessageSeenTime; } - public synchronized void setLatestOldMessageSeenTime(long latestOldMessageSeenTime) - { + public synchronized void setLatestOldMessageSeenTime(long latestOldMessageSeenTime) { this.mLatestOldMessageSeenTime = latestOldMessageSeenTime; } - public synchronized boolean isNotifyNewMail() - { + public synchronized boolean isNotifyNewMail() { return mNotifyNewMail; } - public synchronized void setNotifyNewMail(boolean notifyNewMail) - { + public synchronized void setNotifyNewMail(boolean notifyNewMail) { this.mNotifyNewMail = notifyNewMail; } - public synchronized int getDeletePolicy() - { + public synchronized int getDeletePolicy() { return mDeletePolicy; } - public synchronized void setDeletePolicy(int deletePolicy) - { + public synchronized void setDeletePolicy(int deletePolicy) { this.mDeletePolicy = deletePolicy; } - public boolean isSpecialFolder(String folderName) - { - if ( folderName != null && (folderName.equalsIgnoreCase(K9.INBOX) || - folderName.equals(getTrashFolderName()) || - folderName.equals(getDraftsFolderName()) || - folderName.equals(getArchiveFolderName()) || - folderName.equals(getSpamFolderName()) || - folderName.equals(getOutboxFolderName()) || - folderName.equals(getSentFolderName()) || - folderName.equals(getErrorFolderName()))) - { + public boolean isSpecialFolder(String folderName) { + if (folderName != null && (folderName.equalsIgnoreCase(K9.INBOX) || + folderName.equals(getTrashFolderName()) || + folderName.equals(getDraftsFolderName()) || + folderName.equals(getArchiveFolderName()) || + folderName.equals(getSpamFolderName()) || + folderName.equals(getOutboxFolderName()) || + folderName.equals(getSentFolderName()) || + folderName.equals(getErrorFolderName()))) { return true; - } - else - { + } else { return false; } } - public synchronized String getDraftsFolderName() - { + public synchronized String getDraftsFolderName() { return mDraftsFolderName; } - public synchronized void setDraftsFolderName(String draftsFolderName) - { + public synchronized void setDraftsFolderName(String draftsFolderName) { mDraftsFolderName = draftsFolderName; } - public synchronized String getSentFolderName() - { + public synchronized String getSentFolderName() { return mSentFolderName; } - public synchronized String getErrorFolderName() - { + public synchronized String getErrorFolderName() { return K9.ERROR_FOLDER_NAME; } - public synchronized void setSentFolderName(String sentFolderName) - { + public synchronized void setSentFolderName(String sentFolderName) { mSentFolderName = sentFolderName; } - public synchronized String getTrashFolderName() - { + public synchronized String getTrashFolderName() { return mTrashFolderName; } - public synchronized void setTrashFolderName(String trashFolderName) - { + public synchronized void setTrashFolderName(String trashFolderName) { mTrashFolderName = trashFolderName; } - public synchronized String getArchiveFolderName() - { + public synchronized String getArchiveFolderName() { return mArchiveFolderName; } - public synchronized void setArchiveFolderName(String archiveFolderName) - { + public synchronized void setArchiveFolderName(String archiveFolderName) { mArchiveFolderName = archiveFolderName; } - public synchronized String getSpamFolderName() - { + public synchronized String getSpamFolderName() { return mSpamFolderName; } - public synchronized void setSpamFolderName(String spamFolderName) - { + public synchronized void setSpamFolderName(String spamFolderName) { mSpamFolderName = spamFolderName; } - public synchronized String getOutboxFolderName() - { + public synchronized String getOutboxFolderName() { return mOutboxFolderName; } - public synchronized void setOutboxFolderName(String outboxFolderName) - { + public synchronized void setOutboxFolderName(String outboxFolderName) { mOutboxFolderName = outboxFolderName; } - public synchronized String getAutoExpandFolderName() - { + public synchronized String getAutoExpandFolderName() { return mAutoExpandFolderName; } - public synchronized void setAutoExpandFolderName(String autoExpandFolderName) - { + public synchronized void setAutoExpandFolderName(String autoExpandFolderName) { mAutoExpandFolderName = autoExpandFolderName; } - public synchronized int getAccountNumber() - { + public synchronized int getAccountNumber() { return mAccountNumber; } - public synchronized FolderMode getFolderDisplayMode() - { + public synchronized FolderMode getFolderDisplayMode() { return mFolderDisplayMode; } - public synchronized boolean setFolderDisplayMode(FolderMode displayMode) - { + public synchronized boolean setFolderDisplayMode(FolderMode displayMode) { FolderMode oldDisplayMode = mFolderDisplayMode; mFolderDisplayMode = displayMode; return oldDisplayMode != displayMode; } - public synchronized FolderMode getFolderSyncMode() - { + public synchronized FolderMode getFolderSyncMode() { return mFolderSyncMode; } - public synchronized boolean setFolderSyncMode(FolderMode syncMode) - { + public synchronized boolean setFolderSyncMode(FolderMode syncMode) { FolderMode oldSyncMode = mFolderSyncMode; mFolderSyncMode = syncMode; - if (syncMode == FolderMode.NONE && oldSyncMode != FolderMode.NONE) - { + if (syncMode == FolderMode.NONE && oldSyncMode != FolderMode.NONE) { return true; } - if (syncMode != FolderMode.NONE && oldSyncMode == FolderMode.NONE) - { + if (syncMode != FolderMode.NONE && oldSyncMode == FolderMode.NONE) { return true; } return false; } - public synchronized FolderMode getFolderPushMode() - { + public synchronized FolderMode getFolderPushMode() { return mFolderPushMode; } - public synchronized boolean setFolderPushMode(FolderMode pushMode) - { + public synchronized boolean setFolderPushMode(FolderMode pushMode) { FolderMode oldPushMode = mFolderPushMode; mFolderPushMode = pushMode; return pushMode != oldPushMode; } - public synchronized boolean isShowOngoing() - { + public synchronized boolean isShowOngoing() { return mNotifySync; } - public synchronized void setShowOngoing(boolean showOngoing) - { + public synchronized void setShowOngoing(boolean showOngoing) { this.mNotifySync = showOngoing; } - public synchronized ScrollButtons getScrollMessageViewButtons() - { + public synchronized ScrollButtons getScrollMessageViewButtons() { return mScrollMessageViewButtons; } - public synchronized void setScrollMessageViewButtons(ScrollButtons scrollMessageViewButtons) - { + public synchronized void setScrollMessageViewButtons(ScrollButtons scrollMessageViewButtons) { mScrollMessageViewButtons = scrollMessageViewButtons; } - public synchronized ScrollButtons getScrollMessageViewMoveButtons() - { + public synchronized ScrollButtons getScrollMessageViewMoveButtons() { return mScrollMessageViewMoveButtons; } - public synchronized void setScrollMessageViewMoveButtons(ScrollButtons scrollMessageViewButtons) - { + public synchronized void setScrollMessageViewMoveButtons(ScrollButtons scrollMessageViewButtons) { mScrollMessageViewMoveButtons = scrollMessageViewButtons; } - public synchronized ShowPictures getShowPictures() - { + public synchronized ShowPictures getShowPictures() { return mShowPictures; } - public synchronized void setShowPictures(ShowPictures showPictures) - { + public synchronized void setShowPictures(ShowPictures showPictures) { mShowPictures = showPictures; } - public synchronized FolderMode getFolderTargetMode() - { + public synchronized FolderMode getFolderTargetMode() { return mFolderTargetMode; } - public synchronized void setFolderTargetMode(FolderMode folderTargetMode) - { + public synchronized void setFolderTargetMode(FolderMode folderTargetMode) { mFolderTargetMode = folderTargetMode; } - public synchronized boolean isSignatureBeforeQuotedText() - { + public synchronized boolean isSignatureBeforeQuotedText() { return mIsSignatureBeforeQuotedText; } - public synchronized void setSignatureBeforeQuotedText(boolean mIsSignatureBeforeQuotedText) - { + public synchronized void setSignatureBeforeQuotedText(boolean mIsSignatureBeforeQuotedText) { this.mIsSignatureBeforeQuotedText = mIsSignatureBeforeQuotedText; } - public synchronized boolean isNotifySelfNewMail() - { + public synchronized boolean isNotifySelfNewMail() { return mNotifySelfNewMail; } - public synchronized void setNotifySelfNewMail(boolean notifySelfNewMail) - { + public synchronized void setNotifySelfNewMail(boolean notifySelfNewMail) { mNotifySelfNewMail = notifySelfNewMail; } - public synchronized String getExpungePolicy() - { + public synchronized String getExpungePolicy() { return mExpungePolicy; } - public synchronized void setExpungePolicy(String expungePolicy) - { + public synchronized void setExpungePolicy(String expungePolicy) { mExpungePolicy = expungePolicy; } - public synchronized int getMaxPushFolders() - { + public synchronized int getMaxPushFolders() { return mMaxPushFolders; } - public synchronized boolean setMaxPushFolders(int maxPushFolders) - { + public synchronized boolean setMaxPushFolders(int maxPushFolders) { int oldMaxPushFolders = mMaxPushFolders; mMaxPushFolders = maxPushFolders; return oldMaxPushFolders != maxPushFolders; } - public LocalStore getLocalStore() throws MessagingException - { + public LocalStore getLocalStore() throws MessagingException { return Store.getLocalInstance(this, K9.app); } - public Store getRemoteStore() throws MessagingException - { + public Store getRemoteStore() throws MessagingException { return Store.getRemoteInstance(this); } @Override - public synchronized String toString() - { + public synchronized String toString() { return mDescription; } - public synchronized void setCompression(String networkType, boolean useCompression) - { + public synchronized void setCompression(String networkType, boolean useCompression) { compressionMap.put(networkType, useCompression); } - public synchronized boolean useCompression(String networkType) - { + public synchronized boolean useCompression(String networkType) { Boolean useCompression = compressionMap.get(networkType); - if (useCompression == null) - { + if (useCompression == null) { return true; - } - else - { + } else { return useCompression; } } - public boolean useCompression(int type) - { + public boolean useCompression(int type) { String networkType = TYPE_OTHER; - switch (type) - { - case ConnectivityManager.TYPE_MOBILE: - networkType = TYPE_MOBILE; - break; - case ConnectivityManager.TYPE_WIFI: - networkType = TYPE_WIFI; - break; + switch (type) { + case ConnectivityManager.TYPE_MOBILE: + networkType = TYPE_MOBILE; + break; + case ConnectivityManager.TYPE_WIFI: + networkType = TYPE_WIFI; + break; } return useCompression(networkType); } @Override - public boolean equals(Object o) - { - if (o instanceof Account) - { + public boolean equals(Object o) { + if (o instanceof Account) { return ((Account)o).mUuid.equals(mUuid); } return super.equals(o); } @Override - public int hashCode() - { + public int hashCode() { return mUuid.hashCode(); } - private synchronized List loadIdentities(SharedPreferences prefs) - { + private synchronized List loadIdentities(SharedPreferences prefs) { List newIdentities = new ArrayList(); int ident = 0; boolean gotOne = false; - do - { + do { gotOne = false; String name = prefs.getString(mUuid + ".name." + ident, null); String email = prefs.getString(mUuid + ".email." + ident, null); @@ -1185,8 +1022,7 @@ public class Account implements BaseAccount String signature = prefs.getString(mUuid + ".signature." + ident, null); String description = prefs.getString(mUuid + ".description." + ident, null); final String replyTo = prefs.getString(mUuid + ".replyTo." + ident, null); - if (email != null) - { + if (email != null) { Identity identity = new Identity(); identity.setName(name); identity.setEmail(email); @@ -1198,11 +1034,9 @@ public class Account implements BaseAccount gotOne = true; } ident++; - } - while (gotOne); + } while (gotOne); - if (newIdentities.size() == 0) - { + if (newIdentities.size() == 0) { String name = prefs.getString(mUuid + ".name", null); String email = prefs.getString(mUuid + ".email", null); boolean signatureUse = prefs.getBoolean(mUuid + ".signatureUse", true); @@ -1219,16 +1053,13 @@ public class Account implements BaseAccount return newIdentities; } - private synchronized void deleteIdentities(SharedPreferences prefs, SharedPreferences.Editor editor) - { + private synchronized void deleteIdentities(SharedPreferences prefs, SharedPreferences.Editor editor) { int ident = 0; boolean gotOne = false; - do - { + do { gotOne = false; String email = prefs.getString(mUuid + ".email." + ident, null); - if (email != null) - { + if (email != null) { editor.remove(mUuid + ".name." + ident); editor.remove(mUuid + ".email." + ident); editor.remove(mUuid + ".signatureUse." + ident); @@ -1238,17 +1069,14 @@ public class Account implements BaseAccount gotOne = true; } ident++; - } - while (gotOne); + } while (gotOne); } - private synchronized void saveIdentities(SharedPreferences prefs, SharedPreferences.Editor editor) - { + private synchronized void saveIdentities(SharedPreferences prefs, SharedPreferences.Editor editor) { deleteIdentities(prefs, editor); int ident = 0; - for (Identity identity : identities) - { + for (Identity identity : identities) { editor.putString(mUuid + ".name." + ident, identity.getName()); editor.putString(mUuid + ".email." + ident, identity.getEmail()); editor.putBoolean(mUuid + ".signatureUse." + ident, identity.getSignatureUse()); @@ -1259,35 +1087,27 @@ public class Account implements BaseAccount } } - public synchronized List getIdentities() - { + public synchronized List getIdentities() { return identities; } - public synchronized void setIdentities(List newIdentities) - { + public synchronized void setIdentities(List newIdentities) { identities = new ArrayList(newIdentities); } - public synchronized Identity getIdentity(int i) - { - if (i < identities.size()) - { + public synchronized Identity getIdentity(int i) { + if (i < identities.size()) { return identities.get(i); } return null; } - public boolean isAnIdentity(Address[] addrs) - { - if (addrs == null) - { + public boolean isAnIdentity(Address[] addrs) { + if (addrs == null) { return false; } - for (Address addr : addrs) - { - if (findIdentity(addr) != null) - { + for (Address addr : addrs) { + if (findIdentity(addr) != null) { return true; } } @@ -1295,61 +1115,49 @@ public class Account implements BaseAccount return false; } - public boolean isAnIdentity(Address addr) - { + public boolean isAnIdentity(Address addr) { return findIdentity(addr) != null; } - public synchronized Identity findIdentity(Address addr) - { - for (Identity identity : identities) - { + public synchronized Identity findIdentity(Address addr) { + for (Identity identity : identities) { String email = identity.getEmail(); - if (email != null && email.equalsIgnoreCase(addr.getAddress())) - { + if (email != null && email.equalsIgnoreCase(addr.getAddress())) { return identity; } } return null; } - public synchronized Searchable getSearchableFolders() - { + public synchronized Searchable getSearchableFolders() { return searchableFolders; } - public synchronized void setSearchableFolders(Searchable searchableFolders) - { + public synchronized void setSearchableFolders(Searchable searchableFolders) { this.searchableFolders = searchableFolders; } - public synchronized int getIdleRefreshMinutes() - { + public synchronized int getIdleRefreshMinutes() { return mIdleRefreshMinutes; } - public synchronized void setIdleRefreshMinutes(int idleRefreshMinutes) - { + public synchronized void setIdleRefreshMinutes(int idleRefreshMinutes) { mIdleRefreshMinutes = idleRefreshMinutes; } - public synchronized boolean isPushPollOnConnect() - { + public synchronized boolean isPushPollOnConnect() { return mPushPollOnConnect; } - public synchronized void setPushPollOnConnect(boolean pushPollOnConnect) - { + public synchronized void setPushPollOnConnect(boolean pushPollOnConnect) { mPushPollOnConnect = pushPollOnConnect; } - public synchronized boolean saveAllHeaders() - { + public synchronized boolean saveAllHeaders() { return mSaveAllHeaders; } - public synchronized void setSaveAllHeaders(boolean saveAllHeaders) - { + public synchronized void setSaveAllHeaders(boolean saveAllHeaders) { mSaveAllHeaders = saveAllHeaders; } @@ -1364,207 +1172,167 @@ public class Account implements BaseAccount * Never null. * @throws MessagingException */ - public void switchLocalStorage(final String newStorageProviderId) throws MessagingException - { - if (!mLocalStorageProviderId.equals(newStorageProviderId)) - { + public void switchLocalStorage(final String newStorageProviderId) throws MessagingException { + if (!mLocalStorageProviderId.equals(newStorageProviderId)) { getLocalStore().switchLocalStorage(newStorageProviderId); } } - public synchronized boolean goToUnreadMessageSearch() - { + public synchronized boolean goToUnreadMessageSearch() { return goToUnreadMessageSearch; } - public synchronized void setGoToUnreadMessageSearch(boolean goToUnreadMessageSearch) - { + public synchronized void setGoToUnreadMessageSearch(boolean goToUnreadMessageSearch) { this.goToUnreadMessageSearch = goToUnreadMessageSearch; } - public boolean isNotificationShowsUnreadCount() - { + public boolean isNotificationShowsUnreadCount() { return mNotificationShowsUnreadCount; } - public void setNotificationShowsUnreadCount(boolean notificationShowsUnreadCount) - { + public void setNotificationShowsUnreadCount(boolean notificationShowsUnreadCount) { this.mNotificationShowsUnreadCount = notificationShowsUnreadCount; } - public synchronized boolean subscribedFoldersOnly() - { + public synchronized boolean subscribedFoldersOnly() { return subscribedFoldersOnly; } - public synchronized void setSubscribedFoldersOnly(boolean subscribedFoldersOnly) - { + public synchronized void setSubscribedFoldersOnly(boolean subscribedFoldersOnly) { this.subscribedFoldersOnly = subscribedFoldersOnly; } - public synchronized int getMaximumPolledMessageAge() - { + public synchronized int getMaximumPolledMessageAge() { return maximumPolledMessageAge; } - public synchronized void setMaximumPolledMessageAge(int maximumPolledMessageAge) - { + public synchronized void setMaximumPolledMessageAge(int maximumPolledMessageAge) { this.maximumPolledMessageAge = maximumPolledMessageAge; } - public synchronized int getMaximumAutoDownloadMessageSize() - { + public synchronized int getMaximumAutoDownloadMessageSize() { return maximumAutoDownloadMessageSize; } - public synchronized void setMaximumAutoDownloadMessageSize(int maximumAutoDownloadMessageSize) - { + public synchronized void setMaximumAutoDownloadMessageSize(int maximumAutoDownloadMessageSize) { this.maximumAutoDownloadMessageSize = maximumAutoDownloadMessageSize; } - public Date getEarliestPollDate() - { + public Date getEarliestPollDate() { int age = getMaximumPolledMessageAge(); - if (age >= 0) - { + if (age >= 0) { Calendar now = Calendar.getInstance(); now.set(Calendar.HOUR_OF_DAY, 0); now.set(Calendar.MINUTE, 0); now.set(Calendar.SECOND, 0); now.set(Calendar.MILLISECOND, 0); - if (age < 28) - { + if (age < 28) { now.add(Calendar.DATE, age * -1); - } - else switch (age) - { - case 28: - now.add(Calendar.MONTH, -1); - break; - case 56: - now.add(Calendar.MONTH, -2); - break; - case 84: - now.add(Calendar.MONTH, -3); - break; - case 168: - now.add(Calendar.MONTH, -6); - break; - case 365: - now.add(Calendar.YEAR, -1); - break; + } else switch (age) { + case 28: + now.add(Calendar.MONTH, -1); + break; + case 56: + now.add(Calendar.MONTH, -2); + break; + case 84: + now.add(Calendar.MONTH, -3); + break; + case 168: + now.add(Calendar.MONTH, -6); + break; + case 365: + now.add(Calendar.YEAR, -1); + break; } return now.getTime(); - } - else - { + } else { return null; } } - public MessageFormat getMessageFormat() - { + public MessageFormat getMessageFormat() { return mMessageFormat; } - public void setMessageFormat(MessageFormat messageFormat) - { + public void setMessageFormat(MessageFormat messageFormat) { this.mMessageFormat = messageFormat; } - public QuoteStyle getQuoteStyle() - { + public QuoteStyle getQuoteStyle() { return mQuoteStyle; } - public void setQuoteStyle(QuoteStyle quoteStyle) - { + public void setQuoteStyle(QuoteStyle quoteStyle) { this.mQuoteStyle = quoteStyle; } - public synchronized String getQuotePrefix() - { + public synchronized String getQuotePrefix() { return mQuotePrefix; } - public synchronized void setQuotePrefix(String quotePrefix) - { + public synchronized void setQuotePrefix(String quotePrefix) { mQuotePrefix = quotePrefix; } - public synchronized boolean isReplyAfterQuote() - { + public synchronized boolean isReplyAfterQuote() { return mReplyAfterQuote; } - public synchronized void setReplyAfterQuote(boolean replyAfterQuote) - { + public synchronized void setReplyAfterQuote(boolean replyAfterQuote) { mReplyAfterQuote = replyAfterQuote; } - public boolean getEnableMoveButtons() - { + public boolean getEnableMoveButtons() { return mEnableMoveButtons; } - public void setEnableMoveButtons(boolean enableMoveButtons) - { + public void setEnableMoveButtons(boolean enableMoveButtons) { mEnableMoveButtons = enableMoveButtons; } - public String getCryptoApp() - { + public String getCryptoApp() { return mCryptoApp; } - public void setCryptoApp(String cryptoApp) - { + public void setCryptoApp(String cryptoApp) { mCryptoApp = cryptoApp; // invalidate the provider mCryptoProvider = null; } - public boolean getCryptoAutoSignature() - { + public boolean getCryptoAutoSignature() { return mCryptoAutoSignature; } - public void setCryptoAutoSignature(boolean cryptoAutoSignature) - { + public void setCryptoAutoSignature(boolean cryptoAutoSignature) { mCryptoAutoSignature = cryptoAutoSignature; } - public synchronized boolean syncRemoteDeletions() - { + public synchronized boolean syncRemoteDeletions() { return mSyncRemoteDeletions; } - public synchronized void setSyncRemoteDeletions(boolean syncRemoteDeletions) - { + public synchronized void setSyncRemoteDeletions(boolean syncRemoteDeletions) { mSyncRemoteDeletions = syncRemoteDeletions; } - public synchronized String getLastSelectedFolderName() - { + public synchronized String getLastSelectedFolderName() { return lastSelectedFolderName; } - public synchronized void setLastSelectedFolderName(String folderName) - { + public synchronized void setLastSelectedFolderName(String folderName) { lastSelectedFolderName = folderName; } - public synchronized CryptoProvider getCryptoProvider() - { - if (mCryptoProvider == null) - { + public synchronized CryptoProvider getCryptoProvider() { + if (mCryptoProvider == null) { mCryptoProvider = CryptoProvider.createInstance(getCryptoApp()); } return mCryptoProvider; } - public synchronized NotificationSetting getNotificationSetting() - { + public synchronized NotificationSetting getNotificationSetting() { return mNotificationSetting; } @@ -1572,11 +1340,9 @@ public class Account implements BaseAccount * @return true if our {@link StorageProvider} is ready. (e.g. * card inserted) */ - public boolean isAvailable(Context context) - { + public boolean isAvailable(Context context) { String localStorageProviderId = getLocalStorageProviderId(); - if (localStorageProviderId == null) - { + if (localStorageProviderId == null) { return true; // defaults to internal memory } return StorageManager.getInstance(K9.app).isReady(localStorageProviderId); diff --git a/src/com/fsck/k9/AccountStats.java b/src/com/fsck/k9/AccountStats.java index c8b4167fc..d69685e66 100644 --- a/src/com/fsck/k9/AccountStats.java +++ b/src/com/fsck/k9/AccountStats.java @@ -5,8 +5,7 @@ package com.fsck.k9; import java.io.Serializable; -public class AccountStats implements Serializable -{ +public class AccountStats implements Serializable { private static final long serialVersionUID = -5706839923710842234L; public long size = -1; public int unreadMessageCount = 0; diff --git a/src/com/fsck/k9/BaseAccount.java b/src/com/fsck/k9/BaseAccount.java index 4d7eda82a..2d6b643eb 100644 --- a/src/com/fsck/k9/BaseAccount.java +++ b/src/com/fsck/k9/BaseAccount.java @@ -1,7 +1,6 @@ package com.fsck.k9; -public interface BaseAccount -{ +public interface BaseAccount { public String getEmail(); public void setEmail(String email); public String getDescription(); diff --git a/src/com/fsck/k9/EmailAddressAdapter.java b/src/com/fsck/k9/EmailAddressAdapter.java index 390a1d15c..d9bb59940 100644 --- a/src/com/fsck/k9/EmailAddressAdapter.java +++ b/src/com/fsck/k9/EmailAddressAdapter.java @@ -24,14 +24,11 @@ import android.view.View; import android.widget.ResourceCursorAdapter; import android.widget.TextView; -public class EmailAddressAdapter extends ResourceCursorAdapter -{ +public class EmailAddressAdapter extends ResourceCursorAdapter { private static EmailAddressAdapter sInstance; - public static EmailAddressAdapter getInstance(Context context) - { - if (sInstance == null) - { + public static EmailAddressAdapter getInstance(Context context) { + if (sInstance == null) { sInstance = new EmailAddressAdapter(context); } @@ -41,15 +38,13 @@ public class EmailAddressAdapter extends ResourceCursorAdapter private final Contacts mContacts; - private EmailAddressAdapter(Context context) - { + private EmailAddressAdapter(Context context) { super(context, R.layout.recipient_dropdown_item, null); mContacts = Contacts.getInstance(context); } @Override - public final String convertToString(final Cursor cursor) - { + public final String convertToString(final Cursor cursor) { final String name = mContacts.getName(cursor); final String address = mContacts.getEmail(cursor); @@ -57,8 +52,7 @@ public class EmailAddressAdapter extends ResourceCursorAdapter } @Override - public final void bindView(final View view, final Context context, final Cursor cursor) - { + public final void bindView(final View view, final Context context, final Cursor cursor) { final TextView text1 = (TextView) view.findViewById(R.id.text1); final TextView text2 = (TextView) view.findViewById(R.id.text2); text1.setText(mContacts.getName(cursor)); @@ -66,8 +60,7 @@ public class EmailAddressAdapter extends ResourceCursorAdapter } @Override - public Cursor runQueryOnBackgroundThread(CharSequence constraint) - { + public Cursor runQueryOnBackgroundThread(CharSequence constraint) { return mContacts.searchContacts(constraint); } } diff --git a/src/com/fsck/k9/EmailAddressValidator.java b/src/com/fsck/k9/EmailAddressValidator.java index 052615621..957a1384b 100644 --- a/src/com/fsck/k9/EmailAddressValidator.java +++ b/src/com/fsck/k9/EmailAddressValidator.java @@ -4,20 +4,16 @@ package com.fsck.k9; import android.text.util.Rfc822Tokenizer; import android.widget.AutoCompleteTextView.Validator; -public class EmailAddressValidator implements Validator -{ - public CharSequence fixText(CharSequence invalidText) - { +public class EmailAddressValidator implements Validator { + public CharSequence fixText(CharSequence invalidText) { return ""; } - public boolean isValid(CharSequence text) - { + public boolean isValid(CharSequence text) { return Rfc822Tokenizer.tokenize(text).length > 0; } - public boolean isValidAddressOnly(CharSequence text) - { + public boolean isValidAddressOnly(CharSequence text) { return com.fsck.k9.helper.Regex.EMAIL_ADDRESS_PATTERN.matcher(text).matches(); } } diff --git a/src/com/fsck/k9/EmailReceivedIntent.java b/src/com/fsck/k9/EmailReceivedIntent.java index c834e67a6..24b209a92 100644 --- a/src/com/fsck/k9/EmailReceivedIntent.java +++ b/src/com/fsck/k9/EmailReceivedIntent.java @@ -1,7 +1,6 @@ package com.fsck.k9; -public class EmailReceivedIntent -{ +public class EmailReceivedIntent { public static final String ACTION_EMAIL_RECEIVED = "com.fsck.k9.intent.action.EMAIL_RECEIVED"; public static final String EXTRA_ACCOUNT = "com.fsck.k9.intent.extra.ACCOUNT"; diff --git a/src/com/fsck/k9/FontSizes.java b/src/com/fsck/k9/FontSizes.java index 77f9a0f9c..a45216b2e 100644 --- a/src/com/fsck/k9/FontSizes.java +++ b/src/com/fsck/k9/FontSizes.java @@ -7,8 +7,7 @@ import android.webkit.WebSettings.TextSize; * Manage font size of the information displayed in the account list, folder * list, message list and in the message view. */ -public class FontSizes -{ +public class FontSizes { /* * Keys for the preference storage. */ @@ -126,8 +125,7 @@ public class FontSizes /** * Create a FontSizes object with default values. */ - public FontSizes() - { + public FontSizes() { accountName = MEDIUM; accountDescription = SMALL; @@ -153,8 +151,7 @@ public class FontSizes * * @param editor Used to save the font size settings. */ - public void save(SharedPreferences.Editor editor) - { + public void save(SharedPreferences.Editor editor) { editor.putInt(ACCOUNT_NAME, accountName); editor.putInt(ACCOUNT_DESCRIPTION, accountDescription); @@ -181,8 +178,7 @@ public class FontSizes * * @param prefs Used to load the font size settings. */ - public void load(SharedPreferences prefs) - { + public void load(SharedPreferences prefs) { accountName = prefs.getInt(ACCOUNT_NAME, accountName); accountDescription = prefs.getInt(ACCOUNT_DESCRIPTION, accountDescription); @@ -204,198 +200,163 @@ public class FontSizes setMessageViewContent(prefs.getInt(MESSAGE_VIEW_CONTENT, 3)); } - public int getAccountName() - { + public int getAccountName() { return accountName; } - public void setAccountName(int accountName) - { + public void setAccountName(int accountName) { this.accountName = accountName; } - public int getAccountDescription() - { + public int getAccountDescription() { return accountDescription; } - public void setAccountDescription(int accountDescription) - { + public void setAccountDescription(int accountDescription) { this.accountDescription = accountDescription; } - public int getFolderName() - { + public int getFolderName() { return folderName; } - public void setFolderName(int folderName) - { + public void setFolderName(int folderName) { this.folderName = folderName; } - public int getFolderStatus() - { + public int getFolderStatus() { return folderStatus; } - public void setFolderStatus(int folderStatus) - { + public void setFolderStatus(int folderStatus) { this.folderStatus = folderStatus; } - public int getMessageListSubject() - { + public int getMessageListSubject() { return messageListSubject; } - public void setMessageListSubject(int messageListSubject) - { + public void setMessageListSubject(int messageListSubject) { this.messageListSubject = messageListSubject; } - public int getMessageListSender() - { + public int getMessageListSender() { return messageListSender; } - public void setMessageListSender(int messageListSender) - { + public void setMessageListSender(int messageListSender) { this.messageListSender = messageListSender; } - public int getMessageListDate() - { + public int getMessageListDate() { return messageListDate; } - public void setMessageListDate(int messageListDate) - { + public void setMessageListDate(int messageListDate) { this.messageListDate = messageListDate; } - public int getMessageListPreview() - { + public int getMessageListPreview() { return messageListPreview; } - public void setMessageListPreview(int messageListPreview) - { + public void setMessageListPreview(int messageListPreview) { this.messageListPreview = messageListPreview; } - public int getMessageViewSender() - { + public int getMessageViewSender() { return messageViewSender; } - public void setMessageViewSender(int messageViewSender) - { + public void setMessageViewSender(int messageViewSender) { this.messageViewSender = messageViewSender; } - public int getMessageViewTo() - { + public int getMessageViewTo() { return messageViewTo; } - public void setMessageViewTo(int messageViewTo) - { + public void setMessageViewTo(int messageViewTo) { this.messageViewTo = messageViewTo; } - public int getMessageViewCC() - { + public int getMessageViewCC() { return messageViewCC; } - public void setMessageViewCC(int messageViewCC) - { + public void setMessageViewCC(int messageViewCC) { this.messageViewCC = messageViewCC; } - public int getMessageViewAdditionalHeaders() - { + public int getMessageViewAdditionalHeaders() { return messageViewAdditionalHeaders; } - public void setMessageViewAdditionalHeaders(int messageViewAdditionalHeaders) - { + public void setMessageViewAdditionalHeaders(int messageViewAdditionalHeaders) { this.messageViewAdditionalHeaders = messageViewAdditionalHeaders; } - public int getMessageViewSubject() - { + public int getMessageViewSubject() { return messageViewSubject; } - public void setMessageViewSubject(int messageViewSubject) - { + public void setMessageViewSubject(int messageViewSubject) { this.messageViewSubject = messageViewSubject; } - public int getMessageViewTime() - { + public int getMessageViewTime() { return messageViewTime; } - public void setMessageViewTime(int messageViewTime) - { + public void setMessageViewTime(int messageViewTime) { this.messageViewTime = messageViewTime; } - public int getMessageViewDate() - { + public int getMessageViewDate() { return messageViewDate; } - public void setMessageViewDate(int messageViewDate) - { + public void setMessageViewDate(int messageViewDate) { this.messageViewDate = messageViewDate; } - public TextSize getMessageViewContent() - { + public TextSize getMessageViewContent() { return messageViewContent; } - public int getMessageViewContentAsInt() - { - switch (messageViewContent) - { - case SMALLEST: - return 1; - case SMALLER: - return 2; - default: - case NORMAL: - return 3; - case LARGER: - return 4; - case LARGEST: - return 5; + public int getMessageViewContentAsInt() { + switch (messageViewContent) { + case SMALLEST: + return 1; + case SMALLER: + return 2; + default: + case NORMAL: + return 3; + case LARGER: + return 4; + case LARGEST: + return 5; } } - public void setMessageViewContent(int size) - { - switch (size) - { - case 1: - messageViewContent = TextSize.SMALLEST; - break; - case 2: - messageViewContent = TextSize.SMALLER; - break; - case 3: - messageViewContent = TextSize.NORMAL; - break; - case 4: - messageViewContent = TextSize.LARGER; - break; - case 5: - messageViewContent = TextSize.LARGEST; - break; + public void setMessageViewContent(int size) { + switch (size) { + case 1: + messageViewContent = TextSize.SMALLEST; + break; + case 2: + messageViewContent = TextSize.SMALLER; + break; + case 3: + messageViewContent = TextSize.NORMAL; + break; + case 4: + messageViewContent = TextSize.LARGER; + break; + case 5: + messageViewContent = TextSize.LARGEST; + break; } } } diff --git a/src/com/fsck/k9/Identity.java b/src/com/fsck/k9/Identity.java index 3810bc210..1aead56d6 100644 --- a/src/com/fsck/k9/Identity.java +++ b/src/com/fsck/k9/Identity.java @@ -2,8 +2,7 @@ package com.fsck.k9; import java.io.Serializable; -public class Identity implements Serializable -{ +public class Identity implements Serializable { private static final long serialVersionUID = -1666669071480985760L; private String mDescription; private String mName; @@ -12,69 +11,56 @@ public class Identity implements Serializable private boolean mSignatureUse; private String replyTo; - public synchronized String getName() - { + public synchronized String getName() { return mName; } - public synchronized void setName(String name) - { + public synchronized void setName(String name) { mName = name; } - public synchronized String getEmail() - { + public synchronized String getEmail() { return mEmail; } - public synchronized void setEmail(String email) - { + public synchronized void setEmail(String email) { mEmail = email; } - public synchronized boolean getSignatureUse() - { + public synchronized boolean getSignatureUse() { return mSignatureUse; } - public synchronized void setSignatureUse(boolean signatureUse) - { + public synchronized void setSignatureUse(boolean signatureUse) { mSignatureUse = signatureUse; } - public synchronized String getSignature() - { + public synchronized String getSignature() { return mSignature; } - public synchronized void setSignature(String signature) - { + public synchronized void setSignature(String signature) { mSignature = signature; } - public synchronized String getDescription() - { + public synchronized String getDescription() { return mDescription; } - public synchronized void setDescription(String description) - { + public synchronized void setDescription(String description) { mDescription = description; } - public synchronized String getReplyTo() - { + public synchronized String getReplyTo() { return replyTo; } - public synchronized void setReplyTo(String replyTo) - { + public synchronized void setReplyTo(String replyTo) { this.replyTo = replyTo; } @Override - public synchronized String toString() - { + public synchronized String toString() { return "Account.Identity(description=" + mDescription + ", name=" + mName + ", email=" + mEmail + ", replyTo=" + replyTo + ", signature=" + mSignature; } } diff --git a/src/com/fsck/k9/K9.java b/src/com/fsck/k9/K9.java index a925a028e..f8b45a1e3 100644 --- a/src/com/fsck/k9/K9.java +++ b/src/com/fsck/k9/K9.java @@ -35,16 +35,14 @@ import com.fsck.k9.service.MailService; import com.fsck.k9.service.ShutdownReceiver; import com.fsck.k9.service.StorageGoneReceiver; -public class K9 extends Application -{ +public class K9 extends Application { /** * Components that are interested in knowing when the K9 instance is * available and ready (Android invokes Application.onCreate() after other * components') should implement this interface and register using * {@link K9#registerApplicationAware(ApplicationAware)}. */ - public static interface ApplicationAware - { + public static interface ApplicationAware { /** * Called when the Application instance is available and ready. * @@ -68,8 +66,7 @@ public class K9 extends Application private static List observers = new ArrayList(); - public enum BACKGROUND_OPS - { + public enum BACKGROUND_OPS { WHEN_CHECKED, ALWAYS, NEVER, WHEN_CHECKED_AUTO_SYNC } @@ -178,7 +175,7 @@ public class K9 extends Application private static String mQuietTimeEnds = null; private static boolean compactLayouts = false; - + private static boolean useGalleryBugWorkaround = false; private static boolean galleryBuggy; @@ -187,31 +184,27 @@ public class K9 extends Application /** * The MIME type(s) of attachments we're willing to view. */ - public static final String[] ACCEPTABLE_ATTACHMENT_VIEW_TYPES = new String[] - { + public static final String[] ACCEPTABLE_ATTACHMENT_VIEW_TYPES = new String[] { "*/*", }; /** * The MIME type(s) of attachments we're not willing to view. */ - public static final String[] UNACCEPTABLE_ATTACHMENT_VIEW_TYPES = new String[] - { + public static final String[] UNACCEPTABLE_ATTACHMENT_VIEW_TYPES = new String[] { }; /** * The MIME type(s) of attachments we're willing to download to SD. */ - public static final String[] ACCEPTABLE_ATTACHMENT_DOWNLOAD_TYPES = new String[] - { + public static final String[] ACCEPTABLE_ATTACHMENT_DOWNLOAD_TYPES = new String[] { "*/*", }; /** * The MIME type(s) of attachments we're not willing to download to SD. */ - public static final String[] UNACCEPTABLE_ATTACHMENT_DOWNLOAD_TYPES = new String[] - { + public static final String[] UNACCEPTABLE_ATTACHMENT_DOWNLOAD_TYPES = new String[] { }; /** @@ -283,11 +276,9 @@ public class K9 extends Application public static final int CONNECTIVITY_ID = -3; - public static class Intents - { + public static class Intents { - public static class EmailReceived - { + public static class EmailReceived { public static final String ACTION_EMAIL_RECEIVED = "com.fsck.k9.intent.action.EMAIL_RECEIVED"; public static final String ACTION_EMAIL_DELETED = "com.fsck.k9.intent.action.EMAIL_DELETED"; public static final String ACTION_REFRESH_OBSERVER = "com.fsck.k9.intent.action.REFRESH_OBSERVER"; @@ -309,27 +300,23 @@ public class K9 extends Application * enables or disables the Compose activity, the boot receiver and the service based on * whether any accounts are configured. */ - public static void setServicesEnabled(Context context) - { + public static void setServicesEnabled(Context context) { int acctLength = Preferences.getPreferences(context).getAvailableAccounts().size(); setServicesEnabled(context, acctLength > 0, null); } - public static void setServicesEnabled(Context context, Integer wakeLockId) - { + public static void setServicesEnabled(Context context, Integer wakeLockId) { setServicesEnabled(context, Preferences.getPreferences(context).getAvailableAccounts().size() > 0, wakeLockId); } - public static void setServicesEnabled(Context context, boolean enabled, Integer wakeLockId) - { + public static void setServicesEnabled(Context context, boolean enabled, Integer wakeLockId) { PackageManager pm = context.getPackageManager(); if (!enabled && pm.getComponentEnabledSetting(new ComponentName(context, MailService.class)) == - PackageManager.COMPONENT_ENABLED_STATE_ENABLED) - { + PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { /* * If no accounts now exist but the service is still enabled we're about to disable it * so we'll reschedule to kill off any existing alarms. @@ -338,14 +325,12 @@ public class K9 extends Application } Class[] classes = { MessageCompose.class, BootReceiver.class, MailService.class }; - for (Class clazz : classes) - { + for (Class clazz : classes) { boolean alreadyEnabled = pm.getComponentEnabledSetting(new ComponentName(context, clazz)) == PackageManager.COMPONENT_ENABLED_STATE_ENABLED; - if (enabled != alreadyEnabled) - { + if (enabled != alreadyEnabled) { pm.setComponentEnabledSetting( new ComponentName(context, clazz), enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED : @@ -355,8 +340,7 @@ public class K9 extends Application } if (enabled && pm.getComponentEnabledSetting(new ComponentName(context, MailService.class)) == - PackageManager.COMPONENT_ENABLED_STATE_ENABLED) - { + PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { /* * And now if accounts do exist then we've just enabled the service and we want to * schedule alarms for the new accounts. @@ -371,8 +355,7 @@ public class K9 extends Application * would make K-9 auto-start. We don't want auto-start because the initialization * sequence isn't safe while some events occur (SD card unmount). */ - protected void registerReceivers() - { + protected void registerReceivers() { final StorageGoneReceiver receiver = new StorageGoneReceiver(); final IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_MEDIA_EJECT); @@ -382,18 +365,13 @@ public class K9 extends Application final BlockingQueue queue = new SynchronousQueue(); // starting a new thread to handle unmount events - new Thread(new Runnable() - { + new Thread(new Runnable() { @Override - public void run() - { + public void run() { Looper.prepare(); - try - { + try { queue.put(new Handler()); - } - catch (InterruptedException e) - { + } catch (InterruptedException e) { Log.e(K9.LOG_TAG, "", e); } Looper.loop(); @@ -401,14 +379,11 @@ public class K9 extends Application }, "Unmount-thread").start(); - try - { + try { final Handler storageGoneHandler = queue.take(); registerReceiver(receiver, filter, null, storageGoneHandler); Log.i(K9.LOG_TAG, "Registered: unmount receiver"); - } - catch (InterruptedException e) - { + } catch (InterruptedException e) { Log.e(K9.LOG_TAG, "Unable to register unmount receiver", e); } @@ -416,8 +391,7 @@ public class K9 extends Application Log.i(K9.LOG_TAG, "Registered: shutdown receiver"); } - public static void save(SharedPreferences.Editor editor) - { + public static void save(SharedPreferences.Editor editor) { editor.putBoolean("enableDebugLogging", K9.DEBUG); editor.putBoolean("enableSensitiveLogging", K9.DEBUG_SENSITIVE); editor.putString("backgroundOperations", K9.backgroundOps.toString()); @@ -426,7 +400,7 @@ public class K9 extends Application editor.putBoolean("useVolumeKeysForNavigation", mUseVolumeKeysForNavigation); editor.putBoolean("useVolumeKeysForListNavigation", mUseVolumeKeysForListNavigation); editor.putBoolean("manageBack", mManageBack); - editor.putBoolean("zoomControlsEnabled",mZoomControlsEnabled); + editor.putBoolean("zoomControlsEnabled", mZoomControlsEnabled); editor.putBoolean("mobileOptimizedLayout", mMobileOptimizedLayout); editor.putBoolean("quietTimeEnabled", mQuietTimeEnabled); editor.putString("quietTimeStarts", mQuietTimeStarts); @@ -435,16 +409,16 @@ public class K9 extends Application editor.putBoolean("startIntegratedInbox", mStartIntegratedInbox); editor.putBoolean("measureAccounts", mMeasureAccounts); editor.putBoolean("countSearchMessages", mCountSearchMessages); - editor.putBoolean("messageListStars",mMessageListStars); - editor.putBoolean("messageListCheckboxes",mMessageListCheckboxes); - editor.putBoolean("messageListTouchable",mMessageListTouchable); - editor.putInt("messageListPreviewLines",mMessageListPreviewLines); + editor.putBoolean("messageListStars", mMessageListStars); + editor.putBoolean("messageListCheckboxes", mMessageListCheckboxes); + editor.putBoolean("messageListTouchable", mMessageListTouchable); + editor.putInt("messageListPreviewLines", mMessageListPreviewLines); - editor.putBoolean("showCorrespondentNames",mShowCorrespondentNames); - editor.putBoolean("showContactName",mShowContactName); - editor.putBoolean("changeRegisteredNameColor",mChangeContactNameColor); - editor.putInt("registeredNameColor",mContactNameColor); - editor.putBoolean("messageViewFixedWidthFont",mMessageViewFixedWidthFont); + editor.putBoolean("showCorrespondentNames", mShowCorrespondentNames); + editor.putBoolean("showContactName", mShowContactName); + editor.putBoolean("changeRegisteredNameColor", mChangeContactNameColor); + editor.putInt("registeredNameColor", mContactNameColor); + editor.putBoolean("messageViewFixedWidthFont", mMessageViewFixedWidthFont); editor.putBoolean("messageViewReturnToList", mMessageViewReturnToList); editor.putString("language", language); @@ -454,15 +428,14 @@ public class K9 extends Application editor.putBoolean("confirmDelete", mConfirmDelete); editor.putBoolean("keyguardPrivacy", mKeyguardPrivacy); - + editor.putBoolean("compactLayouts", compactLayouts); fontSizes.save(editor); } @Override - public void onCreate() - { + public void onCreate() { maybeSetupStrictMode(); super.onCreate(); app = this; @@ -482,17 +455,17 @@ public class K9 extends Application mStartIntegratedInbox = sprefs.getBoolean("startIntegratedInbox", false); mMeasureAccounts = sprefs.getBoolean("measureAccounts", true); mCountSearchMessages = sprefs.getBoolean("countSearchMessages", true); - mMessageListStars = sprefs.getBoolean("messageListStars",true); - mMessageListCheckboxes = sprefs.getBoolean("messageListCheckboxes",false); - mMessageListTouchable = sprefs.getBoolean("messageListTouchable",false); + mMessageListStars = sprefs.getBoolean("messageListStars", true); + mMessageListCheckboxes = sprefs.getBoolean("messageListCheckboxes", false); + mMessageListTouchable = sprefs.getBoolean("messageListTouchable", false); mMessageListPreviewLines = sprefs.getInt("messageListPreviewLines", 2); mMobileOptimizedLayout = sprefs.getBoolean("mobileOptimizedLayout", false); - mZoomControlsEnabled = sprefs.getBoolean("zoomControlsEnabled",false); + mZoomControlsEnabled = sprefs.getBoolean("zoomControlsEnabled", false); mQuietTimeEnabled = sprefs.getBoolean("quietTimeEnabled", false); - mQuietTimeStarts = sprefs.getString("quietTimeStarts", "21:00" ); - mQuietTimeEnds= sprefs.getString("quietTimeEnds", "7:00"); + mQuietTimeStarts = sprefs.getString("quietTimeStarts", "21:00"); + mQuietTimeEnds = sprefs.getString("quietTimeEnds", "7:00"); mShowCorrespondentNames = sprefs.getBoolean("showCorrespondentNames", true); mShowContactName = sprefs.getBoolean("showContactName", false); @@ -506,17 +479,14 @@ public class K9 extends Application mConfirmDelete = sprefs.getBoolean("confirmDelete", false); mKeyguardPrivacy = sprefs.getBoolean("keyguardPrivacy", false); - + compactLayouts = sprefs.getBoolean("compactLayouts", false); fontSizes.load(sprefs); - try - { + try { setBackgroundOps(BACKGROUND_OPS.valueOf(sprefs.getString("backgroundOperations", "WHEN_CHECKED"))); - } - catch (Exception e) - { + } catch (Exception e) { setBackgroundOps(BACKGROUND_OPS.WHEN_CHECKED); } @@ -536,12 +506,9 @@ public class K9 extends Application setServicesEnabled(this); registerReceivers(); - MessagingController.getInstance(this).addListener(new MessagingListener() - { - private void broadcastIntent(String action, Account account, String folder, Message message) - { - try - { + MessagingController.getInstance(this).addListener(new MessagingListener() { + private void broadcastIntent(String action, Account account, String folder, Message message) { + try { Uri uri = Uri.parse("email://messages/" + account.getAccountNumber() + "/" + Uri.encode(folder) + "/" + Uri.encode(message.getUid())); Intent intent = new Intent(action, uri); intent.putExtra(K9.Intents.EmailReceived.EXTRA_ACCOUNT, account.getDescription()); @@ -561,9 +528,7 @@ public class K9 extends Application + " message uid=" + message.getUid() ); - } - catch (MessagingException e) - { + } catch (MessagingException e) { Log.w(K9.LOG_TAG, "Error: action=" + action + " account=" + account.getDescription() + " folder=" + folder @@ -573,26 +538,22 @@ public class K9 extends Application } @Override - public void synchronizeMailboxRemovedMessage(Account account, String folder, Message message) - { + public void synchronizeMailboxRemovedMessage(Account account, String folder, Message message) { broadcastIntent(K9.Intents.EmailReceived.ACTION_EMAIL_DELETED, account, folder, message); } @Override - public void messageDeleted(Account account, String folder, Message message) - { + public void messageDeleted(Account account, String folder, Message message) { broadcastIntent(K9.Intents.EmailReceived.ACTION_EMAIL_DELETED, account, folder, message); } @Override - public void synchronizeMailboxNewMessage(Account account, String folder, Message message) - { + public void synchronizeMailboxNewMessage(Account account, String folder, Message message) { broadcastIntent(K9.Intents.EmailReceived.ACTION_EMAIL_RECEIVED, account, folder, message); } @Override - public void searchStats(final AccountStats stats) - { + public void searchStats(final AccountStats stats) { // let observers know a fetch occured K9.this.sendBroadcast(new Intent(K9.Intents.EmailReceived.ACTION_REFRESH_OBSERVER, null)); } @@ -602,22 +563,19 @@ public class K9 extends Application notifyObservers(); } - private void maybeSetupStrictMode() - { + private void maybeSetupStrictMode() { if (!K9.DEVELOPER_MODE) return; - try - { + try { Class strictMode = Class.forName("android.os.StrictMode"); Method enableDefaults = strictMode.getMethod("enableDefaults"); enableDefaults.invoke(strictMode); } - catch (Exception e) - { + catch (Exception e) { // Discard , as it means we're not running on a device with strict mode - Log.v(K9.LOG_TAG, "Failed to turn on strict mode "+e); + Log.v(K9.LOG_TAG, "Failed to turn on strict mode " + e); } } @@ -628,20 +586,14 @@ public class K9 extends Application * other components' onCreate(), here is a way to notify interested * component that the application is available and ready */ - protected void notifyObservers() - { - for (final ApplicationAware aware : observers) - { - if (K9.DEBUG) - { + protected void notifyObservers() { + for (final ApplicationAware aware : observers) { + if (K9.DEBUG) { Log.v(K9.LOG_TAG, "Initializing observer: " + aware); } - try - { + try { aware.initializeComponent(this); - } - catch (Exception e) - { + } catch (Exception e) { Log.w(K9.LOG_TAG, "Failure when notifying " + aware, e); } } @@ -653,147 +605,118 @@ public class K9 extends Application * @param component * Never null. */ - public static void registerApplicationAware(final ApplicationAware component) - { - if (!observers.contains(component)) - { + public static void registerApplicationAware(final ApplicationAware component) { + if (!observers.contains(component)) { observers.add(component); } } - public static String getK9Language() - { + public static String getK9Language() { return language; } - public static void setK9Language(String nlanguage) - { + public static void setK9Language(String nlanguage) { language = nlanguage; } - public static int getK9Theme() - { + public static int getK9Theme() { return theme; } - public static void setK9Theme(int ntheme) - { + public static void setK9Theme(int ntheme) { theme = ntheme; } - public static BACKGROUND_OPS getBackgroundOps() - { + public static BACKGROUND_OPS getBackgroundOps() { return backgroundOps; } - public static boolean setBackgroundOps(BACKGROUND_OPS backgroundOps) - { + public static boolean setBackgroundOps(BACKGROUND_OPS backgroundOps) { BACKGROUND_OPS oldBackgroundOps = K9.backgroundOps; K9.backgroundOps = backgroundOps; return backgroundOps != oldBackgroundOps; } - public static boolean setBackgroundOps(String nbackgroundOps) - { + public static boolean setBackgroundOps(String nbackgroundOps) { return setBackgroundOps(BACKGROUND_OPS.valueOf(nbackgroundOps)); } - public static boolean gesturesEnabled() - { + public static boolean gesturesEnabled() { return mGesturesEnabled; } - public static void setGesturesEnabled(boolean gestures) - { + public static void setGesturesEnabled(boolean gestures) { mGesturesEnabled = gestures; } - public static boolean useVolumeKeysForNavigationEnabled() - { + public static boolean useVolumeKeysForNavigationEnabled() { return mUseVolumeKeysForNavigation; } - public static void setUseVolumeKeysForNavigation(boolean volume) - { + public static void setUseVolumeKeysForNavigation(boolean volume) { mUseVolumeKeysForNavigation = volume; } - public static boolean useVolumeKeysForListNavigationEnabled() - { + public static boolean useVolumeKeysForListNavigationEnabled() { return mUseVolumeKeysForListNavigation; } - public static void setUseVolumeKeysForListNavigation(boolean enabled) - { + public static void setUseVolumeKeysForListNavigation(boolean enabled) { mUseVolumeKeysForListNavigation = enabled; } - public static boolean manageBack() - { + public static boolean manageBack() { return mManageBack; } - public static void setManageBack(boolean manageBack) - { + public static void setManageBack(boolean manageBack) { mManageBack = manageBack; } - public static boolean zoomControlsEnabled() - { + public static boolean zoomControlsEnabled() { return mZoomControlsEnabled; } - public static void setZoomControlsEnabled(boolean zoomControlsEnabled) - { + public static void setZoomControlsEnabled(boolean zoomControlsEnabled) { mZoomControlsEnabled = zoomControlsEnabled; } - public static boolean mobileOptimizedLayout() - { + public static boolean mobileOptimizedLayout() { return mMobileOptimizedLayout; } - public static void setMobileOptimizedLayout(boolean mobileOptimizedLayout) - { + public static void setMobileOptimizedLayout(boolean mobileOptimizedLayout) { mMobileOptimizedLayout = mobileOptimizedLayout; } - public static boolean getQuietTimeEnabled() - { + public static boolean getQuietTimeEnabled() { return mQuietTimeEnabled; } - public static void setQuietTimeEnabled(boolean quietTimeEnabled) - { + public static void setQuietTimeEnabled(boolean quietTimeEnabled) { mQuietTimeEnabled = quietTimeEnabled; } - public static String getQuietTimeStarts() - { + public static String getQuietTimeStarts() { return mQuietTimeStarts; } - public static void setQuietTimeStarts(String quietTimeStarts) - { + public static void setQuietTimeStarts(String quietTimeStarts) { mQuietTimeStarts = quietTimeStarts; } - public static String getQuietTimeEnds() - { + public static String getQuietTimeEnds() { return mQuietTimeEnds; } - public static void setQuietTimeEnds(String quietTimeEnds) - { + public static void setQuietTimeEnds(String quietTimeEnds) { mQuietTimeEnds = quietTimeEnds; } - public static boolean isQuietTime() - { - if (!mQuietTimeEnabled) - { + public static boolean isQuietTime() { + if (!mQuietTimeEnabled) { return false; } @@ -804,34 +727,29 @@ public class K9 extends Application Integer endHour = Integer.parseInt(mQuietTimeEnds.split(":")[0]); Integer endMinute = Integer.parseInt(mQuietTimeEnds.split(":")[1]); - Integer now = (time.hour * 60 ) + time.minute; + Integer now = (time.hour * 60) + time.minute; Integer quietStarts = startHour * 60 + startMinute; - Integer quietEnds = endHour * 60 +endMinute; + Integer quietEnds = endHour * 60 + endMinute; // If start and end times are the same, we're never quiet - if (quietStarts.equals(quietEnds)) - { + if (quietStarts.equals(quietEnds)) { return false; } // 21:00 - 05:00 means we want to be quiet if it's after 9 or before 5 - if (quietStarts > quietEnds) - { + if (quietStarts > quietEnds) { // if it's 22:00 or 03:00 but not 8:00 - if ( now >= quietStarts || now <= quietEnds) - { + if (now >= quietStarts || now <= quietEnds) { return true; } } // 01:00 - 05:00 - else - { + else { // if it' 2:00 or 4:00 but not 8:00 or 0:00 - if ( now >= quietStarts && now <= quietEnds) - { + if (now >= quietStarts && now <= quietEnds) { return true; } } @@ -841,214 +759,170 @@ public class K9 extends Application - public static boolean startIntegratedInbox() - { + public static boolean startIntegratedInbox() { return mStartIntegratedInbox; } - public static void setStartIntegratedInbox(boolean startIntegratedInbox) - { + public static void setStartIntegratedInbox(boolean startIntegratedInbox) { mStartIntegratedInbox = startIntegratedInbox; } - public static boolean showAnimations() - { + public static boolean showAnimations() { return mAnimations; } - public static void setAnimations(boolean animations) - { + public static void setAnimations(boolean animations) { mAnimations = animations; } - public static boolean messageListTouchable() - { + public static boolean messageListTouchable() { return mMessageListTouchable; } - public static void setMessageListTouchable(boolean touchy) - { + public static void setMessageListTouchable(boolean touchy) { mMessageListTouchable = touchy; } - public static int messageListPreviewLines() - { + public static int messageListPreviewLines() { return mMessageListPreviewLines; } - public static void setMessageListPreviewLines(int lines) - { + public static void setMessageListPreviewLines(int lines) { mMessageListPreviewLines = lines; } - public static boolean messageListStars() - { + public static boolean messageListStars() { return mMessageListStars; } - public static void setMessageListStars(boolean stars) - { + public static void setMessageListStars(boolean stars) { mMessageListStars = stars; } - public static boolean messageListCheckboxes() - { + public static boolean messageListCheckboxes() { return mMessageListCheckboxes; } - public static void setMessageListCheckboxes(boolean checkboxes) - { + public static void setMessageListCheckboxes(boolean checkboxes) { mMessageListCheckboxes = checkboxes; } - public static boolean showCorrespondentNames() - { + public static boolean showCorrespondentNames() { return mShowCorrespondentNames; } - public static void setShowCorrespondentNames(boolean showCorrespondentNames) - { + public static void setShowCorrespondentNames(boolean showCorrespondentNames) { mShowCorrespondentNames = showCorrespondentNames; } - public static boolean showContactName() - { + public static boolean showContactName() { return mShowContactName; } - public static void setShowContactName(boolean showContactName) - { + public static void setShowContactName(boolean showContactName) { mShowContactName = showContactName; } - public static boolean changeContactNameColor() - { + public static boolean changeContactNameColor() { return mChangeContactNameColor; } - public static void setChangeContactNameColor(boolean changeContactNameColor) - { + public static void setChangeContactNameColor(boolean changeContactNameColor) { mChangeContactNameColor = changeContactNameColor; } - public static int getContactNameColor() - { + public static int getContactNameColor() { return mContactNameColor; } - public static void setContactNameColor(int contactNameColor) - { + public static void setContactNameColor(int contactNameColor) { mContactNameColor = contactNameColor; } - public static boolean messageViewFixedWidthFont() - { + public static boolean messageViewFixedWidthFont() { return mMessageViewFixedWidthFont; } - public static void setMessageViewFixedWidthFont(boolean fixed) - { + public static void setMessageViewFixedWidthFont(boolean fixed) { mMessageViewFixedWidthFont = fixed; } - public static boolean messageViewReturnToList() - { + public static boolean messageViewReturnToList() { return mMessageViewReturnToList; } - public static void setMessageViewReturnToList(boolean messageViewReturnToList) - { + public static void setMessageViewReturnToList(boolean messageViewReturnToList) { mMessageViewReturnToList = messageViewReturnToList; } - public static Method getMethod(Class classObject, String methodName) - { - try - { + public static Method getMethod(Class classObject, String methodName) { + try { return classObject.getMethod(methodName, boolean.class); - } - catch (NoSuchMethodException e) - { + } catch (NoSuchMethodException e) { Log.i(K9.LOG_TAG, "Can't get method " + classObject.toString() + "." + methodName); - } - catch (Exception e) - { + } catch (Exception e) { Log.e(K9.LOG_TAG, "Error while using reflection to get method " + classObject.toString() + "." + methodName, e); } return null; } - public static FontSizes getFontSizes() - { + public static FontSizes getFontSizes() { return fontSizes; } - public static boolean measureAccounts() - { + public static boolean measureAccounts() { return mMeasureAccounts; } - public static void setMeasureAccounts(boolean measureAccounts) - { + public static void setMeasureAccounts(boolean measureAccounts) { mMeasureAccounts = measureAccounts; } - public static boolean countSearchMessages() - { + public static boolean countSearchMessages() { return mCountSearchMessages; } - public static void setCountSearchMessages(boolean countSearchMessages) - { + public static void setCountSearchMessages(boolean countSearchMessages) { mCountSearchMessages = countSearchMessages; } - public static boolean useGalleryBugWorkaround() - { + public static boolean useGalleryBugWorkaround() { return useGalleryBugWorkaround; } - public static void setUseGalleryBugWorkaround(boolean useGalleryBugWorkaround) - { + public static void setUseGalleryBugWorkaround(boolean useGalleryBugWorkaround) { K9.useGalleryBugWorkaround = useGalleryBugWorkaround; } - public static boolean isGalleryBuggy() - { + public static boolean isGalleryBuggy() { return galleryBuggy; } - public static boolean confirmDelete() - { + public static boolean confirmDelete() { return mConfirmDelete; } - public static void setConfirmDelete(final boolean confirm) - { + public static void setConfirmDelete(final boolean confirm) { mConfirmDelete = confirm; } /** * @return Whether privacy rules should be applied when system is locked */ - public static boolean keyguardPrivacy() - { + public static boolean keyguardPrivacy() { return mKeyguardPrivacy; } - public static void setKeyguardPrivacy(final boolean state) - { + public static void setKeyguardPrivacy(final boolean state) { mKeyguardPrivacy = state; } - - public static boolean useCompactLayouts() - { + + public static boolean useCompactLayouts() { return compactLayouts; } - public static void setCompactLayouts(boolean compactLayouts) - { + public static void setCompactLayouts(boolean compactLayouts) { K9.compactLayouts = compactLayouts; } @@ -1061,16 +935,12 @@ public class K9 extends Application * * @return true, if a buggy Gallery 3D package was found. False, otherwise. */ - private boolean checkForBuggyGallery() - { - try - { + private boolean checkForBuggyGallery() { + try { PackageInfo pi = getPackageManager().getPackageInfo("com.cooliris.media", 0); return (pi.versionCode == 30682); - } - catch (NameNotFoundException e) - { + } catch (NameNotFoundException e) { return false; } } diff --git a/src/com/fsck/k9/NotificationSetting.java b/src/com/fsck/k9/NotificationSetting.java index ff9a6c7a0..6885ae1d3 100644 --- a/src/com/fsck/k9/NotificationSetting.java +++ b/src/com/fsck/k9/NotificationSetting.java @@ -3,8 +3,7 @@ package com.fsck.k9; /** * Describes how a notification should behave. */ -public class NotificationSetting -{ +public class NotificationSetting { /** * Ring notification kill switch. Allow disabling ringtones without losing @@ -38,8 +37,7 @@ public class NotificationSetting * true to allow ringtones, false * otherwise. */ - public synchronized void setRing(boolean ring) - { + public synchronized void setRing(boolean ring) { mRing = ring; } @@ -47,68 +45,55 @@ public class NotificationSetting * @return true if ringtone is allowed to play, * false otherwise. */ - public synchronized boolean shouldRing() - { + public synchronized boolean shouldRing() { return mRing; } - public synchronized String getRingtone() - { + public synchronized String getRingtone() { return mRingtoneUri; } - public synchronized void setRingtone(String ringtoneUri) - { + public synchronized void setRingtone(String ringtoneUri) { mRingtoneUri = ringtoneUri; } - public synchronized boolean isLed() - { + public synchronized boolean isLed() { return mLed; } - public synchronized void setLed(final boolean led) - { + public synchronized void setLed(final boolean led) { mLed = led; } - public synchronized int getLedColor() - { + public synchronized int getLedColor() { return mLedColor; } - public synchronized void setLedColor(int color) - { + public synchronized void setLedColor(int color) { mLedColor = color; } - public synchronized boolean shouldVibrate() - { + public synchronized boolean shouldVibrate() { return mVibrate; } - public synchronized void setVibrate(boolean vibrate) - { + public synchronized void setVibrate(boolean vibrate) { mVibrate = vibrate; } - public synchronized int getVibratePattern() - { + public synchronized int getVibratePattern() { return mVibratePattern; } - public synchronized int getVibrateTimes() - { + public synchronized int getVibrateTimes() { return mVibrateTimes; } - public synchronized void setVibratePattern(int pattern) - { + public synchronized void setVibratePattern(int pattern) { mVibratePattern = pattern; } - public synchronized void setVibrateTimes(int times) - { + public synchronized void setVibrateTimes(int times) { mVibrateTimes = times; } @@ -122,45 +107,41 @@ public class NotificationSetting * @return Pattern multiplied by the number of times requested. */ - public long[] getVibration() - { + public long[] getVibration() { return getVibration(mVibratePattern, mVibrateTimes); } - public static long[] getVibration(int pattern, int times) - { + public static long[] getVibration(int pattern, int times) { // These are "off, on" patterns, specified in milliseconds - long[] pattern0 = new long[] {300,200}; // like the default pattern - long[] pattern1 = new long[] {100,200}; - long[] pattern2 = new long[] {100,500}; - long[] pattern3 = new long[] {200,200}; - long[] pattern4 = new long[] {200,500}; - long[] pattern5 = new long[] {500,500}; + long[] pattern0 = new long[] {300, 200}; // like the default pattern + long[] pattern1 = new long[] {100, 200}; + long[] pattern2 = new long[] {100, 500}; + long[] pattern3 = new long[] {200, 200}; + long[] pattern4 = new long[] {200, 500}; + long[] pattern5 = new long[] {500, 500}; long[] selectedPattern = pattern0; //default pattern - switch (pattern) - { - case 1: - selectedPattern = pattern1; - break; - case 2: - selectedPattern = pattern2; - break; - case 3: - selectedPattern = pattern3; - break; - case 4: - selectedPattern = pattern4; - break; - case 5: - selectedPattern = pattern5; - break; + switch (pattern) { + case 1: + selectedPattern = pattern1; + break; + case 2: + selectedPattern = pattern2; + break; + case 3: + selectedPattern = pattern3; + break; + case 4: + selectedPattern = pattern4; + break; + case 5: + selectedPattern = pattern5; + break; } long[] repeatedPattern = new long[selectedPattern.length * times]; - for (int n = 0; n < times; n++) - { + for (int n = 0; n < times; n++) { System.arraycopy(selectedPattern, 0, repeatedPattern, n * selectedPattern.length, selectedPattern.length); } // Do not wait before starting the vibration pattern. diff --git a/src/com/fsck/k9/Preferences.java b/src/com/fsck/k9/Preferences.java index 5769267f8..dece28412 100644 --- a/src/com/fsck/k9/Preferences.java +++ b/src/com/fsck/k9/Preferences.java @@ -11,8 +11,7 @@ import android.util.Log; import com.fsck.k9.preferences.Editor; import com.fsck.k9.preferences.Storage; -public class Preferences -{ +public class Preferences { /** * Immutable empty {@link Account} array @@ -21,10 +20,8 @@ public class Preferences private static Preferences preferences; - public static synchronized Preferences getPreferences(Context context) - { - if (preferences == null) - { + public static synchronized Preferences getPreferences(Context context) { + if (preferences == null) { preferences = new Preferences(context); } return preferences; @@ -36,12 +33,10 @@ public class Preferences private Account newAccount; private Context mContext; - private Preferences(Context context) - { + private Preferences(Context context) { mStorage = Storage.getStorage(context); mContext = context; - if (mStorage.size() == 0) - { + if (mStorage.size() == 0) { Log.i(K9.LOG_TAG, "Preferences storage is zero-size, importing from Android-style preferences"); Editor editor = mStorage.edit(); editor.copy(context.getSharedPreferences("AndroidMail.Main", Context.MODE_PRIVATE)); @@ -49,20 +44,15 @@ public class Preferences } } - private synchronized void loadAccounts() - { + private synchronized void loadAccounts() { String accountUuids = getPreferences().getString("accountUuids", null); - if ((accountUuids != null) && (accountUuids.length() != 0)) - { + if ((accountUuids != null) && (accountUuids.length() != 0)) { String[] uuids = accountUuids.split(","); accounts = new ArrayList(uuids.length); - for (String uuid : uuids) - { + for (String uuid : uuids) { accounts.add(new Account(this, uuid)); } - } - else - { + } else { accounts = new ArrayList(); } } @@ -72,15 +62,12 @@ public class Preferences * registered the method returns an empty array. * @return all accounts */ - public synchronized Account[] getAccounts() - { - if (accounts == null) - { + public synchronized Account[] getAccounts() { + if (accounts == null) { loadAccounts(); } - if ((newAccount != null) && newAccount.getAccountNumber() != -1) - { + if ((newAccount != null) && newAccount.getAccountNumber() != -1) { accounts.add(newAccount); newAccount = null; } @@ -93,23 +80,18 @@ public class Preferences * registered the method returns an empty array. * @return all accounts with {@link Account#isAvailable(Context)} */ - public synchronized Collection getAvailableAccounts() - { - if (accounts == null) - { + public synchronized Collection getAvailableAccounts() { + if (accounts == null) { loadAccounts(); } - if ((newAccount != null) && newAccount.getAccountNumber() != -1) - { + if ((newAccount != null) && newAccount.getAccountNumber() != -1) { accounts.add(newAccount); newAccount = null; } Collection retval = new ArrayList(accounts.size()); - for (Account account : accounts) - { - if (account.isAvailable(mContext)) - { + for (Account account : accounts) { + if (account.isAvailable(mContext)) { retval.add(account); } } @@ -117,43 +99,35 @@ public class Preferences return retval; } - public synchronized Account getAccount(String uuid) - { - if (accounts == null) - { + public synchronized Account getAccount(String uuid) { + if (accounts == null) { loadAccounts(); } - for (Account account : accounts) - { - if (account.getUuid().equals(uuid)) - { + for (Account account : accounts) { + if (account.getUuid().equals(uuid)) { return account; } } - if ((newAccount != null) && newAccount.getUuid().equals(uuid)) - { + if ((newAccount != null) && newAccount.getUuid().equals(uuid)) { return newAccount; } return null; } - public synchronized Account newAccount() - { + public synchronized Account newAccount() { newAccount = new Account(K9.app); return newAccount; } - public synchronized void deleteAccount(Account account) - { + public synchronized void deleteAccount(Account account) { accounts.remove(account); account.delete(this); - if (newAccount == account) - { + if (newAccount == account) { newAccount = null; } } @@ -163,16 +137,13 @@ public class Preferences * the first account in the list is marked as default and then returned. If * there are no accounts on the system the method returns null. */ - public Account getDefaultAccount() - { + public Account getDefaultAccount() { String defaultAccountUuid = getPreferences().getString("defaultAccountUuid", null); Account defaultAccount = getAccount(defaultAccountUuid); - if (defaultAccount == null) - { + if (defaultAccount == null) { Collection accounts = getAvailableAccounts(); - if (accounts.size() > 0) - { + if (accounts.size() > 0) { defaultAccount = accounts.iterator().next(); setDefaultAccount(defaultAccount); } @@ -181,24 +152,19 @@ public class Preferences return defaultAccount; } - public void setDefaultAccount(Account account) - { + public void setDefaultAccount(Account account) { getPreferences().edit().putString("defaultAccountUuid", account.getUuid()).commit(); } - public void dump() - { - if (Config.LOGV) - { - for (String key : getPreferences().getAll().keySet()) - { + public void dump() { + if (Config.LOGV) { + for (String key : getPreferences().getAll().keySet()) { Log.v(K9.LOG_TAG, key + " = " + getPreferences().getAll().get(key)); } } } - public SharedPreferences getPreferences() - { + public SharedPreferences getPreferences() { return mStorage; } } diff --git a/src/com/fsck/k9/SearchAccount.java b/src/com/fsck/k9/SearchAccount.java index a31d42aba..79161061d 100644 --- a/src/com/fsck/k9/SearchAccount.java +++ b/src/com/fsck/k9/SearchAccount.java @@ -10,8 +10,7 @@ import android.content.Context; import com.fsck.k9.mail.Flag; -public class SearchAccount implements BaseAccount, SearchSpecification, Serializable -{ +public class SearchAccount implements BaseAccount, SearchSpecification, Serializable { private static final long serialVersionUID = -4388420303235543976L; private Flag[] mRequiredFlags = null; private Flag[] mForbiddenFlags = null; @@ -24,116 +23,93 @@ public class SearchAccount implements BaseAccount, SearchSpecification, Serializ private String[] accountUuids = null; private String[] folderNames = null; - public SearchAccount(Preferences preferences) - { + public SearchAccount(Preferences preferences) { } - protected synchronized void delete(Preferences preferences) - { + protected synchronized void delete(Preferences preferences) { } - public synchronized void save(Preferences preferences) - { + public synchronized void save(Preferences preferences) { } - public SearchAccount(Context context, boolean nintegrate, Flag[] requiredFlags, Flag[] forbiddenFlags) - { + public SearchAccount(Context context, boolean nintegrate, Flag[] requiredFlags, Flag[] forbiddenFlags) { mRequiredFlags = requiredFlags; mForbiddenFlags = forbiddenFlags; integrate = nintegrate; } @Override - public synchronized String getEmail() - { + public synchronized String getEmail() { return email; } @Override - public synchronized void setEmail(String email) - { + public synchronized void setEmail(String email) { this.email = email; } - public Flag[] getRequiredFlags() - { + public Flag[] getRequiredFlags() { return mRequiredFlags; } - public Flag[] getForbiddenFlags() - { + public Flag[] getForbiddenFlags() { return mForbiddenFlags; } - public boolean isIntegrate() - { + public boolean isIntegrate() { return integrate; } - public String getDescription() - { + public String getDescription() { return description; } - public void setDescription(String description) - { + public void setDescription(String description) { this.description = description; } - public String getQuery() - { + public String getQuery() { return query; } - public void setQuery(String query) - { + public void setQuery(String query) { this.query = query; } - public String getUuid() - { - if(mUuid == null ) - { - setUuid( UUID.randomUUID().toString()); + public String getUuid() { + if (mUuid == null) { + setUuid(UUID.randomUUID().toString()); } return mUuid; } - public void setUuid(String nUuid) - { + public void setUuid(String nUuid) { mUuid = nUuid; } - public void setIntegrate(boolean integrate) - { + public void setIntegrate(boolean integrate) { this.integrate = integrate; } - public boolean isBuiltin() - { + public boolean isBuiltin() { return builtin; } - public void setBuiltin(boolean builtin) - { + public void setBuiltin(boolean builtin) { this.builtin = builtin; } - public String[] getAccountUuids() - { + public String[] getAccountUuids() { return accountUuids; } - public void setAccountUuids(String[] accountUuids) - { + public void setAccountUuids(String[] accountUuids) { this.accountUuids = accountUuids; } @Override - public String[] getFolderNames() - { + public String[] getFolderNames() { return folderNames; } - public void setFolderNames(String[] folderNames) - { + public void setFolderNames(String[] folderNames) { this.folderNames = folderNames; } } diff --git a/src/com/fsck/k9/SearchSpecification.java b/src/com/fsck/k9/SearchSpecification.java index 6cec76d72..a1f1de0a8 100644 --- a/src/com/fsck/k9/SearchSpecification.java +++ b/src/com/fsck/k9/SearchSpecification.java @@ -3,8 +3,7 @@ package com.fsck.k9; import com.fsck.k9.mail.Flag; -public interface SearchSpecification -{ +public interface SearchSpecification { public Flag[] getRequiredFlags(); diff --git a/src/com/fsck/k9/activity/AccessibleEmailContentActivity.java b/src/com/fsck/k9/activity/AccessibleEmailContentActivity.java index 80beca186..4b62641e4 100644 --- a/src/com/fsck/k9/activity/AccessibleEmailContentActivity.java +++ b/src/com/fsck/k9/activity/AccessibleEmailContentActivity.java @@ -23,8 +23,7 @@ import android.text.Html; import android.text.Spanned; import android.widget.ArrayAdapter; -public class AccessibleEmailContentActivity extends ListActivity -{ +public class AccessibleEmailContentActivity extends ListActivity { /** * Immutable empty String array */ @@ -34,8 +33,7 @@ public class AccessibleEmailContentActivity extends ListActivity * Called when the activity is first created. */ @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); String htmlSource = getIntent().getStringExtra("content"); @@ -43,10 +41,8 @@ public class AccessibleEmailContentActivity extends ListActivity String[] rawListItems = parsedHtml.toString().split("\n"); ArrayList cleanedList = new ArrayList(); - for (String rawListItem : rawListItems) - { - if (rawListItem.trim().length() > 0) - { + for (String rawListItem : rawListItems) { + if (rawListItem.trim().length() > 0) { addToCleanedList(cleanedList, rawListItem); } } @@ -57,30 +53,21 @@ public class AccessibleEmailContentActivity extends ListActivity setListAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, listItems)); } - private void addToCleanedList(ArrayList cleanedList, String line) - { - if (line.length() < 80) - { + private void addToCleanedList(ArrayList cleanedList, String line) { + if (line.length() < 80) { cleanedList.add(line); - } - else - { - while (line.length() > 80) - { + } else { + while (line.length() > 80) { int cutPoint = line.indexOf(" ", 80); - if ((cutPoint > 0) && (cutPoint < line.length())) - { + if ((cutPoint > 0) && (cutPoint < line.length())) { cleanedList.add(line.substring(0, cutPoint)); line = line.substring(cutPoint).trim(); - } - else - { + } else { cleanedList.add(line); line = ""; } } - if (line.length() > 0) - { + if (line.length() > 0) { cleanedList.add(line); } } diff --git a/src/com/fsck/k9/activity/Accounts.java b/src/com/fsck/k9/activity/Accounts.java index 43396a848..75f9f161a 100644 --- a/src/com/fsck/k9/activity/Accounts.java +++ b/src/com/fsck/k9/activity/Accounts.java @@ -32,8 +32,7 @@ import com.fsck.k9.view.ColorChip; import java.util.*; import java.util.concurrent.ConcurrentHashMap; -public class Accounts extends K9ListActivity implements OnItemClickListener, OnClickListener -{ +public class Accounts extends K9ListActivity implements OnItemClickListener, OnClickListener { /** * Immutable empty {@link BaseAccount} array @@ -61,45 +60,33 @@ public class Accounts extends K9ListActivity implements OnItemClickListener, OnC private SearchAccount integratedInboxAccount = null; private FontSizes mFontSizes = K9.getFontSizes(); - class AccountsHandler extends Handler - { - private void setViewTitle() - { + class AccountsHandler extends Handler { + private void setViewTitle() { String dispString = mListener.formatHeader(Accounts.this, getString(R.string.accounts_title), mUnreadMessageCount, getTimeFormat()); setTitle(dispString); } - public void refreshTitle() - { - runOnUiThread(new Runnable() - { - public void run() - { + public void refreshTitle() { + runOnUiThread(new Runnable() { + public void run() { setViewTitle(); } }); } - public void dataChanged() - { - runOnUiThread(new Runnable() - { - public void run() - { - if (mAdapter != null) - { + public void dataChanged() { + runOnUiThread(new Runnable() { + public void run() { + if (mAdapter != null) { mAdapter.notifyDataSetChanged(); } } }); } - public void workingAccount(final Account account, final int res) - { - runOnUiThread(new Runnable() - { - public void run() - { + public void workingAccount(final Account account, final int res) { + runOnUiThread(new Runnable() { + public void run() { String toastText = getString(res, account.getDescription()); Toast toast = Toast.makeText(getApplication(), toastText, Toast.LENGTH_SHORT); @@ -108,15 +95,11 @@ public class Accounts extends K9ListActivity implements OnItemClickListener, OnC }); } - public void accountSizeChanged(final Account account, final long oldSize, final long newSize) - { - runOnUiThread(new Runnable() - { - public void run() - { + public void accountSizeChanged(final Account account, final long oldSize, final long newSize) { + runOnUiThread(new Runnable() { + public void run() { AccountStats stats = accountStats.get(account.getUuid()); - if (newSize != -1 && stats != null && K9.measureAccounts()) - { + if (newSize != -1 && stats != null && K9.measureAccounts()) { stats.size = newSize; } String toastText = getString(R.string.account_size_changed, account.getDescription(), @@ -124,94 +107,71 @@ public class Accounts extends K9ListActivity implements OnItemClickListener, OnC Toast toast = Toast.makeText(getApplication(), toastText, Toast.LENGTH_LONG); toast.show(); - if (mAdapter != null) - { + if (mAdapter != null) { mAdapter.notifyDataSetChanged(); } } }); } - public void progress(final boolean progress) - { - runOnUiThread(new Runnable() - { - public void run() - { + public void progress(final boolean progress) { + runOnUiThread(new Runnable() { + public void run() { setProgressBarIndeterminateVisibility(progress); } }); } - public void progress(final int progress) - { - runOnUiThread(new Runnable() - { - public void run() - { + public void progress(final int progress) { + runOnUiThread(new Runnable() { + public void run() { getWindow().setFeatureInt(Window.FEATURE_PROGRESS, progress); } }); } } - ActivityListener mListener = new ActivityListener() - { + ActivityListener mListener = new ActivityListener() { @Override - public void folderStatusChanged(Account account, String folderName, int unreadMessageCount) - { - try - { + public void folderStatusChanged(Account account, String folderName, int unreadMessageCount) { + try { AccountStats stats = account.getStats(Accounts.this); - if (stats == null) - { + if (stats == null) { Log.w(K9.LOG_TAG, "Unable to get account stats"); - } - else - { + } else { accountStatusChanged(account, stats); } - } - catch (Exception e) - { + } catch (Exception e) { Log.e(K9.LOG_TAG, "Unable to get account stats", e); } } @Override - public void accountStatusChanged(BaseAccount account, AccountStats stats) - { + public void accountStatusChanged(BaseAccount account, AccountStats stats) { AccountStats oldStats = accountStats.get(account.getUuid()); int oldUnreadMessageCount = 0; - if (oldStats != null) - { + if (oldStats != null) { oldUnreadMessageCount = oldStats.unreadMessageCount; } - if (stats == null) - { + if (stats == null) { stats = new AccountStats(); // empty stats for unavailable accounts } accountStats.put(account.getUuid(), stats); - if (account instanceof Account) - { + if (account instanceof Account) { mUnreadMessageCount += stats.unreadMessageCount - oldUnreadMessageCount; } mHandler.dataChanged(); pendingWork.remove(account); - if (pendingWork.isEmpty()) - { + if (pendingWork.isEmpty()) { mHandler.progress(Window.PROGRESS_END); mHandler.refreshTitle(); - } - else - { + } else { int level = (Window.PROGRESS_END / mAdapter.getCount()) * (mAdapter.getCount() - pendingWork.size()) ; mHandler.progress(level); } } @Override - public void accountSizeChanged(Account account, long oldSize, long newSize) - { + public void accountSizeChanged(Account account, long oldSize, long newSize) { mHandler.accountSizeChanged(account, oldSize, newSize); } @@ -220,8 +180,7 @@ public class Accounts extends K9ListActivity implements OnItemClickListener, OnC Account account, String folder, int totalMessagesInMailbox, - int numNewMessages) - { + int numNewMessages) { super.synchronizeMailboxFinished(account, folder, totalMessagesInMailbox, numNewMessages); MessagingController.getInstance(getApplication()).getAccountStats(Accounts.this, account, mListener); @@ -231,24 +190,21 @@ public class Accounts extends K9ListActivity implements OnItemClickListener, OnC } @Override - public void synchronizeMailboxStarted(Account account, String folder) - { + public void synchronizeMailboxStarted(Account account, String folder) { super.synchronizeMailboxStarted(account, folder); mHandler.progress(true); mHandler.refreshTitle(); } @Override - public void synchronizeMailboxProgress(Account account, String folder, int completed, int total) - { + public void synchronizeMailboxProgress(Account account, String folder, int completed, int total) { super.synchronizeMailboxProgress(account, folder, completed, total); mHandler.refreshTitle(); } @Override public void synchronizeMailboxFailed(Account account, String folder, - String message) - { + String message) { super.synchronizeMailboxFailed(account, folder, message); mHandler.progress(false); mHandler.refreshTitle(); @@ -256,58 +212,50 @@ public class Accounts extends K9ListActivity implements OnItemClickListener, OnC } @Override - public void sendPendingMessagesStarted(Account account) - { + public void sendPendingMessagesStarted(Account account) { super.sendPendingMessagesStarted(account); mHandler.refreshTitle(); } @Override - public void sendPendingMessagesCompleted(Account account) - { + public void sendPendingMessagesCompleted(Account account) { super.sendPendingMessagesCompleted(account); mHandler.refreshTitle(); } @Override - public void sendPendingMessagesFailed(Account account) - { + public void sendPendingMessagesFailed(Account account) { super.sendPendingMessagesFailed(account); mHandler.refreshTitle(); } @Override - public void pendingCommandsProcessing(Account account) - { + public void pendingCommandsProcessing(Account account) { super.pendingCommandsProcessing(account); mHandler.refreshTitle(); } @Override - public void pendingCommandsFinished(Account account) - { + public void pendingCommandsFinished(Account account) { super.pendingCommandsFinished(account); mHandler.refreshTitle(); } @Override - public void pendingCommandStarted(Account account, String commandTitle) - { + public void pendingCommandStarted(Account account, String commandTitle) { super.pendingCommandStarted(account, commandTitle); mHandler.refreshTitle(); } @Override - public void pendingCommandCompleted(Account account, String commandTitle) - { + public void pendingCommandCompleted(Account account, String commandTitle) { super.pendingCommandCompleted(account, commandTitle); mHandler.refreshTitle(); } @Override - public void systemStatusChanged() - { + public void systemStatusChanged() { mHandler.refreshTitle(); } }; @@ -318,15 +266,13 @@ public class Accounts extends K9ListActivity implements OnItemClickListener, OnC public static final String EXTRA_STARTUP = "startup"; - public static void actionLaunch(Context context) - { + public static void actionLaunch(Context context) { Intent intent = new Intent(context, Accounts.class); intent.putExtra(EXTRA_STARTUP, true); context.startActivity(intent); } - public static void listAccounts(Context context) - { + public static void listAccounts(Context context) { Intent intent = new Intent(context, Accounts.class); intent.putExtra(EXTRA_STARTUP, false); context.startActivity(intent); @@ -334,8 +280,7 @@ public class Accounts extends K9ListActivity implements OnItemClickListener, OnC @Override - public void onCreate(Bundle icicle) - { + public void onCreate(Bundle icicle) { super.onCreate(icicle); unreadAccount = new SearchAccount(this, false, null, null); @@ -349,20 +294,14 @@ public class Accounts extends K9ListActivity implements OnItemClickListener, OnC Account[] accounts = Preferences.getPreferences(this).getAccounts(); Intent intent = getIntent(); boolean startup = intent.getBooleanExtra(EXTRA_STARTUP, true); - if (startup && K9.startIntegratedInbox()) - { + if (startup && K9.startIntegratedInbox()) { onOpenAccount(integratedInboxAccount); finish(); - } - else if (startup && accounts.length == 1) - { - if (onOpenAccount(accounts[0])) - { + } else if (startup && accounts.length == 1) { + if (onOpenAccount(accounts[0])) { finish(); } - } - else - { + } else { requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); requestWindowFeature(Window.FEATURE_PROGRESS); @@ -374,8 +313,7 @@ public class Accounts extends K9ListActivity implements OnItemClickListener, OnC findViewById(R.id.next).setOnClickListener(this); registerForContextMenu(listView); - if (icicle != null && icicle.containsKey(SELECTED_CONTEXT_ACCOUNT)) - { + if (icicle != null && icicle.containsKey(SELECTED_CONTEXT_ACCOUNT)) { String accountUuid = icicle.getString("selectedContextAccount"); mSelectedContextAccount = Preferences.getPreferences(this).getAccount(accountUuid); } @@ -385,32 +323,26 @@ public class Accounts extends K9ListActivity implements OnItemClickListener, OnC } @SuppressWarnings("unchecked") - private void restoreAccountStats(Bundle icicle) - { - if (icicle != null) - { + private void restoreAccountStats(Bundle icicle) { + if (icicle != null) { Map oldStats = (Map)icicle.get(ACCOUNT_STATS); - if (oldStats != null) - { + if (oldStats != null) { accountStats.putAll(oldStats); } } } @Override - public void onSaveInstanceState(Bundle outState) - { + public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); - if (mSelectedContextAccount != null) - { + if (mSelectedContextAccount != null) { outState.putString(SELECTED_CONTEXT_ACCOUNT, mSelectedContextAccount.getUuid()); } outState.putSerializable(ACCOUNT_STATS, accountStats); } @Override - public void onResume() - { + public void onResume() { super.onResume(); refresh(); @@ -418,19 +350,16 @@ public class Accounts extends K9ListActivity implements OnItemClickListener, OnC } @Override - public void onPause() - { + public void onPause() { super.onPause(); MessagingController.getInstance(getApplication()).removeListener(mListener); } - private void refresh() - { + private void refresh() { BaseAccount[] accounts = Preferences.getPreferences(this).getAccounts(); List newAccounts = new ArrayList(accounts.length + 4); - if (accounts.length > 0) - { + if (accounts.length > 0) { newAccounts.add(integratedInboxAccount); newAccounts.add(unreadAccount); } @@ -439,31 +368,24 @@ public class Accounts extends K9ListActivity implements OnItemClickListener, OnC mAdapter = new AccountsAdapter(newAccounts.toArray(EMPTY_BASE_ACCOUNT_ARRAY)); getListView().setAdapter(mAdapter); - if (newAccounts.size() > 0) - { + if (newAccounts.size() > 0) { mHandler.progress(Window.PROGRESS_START); } pendingWork.clear(); - for (BaseAccount account : newAccounts) - { + for (BaseAccount account : newAccounts) { - if (account instanceof Account) - { + if (account instanceof Account) { pendingWork.put(account, "true"); Account realAccount = (Account)account; MessagingController.getInstance(getApplication()).getAccountStats(Accounts.this, realAccount, mListener); - } - else if (K9.countSearchMessages() && account instanceof SearchAccount) - { + } else if (K9.countSearchMessages() && account instanceof SearchAccount) { pendingWork.put(account, "true"); final SearchAccount searchAccount = (SearchAccount)account; - MessagingController.getInstance(getApplication()).searchLocalMessages(searchAccount, null, new MessagingListener() - { + MessagingController.getInstance(getApplication()).searchLocalMessages(searchAccount, null, new MessagingListener() { @Override - public void searchStats(AccountStats stats) - { + public void searchStats(AccountStats stats) { mListener.accountStatusChanged(searchAccount, stats); } }); @@ -472,18 +394,15 @@ public class Accounts extends K9ListActivity implements OnItemClickListener, OnC } - private void onAddNewAccount() - { + private void onAddNewAccount() { AccountSetupBasics.actionNewAccount(this); } - private void onEditAccount(Account account) - { + private void onEditAccount(Account account) { AccountSettings.actionSettings(this, account); } - private void onEditPrefs() - { + private void onEditPrefs() { Prefs.actionPrefs(this); } @@ -493,40 +412,30 @@ public class Accounts extends K9ListActivity implements OnItemClickListener, OnC * all accounts are to be checked. This is handled accordingly in * MessagingController.checkMail(). */ - private void onCheckMail(Account account) - { + private void onCheckMail(Account account) { MessagingController.getInstance(getApplication()).checkMail(this, account, true, true, null); - if (account == null) - { + if (account == null) { MessagingController.getInstance(getApplication()).sendPendingMessages(null); - } - else - { + } else { MessagingController.getInstance(getApplication()).sendPendingMessages(account, null); } } - private void onClearCommands(Account account) - { + private void onClearCommands(Account account) { MessagingController.getInstance(getApplication()).clearAllPending(account); } - private void onEmptyTrash(Account account) - { + private void onEmptyTrash(Account account) { MessagingController.getInstance(getApplication()).emptyTrash(account, null); } - private void onCompose() - { + private void onCompose() { Account defaultAccount = Preferences.getPreferences(this).getDefaultAccount(); - if (defaultAccount != null) - { + if (defaultAccount != null) { MessageCompose.actionCompose(this, defaultAccount); - } - else - { + } else { onAddNewAccount(); } } @@ -537,108 +446,86 @@ public class Accounts extends K9ListActivity implements OnItemClickListener, OnC * @param account the account to open ({@link SearchAccount} or {@link Account}) * @return false if unsuccessfull */ - private boolean onOpenAccount(BaseAccount account) - { - if (account instanceof SearchAccount) - { + private boolean onOpenAccount(BaseAccount account) { + if (account instanceof SearchAccount) { SearchAccount searchAccount = (SearchAccount)account; MessageList.actionHandle(this, searchAccount.getDescription(), searchAccount); - } - else - { + } else { Account realAccount = (Account)account; - if (!realAccount.isAvailable(this)) - { + if (!realAccount.isAvailable(this)) { Log.i(K9.LOG_TAG, "refusing to open account that is not available"); return false; } - if (K9.FOLDER_NONE.equals(realAccount.getAutoExpandFolderName())) - { + if (K9.FOLDER_NONE.equals(realAccount.getAutoExpandFolderName())) { FolderList.actionHandleAccount(this, realAccount); - } - else - { + } else { MessageList.actionHandleFolder(this, realAccount, realAccount.getAutoExpandFolderName()); } } return true; } - public void onClick(View view) - { - if (view.getId() == R.id.next) - { + public void onClick(View view) { + if (view.getId() == R.id.next) { onAddNewAccount(); } } - private void onDeleteAccount(Account account) - { + private void onDeleteAccount(Account account) { mSelectedContextAccount = account; showDialog(DIALOG_REMOVE_ACCOUNT); } @Override - public Dialog onCreateDialog(int id) - { - switch (id) - { - case DIALOG_REMOVE_ACCOUNT: - return createRemoveAccountDialog(); - case DIALOG_CLEAR_ACCOUNT: - return createClearAccountDialog(); - case DIALOG_RECREATE_ACCOUNT: - return createRecreateAccountDialog(); + public Dialog onCreateDialog(int id) { + switch (id) { + case DIALOG_REMOVE_ACCOUNT: + return createRemoveAccountDialog(); + case DIALOG_CLEAR_ACCOUNT: + return createClearAccountDialog(); + case DIALOG_RECREATE_ACCOUNT: + return createRecreateAccountDialog(); } return super.onCreateDialog(id); } @Override - public void onPrepareDialog(int id, Dialog d) - { + public void onPrepareDialog(int id, Dialog d) { AlertDialog alert = (AlertDialog) d; - switch (id) - { - case DIALOG_REMOVE_ACCOUNT: - alert.setMessage(getString(R.string.account_delete_dlg_instructions_fmt, - mSelectedContextAccount.getDescription())); - break; - case DIALOG_CLEAR_ACCOUNT: - alert.setMessage(getString(R.string.account_clear_dlg_instructions_fmt, - mSelectedContextAccount.getDescription())); - break; - case DIALOG_RECREATE_ACCOUNT: - alert.setMessage(getString(R.string.account_recreate_dlg_instructions_fmt, - mSelectedContextAccount.getDescription())); - break; + switch (id) { + case DIALOG_REMOVE_ACCOUNT: + alert.setMessage(getString(R.string.account_delete_dlg_instructions_fmt, + mSelectedContextAccount.getDescription())); + break; + case DIALOG_CLEAR_ACCOUNT: + alert.setMessage(getString(R.string.account_clear_dlg_instructions_fmt, + mSelectedContextAccount.getDescription())); + break; + case DIALOG_RECREATE_ACCOUNT: + alert.setMessage(getString(R.string.account_recreate_dlg_instructions_fmt, + mSelectedContextAccount.getDescription())); + break; } super.onPrepareDialog(id, d); } - private Dialog createRemoveAccountDialog() - { + private Dialog createRemoveAccountDialog() { return new AlertDialog.Builder(this) .setTitle(R.string.account_delete_dlg_title) .setMessage(getString(R.string.account_delete_dlg_instructions_fmt, mSelectedContextAccount.getDescription())) - .setPositiveButton(R.string.okay_action, new DialogInterface.OnClickListener() - { - public void onClick(DialogInterface dialog, int whichButton) - { + .setPositiveButton(R.string.okay_action, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int whichButton) { dismissDialog(DIALOG_REMOVE_ACCOUNT); removeDialog(DIALOG_REMOVE_ACCOUNT); - if (mSelectedContextAccount instanceof Account) - { + if (mSelectedContextAccount instanceof Account) { Account realAccount = (Account)mSelectedContextAccount; - try - { + try { realAccount.getLocalStore().delete(); - } - catch (Exception e) - { + } catch (Exception e) { // Ignore, this may lead to localStores on sd-cards that are currently not inserted to be left } MessagingController.getInstance(getApplication()).notifyAccountCancel(Accounts.this, realAccount); @@ -648,10 +535,8 @@ public class Accounts extends K9ListActivity implements OnItemClickListener, OnC } } }) - .setNegativeButton(R.string.cancel_action, new DialogInterface.OnClickListener() - { - public void onClick(DialogInterface dialog, int whichButton) - { + .setNegativeButton(R.string.cancel_action, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int whichButton) { dismissDialog(DIALOG_REMOVE_ACCOUNT); removeDialog(DIALOG_REMOVE_ACCOUNT); } @@ -659,30 +544,24 @@ public class Accounts extends K9ListActivity implements OnItemClickListener, OnC .create(); } - private Dialog createClearAccountDialog() - { + private Dialog createClearAccountDialog() { return new AlertDialog.Builder(this) .setTitle(R.string.account_clear_dlg_title) .setMessage(getString(R.string.account_clear_dlg_instructions_fmt, mSelectedContextAccount.getDescription())) - .setPositiveButton(R.string.okay_action, new DialogInterface.OnClickListener() - { - public void onClick(DialogInterface dialog, int whichButton) - { + .setPositiveButton(R.string.okay_action, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int whichButton) { dismissDialog(DIALOG_CLEAR_ACCOUNT); removeDialog(DIALOG_CLEAR_ACCOUNT); - if (mSelectedContextAccount instanceof Account) - { + if (mSelectedContextAccount instanceof Account) { Account realAccount = (Account)mSelectedContextAccount; mHandler.workingAccount(realAccount, R.string.clearing_account); MessagingController.getInstance(getApplication()).clear(realAccount, null); } } }) - .setNegativeButton(R.string.cancel_action, new DialogInterface.OnClickListener() - { - public void onClick(DialogInterface dialog, int whichButton) - { + .setNegativeButton(R.string.cancel_action, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int whichButton) { dismissDialog(DIALOG_CLEAR_ACCOUNT); removeDialog(DIALOG_CLEAR_ACCOUNT); } @@ -690,30 +569,24 @@ public class Accounts extends K9ListActivity implements OnItemClickListener, OnC .create(); } - private Dialog createRecreateAccountDialog() - { + private Dialog createRecreateAccountDialog() { return new AlertDialog.Builder(this) .setTitle(R.string.account_recreate_dlg_title) .setMessage(getString(R.string.account_recreate_dlg_instructions_fmt, mSelectedContextAccount.getDescription())) - .setPositiveButton(R.string.okay_action, new DialogInterface.OnClickListener() - { - public void onClick(DialogInterface dialog, int whichButton) - { + .setPositiveButton(R.string.okay_action, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int whichButton) { dismissDialog(DIALOG_RECREATE_ACCOUNT); removeDialog(DIALOG_RECREATE_ACCOUNT); - if (mSelectedContextAccount instanceof Account) - { + if (mSelectedContextAccount instanceof Account) { Account realAccount = (Account)mSelectedContextAccount; mHandler.workingAccount(realAccount, R.string.recreating_account); MessagingController.getInstance(getApplication()).recreate(realAccount, null); } } }) - .setNegativeButton(R.string.cancel_action, new DialogInterface.OnClickListener() - { - public void onClick(DialogInterface dialog, int whichButton) - { + .setNegativeButton(R.string.cancel_action, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int whichButton) { dismissDialog(DIALOG_RECREATE_ACCOUNT); removeDialog(DIALOG_RECREATE_ACCOUNT); } @@ -722,117 +595,105 @@ public class Accounts extends K9ListActivity implements OnItemClickListener, OnC } @Override - public boolean onContextItemSelected(MenuItem item) - { + public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo)item.getMenuInfo(); // submenus don't actually set the menuInfo, so the "advanced" // submenu wouldn't work. - if (menuInfo != null) - { + if (menuInfo != null) { mSelectedContextAccount = (BaseAccount)getListView().getItemAtPosition(menuInfo.position); } Account realAccount = null; - if (mSelectedContextAccount instanceof Account) - { + if (mSelectedContextAccount instanceof Account) { realAccount = (Account)mSelectedContextAccount; } - switch (item.getItemId()) - { - case R.id.delete_account: - onDeleteAccount(realAccount); - break; - case R.id.edit_account: - onEditAccount(realAccount); - break; - case R.id.open: - onOpenAccount(mSelectedContextAccount); - break; - case R.id.check_mail: - onCheckMail(realAccount); - break; - case R.id.clear_pending: - onClearCommands(realAccount); - break; - case R.id.empty_trash: - onEmptyTrash(realAccount); - break; - case R.id.compact: - onCompact(realAccount); - break; - case R.id.clear: - onClear(realAccount); - break; - case R.id.recreate: - onRecreate(realAccount); - break; + switch (item.getItemId()) { + case R.id.delete_account: + onDeleteAccount(realAccount); + break; + case R.id.edit_account: + onEditAccount(realAccount); + break; + case R.id.open: + onOpenAccount(mSelectedContextAccount); + break; + case R.id.check_mail: + onCheckMail(realAccount); + break; + case R.id.clear_pending: + onClearCommands(realAccount); + break; + case R.id.empty_trash: + onEmptyTrash(realAccount); + break; + case R.id.compact: + onCompact(realAccount); + break; + case R.id.clear: + onClear(realAccount); + break; + case R.id.recreate: + onRecreate(realAccount); + break; } return true; } - private void onCompact(Account account) - { + private void onCompact(Account account) { mHandler.workingAccount(account, R.string.compacting_account); MessagingController.getInstance(getApplication()).compact(account, null); } - private void onClear(Account account) - { + private void onClear(Account account) { showDialog(DIALOG_CLEAR_ACCOUNT); } - private void onRecreate(Account account) - { + private void onRecreate(Account account) { showDialog(DIALOG_RECREATE_ACCOUNT); } - public void onItemClick(AdapterView parent, View view, int position, long id) - { + public void onItemClick(AdapterView parent, View view, int position, long id) { BaseAccount account = (BaseAccount)parent.getItemAtPosition(position); onOpenAccount(account); } @Override - public boolean onOptionsItemSelected(MenuItem item) - { - switch (item.getItemId()) - { - case R.id.add_new_account: - onAddNewAccount(); - break; - case R.id.edit_prefs: - onEditPrefs(); - break; - case R.id.check_mail: - onCheckMail(null); - break; - case R.id.compose: - onCompose(); - break; - case R.id.about: - onAbout(); - break; - case R.id.search: - onSearchRequested(); - break; - default: - return super.onOptionsItemSelected(item); + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + case R.id.add_new_account: + onAddNewAccount(); + break; + case R.id.edit_prefs: + onEditPrefs(); + break; + case R.id.check_mail: + onCheckMail(null); + break; + case R.id.compose: + onCompose(); + break; + case R.id.about: + onAbout(); + break; + case R.id.search: + onSearchRequested(); + break; + default: + return super.onOptionsItemSelected(item); } return true; } - private static String[][] USED_LIBRARIES = new String[][] - { + private static String[][] USED_LIBRARIES = new String[][] { new String[] {"jutf7", "http://jutf7.sourceforge.net/"}, new String[] {"JZlib", "http://www.jcraft.com/jzlib/"}, new String[] {"Commons IO", "http://commons.apache.org/io/"}, new String[] {"Mime4j", "http://james.apache.org/mime4j/"}, }; - private void onAbout() - { + private void onAbout() { String appName = getString(R.string.app_name); String year = "2011"; WebView wv = new WebView(this); @@ -863,8 +724,7 @@ public class Accounts extends K9ListActivity implements OnItemClickListener, OnC .append("


"); StringBuilder libs = new StringBuilder().append("

    "); - for (String[] library : USED_LIBRARIES) - { + for (String[] library : USED_LIBRARIES) { libs.append("
  • " + library[0] + "
  • "); } libs.append("
"); @@ -881,10 +741,8 @@ public class Accounts extends K9ListActivity implements OnItemClickListener, OnC new AlertDialog.Builder(this) .setView(wv) .setCancelable(true) - .setPositiveButton(R.string.okay_action, new DialogInterface.OnClickListener() - { - public void onClick(DialogInterface d, int c) - { + .setPositiveButton(R.string.okay_action, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface d, int c) { d.dismiss(); } }) @@ -896,79 +754,62 @@ public class Accounts extends K9ListActivity implements OnItemClickListener, OnC * * @return String version */ - private String getVersionNumber() - { + private String getVersionNumber() { String version = "?"; - try - { + try { PackageInfo pi = getPackageManager().getPackageInfo(getPackageName(), 0); version = pi.versionName; - } - catch (PackageManager.NameNotFoundException e) - { + } catch (PackageManager.NameNotFoundException e) { //Log.e(TAG, "Package name not found", e); } return version; } - public boolean onItemLongClick(AdapterView parent, View view, int position, long id) - { + public boolean onItemLongClick(AdapterView parent, View view, int position, long id) { return true; } @Override - public boolean onCreateOptionsMenu(Menu menu) - { + public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.accounts_option, menu); return true; } @Override - public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) - { + public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); menu.setHeaderTitle(R.string.accounts_context_menu_title); getMenuInflater().inflate(R.menu.accounts_context, menu); AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; BaseAccount account = mAdapter.getItem(info.position); - if (account instanceof SearchAccount) - { - for (int i = 0; i < menu.size(); i++) - { + if (account instanceof SearchAccount) { + for (int i = 0; i < menu.size(); i++) { MenuItem item = menu.getItem(i); - if (item.getItemId() != R.id.open) - { + if (item.getItemId() != R.id.open) { item.setVisible(false); } } } } - class AccountsAdapter extends ArrayAdapter - { - public AccountsAdapter(BaseAccount[] accounts) - { + class AccountsAdapter extends ArrayAdapter { + public AccountsAdapter(BaseAccount[] accounts) { super(Accounts.this, 0, accounts); } @Override - public View getView(int position, View convertView, ViewGroup parent) - { + public View getView(int position, View convertView, ViewGroup parent) { final BaseAccount account = getItem(position); View view; - if (convertView != null) - { + if (convertView != null) { view = convertView; - } - else - { + } else { view = getLayoutInflater().inflate(R.layout.accounts_item, parent, false); } AccountViewHolder holder = (AccountViewHolder) view.getTag(); - if (holder == null) - { + if (holder == null) { holder = new AccountViewHolder(); holder.description = (TextView) view.findViewById(R.id.description); holder.email = (TextView) view.findViewById(R.id.email); @@ -1002,35 +843,27 @@ public class Accounts extends K9ListActivity implements OnItemClickListener, OnC holder.description.getBackground().setAlpha(255); } */ - if (stats != null && account instanceof Account && stats.size >= 0) - { + if (stats != null && account instanceof Account && stats.size >= 0) { holder.email.setText(SizeFormatter.formatSize(Accounts.this, stats.size)); holder.email.setVisibility(View.VISIBLE); - } - else - { - if (account.getEmail().equals(account.getDescription())) - { + } else { + if (account.getEmail().equals(account.getDescription())) { holder.email.setVisibility(View.GONE); - } - else - { + } else { holder.email.setVisibility(View.VISIBLE); holder.email.setText(account.getEmail()); } } String description = account.getDescription(); - if (description == null || description.length() == 0) - { + if (description == null || description.length() == 0) { description = account.getEmail(); } holder.description.setText(description); Integer unreadMessageCount = null; - if (stats != null) - { + if (stats != null) { unreadMessageCount = stats.unreadMessageCount; holder.newMessageCount.setText(Integer.toString(unreadMessageCount)); holder.newMessageCount.setVisibility(unreadMessageCount > 0 ? View.VISIBLE : View.GONE); @@ -1041,43 +874,31 @@ public class Accounts extends K9ListActivity implements OnItemClickListener, OnC holder.flaggedMessageCount.setOnClickListener(new AccountClickListener(account, SearchModifier.FLAGGED)); holder.newMessageCount.setOnClickListener(new AccountClickListener(account, SearchModifier.UNREAD)); - holder.activeIcons.setOnClickListener(new OnClickListener() - { - public void onClick(View v) - { + holder.activeIcons.setOnClickListener(new OnClickListener() { + public void onClick(View v) { Toast toast = Toast.makeText(getApplication(), getString(R.string.tap_hint), Toast.LENGTH_SHORT); toast.show(); } } ); - } - else - { + } else { holder.newMessageCount.setVisibility(View.GONE); holder.flaggedMessageCount.setVisibility(View.GONE); } - if (account instanceof Account) - { + if (account instanceof Account) { Account realAccount = (Account)account; holder.chip.setBackgroundDrawable(realAccount.generateColorChip().drawable()); - if (unreadMessageCount == null) - { + if (unreadMessageCount == null) { holder.chip.getBackground().setAlpha(0); - } - else if (unreadMessageCount == 0) - { + } else if (unreadMessageCount == 0) { holder.chip.getBackground().setAlpha(127); - } - else - { + } else { holder.chip.getBackground().setAlpha(255); } - } - else - { + } else { holder.chip.setBackgroundDrawable(new ColorChip(0xff999999).drawable()); } @@ -1085,22 +906,16 @@ public class Accounts extends K9ListActivity implements OnItemClickListener, OnC holder.description.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mFontSizes.getAccountName()); holder.email.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mFontSizes.getAccountDescription()); - if (K9.useCompactLayouts()) - { + if (K9.useCompactLayouts()) { holder.accountsItemLayout.setMinimumHeight(0); } - if (account instanceof SearchAccount || K9.useCompactLayouts()) - { + if (account instanceof SearchAccount || K9.useCompactLayouts()) { holder.folders.setVisibility(View.GONE); - } - else - { + } else { holder.folders.setVisibility(View.VISIBLE); - holder.folders.setOnClickListener(new OnClickListener() - { - public void onClick(View v) - { + holder.folders.setOnClickListener(new OnClickListener() { + public void onClick(View v) { FolderList.actionHandleAccount(Accounts.this, (Account)account); } @@ -1110,8 +925,7 @@ public class Accounts extends K9ListActivity implements OnItemClickListener, OnC return view; } - class AccountViewHolder - { + class AccountViewHolder { public TextView description; public TextView email; public TextView newMessageCount; @@ -1122,14 +936,11 @@ public class Accounts extends K9ListActivity implements OnItemClickListener, OnC public LinearLayout accountsItemLayout; } } - private Flag[] combine(Flag[] set1, Flag[] set2) - { - if (set1 == null) - { + private Flag[] combine(Flag[] set1, Flag[] set2) { + if (set1 == null) { return set2; } - if (set2 == null) - { + if (set2 == null) { return set1; } Set flags = new HashSet(); @@ -1138,66 +949,53 @@ public class Accounts extends K9ListActivity implements OnItemClickListener, OnC return flags.toArray(EMPTY_FLAG_ARRAY); } - private class AccountClickListener implements OnClickListener - { + private class AccountClickListener implements OnClickListener { final BaseAccount account; final SearchModifier searchModifier; - AccountClickListener(BaseAccount nAccount, SearchModifier nSearchModifier) - { + AccountClickListener(BaseAccount nAccount, SearchModifier nSearchModifier) { account = nAccount; searchModifier = nSearchModifier; } @Override - public void onClick(View v) - { + public void onClick(View v) { String description = getString(R.string.search_title, account.getDescription(), getString(searchModifier.resId)); - if (account instanceof SearchAccount) - { + if (account instanceof SearchAccount) { SearchAccount searchAccount = (SearchAccount)account; MessageList.actionHandle(Accounts.this, description, "", searchAccount.isIntegrate(), combine(searchAccount.getRequiredFlags(), searchModifier.requiredFlags), combine(searchAccount.getForbiddenFlags(), searchModifier.forbiddenFlags)); - } - else - { - SearchSpecification searchSpec = new SearchSpecification() - { + } else { + SearchSpecification searchSpec = new SearchSpecification() { @Override - public String[] getAccountUuids() - { + public String[] getAccountUuids() { return new String[] { account.getUuid() }; } @Override - public Flag[] getForbiddenFlags() - { + public Flag[] getForbiddenFlags() { return searchModifier.forbiddenFlags; } @Override - public String getQuery() - { + public String getQuery() { return ""; } @Override - public Flag[] getRequiredFlags() - { + public Flag[] getRequiredFlags() { return searchModifier.requiredFlags; } @Override - public boolean isIntegrate() - { + public boolean isIntegrate() { return false; } @Override - public String[] getFolderNames() - { + public String[] getFolderNames() { return null; } diff --git a/src/com/fsck/k9/activity/ActivityListener.java b/src/com/fsck/k9/activity/ActivityListener.java index 1a1b7354f..e458a251a 100644 --- a/src/com/fsck/k9/activity/ActivityListener.java +++ b/src/com/fsck/k9/activity/ActivityListener.java @@ -10,8 +10,7 @@ import com.fsck.k9.R; import com.fsck.k9.controller.MessagingListener; import com.fsck.k9.service.MailService; -public class ActivityListener extends MessagingListener -{ +public class ActivityListener extends MessagingListener { private String mLoadingFolderName = null; private String mLoadingHeaderFolderName = null; private String mLoadingAccountDescription = null; @@ -22,61 +21,44 @@ public class ActivityListener extends MessagingListener private String mProcessingCommandTitle = null; - public String formatHeader(Context context, String activityPrefix, int unreadMessageCount, DateFormat timeFormat) - { + public String formatHeader(Context context, String activityPrefix, int unreadMessageCount, DateFormat timeFormat) { String operation = null; String progress = null; if (mLoadingAccountDescription != null || mSendingAccountDescription != null || mLoadingHeaderFolderName != null - || mProcessingAccountDescription != null) - { + || mProcessingAccountDescription != null) { progress = (mFolderTotal > 0 ? context.getString(R.string.folder_progress, mFolderCompleted, mFolderTotal) : ""); - if (mLoadingFolderName != null || mLoadingHeaderFolderName != null) - { + if (mLoadingFolderName != null || mLoadingHeaderFolderName != null) { String displayName = mLoadingFolderName; - if (K9.INBOX.equalsIgnoreCase(displayName)) - { + if (K9.INBOX.equalsIgnoreCase(displayName)) { displayName = context.getString(R.string.special_mailbox_name_inbox); } - if (mLoadingHeaderFolderName != null) - { + if (mLoadingHeaderFolderName != null) { operation = context.getString(R.string.status_loading_account_folder_headers, mLoadingAccountDescription, displayName, progress); - } - else - { + } else { operation = context.getString(R.string.status_loading_account_folder, mLoadingAccountDescription, displayName, progress); } } - else if (mSendingAccountDescription != null) - { + else if (mSendingAccountDescription != null) { operation = context.getString(R.string.status_sending_account, mSendingAccountDescription, progress); - } - else if (mProcessingAccountDescription != null) - { + } else if (mProcessingAccountDescription != null) { operation = context.getString(R.string.status_processing_account, mProcessingAccountDescription, mProcessingCommandTitle != null ? mProcessingCommandTitle : "", progress); } - } - else - { + } else { long nextPollTime = MailService.getNextPollTime(); - if (nextPollTime != -1) - { + if (nextPollTime != -1) { operation = context.getString(R.string.status_next_poll, timeFormat.format(nextPollTime)); - } - else if (MailService.isSyncDisabled()) - { + } else if (MailService.isSyncDisabled()) { operation = context.getString(R.string.status_syncing_off); - } - else - { + } else { operation = ""; } } @@ -93,15 +75,13 @@ public class ActivityListener extends MessagingListener Account account, String folder, int totalMessagesInMailbox, - int numNewMessages) - { + int numNewMessages) { mLoadingAccountDescription = null; mLoadingFolderName = null; } @Override - public void synchronizeMailboxStarted(Account account, String folder) - { + public void synchronizeMailboxStarted(Account account, String folder) { mLoadingAccountDescription = account.getDescription(); mLoadingFolderName = folder; mFolderCompleted = 0; @@ -110,23 +90,20 @@ public class ActivityListener extends MessagingListener @Override - public void synchronizeMailboxHeadersStarted(Account account, String folder) - { + public void synchronizeMailboxHeadersStarted(Account account, String folder) { mLoadingHeaderFolderName = folder; } @Override - public void synchronizeMailboxHeadersProgress(Account account, String folder, int completed, int total) - { + public void synchronizeMailboxHeadersProgress(Account account, String folder, int completed, int total) { mFolderCompleted = completed; mFolderTotal = total; } @Override public void synchronizeMailboxHeadersFinished(Account account, String folder, - int total, int completed) - { + int total, int completed) { mLoadingHeaderFolderName = null; mFolderCompleted = 0; mFolderTotal = 0; @@ -134,72 +111,61 @@ public class ActivityListener extends MessagingListener @Override - public void synchronizeMailboxProgress(Account account, String folder, int completed, int total) - { + public void synchronizeMailboxProgress(Account account, String folder, int completed, int total) { mFolderCompleted = completed; mFolderTotal = total; } @Override public void synchronizeMailboxFailed(Account account, String folder, - String message) - { + String message) { mLoadingAccountDescription = null; mLoadingFolderName = null; } @Override - public void sendPendingMessagesStarted(Account account) - { + public void sendPendingMessagesStarted(Account account) { mSendingAccountDescription = account.getDescription(); } @Override - public void sendPendingMessagesCompleted(Account account) - { + public void sendPendingMessagesCompleted(Account account) { mSendingAccountDescription = null; } @Override - public void sendPendingMessagesFailed(Account account) - { + public void sendPendingMessagesFailed(Account account) { mSendingAccountDescription = null; } @Override - public void pendingCommandsProcessing(Account account) - { + public void pendingCommandsProcessing(Account account) { mProcessingAccountDescription = account.getDescription(); mFolderCompleted = 0; mFolderTotal = 0; } @Override - public void pendingCommandsFinished(Account account) - { + public void pendingCommandsFinished(Account account) { mProcessingAccountDescription = null; } @Override - public void pendingCommandStarted(Account account, String commandTitle) - { + public void pendingCommandStarted(Account account, String commandTitle) { mProcessingCommandTitle = commandTitle; } @Override - public void pendingCommandCompleted(Account account, String commandTitle) - { + public void pendingCommandCompleted(Account account, String commandTitle) { mProcessingCommandTitle = null; } - public int getFolderCompleted() - { + public int getFolderCompleted() { return mFolderCompleted; } - public int getFolderTotal() - { + public int getFolderTotal() { return mFolderTotal; } diff --git a/src/com/fsck/k9/activity/ChooseAccount.java b/src/com/fsck/k9/activity/ChooseAccount.java index 75a186432..6b04f6b76 100644 --- a/src/com/fsck/k9/activity/ChooseAccount.java +++ b/src/com/fsck/k9/activity/ChooseAccount.java @@ -27,8 +27,7 @@ import java.util.List; * * @see K9ExpandableListActivity */ -public class ChooseAccount extends K9ExpandableListActivity -{ +public class ChooseAccount extends K9ExpandableListActivity { /** * {@link Intent} extended data name for storing {@link Account#getUuid() @@ -42,8 +41,7 @@ public class ChooseAccount extends K9ExpandableListActivity public static final String EXTRA_IDENTITY = ChooseAccount.class.getName() + "_identity"; @Override - protected void onCreate(final Bundle savedInstanceState) - { + protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); @@ -55,17 +53,14 @@ public class ChooseAccount extends K9ExpandableListActivity final ExpandableListAdapter adapter = createAdapter(); setListAdapter(adapter); - expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() - { + expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() { @Override public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, - int childPosition, long id) - { + int childPosition, long id) { final Identity identity = (Identity) adapter.getChild(groupPosition, childPosition); final Account account = (Account) adapter.getGroup(groupPosition); - if (!account.isAvailable(v.getContext())) - { + if (!account.isAvailable(v.getContext())) { Log.i(K9.LOG_TAG, "Refusing selection of unavailable account"); return true; } @@ -81,15 +76,12 @@ public class ChooseAccount extends K9ExpandableListActivity final Bundle extras = getIntent().getExtras(); final String uuid = extras.getString(EXTRA_ACCOUNT); - if (uuid != null) - { + if (uuid != null) { final Account[] accounts = Preferences.getPreferences(this).getAccounts(); final int length = accounts.length; - for (int i = 0; i < length; i++) - { + for (int i = 0; i < length; i++) { final Account account = accounts[i]; - if (uuid.equals(account.getUuid())) - { + if (uuid.equals(account.getUuid())) { // setSelectedChild() doesn't seem to obey the // shouldExpandGroup parameter (2.1), manually expanding // group @@ -97,16 +89,13 @@ public class ChooseAccount extends K9ExpandableListActivity final List identities = account.getIdentities(); final Identity identity = (Identity) extras.getSerializable(EXTRA_IDENTITY); - if (identity == null) - { + if (identity == null) { expandableListView.setSelectedChild(i, 0, true); break; } - for (int j = 0; j < identities.size(); j++) - { + for (int j = 0; j < identities.size(); j++) { final Identity loopIdentity = identities.get(j); - if (identity.equals(loopIdentity)) - { + if (identity.equals(loopIdentity)) { expandableListView.setSelectedChild(i, j, true); break; } @@ -117,8 +106,7 @@ public class ChooseAccount extends K9ExpandableListActivity } } - private ExpandableListAdapter createAdapter() - { + private ExpandableListAdapter createAdapter() { return new IdentitiesAdapter(this, getLayoutInflater()); } @@ -131,65 +119,53 @@ public class ChooseAccount extends K9ExpandableListActivity *
  • Children represent {@link Identity identities} of the parent account
  • * */ - public static class IdentitiesAdapter extends BaseExpandableListAdapter - { + public static class IdentitiesAdapter extends BaseExpandableListAdapter { private Context mContext; private LayoutInflater mLayoutInflater; - public IdentitiesAdapter(final Context context, final LayoutInflater layoutInflater) - { + public IdentitiesAdapter(final Context context, final LayoutInflater layoutInflater) { mContext = context; mLayoutInflater = layoutInflater; } @Override - public Object getChild(int groupPosition, int childPosition) - { + public Object getChild(int groupPosition, int childPosition) { return getAccounts()[groupPosition].getIdentity(childPosition); } @Override - public long getChildId(int groupPosition, int childPosition) - { + public long getChildId(int groupPosition, int childPosition) { return Integer.valueOf(childPosition).longValue(); } @Override - public int getChildrenCount(int groupPosition) - { + public int getChildrenCount(int groupPosition) { return getAccounts()[groupPosition].getIdentities().size(); } @Override - public Object getGroup(int groupPosition) - { + public Object getGroup(int groupPosition) { return getAccounts()[groupPosition]; } @Override - public int getGroupCount() - { + public int getGroupCount() { return getAccounts().length; } @Override - public long getGroupId(int groupPosition) - { + public long getGroupId(int groupPosition) { return Integer.valueOf(groupPosition).longValue(); } @Override public View getGroupView(int groupPosition, boolean isExpanded, View convertView, - ViewGroup parent) - { + ViewGroup parent) { final View v; - if (convertView == null) - { + if (convertView == null) { v = mLayoutInflater.inflate(R.layout.choose_account_item, parent, false); - } - else - { + } else { v = convertView; } @@ -221,18 +197,14 @@ public class ChooseAccount extends K9ExpandableListActivity @Override public View getChildView(int groupPosition, int childPosition, boolean isLastChild, - View convertView, ViewGroup parent) - { + View convertView, ViewGroup parent) { final Account account = getAccounts()[groupPosition]; final Identity identity = account.getIdentity(childPosition); final View v; - if (convertView == null) - { + if (convertView == null) { v = mLayoutInflater.inflate(R.layout.choose_identity_item, parent, false); - } - else - { + } else { v = convertView; } @@ -250,20 +222,17 @@ public class ChooseAccount extends K9ExpandableListActivity } @Override - public boolean hasStableIds() - { + public boolean hasStableIds() { // returning false since accounts/identities are mutable return false; } @Override - public boolean isChildSelectable(int groupPosition, int childPosition) - { + public boolean isChildSelectable(int groupPosition, int childPosition) { return true; } - private Account[] getAccounts() - { + private Account[] getAccounts() { return Preferences.getPreferences(mContext).getAccounts(); } } diff --git a/src/com/fsck/k9/activity/ChooseFolder.java b/src/com/fsck/k9/activity/ChooseFolder.java index 843e87035..4f1a42866 100644 --- a/src/com/fsck/k9/activity/ChooseFolder.java +++ b/src/com/fsck/k9/activity/ChooseFolder.java @@ -24,8 +24,7 @@ import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; -public class ChooseFolder extends K9ListActivity -{ +public class ChooseFolder extends K9ListActivity { String mFolder; String mSelectFolder; Account mAccount; @@ -61,8 +60,7 @@ public class ChooseFolder extends K9ListActivity public static final String EXTRA_SHOW_DISPLAYABLE_ONLY = "com.fsck.k9.ChooseFolder_showDisplayableOnly"; @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); @@ -75,30 +73,24 @@ public class ChooseFolder extends K9ListActivity mMessageReference = (MessageReference)intent.getSerializableExtra(EXTRA_MESSAGE); mFolder = intent.getStringExtra(EXTRA_CUR_FOLDER); mSelectFolder = intent.getStringExtra(EXTRA_SEL_FOLDER); - if (intent.getStringExtra(EXTRA_SHOW_CURRENT) != null) - { + if (intent.getStringExtra(EXTRA_SHOW_CURRENT) != null) { hideCurrentFolder = false; } - if (intent.getStringExtra(EXTRA_SHOW_FOLDER_NONE) != null) - { + if (intent.getStringExtra(EXTRA_SHOW_FOLDER_NONE) != null) { showOptionNone = true; } - if (intent.getStringExtra(EXTRA_SHOW_DISPLAYABLE_ONLY) != null) - { + if (intent.getStringExtra(EXTRA_SHOW_DISPLAYABLE_ONLY) != null) { showDisplayableOnly = true; } if (mFolder == null) mFolder = ""; - mAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1) - { + mAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1) { private Filter myFilter = null; @Override - public Filter getFilter() - { - if (myFilter == null) - { + public Filter getFilter() { + if (myFilter == null) { myFilter = new FolderListFilter(this); } return myFilter; @@ -111,16 +103,13 @@ public class ChooseFolder extends K9ListActivity MessagingController.getInstance(getApplication()).listFolders(mAccount, false, mListener); - this.getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() - { - public void onItemClick(AdapterView parent, View view, int position, long id) - { + this.getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() { + public void onItemClick(AdapterView parent, View view, int position, long id) { Intent intent = new Intent(); intent.putExtra(EXTRA_ACCOUNT, mAccount.getUuid()); intent.putExtra(EXTRA_CUR_FOLDER, mFolder); String destFolderName = (String)((TextView)view).getText(); - if (heldInbox != null && getString(R.string.special_mailbox_name_inbox).equals(destFolderName)) - { + if (heldInbox != null && getString(R.string.special_mailbox_name_inbox).equals(destFolderName)) { destFolderName = heldInbox; } intent.putExtra(EXTRA_NEW_FOLDER, destFolderName); @@ -132,8 +121,7 @@ public class ChooseFolder extends K9ListActivity } - class ChooseFolderHandler extends Handler - { + class ChooseFolderHandler extends Handler { private static final int MSG_PROGRESS = 2; @@ -141,95 +129,81 @@ public class ChooseFolder extends K9ListActivity private static final int MSG_SET_SELECTED_FOLDER = 4; @Override - public void handleMessage(android.os.Message msg) - { - switch (msg.what) - { - case MSG_PROGRESS: - setProgressBarIndeterminateVisibility(msg.arg1 != 0); - break; - case MSG_DATA_CHANGED: - mAdapter.notifyDataSetChanged(); + public void handleMessage(android.os.Message msg) { + switch (msg.what) { + case MSG_PROGRESS: + setProgressBarIndeterminateVisibility(msg.arg1 != 0); + break; + case MSG_DATA_CHANGED: + mAdapter.notifyDataSetChanged(); - /* - * Only enable the text filter after the list has been - * populated to avoid possible race conditions because our - * FolderListFilter isn't really thread-safe. - */ - getListView().setTextFilterEnabled(true); - break; - case MSG_SET_SELECTED_FOLDER: - getListView().setSelection(msg.arg1); - break; + /* + * Only enable the text filter after the list has been + * populated to avoid possible race conditions because our + * FolderListFilter isn't really thread-safe. + */ + getListView().setTextFilterEnabled(true); + break; + case MSG_SET_SELECTED_FOLDER: + getListView().setSelection(msg.arg1); + break; } } - public void progress(boolean progress) - { + public void progress(boolean progress) { android.os.Message msg = new android.os.Message(); msg.what = MSG_PROGRESS; msg.arg1 = progress ? 1 : 0; sendMessage(msg); } - public void setSelectedFolder(int position) - { + public void setSelectedFolder(int position) { android.os.Message msg = new android.os.Message(); msg.what = MSG_SET_SELECTED_FOLDER; msg.arg1 = position; sendMessage(msg); } - public void dataChanged() - { + public void dataChanged() { sendEmptyMessage(MSG_DATA_CHANGED); } } - @Override public boolean onCreateOptionsMenu(Menu menu) - { + @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.folder_select_option, menu); return true; } - @Override public boolean onOptionsItemSelected(MenuItem item) - { - switch (item.getItemId()) - { + @Override public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { - case R.id.display_1st_class: - { - setDisplayMode(FolderMode.FIRST_CLASS); - return true; - } - case R.id.display_1st_and_2nd_class: - { - setDisplayMode(FolderMode.FIRST_AND_SECOND_CLASS); - return true; - } - case R.id.display_not_second_class: - { - setDisplayMode(FolderMode.NOT_SECOND_CLASS); - return true; - } - case R.id.display_all: - { - setDisplayMode(FolderMode.ALL); - return true; - } - default: - return super.onOptionsItemSelected(item); + case R.id.display_1st_class: { + setDisplayMode(FolderMode.FIRST_CLASS); + return true; + } + case R.id.display_1st_and_2nd_class: { + setDisplayMode(FolderMode.FIRST_AND_SECOND_CLASS); + return true; + } + case R.id.display_not_second_class: { + setDisplayMode(FolderMode.NOT_SECOND_CLASS); + return true; + } + case R.id.display_all: { + setDisplayMode(FolderMode.ALL); + return true; + } + default: + return super.onOptionsItemSelected(item); } } - private void setDisplayMode(FolderMode aMode) - { + private void setDisplayMode(FolderMode aMode) { mMode = aMode; // invalidate the current filter as it is working on an inval - if (myFilter != null) - { + if (myFilter != null) { myFilter.invalidate(); } //re-populate the list @@ -237,59 +211,47 @@ public class ChooseFolder extends K9ListActivity false, mListener); } - private MessagingListener mListener = new MessagingListener() - { + private MessagingListener mListener = new MessagingListener() { @Override - public void listFoldersStarted(Account account) - { - if (!account.equals(mAccount)) - { + public void listFoldersStarted(Account account) { + if (!account.equals(mAccount)) { return; } mHandler.progress(true); } @Override - public void listFoldersFailed(Account account, String message) - { - if (!account.equals(mAccount)) - { + public void listFoldersFailed(Account account, String message) { + if (!account.equals(mAccount)) { return; } mHandler.progress(false); } @Override - public void listFoldersFinished(Account account) - { - if (!account.equals(mAccount)) - { + public void listFoldersFinished(Account account) { + if (!account.equals(mAccount)) { return; } mHandler.progress(false); } @Override - public void listFolders(Account account, Folder[] folders) - { - if (!account.equals(mAccount)) - { + public void listFolders(Account account, Folder[] folders) { + if (!account.equals(mAccount)) { return; } Account.FolderMode aMode = mMode; Preferences prefs = Preferences.getPreferences(getApplication().getApplicationContext()); ArrayList localFolders = new ArrayList(); - for (Folder folder : folders) - { + for (Folder folder : folders) { String name = folder.getName(); // Inbox needs to be compared case-insensitively - if (hideCurrentFolder && (name.equals(mFolder) || (K9.INBOX.equalsIgnoreCase(mFolder) && K9.INBOX.equalsIgnoreCase(name)))) - { + if (hideCurrentFolder && (name.equals(mFolder) || (K9.INBOX.equalsIgnoreCase(mFolder) && K9.INBOX.equalsIgnoreCase(name)))) { continue; } - try - { + try { folder.refresh(prefs); Folder.FolderClass fMode = folder.getDisplayClass(); @@ -297,13 +259,10 @@ public class ChooseFolder extends K9ListActivity || (aMode == Account.FolderMode.FIRST_AND_SECOND_CLASS && fMode != Folder.FolderClass.FIRST_CLASS && fMode != Folder.FolderClass.SECOND_CLASS) - || (aMode == Account.FolderMode.NOT_SECOND_CLASS && fMode == Folder.FolderClass.SECOND_CLASS)) - { + || (aMode == Account.FolderMode.NOT_SECOND_CLASS && fMode == Folder.FolderClass.SECOND_CLASS)) { continue; } - } - catch (MessagingException me) - { + } catch (MessagingException me) { Log.e(K9.LOG_TAG, "Couldn't get prefs to check for displayability of folder " + folder.getName(), me); } @@ -311,29 +270,22 @@ public class ChooseFolder extends K9ListActivity } - if (showOptionNone) - { + if (showOptionNone) { localFolders.add(K9.FOLDER_NONE); } - Collections.sort(localFolders, new Comparator() - { - public int compare(String aName, String bName) - { - if (K9.FOLDER_NONE.equalsIgnoreCase(aName)) - { + Collections.sort(localFolders, new Comparator() { + public int compare(String aName, String bName) { + if (K9.FOLDER_NONE.equalsIgnoreCase(aName)) { return -1; } - if (K9.FOLDER_NONE.equalsIgnoreCase(bName)) - { + if (K9.FOLDER_NONE.equalsIgnoreCase(bName)) { return 1; } - if (K9.INBOX.equalsIgnoreCase(aName)) - { + if (K9.INBOX.equalsIgnoreCase(aName)) { return -1; } - if (K9.INBOX.equalsIgnoreCase(bName)) - { + if (K9.INBOX.equalsIgnoreCase(bName)) { return 1; } @@ -342,49 +294,36 @@ public class ChooseFolder extends K9ListActivity }); mAdapter.setNotifyOnChange(false); int selectedFolder = -1; - try - { + try { mAdapter.clear(); int position = 0; - for (String name : localFolders) - { - if (K9.INBOX.equalsIgnoreCase(name)) - { + for (String name : localFolders) { + if (K9.INBOX.equalsIgnoreCase(name)) { mAdapter.add(getString(R.string.special_mailbox_name_inbox)); heldInbox = name; - } - else if (!K9.ERROR_FOLDER_NAME.equals(name)) - { + } else if (!K9.ERROR_FOLDER_NAME.equals(name)) { mAdapter.add(name); } - if (mSelectFolder != null) - { + if (mSelectFolder != null) { /* * Never select EXTRA_CUR_FOLDER (mFolder) if EXTRA_SEL_FOLDER * (mSelectedFolder) was provided. */ - if (name.equals(mSelectFolder)) - { + if (name.equals(mSelectFolder)) { selectedFolder = position; } - } - else if (name.equals(mFolder) || - (K9.INBOX.equalsIgnoreCase(mFolder) && K9.INBOX.equalsIgnoreCase(name))) - { + } else if (name.equals(mFolder) || + (K9.INBOX.equalsIgnoreCase(mFolder) && K9.INBOX.equalsIgnoreCase(name))) { selectedFolder = position; } position++; } - } - finally - { + } finally { mAdapter.setNotifyOnChange(true); - runOnUiThread(new Runnable() - { - public void run() - { + runOnUiThread(new Runnable() { + public void run() { // runOnUiThread( mAdapter.notifyDataSetChanged(); } @@ -393,8 +332,7 @@ public class ChooseFolder extends K9ListActivity mHandler.dataChanged(); - if (selectedFolder != -1) - { + if (selectedFolder != -1) { mHandler.setSelectedFolder(selectedFolder); } } diff --git a/src/com/fsck/k9/activity/ChooseIdentity.java b/src/com/fsck/k9/activity/ChooseIdentity.java index 7c6336ad8..a769ddfae 100644 --- a/src/com/fsck/k9/activity/ChooseIdentity.java +++ b/src/com/fsck/k9/activity/ChooseIdentity.java @@ -15,8 +15,7 @@ import com.fsck.k9.Preferences; import com.fsck.k9.R; import java.util.List; -public class ChooseIdentity extends K9ListActivity -{ +public class ChooseIdentity extends K9ListActivity { Account mAccount; String mUID; ArrayAdapter adapter; @@ -27,8 +26,7 @@ public class ChooseIdentity extends K9ListActivity protected List identities = null; @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); @@ -48,24 +46,20 @@ public class ChooseIdentity extends K9ListActivity @Override - public void onResume() - { + public void onResume() { super.onResume(); refreshView(); } - protected void refreshView() - { + protected void refreshView() { adapter.setNotifyOnChange(false); adapter.clear(); identities = mAccount.getIdentities(); - for (Identity identity : identities) - { + for (Identity identity : identities) { String description = identity.getDescription(); - if (description == null || description.trim().length() == 0) - { + if (description == null || description.trim().length() == 0) { description = getString(R.string.message_view_from_format, identity.getName(), identity.getEmail()); } adapter.add(description); @@ -74,24 +68,18 @@ public class ChooseIdentity extends K9ListActivity adapter.notifyDataSetChanged(); } - protected void setupClickListeners() - { - this.getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() - { - public void onItemClick(AdapterView parent, View view, int position, long id) - { + protected void setupClickListeners() { + this.getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() { + public void onItemClick(AdapterView parent, View view, int position, long id) { Identity identity = mAccount.getIdentity(position); String email = identity.getEmail(); - if (email != null && !email.trim().equals("")) - { + if (email != null && !email.trim().equals("")) { Intent intent = new Intent(); intent.putExtra(EXTRA_IDENTITY, mAccount.getIdentity(position)); setResult(RESULT_OK, intent); finish(); - } - else - { + } else { Toast.makeText(ChooseIdentity.this, getString(R.string.identity_has_no_email), Toast.LENGTH_LONG).show(); } diff --git a/src/com/fsck/k9/activity/ColorPickerDialog.java b/src/com/fsck/k9/activity/ColorPickerDialog.java index d892fe6e5..b5f93edee 100644 --- a/src/com/fsck/k9/activity/ColorPickerDialog.java +++ b/src/com/fsck/k9/activity/ColorPickerDialog.java @@ -18,12 +18,10 @@ import android.widget.*; import com.fsck.k9.view.ColorPickerBox; -public class ColorPickerDialog -{ +public class ColorPickerDialog { private static final String TAG = ColorPickerDialog.class.getSimpleName(); - public interface OnColorChangedListener - { + public interface OnColorChangedListener { void colorChanged(int color); } @@ -45,8 +43,7 @@ public class ColorPickerDialog float sizeUiDp = 240.f; float sizeUiPx; // diset di constructor - public ColorPickerDialog(Context context, OnColorChangedListener listener, int color ) - { + public ColorPickerDialog(Context context, OnColorChangedListener listener, int color) { this.listener = listener; this.colorOld = color; this.colorNew = color; @@ -73,15 +70,12 @@ public class ColorPickerDialog viewColorOld.setBackgroundColor(color); viewColorNew.setBackgroundColor(color); - viewHue.setOnTouchListener(new View.OnTouchListener() - { + viewHue.setOnTouchListener(new View.OnTouchListener() { @Override - public boolean onTouch(View v, MotionEvent event) - { + public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_MOVE || event.getAction() == MotionEvent.ACTION_DOWN - || event.getAction() == MotionEvent.ACTION_UP) - { + || event.getAction() == MotionEvent.ACTION_UP) { float y = event.getY(); // dalam px, bukan dp if (y < 0.f) y = 0.f; @@ -101,15 +95,12 @@ public class ColorPickerDialog return false; } }); - viewBox.setOnTouchListener(new View.OnTouchListener() - { + viewBox.setOnTouchListener(new View.OnTouchListener() { @Override - public boolean onTouch(View v, MotionEvent event) - { + public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_MOVE || event.getAction() == MotionEvent.ACTION_DOWN - || event.getAction() == MotionEvent.ACTION_UP) - { + || event.getAction() == MotionEvent.ACTION_UP) { float x = event.getX(); // dalam px, bukan dp float y = event.getY(); // dalam px, bukan dp @@ -135,24 +126,18 @@ public class ColorPickerDialog dialog = new AlertDialog.Builder(context) .setView(view) - .setPositiveButton(R.string.okay_action, new DialogInterface.OnClickListener() - { + .setPositiveButton(R.string.okay_action, new DialogInterface.OnClickListener() { @Override - public void onClick(DialogInterface dialog, int which) - { - if (ColorPickerDialog.this.listener != null) - { + public void onClick(DialogInterface dialog, int which) { + if (ColorPickerDialog.this.listener != null) { ColorPickerDialog.this.listener.colorChanged(colorNew); } } }) - .setNegativeButton(R.string.cancel_action, new DialogInterface.OnClickListener() - { + .setNegativeButton(R.string.cancel_action, new DialogInterface.OnClickListener() { @Override - public void onClick(DialogInterface dialog, int which) - { - if (ColorPickerDialog.this.listener != null) - { + public void onClick(DialogInterface dialog, int which) { + if (ColorPickerDialog.this.listener != null) { } } }) @@ -161,39 +146,35 @@ public class ColorPickerDialog } @SuppressWarnings("deprecation") - protected void placeArrow() - { + protected void placeArrow() { float y = sizeUiPx - (hue * sizeUiPx / 360.f); if (y == sizeUiPx) y = 0.f; AbsoluteLayout.LayoutParams layoutParams = (AbsoluteLayout.LayoutParams) arrow.getLayoutParams(); - layoutParams.y = (int) (y + 4); + layoutParams.y = (int)(y + 4); arrow.setLayoutParams(layoutParams); } @SuppressWarnings("deprecation") - protected void placeSpyglass() - { + protected void placeSpyglass() { float x = sat * sizeUiPx; float y = (1.f - val) * sizeUiPx; AbsoluteLayout.LayoutParams layoutParams = (AbsoluteLayout.LayoutParams) viewSpyglass.getLayoutParams(); - layoutParams.x = (int) (x + 3); - layoutParams.y = (int) (y + 3); + layoutParams.x = (int)(x + 3); + layoutParams.y = (int)(y + 3); viewSpyglass.setLayoutParams(layoutParams); } float[] tmp01 = new float[3]; - private int calculateColor() - { + private int calculateColor() { tmp01[0] = hue; tmp01[1] = sat; tmp01[2] = val; return Color.HSVToColor(tmp01); } - public void show() - { + public void show() { dialog.show(); } } diff --git a/src/com/fsck/k9/activity/EditIdentity.java b/src/com/fsck/k9/activity/EditIdentity.java index 7ff7d5679..6fff570cb 100644 --- a/src/com/fsck/k9/activity/EditIdentity.java +++ b/src/com/fsck/k9/activity/EditIdentity.java @@ -13,8 +13,7 @@ import com.fsck.k9.Preferences; import com.fsck.k9.R; import java.util.List; -public class EditIdentity extends K9Activity -{ +public class EditIdentity extends K9Activity { public static final String EXTRA_IDENTITY = "com.fsck.k9.EditIdentity_identity"; public static final String EXTRA_IDENTITY_INDEX = "com.fsck.k9.EditIdentity_identity_index"; @@ -33,8 +32,7 @@ public class EditIdentity extends K9Activity private EditText mReplyTo; @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mIdentity = (Identity)getIntent().getSerializableExtra(EXTRA_IDENTITY); @@ -42,8 +40,7 @@ public class EditIdentity extends K9Activity String accountUuid = getIntent().getStringExtra(EXTRA_ACCOUNT); mAccount = Preferences.getPreferences(this).getAccount(accountUuid); - if (mIdentityIndex == -1) - { + if (mIdentityIndex == -1) { mIdentity = new Identity(); } @@ -53,8 +50,7 @@ public class EditIdentity extends K9Activity * If we're being reloaded we override the original account with the one * we saved */ - if (savedInstanceState != null && savedInstanceState.containsKey(EXTRA_IDENTITY)) - { + if (savedInstanceState != null && savedInstanceState.containsKey(EXTRA_IDENTITY)) { mIdentity = (Identity)savedInstanceState.getSerializable(EXTRA_IDENTITY); } @@ -77,40 +73,30 @@ public class EditIdentity extends K9Activity mSignatureUse = (CheckBox)findViewById(R.id.signature_use); mSignatureView = (EditText)findViewById(R.id.signature); mSignatureUse.setChecked(mIdentity.getSignatureUse()); - mSignatureUse.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() - { - public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) - { - if (isChecked) - { + mSignatureUse.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { + public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { + if (isChecked) { mSignatureLayout.setVisibility(View.VISIBLE); mSignatureView.setText(mIdentity.getSignature()); - } - else - { + } else { mSignatureLayout.setVisibility(View.GONE); } } }); - if (mSignatureUse.isChecked()) - { + if (mSignatureUse.isChecked()) { mSignatureView.setText(mIdentity.getSignature()); - } - else - { + } else { mSignatureLayout.setVisibility(View.GONE); } } @Override - public void onResume() - { + public void onResume() { super.onResume(); } - private void saveIdentity() - { + private void saveIdentity() { mIdentity.setDescription(mDescriptionView.getText().toString()); mIdentity.setEmail(mEmailView.getText().toString()); @@ -119,22 +105,16 @@ public class EditIdentity extends K9Activity mIdentity.setSignatureUse(mSignatureUse.isChecked()); mIdentity.setSignature(mSignatureView.getText().toString()); - if (mReplyTo.getText().length() == 0) - { + if (mReplyTo.getText().length() == 0) { mIdentity.setReplyTo(null); - } - else - { + } else { mIdentity.setReplyTo(mReplyTo.getText().toString()); } List identities = mAccount.getIdentities(); - if (mIdentityIndex == -1) - { + if (mIdentityIndex == -1) { identities.add(mIdentity); - } - else - { + } else { identities.remove(mIdentityIndex); identities.add(mIdentityIndex, mIdentity); } @@ -145,10 +125,8 @@ public class EditIdentity extends K9Activity } @Override - public boolean onKeyDown(int keyCode, KeyEvent event) - { - if (keyCode == KeyEvent.KEYCODE_BACK) - { + public boolean onKeyDown(int keyCode, KeyEvent event) { + if (keyCode == KeyEvent.KEYCODE_BACK) { saveIdentity(); return true; } @@ -156,8 +134,7 @@ public class EditIdentity extends K9Activity } @Override - public void onSaveInstanceState(Bundle outState) - { + public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putSerializable(EXTRA_IDENTITY, mIdentity); } diff --git a/src/com/fsck/k9/activity/FolderInfoHolder.java b/src/com/fsck/k9/activity/FolderInfoHolder.java index e07cf4b67..98d8f6034 100644 --- a/src/com/fsck/k9/activity/FolderInfoHolder.java +++ b/src/com/fsck/k9/activity/FolderInfoHolder.java @@ -9,8 +9,7 @@ import com.fsck.k9.R; import com.fsck.k9.mail.Folder; import com.fsck.k9.mail.MessagingException; -public class FolderInfoHolder implements Comparable -{ +public class FolderInfoHolder implements Comparable { public String name; public String displayName; public long lastChecked; @@ -23,85 +22,66 @@ public class FolderInfoHolder implements Comparable public boolean pushActive; @Override - public boolean equals(Object o) - { + public boolean equals(Object o) { return this.name.equals(((FolderInfoHolder)o).name); } @Override - public int hashCode() - { + public int hashCode() { return name.hashCode(); } - public int compareTo(FolderInfoHolder o) - { + public int compareTo(FolderInfoHolder o) { String s1 = this.name; String s2 = o.name; int ret = s1.compareToIgnoreCase(s2); - if (ret != 0) - { + if (ret != 0) { return ret; - } - else - { + } else { return s1.compareTo(s2); } } - private String truncateStatus(String mess) - { - if (mess != null && mess.length() > 27) - { + private String truncateStatus(String mess) { + if (mess != null && mess.length() > 27) { mess = mess.substring(0, 27); } return mess; } // constructor for an empty object for comparisons - public FolderInfoHolder() - { + public FolderInfoHolder() { } - public FolderInfoHolder(Context context, Folder folder, Account account) - { - if (context == null) - { + public FolderInfoHolder(Context context, Folder folder, Account account) { + if (context == null) { throw new IllegalArgumentException("null context given"); } populate(context, folder, account); } - public FolderInfoHolder(Context context, Folder folder, Account account, int unreadCount) - { + public FolderInfoHolder(Context context, Folder folder, Account account, int unreadCount) { populate(context, folder, account, unreadCount); } - public void populate(Context context, Folder folder, Account account, int unreadCount) - { + public void populate(Context context, Folder folder, Account account, int unreadCount) { - try - { + try { folder.open(Folder.OpenMode.READ_WRITE); // unreadCount = folder.getUnreadMessageCount(); - } - catch (MessagingException me) - { + } catch (MessagingException me) { Log.e(K9.LOG_TAG, "Folder.getUnreadMessageCount() failed", me); } - populate(context,folder,account); + populate(context, folder, account); this.unreadMessageCount = unreadCount; - try - { + try { this.flaggedMessageCount = folder.getFlaggedMessageCount(); - } - catch (Exception e) - { + } catch (Exception e) { Log.e(K9.LOG_TAG, "Unable to get flaggedMessageCount", e); } @@ -110,50 +90,40 @@ public class FolderInfoHolder implements Comparable } - public void populate(Context context, Folder folder, Account account) - { + public void populate(Context context, Folder folder, Account account) { this.folder = folder; this.name = folder.getName(); this.lastChecked = folder.getLastUpdate(); this.status = truncateStatus(folder.getStatus()); - if (this.name.equalsIgnoreCase(K9.INBOX)) - { + if (this.name.equalsIgnoreCase(K9.INBOX)) { this.displayName = context.getString(R.string.special_mailbox_name_inbox); - } - else - { + } else { this.displayName = folder.getName(); } - if (this.name.equals(account.getOutboxFolderName())) - { + if (this.name.equals(account.getOutboxFolderName())) { this.displayName = String.format(context.getString(R.string.special_mailbox_name_outbox_fmt), this.name); } - if (this.name.equals(account.getDraftsFolderName())) - { + if (this.name.equals(account.getDraftsFolderName())) { this.displayName = String.format(context.getString(R.string.special_mailbox_name_drafts_fmt), this.name); } - if (this.name.equals(account.getTrashFolderName())) - { + if (this.name.equals(account.getTrashFolderName())) { this.displayName = String.format(context.getString(R.string.special_mailbox_name_trash_fmt), this.name); } - if (this.name.equals(account.getSentFolderName())) - { + if (this.name.equals(account.getSentFolderName())) { this.displayName = String.format(context.getString(R.string.special_mailbox_name_sent_fmt), this.name); } - if (this.name.equals(account.getArchiveFolderName())) - { + if (this.name.equals(account.getArchiveFolderName())) { this.displayName = String.format(context.getString(R.string.special_mailbox_name_archive_fmt), this.name); } - if (this.name.equals(account.getSpamFolderName())) - { + if (this.name.equals(account.getSpamFolderName())) { this.displayName = String.format(context.getString(R.string.special_mailbox_name_spam_fmt), this.name); } } diff --git a/src/com/fsck/k9/activity/FolderList.java b/src/com/fsck/k9/activity/FolderList.java index 6ef59138d..66d39f5a5 100644 --- a/src/com/fsck/k9/activity/FolderList.java +++ b/src/com/fsck/k9/activity/FolderList.java @@ -46,8 +46,7 @@ import java.util.List; * Activity shows list of the Account's folders */ -public class FolderList extends K9ListActivity -{ +public class FolderList extends K9ListActivity { private static final int DIALOG_MARK_ALL_AS_READ = 1; @@ -74,15 +73,11 @@ public class FolderList extends K9ListActivity private FontSizes mFontSizes = K9.getFontSizes(); private Context context; - class FolderListHandler extends Handler - { + class FolderListHandler extends Handler { - public void refreshTitle() - { - runOnUiThread(new Runnable() - { - public void run() - { + public void refreshTitle() { + runOnUiThread(new Runnable() { + public void run() { String dispString = mAdapter.mListener.formatHeader(FolderList.this, getString(R.string.folder_list_title, mAccount.getDescription()), mUnreadMessageCount, getTimeFormat()); @@ -93,12 +88,9 @@ public class FolderList extends K9ListActivity } - public void newFolders(final List newFolders) - { - runOnUiThread(new Runnable() - { - public void run() - { + public void newFolders(final List newFolders) { + runOnUiThread(new Runnable() { + public void run() { mAdapter.mFolders.clear(); mAdapter.mFolders.addAll(newFolders); mHandler.dataChanged(); @@ -106,12 +98,9 @@ public class FolderList extends K9ListActivity }); } - public void workingAccount(final int res) - { - runOnUiThread(new Runnable() - { - public void run() - { + public void workingAccount(final int res) { + runOnUiThread(new Runnable() { + public void run() { String toastText = getString(res, mAccount.getDescription()); Toast toast = Toast.makeText(getApplication(), toastText, Toast.LENGTH_SHORT); toast.show(); @@ -119,12 +108,9 @@ public class FolderList extends K9ListActivity }); } - public void accountSizeChanged(final long oldSize, final long newSize) - { - runOnUiThread(new Runnable() - { - public void run() - { + public void accountSizeChanged(final long oldSize, final long newSize) { + runOnUiThread(new Runnable() { + public void run() { String toastText = getString(R.string.account_size_changed, mAccount.getDescription(), SizeFormatter.formatSize(getApplication(), oldSize), SizeFormatter.formatSize(getApplication(), newSize)); Toast toast = Toast.makeText(getApplication(), toastText, Toast.LENGTH_LONG); @@ -133,17 +119,13 @@ public class FolderList extends K9ListActivity }); } - public void folderLoading(final String folder, final boolean loading) - { - runOnUiThread(new Runnable() - { - public void run() - { + public void folderLoading(final String folder, final boolean loading) { + runOnUiThread(new Runnable() { + public void run() { FolderInfoHolder folderHolder = mAdapter.getFolder(folder); - if (folderHolder != null) - { + if (folderHolder != null) { folderHolder.loading = loading; } @@ -151,24 +133,18 @@ public class FolderList extends K9ListActivity }); } - public void progress(final boolean progress) - { - runOnUiThread(new Runnable() - { - public void run() - { + public void progress(final boolean progress) { + runOnUiThread(new Runnable() { + public void run() { setProgressBarIndeterminateVisibility(progress); } }); } - public void dataChanged() - { - runOnUiThread(new Runnable() - { - public void run() - { + public void dataChanged() { + runOnUiThread(new Runnable() { + public void run() { mAdapter.notifyDataSetChanged(); } }); @@ -181,19 +157,15 @@ public class FolderList extends K9ListActivity * queueing up a remote update of the folder. */ - private void checkMail(FolderInfoHolder folder) - { + private void checkMail(FolderInfoHolder folder) { TracingPowerManager pm = TracingPowerManager.getPowerManager(this); final TracingWakeLock wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "FolderList checkMail"); wakeLock.setReferenceCounted(false); wakeLock.acquire(K9.WAKE_LOCK_TIMEOUT); - MessagingListener listener = new MessagingListener() - { + MessagingListener listener = new MessagingListener() { @Override - public void synchronizeMailboxFinished(Account account, String folder, int totalMessagesInMailbox, int numNewMessages) - { - if (!account.equals(mAccount)) - { + public void synchronizeMailboxFinished(Account account, String folder, int totalMessagesInMailbox, int numNewMessages) { + if (!account.equals(mAccount)) { return; } wakeLock.release(); @@ -201,10 +173,8 @@ public class FolderList extends K9ListActivity @Override public void synchronizeMailboxFailed(Account account, String folder, - String message) - { - if (!account.equals(mAccount)) - { + String message) { + if (!account.equals(mAccount)) { return; } wakeLock.release(); @@ -214,47 +184,39 @@ public class FolderList extends K9ListActivity sendMail(mAccount); } - public static Intent actionHandleAccountIntent(Context context, Account account) - { + public static Intent actionHandleAccountIntent(Context context, Account account) { return actionHandleAccountIntent(context, account, null, false); } - public static Intent actionHandleAccountIntent(Context context, Account account, String initialFolder) - { + public static Intent actionHandleAccountIntent(Context context, Account account, String initialFolder) { return actionHandleAccountIntent(context, account, initialFolder, false); } - public static Intent actionHandleAccountIntent(Context context, Account account, String initialFolder, boolean fromShortcut) - { + public static Intent actionHandleAccountIntent(Context context, Account account, String initialFolder, boolean fromShortcut) { Intent intent = new Intent(context, FolderList.class); intent.putExtra(EXTRA_ACCOUNT, account.getUuid()); - if (initialFolder != null) - { + if (initialFolder != null) { intent.putExtra(EXTRA_INITIAL_FOLDER, initialFolder); } - if (fromShortcut) - { + if (fromShortcut) { intent.putExtra(EXTRA_FROM_SHORTCUT, true); } return intent; } - private static void actionHandleAccount(Context context, Account account, String initialFolder) - { + private static void actionHandleAccount(Context context, Account account, String initialFolder) { Intent intent = actionHandleAccountIntent(context, account, initialFolder); context.startActivity(intent); } - public static void actionHandleAccount(Context context, Account account) - { + public static void actionHandleAccount(Context context, Account account) { actionHandleAccount(context, account, null); } - public static Intent actionHandleNotification(Context context, Account account, String initialFolder) - { + public static Intent actionHandleNotification(Context context, Account account, String initialFolder) { Intent intent = new Intent( Intent.ACTION_VIEW, Uri.parse("email://accounts/" + account.getAccountNumber()), @@ -264,16 +226,14 @@ public class FolderList extends K9ListActivity intent.putExtra(EXTRA_ACCOUNT, account.getUuid()); intent.putExtra(EXTRA_FROM_NOTIFICATION, true); - if (initialFolder != null) - { + if (initialFolder != null) { intent.putExtra(EXTRA_INITIAL_FOLDER, initialFolder); } return intent; } @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); @@ -283,10 +243,8 @@ public class FolderList extends K9ListActivity mListView.setLongClickable(true); mListView.setFastScrollEnabled(true); mListView.setScrollingCacheEnabled(true); - mListView.setOnItemClickListener(new OnItemClickListener() - { - public void onItemClick(AdapterView parent, View view, int position, long id) - { + mListView.setOnItemClickListener(new OnItemClickListener() { + public void onItemClick(AdapterView parent, View view, int position, long id) { onOpenFolder(((FolderInfoHolder)mAdapter.getItem(id)).name); } }); @@ -302,8 +260,7 @@ public class FolderList extends K9ListActivity } @Override - public void onNewIntent(Intent intent) - { + public void onNewIntent(Intent intent) { setIntent(intent); // onNewIntent doesn't autoset our "internal" intent String initialFolder; @@ -312,8 +269,7 @@ public class FolderList extends K9ListActivity String accountUuid = intent.getStringExtra(EXTRA_ACCOUNT); mAccount = Preferences.getPreferences(this).getAccount(accountUuid); - if (mAccount == null) - { + if (mAccount == null) { // This shouldn't normally happen. But apparently it does. See issue 2261. finish(); return; @@ -321,32 +277,24 @@ public class FolderList extends K9ListActivity initialFolder = intent.getStringExtra(EXTRA_INITIAL_FOLDER); boolean fromNotification = intent.getBooleanExtra(EXTRA_FROM_NOTIFICATION, false); - if (fromNotification && mAccount.goToUnreadMessageSearch()) - { + if (fromNotification && mAccount.goToUnreadMessageSearch()) { MessagingController.getInstance(getApplication()).notifyAccountCancel(this, mAccount); openUnreadSearch(this, mAccount); finish(); - } - else if (initialFolder != null && !K9.FOLDER_NONE.equals(initialFolder)) - { + } else if (initialFolder != null && !K9.FOLDER_NONE.equals(initialFolder)) { onOpenFolder(initialFolder); finish(); - } - else if (intent.getBooleanExtra(EXTRA_FROM_SHORTCUT, false) && - !K9.FOLDER_NONE.equals(mAccount.getAutoExpandFolderName())) - { + } else if (intent.getBooleanExtra(EXTRA_FROM_SHORTCUT, false) && + !K9.FOLDER_NONE.equals(mAccount.getAutoExpandFolderName())) { onOpenFolder(mAccount.getAutoExpandFolderName()); finish(); - } - else - { + } else { initializeActivityView(); } } - private void initializeActivityView() - { + private void initializeActivityView() { mAdapter = new FolderListAdapter(); restorePreviousData(); @@ -357,24 +305,20 @@ public class FolderList extends K9ListActivity } @SuppressWarnings("unchecked") - private void restorePreviousData() - { + private void restorePreviousData() { final Object previousData = getLastNonConfigurationInstance(); - if (previousData != null) - { + if (previousData != null) { mAdapter.mFolders = (ArrayList) previousData; } } - @Override public Object onRetainNonConfigurationInstance() - { + @Override public Object onRetainNonConfigurationInstance() { return (mAdapter == null) ? null : mAdapter.mFolders; } - @Override public void onPause() - { + @Override public void onPause() { super.onPause(); MessagingController.getInstance(getApplication()).removeListener(mAdapter.mListener); } @@ -384,12 +328,10 @@ public class FolderList extends K9ListActivity * messages for any folder that is currently open. This guarantees that things * like unread message count and read status are updated. */ - @Override public void onResume() - { + @Override public void onResume() { super.onResume(); - if (!mAccount.isAvailable(this)) - { + if (!mAccount.isAvailable(this)) { Log.i(K9.LOG_TAG, "account unavaliabale, not showing folder-list but account-list"); startActivity(new Intent(this, Accounts.class)); finish(); @@ -409,25 +351,20 @@ public class FolderList extends K9ListActivity @Override - public void onBackPressed() - { + public void onBackPressed() { // This will be called either automatically for you on 2.0 // or later, or by the code above on earlier versions of the // platform. - if (K9.manageBack()) - { + if (K9.manageBack()) { onAccounts(); - } - else - { + } else { // TODO - when we move to android 2.0, uncomment this instead. // super.onBackPressed() finish(); } } - @Override public boolean onKeyDown(int keyCode, KeyEvent event) - { + @Override public boolean onKeyDown(int keyCode, KeyEvent event) { //Shortcuts that work no matter what is selected if ( @@ -436,8 +373,7 @@ public class FolderList extends K9ListActivity keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0 - && K9.manageBack()) - { + && K9.manageBack()) { // Take care of calling this method on earlier versions of // the platform where it doesn't exist. onBackPressed(); @@ -445,129 +381,105 @@ public class FolderList extends K9ListActivity } - switch (keyCode) + switch (keyCode) { + case KeyEvent.KEYCODE_Q: + //case KeyEvent.KEYCODE_BACK: { - case KeyEvent.KEYCODE_Q: - //case KeyEvent.KEYCODE_BACK: - { - onAccounts(); - return true; - } + onAccounts(); + return true; + } - case KeyEvent.KEYCODE_S: - { - onEditAccount(); - return true; - } + case KeyEvent.KEYCODE_S: { + onEditAccount(); + return true; + } - case KeyEvent.KEYCODE_H: - { - Toast toast = Toast.makeText(this, R.string.folder_list_help_key, Toast.LENGTH_LONG); - toast.show(); - return true; - } + case KeyEvent.KEYCODE_H: { + Toast toast = Toast.makeText(this, R.string.folder_list_help_key, Toast.LENGTH_LONG); + toast.show(); + return true; + } - case KeyEvent.KEYCODE_1: - { - setDisplayMode(FolderMode.FIRST_CLASS); - return true; - } - case KeyEvent.KEYCODE_2: - { - setDisplayMode(FolderMode.FIRST_AND_SECOND_CLASS); - return true; - } - case KeyEvent.KEYCODE_3: - { - setDisplayMode(FolderMode.NOT_SECOND_CLASS); - return true; - } - case KeyEvent.KEYCODE_4: - { - setDisplayMode(FolderMode.ALL); - return true; - } + case KeyEvent.KEYCODE_1: { + setDisplayMode(FolderMode.FIRST_CLASS); + return true; + } + case KeyEvent.KEYCODE_2: { + setDisplayMode(FolderMode.FIRST_AND_SECOND_CLASS); + return true; + } + case KeyEvent.KEYCODE_3: { + setDisplayMode(FolderMode.NOT_SECOND_CLASS); + return true; + } + case KeyEvent.KEYCODE_4: { + setDisplayMode(FolderMode.ALL); + return true; + } }//switch return super.onKeyDown(keyCode, event); }//onKeyDown - private void setDisplayMode(FolderMode newMode) - { + private void setDisplayMode(FolderMode newMode) { mAccount.setFolderDisplayMode(newMode); mAccount.save(Preferences.getPreferences(this)); - if (mAccount.getFolderPushMode() != FolderMode.NONE) - { + if (mAccount.getFolderPushMode() != FolderMode.NONE) { MailService.actionRestartPushers(this, null); } onRefresh(false); } - private void onRefresh(final boolean forceRemote) - { + private void onRefresh(final boolean forceRemote) { MessagingController.getInstance(getApplication()).listFolders(mAccount, forceRemote, mAdapter.mListener); } - private void onEditPrefs() - { + private void onEditPrefs() { Prefs.actionPrefs(this); } - private void onEditAccount() - { + private void onEditAccount() { AccountSettings.actionSettings(this, mAccount); } - private void onEditFolder(Account account, String folderName) - { + private void onEditFolder(Account account, String folderName) { FolderSettings.actionSettings(this, account, folderName); } - private void onAccounts() - { + private void onAccounts() { Accounts.listAccounts(this); finish(); } - private void onEmptyTrash(final Account account) - { + private void onEmptyTrash(final Account account) { mHandler.dataChanged(); MessagingController.getInstance(getApplication()).emptyTrash(account, null); } - private void onExpunge(final Account account, String folderName) - { + private void onExpunge(final Account account, String folderName) { MessagingController.getInstance(getApplication()).expunge(account, folderName, null); } - private void onClearFolder(Account account, String folderName) - { + private void onClearFolder(Account account, String folderName) { // There has to be a cheaper way to get at the localFolder object than this LocalFolder localFolder = null; - try - { - if (account == null || folderName == null || !account.isAvailable(FolderList.this)) - { + try { + if (account == null || folderName == null || !account.isAvailable(FolderList.this)) { Log.i(K9.LOG_TAG, "not clear folder of unavailable account"); return; } localFolder = account.getLocalStore().getFolder(folderName); localFolder.open(Folder.OpenMode.READ_WRITE); localFolder.clearAllMessages(); - } - catch (Exception e) - { + } catch (Exception e) { Log.e(K9.LOG_TAG, "Exception while clearing folder", e); - } - finally - { - if (localFolder != null) - { + } finally { + if (localFolder != null) { localFolder.close(); } } @@ -578,147 +490,134 @@ public class FolderList extends K9ListActivity - private void sendMail(Account account) - { + private void sendMail(Account account) { MessagingController.getInstance(getApplication()).sendPendingMessages(account, mAdapter.mListener); } - @Override public boolean onOptionsItemSelected(MenuItem item) - { - switch (item.getItemId()) - { - case R.id.compose: - MessageCompose.actionCompose(this, mAccount); + @Override public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + case R.id.compose: + MessageCompose.actionCompose(this, mAccount); - return true; + return true; - case R.id.check_mail: - MessagingController.getInstance(getApplication()).checkMail(this, mAccount, true, true, mAdapter.mListener); + case R.id.check_mail: + MessagingController.getInstance(getApplication()).checkMail(this, mAccount, true, true, mAdapter.mListener); - return true; + return true; - case R.id.send_messages: - MessagingController.getInstance(getApplication()).sendPendingMessages(mAccount, null); - return true; - case R.id.accounts: - onAccounts(); + case R.id.send_messages: + MessagingController.getInstance(getApplication()).sendPendingMessages(mAccount, null); + return true; + case R.id.accounts: + onAccounts(); - return true; + return true; - case R.id.list_folders: - onRefresh(REFRESH_REMOTE); + case R.id.list_folders: + onRefresh(REFRESH_REMOTE); - return true; + return true; - case R.id.account_settings: - onEditAccount(); + case R.id.account_settings: + onEditAccount(); - return true; + return true; - case R.id.app_settings: - onEditPrefs(); + case R.id.app_settings: + onEditPrefs(); - return true; + return true; - case R.id.empty_trash: - onEmptyTrash(mAccount); + case R.id.empty_trash: + onEmptyTrash(mAccount); - return true; + return true; - case R.id.compact: - onCompact(mAccount); + case R.id.compact: + onCompact(mAccount); - return true; + return true; - case R.id.display_1st_class: - { - setDisplayMode(FolderMode.FIRST_CLASS); - return true; - } - case R.id.display_1st_and_2nd_class: - { - setDisplayMode(FolderMode.FIRST_AND_SECOND_CLASS); - return true; - } - case R.id.display_not_second_class: - { - setDisplayMode(FolderMode.NOT_SECOND_CLASS); - return true; - } - case R.id.display_all: - { - setDisplayMode(FolderMode.ALL); - return true; - } - default: - return super.onOptionsItemSelected(item); + case R.id.display_1st_class: { + setDisplayMode(FolderMode.FIRST_CLASS); + return true; + } + case R.id.display_1st_and_2nd_class: { + setDisplayMode(FolderMode.FIRST_AND_SECOND_CLASS); + return true; + } + case R.id.display_not_second_class: { + setDisplayMode(FolderMode.NOT_SECOND_CLASS); + return true; + } + case R.id.display_all: { + setDisplayMode(FolderMode.ALL); + return true; + } + default: + return super.onOptionsItemSelected(item); } } - private void onOpenFolder(String folder) - { + private void onOpenFolder(String folder) { MessageList.actionHandleFolder(this, mAccount, folder); - if (K9.manageBack()) - { + if (K9.manageBack()) { finish(); } } - private void onCompact(Account account) - { + private void onCompact(Account account) { mHandler.workingAccount(R.string.compacting_account); MessagingController.getInstance(getApplication()).compact(account, null); } - @Override public boolean onCreateOptionsMenu(Menu menu) - { + @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.folder_list_option, menu); return true; } - @Override public boolean onContextItemSelected(MenuItem item) - { + @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item .getMenuInfo(); FolderInfoHolder folder = (FolderInfoHolder) mAdapter.getItem(info.position); - switch (item.getItemId()) - { - case R.id.open_folder: - onOpenFolder(folder.name); - break; + switch (item.getItemId()) { + case R.id.open_folder: + onOpenFolder(folder.name); + break; - case R.id.mark_all_as_read: - onMarkAllAsRead(mAccount, folder.name); - break; + case R.id.mark_all_as_read: + onMarkAllAsRead(mAccount, folder.name); + break; - case R.id.send_messages: - sendMail(mAccount); + case R.id.send_messages: + sendMail(mAccount); - break; + break; - case R.id.check_mail: - checkMail(folder); + case R.id.check_mail: + checkMail(folder); - break; + break; - case R.id.folder_settings: - onEditFolder(mAccount, folder.name); + case R.id.folder_settings: + onEditFolder(mAccount, folder.name); - break; + break; - case R.id.empty_trash: - onEmptyTrash(mAccount); + case R.id.empty_trash: + onEmptyTrash(mAccount); - break; - case R.id.expunge: - onExpunge(mAccount, folder.name); + break; + case R.id.expunge: + onExpunge(mAccount, folder.name); - break; + break; - case R.id.clear_local_folder: - onClearFolder(mAccount,folder.name); - break; + case R.id.clear_local_folder: + onClearFolder(mAccount, folder.name); + break; } return super.onContextItemSelected(item); @@ -727,55 +626,46 @@ public class FolderList extends K9ListActivity private FolderInfoHolder mSelectedContextFolder = null; - private void onMarkAllAsRead(final Account account, final String folder) - { + private void onMarkAllAsRead(final Account account, final String folder) { mSelectedContextFolder = mAdapter.getFolder(folder); showDialog(DIALOG_MARK_ALL_AS_READ); } @Override - public Dialog onCreateDialog(int id) - { - switch (id) - { - case DIALOG_MARK_ALL_AS_READ: - return createMarkAllAsReadDialog(); + public Dialog onCreateDialog(int id) { + switch (id) { + case DIALOG_MARK_ALL_AS_READ: + return createMarkAllAsReadDialog(); } return super.onCreateDialog(id); } @Override - public void onPrepareDialog(int id, Dialog dialog) - { - switch (id) - { - case DIALOG_MARK_ALL_AS_READ: - ((AlertDialog)dialog).setMessage(getString(R.string.mark_all_as_read_dlg_instructions_fmt, - mSelectedContextFolder.displayName)); + public void onPrepareDialog(int id, Dialog dialog) { + switch (id) { + case DIALOG_MARK_ALL_AS_READ: + ((AlertDialog)dialog).setMessage(getString(R.string.mark_all_as_read_dlg_instructions_fmt, + mSelectedContextFolder.displayName)); - break; + break; - default: - super.onPrepareDialog(id, dialog); + default: + super.onPrepareDialog(id, dialog); } } - private Dialog createMarkAllAsReadDialog() - { + private Dialog createMarkAllAsReadDialog() { return new AlertDialog.Builder(this) .setTitle(R.string.mark_all_as_read_dlg_title) .setMessage(getString(R.string.mark_all_as_read_dlg_instructions_fmt, mSelectedContextFolder.displayName)) - .setPositiveButton(R.string.okay_action, new DialogInterface.OnClickListener() - { - public void onClick(DialogInterface dialog, int whichButton) - { + .setPositiveButton(R.string.okay_action, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int whichButton) { dismissDialog(DIALOG_MARK_ALL_AS_READ); - try - { + try { MessagingController.getInstance(getApplication()).markAllMessagesRead(mAccount, mSelectedContextFolder.name); @@ -784,18 +674,14 @@ public class FolderList extends K9ListActivity mHandler.dataChanged(); - } - catch (Exception e) - { + } catch (Exception e) { // Ignore } } }) - .setNegativeButton(R.string.cancel_action, new DialogInterface.OnClickListener() - { - public void onClick(DialogInterface dialog, int whichButton) - { + .setNegativeButton(R.string.cancel_action, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int whichButton) { dismissDialog(DIALOG_MARK_ALL_AS_READ); } }) @@ -804,8 +690,7 @@ public class FolderList extends K9ListActivity } - @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) - { + @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; getMenuInflater().inflate(R.menu.folder_context, menu); @@ -817,70 +702,55 @@ public class FolderList extends K9ListActivity if (!folder.name.equals(mAccount.getTrashFolderName())) menu.findItem(R.id.empty_trash).setVisible(false); - if (folder.name.equals(mAccount.getOutboxFolderName())) - { + if (folder.name.equals(mAccount.getOutboxFolderName())) { menu.findItem(R.id.check_mail).setVisible(false); - } - else - { + } else { menu.findItem(R.id.send_messages).setVisible(false); } - if (K9.ERROR_FOLDER_NAME.equals(folder.name)) - { + if (K9.ERROR_FOLDER_NAME.equals(folder.name)) { menu.findItem(R.id.expunge).setVisible(false); } menu.setHeaderTitle(folder.displayName); } - class FolderListAdapter extends BaseAdapter - { + class FolderListAdapter extends BaseAdapter { private ArrayList mFolders = new ArrayList(); - public Object getItem(long position) - { + public Object getItem(long position) { return getItem((int)position); } - public Object getItem(int position) - { + public Object getItem(int position) { return mFolders.get(position); } - public long getItemId(int position) - { + public long getItemId(int position) { return position ; } - public int getCount() - { + public int getCount() { return mFolders.size(); } @Override - public boolean isEnabled(int item) - { + public boolean isEnabled(int item) { return true; } @Override - public boolean areAllItemsEnabled() - { + public boolean areAllItemsEnabled() { return true; } - private ActivityListener mListener = new ActivityListener() - { + private ActivityListener mListener = new ActivityListener() { @Override - public void accountStatusChanged(BaseAccount account, AccountStats stats) - { - if (!account.equals(mAccount)) - { + public void accountStatusChanged(BaseAccount account, AccountStats stats) { + if (!account.equals(mAccount)) { return; } - if (stats == null) - { + if (stats == null) { return; } mUnreadMessageCount = stats.unreadMessageCount; @@ -888,10 +758,8 @@ public class FolderList extends K9ListActivity } @Override - public void listFoldersStarted(Account account) - { - if (!account.equals(mAccount)) - { + public void listFoldersStarted(Account account) { + if (!account.equals(mAccount)) { return; } @@ -899,26 +767,21 @@ public class FolderList extends K9ListActivity } @Override - public void listFoldersFailed(Account account, String message) - { - if (!account.equals(mAccount)) - { + public void listFoldersFailed(Account account, String message) { + if (!account.equals(mAccount)) { return; } mHandler.progress(false); - if (Config.LOGV) - { + if (Config.LOGV) { Log.v(K9.LOG_TAG, "listFoldersFailed " + message); } } @Override - public void listFoldersFinished(Account account) - { - if (!account.equals(mAccount)) - { + public void listFoldersFinished(Account account) { + if (!account.equals(mAccount)) { return; } @@ -929,10 +792,8 @@ public class FolderList extends K9ListActivity } @Override - public void listFolders(Account account, Folder[] folders) - { - if (!account.equals(mAccount)) - { + public void listFolders(Account account, Folder[] folders) { + if (!account.equals(mAccount)) { return; } @@ -941,10 +802,8 @@ public class FolderList extends K9ListActivity Account.FolderMode aMode = account.getFolderDisplayMode(); Preferences prefs = Preferences.getPreferences(getApplication().getApplicationContext()); - for (Folder folder : folders) - { - try - { + for (Folder folder : folders) { + try { folder.refresh(prefs); Folder.FolderClass fMode = folder.getDisplayClass(); @@ -953,49 +812,36 @@ public class FolderList extends K9ListActivity || (aMode == Account.FolderMode.FIRST_AND_SECOND_CLASS && fMode != Folder.FolderClass.FIRST_CLASS && fMode != Folder.FolderClass.SECOND_CLASS) - || (aMode == Account.FolderMode.NOT_SECOND_CLASS && fMode == Folder.FolderClass.SECOND_CLASS)) - { + || (aMode == Account.FolderMode.NOT_SECOND_CLASS && fMode == Folder.FolderClass.SECOND_CLASS)) { continue; } - } - catch (MessagingException me) - { + } catch (MessagingException me) { Log.e(K9.LOG_TAG, "Couldn't get prefs to check for displayability of folder " + folder.getName(), me); } FolderInfoHolder holder = null; int folderIndex = getFolderIndex(folder.getName()); - if (folderIndex >= 0) - { + if (folderIndex >= 0) { holder = (FolderInfoHolder) getItem(folderIndex); } int unreadMessageCount = 0; - try - { + try { unreadMessageCount = folder.getUnreadMessageCount(); - } - catch (Exception e) - { + } catch (Exception e) { Log.e(K9.LOG_TAG, "Unable to get unreadMessageCount for " + mAccount.getDescription() + ":" + folder.getName()); } - if (holder == null) - { + if (holder == null) { holder = new FolderInfoHolder(context, folder, mAccount, unreadMessageCount); - } - else - { + } else { holder.populate(context, folder, mAccount, unreadMessageCount); } - if (folder.isInTopGroup()) - { + if (folder.isInTopGroup()) { topFolders.add(holder); - } - else - { + } else { newFolders.add(holder); } } @@ -1008,12 +854,10 @@ public class FolderList extends K9ListActivity } @Override - public void synchronizeMailboxStarted(Account account, String folder) - { + public void synchronizeMailboxStarted(Account account, String folder) { super.synchronizeMailboxStarted(account, folder); mHandler.refreshTitle(); - if (!account.equals(mAccount)) - { + if (!account.equals(mAccount)) { return; } @@ -1024,8 +868,7 @@ public class FolderList extends K9ListActivity } @Override - public void synchronizeMailboxHeadersStarted(Account account, String folder) - { + public void synchronizeMailboxHeadersStarted(Account account, String folder) { super.synchronizeMailboxHeadersStarted(account, folder); mHandler.refreshTitle(); @@ -1033,17 +876,15 @@ public class FolderList extends K9ListActivity @Override - public void synchronizeMailboxHeadersProgress(Account account, String folder, int completed, int total) - { - super.synchronizeMailboxHeadersProgress(account,folder,completed, total); + public void synchronizeMailboxHeadersProgress(Account account, String folder, int completed, int total) { + super.synchronizeMailboxHeadersProgress(account, folder, completed, total); mHandler.refreshTitle(); } @Override public void synchronizeMailboxHeadersFinished(Account account, String folder, - int total, int completed) - { - super.synchronizeMailboxHeadersFinished(account,folder, total, completed); + int total, int completed) { + super.synchronizeMailboxHeadersFinished(account, folder, total, completed); mHandler.refreshTitle(); } @@ -1052,19 +893,16 @@ public class FolderList extends K9ListActivity @Override - public void synchronizeMailboxProgress(Account account, String folder, int completed, int total) - { + public void synchronizeMailboxProgress(Account account, String folder, int completed, int total) { super.synchronizeMailboxProgress(account, folder, completed, total); mHandler.refreshTitle(); } @Override - public void synchronizeMailboxFinished(Account account, String folder, int totalMessagesInMailbox, int numNewMessages) - { + public void synchronizeMailboxFinished(Account account, String folder, int totalMessagesInMailbox, int numNewMessages) { super.synchronizeMailboxFinished(account, folder, totalMessagesInMailbox, numNewMessages); mHandler.refreshTitle(); - if (!account.equals(mAccount)) - { + if (!account.equals(mAccount)) { return; } mHandler.progress(false); @@ -1075,37 +913,27 @@ public class FolderList extends K9ListActivity } - private void refreshFolder(Account account, String folderName) - { + private void refreshFolder(Account account, String folderName) { // There has to be a cheaper way to get at the localFolder object than this Folder localFolder = null; - try - { - if (account != null && folderName != null) - { - if (!account.isAvailable(FolderList.this)) - { + try { + if (account != null && folderName != null) { + if (!account.isAvailable(FolderList.this)) { Log.i(K9.LOG_TAG, "not refreshing folder of unavailable account"); return; } localFolder = account.getLocalStore().getFolder(folderName); int unreadMessageCount = localFolder.getUnreadMessageCount(); FolderInfoHolder folderHolder = getFolder(folderName); - if (folderHolder != null) - { + if (folderHolder != null) { folderHolder.populate(context, localFolder, mAccount, unreadMessageCount); mHandler.dataChanged(); } } - } - catch (Exception e) - { + } catch (Exception e) { Log.e(K9.LOG_TAG, "Exception while populating folder", e); - } - finally - { - if (localFolder != null) - { + } finally { + if (localFolder != null) { localFolder.close(); } } @@ -1114,12 +942,10 @@ public class FolderList extends K9ListActivity @Override public void synchronizeMailboxFailed(Account account, String folder, - String message) - { + String message) { super.synchronizeMailboxFailed(account, folder, message); mHandler.refreshTitle(); - if (!account.equals(mAccount)) - { + if (!account.equals(mAccount)) { return; } @@ -1133,8 +959,7 @@ public class FolderList extends K9ListActivity // mHandler.folderStatus(folder, mess); FolderInfoHolder holder = getFolder(folder); - if (holder != null) - { + if (holder != null) { holder.lastChecked = 0; } @@ -1143,16 +968,13 @@ public class FolderList extends K9ListActivity } @Override - public void setPushActive(Account account, String folderName, boolean enabled) - { - if (!account.equals(mAccount)) - { + public void setPushActive(Account account, String folderName, boolean enabled) { + if (!account.equals(mAccount)) { return; } FolderInfoHolder holder = getFolder(folderName); - if (holder != null) - { + if (holder != null) { holder.pushActive = enabled; mHandler.dataChanged(); @@ -1162,39 +984,32 @@ public class FolderList extends K9ListActivity @Override public void messageDeleted(Account account, - String folder, Message message) - { + String folder, Message message) { synchronizeMailboxRemovedMessage(account, folder, message); } @Override - public void emptyTrashCompleted(Account account) - { - if (!account.equals(mAccount)) - { + public void emptyTrashCompleted(Account account) { + if (!account.equals(mAccount)) { return; } refreshFolder(account, mAccount.getTrashFolderName()); } @Override - public void folderStatusChanged(Account account, String folderName, int unreadMessageCount) - { - if (!account.equals(mAccount)) - { + public void folderStatusChanged(Account account, String folderName, int unreadMessageCount) { + if (!account.equals(mAccount)) { return; } refreshFolder(account, folderName); } @Override - public void sendPendingMessagesCompleted(Account account) - { + public void sendPendingMessagesCompleted(Account account) { super.sendPendingMessagesCompleted(account); mHandler.refreshTitle(); - if (!account.equals(mAccount)) - { + if (!account.equals(mAccount)) { return; } @@ -1204,13 +1019,11 @@ public class FolderList extends K9ListActivity } @Override - public void sendPendingMessagesStarted(Account account) - { + public void sendPendingMessagesStarted(Account account) { super.sendPendingMessagesStarted(account); mHandler.refreshTitle(); - if (!account.equals(mAccount)) - { + if (!account.equals(mAccount)) { return; } @@ -1219,12 +1032,10 @@ public class FolderList extends K9ListActivity } @Override - public void sendPendingMessagesFailed(Account account) - { + public void sendPendingMessagesFailed(Account account) { super.sendPendingMessagesFailed(account); mHandler.refreshTitle(); - if (!account.equals(mAccount)) - { + if (!account.equals(mAccount)) { return; } @@ -1233,10 +1044,8 @@ public class FolderList extends K9ListActivity } @Override - public void accountSizeChanged(Account account, long oldSize, long newSize) - { - if (!account.equals(mAccount)) - { + public void accountSizeChanged(Account account, long oldSize, long newSize) { + if (!account.equals(mAccount)) { return; } @@ -1245,95 +1054,77 @@ public class FolderList extends K9ListActivity } @Override - public void pendingCommandsProcessing(Account account) - { + public void pendingCommandsProcessing(Account account) { super.pendingCommandsProcessing(account); mHandler.refreshTitle(); } @Override - public void pendingCommandsFinished(Account account) - { + public void pendingCommandsFinished(Account account) { super.pendingCommandsFinished(account); mHandler.refreshTitle(); } @Override - public void pendingCommandStarted(Account account, String commandTitle) - { + public void pendingCommandStarted(Account account, String commandTitle) { super.pendingCommandStarted(account, commandTitle); mHandler.refreshTitle(); } @Override - public void pendingCommandCompleted(Account account, String commandTitle) - { + public void pendingCommandCompleted(Account account, String commandTitle) { super.pendingCommandCompleted(account, commandTitle); mHandler.refreshTitle(); } @Override - public void systemStatusChanged() - { + public void systemStatusChanged() { mHandler.refreshTitle(); } }; - public int getFolderIndex(String folder) - { + public int getFolderIndex(String folder) { FolderInfoHolder searchHolder = new FolderInfoHolder(); searchHolder.name = folder; return mFolders.indexOf(searchHolder); } - public FolderInfoHolder getFolder(String folder) - { + public FolderInfoHolder getFolder(String folder) { FolderInfoHolder holder = null; int index = getFolderIndex(folder); - if (index >= 0) - { + if (index >= 0) { holder = (FolderInfoHolder) getItem(index); - if (holder != null) - { + if (holder != null) { return holder; } } return null; } - public View getView(int position, View convertView, ViewGroup parent) - { - if (position <= getCount()) - { + public View getView(int position, View convertView, ViewGroup parent) { + if (position <= getCount()) { return getItemView(position, convertView, parent); - } - else - { + } else { // XXX TODO - should catch an exception here return null; } } - public View getItemView(int itemPosition, View convertView, ViewGroup parent) - { + public View getItemView(int itemPosition, View convertView, ViewGroup parent) { FolderInfoHolder folder = (FolderInfoHolder) getItem(itemPosition); View view; - if (convertView != null) - { + if (convertView != null) { view = convertView; - } - else - { + } else { view = mInflater.inflate(R.layout.folder_list_item, parent, false); } FolderViewHolder holder = (FolderViewHolder) view.getTag(); - if (holder == null) - { + if (holder == null) { holder = new FolderViewHolder(); holder.folderName = (TextView) view.findViewById(R.id.folder_name); holder.newMessageCount = (TextView) view.findViewById(R.id.folder_unread_message_count); @@ -1347,77 +1138,58 @@ public class FolderList extends K9ListActivity view.setTag(holder); } - if (folder == null) - { + if (folder == null) { return view; } holder.folderName.setText(folder.displayName); String statusText = ""; - if (folder.loading) - { + if (folder.loading) { statusText = getString(R.string.status_loading); - } - else if (folder.status != null) - { + } else if (folder.status != null) { statusText = folder.status; - } - else if (folder.lastChecked != 0) - { + } else if (folder.lastChecked != 0) { Date lastCheckedDate = new Date(folder.lastChecked); - statusText = getTimeFormat().format(lastCheckedDate) + " "+ + statusText = getTimeFormat().format(lastCheckedDate) + " " + getDateFormat().format(lastCheckedDate); } - if (folder.pushActive) - { - statusText = getString(R.string.folder_push_active_symbol) + " "+ statusText; + if (folder.pushActive) { + statusText = getString(R.string.folder_push_active_symbol) + " " + statusText; } - if (statusText != null) - { + if (statusText != null) { holder.folderStatus.setText(statusText); holder.folderStatus.setVisibility(View.VISIBLE); - } - else - { + } else { holder.folderStatus.setText(null); holder.folderStatus.setVisibility(View.GONE); } - if (folder.unreadMessageCount != 0) - { + if (folder.unreadMessageCount != 0) { holder.newMessageCount.setText(Integer .toString(folder.unreadMessageCount)); holder.newMessageCount.setOnClickListener(new FolderClickListener(mAccount, folder.name, folder.displayName, SearchModifier.UNREAD)); holder.newMessageCount.setVisibility(View.VISIBLE); - } - else - { + } else { holder.newMessageCount.setVisibility(View.GONE); } - if (K9.messageListStars() && folder.flaggedMessageCount > 0) - { + if (K9.messageListStars() && folder.flaggedMessageCount > 0) { holder.flaggedMessageCount.setText(Integer .toString(folder.flaggedMessageCount)); holder.flaggedMessageCount.setOnClickListener(new FolderClickListener(mAccount, folder.name, folder.displayName, SearchModifier.FLAGGED)); holder.flaggedMessageCount.setVisibility(View.VISIBLE); - } - else - { + } else { holder.flaggedMessageCount.setVisibility(View.GONE); } - if (K9.useCompactLayouts() && holder.folderListItemLayout != null) - { + if (K9.useCompactLayouts() && holder.folderListItemLayout != null) { holder.folderListItemLayout.setMinimumHeight(0); } - holder.activeIcons.setOnClickListener(new OnClickListener() - { - public void onClick(View v) - { + holder.activeIcons.setOnClickListener(new OnClickListener() { + public void onClick(View v) { Toast toast = Toast.makeText(getApplication(), getString(R.string.tap_hint), Toast.LENGTH_SHORT); toast.show(); } @@ -1435,20 +1207,17 @@ public class FolderList extends K9ListActivity } @Override - public boolean hasStableIds() - { + public boolean hasStableIds() { return false; } - public boolean isItemSelectable(int position) - { + public boolean isItemSelectable(int position) { return true; } } - static class FolderViewHolder - { + static class FolderViewHolder { public TextView folderName; public TextView folderStatus; @@ -1462,62 +1231,52 @@ public class FolderList extends K9ListActivity public LinearLayout folderListItemLayout; } - private class FolderClickListener implements OnClickListener - { + private class FolderClickListener implements OnClickListener { final BaseAccount account; final String folderName; final String displayName; final SearchModifier searchModifier; - FolderClickListener(BaseAccount nAccount, String folderName, String displayName, SearchModifier nSearchModifier) - { + FolderClickListener(BaseAccount nAccount, String folderName, String displayName, SearchModifier nSearchModifier) { account = nAccount; this.folderName = folderName; searchModifier = nSearchModifier; this.displayName = displayName; } @Override - public void onClick(View v) - { + public void onClick(View v) { String description = getString(R.string.search_title, getString(R.string.message_list_title, account.getDescription(), displayName), getString(searchModifier.resId)); - SearchSpecification searchSpec = new SearchSpecification() - { + SearchSpecification searchSpec = new SearchSpecification() { @Override - public String[] getAccountUuids() - { + public String[] getAccountUuids() { return new String[] { account.getUuid() }; } @Override - public Flag[] getForbiddenFlags() - { + public Flag[] getForbiddenFlags() { return searchModifier.forbiddenFlags; } @Override - public String getQuery() - { + public String getQuery() { return ""; } @Override - public Flag[] getRequiredFlags() - { + public Flag[] getRequiredFlags() { return searchModifier.requiredFlags; } @Override - public boolean isIntegrate() - { + public boolean isIntegrate() { return false; } @Override - public String[] getFolderNames() - { + public String[] getFolderNames() { return new String[] { folderName }; } @@ -1530,45 +1289,37 @@ public class FolderList extends K9ListActivity private static Flag[] UNREAD_FLAG_ARRAY = { Flag.SEEN }; - private void openUnreadSearch(Context context, final Account account) - { + private void openUnreadSearch(Context context, final Account account) { String description = getString(R.string.search_title, mAccount.getDescription(), getString(R.string.unread_modifier)); - SearchSpecification searchSpec = new SearchSpecification() - { + SearchSpecification searchSpec = new SearchSpecification() { //interface has no override @Override - public String[] getAccountUuids() - { + public String[] getAccountUuids() { return new String[] { account.getUuid() }; } //interface has no override @Override - public Flag[] getForbiddenFlags() - { + public Flag[] getForbiddenFlags() { return UNREAD_FLAG_ARRAY; } //interface has no override @Override - public String getQuery() - { + public String getQuery() { return ""; } @Override - public Flag[] getRequiredFlags() - { + public Flag[] getRequiredFlags() { return null; } @Override - public boolean isIntegrate() - { + public boolean isIntegrate() { return false; } @Override - public String[] getFolderNames() - { + public String[] getFolderNames() { return null; } diff --git a/src/com/fsck/k9/activity/FolderListFilter.java b/src/com/fsck/k9/activity/FolderListFilter.java index cf248b201..364af8879 100644 --- a/src/com/fsck/k9/activity/FolderListFilter.java +++ b/src/com/fsck/k9/activity/FolderListFilter.java @@ -15,8 +15,7 @@ import com.fsck.k9.K9; * * @author Marcus@Wolschon.biz */ -public class FolderListFilter extends Filter -{ +public class FolderListFilter extends Filter { /** * ArrayAdapter that contains the list of folders displayed in the * ListView. @@ -36,8 +35,7 @@ public class FolderListFilter extends Filter * * @param folderNames */ - public FolderListFilter(final ArrayAdapter folderNames) - { + public FolderListFilter(final ArrayAdapter folderNames) { this.mFolders = folderNames; } @@ -48,30 +46,24 @@ public class FolderListFilter extends Filter * @see #publishResults(CharSequence, FilterResults) */ @Override - protected FilterResults performFiltering(CharSequence searchTerm) - { + protected FilterResults performFiltering(CharSequence searchTerm) { FilterResults results = new FilterResults(); // Copy the values from mFolders to mOriginalValues if this is the // first time this method is called. - if (mOriginalValues == null) - { + if (mOriginalValues == null) { int count = mFolders.getCount(); mOriginalValues = new ArrayList(count); - for (int i = 0; i < count; i++) - { + for (int i = 0; i < count; i++) { mOriginalValues.add(mFolders.getItem(i)); } } - if ((searchTerm == null) || (searchTerm.length() == 0)) - { + if ((searchTerm == null) || (searchTerm.length() == 0)) { ArrayList list = new ArrayList(mOriginalValues); results.values = list; results.count = list.size(); - } - else - { + } else { final String searchTermString = searchTerm.toString().toLowerCase(); final String[] words = searchTermString.split(" "); final int wordCount = words.length; @@ -80,14 +72,11 @@ public class FolderListFilter extends Filter final ArrayList newValues = new ArrayList(); - for (final T value : values) - { + for (final T value : values) { final String valueText = value.toString().toLowerCase(); - for (int k = 0; k < wordCount; k++) - { - if (valueText.contains(words[k])) - { + for (int k = 0; k < wordCount; k++) { + if (valueText.contains(words[k])) { newValues.add(value); break; } @@ -107,26 +96,20 @@ public class FolderListFilter extends Filter */ @SuppressWarnings("unchecked") @Override - protected void publishResults(CharSequence constraint, FilterResults results) - { + protected void publishResults(CharSequence constraint, FilterResults results) { // Don't notify for every change mFolders.setNotifyOnChange(false); //noinspection unchecked final List folders = (List) results.values; mFolders.clear(); - if (folders != null) - { - for (T folder : folders) - { - if (folder != null) - { + if (folders != null) { + for (T folder : folders) { + if (folder != null) { mFolders.add(folder); } } - } - else - { + } else { Log.w(K9.LOG_TAG, "FolderListFilter.publishResults - null search-result "); } @@ -134,8 +117,7 @@ public class FolderListFilter extends Filter mFolders.notifyDataSetChanged(); } - public void invalidate() - { + public void invalidate() { mOriginalValues = null; } } diff --git a/src/com/fsck/k9/activity/InsertableHtmlContent.java b/src/com/fsck/k9/activity/InsertableHtmlContent.java index 76ced9dae..168b90b71 100644 --- a/src/com/fsck/k9/activity/InsertableHtmlContent.java +++ b/src/com/fsck/k9/activity/InsertableHtmlContent.java @@ -12,8 +12,7 @@ import java.io.Serializable; * * TODO: This container should also have a text part, along with its insertion point. Or maybe a generic InsertableContent and maintain one each for Html and Text? */ -class InsertableHtmlContent implements Serializable -{ +class InsertableHtmlContent implements Serializable { private static final long serialVersionUID = 2397327034L; // Default to a headerInsertionPoint at the beginning of the message. private int headerInsertionPoint = 0; @@ -28,18 +27,15 @@ class InsertableHtmlContent implements Serializable /** * Defines where user content should be inserted, either before or after quoted content. */ - public enum InsertionLocation - { + public enum InsertionLocation { BEFORE_QUOTE, AFTER_QUOTE } - public void setHeaderInsertionPoint(int headerInsertionPoint) - { + public void setHeaderInsertionPoint(int headerInsertionPoint) { this.headerInsertionPoint = headerInsertionPoint; } - public void setFooterInsertionPoint(int footerInsertionPoint) - { + public void setFooterInsertionPoint(int footerInsertionPoint) { this.footerInsertionPoint = footerInsertionPoint; } @@ -47,8 +43,7 @@ class InsertableHtmlContent implements Serializable * Get the quoted content. * @return Quoted content. */ - public String getQuotedContent() - { + public String getQuotedContent() { return quotedContent.toString(); } @@ -56,8 +51,7 @@ class InsertableHtmlContent implements Serializable * Set the quoted content. The insertion point should be set against this content. * @param content */ - public void setQuotedContent(StringBuilder content) - { + public void setQuotedContent(StringBuilder content) { this.quotedContent = content; } @@ -70,8 +64,7 @@ class InsertableHtmlContent implements Serializable * existing header and quoted content.

    * @param content Content to add. */ - public void insertIntoQuotedHeader(final String content) - { + public void insertIntoQuotedHeader(final String content) { quotedContent.insert(headerInsertionPoint, content); // Update the location of the footer insertion point. footerInsertionPoint += content.length(); @@ -85,8 +78,7 @@ class InsertableHtmlContent implements Serializable * existing footer and quoted content.

    * @param content Content to add. */ - public void insertIntoQuotedFooter(final String content) - { + public void insertIntoQuotedFooter(final String content) { quotedContent.insert(footerInsertionPoint, content); // Update the location of the footer insertion point to the end of the inserted content. footerInsertionPoint += content.length(); @@ -95,8 +87,7 @@ class InsertableHtmlContent implements Serializable /** * Remove all quoted content. */ - public void clearQuotedContent() - { + public void clearQuotedContent() { quotedContent.setLength(0); footerInsertionPoint = 0; headerInsertionPoint = 0; @@ -107,8 +98,7 @@ class InsertableHtmlContent implements Serializable * inserted content buffer. * @param content */ - public void setUserContent(final String content) - { + public void setUserContent(final String content) { userContent = new StringBuilder(content); } @@ -116,8 +106,7 @@ class InsertableHtmlContent implements Serializable * Configure where user content should be inserted, either before or after the quoted content. * @param insertionLocation Where to insert user content. */ - public void setInsertionLocation(final InsertionLocation insertionLocation) - { + public void setInsertionLocation(final InsertionLocation insertionLocation) { this.insertionLocation = insertionLocation; } @@ -125,14 +114,10 @@ class InsertableHtmlContent implements Serializable * Fetch the insertion point based upon the quote style. * @return Insertion point */ - public int getInsertionPoint() - { - if (insertionLocation == InsertionLocation.BEFORE_QUOTE) - { + public int getInsertionPoint() { + if (insertionLocation == InsertionLocation.BEFORE_QUOTE) { return headerInsertionPoint; - } - else - { + } else { return footerInsertionPoint; } } @@ -142,8 +127,7 @@ class InsertableHtmlContent implements Serializable * @return Composed string. */ @Override - public String toString() - { + public String toString() { final int insertionPoint = getInsertionPoint(); // Inserting and deleting was twice as fast as instantiating a new StringBuilder and // using substring() to build the new pieces. @@ -156,8 +140,7 @@ class InsertableHtmlContent implements Serializable * Return debugging information for this container. * @return Debug string. */ - public String toDebugString() - { + public String toDebugString() { return "InsertableHtmlContent{" + "headerInsertionPoint=" + headerInsertionPoint + ", footerInsertionPoint=" + footerInsertionPoint + diff --git a/src/com/fsck/k9/activity/K9Activity.java b/src/com/fsck/k9/activity/K9Activity.java index f59b63014..3fa72700b 100644 --- a/src/com/fsck/k9/activity/K9Activity.java +++ b/src/com/fsck/k9/activity/K9Activity.java @@ -19,23 +19,19 @@ import com.fsck.k9.K9; import com.fsck.k9.helper.DateFormatter; -public class K9Activity extends Activity -{ +public class K9Activity extends Activity { private GestureDetector gestureDetector; protected ScrollView mTopView; @Override - public void onCreate(Bundle icicle) - { + public void onCreate(Bundle icicle) { onCreate(icicle, true); } - public void onCreate(Bundle icicle, boolean useTheme) - { + public void onCreate(Bundle icicle, boolean useTheme) { setLanguage(this, K9.getK9Language()); - if (useTheme) - { + if (useTheme) { setTheme(K9.getK9Theme()); } super.onCreate(icicle); @@ -46,20 +42,14 @@ public class K9Activity extends Activity } - public static void setLanguage(Context context, String language) - { + public static void setLanguage(Context context, String language) { Locale locale; - if (language == null || language.equals("")) - { + if (language == null || language.equals("")) { locale = Locale.getDefault(); - } - else if (language.length() == 5 && language.charAt(2) == '_') - { + } else if (language.length() == 5 && language.charAt(2) == '_') { // language is in the form: en_US locale = new Locale(language.substring(0, 2), language.substring(3)); - } - else - { + } else { locale = new Locale(language); } Configuration config = new Configuration(); @@ -69,15 +59,13 @@ public class K9Activity extends Activity } @Override - public boolean dispatchTouchEvent(MotionEvent ev) - { + public boolean dispatchTouchEvent(MotionEvent ev) { super.dispatchTouchEvent(ev); return gestureDetector.onTouchEvent(ev); } @Override - public void onResume() - { + public void onResume() { super.onResume(); setupFormats(); } @@ -85,43 +73,35 @@ public class K9Activity extends Activity private java.text.DateFormat mDateFormat; private java.text.DateFormat mTimeFormat; - private void setupFormats() - { + private void setupFormats() { mDateFormat = DateFormatter.getDateFormat(this); mTimeFormat = android.text.format.DateFormat.getTimeFormat(this); // 12/24 date format } - public java.text.DateFormat getTimeFormat() - { + public java.text.DateFormat getTimeFormat() { return mTimeFormat; } - public java.text.DateFormat getDateFormat() - { + public java.text.DateFormat getDateFormat() { return mDateFormat; } - protected void onNext() - { + protected void onNext() { } - protected void onPrevious() - { + protected void onPrevious() { } - protected Animation inFromRightAnimation() - { + protected Animation inFromRightAnimation() { return slideAnimation(0.0f, +1.0f); } - protected Animation outToLeftAnimation() - { + protected Animation outToLeftAnimation() { return slideAnimation(0.0f, -1.0f); } - private Animation slideAnimation(float right, float left) - { + private Animation slideAnimation(float right, float left) { Animation slide = new TranslateAnimation( Animation.RELATIVE_TO_PARENT, right, Animation.RELATIVE_TO_PARENT, left, @@ -133,27 +113,21 @@ public class K9Activity extends Activity return slide; } - class MyGestureDetector extends SimpleOnGestureListener - { + class MyGestureDetector extends SimpleOnGestureListener { private static final float SWIPE_MIN_DISTANCE_DIP = 130.0f; private static final float SWIPE_MAX_OFF_PATH_DIP = 250f; private static final float SWIPE_THRESHOLD_VELOCITY_DIP = 325f; @Override - public boolean onDoubleTap(MotionEvent ev) - { + public boolean onDoubleTap(MotionEvent ev) { super.onDoubleTap(ev); - if (mTopView != null) - { + if (mTopView != null) { int height = getResources().getDisplayMetrics().heightPixels; - if (ev.getRawY() < (height/4)) - { + if (ev.getRawY() < (height / 4)) { mTopView.fullScroll(View.FOCUS_UP); - } - else if (ev.getRawY() > (height - height/4)) - { + } else if (ev.getRawY() > (height - height / 4)) { mTopView.fullScroll(View.FOCUS_DOWN); } @@ -162,10 +136,8 @@ public class K9Activity extends Activity } @Override - public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) - { - if (K9.gesturesEnabled()) - { + public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { + if (K9.gesturesEnabled()) { // Convert the dips to pixels final float mGestureScale = getResources().getDisplayMetrics().density; int min_distance = (int)(SWIPE_MIN_DISTANCE_DIP * mGestureScale + 0.5f); @@ -173,22 +145,16 @@ public class K9Activity extends Activity int max_off_path = (int)(SWIPE_MAX_OFF_PATH_DIP * mGestureScale + 0.5f); - try - { + try { if (Math.abs(e1.getY() - e2.getY()) > max_off_path) return false; // right to left swipe - if (e1.getX() - e2.getX() > min_distance && Math.abs(velocityX) > min_velocity) - { + if (e1.getX() - e2.getX() > min_distance && Math.abs(velocityX) > min_velocity) { onNext(); - } - else if (e2.getX() - e1.getX() > min_distance && Math.abs(velocityX) > min_velocity) - { + } else if (e2.getX() - e1.getX() > min_distance && Math.abs(velocityX) > min_velocity) { onPrevious(); } - } - catch (Exception e) - { + } catch (Exception e) { // nothing } } diff --git a/src/com/fsck/k9/activity/K9ExpandableListActivity.java b/src/com/fsck/k9/activity/K9ExpandableListActivity.java index c5438289a..3e1b509a7 100644 --- a/src/com/fsck/k9/activity/K9ExpandableListActivity.java +++ b/src/com/fsck/k9/activity/K9ExpandableListActivity.java @@ -8,12 +8,10 @@ import com.fsck.k9.K9; /** * @see ExpandableListActivity */ -public class K9ExpandableListActivity extends ExpandableListActivity -{ +public class K9ExpandableListActivity extends ExpandableListActivity { @Override - protected void onCreate(Bundle savedInstanceState) - { + protected void onCreate(Bundle savedInstanceState) { setTheme(K9.getK9Theme()); super.onCreate(savedInstanceState); } diff --git a/src/com/fsck/k9/activity/K9ListActivity.java b/src/com/fsck/k9/activity/K9ListActivity.java index 4a9d60aea..204182be2 100644 --- a/src/com/fsck/k9/activity/K9ListActivity.java +++ b/src/com/fsck/k9/activity/K9ListActivity.java @@ -9,11 +9,9 @@ import android.os.Bundle; import com.fsck.k9.K9; import com.fsck.k9.helper.DateFormatter; -public class K9ListActivity extends ListActivity -{ +public class K9ListActivity extends ListActivity { @Override - public void onCreate(Bundle icicle) - { + public void onCreate(Bundle icicle) { K9Activity.setLanguage(this, K9.getK9Language()); setTheme(K9.getK9Theme()); super.onCreate(icicle); @@ -21,8 +19,7 @@ public class K9ListActivity extends ListActivity } @Override - public void onResume() - { + public void onResume() { super.onResume(); setupFormats(); } @@ -30,80 +27,64 @@ public class K9ListActivity extends ListActivity private java.text.DateFormat mDateFormat; private java.text.DateFormat mTimeFormat; - private void setupFormats() - { + private void setupFormats() { mDateFormat = DateFormatter.getDateFormat(this); mTimeFormat = android.text.format.DateFormat.getTimeFormat(this); // 12/24 date format } - public java.text.DateFormat getTimeFormat() - { + public java.text.DateFormat getTimeFormat() { return mTimeFormat; } - public java.text.DateFormat getDateFormat() - { + public java.text.DateFormat getDateFormat() { return mDateFormat; } @Override - public boolean onKeyDown(int keyCode, KeyEvent event) - { + public boolean onKeyDown(int keyCode, KeyEvent event) { // Shortcuts that work no matter what is selected - switch (keyCode) - { - case KeyEvent.KEYCODE_VOLUME_UP: - { - final ListView listView = getListView(); - if (K9.useVolumeKeysForListNavigationEnabled()) - { - int currentPosition = listView.getSelectedItemPosition(); - if (currentPosition == AdapterView.INVALID_POSITION || listView.isInTouchMode()) - { - currentPosition = listView.getFirstVisiblePosition(); - } - if (currentPosition > 0) - { - listView.setSelection(currentPosition - 1); - } - return true; + switch (keyCode) { + case KeyEvent.KEYCODE_VOLUME_UP: { + final ListView listView = getListView(); + if (K9.useVolumeKeysForListNavigationEnabled()) { + int currentPosition = listView.getSelectedItemPosition(); + if (currentPosition == AdapterView.INVALID_POSITION || listView.isInTouchMode()) { + currentPosition = listView.getFirstVisiblePosition(); } + if (currentPosition > 0) { + listView.setSelection(currentPosition - 1); + } + return true; } - case KeyEvent.KEYCODE_VOLUME_DOWN: - { - final ListView listView = getListView(); - if (K9.useVolumeKeysForListNavigationEnabled()) - { - int currentPosition = listView.getSelectedItemPosition(); - if (currentPosition == AdapterView.INVALID_POSITION || listView.isInTouchMode()) - { - currentPosition = listView.getFirstVisiblePosition(); - } + } + case KeyEvent.KEYCODE_VOLUME_DOWN: { + final ListView listView = getListView(); + if (K9.useVolumeKeysForListNavigationEnabled()) { + int currentPosition = listView.getSelectedItemPosition(); + if (currentPosition == AdapterView.INVALID_POSITION || listView.isInTouchMode()) { + currentPosition = listView.getFirstVisiblePosition(); + } - if (currentPosition < listView.getCount()) - { - listView.setSelection(currentPosition + 1); - } - return true; + if (currentPosition < listView.getCount()) { + listView.setSelection(currentPosition + 1); } + return true; } } + } return super.onKeyDown(keyCode, event); } @Override - public boolean onKeyUp(int keyCode, KeyEvent event) - { + public boolean onKeyUp(int keyCode, KeyEvent event) { // Swallow these events too to avoid the audible notification of a volume change - if (K9.useVolumeKeysForListNavigationEnabled()) - { - if ((keyCode == KeyEvent.KEYCODE_VOLUME_UP) || (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)) - { + if (K9.useVolumeKeysForListNavigationEnabled()) { + if ((keyCode == KeyEvent.KEYCODE_VOLUME_UP) || (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)) { if (K9.DEBUG) Log.v(K9.LOG_TAG, "Swallowed key up."); return true; } } - return super.onKeyUp(keyCode,event); + return super.onKeyUp(keyCode, event); } } diff --git a/src/com/fsck/k9/activity/K9PreferenceActivity.java b/src/com/fsck/k9/activity/K9PreferenceActivity.java index 98deec3fe..fff69b028 100644 --- a/src/com/fsck/k9/activity/K9PreferenceActivity.java +++ b/src/com/fsck/k9/activity/K9PreferenceActivity.java @@ -7,11 +7,9 @@ import android.preference.ListPreference; import android.preference.Preference; -public class K9PreferenceActivity extends PreferenceActivity -{ +public class K9PreferenceActivity extends PreferenceActivity { @Override - public void onCreate(Bundle icicle) - { + public void onCreate(Bundle icicle) { K9Activity.setLanguage(this, K9.getK9Language()); // http://code.google.com/p/k9mail/issues/detail?id=2439 // Re-enable themeing support in preferences when @@ -30,8 +28,7 @@ public class K9PreferenceActivity extends PreferenceActivity * * @return The {@link ListPreference} instance identified by {@code key}. */ - protected ListPreference setupListPreference(final String key, final String value) - { + protected ListPreference setupListPreference(final String key, final String value) { final ListPreference prefView = (ListPreference) findPreference(key); prefView.setValue(value); prefView.setSummary(prefView.getEntry()); @@ -53,8 +50,7 @@ public class K9PreferenceActivity extends PreferenceActivity * entry from entries is selected. */ protected void initListPreference(final ListPreference prefView, final String value, - final CharSequence[] entries, final CharSequence[] entryValues) - { + final CharSequence[] entries, final CharSequence[] entryValues) { prefView.setEntries(entries); prefView.setEntryValues(entryValues); prefView.setValue(value); @@ -65,12 +61,10 @@ public class K9PreferenceActivity extends PreferenceActivity /** * This class handles value changes of the {@link ListPreference} objects. */ - private static class PreferenceChangeListener implements Preference.OnPreferenceChangeListener - { + private static class PreferenceChangeListener implements Preference.OnPreferenceChangeListener { private ListPreference mPrefView; - private PreferenceChangeListener(final ListPreference prefView) - { + private PreferenceChangeListener(final ListPreference prefView) { this.mPrefView = prefView; } @@ -78,8 +72,7 @@ public class K9PreferenceActivity extends PreferenceActivity * Show the preference value in the preference summary field. */ @Override - public boolean onPreferenceChange(final Preference preference, final Object newValue) - { + public boolean onPreferenceChange(final Preference preference, final Object newValue) { final String summary = newValue.toString(); final int index = mPrefView.findIndexOfValue(summary); mPrefView.setSummary(mPrefView.getEntries()[index]); diff --git a/src/com/fsck/k9/activity/LauncherShortcuts.java b/src/com/fsck/k9/activity/LauncherShortcuts.java index fd9c20cfb..58107e54d 100644 --- a/src/com/fsck/k9/activity/LauncherShortcuts.java +++ b/src/com/fsck/k9/activity/LauncherShortcuts.java @@ -18,19 +18,16 @@ import com.fsck.k9.K9; import com.fsck.k9.Preferences; import com.fsck.k9.R; -public class LauncherShortcuts extends K9ListActivity implements OnItemClickListener -{ +public class LauncherShortcuts extends K9ListActivity implements OnItemClickListener { private AccountsAdapter mAdapter; private FontSizes mFontSizes = K9.getFontSizes(); @Override - public void onCreate(Bundle icicle) - { + public void onCreate(Bundle icicle) { super.onCreate(icicle); // finish() immediately if we aren't supposed to be here - if (!Intent.ACTION_CREATE_SHORTCUT.equals(getIntent().getAction())) - { + if (!Intent.ACTION_CREATE_SHORTCUT.equals(getIntent().getAction())) { finish(); return; } @@ -43,23 +40,20 @@ public class LauncherShortcuts extends K9ListActivity implements OnItemClickList refresh(); } - private void refresh() - { + private void refresh() { Account[] accounts = Preferences.getPreferences(this).getAccounts(); mAdapter = new AccountsAdapter(accounts); getListView().setAdapter(mAdapter); } - private void setupShortcut(Account account) - { + private void setupShortcut(Account account) { final Intent shortcutIntent = FolderList.actionHandleAccountIntent(this, account, null, true); Intent intent = new Intent(); intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent); String description = account.getDescription(); - if (description == null || description.length() == 0) - { + if (description == null || description.length() == 0) { description = account.getEmail(); } intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, description); @@ -70,38 +64,30 @@ public class LauncherShortcuts extends K9ListActivity implements OnItemClickList finish(); } - public void onItemClick(AdapterView parent, View view, int position, long id) - { + public void onItemClick(AdapterView parent, View view, int position, long id) { Account account = (Account) parent.getItemAtPosition(position); setupShortcut(account); } - class AccountsAdapter extends ArrayAdapter - { - public AccountsAdapter(Account[] accounts) - { + class AccountsAdapter extends ArrayAdapter { + public AccountsAdapter(Account[] accounts) { super(LauncherShortcuts.this, 0, accounts); } @Override - public View getView(int position, View convertView, ViewGroup parent) - { + public View getView(int position, View convertView, ViewGroup parent) { final Account account = getItem(position); final View view; - if (convertView != null) - { + if (convertView != null) { view = convertView; - } - else - { + } else { view = getLayoutInflater().inflate(R.layout.accounts_item, parent, false); view.findViewById(R.id.active_icons).setVisibility(View.GONE); } AccountViewHolder holder = (AccountViewHolder) view.getTag(); - if (holder == null) - { + if (holder == null) { holder = new AccountViewHolder(); holder.description = (TextView) view.findViewById(R.id.description); holder.email = (TextView) view.findViewById(R.id.email); @@ -111,18 +97,14 @@ public class LauncherShortcuts extends K9ListActivity implements OnItemClickList } String description = account.getDescription(); - if (account.getEmail().equals(description)) - { + if (account.getEmail().equals(description)) { holder.email.setVisibility(View.GONE); - } - else - { + } else { holder.email.setVisibility(View.VISIBLE); holder.email.setText(account.getEmail()); } - if (description == null || description.length() == 0) - { + if (description == null || description.length() == 0) { description = account.getEmail(); } @@ -137,8 +119,7 @@ public class LauncherShortcuts extends K9ListActivity implements OnItemClickList return view; } - class AccountViewHolder - { + class AccountViewHolder { public TextView description; public TextView email; public View chip; diff --git a/src/com/fsck/k9/activity/ManageIdentities.java b/src/com/fsck/k9/activity/ManageIdentities.java index e493d5de2..3e5d83813 100644 --- a/src/com/fsck/k9/activity/ManageIdentities.java +++ b/src/com/fsck/k9/activity/ManageIdentities.java @@ -11,20 +11,16 @@ import com.fsck.k9.Identity; import com.fsck.k9.Preferences; import com.fsck.k9.R; -public class ManageIdentities extends ChooseIdentity -{ +public class ManageIdentities extends ChooseIdentity { private boolean mIdentitiesChanged = false; public static final String EXTRA_IDENTITIES = "com.fsck.k9.EditIdentity_identities"; private static final int ACTIVITY_EDIT_IDENTITY = 1; @Override - protected void setupClickListeners() - { - this.getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() - { - public void onItemClick(AdapterView parent, View view, int position, long id) - { + protected void setupClickListeners() { + this.getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() { + public void onItemClick(AdapterView parent, View view, int position, long id) { editItem(position); } }); @@ -33,8 +29,7 @@ public class ManageIdentities extends ChooseIdentity registerForContextMenu(listView); } - private void editItem(int i) - { + private void editItem(int i) { Intent intent = new Intent(ManageIdentities.this, EditIdentity.class); intent.putExtra(EditIdentity.EXTRA_ACCOUNT, mAccount.getUuid()); intent.putExtra(EditIdentity.EXTRA_IDENTITY, mAccount.getIdentity(i)); @@ -43,92 +38,80 @@ public class ManageIdentities extends ChooseIdentity } @Override - public boolean onCreateOptionsMenu(Menu menu) - { + public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.manage_identities_option, menu); return true; } @Override - public boolean onOptionsItemSelected(MenuItem item) - { - switch (item.getItemId()) - { - case R.id.new_identity: - Intent intent = new Intent(ManageIdentities.this, EditIdentity.class); - intent.putExtra(EditIdentity.EXTRA_ACCOUNT, mAccount.getUuid()); - startActivityForResult(intent, ACTIVITY_EDIT_IDENTITY); - break; - default: - return super.onOptionsItemSelected(item); + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + case R.id.new_identity: + Intent intent = new Intent(ManageIdentities.this, EditIdentity.class); + intent.putExtra(EditIdentity.EXTRA_ACCOUNT, mAccount.getUuid()); + startActivityForResult(intent, ACTIVITY_EDIT_IDENTITY); + break; + default: + return super.onOptionsItemSelected(item); } return true; } @Override - public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) - { + public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); menu.setHeaderTitle(R.string.manage_identities_context_menu_title); getMenuInflater().inflate(R.menu.manage_identities_context, menu); } @Override - public boolean onContextItemSelected(MenuItem item) - { + public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo)item.getMenuInfo(); - switch (item.getItemId()) - { - case R.id.edit: - editItem(menuInfo.position); - break; - case R.id.up: - if (menuInfo.position > 0) - { - Identity identity = identities.remove(menuInfo.position); - identities.add(menuInfo.position - 1, identity); - mIdentitiesChanged = true; - refreshView(); - } - - break; - case R.id.down: - if (menuInfo.position < identities.size() - 1) - { - Identity identity = identities.remove(menuInfo.position); - identities.add(menuInfo.position + 1, identity); - mIdentitiesChanged = true; - refreshView(); - } - break; - case R.id.top: + switch (item.getItemId()) { + case R.id.edit: + editItem(menuInfo.position); + break; + case R.id.up: + if (menuInfo.position > 0) { Identity identity = identities.remove(menuInfo.position); - identities.add(0, identity); + identities.add(menuInfo.position - 1, identity); mIdentitiesChanged = true; refreshView(); - break; - case R.id.remove: - if (identities.size() > 1) - { - identities.remove(menuInfo.position); - mIdentitiesChanged = true; - refreshView(); - } - else - { - Toast.makeText(this, getString(R.string.no_removable_identity), - Toast.LENGTH_LONG).show(); - } - break; + } + + break; + case R.id.down: + if (menuInfo.position < identities.size() - 1) { + Identity identity = identities.remove(menuInfo.position); + identities.add(menuInfo.position + 1, identity); + mIdentitiesChanged = true; + refreshView(); + } + break; + case R.id.top: + Identity identity = identities.remove(menuInfo.position); + identities.add(0, identity); + mIdentitiesChanged = true; + refreshView(); + break; + case R.id.remove: + if (identities.size() > 1) { + identities.remove(menuInfo.position); + mIdentitiesChanged = true; + refreshView(); + } else { + Toast.makeText(this, getString(R.string.no_removable_identity), + Toast.LENGTH_LONG).show(); + } + break; } return true; } @Override - public void onResume() - { + public void onResume() { super.onResume(); //mAccount.refresh(Preferences.getPreferences(getApplication().getApplicationContext())); refreshView(); @@ -136,19 +119,15 @@ public class ManageIdentities extends ChooseIdentity @Override - public boolean onKeyDown(int keyCode, KeyEvent event) - { - if (keyCode == KeyEvent.KEYCODE_BACK) - { + public boolean onKeyDown(int keyCode, KeyEvent event) { + if (keyCode == KeyEvent.KEYCODE_BACK) { saveIdentities(); } return super.onKeyDown(keyCode, event); } - private void saveIdentities() - { - if (mIdentitiesChanged) - { + private void saveIdentities() { + if (mIdentitiesChanged) { mAccount.setIdentities(identities); mAccount.save(Preferences.getPreferences(getApplication().getApplicationContext())); } diff --git a/src/com/fsck/k9/activity/MessageCompose.java b/src/com/fsck/k9/activity/MessageCompose.java index 74ebdf4d9..3352808d7 100644 --- a/src/com/fsck/k9/activity/MessageCompose.java +++ b/src/com/fsck/k9/activity/MessageCompose.java @@ -71,8 +71,7 @@ import com.fsck.k9.mail.internet.TextBody; import com.fsck.k9.mail.store.LocalStore; import com.fsck.k9.mail.store.LocalStore.LocalAttachmentBody; -public class MessageCompose extends K9Activity implements OnClickListener, OnFocusChangeListener -{ +public class MessageCompose extends K9Activity implements OnClickListener, OnFocusChangeListener { private static final int DIALOG_SAVE_OR_DISCARD_DRAFT_MESSAGE = 1; private static final String ACTION_REPLY = "com.fsck.k9.intent.action.REPLY"; @@ -193,43 +192,40 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc */ private String mDraftUid; - private Handler mHandler = new Handler() - { + private Handler mHandler = new Handler() { @Override - public void handleMessage(android.os.Message msg) - { - switch (msg.what) - { - case MSG_PROGRESS_ON: - setProgressBarIndeterminateVisibility(true); - break; - case MSG_PROGRESS_OFF: - setProgressBarIndeterminateVisibility(false); - break; - case MSG_UPDATE_TITLE: - updateTitle(); - break; - case MSG_SKIPPED_ATTACHMENTS: - Toast.makeText( - MessageCompose.this, - getString(R.string.message_compose_attachments_skipped_toast), - Toast.LENGTH_LONG).show(); - break; - case MSG_SAVED_DRAFT: - Toast.makeText( - MessageCompose.this, - getString(R.string.message_saved_toast), - Toast.LENGTH_LONG).show(); - break; - case MSG_DISCARDED_DRAFT: - Toast.makeText( - MessageCompose.this, - getString(R.string.message_discarded_toast), - Toast.LENGTH_LONG).show(); - break; - default: - super.handleMessage(msg); - break; + public void handleMessage(android.os.Message msg) { + switch (msg.what) { + case MSG_PROGRESS_ON: + setProgressBarIndeterminateVisibility(true); + break; + case MSG_PROGRESS_OFF: + setProgressBarIndeterminateVisibility(false); + break; + case MSG_UPDATE_TITLE: + updateTitle(); + break; + case MSG_SKIPPED_ATTACHMENTS: + Toast.makeText( + MessageCompose.this, + getString(R.string.message_compose_attachments_skipped_toast), + Toast.LENGTH_LONG).show(); + break; + case MSG_SAVED_DRAFT: + Toast.makeText( + MessageCompose.this, + getString(R.string.message_saved_toast), + Toast.LENGTH_LONG).show(); + break; + case MSG_DISCARDED_DRAFT: + Toast.makeText( + MessageCompose.this, + getString(R.string.message_discarded_toast), + Toast.LENGTH_LONG).show(); + break; + default: + super.handleMessage(msg); + break; } } }; @@ -239,8 +235,7 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc private Validator mAddressValidator; - static class Attachment implements Serializable - { + static class Attachment implements Serializable { private static final long serialVersionUID = 3642382876618963734L; public String name; public String contentType; @@ -254,10 +249,8 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc * @param context * @param account */ - public static void actionCompose(Context context, Account account) - { - if (account == null) - { + public static void actionCompose(Context context, Account account) { + if (account == null) { account = Preferences.getPreferences(context).getDefaultAccount(); } Intent i = new Intent(context, MessageCompose.class); @@ -279,17 +272,13 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc Account account, Message message, boolean replyAll, - String messageBody) - { + String messageBody) { Intent i = new Intent(context, MessageCompose.class); i.putExtra(EXTRA_MESSAGE_BODY, messageBody); i.putExtra(EXTRA_MESSAGE_REFERENCE, message.makeMessageReference()); - if (replyAll) - { + if (replyAll) { i.setAction(ACTION_REPLY_ALL); - } - else - { + } else { i.setAction(ACTION_REPLY); } context.startActivity(i); @@ -306,8 +295,7 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc Context context, Account account, Message message, - String messageBody) - { + String messageBody) { Intent i = new Intent(context, MessageCompose.class); i.putExtra(EXTRA_MESSAGE_BODY, messageBody); i.putExtra(EXTRA_MESSAGE_REFERENCE, message.makeMessageReference()); @@ -324,8 +312,7 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc * @param account * @param message */ - public static void actionEditDraft(Context context, Account account, Message message) - { + public static void actionEditDraft(Context context, Account account, Message message) { Intent i = new Intent(context, MessageCompose.class); i.putExtra(EXTRA_MESSAGE_REFERENCE, message.makeMessageReference()); i.setAction(ACTION_EDIT_DRAFT); @@ -333,8 +320,7 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc } @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.message_compose); @@ -344,7 +330,7 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc mMessageReference = (MessageReference) intent.getSerializableExtra(EXTRA_MESSAGE_REFERENCE); mSourceMessageBody = intent.getStringExtra(EXTRA_MESSAGE_BODY); - if(K9.DEBUG && mSourceMessageBody != null) + if (K9.DEBUG && mSourceMessageBody != null) Log.d(K9.LOG_TAG, "Composing message with explicitly specified message body."); final String accountUuid = (mMessageReference != null) ? @@ -353,13 +339,11 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc mAccount = Preferences.getPreferences(this).getAccount(accountUuid); - if (mAccount == null) - { + if (mAccount == null) { mAccount = Preferences.getPreferences(this).getDefaultAccount(); } - if (mAccount == null) - { + if (mAccount == null) { /* * There are no accounts set up. This should not have happened. Prompt the * user to set up an account as an acceptable bailout. @@ -395,37 +379,31 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc mQuotedHTML.configure(); // Disable the ability to click links in the quoted HTML page. I think this is a nice feature, but if someone // feels this should be a preference (or should go away all together), I'm ok with that too. -achen 20101130 - mQuotedHTML.setWebViewClient(new WebViewClient() - { + mQuotedHTML.setWebViewClient(new WebViewClient() { @Override - public boolean shouldOverrideUrlLoading(WebView view, String url) - { + public boolean shouldOverrideUrlLoading(WebView view, String url) { return true; } }); - TextWatcher watcher = new TextWatcher() - { + TextWatcher watcher = new TextWatcher() { public void beforeTextChanged(CharSequence s, int start, int before, int after) { } public void onTextChanged(CharSequence s, int start, - int before, int count) - { + int before, int count) { mDraftNeedsSaving = true; } public void afterTextChanged(android.text.Editable s) { } }; - TextWatcher sigwatcher = new TextWatcher() - { + TextWatcher sigwatcher = new TextWatcher() { public void beforeTextChanged(CharSequence s, int start, int before, int after) { } public void onTextChanged(CharSequence s, int start, - int before, int count) - { + int before, int count) { mDraftNeedsSaving = true; mSignatureChanged = true; } @@ -470,8 +448,7 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc mSubjectView.setOnFocusChangeListener(this); - if (savedInstanceState != null) - { + if (savedInstanceState != null) { /* * This data gets used in onCreate, so grab it here instead of onRestoreInstanceState */ @@ -482,40 +459,33 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc final String action = intent.getAction(); initFromIntent(intent); - if (mIdentity == null) - { + if (mIdentity == null) { mIdentity = mAccount.getIdentity(0); } - if (mAccount.isSignatureBeforeQuotedText()) - { + if (mAccount.isSignatureBeforeQuotedText()) { mSignatureView = upperSignature; lowerSignature.setVisibility(View.GONE); - } - else - { + } else { mSignatureView = lowerSignature; upperSignature.setVisibility(View.GONE); } mSignatureView.addTextChangedListener(sigwatcher); - if (!mIdentity.getSignatureUse()) - { + if (!mIdentity.getSignatureUse()) { mSignatureView.setVisibility(View.GONE); } mMessageFormat = mAccount.getMessageFormat(); - if (!mSourceMessageProcessed) - { + if (!mSourceMessageProcessed) { updateFrom(); updateSignature(); if (ACTION_REPLY.equals(action) || ACTION_REPLY_ALL.equals(action) || ACTION_FORWARD.equals(action) || - ACTION_EDIT_DRAFT.equals(action)) - { + ACTION_EDIT_DRAFT.equals(action)) { /* * If we need to load the message we add ourself as a message listener here * so we can kick it off. Normally we add in onResume but we don't @@ -530,11 +500,9 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc MessagingController.getInstance(getApplication()).loadMessageForView(account, folderName, sourceMessageUid, null); } - if (!ACTION_EDIT_DRAFT.equals(action)) - { + if (!ACTION_EDIT_DRAFT.equals(action)) { String bccAddress = mAccount.getAlwaysBcc(); - if ((bccAddress != null) && !("".equals(bccAddress))) - { + if ((bccAddress != null) && !("".equals(bccAddress))) { addAddress(mBccView, new Address(bccAddress, "")); } } @@ -548,15 +516,13 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc } if (ACTION_REPLY.equals(action) || - ACTION_REPLY_ALL.equals(action)) - { + ACTION_REPLY_ALL.equals(action)) { mMessageReference.flag = Flag.ANSWERED; } if (ACTION_REPLY.equals(action) || ACTION_REPLY_ALL.equals(action) || - ACTION_EDIT_DRAFT.equals(action)) - { + ACTION_EDIT_DRAFT.equals(action)) { //change focus to message body. mMessageContentView.requestFocus(); } @@ -569,50 +535,37 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc initializeCrypto(); final CryptoProvider crypto = mAccount.getCryptoProvider(); - if (crypto.isAvailable(this)) - { + if (crypto.isAvailable(this)) { mEncryptLayout.setVisibility(View.VISIBLE); - mCryptoSignatureCheckbox.setOnClickListener(new OnClickListener() - { + mCryptoSignatureCheckbox.setOnClickListener(new OnClickListener() { @Override - public void onClick(View v) - { + public void onClick(View v) { CheckBox checkBox = (CheckBox) v; - if (checkBox.isChecked()) - { + if (checkBox.isChecked()) { mPreventDraftSaving = true; - if (!crypto.selectSecretKey(MessageCompose.this, mPgpData)) - { + if (!crypto.selectSecretKey(MessageCompose.this, mPgpData)) { mPreventDraftSaving = false; } checkBox.setChecked(false); - } - else - { + } else { mPgpData.setSignatureKeyId(0); updateEncryptLayout(); } } }); - if (mAccount.getCryptoAutoSignature()) - { + if (mAccount.getCryptoAutoSignature()) { long ids[] = crypto.getSecretKeyIdsFromEmail(this, mIdentity.getEmail()); - if (ids != null && ids.length > 0) - { + if (ids != null && ids.length > 0) { mPgpData.setSignatureKeyId(ids[0]); mPgpData.setSignatureUserId(crypto.getUserId(this, ids[0])); - } - else - { + } else { mPgpData.setSignatureKeyId(0); mPgpData.setSignatureUserId(null); } } updateEncryptLayout(); - } - else - { + } else { mEncryptLayout.setVisibility(View.GONE); } @@ -624,20 +577,16 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc * * @param intent The (external) intent that started the activity. */ - private void initFromIntent(final Intent intent) - { + private void initFromIntent(final Intent intent) { final String action = intent.getAction(); - if (Intent.ACTION_VIEW.equals(action) || Intent.ACTION_SENDTO.equals(action)) - { + if (Intent.ACTION_VIEW.equals(action) || Intent.ACTION_SENDTO.equals(action)) { /* * Someone has clicked a mailto: link. The address is in the URI. */ - if (intent.getData() != null) - { + if (intent.getData() != null) { Uri uri = intent.getData(); - if ("mailto".equals(uri.getScheme())) - { + if ("mailto".equals(uri.getScheme())) { initializeFromMailto(uri); } } @@ -652,8 +601,7 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc } //TODO: Use constant Intent.ACTION_SEND_MULTIPLE once we drop Android 1.5 support else if (Intent.ACTION_SEND.equals(action) || - "android.intent.action.SEND_MULTIPLE".equals(action)) - { + "android.intent.action.SEND_MULTIPLE".equals(action)) { /* * Note: Here we allow a slight deviation from the documentated behavior. * EXTRA_TEXT is used as message body (if available) regardless of the MIME @@ -661,30 +609,22 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc * using EXTRA_STREAM. */ CharSequence text = intent.getCharSequenceExtra(Intent.EXTRA_TEXT); - if (text != null) - { + if (text != null) { mMessageContentView.setText(text); } String type = intent.getType(); - if (Intent.ACTION_SEND.equals(action)) - { + if (Intent.ACTION_SEND.equals(action)) { Uri stream = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM); - if (stream != null) - { + if (stream != null) { addAttachment(stream, type); } - } - else - { + } else { ArrayList list = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM); - if (list != null) - { - for (Parcelable parcelable : list) - { + if (list != null) { + for (Parcelable parcelable : list) { Uri stream = (Uri) parcelable; - if (stream != null) - { + if (stream != null) { addAttachment(stream, type); } } @@ -692,8 +632,7 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc } String subject = intent.getStringExtra(Intent.EXTRA_SUBJECT); - if (subject != null) - { + if (subject != null) { mSubjectView.setText(subject); } @@ -701,38 +640,31 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc String[] extraCc = intent.getStringArrayExtra(Intent.EXTRA_CC); String[] extraBcc = intent.getStringArrayExtra(Intent.EXTRA_BCC); - if (extraEmail != null) - { + if (extraEmail != null) { setRecipients(mToView, Arrays.asList(extraEmail)); } boolean ccOrBcc = false; - if (extraCc != null) - { + if (extraCc != null) { ccOrBcc |= setRecipients(mCcView, Arrays.asList(extraCc)); } - if (extraBcc != null) - { + if (extraBcc != null) { ccOrBcc |= setRecipients(mBccView, Arrays.asList(extraBcc)); } - if (ccOrBcc) - { + if (ccOrBcc) { // Display CC and BCC text fields if CC or BCC recipients were set by the intent. onAddCcBcc(); } } } - private boolean setRecipients(TextView view, List recipients) - { + private boolean setRecipients(TextView view, List recipients) { boolean recipientAdded = false; - if (recipients != null) - { + if (recipients != null) { StringBuffer addressList = new StringBuffer(); - for (String recipient : recipients) - { + for (String recipient : recipients) { addressList.append(recipient); addressList.append(", "); recipientAdded = true; @@ -743,10 +675,8 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc return recipientAdded; } - private void initializeCrypto() - { - if (mPgpData != null) - { + private void initializeCrypto() { + if (mPgpData != null) { return; } mPgpData = new PgpData(); @@ -755,17 +685,13 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc /** * Fill the encrypt layout with the latest data about signature key and encryption keys. */ - public void updateEncryptLayout() - { - if (!mPgpData.hasSignatureKey()) - { + public void updateEncryptLayout() { + if (!mPgpData.hasSignatureKey()) { mCryptoSignatureCheckbox.setText(R.string.btn_crypto_sign); mCryptoSignatureCheckbox.setChecked(false); mCryptoSignatureUserId.setVisibility(View.INVISIBLE); mCryptoSignatureUserIdRest.setVisibility(View.INVISIBLE); - } - else - { + } else { // if a signature key is selected, then the checkbox itself has no text mCryptoSignatureCheckbox.setText(""); mCryptoSignatureCheckbox.setChecked(true); @@ -775,18 +701,15 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc mCryptoSignatureUserIdRest.setText(""); String userId = mPgpData.getSignatureUserId(); - if (userId == null) - { + if (userId == null) { userId = mAccount.getCryptoProvider().getUserId(this, mPgpData.getSignatureKeyId()); mPgpData.setSignatureUserId(userId); } - if (userId != null) - { + if (userId != null) { String chunks[] = mPgpData.getSignatureUserId().split(" <", 2); mCryptoSignatureUserId.setText(chunks[0]); - if (chunks.length > 1) - { + if (chunks.length > 1) { mCryptoSignatureUserIdRest.setText("<" + chunks[1]); } } @@ -794,15 +717,13 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc } @Override - public void onResume() - { + public void onResume() { super.onResume(); MessagingController.getInstance(getApplication()).addListener(mListener); } @Override - public void onPause() - { + public void onPause() { super.onPause(); saveIfNeeded(); MessagingController.getInstance(getApplication()).removeListener(mListener); @@ -817,13 +738,11 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc * Quoted text, */ @Override - protected void onSaveInstanceState(Bundle outState) - { + protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); saveIfNeeded(); ArrayList attachments = new ArrayList(); - for (int i = 0, count = mAttachments.getChildCount(); i < count; i++) - { + for (int i = 0, count = mAttachments.getChildCount(); i < count; i++) { View view = mAttachments.getChildAt(i); Attachment attachment = (Attachment) view.getTag(); attachments.add(attachment.uri); @@ -844,13 +763,11 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc } @Override - protected void onRestoreInstanceState(Bundle savedInstanceState) - { + protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); ArrayList attachments = savedInstanceState.getParcelableArrayList(STATE_KEY_ATTACHMENTS); mAttachments.removeAllViews(); - for (Parcelable p : attachments) - { + for (Parcelable p : attachments) { Uri uri = (Uri) p; addAttachment(uri); } @@ -858,19 +775,15 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc mMessageFormat = (MessageFormat)savedInstanceState.getSerializable(STATE_KEY_MESSAGE_FORMAT); mCcView.setVisibility(savedInstanceState.getBoolean(STATE_KEY_CC_SHOWN) ? View.VISIBLE : View.GONE); mBccView.setVisibility(savedInstanceState.getBoolean(STATE_KEY_BCC_SHOWN) ? View.VISIBLE : View.GONE); - if (mMessageFormat == MessageFormat.HTML) - { + if (mMessageFormat == MessageFormat.HTML) { mQuotedHtmlContent = (InsertableHtmlContent) savedInstanceState.getSerializable(STATE_KEY_HTML_QUOTE); mQuotedTextBar.setVisibility(savedInstanceState.getBoolean(STATE_KEY_QUOTED_TEXT_SHOWN) ? View.VISIBLE : View.GONE); mQuotedHTML.setVisibility(savedInstanceState.getBoolean(STATE_KEY_QUOTED_TEXT_SHOWN) ? View.VISIBLE : View.GONE); - if (mQuotedHtmlContent != null && mQuotedHtmlContent.getQuotedContent() != null) - { + if (mQuotedHtmlContent != null && mQuotedHtmlContent.getQuotedContent() != null) { mQuotedHTML.loadDataWithBaseURL("http://", mQuotedHtmlContent.getQuotedContent(), "text/html", "utf-8", null); mQuotedTextEdit.setVisibility(View.VISIBLE); } - } - else - { + } else { mQuotedTextBar.setVisibility(savedInstanceState.getBoolean(STATE_KEY_QUOTED_TEXT_SHOWN) ? View.VISIBLE : View.GONE); mQuotedText.setVisibility(savedInstanceState.getBoolean(STATE_KEY_QUOTED_TEXT_SHOWN) ? View.VISIBLE : View.GONE); } @@ -889,45 +802,34 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc mDraftNeedsSaving = false; } - private void updateTitle() - { - if (mSubjectView.getText().length() == 0) - { + private void updateTitle() { + if (mSubjectView.getText().length() == 0) { setTitle(R.string.compose_title); - } - else - { + } else { setTitle(mSubjectView.getText().toString()); } } - public void onFocusChange(View view, boolean focused) - { - if (!focused) - { + public void onFocusChange(View view, boolean focused) { + if (!focused) { updateTitle(); } } - private void addAddresses(MultiAutoCompleteTextView view, Address[] addresses) - { - if (addresses == null) - { + private void addAddresses(MultiAutoCompleteTextView view, Address[] addresses) { + if (addresses == null) { return; } - for (Address address : addresses) - { + for (Address address : addresses) { addAddress(view, address); } } - private void addAddress(MultiAutoCompleteTextView view, Address address) - { + private void addAddress(MultiAutoCompleteTextView view, Address address) { view.append(address + ", "); } - private Address[] getAddresses(MultiAutoCompleteTextView view) - { + private Address[] getAddresses(MultiAutoCompleteTextView view) { return Address.parseUnencoded(view.getText().toString().trim()); } @@ -938,13 +840,11 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc * appended and HTML separators between composed text and quoted text are not added. * @param isDraft If we should build a message that will be saved as a draft (as opposed to sent). */ - private TextBody buildText(boolean isDraft) - { + private TextBody buildText(boolean isDraft) { boolean replyAfterQuote = false; String action = getIntent().getAction(); if (mAccount.isReplyAfterQuote() && - (ACTION_REPLY.equals(action) || ACTION_REPLY_ALL.equals(action))) - { + (ACTION_REPLY.equals(action) || ACTION_REPLY_ALL.equals(action))) { replyAfterQuote = true; } @@ -953,22 +853,18 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc // Handle HTML separate from the rest of the text content. HTML mode doesn't allow signature after the quoted // text, nor does it allow reply after quote. Users who want that functionality will need to stick with text // mode. - if (mMessageFormat == MessageFormat.HTML) - { + if (mMessageFormat == MessageFormat.HTML) { // Add the signature. - if (!isDraft) - { + if (!isDraft) { text = appendSignature(text); } text = HtmlConverter.textToHtmlFragment(text); // Insert it into the existing content object. if (K9.DEBUG && mQuotedHtmlContent != null) Log.d(K9.LOG_TAG, "insertable: " + mQuotedHtmlContent.toDebugString()); - if (mQuotedHtmlContent != null) - { + if (mQuotedHtmlContent != null) { // Remove the quoted part if it's no longer visible. - if (mQuotedTextBar.getVisibility() != View.VISIBLE) - { + if (mQuotedTextBar.getVisibility() != View.VISIBLE) { mQuotedHtmlContent.clearQuotedContent(); } @@ -978,19 +874,14 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc // location. We only add the extra separators when we're sending, that way when we // load a draft, we don't have to know the length of the separators to remove them // before editing. - if (mAccount.getQuoteStyle() == QuoteStyle.PREFIX && replyAfterQuote) - { + if (mAccount.getQuoteStyle() == QuoteStyle.PREFIX && replyAfterQuote) { mQuotedHtmlContent.setInsertionLocation(InsertableHtmlContent.InsertionLocation.AFTER_QUOTE); - if (!isDraft) - { + if (!isDraft) { text = "
    " + text; } - } - else - { + } else { mQuotedHtmlContent.setInsertionLocation(InsertableHtmlContent.InsertionLocation.BEFORE_QUOTE); - if (!isDraft) - { + if (!isDraft) { text += "

    "; } } @@ -1003,45 +894,35 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc body.setComposedMessageLength(text.length()); body.setComposedMessageOffset(mQuotedHtmlContent.getInsertionPoint()); return body; - } - else - { + } else { TextBody body = new TextBody(text); body.setComposedMessageLength(text.length()); // Not in reply to anything so the message starts at the beginning (0). body.setComposedMessageOffset(0); return body; } - } - else if (mMessageFormat == MessageFormat.TEXT) - { + } else if (mMessageFormat == MessageFormat.TEXT) { // Capture composed message length before we start attaching quoted parts and signatures. Integer composedMessageLength = text.length(); Integer composedMessageOffset = 0; // Placing the signature before the quoted text does not make sense if replyAfterQuote is true. - if (!replyAfterQuote && !isDraft && mAccount.isSignatureBeforeQuotedText()) - { + if (!replyAfterQuote && !isDraft && mAccount.isSignatureBeforeQuotedText()) { text = appendSignature(text); } - if (mQuotedTextBar.getVisibility() == View.VISIBLE) - { - if (replyAfterQuote) - { + if (mQuotedTextBar.getVisibility() == View.VISIBLE) { + if (replyAfterQuote) { composedMessageOffset = mQuotedText.getText().toString().length() + "\n".length(); text = mQuotedText.getText().toString() + "\n" + text; - } - else - { + } else { text += "\n\n" + mQuotedText.getText().toString(); } } // Note: If user has selected reply after quote AND signature before quote, ignore the // latter setting and append the signature at the end. - if (!isDraft && (!mAccount.isSignatureBeforeQuotedText() || replyAfterQuote)) - { + if (!isDraft && (!mAccount.isSignatureBeforeQuotedText() || replyAfterQuote)) { text = appendSignature(text); } @@ -1051,9 +932,7 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc body.setComposedMessageOffset(composedMessageOffset); return body; - } - else - { + } else { // Shouldn't happen. return new TextBody(""); } @@ -1067,8 +946,7 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc * @return Message to be sent. * @throws MessagingException */ - private MimeMessage createMessage(boolean isDraft) throws MessagingException - { + private MimeMessage createMessage(boolean isDraft) throws MessagingException { MimeMessage message = new MimeMessage(); message.addSentDate(new Date()); Address from = new Address(mIdentity.getEmail(), mIdentity.getName()); @@ -1080,38 +958,31 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc message.setHeader("User-Agent", getString(R.string.message_header_mua)); final String replyTo = mIdentity.getReplyTo(); - if (replyTo != null) - { + if (replyTo != null) { message.setReplyTo(new Address[] { new Address(replyTo) }); } - if (mInReplyTo != null) - { + if (mInReplyTo != null) { message.setInReplyTo(mInReplyTo); } - if (mReferences != null) - { + if (mReferences != null) { message.setReferences(mReferences); } // Build the body. // TODO FIXME - body can be either an HTML or Text part, depending on whether we're in HTML mode or not. Should probably fix this so we don't mix up html and text parts. TextBody body = null; - if (mPgpData.getEncryptedData() != null) - { + if (mPgpData.getEncryptedData() != null) { String text = mPgpData.getEncryptedData(); body = new TextBody(text); - } - else - { + } else { body = buildText(isDraft); } final boolean hasAttachments = mAttachments.getChildCount() > 0; - if (mMessageFormat == MessageFormat.HTML) - { + if (mMessageFormat == MessageFormat.HTML) { // HTML message (with alternative text part) // This is the compiled MIME part for an HTML message. @@ -1120,8 +991,7 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc composedMimeMessage.addBodyPart(new MimeBodyPart(body, "text/html")); composedMimeMessage.addBodyPart(new MimeBodyPart(new TextBody(HtmlConverter.htmlToText(body.getText())), "text/plain")); - if (hasAttachments) - { + if (hasAttachments) { // If we're HTML and have attachments, we have a MimeMultipart container to hold the // whole message (mp here), of which one part is a MimeMultipart container // (composedMimeMessage) with the user's composed messages, and subsequent parts for @@ -1130,33 +1000,25 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc mp.addBodyPart(new MimeBodyPart(composedMimeMessage)); addAttachmentsToMessage(mp); message.setBody(mp); - } - else - { + } else { // If no attachments, our multipart/alternative part is the only one we need. message.setBody(composedMimeMessage); } - } - else - { + } else { // Text-only message. - if (hasAttachments) - { + if (hasAttachments) { MimeMultipart mp = new MimeMultipart(); mp.addBodyPart(new MimeBodyPart(body, "text/plain")); addAttachmentsToMessage(mp); message.setBody(mp); - } - else - { + } else { // No attachments to include, just stick the text body in the message and call it good. message.setBody(body); } } // If this is a draft, add metadata for thawing. - if (isDraft) - { + if (isDraft) { // Add the identity to the message. message.addHeader(K9.IDENTITY_HEADER, buildIdentityHeader(body)); } @@ -1169,10 +1031,8 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc * @param mp MimeMultipart container in which to insert parts. * @throws MessagingException */ - private void addAttachmentsToMessage(final MimeMultipart mp) throws MessagingException - { - for (int i = 0, count = mAttachments.getChildCount(); i < count; i++) - { + private void addAttachmentsToMessage(final MimeMultipart mp) throws MessagingException { + for (int i = 0, count = mAttachments.getChildCount(); i < count; i++) { Attachment attachment = (Attachment) mAttachments.getChildAt(i).getTag(); MimeBodyPart bp = new MimeBodyPart( @@ -1215,8 +1075,7 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc // FYI, there's nothing in the code that requires these variables to one letter. They're one // letter simply to save space. This name sucks. It's too similar to Account.Identity. - private enum IdentityField - { + private enum IdentityField { LENGTH("l"), OFFSET("o"), MESSAGE_FORMAT("f"), @@ -1228,13 +1087,11 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc private final String value; - IdentityField(String value) - { + IdentityField(String value) { this.value = value; } - public String value() - { + public String value() { return value; } @@ -1243,8 +1100,7 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc * checked for integer-ness during decoding. * @return */ - public static IdentityField[] getIntegerFields() - { + public static IdentityField[] getIntegerFields() { return new IdentityField[] { LENGTH, OFFSET }; } } @@ -1262,17 +1118,13 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc * @param body {@link TextBody} to analyze for body length and offset. * @return Identity string. */ - private String buildIdentityHeader(final TextBody body) - { + private String buildIdentityHeader(final TextBody body) { Uri.Builder uri = new Uri.Builder(); - if(body.getComposedMessageLength() != null && body.getComposedMessageOffset() != null) - { + if (body.getComposedMessageLength() != null && body.getComposedMessageOffset() != null) { // See if the message body length is already in the TextBody. uri.appendQueryParameter(IdentityField.LENGTH.value(), body.getComposedMessageLength().toString()); uri.appendQueryParameter(IdentityField.OFFSET.value(), body.getComposedMessageOffset().toString()); - } - else - { + } else { // If not, calculate it now. uri.appendQueryParameter(IdentityField.LENGTH.value(), Integer.toString(body.getText().length())); uri.appendQueryParameter(IdentityField.OFFSET.value(), Integer.toString(0)); @@ -1281,26 +1133,22 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc uri.appendQueryParameter(IdentityField.MESSAGE_FORMAT.value(), mMessageFormat.name()); // If we're not using the standard identity of signature, append it on to the identity blob. - if (mSignatureChanged) - { + if (mSignatureChanged) { uri.appendQueryParameter(IdentityField.SIGNATURE.value(), mSignatureView.getText().toString()); } - if (mIdentityChanged) - { + if (mIdentityChanged) { uri.appendQueryParameter(IdentityField.NAME.value(), mIdentity.getName()); uri.appendQueryParameter(IdentityField.EMAIL.value(), mIdentity.getEmail()); } - if (mMessageReference != null) - { + if (mMessageReference != null) { uri.appendQueryParameter(IdentityField.ORIGINAL_MESSAGE.value(), mMessageReference.toIdentityString()); } String k9identity = IDENTITY_VERSION_1 + uri.build().getEncodedQuery(); - if (K9.DEBUG) - { + if (K9.DEBUG) { Log.d(K9.LOG_TAG, "Generated identity: " + k9identity); } @@ -1312,29 +1160,24 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc * @param identityString * @return */ - private Map parseIdentityHeader(final String identityString) - { + private Map parseIdentityHeader(final String identityString) { Map identity = new HashMap(); if (K9.DEBUG) Log.d(K9.LOG_TAG, "Decoding identity: " + identityString); - if (identityString == null || identityString.length() < 1) - { + if (identityString == null || identityString.length() < 1) { return identity; } // Check to see if this is a "next gen" identity. - if (identityString.charAt(0) == IDENTITY_VERSION_1.charAt(0) && identityString.length() > 2) - { + if (identityString.charAt(0) == IDENTITY_VERSION_1.charAt(0) && identityString.length() > 2) { Uri.Builder builder = new Uri.Builder(); builder.encodedQuery(identityString.substring(1)); // Need to cut off the ! at the beginning. Uri uri = builder.build(); - for (IdentityField key : IdentityField.values()) - { + for (IdentityField key : IdentityField.values()) { String value = uri.getQueryParameter(key.value()); - if (value != null) - { + if (value != null) { identity.put(key, value); } } @@ -1343,23 +1186,16 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc Log.d(K9.LOG_TAG, "Decoded identity: " + identity.toString()); // Sanity check our Integers so that recipients of this result don't have to. - for (IdentityField key : IdentityField.getIntegerFields()) - { - if (identity.get(key) != null) - { - try - { + for (IdentityField key : IdentityField.getIntegerFields()) { + if (identity.get(key) != null) { + try { Integer.parseInt(identity.get(key)); - } - catch (NumberFormatException e) - { + } catch (NumberFormatException e) { Log.e(K9.LOG_TAG, "Invalid " + key.name() + " field in identity: " + identity.get(key)); } } } - } - else - { + } else { // Legacy identity if (K9.DEBUG) @@ -1367,28 +1203,21 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc StringTokenizer tokens = new StringTokenizer(identityString, ":", false); // First item is the body length. We use this to separate the composed reply from the quoted text. - if (tokens.hasMoreTokens()) - { + if (tokens.hasMoreTokens()) { String bodyLengthS = Utility.base64Decode(tokens.nextToken()); - try - { + try { identity.put(IdentityField.LENGTH, Integer.valueOf(bodyLengthS).toString()); - } - catch (Exception e) - { + } catch (Exception e) { Log.e(K9.LOG_TAG, "Unable to parse bodyLength '" + bodyLengthS + "'"); } } - if (tokens.hasMoreTokens()) - { + if (tokens.hasMoreTokens()) { identity.put(IdentityField.SIGNATURE, Utility.base64Decode(tokens.nextToken())); } - if (tokens.hasMoreTokens()) - { + if (tokens.hasMoreTokens()) { identity.put(IdentityField.NAME, Utility.base64Decode(tokens.nextToken())); } - if (tokens.hasMoreTokens()) - { + if (tokens.hasMoreTokens()) { identity.put(IdentityField.EMAIL, Utility.base64Decode(tokens.nextToken())); } } @@ -1397,14 +1226,11 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc } - private String appendSignature(String text) - { - if (mIdentity.getSignatureUse()) - { + private String appendSignature(String text) { + if (mIdentity.getSignatureUse()) { String signature = mSignatureView.getText().toString(); - if (signature != null && !signature.contentEquals("")) - { + if (signature != null && !signature.contentEquals("")) { text += "\n" + signature; } } @@ -1413,19 +1239,15 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc } - private void sendMessage() - { + private void sendMessage() { new SendMessageTask().execute(); } - private void saveMessage() - { + private void saveMessage() { new SaveMessageTask().execute(); } - private void saveIfNeeded() - { - if (!mDraftNeedsSaving || mPreventDraftSaving || mPgpData.hasEncryptionKeys()) - { + private void saveIfNeeded() { + if (!mDraftNeedsSaving || mPreventDraftSaving || mPgpData.hasEncryptionKeys()) { return; } @@ -1433,78 +1255,59 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc saveMessage(); } - public void onEncryptionKeySelectionDone() - { - if (mPgpData.hasEncryptionKeys()) - { + public void onEncryptionKeySelectionDone() { + if (mPgpData.hasEncryptionKeys()) { onSend(); - } - else - { + } else { Toast.makeText(this, R.string.send_aborted, Toast.LENGTH_SHORT).show(); } } - public void onEncryptDone() - { - if (mPgpData.getEncryptedData() != null) - { + public void onEncryptDone() { + if (mPgpData.getEncryptedData() != null) { onSend(); - } - else - { + } else { Toast.makeText(this, R.string.send_aborted, Toast.LENGTH_SHORT).show(); } } - private void onSend() - { - if (getAddresses(mToView).length == 0 && getAddresses(mCcView).length == 0 && getAddresses(mBccView).length == 0) - { + private void onSend() { + if (getAddresses(mToView).length == 0 && getAddresses(mCcView).length == 0 && getAddresses(mBccView).length == 0) { mToView.setError(getString(R.string.message_compose_error_no_recipients)); Toast.makeText(this, getString(R.string.message_compose_error_no_recipients), Toast.LENGTH_LONG).show(); return; } - if (mEncryptCheckbox.isChecked() && !mPgpData.hasEncryptionKeys()) - { + if (mEncryptCheckbox.isChecked() && !mPgpData.hasEncryptionKeys()) { // key selection before encryption String emails = ""; Address[][] addresses = new Address[][] { getAddresses(mToView), getAddresses(mCcView), getAddresses(mBccView) }; - for (Address[] addressArray : addresses) - { - for (Address address : addressArray) - { - if (emails.length() != 0) - { + for (Address[] addressArray : addresses) { + for (Address address : addressArray) { + if (emails.length() != 0) { emails += ","; } emails += address.getAddress(); } } - if (emails.length() != 0) - { + if (emails.length() != 0) { emails += ","; } emails += mIdentity.getEmail(); mPreventDraftSaving = true; - if (!mAccount.getCryptoProvider().selectEncryptionKeys(MessageCompose.this, emails, mPgpData)) - { + if (!mAccount.getCryptoProvider().selectEncryptionKeys(MessageCompose.this, emails, mPgpData)) { mPreventDraftSaving = false; } return; } - if (mPgpData.hasEncryptionKeys() || mPgpData.hasSignatureKey()) - { - if (mPgpData.getEncryptedData() == null) - { + if (mPgpData.hasEncryptionKeys() || mPgpData.hasSignatureKey()) { + if (mPgpData.getEncryptedData() == null) { String text = buildText(false).getText(); mPreventDraftSaving = true; - if (!mAccount.getCryptoProvider().encrypt(this, text, mPgpData)) - { + if (!mAccount.getCryptoProvider().encrypt(this, text, mPgpData)) { mPreventDraftSaving = false; } return; @@ -1512,25 +1315,22 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc } sendMessage(); - if (mMessageReference != null && mMessageReference.flag != null) - { + if (mMessageReference != null && mMessageReference.flag != null) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "Setting referenced message (" + mMessageReference.folderName + ", " + mMessageReference.uid + ") flag to " + mMessageReference.flag); final Account account = Preferences.getPreferences(this).getAccount(mMessageReference.accountUuid); final String folderName = mMessageReference.folderName; final String sourceMessageUid = mMessageReference.uid; - MessagingController.getInstance(getApplication()).setFlag(account, folderName, new String[]{sourceMessageUid}, mMessageReference.flag, true); + MessagingController.getInstance(getApplication()).setFlag(account, folderName, new String[] {sourceMessageUid}, mMessageReference.flag, true); } mDraftNeedsSaving = false; finish(); } - private void onDiscard() - { - if (mDraftUid != null) - { + private void onDiscard() { + if (mDraftUid != null) { MessagingController.getInstance(getApplication()).deleteDraft(mAccount, mDraftUid); mDraftUid = null; } @@ -1539,15 +1339,13 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc finish(); } - private void onSave() - { + private void onSave() { mDraftNeedsSaving = true; saveIfNeeded(); finish(); } - private void onAddCcBcc() - { + private void onAddCcBcc() { mCcView.setVisibility(View.VISIBLE); mBccView.setVisibility(View.VISIBLE); } @@ -1555,18 +1353,13 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc /** * Kick off a picker for whatever kind of MIME types we'll accept and let Android take over. */ - private void onAddAttachment() - { - if (K9.isGalleryBuggy()) - { - if (K9.useGalleryBugWorkaround()) - { + private void onAddAttachment() { + if (K9.isGalleryBuggy()) { + if (K9.useGalleryBugWorkaround()) { Toast.makeText(MessageCompose.this, getString(R.string.message_compose_use_workaround), Toast.LENGTH_LONG).show(); - } - else - { + } else { Toast.makeText(MessageCompose.this, getString(R.string.message_compose_buggy_gallery), Toast.LENGTH_LONG).show(); @@ -1579,10 +1372,8 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc /** * Kick off a picker for the specified MIME type and let Android take over. */ - private void onAddAttachment2(final String mime_type) - { - if (mAccount.getCryptoProvider().isAvailable(this)) - { + private void onAddAttachment2(final String mime_type) { + if (mAccount.getCryptoProvider().isAvailable(this)) { Toast.makeText(this, R.string.attachment_encryption_unsupported, Toast.LENGTH_LONG).show(); } Intent i = new Intent(Intent.ACTION_GET_CONTENT); @@ -1591,13 +1382,11 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc startActivityForResult(Intent.createChooser(i, null), ACTIVITY_REQUEST_PICK_ATTACHMENT); } - private void addAttachment(Uri uri) - { + private void addAttachment(Uri uri) { addAttachment(uri, null); } - private void addAttachment(Uri uri, String contentType) - { + private void addAttachment(Uri uri, String contentType) { long size = -1; String name = null; @@ -1610,52 +1399,38 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc null, null); - if (metadataCursor != null) - { - try - { - if (metadataCursor.moveToFirst()) - { + if (metadataCursor != null) { + try { + if (metadataCursor.moveToFirst()) { name = metadataCursor.getString(0); size = metadataCursor.getInt(1); } - } - finally - { + } finally { metadataCursor.close(); } } - if (name == null) - { + if (name == null) { name = uri.getLastPathSegment(); } - if ((contentType == null) || (contentType.indexOf('*') != -1)) - { + if ((contentType == null) || (contentType.indexOf('*') != -1)) { contentType = contentResolver.getType(uri); } - if (contentType == null) - { + if (contentType == null) { contentType = MimeUtility.getMimeTypeByExtension(name); } - if (size <= 0) - { + if (size <= 0) { String uriString = uri.toString(); - if (uriString.startsWith("file://")) - { + if (uriString.startsWith("file://")) { Log.v(K9.LOG_TAG, uriString.substring("file://".length())); File f = new File(uriString.substring("file://".length())); size = f.length(); - } - else - { + } else { Log.v(K9.LOG_TAG, "Not a file: " + uriString); } - } - else - { + } else { Log.v(K9.LOG_TAG, "old attachment.size: " + size); } Log.v(K9.LOG_TAG, "new attachment.size: " + size); @@ -1677,61 +1452,52 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc } @Override - protected void onActivityResult(int requestCode, int resultCode, Intent data) - { + protected void onActivityResult(int requestCode, int resultCode, Intent data) { // if a CryptoSystem activity is returning, then mPreventDraftSaving was set to true mPreventDraftSaving = false; - if (mAccount.getCryptoProvider().onActivityResult(this, requestCode, resultCode, data, mPgpData)) - { + if (mAccount.getCryptoProvider().onActivityResult(this, requestCode, resultCode, data, mPgpData)) { return; } if (resultCode != RESULT_OK) return; - if (data == null) - { + if (data == null) { return; } - switch (requestCode) - { - case ACTIVITY_REQUEST_PICK_ATTACHMENT: - addAttachment(data.getData()); - mDraftNeedsSaving = true; - break; - case ACTIVITY_CHOOSE_IDENTITY: - onIdentityChosen(data); - break; - case ACTIVITY_CHOOSE_ACCOUNT: - onAccountChosen(data); - break; + switch (requestCode) { + case ACTIVITY_REQUEST_PICK_ATTACHMENT: + addAttachment(data.getData()); + mDraftNeedsSaving = true; + break; + case ACTIVITY_CHOOSE_IDENTITY: + onIdentityChosen(data); + break; + case ACTIVITY_CHOOSE_ACCOUNT: + onAccountChosen(data); + break; } } - private void onAccountChosen(final Intent intent) - { + private void onAccountChosen(final Intent intent) { final Bundle extras = intent.getExtras(); final String uuid = extras.getString(ChooseAccount.EXTRA_ACCOUNT); final Identity identity = (Identity) extras.getSerializable(ChooseAccount.EXTRA_IDENTITY); final Account account = Preferences.getPreferences(this).getAccount(uuid); - if (!mAccount.equals(account)) - { - if (K9.DEBUG) - { + if (!mAccount.equals(account)) { + if (K9.DEBUG) { Log.v(K9.LOG_TAG, "Switching account from " + mAccount + " to " + account); } // on draft edit, make sure we don't keep previous message UID - if (ACTION_EDIT_DRAFT.equals(getIntent().getAction())) - { + if (ACTION_EDIT_DRAFT.equals(getIntent().getAction())) { mMessageReference = null; } // test whether there is something to save - if (mDraftNeedsSaving || (mDraftUid != null)) - { + if (mDraftNeedsSaving || (mDraftUid != null)) { final String previousDraftUid = mDraftUid; final Account previousAccount = mAccount; @@ -1741,25 +1507,20 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc // actual account switch mAccount = account; - if (K9.DEBUG) - { + if (K9.DEBUG) { Log.v(K9.LOG_TAG, "Account switch, saving new draft in new account"); } saveMessage(); - if (previousDraftUid != null) - { - if (K9.DEBUG) - { + if (previousDraftUid != null) { + if (K9.DEBUG) { Log.v(K9.LOG_TAG, "Account switch, deleting draft from previous account: " + previousDraftUid); } MessagingController.getInstance(getApplication()).deleteDraft(previousAccount, previousDraftUid); } - } - else - { + } else { mAccount = account; } // not sure how to handle mFolder, mSourceMessage? @@ -1768,14 +1529,12 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc switchToIdentity(identity); } - private void onIdentityChosen(Intent intent) - { + private void onIdentityChosen(Intent intent) { Bundle bundle = intent.getExtras(); switchToIdentity((Identity) bundle.getSerializable(ChooseIdentity.EXTRA_IDENTITY)); } - private void switchToIdentity(Identity identity) - { + private void switchToIdentity(Identity identity) { mIdentity = identity; mIdentityChanged = true; mDraftNeedsSaving = true; @@ -1783,137 +1542,117 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc updateSignature(); } - private void updateFrom() - { - if (mIdentityChanged) - { + private void updateFrom() { + if (mIdentityChanged) { mFromView.setVisibility(View.VISIBLE); } mFromView.setText(getString(R.string.message_view_from_format, mIdentity.getName(), mIdentity.getEmail())); } - private void updateSignature() - { - if (mIdentity.getSignatureUse()) - { + private void updateSignature() { + if (mIdentity.getSignatureUse()) { mSignatureView.setText(mIdentity.getSignature()); mSignatureView.setVisibility(View.VISIBLE); - } - else - { + } else { mSignatureView.setVisibility(View.GONE); } } - public void onClick(View view) - { - switch (view.getId()) - { - case R.id.attachment_delete: - /* - * The view is the delete button, and we have previously set the tag of - * the delete button to the view that owns it. We don't use parent because the - * view is very complex and could change in the future. - */ - mAttachments.removeView((View) view.getTag()); - mDraftNeedsSaving = true; - break; - case R.id.quoted_text_delete: - deleteQuotedText(); - mDraftNeedsSaving = true; - break; - case R.id.quoted_text_edit: - mMessageFormat = MessageFormat.TEXT; - if (mMessageReference != null) // shouldn't happen... - { - // TODO - Should we check if mSourceMessageBody is already present and bypass the MessagingController call? - MessagingController.getInstance(getApplication()).addListener(mListener); - final Account account = Preferences.getPreferences(this).getAccount(mMessageReference.accountUuid); - final String folderName = mMessageReference.folderName; - final String sourceMessageUid = mMessageReference.uid; - MessagingController.getInstance(getApplication()).loadMessageForView(account, folderName, sourceMessageUid, null); - } - break; + public void onClick(View view) { + switch (view.getId()) { + case R.id.attachment_delete: + /* + * The view is the delete button, and we have previously set the tag of + * the delete button to the view that owns it. We don't use parent because the + * view is very complex and could change in the future. + */ + mAttachments.removeView((View) view.getTag()); + mDraftNeedsSaving = true; + break; + case R.id.quoted_text_delete: + deleteQuotedText(); + mDraftNeedsSaving = true; + break; + case R.id.quoted_text_edit: + mMessageFormat = MessageFormat.TEXT; + if (mMessageReference != null) { // shouldn't happen... + // TODO - Should we check if mSourceMessageBody is already present and bypass the MessagingController call? + MessagingController.getInstance(getApplication()).addListener(mListener); + final Account account = Preferences.getPreferences(this).getAccount(mMessageReference.accountUuid); + final String folderName = mMessageReference.folderName; + final String sourceMessageUid = mMessageReference.uid; + MessagingController.getInstance(getApplication()).loadMessageForView(account, folderName, sourceMessageUid, null); + } + break; } } /** * Delete the quoted text. */ - private void deleteQuotedText() - { + private void deleteQuotedText() { mQuotedTextBar.setVisibility(View.GONE); mQuotedText.setVisibility(View.GONE); mQuotedHTML.setVisibility(View.GONE); - if (mQuotedHtmlContent != null) - { + if (mQuotedHtmlContent != null) { mQuotedHtmlContent.clearQuotedContent(); } } @Override - public boolean onOptionsItemSelected(MenuItem item) - { - switch (item.getItemId()) - { - case R.id.send: - mPgpData.setEncryptionKeys(null); - onSend(); - break; - case R.id.save: - onSave(); - break; - case R.id.discard: - onDiscard(); - break; - case R.id.add_cc_bcc: - onAddCcBcc(); - break; - case R.id.add_attachment: - onAddAttachment(); - break; - case R.id.add_attachment_image: - onAddAttachment2("image/*"); - break; - case R.id.add_attachment_video: - onAddAttachment2("video/*"); - break; - case R.id.choose_identity: - onChooseIdentity(); - break; - default: - return super.onOptionsItemSelected(item); + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + case R.id.send: + mPgpData.setEncryptionKeys(null); + onSend(); + break; + case R.id.save: + onSave(); + break; + case R.id.discard: + onDiscard(); + break; + case R.id.add_cc_bcc: + onAddCcBcc(); + break; + case R.id.add_attachment: + onAddAttachment(); + break; + case R.id.add_attachment_image: + onAddAttachment2("image/*"); + break; + case R.id.add_attachment_video: + onAddAttachment2("video/*"); + break; + case R.id.choose_identity: + onChooseIdentity(); + break; + default: + return super.onOptionsItemSelected(item); } return true; } - private void onChooseIdentity() - { + private void onChooseIdentity() { // keep things simple: trigger account choice only if there are more // than 1 account - if (Preferences.getPreferences(this).getAvailableAccounts().size() > 1) - { + if (Preferences.getPreferences(this).getAvailableAccounts().size() > 1) { final Intent intent = new Intent(this, ChooseAccount.class); intent.putExtra(ChooseAccount.EXTRA_ACCOUNT, mAccount.getUuid()); intent.putExtra(ChooseAccount.EXTRA_IDENTITY, mIdentity); startActivityForResult(intent, ACTIVITY_CHOOSE_ACCOUNT); - } - else if (mAccount.getIdentities().size() > 1) - { + } else if (mAccount.getIdentities().size() > 1) { Intent intent = new Intent(this, ChooseIdentity.class); intent.putExtra(ChooseIdentity.EXTRA_ACCOUNT, mAccount.getUuid()); startActivityForResult(intent, ACTIVITY_CHOOSE_IDENTITY); - } - else - { + } else { Toast.makeText(this, getString(R.string.no_identities), Toast.LENGTH_LONG).show(); } } @Override - public boolean onCreateOptionsMenu(Menu menu) - { + public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.message_compose_option, menu); @@ -1922,13 +1661,11 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc * if the work-around for the Gallery bug is enabled (see Issue 1186). */ int found = 0; - for (int i = menu.size() - 1; i >= 0; i--) - { + for (int i = menu.size() - 1; i >= 0; i--) { MenuItem item = menu.getItem(i); int id = item.getItemId(); if ((id == R.id.add_attachment_image) || - (id == R.id.add_attachment_video)) - { + (id == R.id.add_attachment_video)) { item.setVisible(K9.useGalleryBugWorkaround()); found++; } @@ -1941,62 +1678,50 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc } @Override - public void onBackPressed() - { + public void onBackPressed() { // This will be called either automatically for you on 2.0 // or later, or by the code above on earlier versions of the // platform. - if (mDraftNeedsSaving) - { + if (mDraftNeedsSaving) { showDialog(DIALOG_SAVE_OR_DISCARD_DRAFT_MESSAGE); - } - else - { + } else { finish(); } } @Override - public Dialog onCreateDialog(int id) - { - switch (id) - { - case DIALOG_SAVE_OR_DISCARD_DRAFT_MESSAGE: - return new AlertDialog.Builder(this) - .setTitle(R.string.save_or_discard_draft_message_dlg_title) - .setMessage(R.string.save_or_discard_draft_message_instructions_fmt) - .setPositiveButton(R.string.save_draft_action, new DialogInterface.OnClickListener() - { - public void onClick(DialogInterface dialog, int whichButton) - { - dismissDialog(DIALOG_SAVE_OR_DISCARD_DRAFT_MESSAGE); - onSave(); - } - }) - .setNegativeButton(R.string.discard_action, new DialogInterface.OnClickListener() - { - public void onClick(DialogInterface dialog, int whichButton) - { - dismissDialog(DIALOG_SAVE_OR_DISCARD_DRAFT_MESSAGE); - onDiscard(); - } - }) - .create(); + public Dialog onCreateDialog(int id) { + switch (id) { + case DIALOG_SAVE_OR_DISCARD_DRAFT_MESSAGE: + return new AlertDialog.Builder(this) + .setTitle(R.string.save_or_discard_draft_message_dlg_title) + .setMessage(R.string.save_or_discard_draft_message_instructions_fmt) + .setPositiveButton(R.string.save_draft_action, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int whichButton) { + dismissDialog(DIALOG_SAVE_OR_DISCARD_DRAFT_MESSAGE); + onSave(); + } + }) + .setNegativeButton(R.string.discard_action, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int whichButton) { + dismissDialog(DIALOG_SAVE_OR_DISCARD_DRAFT_MESSAGE); + onDiscard(); + } + }) + .create(); } return super.onCreateDialog(id); } @Override - public boolean onKeyDown(int keyCode, KeyEvent event) - { + public boolean onKeyDown(int keyCode, KeyEvent event) { if ( // TODO - when we move to android 2.0, uncomment this. // android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.ECLAIR && keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0 - && K9.manageBack()) - { + && K9.manageBack()) { // Take care of calling this method on earlier versions of // the platform where it doesn't exist. onBackPressed(); @@ -2009,41 +1734,29 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc /** * Returns true if all attachments were able to be attached, otherwise returns false. */ - private boolean loadAttachments(Part part, int depth) throws MessagingException - { - if (part.getBody() instanceof Multipart) - { + private boolean loadAttachments(Part part, int depth) throws MessagingException { + if (part.getBody() instanceof Multipart) { Multipart mp = (Multipart) part.getBody(); boolean ret = true; - for (int i = 0, count = mp.getCount(); i < count; i++) - { - if (!loadAttachments(mp.getBodyPart(i), depth + 1)) - { + for (int i = 0, count = mp.getCount(); i < count; i++) { + if (!loadAttachments(mp.getBodyPart(i), depth + 1)) { ret = false; } } return ret; - } - else - { + } else { String contentType = MimeUtility.unfoldAndDecode(part.getContentType()); String name = MimeUtility.getHeaderParameter(contentType, "name"); - if (name != null) - { + if (name != null) { Body body = part.getBody(); - if (body != null && body instanceof LocalAttachmentBody) - { + if (body != null && body instanceof LocalAttachmentBody) { final Uri uri = ((LocalAttachmentBody) body).getContentUri(); - mHandler.post(new Runnable() - { - public void run() - { + mHandler.post(new Runnable() { + public void run() { addAttachment(uri); } }); - } - else - { + } else { return false; } } @@ -2056,28 +1769,19 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc * depending on the type of message being composed. * @param message Source message */ - private void processSourceMessage(Message message) - { + private void processSourceMessage(Message message) { String action = getIntent().getAction(); - try - { - if (ACTION_REPLY.equals(action) || ACTION_REPLY_ALL.equals(action)) - { - if (message.getSubject() != null) - { + try { + if (ACTION_REPLY.equals(action) || ACTION_REPLY_ALL.equals(action)) { + if (message.getSubject() != null) { final String subject = prefix.matcher(message.getSubject()).replaceFirst(""); - if (!subject.toLowerCase().startsWith("re:")) - { + if (!subject.toLowerCase().startsWith("re:")) { mSubjectView.setText("Re: " + subject); - } - else - { + } else { mSubjectView.setText(subject); } - } - else - { + } else { mSubjectView.setText(""); } @@ -2086,19 +1790,15 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc * or sender address. */ Address[] replyToAddresses; - if (message.getReplyTo().length > 0) - { + if (message.getReplyTo().length > 0) { replyToAddresses = message.getReplyTo(); - } - else - { + } else { replyToAddresses = message.getFrom(); } // if we're replying to a message we sent, we probably meant // to reply to the recipient of that message - if (mAccount.isAnIdentity(replyToAddresses)) - { + if (mAccount.isAnIdentity(replyToAddresses)) { replyToAddresses = message.getRecipients(RecipientType.TO); } @@ -2106,26 +1806,20 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc - if (message.getMessageId() != null && message.getMessageId().length() > 0) - { + if (message.getMessageId() != null && message.getMessageId().length() > 0) { mInReplyTo = message.getMessageId(); - if (message.getReferences() != null && message.getReferences().length > 0) - { + if (message.getReferences() != null && message.getReferences().length > 0) { StringBuffer buffy = new StringBuffer(); - for (int i=0; i < message.getReferences().length; i++) + for (int i = 0; i < message.getReferences().length; i++) buffy.append(message.getReferences()[i]); mReferences = buffy.toString() + " " + mInReplyTo; - } - else - { + } else { mReferences = mInReplyTo; } - } - else - { + } else { if (K9.DEBUG) Log.d(K9.LOG_TAG, "could not get Message-ID."); } @@ -2133,59 +1827,44 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc // Quote the message and setup the UI. populateUIWithQuotedMessage(); - if (ACTION_REPLY_ALL.equals(action) || ACTION_REPLY.equals(action)) - { + if (ACTION_REPLY_ALL.equals(action) || ACTION_REPLY.equals(action)) { Identity useIdentity = null; - for (Address address : message.getRecipients(RecipientType.TO)) - { + for (Address address : message.getRecipients(RecipientType.TO)) { Identity identity = mAccount.findIdentity(address); - if (identity != null) - { + if (identity != null) { useIdentity = identity; break; } } - if (useIdentity == null) - { - if (message.getRecipients(RecipientType.CC).length > 0) - { - for (Address address : message.getRecipients(RecipientType.CC)) - { + if (useIdentity == null) { + if (message.getRecipients(RecipientType.CC).length > 0) { + for (Address address : message.getRecipients(RecipientType.CC)) { Identity identity = mAccount.findIdentity(address); - if (identity != null) - { + if (identity != null) { useIdentity = identity; break; } } } } - if (useIdentity != null) - { + if (useIdentity != null) { Identity defaultIdentity = mAccount.getIdentity(0); - if (useIdentity != defaultIdentity) - { + if (useIdentity != defaultIdentity) { switchToIdentity(useIdentity); } } } - if (ACTION_REPLY_ALL.equals(action)) - { - for (Address address : message.getRecipients(RecipientType.TO)) - { - if (!mAccount.isAnIdentity(address)) - { + if (ACTION_REPLY_ALL.equals(action)) { + for (Address address : message.getRecipients(RecipientType.TO)) { + if (!mAccount.isAnIdentity(address)) { addAddress(mToView, address); } } - if (message.getRecipients(RecipientType.CC).length > 0) - { - for (Address address : message.getRecipients(RecipientType.CC)) - { - if (!mAccount.isAnIdentity(address) && !Utility.arrayContains(replyToAddresses, address)) - { + if (message.getRecipients(RecipientType.CC).length > 0) { + for (Address address : message.getRecipients(RecipientType.CC)) { + if (!mAccount.isAnIdentity(address) && !Utility.arrayContains(replyToAddresses, address)) { addAddress(mCcView, address); } @@ -2193,124 +1872,94 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc mCcView.setVisibility(View.VISIBLE); } } - } - else if (ACTION_FORWARD.equals(action)) - { - if (message.getSubject() != null && !message.getSubject().toLowerCase().startsWith("fwd:")) - { + } else if (ACTION_FORWARD.equals(action)) { + if (message.getSubject() != null && !message.getSubject().toLowerCase().startsWith("fwd:")) { mSubjectView.setText("Fwd: " + message.getSubject()); - } - else - { + } else { mSubjectView.setText(message.getSubject()); } // Quote the message and setup the UI. populateUIWithQuotedMessage(); - if (!mSourceMessageProcessed) - { - if (!loadAttachments(message, 0)) - { + if (!mSourceMessageProcessed) { + if (!loadAttachments(message, 0)) { mHandler.sendEmptyMessage(MSG_SKIPPED_ATTACHMENTS); } } - } - else if (ACTION_EDIT_DRAFT.equals(action)) - { + } else if (ACTION_EDIT_DRAFT.equals(action)) { mDraftUid = message.getUid(); mSubjectView.setText(message.getSubject()); addAddresses(mToView, message.getRecipients(RecipientType.TO)); - if (message.getRecipients(RecipientType.CC).length > 0) - { + if (message.getRecipients(RecipientType.CC).length > 0) { addAddresses(mCcView, message.getRecipients(RecipientType.CC)); mCcView.setVisibility(View.VISIBLE); } Address[] bccRecipients = message.getRecipients(RecipientType.BCC); - if (bccRecipients.length > 0) - { + if (bccRecipients.length > 0) { addAddresses(mBccView, bccRecipients); String bccAddress = mAccount.getAlwaysBcc(); - if (bccRecipients.length == 1 && bccAddress != null && bccAddress.equals(bccRecipients[0].toString())) - { + if (bccRecipients.length == 1 && bccAddress != null && bccAddress.equals(bccRecipients[0].toString())) { // If the auto-bcc is the only entry in the BCC list, don't show the Bcc fields. mBccView.setVisibility(View.GONE); - } - else - { + } else { mBccView.setVisibility(View.VISIBLE); } } // Read In-Reply-To header from draft final String[] inReplyTo = message.getHeader("In-Reply-To"); - if ((inReplyTo != null) && (inReplyTo.length >= 1)) - { + if ((inReplyTo != null) && (inReplyTo.length >= 1)) { mInReplyTo = inReplyTo[0]; } // Read References header from draft final String[] references = message.getHeader("References"); - if ((references != null) && (references.length >= 1)) - { + if ((references != null) && (references.length >= 1)) { mReferences = references[0]; } - if (!mSourceMessageProcessed) - { + if (!mSourceMessageProcessed) { loadAttachments(message, 0); } // Decode the identity header when loading a draft. // See buildIdentityHeader(TextBody) for a detailed description of the composition of this blob. Map k9identity = new HashMap(); - if (message.getHeader(K9.IDENTITY_HEADER) != null && message.getHeader(K9.IDENTITY_HEADER).length > 0 && message.getHeader(K9.IDENTITY_HEADER)[0] != null) - { + if (message.getHeader(K9.IDENTITY_HEADER) != null && message.getHeader(K9.IDENTITY_HEADER).length > 0 && message.getHeader(K9.IDENTITY_HEADER)[0] != null) { k9identity = parseIdentityHeader(message.getHeader(K9.IDENTITY_HEADER)[0]); } Identity newIdentity = new Identity(); - if (k9identity.containsKey(IdentityField.SIGNATURE)) - { + if (k9identity.containsKey(IdentityField.SIGNATURE)) { newIdentity.setSignatureUse(true); newIdentity.setSignature(k9identity.get(IdentityField.SIGNATURE)); mSignatureChanged = true; - } - else - { + } else { newIdentity.setSignatureUse(message.getFolder().getAccount().getSignatureUse()); newIdentity.setSignature(mIdentity.getSignature()); } - if (k9identity.containsKey(IdentityField.NAME)) - { + if (k9identity.containsKey(IdentityField.NAME)) { newIdentity.setName(k9identity.get(IdentityField.NAME)); mIdentityChanged = true; - } - else - { + } else { newIdentity.setName(mIdentity.getName()); } - if (k9identity.containsKey(IdentityField.EMAIL)) - { + if (k9identity.containsKey(IdentityField.EMAIL)) { newIdentity.setEmail(k9identity.get(IdentityField.EMAIL)); mIdentityChanged = true; - } - else - { + } else { newIdentity.setEmail(mIdentity.getEmail()); } - if (k9identity.containsKey(IdentityField.ORIGINAL_MESSAGE)) - { + if (k9identity.containsKey(IdentityField.ORIGINAL_MESSAGE)) { mMessageReference = null; - try - { + try { mMessageReference = new MessageReference(k9identity.get(IdentityField.ORIGINAL_MESSAGE)); - } catch (MessagingException e) - { + } catch (MessagingException e) { Log.e(K9.LOG_TAG, "Could not decode message reference in identity.", e); } } @@ -2329,25 +1978,19 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc // Always respect the user's current composition format preference, even if the // draft was saved in a different format. // TODO - The current implementation doesn't allow a user in HTML mode to edit a draft that wasn't saved with K9mail. - if (mMessageFormat == MessageFormat.HTML) - { - if (k9identity.get(IdentityField.MESSAGE_FORMAT) == null || !MessageFormat.valueOf(k9identity.get(IdentityField.MESSAGE_FORMAT)).equals(MessageFormat.HTML)) - { + if (mMessageFormat == MessageFormat.HTML) { + if (k9identity.get(IdentityField.MESSAGE_FORMAT) == null || !MessageFormat.valueOf(k9identity.get(IdentityField.MESSAGE_FORMAT)).equals(MessageFormat.HTML)) { // This message probably wasn't created by us. The exception is legacy // drafts created before the advent of HTML composition. In those cases, // we'll display the whole message (including the quoted part) in the // composition window. If that's the case, try and convert it to text to // match the behavior in text mode. mMessageContentView.setText(getBodyTextFromMessage(message, MessageFormat.TEXT)); - } - else - { + } else { Part part = MimeUtility.findFirstPartByMimeType(message, "text/html"); - if (part != null) // Shouldn't happen if we were the one who saved it. - { + if (part != null) { // Shouldn't happen if we were the one who saved it. String text = MimeUtility.getTextFromPart(part); - if (K9.DEBUG) - { + if (K9.DEBUG) { Log.d(K9.LOG_TAG, "Loading message with offset " + bodyOffset + ", length " + bodyLength + ". Text length is " + text.length() + "."); } @@ -2359,8 +2002,7 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc StringBuilder quotedHTML = new StringBuilder(); quotedHTML.append(text.substring(0, bodyOffset)); // stuff before the reply quotedHTML.append(text.substring(bodyOffset + bodyLength)); - if (quotedHTML.length() > 0) - { + if (quotedHTML.length() > 0) { mQuotedHtmlContent = new InsertableHtmlContent(); mQuotedHtmlContent.setQuotedContent(quotedHTML); mQuotedHtmlContent.setHeaderInsertionPoint(bodyOffset); @@ -2371,25 +2013,18 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc } } } - } - else if (mMessageFormat == MessageFormat.TEXT) - { + } else if (mMessageFormat == MessageFormat.TEXT) { MessageFormat format = k9identity.get(IdentityField.MESSAGE_FORMAT) != null ? MessageFormat.valueOf(k9identity.get(IdentityField.MESSAGE_FORMAT)) : null; - if (format == null) - { + if (format == null) { mMessageContentView.setText(getBodyTextFromMessage(message, MessageFormat.TEXT)); - } - else if (format.equals(MessageFormat.HTML)) - { + } else if (format.equals(MessageFormat.HTML)) { // We are in text mode, but have an HTML message. Part htmlPart = MimeUtility.findFirstPartByMimeType(message, "text/html"); - if (htmlPart != null) // Shouldn't happen if we were the one who saved it. - { + if (htmlPart != null) { // Shouldn't happen if we were the one who saved it. String text = MimeUtility.getTextFromPart(htmlPart); - if (K9.DEBUG) - { + if (K9.DEBUG) { Log.d(K9.LOG_TAG, "Loading message with offset " + bodyOffset + ", length " + bodyLength + ". Text length is " + text.length() + "."); } @@ -2406,22 +2041,16 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc mQuotedTextBar.setVisibility(View.VISIBLE); mQuotedText.setVisibility(View.VISIBLE); - } - else - { + } else { Log.e(K9.LOG_TAG, "Found an HTML draft but couldn't find the HTML part! Something's wrong."); } - } - else if (format.equals(MessageFormat.TEXT)) - { + } else if (format.equals(MessageFormat.TEXT)) { Part textPart = MimeUtility.findFirstPartByMimeType(message, "text/plain"); - if (textPart != null) - { + if (textPart != null) { String text = MimeUtility.getTextFromPart(textPart); // If we had a body length (and it was valid), separate the composition from the quoted text // and put them in their respective places in the UI. - if (bodyLength != null && bodyLength + 1 < text.length()) // + 1 to get rid of the newline we added when saving the draft - { + if (bodyLength != null && bodyLength + 1 < text.length()) { // + 1 to get rid of the newline we added when saving the draft String bodyText = text.substring(0, bodyLength); String quotedText = text.substring(bodyLength + 1, text.length()); @@ -2431,22 +2060,16 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc mQuotedTextBar.setVisibility(View.VISIBLE); mQuotedText.setVisibility(View.VISIBLE); mQuotedHTML.setVisibility(View.VISIBLE); - } - else - { + } else { mMessageContentView.setText(text); } } - } - else - { + } else { Log.e(K9.LOG_TAG, "Unhandled message format."); } } } - } - catch (MessagingException me) - { + } catch (MessagingException me) { /** * Let the user continue composing their message even if we have a problem processing * the source message. Log it as an error, though. @@ -2461,8 +2084,7 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc * Build and populate the UI with the quoted message. * @throws MessagingException */ - private void populateUIWithQuotedMessage() throws MessagingException - { + private void populateUIWithQuotedMessage() throws MessagingException { // TODO -- I am assuming that mSourceMessageBody will always be a text part. Is this a safe assumption? // Handle the original message in the reply @@ -2470,8 +2092,7 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc String content = mSourceMessageBody != null ? mSourceMessageBody : getBodyTextFromMessage(mSourceMessage, mMessageFormat); - if (mMessageFormat == MessageFormat.HTML) - { + if (mMessageFormat == MessageFormat.HTML) { // Add the HTML reply header to the top of the content. mQuotedHtmlContent = quoteOriginalHtmlMessage(mSourceMessage, content, mAccount.getQuoteStyle()); // Load the message with the reply header. @@ -2482,9 +2103,7 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc mQuotedTextEdit.setVisibility(View.VISIBLE); mQuotedText.setVisibility(View.GONE); - } - else if (mMessageFormat == MessageFormat.TEXT) - { + } else if (mMessageFormat == MessageFormat.TEXT) { mQuotedText.setText(quoteOriginalTextMessage(mSourceMessage, content, mAccount.getQuoteStyle())); mQuotedTextBar.setVisibility(View.VISIBLE); @@ -2504,43 +2123,35 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc * @return Text in desired format. * @throws MessagingException */ - private String getBodyTextFromMessage(final Message message, final MessageFormat format) throws MessagingException - { + private String getBodyTextFromMessage(final Message message, final MessageFormat format) throws MessagingException { Part part; - if (format == MessageFormat.HTML) - { + if (format == MessageFormat.HTML) { // HTML takes precedence, then text. part = MimeUtility.findFirstPartByMimeType(message, "text/html"); - if (part != null) - { - if(K9.DEBUG) + if (part != null) { + if (K9.DEBUG) Log.d(K9.LOG_TAG, "getBodyTextFromMessage: HTML requested, HTML found."); return MimeUtility.getTextFromPart(part); } part = MimeUtility.findFirstPartByMimeType(message, "text/plain"); - if (part != null) - { - if(K9.DEBUG) + if (part != null) { + if (K9.DEBUG) Log.d(K9.LOG_TAG, "getBodyTextFromMessage: HTML requested, text found."); return HtmlConverter.textToHtml(MimeUtility.getTextFromPart(part)); } - } - else if (format == MessageFormat.TEXT) - { + } else if (format == MessageFormat.TEXT) { // Text takes precedence, then html. part = MimeUtility.findFirstPartByMimeType(message, "text/plain"); - if (part != null) - { - if(K9.DEBUG) + if (part != null) { + if (K9.DEBUG) Log.d(K9.LOG_TAG, "getBodyTextFromMessage: Text requested, text found."); return MimeUtility.getTextFromPart(part); } part = MimeUtility.findFirstPartByMimeType(message, "text/html"); - if (part != null) - { - if(K9.DEBUG) + if (part != null) { + if (K9.DEBUG) Log.d(K9.LOG_TAG, "getBodyTextFromMessage: Text requested, HTML found."); return HtmlConverter.htmlToText(MimeUtility.getTextFromPart(part)); } @@ -2579,13 +2190,11 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc * @param content Content to examine for HTML insertion points * @return Insertion points and HTML to use for insertion. */ - private InsertableHtmlContent findInsertionPoints(final String content) - { + private InsertableHtmlContent findInsertionPoints(final String content) { InsertableHtmlContent insertable = new InsertableHtmlContent(); // If there is no content, don't bother doing any of the regex dancing. - if (content == null || content.equals("")) - { + if (content == null || content.equals("")) { return insertable; } @@ -2595,20 +2204,17 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc boolean hasBodyTag = false; // First see if we have an opening HTML tag. If we don't find one, we'll add one later. Matcher htmlMatcher = FIND_INSERTION_POINT_HTML.matcher(content); - if (htmlMatcher.matches()) - { + if (htmlMatcher.matches()) { hasHtmlTag = true; } // Look for a HEAD tag. If we're missing a BODY tag, we'll use the close of the HEAD to start our content. Matcher headMatcher = FIND_INSERTION_POINT_HEAD.matcher(content); - if (headMatcher.matches()) - { + if (headMatcher.matches()) { hasHeadTag = true; } // Look for a BODY tag. This is the ideal place for us to start our content. Matcher bodyMatcher = FIND_INSERTION_POINT_BODY.matcher(content); - if (bodyMatcher.matches()) - { + if (bodyMatcher.matches()) { hasBodyTag = true; } @@ -2617,22 +2223,17 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc // Given our inspections, let's figure out where to start our content. // This is the ideal case -- there's a BODY tag and we insert ourselves just after it. - if (hasBodyTag) - { + if (hasBodyTag) { insertable.setQuotedContent(new StringBuilder(content)); insertable.setHeaderInsertionPoint(bodyMatcher.end(FIND_INSERTION_POINT_FIRST_GROUP)); - } - else if (hasHeadTag) - { + } else if (hasHeadTag) { // Now search for a HEAD tag. We can insert after there. // If BlackBerry sees a HEAD tag, it inserts right after that, so long as there is no BODY tag. It doesn't // try to add BODY, either. Right or wrong, it seems to work fine. insertable.setQuotedContent(new StringBuilder(content)); insertable.setHeaderInsertionPoint(headMatcher.end(FIND_INSERTION_POINT_FIRST_GROUP)); - } - else if (hasHtmlTag) - { + } else if (hasHtmlTag) { // Lastly, check for an HTML tag. // In this case, it will add a HEAD, but no BODY. StringBuilder newContent = new StringBuilder(content); @@ -2641,9 +2242,7 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc insertable.setQuotedContent(newContent); // The new insertion point is the end of the HTML tag, plus the length of the HEAD content. insertable.setHeaderInsertionPoint(htmlMatcher.end(FIND_INSERTION_POINT_FIRST_GROUP) + FIND_INSERTION_POINT_HEAD_CONTENT.length()); - } - else - { + } else { // If we have none of the above, we probably have a fragment of HTML. Yahoo! and Gmail both do this. // Again, we add a HEAD, but not BODY. StringBuilder newContent = new StringBuilder(content); @@ -2662,14 +2261,12 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc boolean hasBodyEndTag = false; // First see if we have an opening HTML tag. If we don't find one, we'll add one later. Matcher htmlEndMatcher = FIND_INSERTION_POINT_HTML_END.matcher(insertable.getQuotedContent()); - if (htmlEndMatcher.matches()) - { + if (htmlEndMatcher.matches()) { hasHtmlEndTag = true; } // Look for a BODY tag. This is the ideal place for us to place our footer. Matcher bodyEndMatcher = FIND_INSERTION_POINT_BODY_END.matcher(insertable.getQuotedContent()); - if (bodyEndMatcher.matches()) - { + if (bodyEndMatcher.matches()) { hasBodyEndTag = true; } @@ -2678,17 +2275,12 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc // Now figure out where to put our footer. // This is the ideal case -- there's a BODY tag and we insert ourselves just before it. - if (hasBodyEndTag) - { + if (hasBodyEndTag) { insertable.setFooterInsertionPoint(bodyEndMatcher.start(FIND_INSERTION_POINT_FIRST_GROUP)); - } - else if (hasHtmlEndTag) - { + } else if (hasHtmlEndTag) { // Check for an HTML tag. Add ourselves just before it. insertable.setFooterInsertionPoint(htmlEndMatcher.start(FIND_INSERTION_POINT_FIRST_GROUP)); - } - else - { + } else { // If we have none of the above, we probably have a fragment of HTML. // Set our footer insertion point as the end of the string. insertable.setFooterInsertionPoint(insertable.getQuotedContent().length()); @@ -2697,13 +2289,10 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc return insertable; } - class Listener extends MessagingListener - { + class Listener extends MessagingListener { @Override - public void loadMessageForViewStarted(Account account, String folder, String uid) - { - if ((mMessageReference == null) || !mMessageReference.uid.equals(uid)) - { + public void loadMessageForViewStarted(Account account, String folder, String uid) { + if ((mMessageReference == null) || !mMessageReference.uid.equals(uid)) { return; } @@ -2711,10 +2300,8 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc } @Override - public void loadMessageForViewFinished(Account account, String folder, String uid, Message message) - { - if ((mMessageReference == null) || !mMessageReference.uid.equals(uid)) - { + public void loadMessageForViewFinished(Account account, String folder, String uid, Message message) { + if ((mMessageReference == null) || !mMessageReference.uid.equals(uid)) { return; } @@ -2722,36 +2309,27 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc } @Override - public void loadMessageForViewBodyAvailable(Account account, String folder, String uid, final Message message) - { - if ((mMessageReference == null) || !mMessageReference.uid.equals(uid)) - { + public void loadMessageForViewBodyAvailable(Account account, String folder, String uid, final Message message) { + if ((mMessageReference == null) || !mMessageReference.uid.equals(uid)) { return; } mSourceMessage = message; - runOnUiThread(new Runnable() - { - public void run() - { + runOnUiThread(new Runnable() { + public void run() { // We check to see if we've previously processed the source message since this // could be called when switching from HTML to text replies. If that happens, we // only want to update the UI with quoted text (which picks the appropriate // part). - if (mSourceProcessed) - { - try - { + if (mSourceProcessed) { + try { populateUIWithQuotedMessage(); - } catch (MessagingException e) - { + } catch (MessagingException e) { // Hm, if we couldn't populate the UI after source reprocessing, let's just delete it? deleteQuotedText(); Log.e(K9.LOG_TAG, "Could not re-process source message; deleting quoted text to be safe.", e); } - } - else - { + } else { processSourceMessage(message); mSourceProcessed = true; } @@ -2760,10 +2338,8 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc } @Override - public void loadMessageForViewFailed(Account account, String folder, String uid, Throwable t) - { - if ((mMessageReference == null) || !mMessageReference.uid.equals(uid)) - { + public void loadMessageForViewFailed(Account account, String folder, String uid, Throwable t) { + if ((mMessageReference == null) || !mMessageReference.uid.equals(uid)) { return; } mHandler.sendEmptyMessage(MSG_PROGRESS_OFF); @@ -2771,32 +2347,26 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc } @Override - public void messageUidChanged(Account account, String folder, String oldUid, String newUid) - { + public void messageUidChanged(Account account, String folder, String oldUid, String newUid) { //TODO: is this really necessary here? mDraftUid is update after the call to MessagingController.saveDraft() // Track UID changes of the draft message if (account.equals(mAccount) && folder.equals(mAccount.getDraftsFolderName()) && - oldUid.equals(mDraftUid)) - { + oldUid.equals(mDraftUid)) { mDraftUid = newUid; } // Track UID changes of the source message - if (mMessageReference != null) - { + if (mMessageReference != null) { final Account sourceAccount = Preferences.getPreferences(MessageCompose.this).getAccount(mMessageReference.accountUuid); final String sourceFolder = mMessageReference.folderName; final String sourceMessageUid = mMessageReference.uid; - if (account.equals(sourceAccount) && (folder.equals(sourceFolder))) - { - if (oldUid.equals(sourceMessageUid)) - { + if (account.equals(sourceAccount) && (folder.equals(sourceFolder))) { + if (oldUid.equals(sourceMessageUid)) { mMessageReference.uid = newUid; } - if ((mSourceMessage != null) && (oldUid.equals(mSourceMessage.getUid()))) - { + if ((mSourceMessage != null) && (oldUid.equals(mSourceMessage.getUid()))) { mSourceMessage.setUid(newUid); } } @@ -2808,12 +2378,10 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc * When we are launched with an intent that includes a mailto: URI, we can actually * gather quite a few of our message fields from it. */ - private void initializeFromMailto(Uri mailtoUri) - { + private void initializeFromMailto(Uri mailtoUri) { String schemaSpecific = mailtoUri.getSchemeSpecificPart(); int end = schemaSpecific.indexOf('?'); - if (end == -1) - { + if (end == -1) { end = schemaSpecific.length(); } @@ -2830,8 +2398,7 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc // Read additional recipients from the "to" parameter. List to = uri.getQueryParameters("to"); - if (recipient.length() != 0) - { + if (recipient.length() != 0) { to = new ArrayList(to); to.add(0, recipient); } @@ -2843,61 +2410,49 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc // Read blind carbon copy recipients from the "bcc" parameter. ccOrBcc |= setRecipients(mBccView, uri.getQueryParameters("bcc")); - if (ccOrBcc) - { + if (ccOrBcc) { // Display CC and BCC text fields if CC or BCC recipients were set by the intent. onAddCcBcc(); } // Read subject from the "subject" parameter. List subject = uri.getQueryParameters("subject"); - if (subject.size() > 0) - { + if (subject.size() > 0) { mSubjectView.setText(subject.get(0)); } // Read message body from the "body" parameter. List body = uri.getQueryParameters("body"); - if (body.size() > 0) - { + if (body.size() > 0) { mMessageContentView.setText(body.get(0)); } } - private class SendMessageTask extends AsyncTask - { + private class SendMessageTask extends AsyncTask { @Override - protected Void doInBackground(Void... params) - { + protected Void doInBackground(Void... params) { /* * Create the message from all the data the user has entered. */ MimeMessage message; - try - { + try { message = createMessage(false); // isDraft = true - } - catch (MessagingException me) - { + } catch (MessagingException me) { Log.e(K9.LOG_TAG, "Failed to create new message for send or save.", me); throw new RuntimeException("Failed to create a new message for send or save.", me); } - try - { + try { final Contacts contacts = Contacts.getInstance(MessageCompose.this); contacts.markAsContacted(message.getRecipients(RecipientType.TO)); contacts.markAsContacted(message.getRecipients(RecipientType.CC)); contacts.markAsContacted(message.getRecipients(RecipientType.BCC)); - } - catch (Exception e) - { + } catch (Exception e) { Log.e(K9.LOG_TAG, "Failed to mark contact as contacted.", e); } MessagingController.getInstance(getApplication()).sendMessage(mAccount, message, null); - if (mDraftUid != null) - { + if (mDraftUid != null) { MessagingController.getInstance(getApplication()).deleteDraft(mAccount, mDraftUid); mDraftUid = null; } @@ -2906,22 +2461,17 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc } } - private class SaveMessageTask extends AsyncTask - { + private class SaveMessageTask extends AsyncTask { @Override - protected Void doInBackground(Void... params) - { + protected Void doInBackground(Void... params) { /* * Create the message from all the data the user has entered. */ MimeMessage message; - try - { + try { message = createMessage(true); // isDraft = true - } - catch (MessagingException me) - { + } catch (MessagingException me) { Log.e(K9.LOG_TAG, "Failed to create new message for send or save.", me); throw new RuntimeException("Failed to create a new message for send or save.", me); } @@ -2929,18 +2479,14 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc /* * Save a draft */ - if (mDraftUid != null) - { + if (mDraftUid != null) { message.setUid(mDraftUid); - } - else if (ACTION_EDIT_DRAFT.equals(getIntent().getAction())) - { + } else if (ACTION_EDIT_DRAFT.equals(getIntent().getAction())) { /* * We're saving a previously saved draft, so update the new message's uid * to the old message's uid. */ - if (mMessageReference != null) - { + if (mMessageReference != null) { message.setUid(mMessageReference.uid); } } @@ -2950,8 +2496,7 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc mDraftUid = draftMessage.getUid(); // Don't display the toast if the user is just changing the orientation - if ((getChangingConfigurations() & ActivityInfo.CONFIG_ORIENTATION) == 0) - { + if ((getChangingConfigurations() & ActivityInfo.CONFIG_ORIENTATION) == 0) { mHandler.sendEmptyMessage(MSG_SAVED_DRAFT); } return null; @@ -2969,11 +2514,9 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc * @return Quoted text. * @throws MessagingException */ - private String quoteOriginalTextMessage(final Message originalMessage, final String messageBody, final QuoteStyle quoteStyle) throws MessagingException - { + private String quoteOriginalTextMessage(final Message originalMessage, final String messageBody, final QuoteStyle quoteStyle) throws MessagingException { String body = messageBody == null ? "" : messageBody; - if (quoteStyle == QuoteStyle.PREFIX) - { + if (quoteStyle == QuoteStyle.PREFIX) { StringBuilder quotedText = new StringBuilder(body.length() + QUOTE_BUFFER_LENGTH); quotedText.append(String.format( getString(R.string.message_compose_reply_header_fmt), @@ -2989,30 +2532,23 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc quotedText.append(wrappedText.replaceAll("(?m)^", escapedPrefix)); return quotedText.toString().replaceAll("\\\r", ""); - } - else if (quoteStyle == QuoteStyle.HEADER) - { + } else if (quoteStyle == QuoteStyle.HEADER) { StringBuilder quotedText = new StringBuilder(body.length() + QUOTE_BUFFER_LENGTH); quotedText.append("\n"); quotedText.append(getString(R.string.message_compose_quote_header_separator)).append("\n"); - if (originalMessage.getFrom() != null && Address.toString(originalMessage.getFrom()).length() != 0) - { + if (originalMessage.getFrom() != null && Address.toString(originalMessage.getFrom()).length() != 0) { quotedText.append(getString(R.string.message_compose_quote_header_from)).append(" ").append(Address.toString(originalMessage.getFrom())).append("\n"); } - if (originalMessage.getSentDate() != null) - { + if (originalMessage.getSentDate() != null) { quotedText.append(getString(R.string.message_compose_quote_header_send_date)).append(" ").append(originalMessage.getSentDate()).append("\n"); } - if (originalMessage.getRecipients(RecipientType.TO) != null && originalMessage.getRecipients(RecipientType.TO).length != 0) - { + if (originalMessage.getRecipients(RecipientType.TO) != null && originalMessage.getRecipients(RecipientType.TO).length != 0) { quotedText.append(getString(R.string.message_compose_quote_header_to)).append(" ").append(Address.toString(originalMessage.getRecipients(RecipientType.TO))).append("\n"); } - if (originalMessage.getRecipients(RecipientType.CC) != null && originalMessage.getRecipients(RecipientType.CC).length != 0) - { + if (originalMessage.getRecipients(RecipientType.CC) != null && originalMessage.getRecipients(RecipientType.CC).length != 0) { quotedText.append(getString(R.string.message_compose_quote_header_cc)).append(" ").append(Address.toString(originalMessage.getRecipients(RecipientType.CC))).append("\n"); } - if (originalMessage.getSubject() != null) - { + if (originalMessage.getSubject() != null) { quotedText.append(getString(R.string.message_compose_quote_header_subject)).append(" ").append(originalMessage.getSubject()).append("\n"); } quotedText.append("\n"); @@ -3020,9 +2556,7 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc quotedText.append(body); return quotedText.toString(); - } - else - { + } else { // Shouldn't ever happen. return body; } @@ -3036,12 +2570,10 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc * @return Modified insertable message. * @throws MessagingException */ - private InsertableHtmlContent quoteOriginalHtmlMessage(final Message originalMessage, final String messageBody, final QuoteStyle quoteStyle) throws MessagingException - { + private InsertableHtmlContent quoteOriginalHtmlMessage(final Message originalMessage, final String messageBody, final QuoteStyle quoteStyle) throws MessagingException { InsertableHtmlContent insertable = findInsertionPoints(messageBody); - if (quoteStyle == QuoteStyle.PREFIX) - { + if (quoteStyle == QuoteStyle.PREFIX) { StringBuilder header = new StringBuilder(QUOTE_BUFFER_LENGTH); header.append("
    "); // Remove all trailing newlines so that the quote starts immediately after the header. "Be like Gmail!" @@ -3056,31 +2588,24 @@ public class MessageCompose extends K9Activity implements OnClickListener, OnFoc insertable.insertIntoQuotedHeader(header.toString()); insertable.insertIntoQuotedFooter(footer); - } - else if (quoteStyle == QuoteStyle.HEADER) - { + } else if (quoteStyle == QuoteStyle.HEADER) { StringBuilder header = new StringBuilder(); header.append("
    \n"); header.append("
    \n"); // This gets converted into a horizontal line during html to text conversion. - if (mSourceMessage.getFrom() != null && Address.toString(mSourceMessage.getFrom()).length() != 0) - { + if (mSourceMessage.getFrom() != null && Address.toString(mSourceMessage.getFrom()).length() != 0) { header.append("").append(getString(R.string.message_compose_quote_header_from)).append(" ").append(HtmlConverter.textToHtmlFragment(Address.toString(mSourceMessage.getFrom()))).append("
    \n"); } - if (mSourceMessage.getSentDate() != null) - { + if (mSourceMessage.getSentDate() != null) { header.append("").append(getString(R.string.message_compose_quote_header_send_date)).append(" ").append(mSourceMessage.getSentDate()).append("
    \n"); } - if (mSourceMessage.getRecipients(RecipientType.TO) != null && mSourceMessage.getRecipients(RecipientType.TO).length != 0) - { + if (mSourceMessage.getRecipients(RecipientType.TO) != null && mSourceMessage.getRecipients(RecipientType.TO).length != 0) { header.append("").append(getString(R.string.message_compose_quote_header_to)).append(" ").append(HtmlConverter.textToHtmlFragment(Address.toString(mSourceMessage.getRecipients(RecipientType.TO)))).append("
    \n"); } - if (mSourceMessage.getRecipients(RecipientType.CC) != null && mSourceMessage.getRecipients(RecipientType.CC).length != 0) - { + if (mSourceMessage.getRecipients(RecipientType.CC) != null && mSourceMessage.getRecipients(RecipientType.CC).length != 0) { header.append("").append(getString(R.string.message_compose_quote_header_cc)).append(" ").append(HtmlConverter.textToHtmlFragment(Address.toString(mSourceMessage.getRecipients(RecipientType.CC)))).append("
    \n"); } - if (mSourceMessage.getSubject() != null) - { + if (mSourceMessage.getSubject() != null) { header.append("").append(getString(R.string.message_compose_quote_header_subject)).append(" ").append(HtmlConverter.textToHtmlFragment(mSourceMessage.getSubject())).append("
    \n"); } header.append("
    \n"); diff --git a/src/com/fsck/k9/activity/MessageInfoHolder.java b/src/com/fsck/k9/activity/MessageInfoHolder.java index d12ca12ff..e19fb953a 100644 --- a/src/com/fsck/k9/activity/MessageInfoHolder.java +++ b/src/com/fsck/k9/activity/MessageInfoHolder.java @@ -4,8 +4,7 @@ import java.util.Date; import com.fsck.k9.helper.MessageHelper; import com.fsck.k9.mail.store.LocalStore.LocalMessage; -public class MessageInfoHolder -{ +public class MessageInfoHolder { public String date; public Date compareDate; public String compareSubject; @@ -27,16 +26,13 @@ public class MessageInfoHolder public String uri; // Empty constructor for comparison - public MessageInfoHolder() - { + public MessageInfoHolder() { this.selected = false; } @Override - public boolean equals(Object o) - { - if (o instanceof MessageInfoHolder == false) - { + public boolean equals(Object o) { + if (o instanceof MessageInfoHolder == false) { return false; } MessageInfoHolder other = (MessageInfoHolder)o; @@ -44,15 +40,12 @@ public class MessageInfoHolder } @Override - public int hashCode() - { + public int hashCode() { return uid.hashCode(); } - public String getDate(MessageHelper messageHelper) - { - if (date == null) - { + public String getDate(MessageHelper messageHelper) { + if (date == null) { date = messageHelper.formatDate(message.getSentDate()); } return date; diff --git a/src/com/fsck/k9/activity/MessageList.java b/src/com/fsck/k9/activity/MessageList.java index 57f32a4ad..5562c88d1 100644 --- a/src/com/fsck/k9/activity/MessageList.java +++ b/src/com/fsck/k9/activity/MessageList.java @@ -80,30 +80,26 @@ import com.fsck.k9.mail.store.LocalStore.LocalFolder; */ public class MessageList extends K9Activity - implements OnClickListener, AdapterView.OnItemClickListener, AnimationListener -{ + implements OnClickListener, AdapterView.OnItemClickListener, AnimationListener { /** * Reverses the result of a {@link Comparator}. * * @param */ - public static class ReverseComparator implements Comparator - { + public static class ReverseComparator implements Comparator { private Comparator mDelegate; /** * @param delegate * Never null. */ - public ReverseComparator(final Comparator delegate) - { + public ReverseComparator(final Comparator delegate) { mDelegate = delegate; } @Override - public int compare(final T object1, final T object2) - { + public int compare(final T object1, final T object2) { // arg1 & 2 are mixed up, this is done on purpose return mDelegate.compare(object2, object1); } @@ -115,8 +111,7 @@ public class MessageList * * @param */ - public static class ComparatorChain implements Comparator - { + public static class ComparatorChain implements Comparator { private List> mChain; @@ -124,20 +119,16 @@ public class MessageList * @param chain * Comparator chain. Never null. */ - public ComparatorChain(final List> chain) - { + public ComparatorChain(final List> chain) { mChain = chain; } @Override - public int compare(T object1, T object2) - { + public int compare(T object1, T object2) { int result = 0; - for (final Comparator comparator : mChain) - { + for (final Comparator comparator : mChain) { result = comparator.compare(object1, object2); - if (result != 0) - { + if (result != 0) { break; } } @@ -146,74 +137,60 @@ public class MessageList } - public static class AttachmentComparator implements Comparator - { + public static class AttachmentComparator implements Comparator { @Override - public int compare(MessageInfoHolder object1, MessageInfoHolder object2) - { + public int compare(MessageInfoHolder object1, MessageInfoHolder object2) { return (object1.message.hasAttachments() ? 0 : 1) - (object2.message.hasAttachments() ? 0 : 1); } } - public static class FlaggedComparator implements Comparator - { + public static class FlaggedComparator implements Comparator { @Override - public int compare(MessageInfoHolder object1, MessageInfoHolder object2) - { + public int compare(MessageInfoHolder object1, MessageInfoHolder object2) { return (object1.flagged ? 0 : 1) - (object2.flagged ? 0 : 1); } } - public static class UnreadComparator implements Comparator - { + public static class UnreadComparator implements Comparator { @Override - public int compare(MessageInfoHolder object1, MessageInfoHolder object2) - { + public int compare(MessageInfoHolder object1, MessageInfoHolder object2) { return (object1.read ? 1 : 0) - (object2.read ? 1 : 0); } } - public static class SenderComparator implements Comparator - { + public static class SenderComparator implements Comparator { @Override - public int compare(MessageInfoHolder object1, MessageInfoHolder object2) - { + public int compare(MessageInfoHolder object1, MessageInfoHolder object2) { return object1.compareCounterparty.toLowerCase().compareTo(object2.compareCounterparty.toLowerCase()); } } - public static class DateComparator implements Comparator - { + public static class DateComparator implements Comparator { @Override - public int compare(MessageInfoHolder object1, MessageInfoHolder object2) - { + public int compare(MessageInfoHolder object1, MessageInfoHolder object2) { return object1.compareDate.compareTo(object2.compareDate); } } - public static class SubjectComparator implements Comparator - { + public static class SubjectComparator implements Comparator { @Override - public int compare(MessageInfoHolder arg0, MessageInfoHolder arg1) - { + public int compare(MessageInfoHolder arg0, MessageInfoHolder arg1) { // XXX doesn't respect the Comparator contract since it alters the compared object - if (arg0.compareSubject == null) - { + if (arg0.compareSubject == null) { arg0.compareSubject = Utility.stripSubject(arg0.message.getSubject()); } - if (arg1.compareSubject == null) - { + if (arg1.compareSubject == null) { arg1.compareSubject = Utility.stripSubject(arg1.message.getSubject()); } return arg0.compareSubject.compareToIgnoreCase(arg1.compareSubject); @@ -249,8 +226,7 @@ public class MessageList */ private static final Map> SORT_COMPARATORS; - static - { + static { // fill the mapping at class time loading final Map> map = new EnumMap>(SORT_TYPE.class); @@ -330,18 +306,13 @@ public class MessageList private StorageManager.StorageListener mStorageListener = new StorageListenerImplementation(); - private final class StorageListenerImplementation implements StorageManager.StorageListener - { + private final class StorageListenerImplementation implements StorageManager.StorageListener { @Override - public void onUnmount(String providerId) - { - if (mAccount != null && providerId.equals(mAccount.getLocalStorageProviderId())) - { - runOnUiThread(new Runnable() - { + public void onUnmount(String providerId) { + if (mAccount != null && providerId.equals(mAccount.getLocalStorageProviderId())) { + runOnUiThread(new Runnable() { @Override - public void run() - { + public void run() { onAccountUnavailable(); } }); @@ -349,28 +320,19 @@ public class MessageList } @Override - public void onMount(String providerId) - { + public void onMount(String providerId) { // no-op } } - class MessageListHandler - { - public void removeMessage(final List messages) - { - runOnUiThread(new Runnable() - { - public void run() - { - for (MessageInfoHolder message : messages) - { - if (message != null) - { - if (mFolderName == null || (message.folder != null && message.folder.name.equals(mFolderName))) - { - if (message.selected && mSelectedCount > 0) - { + class MessageListHandler { + public void removeMessage(final List messages) { + runOnUiThread(new Runnable() { + public void run() { + for (MessageInfoHolder message : messages) { + if (message != null) { + if (mFolderName == null || (message.folder != null && message.folder.name.equals(mFolderName))) { + if (message.selected && mSelectedCount > 0) { mSelectedCount--; } mAdapter.messages.remove(message); @@ -385,25 +347,18 @@ public class MessageList }); } - public void addMessages(final List messages) - { + public void addMessages(final List messages) { final boolean wasEmpty = mAdapter.messages.isEmpty(); - runOnUiThread(new Runnable() - { - public void run() - { - for (final MessageInfoHolder message : messages) - { - if (mFolderName == null || (message.folder != null && message.folder.name.equals(mFolderName))) - { + runOnUiThread(new Runnable() { + public void run() { + for (final MessageInfoHolder message : messages) { + if (mFolderName == null || (message.folder != null && message.folder.name.equals(mFolderName))) { int index; - synchronized (mAdapter.messages) - { + synchronized (mAdapter.messages) { index = Collections.binarySearch(mAdapter.messages, message, getComparator()); } - if (index < 0) - { + if (index < 0) { index = (index * -1) - 1; } @@ -411,8 +366,7 @@ public class MessageList } } - if (wasEmpty) - { + if (wasEmpty) { mListView.setSelection(0); } resetUnreadCountOnThread(); @@ -422,26 +376,19 @@ public class MessageList }); } - private void resetUnreadCount() - { - runOnUiThread(new Runnable() - { - public void run() - { + private void resetUnreadCount() { + runOnUiThread(new Runnable() { + public void run() { resetUnreadCountOnThread(); } }); } - private void resetUnreadCountOnThread() - { - if (mQueryString != null) - { + private void resetUnreadCountOnThread() { + if (mQueryString != null) { int unreadCount = 0; - synchronized (mAdapter.messages) - { - for (MessageInfoHolder holder : mAdapter.messages) - { + synchronized (mAdapter.messages) { + for (MessageInfoHolder holder : mAdapter.messages) { unreadCount += holder.read ? 0 : 1; } } @@ -450,16 +397,12 @@ public class MessageList } } - private void sortMessages() - { + private void sortMessages() { final Comparator chainComparator = getComparator(); - runOnUiThread(new Runnable() - { - public void run() - { - synchronized (mAdapter.messages) - { + runOnUiThread(new Runnable() { + public void run() { + synchronized (mAdapter.messages) { Collections.sort(mAdapter.messages, chainComparator); } mAdapter.notifyDataSetChanged(); @@ -471,34 +414,26 @@ public class MessageList * @return The comparator to use to display messages in an ordered * fashion. Never null. */ - protected Comparator getComparator() - { - final List> chain = new ArrayList>(2 /* we add 2 comparators at most */ ); + protected Comparator getComparator() { + final List> chain = new ArrayList>(2 /* we add 2 comparators at most */); { // add the specified comparator final Comparator comparator = SORT_COMPARATORS.get(sortType); - if (sortAscending) - { + if (sortAscending) { chain.add(comparator); - } - else - { + } else { chain.add(new ReverseComparator(comparator)); } } { // add the date comparator if not already specified - if (sortType != SORT_TYPE.SORT_DATE) - { + if (sortType != SORT_TYPE.SORT_DATE) { final Comparator comparator = SORT_COMPARATORS.get(SORT_TYPE.SORT_DATE); - if (sortDateAscending) - { + if (sortDateAscending) { chain.add(comparator); - } - else - { + } else { chain.add(new ReverseComparator(comparator)); } } @@ -510,43 +445,33 @@ public class MessageList return chainComparator; } - public void folderLoading(String folder, boolean loading) - { - if (mCurrentFolder != null && mCurrentFolder.name.equals(folder)) - { + public void folderLoading(String folder, boolean loading) { + if (mCurrentFolder != null && mCurrentFolder.name.equals(folder)) { mCurrentFolder.loading = loading; } } - private void refreshTitle() - { - runOnUiThread(new Runnable() - { - public void run() - { + private void refreshTitle() { + runOnUiThread(new Runnable() { + public void run() { refreshTitleOnThread(); } }); } - private void refreshTitleOnThread() - { + private void refreshTitleOnThread() { setWindowTitle(); setWindowProgress(); } - private void setWindowProgress() - { + private void setWindowProgress() { int level = Window.PROGRESS_END; - if (mCurrentFolder != null && mCurrentFolder.loading && mAdapter.mListener.getFolderTotal() > 0) - { + if (mCurrentFolder != null && mCurrentFolder.loading && mAdapter.mListener.getFolderTotal() > 0) { int divisor = mAdapter.mListener.getFolderTotal(); - if (divisor != 0) - { + if (divisor != 0) { level = (Window.PROGRESS_END / divisor) * (mAdapter.mListener.getFolderCompleted()) ; - if (level > Window.PROGRESS_END) - { + if (level > Window.PROGRESS_END) { level = Window.PROGRESS_END; } } @@ -555,76 +480,59 @@ public class MessageList getWindow().setFeatureInt(Window.FEATURE_PROGRESS, level); } - private void setWindowTitle() - { + private void setWindowTitle() { String displayName; - if (mFolderName != null) - { + if (mFolderName != null) { displayName = mFolderName; - if (K9.INBOX.equalsIgnoreCase(displayName)) - { + if (K9.INBOX.equalsIgnoreCase(displayName)) { displayName = getString(R.string.special_mailbox_name_inbox); } String dispString = mAdapter.mListener.formatHeader(MessageList.this, getString(R.string.message_list_title, mAccount.getDescription(), displayName), mUnreadMessageCount, getTimeFormat()); setTitle(dispString); - } - else if (mQueryString != null) - { - if (mTitle != null) - { + } else if (mQueryString != null) { + if (mTitle != null) { String dispString = mAdapter.mListener.formatHeader(MessageList.this, mTitle, mUnreadMessageCount, getTimeFormat()); setTitle(dispString); - } - else - { - setTitle(getString(R.string.search_results) + ": "+ mQueryString); + } else { + setTitle(getString(R.string.search_results) + ": " + mQueryString); } } } - public void progress(final boolean progress) - { - runOnUiThread(new Runnable() - { - public void run() - { + public void progress(final boolean progress) { + runOnUiThread(new Runnable() { + public void run() { showProgressIndicator(progress); } }); } } - public static void actionHandleFolder(Context context, Account account, String folder) - { - Intent intent = actionHandleFolderIntent(context,account,folder); + public static void actionHandleFolder(Context context, Account account, String folder) { + Intent intent = actionHandleFolderIntent(context, account, folder); context.startActivity(intent); } - public static Intent actionHandleFolderIntent(Context context, Account account, String folder) - { + public static Intent actionHandleFolderIntent(Context context, Account account, String folder) { Intent intent = new Intent(context, MessageList.class); intent.putExtra(EXTRA_ACCOUNT, account.getUuid()); - if (folder != null) - { + if (folder != null) { intent.putExtra(EXTRA_FOLDER, folder); } return intent; } - public static void actionHandle(Context context, String title, String queryString, boolean integrate, Flag[] flags, Flag[] forbiddenFlags) - { + public static void actionHandle(Context context, String title, String queryString, boolean integrate, Flag[] flags, Flag[] forbiddenFlags) { Intent intent = new Intent(context, MessageList.class); intent.putExtra(EXTRA_QUERY, queryString); - if (flags != null) - { + if (flags != null) { intent.putExtra(EXTRA_QUERY_FLAGS, Utility.combine(flags, ',')); } - if (forbiddenFlags != null) - { + if (forbiddenFlags != null) { intent.putExtra(EXTRA_FORBIDDEN_FLAGS, Utility.combine(forbiddenFlags, ',')); } intent.putExtra(EXTRA_INTEGRATE, integrate); @@ -632,16 +540,13 @@ public class MessageList context.startActivity(intent); } - public static void actionHandle(Context context, String title, SearchSpecification searchSpecification) - { + public static void actionHandle(Context context, String title, SearchSpecification searchSpecification) { Intent intent = new Intent(context, MessageList.class); intent.putExtra(EXTRA_QUERY, searchSpecification.getQuery()); - if (searchSpecification.getRequiredFlags() != null) - { + if (searchSpecification.getRequiredFlags() != null) { intent.putExtra(EXTRA_QUERY_FLAGS, Utility.combine(searchSpecification.getRequiredFlags(), ',')); } - if (searchSpecification.getForbiddenFlags() != null) - { + if (searchSpecification.getForbiddenFlags() != null) { intent.putExtra(EXTRA_FORBIDDEN_FLAGS, Utility.combine(searchSpecification.getForbiddenFlags(), ',')); } intent.putExtra(EXTRA_INTEGRATE, searchSpecification.isIntegrate()); @@ -652,31 +557,25 @@ public class MessageList } @Override - public void onItemClick(AdapterView parent, View view, int position, long id) - { - if (mCurrentFolder != null && ((position+1) == mAdapter.getCount())) - { + public void onItemClick(AdapterView parent, View view, int position, long id) { + if (mCurrentFolder != null && ((position + 1) == mAdapter.getCount())) { mController.loadMoreMessages(mAccount, mFolderName, mAdapter.mListener); return; } MessageInfoHolder message = (MessageInfoHolder) mAdapter.getItem(position); - if (mSelectedCount > 0) - { + if (mSelectedCount > 0) { // In multiselect mode make sure that clicking on the item results // in toggling the 'selected' checkbox. setSelected(message, !message.selected); - } - else - { + } else { onOpenMessage(message); } } @Override - public void onCreate(Bundle savedInstanceState) - { - context=this; + public void onCreate(Bundle savedInstanceState) { + context = this; super.onCreate(savedInstanceState); mInflater = getLayoutInflater(); @@ -685,8 +584,7 @@ public class MessageList } @Override - public void onNewIntent(Intent intent) - { + public void onNewIntent(Intent intent) { setIntent(intent); // onNewIntent doesn't autoset our "internal" intent // Only set "touchable" when we're first starting up the activity. @@ -699,30 +597,25 @@ public class MessageList mFolderName = intent.getStringExtra(EXTRA_FOLDER); mQueryString = intent.getStringExtra(EXTRA_QUERY); - if (mAccount != null && !mAccount.isAvailable(this)) - { + if (mAccount != null && !mAccount.isAvailable(this)) { Log.i(K9.LOG_TAG, "not opening MessageList of unavailable account"); onAccountUnavailable(); return; } String queryFlags = intent.getStringExtra(EXTRA_QUERY_FLAGS); - if (queryFlags != null) - { + if (queryFlags != null) { String[] flagStrings = queryFlags.split(","); mQueryFlags = new Flag[flagStrings.length]; - for (int i = 0; i < flagStrings.length; i++) - { + for (int i = 0; i < flagStrings.length; i++) { mQueryFlags[i] = Flag.valueOf(flagStrings[i]); } } String forbiddenFlags = intent.getStringExtra(EXTRA_FORBIDDEN_FLAGS); - if (forbiddenFlags != null) - { + if (forbiddenFlags != null) { String[] flagStrings = forbiddenFlags.split(","); mForbiddenFlags = new Flag[flagStrings.length]; - for (int i = 0; i < flagStrings.length; i++) - { + for (int i = 0; i < flagStrings.length; i++) { mForbiddenFlags[i] = Flag.valueOf(flagStrings[i]); } } @@ -733,16 +626,14 @@ public class MessageList // Take the initial folder into account only if we are *not* restoring // the activity already. - if (mFolderName == null && mQueryString == null) - { + if (mFolderName == null && mQueryString == null) { mFolderName = mAccount.getAutoExpandFolderName(); } mAdapter = new MessageListAdapter(); restorePreviousData(); - if (mFolderName != null) - { + if (mFolderName != null) { mCurrentFolder = mAdapter.getFolder(mFolderName, mAccount); } @@ -751,19 +642,16 @@ public class MessageList } @SuppressWarnings("unchecked") - private void restorePreviousData() - { + private void restorePreviousData() { final Object previousData = getLastNonConfigurationInstance(); - if (previousData != null) - { + if (previousData != null) { mAdapter.messages.addAll((List) previousData); } } @Override - public void onPause() - { + public void onPause() { super.onPause(); mController.removeListener(mAdapter.mListener); saveListState(); @@ -771,32 +659,25 @@ public class MessageList StorageManager.getInstance(getApplication()).removeListener(mStorageListener); } - public void saveListState() - { + public void saveListState() { mState = new Bundle(); mState.putInt(EXTRA_LIST_POSITION, mListView.getSelectedItemPosition()); } - public void restoreListState() - { - if (mState == null) - { + public void restoreListState() { + if (mState == null) { return; } int pos = mState.getInt(EXTRA_LIST_POSITION, ListView.INVALID_POSITION); - if (pos >= mListView.getCount()) - { + if (pos >= mListView.getCount()) { pos = mListView.getCount() - 1; } - if (pos == ListView.INVALID_POSITION) - { + if (pos == ListView.INVALID_POSITION) { mListView.setSelected(false); - } - else - { + } else { mListView.setSelection(pos); } } @@ -807,12 +688,10 @@ public class MessageList * are updated. */ @Override - public void onResume() - { + public void onResume() { super.onResume(); - if (mAccount != null && !mAccount.isAvailable(this)) - { + if (mAccount != null && !mAccount.isAvailable(this)) { onAccountUnavailable(); return; } @@ -826,48 +705,34 @@ public class MessageList sortDateAscending = mController.isSortAscending(SORT_TYPE.SORT_DATE); mController.addListener(mAdapter.mListener); - if (mAccount != null) - { + if (mAccount != null) { mController.notifyAccountCancel(this, mAccount); MessagingController.getInstance(getApplication()).notifyAccountCancel(this, mAccount); } - if (mAdapter.messages.isEmpty()) - { - if (mFolderName != null) - { + if (mAdapter.messages.isEmpty()) { + if (mFolderName != null) { mController.listLocalMessages(mAccount, mFolderName, mAdapter.mListener); - } - else if (mQueryString != null) - { + } else if (mQueryString != null) { mController.searchLocalMessages(mAccountUuids, mFolderNames, null, mQueryString, mIntegrate, mQueryFlags, mForbiddenFlags, mAdapter.mListener); } - } - else - { - new Thread() - { + } else { + new Thread() { @Override - public void run() - { + public void run() { mAdapter.markAllMessagesAsDirty(); - if (mFolderName != null) - { + if (mFolderName != null) { mController.listLocalMessagesSynchronous(mAccount, mFolderName, mAdapter.mListener); - } - else if (mQueryString != null) - { + } else if (mQueryString != null) { mController.searchLocalMessagesSynchronous(mAccountUuids, mFolderNames, null, mQueryString, mIntegrate, mQueryFlags, mForbiddenFlags, mAdapter.mListener); } mAdapter.pruneDirtyMessages(); - runOnUiThread(new Runnable() - { - public void run() - { + runOnUiThread(new Runnable() { + public void run() { mAdapter.notifyDataSetChanged(); restoreListState(); } @@ -878,15 +743,13 @@ public class MessageList .start(); } - if (mAccount != null && mFolderName != null) - { + if (mAccount != null && mFolderName != null) { mController.getFolderUnreadMessageCount(mAccount, mFolderName, mAdapter.mListener); } mHandler.refreshTitle(); } - private void initializeLayout() - { + private void initializeLayout() { requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); requestWindowFeature(Window.FEATURE_PROGRESS); setContentView(R.layout.message_list); @@ -913,12 +776,9 @@ public class MessageList // Gesture detection gestureDetector = new GestureDetector(new MyGestureDetector()); - gestureListener = new View.OnTouchListener() - { - public boolean onTouch(View v, MotionEvent event) - { - if (gestureDetector.onTouchEvent(event)) - { + gestureListener = new View.OnTouchListener() { + public boolean onTouch(View v, MotionEvent event) { + if (gestureDetector.onTouchEvent(event)) { return true; } return false; @@ -929,44 +789,34 @@ public class MessageList } @Override - public Object onRetainNonConfigurationInstance() - { + public Object onRetainNonConfigurationInstance() { return mAdapter.messages; } @Override - public void onBackPressed() - { + public void onBackPressed() { // This will be called either automatically for you on 2.0 // or later, or by the code above on earlier versions of the // platform. - if (K9.manageBack()) - { - if (mQueryString == null) - { + if (K9.manageBack()) { + if (mQueryString == null) { onShowFolderList(); - } - else - { + } else { onAccounts(); } - } - else - { + } else { finish(); } } @Override - public boolean onKeyDown(int keyCode, KeyEvent event) - { + public boolean onKeyDown(int keyCode, KeyEvent event) { if ( // XXX TODO - when we go to android 2.0, uncomment this // android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.ECLAIR && keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0 - ) - { + ) { // Take care of calling this method on earlier versions of // the platform where it doesn't exist. onBackPressed(); @@ -974,212 +824,163 @@ public class MessageList } // Shortcuts that work no matter what is selected - switch (keyCode) - { + switch (keyCode) { - // messagelist is actually a K9Activity, not a K9ListActivity - // This saddens me greatly, but to support volume key navigation - // in MessageView, we implement this bit of wrapper code - case KeyEvent.KEYCODE_VOLUME_UP: - { - if (K9.useVolumeKeysForListNavigationEnabled()) - { - int currentPosition = mListView.getSelectedItemPosition(); - if (currentPosition == AdapterView.INVALID_POSITION || mListView.isInTouchMode()) - { - currentPosition = mListView.getFirstVisiblePosition(); - } - if (currentPosition > 0) - { - mListView.setSelection(currentPosition - 1); - } - return true; + // messagelist is actually a K9Activity, not a K9ListActivity + // This saddens me greatly, but to support volume key navigation + // in MessageView, we implement this bit of wrapper code + case KeyEvent.KEYCODE_VOLUME_UP: { + if (K9.useVolumeKeysForListNavigationEnabled()) { + int currentPosition = mListView.getSelectedItemPosition(); + if (currentPosition == AdapterView.INVALID_POSITION || mListView.isInTouchMode()) { + currentPosition = mListView.getFirstVisiblePosition(); } - return false; + if (currentPosition > 0) { + mListView.setSelection(currentPosition - 1); + } + return true; } - case KeyEvent.KEYCODE_VOLUME_DOWN: - { - if (K9.useVolumeKeysForListNavigationEnabled()) - { - int currentPosition = mListView.getSelectedItemPosition(); - if (currentPosition == AdapterView.INVALID_POSITION || mListView.isInTouchMode()) - { - currentPosition = mListView.getFirstVisiblePosition(); - } + return false; + } + case KeyEvent.KEYCODE_VOLUME_DOWN: { + if (K9.useVolumeKeysForListNavigationEnabled()) { + int currentPosition = mListView.getSelectedItemPosition(); + if (currentPosition == AdapterView.INVALID_POSITION || mListView.isInTouchMode()) { + currentPosition = mListView.getFirstVisiblePosition(); + } - if (currentPosition < mListView.getCount()) - { - mListView.setSelection(currentPosition + 1); - } - return true; + if (currentPosition < mListView.getCount()) { + mListView.setSelection(currentPosition + 1); } + return true; + } + return false; + } + case KeyEvent.KEYCODE_DPAD_LEFT: { + if (mBatchButtonArea.hasFocus()) { return false; - } - case KeyEvent.KEYCODE_DPAD_LEFT: - { - if (mBatchButtonArea.hasFocus()) - { - return false; - } - else - { - return true; - } - } - case KeyEvent.KEYCODE_DPAD_RIGHT: - { - if (mBatchButtonArea.hasFocus()) - { - return false; - } - else - { - return true; - } - } - case KeyEvent.KEYCODE_C: - { - onCompose(); + } else { return true; } - case KeyEvent.KEYCODE_Q: - { - onShowFolderList(); - return true; - } - case KeyEvent.KEYCODE_O: - { - onCycleSort(); - return true; - } - case KeyEvent.KEYCODE_I: - { - onToggleSortAscending(); - return true; - } - case KeyEvent.KEYCODE_H: - { - Toast toast = Toast.makeText(this, R.string.message_list_help_key, Toast.LENGTH_LONG); - toast.show(); + } + case KeyEvent.KEYCODE_DPAD_RIGHT: { + if (mBatchButtonArea.hasFocus()) { + return false; + } else { return true; } } + case KeyEvent.KEYCODE_C: { + onCompose(); + return true; + } + case KeyEvent.KEYCODE_Q: { + onShowFolderList(); + return true; + } + case KeyEvent.KEYCODE_O: { + onCycleSort(); + return true; + } + case KeyEvent.KEYCODE_I: { + onToggleSortAscending(); + return true; + } + case KeyEvent.KEYCODE_H: { + Toast toast = Toast.makeText(this, R.string.message_list_help_key, Toast.LENGTH_LONG); + toast.show(); + return true; + } + } boolean retval = true; int position = mListView.getSelectedItemPosition(); - try - { - if (position >= 0) - { + try { + if (position >= 0) { MessageInfoHolder message = (MessageInfoHolder) mAdapter.getItem(position); - if (message != null) - { - switch (keyCode) - { - case KeyEvent.KEYCODE_DEL: - { - onDelete(message, position); - return true; - } - case KeyEvent.KEYCODE_S: - { - setSelected(message, !message.selected); - return true; - } - case KeyEvent.KEYCODE_D: - { - onDelete(message, position); - return true; - } - case KeyEvent.KEYCODE_F: - { - onForward(message); - return true; - } - case KeyEvent.KEYCODE_A: - { - onReplyAll(message); - return true; - } - case KeyEvent.KEYCODE_R: - { - onReply(message); - return true; - } - case KeyEvent.KEYCODE_G: - { - onToggleFlag(message); - return true; - } - case KeyEvent.KEYCODE_M: - { - onMove(message); - return true; - } - case KeyEvent.KEYCODE_V: - { - onArchive(message); - return true; - } - case KeyEvent.KEYCODE_Y: - { - onCopy(message); - return true; - } - case KeyEvent.KEYCODE_Z: - { - onToggleRead(message); - return true; - } + if (message != null) { + switch (keyCode) { + case KeyEvent.KEYCODE_DEL: { + onDelete(message, position); + return true; + } + case KeyEvent.KEYCODE_S: { + setSelected(message, !message.selected); + return true; + } + case KeyEvent.KEYCODE_D: { + onDelete(message, position); + return true; + } + case KeyEvent.KEYCODE_F: { + onForward(message); + return true; + } + case KeyEvent.KEYCODE_A: { + onReplyAll(message); + return true; + } + case KeyEvent.KEYCODE_R: { + onReply(message); + return true; + } + case KeyEvent.KEYCODE_G: { + onToggleFlag(message); + return true; + } + case KeyEvent.KEYCODE_M: { + onMove(message); + return true; + } + case KeyEvent.KEYCODE_V: { + onArchive(message); + return true; + } + case KeyEvent.KEYCODE_Y: { + onCopy(message); + return true; + } + case KeyEvent.KEYCODE_Z: { + onToggleRead(message); + return true; + } } } } - } - finally - { + } finally { retval = super.onKeyDown(keyCode, event); } return retval; } @Override - public boolean onKeyUp(int keyCode, KeyEvent event) - { + public boolean onKeyUp(int keyCode, KeyEvent event) { // Swallow these events too to avoid the audible notification of a volume change - if (K9.useVolumeKeysForListNavigationEnabled()) - { - if ((keyCode == KeyEvent.KEYCODE_VOLUME_UP) || (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)) - { + if (K9.useVolumeKeysForListNavigationEnabled()) { + if ((keyCode == KeyEvent.KEYCODE_VOLUME_UP) || (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)) { if (K9.DEBUG) Log.v(K9.LOG_TAG, "Swallowed key up."); return true; } } - return super.onKeyUp(keyCode,event); + return super.onKeyUp(keyCode, event); } - private void onResendMessage(MessageInfoHolder message) - { + private void onResendMessage(MessageInfoHolder message) { MessageCompose.actionEditDraft(this, message.message.getFolder().getAccount(), message.message); } - private void onOpenMessage(MessageInfoHolder message) - { - if (message.folder.name.equals(message.message.getFolder().getAccount().getDraftsFolderName())) - { + private void onOpenMessage(MessageInfoHolder message) { + if (message.folder.name.equals(message.message.getFolder().getAccount().getDraftsFolderName())) { MessageCompose.actionEditDraft(this, message.message.getFolder().getAccount(), message.message); - } - else - { + } else { // Need to get the list before the sort starts ArrayList messageRefs = new ArrayList(); - synchronized (mAdapter.messages) - { - for (MessageInfoHolder holder : mAdapter.messages) - { + synchronized (mAdapter.messages) { + for (MessageInfoHolder holder : mAdapter.messages) { MessageReference ref = holder.message.makeMessageReference(); messageRefs.add(ref); } @@ -1197,58 +998,45 @@ public class MessageList * then go away. I've gone back and forth on this, and this gives a * better UI experience, so I am putting it back in. */ - if (!message.read) - { + if (!message.read) { message.read = true; } } - private void onAccounts() - { + private void onAccounts() { Accounts.listAccounts(this); finish(); } - private void onShowFolderList() - { + private void onShowFolderList() { FolderList.actionHandleAccount(this, mAccount); finish(); } - private void onCompose() - { - if (mQueryString != null) - { + private void onCompose() { + if (mQueryString != null) { /* * If we have a query string, we don't have an account to let * compose start the default action. */ MessageCompose.actionCompose(this, null); - } - else - { + } else { MessageCompose.actionCompose(this, mAccount); } } - private void onEditPrefs() - { + private void onEditPrefs() { Prefs.actionPrefs(this); } - private void onEditAccount() - { + private void onEditAccount() { AccountSettings.actionSettings(this, mAccount); } - private void changeSort(SORT_TYPE newSortType) - { - if (sortType == newSortType) - { + private void changeSort(SORT_TYPE newSortType) { + if (sortType == newSortType) { onToggleSortAscending(); - } - else - { + } else { sortType = newSortType; mController.setSortType(sortType); sortAscending = mController.isSortAscending(sortType); @@ -1257,8 +1045,7 @@ public class MessageList } } - private void reSort() - { + private void reSort() { int toastString = sortType.getToast(sortAscending); Toast toast = Toast.makeText(this, toastString, Toast.LENGTH_SHORT); @@ -1267,15 +1054,12 @@ public class MessageList mHandler.sortMessages(); } - private void onCycleSort() - { + private void onCycleSort() { SORT_TYPE[] sorts = SORT_TYPE.values(); int curIndex = 0; - for (int i = 0; i < sorts.length; i++) - { - if (sorts[i] == sortType) - { + for (int i = 0; i < sorts.length; i++) { + if (sorts[i] == sortType) { curIndex = i; break; } @@ -1283,16 +1067,14 @@ public class MessageList curIndex++; - if (curIndex == sorts.length) - { + if (curIndex == sorts.length) { curIndex = 0; } changeSort(sorts[curIndex]); } - private void onToggleSortAscending() - { + private void onToggleSortAscending() { mController.setSortAscending(sortType, !sortAscending); sortAscending = mController.isSortAscending(sortType); @@ -1301,21 +1083,17 @@ public class MessageList reSort(); } - private void onDelete(MessageInfoHolder holder, int position) - { + private void onDelete(MessageInfoHolder holder, int position) { mAdapter.removeMessage(holder); mController.deleteMessages(new Message[] { holder.message }, null); } - private void onMove(MessageInfoHolder holder) - { - if (!mController.isMoveCapable(holder.message.getFolder().getAccount())) - { + private void onMove(MessageInfoHolder holder) { + if (!mController.isMoveCapable(holder.message.getFolder().getAccount())) { return; } - if (!mController.isMoveCapable(holder.message)) - { + if (!mController.isMoveCapable(holder.message)) { Toast toast = Toast.makeText(this, R.string.move_copy_cannot_copy_unsynced_message, Toast.LENGTH_LONG); toast.show(); return; @@ -1331,15 +1109,12 @@ public class MessageList startActivityForResult(intent, ACTIVITY_CHOOSE_FOLDER_MOVE); } - private void onArchive(MessageInfoHolder holder) - { - if (!mController.isMoveCapable(holder.message.getFolder().getAccount())) - { + private void onArchive(MessageInfoHolder holder) { + if (!mController.isMoveCapable(holder.message.getFolder().getAccount())) { return; } - if (!mController.isMoveCapable(holder.message)) - { + if (!mController.isMoveCapable(holder.message)) { Toast toast = Toast.makeText(this, R.string.move_copy_cannot_copy_unsynced_message, Toast.LENGTH_LONG); toast.show(); return; @@ -1348,15 +1123,12 @@ public class MessageList onMoveChosen(holder, holder.message.getFolder().getAccount().getArchiveFolderName()); } - private void onSpam(MessageInfoHolder holder) - { - if (!mController.isMoveCapable(holder.message.getFolder().getAccount())) - { + private void onSpam(MessageInfoHolder holder) { + if (!mController.isMoveCapable(holder.message.getFolder().getAccount())) { return; } - if (!mController.isMoveCapable(holder.message)) - { + if (!mController.isMoveCapable(holder.message)) { Toast toast = Toast.makeText(this, R.string.move_copy_cannot_copy_unsynced_message, Toast.LENGTH_LONG); toast.show(); return; @@ -1365,15 +1137,12 @@ public class MessageList onMoveChosen(holder, holder.message.getFolder().getAccount().getSpamFolderName()); } - private void onCopy(MessageInfoHolder holder) - { - if (!mController.isCopyCapable(holder.message.getFolder().getAccount())) - { + private void onCopy(MessageInfoHolder holder) { + if (!mController.isCopyCapable(holder.message.getFolder().getAccount())) { return; } - if (!mController.isCopyCapable(holder.message)) - { + if (!mController.isCopyCapable(holder.message)) { Toast toast = Toast.makeText(this, R.string.move_copy_cannot_copy_unsynced_message, Toast.LENGTH_LONG); toast.show(); return; @@ -1390,71 +1159,61 @@ public class MessageList } @Override - protected void onActivityResult(int requestCode, int resultCode, Intent data) - { + protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode != RESULT_OK) return; - switch (requestCode) - { - case ACTIVITY_CHOOSE_FOLDER_MOVE: - case ACTIVITY_CHOOSE_FOLDER_COPY: - { - if (data == null) - return; + switch (requestCode) { + case ACTIVITY_CHOOSE_FOLDER_MOVE: + case ACTIVITY_CHOOSE_FOLDER_COPY: { + if (data == null) + return; - final String destFolderName = data.getStringExtra(ChooseFolder.EXTRA_NEW_FOLDER); - final MessageReference ref = (MessageReference)data.getSerializableExtra(ChooseFolder.EXTRA_MESSAGE); - final MessageInfoHolder m = mAdapter.getMessage(ref); + final String destFolderName = data.getStringExtra(ChooseFolder.EXTRA_NEW_FOLDER); + final MessageReference ref = (MessageReference)data.getSerializableExtra(ChooseFolder.EXTRA_MESSAGE); + final MessageInfoHolder m = mAdapter.getMessage(ref); - if ((destFolderName != null) && (m != null)) - { - final Account account = m.message.getFolder().getAccount(); - - account.setLastSelectedFolderName(destFolderName); - - switch (requestCode) - { - case ACTIVITY_CHOOSE_FOLDER_MOVE: - onMoveChosen(m, destFolderName); - break; - - case ACTIVITY_CHOOSE_FOLDER_COPY: - onCopyChosen(m, destFolderName); - break; - } - } - break; - } - case ACTIVITY_CHOOSE_FOLDER_MOVE_BATCH: - case ACTIVITY_CHOOSE_FOLDER_COPY_BATCH: - { - final String destFolderName = data.getStringExtra(ChooseFolder.EXTRA_NEW_FOLDER); - final String accountUuid = data.getStringExtra(ChooseFolder.EXTRA_ACCOUNT); - final Account account = Preferences.getPreferences(this).getAccount(accountUuid); + if ((destFolderName != null) && (m != null)) { + final Account account = m.message.getFolder().getAccount(); account.setLastSelectedFolderName(destFolderName); - switch (requestCode) - { - case ACTIVITY_CHOOSE_FOLDER_MOVE_BATCH: - onMoveChosenBatch(destFolderName); - break; + switch (requestCode) { + case ACTIVITY_CHOOSE_FOLDER_MOVE: + onMoveChosen(m, destFolderName); + break; - case ACTIVITY_CHOOSE_FOLDER_COPY_BATCH: - onCopyChosenBatch(destFolderName); - break; + case ACTIVITY_CHOOSE_FOLDER_COPY: + onCopyChosen(m, destFolderName); + break; } } + break; + } + case ACTIVITY_CHOOSE_FOLDER_MOVE_BATCH: + case ACTIVITY_CHOOSE_FOLDER_COPY_BATCH: { + final String destFolderName = data.getStringExtra(ChooseFolder.EXTRA_NEW_FOLDER); + final String accountUuid = data.getStringExtra(ChooseFolder.EXTRA_ACCOUNT); + final Account account = Preferences.getPreferences(this).getAccount(accountUuid); + + account.setLastSelectedFolderName(destFolderName); + + switch (requestCode) { + case ACTIVITY_CHOOSE_FOLDER_MOVE_BATCH: + onMoveChosenBatch(destFolderName); + break; + + case ACTIVITY_CHOOSE_FOLDER_COPY_BATCH: + onCopyChosenBatch(destFolderName); + break; + } + } } } - private void onMoveChosen(MessageInfoHolder holder, String folderName) - { - if (mController.isMoveCapable(holder.message.getFolder().getAccount()) && folderName != null) - { - if (K9.FOLDER_NONE.equalsIgnoreCase(folderName)) - { + private void onMoveChosen(MessageInfoHolder holder, String folderName) { + if (mController.isMoveCapable(holder.message.getFolder().getAccount()) && folderName != null) { + if (K9.FOLDER_NONE.equalsIgnoreCase(folderName)) { return; } mAdapter.removeMessage(holder); @@ -1462,305 +1221,242 @@ public class MessageList } } - private void onCopyChosen(MessageInfoHolder holder, String folderName) - { - if (mController.isCopyCapable(holder.message.getFolder().getAccount()) && folderName != null) - { + private void onCopyChosen(MessageInfoHolder holder, String folderName) { + if (mController.isCopyCapable(holder.message.getFolder().getAccount()) && folderName != null) { mController.copyMessage(holder.message.getFolder().getAccount(), holder.message.getFolder().getName(), holder.message, folderName, null); } } - private void onReply(MessageInfoHolder holder) - { + private void onReply(MessageInfoHolder holder) { MessageCompose.actionReply(this, holder.message.getFolder().getAccount(), holder.message, false, null); } - private void onReplyAll(MessageInfoHolder holder) - { + private void onReplyAll(MessageInfoHolder holder) { MessageCompose.actionReply(this, holder.message.getFolder().getAccount(), holder.message, true, null); } - private void onForward(MessageInfoHolder holder) - { + private void onForward(MessageInfoHolder holder) { MessageCompose.actionForward(this, holder.message.getFolder().getAccount(), holder.message, null); } - private void onMarkAllAsRead(final Account account, final String folder) - { + private void onMarkAllAsRead(final Account account, final String folder) { showDialog(DIALOG_MARK_ALL_AS_READ); } - private void onExpunge(final Account account, String folderName) - { + private void onExpunge(final Account account, String folderName) { mController.expunge(account, folderName, null); } @Override - public Dialog onCreateDialog(int id) - { - switch (id) - { - case DIALOG_MARK_ALL_AS_READ: - return createMarkAllAsReadDialog(); + public Dialog onCreateDialog(int id) { + switch (id) { + case DIALOG_MARK_ALL_AS_READ: + return createMarkAllAsReadDialog(); } return super.onCreateDialog(id); } @Override - public void onPrepareDialog(int id, Dialog dialog) - { - switch (id) - { - case DIALOG_MARK_ALL_AS_READ: - { - if (mCurrentFolder != null) - { - ((AlertDialog)dialog).setMessage(getString(R.string.mark_all_as_read_dlg_instructions_fmt, - mCurrentFolder.displayName)); - } - break; - } - default: - { - super.onPrepareDialog(id, dialog); + public void onPrepareDialog(int id, Dialog dialog) { + switch (id) { + case DIALOG_MARK_ALL_AS_READ: { + if (mCurrentFolder != null) { + ((AlertDialog)dialog).setMessage(getString(R.string.mark_all_as_read_dlg_instructions_fmt, + mCurrentFolder.displayName)); } + break; + } + default: { + super.onPrepareDialog(id, dialog); + } } } - private Dialog createMarkAllAsReadDialog() - { + private Dialog createMarkAllAsReadDialog() { return new AlertDialog.Builder(this) .setTitle(R.string.mark_all_as_read_dlg_title) .setMessage(getString(R.string.mark_all_as_read_dlg_instructions_fmt, mCurrentFolder.displayName)) - .setPositiveButton(R.string.okay_action, new DialogInterface.OnClickListener() - { - public void onClick(DialogInterface dialog, int whichButton) - { + .setPositiveButton(R.string.okay_action, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int whichButton) { dismissDialog(DIALOG_MARK_ALL_AS_READ); - try - { + try { mController.markAllMessagesRead(mAccount, mCurrentFolder.name); - synchronized (mAdapter.messages) - { - for (MessageInfoHolder holder : mAdapter.messages) - { + synchronized (mAdapter.messages) { + for (MessageInfoHolder holder : mAdapter.messages) { holder.read = true; } } mHandler.sortMessages(); - } - catch (Exception e) - { + } catch (Exception e) { // Ignore } } }) - .setNegativeButton(R.string.cancel_action, new DialogInterface.OnClickListener() - { - public void onClick(DialogInterface dialog, int whichButton) - { + .setNegativeButton(R.string.cancel_action, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int whichButton) { dismissDialog(DIALOG_MARK_ALL_AS_READ); } }) .create(); } - private void onToggleRead(MessageInfoHolder holder) - { + private void onToggleRead(MessageInfoHolder holder) { mController.setFlag(holder.message.getFolder().getAccount(), holder.message.getFolder().getName(), new String[] { holder.uid }, Flag.SEEN, !holder.read); holder.read = !holder.read; mHandler.sortMessages(); } - private void onToggleFlag(MessageInfoHolder holder) - { + private void onToggleFlag(MessageInfoHolder holder) { mController.setFlag(holder.message.getFolder().getAccount(), holder.message.getFolder().getName(), new String[] { holder.uid }, Flag.FLAGGED, !holder.flagged); holder.flagged = !holder.flagged; mHandler.sortMessages(); } - private void checkMail(Account account, String folderName) - { + private void checkMail(Account account, String folderName) { mController.synchronizeMailbox(account, folderName, mAdapter.mListener, null); mController.sendPendingMessages(account, mAdapter.mListener); } @Override - public boolean onOptionsItemSelected(MenuItem item) - { + public boolean onOptionsItemSelected(MenuItem item) { int itemId = item.getItemId(); - switch (itemId) - { - case R.id.compose: - { - onCompose(); - return true; - } - case R.id.accounts: - { - onAccounts(); - return true; - } - case R.id.set_sort_date: - { - changeSort(SORT_TYPE.SORT_DATE); - return true; - } - case R.id.set_sort_subject: - { - changeSort(SORT_TYPE.SORT_SUBJECT); - return true; - } - case R.id.set_sort_sender: - { - changeSort(SORT_TYPE.SORT_SENDER); - return true; - } - case R.id.set_sort_flag: - { - changeSort(SORT_TYPE.SORT_FLAGGED); - return true; - } - case R.id.set_sort_unread: - { - changeSort(SORT_TYPE.SORT_UNREAD); - return true; - } - case R.id.set_sort_attach: - { - changeSort(SORT_TYPE.SORT_ATTACHMENT); - return true; - } - case R.id.select_all: - case R.id.batch_select_all: - { - setAllSelected(true); - toggleBatchButtons(); - return true; - } - case R.id.batch_deselect_all: - { - setAllSelected(false); - toggleBatchButtons(); - return true; - } - case R.id.batch_delete_op: - { - deleteSelected(); - return true; - } - case R.id.batch_mark_read_op: - { - flagSelected(Flag.SEEN, true); - return true; - } - case R.id.batch_mark_unread_op: - { - flagSelected(Flag.SEEN, false); - return true; - } - case R.id.batch_flag_op: - { - flagSelected(Flag.FLAGGED, true); - return true; - } - case R.id.batch_unflag_op: - { - flagSelected(Flag.FLAGGED, false); - return true; - } - case R.id.app_settings: - { - onEditPrefs(); - return true; - } + switch (itemId) { + case R.id.compose: { + onCompose(); + return true; + } + case R.id.accounts: { + onAccounts(); + return true; + } + case R.id.set_sort_date: { + changeSort(SORT_TYPE.SORT_DATE); + return true; + } + case R.id.set_sort_subject: { + changeSort(SORT_TYPE.SORT_SUBJECT); + return true; + } + case R.id.set_sort_sender: { + changeSort(SORT_TYPE.SORT_SENDER); + return true; + } + case R.id.set_sort_flag: { + changeSort(SORT_TYPE.SORT_FLAGGED); + return true; + } + case R.id.set_sort_unread: { + changeSort(SORT_TYPE.SORT_UNREAD); + return true; + } + case R.id.set_sort_attach: { + changeSort(SORT_TYPE.SORT_ATTACHMENT); + return true; + } + case R.id.select_all: + case R.id.batch_select_all: { + setAllSelected(true); + toggleBatchButtons(); + return true; + } + case R.id.batch_deselect_all: { + setAllSelected(false); + toggleBatchButtons(); + return true; + } + case R.id.batch_delete_op: { + deleteSelected(); + return true; + } + case R.id.batch_mark_read_op: { + flagSelected(Flag.SEEN, true); + return true; + } + case R.id.batch_mark_unread_op: { + flagSelected(Flag.SEEN, false); + return true; + } + case R.id.batch_flag_op: { + flagSelected(Flag.FLAGGED, true); + return true; + } + case R.id.batch_unflag_op: { + flagSelected(Flag.FLAGGED, false); + return true; + } + case R.id.app_settings: { + onEditPrefs(); + return true; + } } - if (mQueryString != null) - { + if (mQueryString != null) { // None of the options after this point are "safe" for search results //TODO: This is not true for "unread" and "starred" searches in regular folders return false; } - switch (itemId) - { - case R.id.check_mail: - { - if (mFolderName != null) - { - checkMail(mAccount, mFolderName); - } - return true; + switch (itemId) { + case R.id.check_mail: { + if (mFolderName != null) { + checkMail(mAccount, mFolderName); } - case R.id.send_messages: - { - mController.sendPendingMessages(mAccount, mAdapter.mListener); - return true; + return true; + } + case R.id.send_messages: { + mController.sendPendingMessages(mAccount, mAdapter.mListener); + return true; + } + case R.id.list_folders: { + onShowFolderList(); + return true; + } + case R.id.mark_all_as_read: { + if (mFolderName != null) { + onMarkAllAsRead(mAccount, mFolderName); } - case R.id.list_folders: - { - onShowFolderList(); - return true; + return true; + } + case R.id.folder_settings: { + if (mFolderName != null) { + FolderSettings.actionSettings(this, mAccount, mFolderName); } - case R.id.mark_all_as_read: - { - if (mFolderName != null) - { - onMarkAllAsRead(mAccount, mFolderName); - } - return true; - } - case R.id.folder_settings: - { - if (mFolderName != null) - { - FolderSettings.actionSettings(this, mAccount, mFolderName); - } - return true; - } - case R.id.account_settings: - { - onEditAccount(); - return true; - } - case R.id.batch_copy_op: - { - onCopyBatch(); - return true; - } - case R.id.batch_archive_op: - { - onArchiveBatch(); - return true; - } - case R.id.batch_spam_op: - { - onSpamBatch(); - return true; - } - case R.id.batch_move_op: - { - onMoveBatch(); - return true; - } - case R.id.expunge: - { - if (mCurrentFolder != null) - { - onExpunge(mAccount, mCurrentFolder.name); - } - return true; - } - default: - { - return super.onOptionsItemSelected(item); + return true; + } + case R.id.account_settings: { + onEditAccount(); + return true; + } + case R.id.batch_copy_op: { + onCopyBatch(); + return true; + } + case R.id.batch_archive_op: { + onArchiveBatch(); + return true; + } + case R.id.batch_spam_op: { + onSpamBatch(); + return true; + } + case R.id.batch_move_op: { + onMoveBatch(); + return true; + } + case R.id.expunge: { + if (mCurrentFolder != null) { + onExpunge(mAccount, mCurrentFolder.name); } + return true; + } + default: { + return super.onOptionsItemSelected(item); + } } } @@ -1770,18 +1466,15 @@ public class MessageList R.id.batch_select_all, R.id.batch_deselect_all }; - private void setOpsState(Menu menu, boolean state, boolean enabled) - { - for (int id : batch_ops) - { + private void setOpsState(Menu menu, boolean state, boolean enabled) { + for (int id : batch_ops) { menu.findItem(id).setVisible(state); menu.findItem(id).setEnabled(enabled); } } @Override - public boolean onPrepareOptionsMenu(Menu menu) - { + public boolean onPrepareOptionsMenu(Menu menu) { boolean anySelected = anySelected(); menu.findItem(R.id.select_all).setVisible(! anySelected); @@ -1789,8 +1482,7 @@ public class MessageList setOpsState(menu, true, anySelected); - if (mQueryString != null) - { + if (mQueryString != null) { menu.findItem(R.id.mark_all_as_read).setVisible(false); menu.findItem(R.id.list_folders).setVisible(false); menu.findItem(R.id.expunge).setVisible(false); @@ -1802,28 +1494,20 @@ public class MessageList menu.findItem(R.id.send_messages).setVisible(false); menu.findItem(R.id.folder_settings).setVisible(false); menu.findItem(R.id.account_settings).setVisible(false); - } - else - { - if (mCurrentFolder != null && mCurrentFolder.name.equals(mAccount.getOutboxFolderName())) - { + } else { + if (mCurrentFolder != null && mCurrentFolder.name.equals(mAccount.getOutboxFolderName())) { menu.findItem(R.id.check_mail).setVisible(false); - } - else - { + } else { menu.findItem(R.id.send_messages).setVisible(false); } - if (mCurrentFolder != null && K9.ERROR_FOLDER_NAME.equals(mCurrentFolder.name)) - { + if (mCurrentFolder != null && K9.ERROR_FOLDER_NAME.equals(mCurrentFolder.name)) { menu.findItem(R.id.expunge).setVisible(false); } - if (K9.FOLDER_NONE.equalsIgnoreCase(mAccount.getArchiveFolderName())) - { + if (K9.FOLDER_NONE.equalsIgnoreCase(mAccount.getArchiveFolderName())) { menu.findItem(R.id.batch_archive_op).setVisible(false); } - if (K9.FOLDER_NONE.equalsIgnoreCase(mAccount.getSpamFolderName())) - { + if (K9.FOLDER_NONE.equalsIgnoreCase(mAccount.getSpamFolderName())) { menu.findItem(R.id.batch_spam_op).setVisible(false); } } @@ -1841,8 +1525,7 @@ public class MessageList } @Override - public boolean onCreateOptionsMenu(Menu menu) - { + public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.message_list_option, menu); @@ -1850,136 +1533,109 @@ public class MessageList } @Override - public boolean onContextItemSelected(MenuItem item) - { + public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); MessageInfoHolder holder = mSelectedMessage; // don't need this anymore mSelectedMessage = null; - if (holder == null) - { + if (holder == null) { holder = (MessageInfoHolder) mAdapter.getItem(info.position); } - switch (item.getItemId()) - { - case R.id.open: - { - onOpenMessage(holder); - break; - } - case R.id.select: - { - setSelected(holder, true); - break; - } - case R.id.deselect: - { - setSelected(holder, false); - break; - } - case R.id.delete: - { - onDelete(holder, info.position); - break; - } - case R.id.reply: - { - onReply(holder); - break; - } - case R.id.reply_all: - { - onReplyAll(holder); - break; - } - case R.id.forward: - { - onForward(holder); - break; - } - case R.id.send_again: - { - onResendMessage(holder); - break; + switch (item.getItemId()) { + case R.id.open: { + onOpenMessage(holder); + break; + } + case R.id.select: { + setSelected(holder, true); + break; + } + case R.id.deselect: { + setSelected(holder, false); + break; + } + case R.id.delete: { + onDelete(holder, info.position); + break; + } + case R.id.reply: { + onReply(holder); + break; + } + case R.id.reply_all: { + onReplyAll(holder); + break; + } + case R.id.forward: { + onForward(holder); + break; + } + case R.id.send_again: { + onResendMessage(holder); + break; - } - case R.id.mark_as_read: - { - onToggleRead(holder); - break; - } - case R.id.flag: - { - onToggleFlag(holder); - break; - } - case R.id.archive: - { - onArchive(holder); - break; - } - case R.id.spam: - { - onSpam(holder); - break; - } - case R.id.move: - { - onMove(holder); - break; - } - case R.id.copy: - { - onCopy(holder); - break; - } - case R.id.send_alternate: - { - onSendAlternate(mAccount, holder); - break; - } - case R.id.same_sender: - { - MessageList.actionHandle(MessageList.this, - "From "+holder.sender, holder.senderAddress, true, - null, null); - break; - } + } + case R.id.mark_as_read: { + onToggleRead(holder); + break; + } + case R.id.flag: { + onToggleFlag(holder); + break; + } + case R.id.archive: { + onArchive(holder); + break; + } + case R.id.spam: { + onSpam(holder); + break; + } + case R.id.move: { + onMove(holder); + break; + } + case R.id.copy: { + onCopy(holder); + break; + } + case R.id.send_alternate: { + onSendAlternate(mAccount, holder); + break; + } + case R.id.same_sender: { + MessageList.actionHandle(MessageList.this, + "From " + holder.sender, holder.senderAddress, true, + null, null); + break; + } } return super.onContextItemSelected(item); } - public void onSendAlternate(Account account, MessageInfoHolder holder) - { + public void onSendAlternate(Account account, MessageInfoHolder holder) { mController.sendAlternate(this, account, holder.message); } - public void showProgressIndicator(boolean status) - { + public void showProgressIndicator(boolean status) { setProgressBarIndeterminateVisibility(status); ProgressBar bar = (ProgressBar)mListView.findViewById(R.id.message_list_progress); - if (bar == null) - { + if (bar == null) { return; } bar.setIndeterminate(true); - if (status) - { + if (status) { bar.setVisibility(ProgressBar.VISIBLE); - } - else - { + } else { bar.setVisibility(ProgressBar.INVISIBLE); } } - class MyGestureDetector extends SimpleOnGestureListener - { + class MyGestureDetector extends SimpleOnGestureListener { @Override - public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) - { + public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { if (e2 == null || e1 == null) return true; @@ -1989,17 +1645,14 @@ public class MessageList boolean movedAcross = (Math.abs(deltaX) > Math.abs(deltaY * 4)); boolean steadyHand = (Math.abs(deltaX / deltaY) > 2); - if (movedAcross && steadyHand) - { + if (movedAcross && steadyHand) { boolean selected = (deltaX > 0); int position = mListView.pointToPosition((int)e1.getX(), (int)e1.getY()); - if (position != AdapterView.INVALID_POSITION) - { + if (position != AdapterView.INVALID_POSITION) { MessageInfoHolder msgInfoHolder = (MessageInfoHolder) mAdapter.getItem(position); - if (msgInfoHolder != null && msgInfoHolder.selected != selected) - { + if (msgInfoHolder != null && msgInfoHolder.selected != selected) { msgInfoHolder.selected = selected; mSelectedCount += (selected ? 1 : -1); mAdapter.notifyDataSetChanged(); @@ -2013,8 +1666,7 @@ public class MessageList } @Override - public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) - { + public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; @@ -2023,8 +1675,7 @@ public class MessageList // dialog is up mSelectedMessage = message; - if (message == null) - { + if (message == null) { return; } @@ -2032,80 +1683,65 @@ public class MessageList menu.setHeaderTitle(message.message.getSubject()); - if (message.read) - { + if (message.read) { menu.findItem(R.id.mark_as_read).setTitle(R.string.mark_as_unread_action); } - if (message.flagged) - { + if (message.flagged) { menu.findItem(R.id.flag).setTitle(R.string.unflag_action); } Account account = message.message.getFolder().getAccount(); - if (!mController.isCopyCapable(account)) - { + if (!mController.isCopyCapable(account)) { menu.findItem(R.id.copy).setVisible(false); } - if (!mController.isMoveCapable(account)) - { + if (!mController.isMoveCapable(account)) { menu.findItem(R.id.move).setVisible(false); menu.findItem(R.id.archive).setVisible(false); menu.findItem(R.id.spam).setVisible(false); } - if (K9.FOLDER_NONE.equalsIgnoreCase(account.getArchiveFolderName())) - { + if (K9.FOLDER_NONE.equalsIgnoreCase(account.getArchiveFolderName())) { menu.findItem(R.id.archive).setVisible(false); } - if (K9.FOLDER_NONE.equalsIgnoreCase(account.getSpamFolderName())) - { + if (K9.FOLDER_NONE.equalsIgnoreCase(account.getSpamFolderName())) { menu.findItem(R.id.spam).setVisible(false); } - if (message.selected) - { + if (message.selected) { menu.findItem(R.id.select).setVisible(false); menu.findItem(R.id.deselect).setVisible(true); - } - else - { + } else { menu.findItem(R.id.select).setVisible(true); menu.findItem(R.id.deselect).setVisible(false); } } - class MessageListAdapter extends BaseAdapter - { + class MessageListAdapter extends BaseAdapter { private final List messages = java.util.Collections.synchronizedList(new ArrayList()); - private final ActivityListener mListener = new ActivityListener() - { + private final ActivityListener mListener = new ActivityListener() { @Override - public void synchronizeMailboxStarted(Account account, String folder) - { + public void synchronizeMailboxStarted(Account account, String folder) { super.synchronizeMailboxStarted(account, folder); - if (updateForMe(account, folder)) - { + if (updateForMe(account, folder)) { mHandler.progress(true); mHandler.folderLoading(folder, true); } mHandler.refreshTitle(); } @Override - public void synchronizeMailboxHeadersProgress(Account account, String folder, int completed, int total) - { - super.synchronizeMailboxHeadersProgress(account,folder,completed, total); + public void synchronizeMailboxHeadersProgress(Account account, String folder, int completed, int total) { + super.synchronizeMailboxHeadersProgress(account, folder, completed, total); mHandler.refreshTitle(); } @Override public void synchronizeMailboxHeadersFinished(Account account, String folder, - int total, int completed) - { - super.synchronizeMailboxHeadersFinished(account,folder, total, completed); + int total, int completed) { + super.synchronizeMailboxHeadersFinished(account, folder, total, completed); mHandler.refreshTitle(); } @@ -2114,12 +1750,10 @@ public class MessageList @Override public void synchronizeMailboxFinished(Account account, String folder, - int totalMessagesInMailbox, int numNewMessages) - { + int totalMessagesInMailbox, int numNewMessages) { super.synchronizeMailboxFinished(account, folder, totalMessagesInMailbox, numNewMessages); - if (updateForMe(account, folder)) - { + if (updateForMe(account, folder)) { mHandler.progress(false); mHandler.folderLoading(folder, false); mHandler.sortMessages(); @@ -2128,12 +1762,10 @@ public class MessageList } @Override - public void synchronizeMailboxFailed(Account account, String folder, String message) - { + public void synchronizeMailboxFailed(Account account, String folder, String message) { super.synchronizeMailboxFailed(account, folder, message); - if (updateForMe(account, folder)) - { + if (updateForMe(account, folder)) { mHandler.progress(false); mHandler.folderLoading(folder, false); mHandler.sortMessages(); @@ -2142,197 +1774,161 @@ public class MessageList } @Override - public void sendPendingMessagesStarted(Account account) - { + public void sendPendingMessagesStarted(Account account) { super.sendPendingMessagesStarted(account); mHandler.refreshTitle(); } @Override - public void sendPendingMessagesCompleted(Account account) - { + public void sendPendingMessagesCompleted(Account account) { super.sendPendingMessagesCompleted(account); mHandler.refreshTitle(); } @Override - public void sendPendingMessagesFailed(Account account) - { + public void sendPendingMessagesFailed(Account account) { super.sendPendingMessagesFailed(account); mHandler.refreshTitle(); } @Override - public void synchronizeMailboxProgress(Account account, String folder, int completed, int total) - { + public void synchronizeMailboxProgress(Account account, String folder, int completed, int total) { super.synchronizeMailboxProgress(account, folder, completed, total); mHandler.refreshTitle(); } @Override - public void synchronizeMailboxAddOrUpdateMessage(Account account, String folder, Message message) - { + public void synchronizeMailboxAddOrUpdateMessage(Account account, String folder, Message message) { addOrUpdateMessage(account, folder, message, true); } @Override - public void synchronizeMailboxRemovedMessage(Account account, String folder,Message message) - { + public void synchronizeMailboxRemovedMessage(Account account, String folder, Message message) { MessageInfoHolder holder = getMessage(message); - if (holder == null) - { + if (holder == null) { Log.w(K9.LOG_TAG, "Got callback to remove non-existent message with UID " + message.getUid()); - } - else - { + } else { removeMessage(holder); } } @Override - public void listLocalMessagesStarted(Account account, String folder) - { + public void listLocalMessagesStarted(Account account, String folder) { if ((mQueryString != null && folder == null) || (account != null && account.equals(mAccount)) - ) - { + ) { mHandler.progress(true); - if (folder != null) - { + if (folder != null) { mHandler.folderLoading(folder, true); } } } @Override - public void listLocalMessagesFailed(Account account, String folder, String message) - { + public void listLocalMessagesFailed(Account account, String folder, String message) { if ((mQueryString != null && folder == null) || - (account != null && account.equals(mAccount))) - { + (account != null && account.equals(mAccount))) { mHandler.sortMessages(); mHandler.progress(false); - if (folder != null) - { + if (folder != null) { mHandler.folderLoading(folder, false); } } } @Override - public void listLocalMessagesFinished(Account account, String folder) - { + public void listLocalMessagesFinished(Account account, String folder) { if ((mQueryString != null && folder == null) || - (account != null && account.equals(mAccount))) - { + (account != null && account.equals(mAccount))) { mHandler.sortMessages(); mHandler.progress(false); - if (folder != null) - { + if (folder != null) { mHandler.folderLoading(folder, false); } } } @Override - public void listLocalMessagesRemoveMessage(Account account, String folder,Message message) - { + public void listLocalMessagesRemoveMessage(Account account, String folder, Message message) { MessageInfoHolder holder = getMessage(message); - if (holder != null) - { + if (holder != null) { removeMessage(holder); } } @Override - public void listLocalMessagesAddMessages(Account account, String folder, List messages) - { + public void listLocalMessagesAddMessages(Account account, String folder, List messages) { addOrUpdateMessages(account, folder, messages, false); } @Override - public void listLocalMessagesUpdateMessage(Account account, String folder, Message message) - { + public void listLocalMessagesUpdateMessage(Account account, String folder, Message message) { addOrUpdateMessage(account, folder, message, false); } @Override - public void searchStats(AccountStats stats) - { + public void searchStats(AccountStats stats) { mUnreadMessageCount = stats.unreadMessageCount; mHandler.refreshTitle(); } @Override - public void folderStatusChanged(Account account, String folder, int unreadMessageCount) - { + public void folderStatusChanged(Account account, String folder, int unreadMessageCount) { super.folderStatusChanged(account, folder, unreadMessageCount); - if (updateForMe(account, folder)) - { + if (updateForMe(account, folder)) { mUnreadMessageCount = unreadMessageCount; mHandler.refreshTitle(); } } @Override - public void pendingCommandsProcessing(Account account) - { + public void pendingCommandsProcessing(Account account) { super.pendingCommandsProcessing(account); mHandler.refreshTitle(); } @Override - public void pendingCommandsFinished(Account account) - { + public void pendingCommandsFinished(Account account) { super.pendingCommandsFinished(account); mHandler.refreshTitle(); } @Override - public void pendingCommandStarted(Account account, String commandTitle) - { + public void pendingCommandStarted(Account account, String commandTitle) { super.pendingCommandStarted(account, commandTitle); mHandler.refreshTitle(); } @Override - public void pendingCommandCompleted(Account account, String commandTitle) - { + public void pendingCommandCompleted(Account account, String commandTitle) { super.pendingCommandCompleted(account, commandTitle); mHandler.refreshTitle(); } @Override - public void messageUidChanged(Account account, String folder, String oldUid, String newUid) - { + public void messageUidChanged(Account account, String folder, String oldUid, String newUid) { MessageReference ref = new MessageReference(); ref.accountUuid = account.getUuid(); ref.folderName = folder; ref.uid = oldUid; MessageInfoHolder holder = getMessage(ref); - if (holder != null) - { + if (holder != null) { holder.uid = newUid; holder.message.setUid(newUid); } } @Override - public void systemStatusChanged() - { + public void systemStatusChanged() { mHandler.refreshTitle(); } }; - private boolean updateForMe(Account account, String folder) - { - if ((account.equals(mAccount) && mFolderName != null && folder.equals(mFolderName))) - { + private boolean updateForMe(Account account, String folder) { + if ((account.equals(mAccount) && mFolderName != null && folder.equals(mFolderName))) { return true; - } - else - { + } else { return false; } } @@ -2341,31 +1937,23 @@ public class MessageList private Drawable mAnsweredIcon; private View footerView = null; - MessageListAdapter() - { + MessageListAdapter() { mAttachmentIcon = getResources().getDrawable(R.drawable.ic_email_attachment_small); mAnsweredIcon = getResources().getDrawable(R.drawable.ic_email_answered_small); } - public void markAllMessagesAsDirty() - { - for (MessageInfoHolder holder : mAdapter.messages) - { + public void markAllMessagesAsDirty() { + for (MessageInfoHolder holder : mAdapter.messages) { holder.dirty = true; } } - public void pruneDirtyMessages() - { - synchronized (mAdapter.messages) - { + public void pruneDirtyMessages() { + synchronized (mAdapter.messages) { Iterator iter = mAdapter.messages.iterator(); - while (iter.hasNext()) - { + while (iter.hasNext()) { MessageInfoHolder holder = iter.next(); - if (holder.dirty) - { - if (holder.selected) - { + if (holder.dirty) { + if (holder.selected) { mSelectedCount--; toggleBatchButtons(); } @@ -2375,30 +1963,25 @@ public class MessageList } } - public void removeMessages(List holders) - { - if (holders != null) - { + public void removeMessages(List holders) { + if (holders != null) { mHandler.removeMessage(holders); } } - public void removeMessage(MessageInfoHolder holder) - { + public void removeMessage(MessageInfoHolder holder) { List messages = new ArrayList(); messages.add(holder); removeMessages(messages); } - private void addOrUpdateMessage(Account account, String folderName, Message message, boolean verifyAgainstSearch) - { + private void addOrUpdateMessage(Account account, String folderName, Message message, boolean verifyAgainstSearch) { List messages = new ArrayList(); messages.add(message); addOrUpdateMessages(account, folderName, messages, verifyAgainstSearch); } - private void addOrUpdateMessages(final Account account, final String folderName, final List providedMessages, final boolean verifyAgainstSearch) - { + private void addOrUpdateMessages(final Account account, final String folderName, final List providedMessages, final boolean verifyAgainstSearch) { // we copy the message list because the callback doesn't expect // the callbacks to mutate it. final List messages = new ArrayList(providedMessages); @@ -2411,47 +1994,32 @@ public class MessageList // cache field into local variable for faster access for JVM without JIT final MessageHelper messageHelper = mMessageHelper; - for (Message message : messages) - { + for (Message message : messages) { MessageInfoHolder m = getMessage(message); - if (message.isSet(Flag.DELETED)) - { - if (m != null) - { + if (message.isSet(Flag.DELETED)) { + if (m != null) { messagesToRemove.add(m); } - } - else - { + } else { final Folder messageFolder = message.getFolder(); final Account messageAccount = messageFolder.getAccount(); - if (m == null) - { - if (updateForMe(account, folderName)) - { + if (m == null) { + if (updateForMe(account, folderName)) { m = new MessageInfoHolder(); messageHelper.populate(m, message, new FolderInfoHolder(MessageList.this, messageFolder, messageAccount), messageAccount); messagesToAdd.add(m); - } - else - { - if (mQueryString != null) - { - if (verifyAgainstSearch) - { + } else { + if (mQueryString != null) { + if (verifyAgainstSearch) { messagesToSearch.add(message); - } - else - { + } else { m = new MessageInfoHolder(); messageHelper.populate(m, message, new FolderInfoHolder(MessageList.this, messageFolder, messageAccount), messageAccount); messagesToAdd.add(m); } } } - } - else - { + } else { m.dirty = false; // as we reload the message, unset its dirty flag messageHelper.populate(m, message, new FolderInfoHolder(MessageList.this, messageFolder, account), account); needsSort = true; @@ -2459,47 +2027,37 @@ public class MessageList } } - if (messagesToSearch.size() > 0) - { + if (messagesToSearch.size() > 0) { mController.searchLocalMessages(mAccountUuids, mFolderNames, messagesToSearch.toArray(EMPTY_MESSAGE_ARRAY), mQueryString, mIntegrate, mQueryFlags, mForbiddenFlags, - new MessagingListener() - { + new MessagingListener() { @Override - public void listLocalMessagesAddMessages(Account account, String folder, List messages) - { + public void listLocalMessagesAddMessages(Account account, String folder, List messages) { addOrUpdateMessages(account, folder, messages, false); } }); } - if (messagesToRemove.size() > 0) - { + if (messagesToRemove.size() > 0) { removeMessages(messagesToRemove); } - if (messagesToAdd.size() > 0) - { + if (messagesToAdd.size() > 0) { mHandler.addMessages(messagesToAdd); } - if (needsSort) - { + if (needsSort) { mHandler.sortMessages(); mHandler.resetUnreadCount(); } } - public MessageInfoHolder getMessage(Message message) - { + public MessageInfoHolder getMessage(Message message) { return getMessage(message.makeMessageReference()); } // XXX TODO - make this not use a for loop - public MessageInfoHolder getMessage(MessageReference messageReference) - { - synchronized (mAdapter.messages) - { - for (MessageInfoHolder holder : mAdapter.messages) - { + public MessageInfoHolder getMessage(MessageReference messageReference) { + synchronized (mAdapter.messages) { + for (MessageInfoHolder holder : mAdapter.messages) { /* * 2010-06-21 - cketti * Added null pointer check. Not sure what's causing 'holder' @@ -2508,8 +2066,7 @@ public class MessageList * Please remove this comment once the cause was found and the * bug(?) fixed. */ - if ((holder != null) && holder.message.equalsReference(messageReference)) - { + if ((holder != null) && holder.message.equalsReference(messageReference)) { return holder; } } @@ -2517,24 +2074,17 @@ public class MessageList return null; } - public FolderInfoHolder getFolder(String folder, Account account) - { + public FolderInfoHolder getFolder(String folder, Account account) { LocalFolder local_folder = null; - try - { + try { LocalStore localStore = account.getLocalStore(); local_folder = localStore.getFolder(folder); return new FolderInfoHolder(context, local_folder, account); - } - catch (Exception e) - { - Log.e(K9.LOG_TAG, "getFolder(" + folder + ") goes boom: ",e); + } catch (Exception e) { + Log.e(K9.LOG_TAG, "getFolder(" + folder + ") goes boom: ", e); return null; - } - finally - { - if (local_folder != null) - { + } finally { + if (local_folder != null) { local_folder.close(); } } @@ -2542,10 +2092,8 @@ public class MessageList private static final int NON_MESSAGE_ITEMS = 1; - private final OnClickListener flagClickListener = new OnClickListener() - { - public void onClick(View v) - { + private final OnClickListener flagClickListener = new OnClickListener() { + public void onClick(View v) { // Perform action on clicks MessageInfoHolder message = (MessageInfoHolder) getItem((Integer)v.getTag()); onToggleFlag(message); @@ -2553,86 +2101,62 @@ public class MessageList }; @Override - public int getCount() - { + public int getCount() { return messages.size() + NON_MESSAGE_ITEMS; } @Override - public long getItemId(int position) - { - try - { - MessageInfoHolder messageHolder =(MessageInfoHolder) getItem(position); - if (messageHolder != null) - { + public long getItemId(int position) { + try { + MessageInfoHolder messageHolder = (MessageInfoHolder) getItem(position); + if (messageHolder != null) { return messageHolder.message.getId(); } - } - catch (Exception e) - { - Log.i(K9.LOG_TAG,"getItemId("+position+") ",e); + } catch (Exception e) { + Log.i(K9.LOG_TAG, "getItemId(" + position + ") ", e); } return -1; } - public Object getItem(long position) - { + public Object getItem(long position) { return getItem((int)position); } @Override - public Object getItem(int position) - { - try - { - synchronized (mAdapter.messages) - { - if (position < mAdapter.messages.size()) - { + public Object getItem(int position) { + try { + synchronized (mAdapter.messages) { + if (position < mAdapter.messages.size()) { return mAdapter.messages.get(position); } } - } - catch (Exception e) - { + } catch (Exception e) { Log.e(K9.LOG_TAG, "getItem(" + position + "), but folder.messages.size() = " + mAdapter.messages.size(), e); } return null; } @Override - public View getView(int position, View convertView, ViewGroup parent) - { + public View getView(int position, View convertView, ViewGroup parent) { - if (position == mAdapter.messages.size()) - { + if (position == mAdapter.messages.size()) { return getFooterView(position, convertView, parent); - } - else - { + } else { return getItemView(position, convertView, parent); } } - public View getItemView(int position, View convertView, ViewGroup parent) - { + public View getItemView(int position, View convertView, ViewGroup parent) { MessageInfoHolder message = (MessageInfoHolder) getItem(position); View view; - if ((convertView != null) && (convertView.getId() == R.layout.message_list_item)) - { + if ((convertView != null) && (convertView.getId() == R.layout.message_list_item)) { view = convertView; - } - else - { - if (mTouchView) - { + } else { + if (mTouchView) { view = mInflater.inflate(R.layout.message_list_item_touchable, parent, false); view.setId(R.layout.message_list_item); - } - else - { + } else { view = mInflater.inflate(R.layout.message_list_item, parent, false); view.setId(R.layout.message_list_item); } @@ -2640,8 +2164,7 @@ public class MessageList MessageViewHolder holder = (MessageViewHolder) view.getTag(); - if (holder == null) - { + if (holder == null) { holder = new MessageViewHolder(); holder.subject = (TextView) view.findViewById(R.id.subject); holder.from = (TextView) view.findViewById(R.id.from); @@ -2653,43 +2176,34 @@ public class MessageList holder.flagged.setOnClickListener(flagClickListener); - if (!mStars) - { + if (!mStars) { holder.flagged.setVisibility(View.GONE); } - if (mCheckboxes) - { + if (mCheckboxes) { holder.selected.setVisibility(View.VISIBLE); } - if (holder.selected != null) - { + if (holder.selected != null) { holder.selected.setOnCheckedChangeListener(holder); } holder.subject.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mFontSizes.getMessageListSubject()); holder.date.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mFontSizes.getMessageListDate()); - if (mTouchView) - { + if (mTouchView) { holder.preview.setLines(mPreviewLines); holder.preview.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mFontSizes.getMessageListPreview()); - } - else - { + } else { holder.from.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mFontSizes.getMessageListSender()); } view.setTag(holder); } - if (message != null) - { + if (message != null) { bindView(position, view, holder, message); - } - else - { + } else { // This branch code is triggered when the local store // hands us an invalid message @@ -2697,8 +2211,7 @@ public class MessageList holder.subject.setText(getString(R.string.general_no_subject)); holder.subject.setTypeface(null, Typeface.NORMAL); String noSender = getString(R.string.general_no_sender); - if (holder.preview != null) - { + if (holder.preview != null) { holder.preview.setText(noSender, TextView.BufferType.SPANNABLE); Spannable str = (Spannable) holder.preview.getText(); @@ -2709,9 +2222,7 @@ public class MessageList noSender.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE ); - } - else - { + } else { holder.from.setText(noSender); holder.from.setTypeface(null, Typeface.NORMAL); holder.from.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null); @@ -2723,8 +2234,7 @@ public class MessageList holder.position = -1; holder.selected.setChecked(false); - if (!mCheckboxes) - { + if (!mCheckboxes) { holder.selected.setVisibility(View.GONE); } holder.flagged.setChecked(false); @@ -2749,8 +2259,7 @@ public class MessageList * Never null. */ private void bindView(final int position, final View view, final MessageViewHolder holder, - final MessageInfoHolder message) - { + final MessageInfoHolder message) { holder.subject.setTypeface(null, message.read ? Typeface.NORMAL : Typeface.BOLD); // XXX TODO there has to be some way to walk our view hierarchy and get this @@ -2762,8 +2271,7 @@ public class MessageList holder.position = -1; holder.selected.setChecked(message.selected); - if (!mCheckboxes) - { + if (!mCheckboxes) { holder.selected.setVisibility(message.selected ? View.VISIBLE : View.GONE); } @@ -2773,18 +2281,14 @@ public class MessageList holder.chip.getBackground().setAlpha(message.read ? 127 : 255); view.getBackground().setAlpha(message.downloaded ? 0 : 127); - if ((message.message.getSubject() == null) || message.message.getSubject().equals("")) - { + if ((message.message.getSubject() == null) || message.message.getSubject().equals("")) { holder.subject.setText(getText(R.string.general_no_subject)); - } - else - { + } else { holder.subject.setText(message.message.getSubject()); } int senderTypeface = message.read ? Typeface.NORMAL : Typeface.BOLD; - if (holder.preview != null) - { + if (holder.preview != null) { /* * In the touchable UI, we have previews. Otherwise, we * have just a "from" line. @@ -2806,10 +2310,8 @@ public class MessageList message.sender.length() + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE ); - } - else - { - holder.from.setText(new SpannableStringBuilder(recipientSigil(message)).append( message.sender)); + } else { + holder.from.setText(new SpannableStringBuilder(recipientSigil(message)).append(message.sender)); holder.from.setTypeface(null, senderTypeface); } @@ -2823,30 +2325,21 @@ public class MessageList holder.position = position; } - private String recipientSigil (MessageInfoHolder message) - { - if (message.message.toMe()) - { + private String recipientSigil(MessageInfoHolder message) { + if (message.message.toMe()) { return getString(R.string.messagelist_sent_to_me_sigil); - } - else if (message.message.ccMe()) - { + } else if (message.message.ccMe()) { return getString(R.string.messagelist_sent_cc_me_sigil); - } - else - { + } else { return ""; } } - public View getFooterView(int position, View convertView, ViewGroup parent) - { - if (footerView == null) - { + public View getFooterView(int position, View convertView, ViewGroup parent) { + if (footerView == null) { footerView = mInflater.inflate(R.layout.message_list_item_footer, parent, false); - if (mQueryString != null) - { + if (mQueryString != null) { footerView.setVisibility(View.GONE); } footerView.setId(R.layout.message_list_item_footer); @@ -2859,35 +2352,23 @@ public class MessageList FooterViewHolder holder = (FooterViewHolder)footerView.getTag(); - if (mCurrentFolder != null && mAccount != null) - { - if (mCurrentFolder.loading) - { + if (mCurrentFolder != null && mAccount != null) { + if (mCurrentFolder.loading) { holder.main.setText(getString(R.string.status_loading_more)); holder.progress.setVisibility(ProgressBar.VISIBLE); - } - else - { - if (!mCurrentFolder.lastCheckFailed) - { - if (mAccount.getDisplayCount() == 0 ) - { + } else { + if (!mCurrentFolder.lastCheckFailed) { + if (mAccount.getDisplayCount() == 0) { holder.main.setText(getString(R.string.message_list_load_more_messages_action)); - } - else - { + } else { holder.main.setText(String.format(getString(R.string.load_more_messages_fmt), mAccount.getDisplayCount())); } - } - else - { + } else { holder.main.setText(getString(R.string.status_loading_more_failed)); } holder.progress.setVisibility(ProgressBar.INVISIBLE); } - } - else - { + } else { holder.progress.setVisibility(ProgressBar.INVISIBLE); } @@ -2895,27 +2376,21 @@ public class MessageList } @Override - public boolean hasStableIds() - { + public boolean hasStableIds() { return true; } - public boolean isItemSelectable(int position) - { - if (position < mAdapter.messages.size()) - { + public boolean isItemSelectable(int position) { + if (position < mAdapter.messages.size()) { return true; - } - else - { + } else { return false; } } } class MessageViewHolder - implements OnCheckedChangeListener - { + implements OnCheckedChangeListener { public TextView subject; public TextView preview; public TextView from; @@ -2927,33 +2402,23 @@ public class MessageList public int position = -1; @Override - public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) - { - if (position!=-1) - { + public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { + if (position != -1) { MessageInfoHolder message = (MessageInfoHolder) mAdapter.getItem(position); - if (message.selected!=isChecked) - { - if (isChecked) - { + if (message.selected != isChecked) { + if (isChecked) { mSelectedCount++; - } - else if (mSelectedCount > 0) - { + } else if (mSelectedCount > 0) { mSelectedCount--; } // We must set the flag before showing the buttons as the // buttons text depends on what is selected. message.selected = isChecked; - if (!mCheckboxes) - { - if (isChecked) - { + if (!mCheckboxes) { + if (isChecked) { selected.setVisibility(View.VISIBLE); - } - else - { + } else { selected.setVisibility(View.GONE); } } @@ -2963,20 +2428,16 @@ public class MessageList } } - private void hideBatchButtons() - { - if (mBatchButtonArea.getVisibility() != View.GONE) - { + private void hideBatchButtons() { + if (mBatchButtonArea.getVisibility() != View.GONE) { mBatchButtonArea.setVisibility(View.GONE); mBatchButtonArea.startAnimation( AnimationUtils.loadAnimation(this, R.anim.footer_disappear)); } } - private void showBatchButtons() - { - if (mBatchButtonArea.getVisibility() != View.VISIBLE) - { + private void showBatchButtons() { + if (mBatchButtonArea.getVisibility() != View.VISIBLE) { mBatchButtonArea.setVisibility(View.VISIBLE); Animation animation = AnimationUtils.loadAnimation(this, R.anim.footer_appear); animation.setAnimationListener(this); @@ -2984,47 +2445,34 @@ public class MessageList } } - private void toggleBatchButtons() - { + private void toggleBatchButtons() { - runOnUiThread(new Runnable() - { + runOnUiThread(new Runnable() { @Override - public void run() - { + public void run() { - if (mSelectedCount < 0) - { + if (mSelectedCount < 0) { mSelectedCount = 0; } int readButtonIconId; int flagButtonIconId; - if (mSelectedCount==0) - { + if (mSelectedCount == 0) { readButtonIconId = R.drawable.ic_button_mark_read; flagButtonIconId = R.drawable.ic_button_flag; hideBatchButtons(); - } - else - { + } else { boolean newReadState = computeBatchDirection(false); - if (newReadState) - { + if (newReadState) { readButtonIconId = R.drawable.ic_button_mark_read; - } - else - { + } else { readButtonIconId = R.drawable.ic_button_mark_unread; } boolean newFlagState = computeBatchDirection(true); - if (newFlagState) - { + if (newFlagState) { flagButtonIconId = R.drawable.ic_button_flag; - } - else - { + } else { flagButtonIconId = R.drawable.ic_button_unflag; } showBatchButtons(); @@ -3040,35 +2488,25 @@ public class MessageList } - static class FooterViewHolder - { + static class FooterViewHolder { public ProgressBar progress; public TextView main; } - private boolean computeBatchDirection(boolean flagged) - { + private boolean computeBatchDirection(boolean flagged) { boolean newState = false; - synchronized (mAdapter.messages) - { - for (MessageInfoHolder holder : mAdapter.messages) - { - if (holder.selected) - { - if (flagged) - { - if (!holder.flagged) - { + synchronized (mAdapter.messages) { + for (MessageInfoHolder holder : mAdapter.messages) { + if (holder.selected) { + if (flagged) { + if (!holder.flagged) { newState = true; break; } - } - else - { - if (!holder.read) - { + } else { + if (!holder.read) { newState = true; break; } @@ -3079,14 +2517,10 @@ public class MessageList return newState; } - private boolean anySelected() - { - synchronized (mAdapter.messages) - { - for (MessageInfoHolder holder : mAdapter.messages) - { - if (holder.selected) - { + private boolean anySelected() { + synchronized (mAdapter.messages) { + for (MessageInfoHolder holder : mAdapter.messages) { + if (holder.selected) { return true; } } @@ -3095,43 +2529,30 @@ public class MessageList } @Override - public void onClick(View v) - { + public void onClick(View v) { boolean newState = false; List messageList = new ArrayList(); List removeHolderList = new ArrayList(); - if (v == mBatchDoneButton) - { + if (v == mBatchDoneButton) { setAllSelected(false); return; } - if (v == mBatchFlagButton) - { + if (v == mBatchFlagButton) { newState = computeBatchDirection(true); - } - else - { + } else { newState = computeBatchDirection(false); } - synchronized (mAdapter.messages) - { - for (MessageInfoHolder holder : mAdapter.messages) - { - if (holder.selected) - { - if (v == mBatchDeleteButton) - { + synchronized (mAdapter.messages) { + for (MessageInfoHolder holder : mAdapter.messages) { + if (holder.selected) { + if (v == mBatchDeleteButton) { removeHolderList.add(holder); - } - else if (v == mBatchFlagButton) - { + } else if (v == mBatchFlagButton) { holder.flagged = newState; - } - else if (v == mBatchReadButton) - { + } else if (v == mBatchReadButton) { holder.read = newState; } messageList.add(holder.message); @@ -3140,48 +2561,36 @@ public class MessageList } mAdapter.removeMessages(removeHolderList); - if (!messageList.isEmpty()) - { - if (v == mBatchDeleteButton) - { + if (!messageList.isEmpty()) { + if (v == mBatchDeleteButton) { mController.deleteMessages(messageList.toArray(EMPTY_MESSAGE_ARRAY), null); mSelectedCount = 0; toggleBatchButtons(); - } - else - { + } else { mController.setFlag(messageList.toArray(EMPTY_MESSAGE_ARRAY), (v == mBatchReadButton ? Flag.SEEN : Flag.FLAGGED), newState); } - } - else - { + } else { // Should not happen Toast.makeText(this, R.string.no_message_seletected_toast, Toast.LENGTH_SHORT).show(); } mHandler.sortMessages(); } - public void onAnimationEnd(Animation animation) - { + public void onAnimationEnd(Animation animation) { } - public void onAnimationRepeat(Animation animation) - { + public void onAnimationRepeat(Animation animation) { } - public void onAnimationStart(Animation animation) - { + public void onAnimationStart(Animation animation) { } - private void setAllSelected(boolean isSelected) - { + private void setAllSelected(boolean isSelected) { mSelectedCount = 0; - synchronized (mAdapter.messages) - { - for (MessageInfoHolder holder : mAdapter.messages) - { + synchronized (mAdapter.messages) { + for (MessageInfoHolder holder : mAdapter.messages) { holder.selected = isSelected; mSelectedCount += (isSelected ? 1 : 0); } @@ -3190,10 +2599,8 @@ public class MessageList toggleBatchButtons(); } - private void setSelected(MessageInfoHolder holder, boolean newState) - { - if (holder.selected != newState) - { + private void setSelected(MessageInfoHolder holder, boolean newState) { + if (holder.selected != newState) { holder.selected = newState; mSelectedCount += (newState ? 1 : -1); } @@ -3201,22 +2608,15 @@ public class MessageList toggleBatchButtons(); } - private void flagSelected(Flag flag, boolean newState) - { + private void flagSelected(Flag flag, boolean newState) { List messageList = new ArrayList(); - synchronized (mAdapter.messages) - { - for (MessageInfoHolder holder : mAdapter.messages) - { - if (holder.selected) - { + synchronized (mAdapter.messages) { + for (MessageInfoHolder holder : mAdapter.messages) { + if (holder.selected) { messageList.add(holder.message); - if (flag == Flag.SEEN) - { + if (flag == Flag.SEEN) { holder.read = newState; - } - else if (flag == Flag.FLAGGED) - { + } else if (flag == Flag.FLAGGED) { holder.flagged = newState; } } @@ -3226,16 +2626,12 @@ public class MessageList mHandler.sortMessages(); } - private void deleteSelected() - { + private void deleteSelected() { List messageList = new ArrayList(); List removeHolderList = new ArrayList(); - synchronized (mAdapter.messages) - { - for (MessageInfoHolder holder : mAdapter.messages) - { - if (holder.selected) - { + synchronized (mAdapter.messages) { + for (MessageInfoHolder holder : mAdapter.messages) { + if (holder.selected) { removeHolderList.add(holder); messageList.add(holder.message); } @@ -3248,22 +2644,16 @@ public class MessageList toggleBatchButtons(); } - private void onMoveBatch() - { - if (!mController.isMoveCapable(mAccount)) - { + private void onMoveBatch() { + if (!mController.isMoveCapable(mAccount)) { return; } - synchronized (mAdapter.messages) - { - for (MessageInfoHolder holder : mAdapter.messages) - { - if (holder.selected) - { + synchronized (mAdapter.messages) { + for (MessageInfoHolder holder : mAdapter.messages) { + if (holder.selected) { Message message = holder.message; - if (!mController.isMoveCapable(message)) - { + if (!mController.isMoveCapable(message)) { Toast toast = Toast.makeText(this, R.string.move_copy_cannot_copy_unsynced_message, Toast.LENGTH_LONG); toast.show(); @@ -3281,24 +2671,18 @@ public class MessageList startActivityForResult(intent, ACTIVITY_CHOOSE_FOLDER_MOVE_BATCH); } - private void onMoveChosenBatch(String folderName) - { - if (!mController.isMoveCapable(mAccount)) - { + private void onMoveChosenBatch(String folderName) { + if (!mController.isMoveCapable(mAccount)) { return; } List messageList = new ArrayList(); List removeHolderList = new ArrayList(); - synchronized (mAdapter.messages) - { - for (MessageInfoHolder holder : mAdapter.messages) - { - if (holder.selected) - { + synchronized (mAdapter.messages) { + for (MessageInfoHolder holder : mAdapter.messages) { + if (holder.selected) { Message message = holder.message; - if (!mController.isMoveCapable(message)) - { + if (!mController.isMoveCapable(message)) { Toast toast = Toast.makeText(this, R.string.move_copy_cannot_copy_unsynced_message, Toast.LENGTH_LONG); toast.show(); @@ -3316,22 +2700,16 @@ public class MessageList toggleBatchButtons(); } - private void onArchiveBatch() - { - if (!mController.isMoveCapable(mAccount)) - { + private void onArchiveBatch() { + if (!mController.isMoveCapable(mAccount)) { return; } - synchronized (mAdapter.messages) - { - for (MessageInfoHolder holder : mAdapter.messages) - { - if (holder.selected) - { + synchronized (mAdapter.messages) { + for (MessageInfoHolder holder : mAdapter.messages) { + if (holder.selected) { Message message = holder.message; - if (!mController.isMoveCapable(message)) - { + if (!mController.isMoveCapable(message)) { Toast toast = Toast.makeText(this, R.string.move_copy_cannot_copy_unsynced_message, Toast.LENGTH_LONG); toast.show(); return; @@ -3341,29 +2719,22 @@ public class MessageList } String folderName = mAccount.getArchiveFolderName(); - if (K9.FOLDER_NONE.equalsIgnoreCase(folderName)) - { + if (K9.FOLDER_NONE.equalsIgnoreCase(folderName)) { return; } onMoveChosenBatch(folderName); } - private void onSpamBatch() - { - if (!mController.isMoveCapable(mAccount)) - { + private void onSpamBatch() { + if (!mController.isMoveCapable(mAccount)) { return; } - synchronized (mAdapter.messages) - { - for (MessageInfoHolder holder : mAdapter.messages) - { - if (holder.selected) - { + synchronized (mAdapter.messages) { + for (MessageInfoHolder holder : mAdapter.messages) { + if (holder.selected) { Message message = holder.message; - if (!mController.isMoveCapable(message)) - { + if (!mController.isMoveCapable(message)) { Toast toast = Toast.makeText(this, R.string.move_copy_cannot_copy_unsynced_message, Toast.LENGTH_LONG); toast.show(); return; @@ -3373,29 +2744,22 @@ public class MessageList } String folderName = mAccount.getSpamFolderName(); - if (K9.FOLDER_NONE.equalsIgnoreCase(folderName)) - { + if (K9.FOLDER_NONE.equalsIgnoreCase(folderName)) { return; } onMoveChosenBatch(folderName); } - private void onCopyBatch() - { - if (!mController.isCopyCapable(mAccount)) - { + private void onCopyBatch() { + if (!mController.isCopyCapable(mAccount)) { return; } - synchronized (mAdapter.messages) - { - for (MessageInfoHolder holder : mAdapter.messages) - { - if (holder.selected) - { + synchronized (mAdapter.messages) { + for (MessageInfoHolder holder : mAdapter.messages) { + if (holder.selected) { Message message = holder.message; - if (!mController.isCopyCapable(message)) - { + if (!mController.isCopyCapable(message)) { Toast toast = Toast.makeText(this, R.string.move_copy_cannot_copy_unsynced_message, Toast.LENGTH_LONG); toast.show(); @@ -3413,23 +2777,17 @@ public class MessageList startActivityForResult(intent, ACTIVITY_CHOOSE_FOLDER_COPY_BATCH); } - private void onCopyChosenBatch(String folderName) - { - if (!mController.isCopyCapable(mAccount)) - { + private void onCopyChosenBatch(String folderName) { + if (!mController.isCopyCapable(mAccount)) { return; } List messageList = new ArrayList(); - synchronized (mAdapter.messages) - { - for (MessageInfoHolder holder : mAdapter.messages) - { - if (holder.selected) - { + synchronized (mAdapter.messages) { + for (MessageInfoHolder holder : mAdapter.messages) { + if (holder.selected) { Message message = holder.message; - if (!mController.isCopyCapable(message)) - { + if (!mController.isCopyCapable(message)) { Toast toast = Toast.makeText(this, R.string.move_copy_cannot_copy_unsynced_message, Toast.LENGTH_LONG); toast.show(); @@ -3442,8 +2800,7 @@ public class MessageList mController.copyMessages(mAccount, mCurrentFolder.name, messageList.toArray(EMPTY_MESSAGE_ARRAY), folderName, null); } - protected void onAccountUnavailable() - { + protected void onAccountUnavailable() { finish(); // TODO inform user about account unavailability using Toast Accounts.listAccounts(this); diff --git a/src/com/fsck/k9/activity/MessageReference.java b/src/com/fsck/k9/activity/MessageReference.java index eda8f0864..98ae77212 100644 --- a/src/com/fsck/k9/activity/MessageReference.java +++ b/src/com/fsck/k9/activity/MessageReference.java @@ -9,8 +9,7 @@ import com.fsck.k9.mail.MessagingException; import java.io.Serializable; import java.util.StringTokenizer; -public class MessageReference implements Serializable -{ +public class MessageReference implements Serializable { private static final long serialVersionUID = -1625198750239083389L; public String accountUuid; public String folderName; @@ -20,8 +19,7 @@ public class MessageReference implements Serializable /** * Initialize an empty MessageReference. */ - public MessageReference() - { + public MessageReference() { } // Version identifier for use when serializing. This will allow us to introduce future versions @@ -34,42 +32,33 @@ public class MessageReference implements Serializable * @param identity Serialized identity. * @throws MessagingException On missing or corrupted identity. */ - public MessageReference(final String identity) throws MessagingException - { + public MessageReference(final String identity) throws MessagingException { // Can't be null and must be at least length one so we can check the version. - if (identity == null || identity.length() < 1) - { + if (identity == null || identity.length() < 1) { throw new MessagingException("Null or truncated MessageReference identity."); } // Version check. - if (identity.charAt(0) == IDENTITY_VERSION_1.charAt(0)) - { + if (identity.charAt(0) == IDENTITY_VERSION_1.charAt(0)) { // Split the identity, stripping away the first two characters representing the version and delimiter. StringTokenizer tokens = new StringTokenizer(identity.substring(2), IDENTITY_SEPARATOR, false); - if (tokens.countTokens() >= 3) - { + if (tokens.countTokens() >= 3) { accountUuid = Utility.base64Decode(tokens.nextToken()); folderName = Utility.base64Decode(tokens.nextToken()); uid = Utility.base64Decode(tokens.nextToken()); - if (tokens.hasMoreTokens()) - { + if (tokens.hasMoreTokens()) { final String flagString = tokens.nextToken(); - try - { + try { flag = Flag.valueOf(flagString); - } catch (IllegalArgumentException ie) - { + } catch (IllegalArgumentException ie) { throw new MessagingException("Could not thaw message flag '" + flagString + "'", ie); } } if (K9.DEBUG) Log.d(K9.LOG_TAG, "Thawed " + toString()); - } - else - { + } else { throw new MessagingException("Invalid MessageReference in " + identity + " identity."); } } @@ -80,8 +69,7 @@ public class MessageReference implements Serializable * * @return Serialized string. */ - public String toIdentityString() - { + public String toIdentityString() { StringBuilder refString = new StringBuilder(); refString.append(IDENTITY_VERSION_1); @@ -91,8 +79,7 @@ public class MessageReference implements Serializable refString.append(Utility.base64Encode(folderName)); refString.append(IDENTITY_SEPARATOR); refString.append(Utility.base64Encode(uid)); - if (flag != null) - { + if (flag != null) { refString.append(IDENTITY_SEPARATOR); refString.append(flag.name()); } @@ -101,25 +88,21 @@ public class MessageReference implements Serializable } @Override - public boolean equals(Object o) - { - if (o instanceof MessageReference == false) - { + public boolean equals(Object o) { + if (o instanceof MessageReference == false) { return false; } MessageReference other = (MessageReference)o; if ((accountUuid == other.accountUuid || (accountUuid != null && accountUuid.equals(other.accountUuid))) && (folderName == other.folderName || (folderName != null && folderName.equals(other.folderName))) - && (uid == other.uid || (uid != null && uid.equals(other.uid)))) - { + && (uid == other.uid || (uid != null && uid.equals(other.uid)))) { return true; } return false; } @Override - public int hashCode() - { + public int hashCode() { final int MULTIPLIER = 31; int result = 1; @@ -130,13 +113,12 @@ public class MessageReference implements Serializable } @Override - public String toString() - { + public String toString() { return "MessageReference{" + - "accountUuid='" + accountUuid + '\'' + - ", folderName='" + folderName + '\'' + - ", uid='" + uid + '\'' + - ", flag=" + flag + - '}'; + "accountUuid='" + accountUuid + '\'' + + ", folderName='" + folderName + '\'' + + ", uid='" + uid + '\'' + + ", flag=" + flag + + '}'; } } diff --git a/src/com/fsck/k9/activity/MessageView.java b/src/com/fsck/k9/activity/MessageView.java index bc2cc731c..87fe292e4 100644 --- a/src/com/fsck/k9/activity/MessageView.java +++ b/src/com/fsck/k9/activity/MessageView.java @@ -38,8 +38,7 @@ import com.fsck.k9.view.MessageHeader; import java.io.Serializable; import java.util.*; -public class MessageView extends K9Activity implements OnClickListener -{ +public class MessageView extends K9Activity implements OnClickListener { private static final String EXTRA_MESSAGE_REFERENCE = "com.fsck.k9.MessageView_messageReference"; private static final String EXTRA_MESSAGE_REFERENCES = "com.fsck.k9.MessageView_messageReferences"; private static final String EXTRA_NEXT = "com.fsck.k9.MessageView_next"; @@ -85,20 +84,15 @@ public class MessageView extends K9Activity implements OnClickListener private Contacts mContacts; private StorageManager.StorageListener mStorageListener = new StorageListenerImplementation(); - private final class StorageListenerImplementation implements StorageManager.StorageListener - { + private final class StorageListenerImplementation implements StorageManager.StorageListener { @Override - public void onUnmount(String providerId) - { - if (!providerId.equals(mAccount.getLocalStorageProviderId())) - { + public void onUnmount(String providerId) { + if (!providerId.equals(mAccount.getLocalStorageProviderId())) { return; } - runOnUiThread(new Runnable() - { + runOnUiThread(new Runnable() { @Override - public void run() - { + public void run() { onAccountUnavailable(); } }); @@ -110,23 +104,16 @@ public class MessageView extends K9Activity implements OnClickListener @Override - public boolean dispatchTouchEvent(MotionEvent ev) - { - if (ev.getAction() == MotionEvent.ACTION_UP) - { + public boolean dispatchTouchEvent(MotionEvent ev) { + if (ev.getAction() == MotionEvent.ACTION_UP) { // Text selection is finished. Allow scrolling again. mToggleScrollView.setScrolling(true); - } - else if (K9.zoomControlsEnabled()) - { + } else if (K9.zoomControlsEnabled()) { // If we have system zoom controls enabled, disable scrolling so the screen isn't wiggling around while // trying to zoom. - if (ev.getAction() == MotionEvent.ACTION_POINTER_2_DOWN) - { + if (ev.getAction() == MotionEvent.ACTION_POINTER_2_DOWN) { mToggleScrollView.setScrolling(false); - } - else if (ev.getAction() == MotionEvent.ACTION_POINTER_2_UP) - { + } else if (ev.getAction() == MotionEvent.ACTION_POINTER_2_UP) { mToggleScrollView.setScrolling(true); } } @@ -134,156 +121,121 @@ public class MessageView extends K9Activity implements OnClickListener } @Override - public boolean dispatchKeyEvent(KeyEvent event) - { + public boolean dispatchKeyEvent(KeyEvent event) { boolean ret = false; - if (KeyEvent.ACTION_DOWN == event.getAction()) - { + if (KeyEvent.ACTION_DOWN == event.getAction()) { ret = onKeyDown(event.getKeyCode(), event); } - if (!ret) - { + if (!ret) { ret = super.dispatchKeyEvent(event); } return ret; } @Override - public boolean onKeyDown(final int keyCode, final KeyEvent event) - { - switch (keyCode) - { - case KeyEvent.KEYCODE_VOLUME_UP: - { - if (K9.useVolumeKeysForNavigationEnabled()) - { - onNext(); - return true; - } - } - case KeyEvent.KEYCODE_VOLUME_DOWN: - { - if (K9.useVolumeKeysForNavigationEnabled()) - { - onPrevious(); - return true; - } - } - case KeyEvent.KEYCODE_SHIFT_LEFT: - case KeyEvent.KEYCODE_SHIFT_RIGHT: - { - /* - * Selecting text started via shift key. Disable scrolling as - * this causes problems when selecting text. - */ - mToggleScrollView.setScrolling(false); - break; - } - case KeyEvent.KEYCODE_DEL: - { - onDelete(); - return true; - } - case KeyEvent.KEYCODE_D: - { - onDelete(); - return true; - } - case KeyEvent.KEYCODE_F: - { - onForward(); - return true; - } - case KeyEvent.KEYCODE_A: - { - onReplyAll(); - return true; - } - case KeyEvent.KEYCODE_R: - { - onReply(); - return true; - } - case KeyEvent.KEYCODE_G: - { - onFlag(); - return true; - } - case KeyEvent.KEYCODE_M: - { - onMove(); - return true; - } - case KeyEvent.KEYCODE_S: - { - onRefile(mAccount.getSpamFolderName()); - return true; - } - case KeyEvent.KEYCODE_V: - { - onRefile(mAccount.getArchiveFolderName()); - return true; - } - case KeyEvent.KEYCODE_Y: - { - onCopy(); - return true; - } - case KeyEvent.KEYCODE_J: - case KeyEvent.KEYCODE_P: - { - onPrevious(); - return true; - } - case KeyEvent.KEYCODE_N: - case KeyEvent.KEYCODE_K: - { + public boolean onKeyDown(final int keyCode, final KeyEvent event) { + switch (keyCode) { + case KeyEvent.KEYCODE_VOLUME_UP: { + if (K9.useVolumeKeysForNavigationEnabled()) { onNext(); return true; } - case KeyEvent.KEYCODE_Z: - { - mHandler.post(new Runnable() - { - public void run() - { - if (mScreenReaderEnabled) - { - mAccessibleMessageContentView.zoomIn(); - } - else - { - if (event.isShiftPressed()) - { - mMessageContentView.zoomIn(); - } - else - { - mMessageContentView.zoomOut(); - } + } + case KeyEvent.KEYCODE_VOLUME_DOWN: { + if (K9.useVolumeKeysForNavigationEnabled()) { + onPrevious(); + return true; + } + } + case KeyEvent.KEYCODE_SHIFT_LEFT: + case KeyEvent.KEYCODE_SHIFT_RIGHT: { + /* + * Selecting text started via shift key. Disable scrolling as + * this causes problems when selecting text. + */ + mToggleScrollView.setScrolling(false); + break; + } + case KeyEvent.KEYCODE_DEL: { + onDelete(); + return true; + } + case KeyEvent.KEYCODE_D: { + onDelete(); + return true; + } + case KeyEvent.KEYCODE_F: { + onForward(); + return true; + } + case KeyEvent.KEYCODE_A: { + onReplyAll(); + return true; + } + case KeyEvent.KEYCODE_R: { + onReply(); + return true; + } + case KeyEvent.KEYCODE_G: { + onFlag(); + return true; + } + case KeyEvent.KEYCODE_M: { + onMove(); + return true; + } + case KeyEvent.KEYCODE_S: { + onRefile(mAccount.getSpamFolderName()); + return true; + } + case KeyEvent.KEYCODE_V: { + onRefile(mAccount.getArchiveFolderName()); + return true; + } + case KeyEvent.KEYCODE_Y: { + onCopy(); + return true; + } + case KeyEvent.KEYCODE_J: + case KeyEvent.KEYCODE_P: { + onPrevious(); + return true; + } + case KeyEvent.KEYCODE_N: + case KeyEvent.KEYCODE_K: { + onNext(); + return true; + } + case KeyEvent.KEYCODE_Z: { + mHandler.post(new Runnable() { + public void run() { + if (mScreenReaderEnabled) { + mAccessibleMessageContentView.zoomIn(); + } else { + if (event.isShiftPressed()) { + mMessageContentView.zoomIn(); + } else { + mMessageContentView.zoomOut(); } } - }); - return true; - } - case KeyEvent.KEYCODE_H: - { - Toast toast = Toast.makeText(this, R.string.message_help_key, Toast.LENGTH_LONG); - toast.show(); - return true; - } + } + }); + return true; + } + case KeyEvent.KEYCODE_H: { + Toast toast = Toast.makeText(this, R.string.message_help_key, Toast.LENGTH_LONG); + toast.show(); + return true; + } } return super.onKeyDown(keyCode, event); } @Override - public boolean onKeyUp(int keyCode, KeyEvent event) - { + public boolean onKeyUp(int keyCode, KeyEvent event) { // Swallow these events too to avoid the audible notification of a volume change - if (K9.useVolumeKeysForNavigationEnabled()) - { - if ((keyCode == KeyEvent.KEYCODE_VOLUME_UP) || (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)) - { + if (K9.useVolumeKeysForNavigationEnabled()) { + if ((keyCode == KeyEvent.KEYCODE_VOLUME_UP) || (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)) { if (K9.DEBUG) Log.v(K9.LOG_TAG, "Swallowed key up."); return true; @@ -292,38 +244,25 @@ public class MessageView extends K9Activity implements OnClickListener return super.onKeyUp(keyCode, event); } - class MessageViewHandler extends Handler - { - public void setHeaders (final Message message) - { - runOnUiThread(new Runnable() - { - public void run() - { - try - { - mHeaderContainer.populate( message,mAccount); - mHeaderContainer.setOnFlagListener( new OnClickListener() - { - @Override public void onClick(View v) - { - if (mMessage != null) - { + class MessageViewHandler extends Handler { + public void setHeaders(final Message message) { + runOnUiThread(new Runnable() { + public void run() { + try { + mHeaderContainer.populate(message, mAccount); + mHeaderContainer.setOnFlagListener(new OnClickListener() { + @Override public void onClick(View v) { + if (mMessage != null) { onFlag(); } } }); - } - catch (Exception me) - { + } catch (Exception me) { Log.e(K9.LOG_TAG, "setHeaders - error", me); } - if (mMessage.isSet(Flag.X_DOWNLOADED_FULL)) - { + if (mMessage.isSet(Flag.X_DOWNLOADED_FULL)) { mDownloadRemainder.setVisibility(View.GONE); - } - else - { + } else { mDownloadRemainder.setEnabled(true); mDownloadRemainder.setVisibility(View.VISIBLE); } @@ -332,51 +271,37 @@ public class MessageView extends K9Activity implements OnClickListener } - public void progress(final boolean progress) - { - runOnUiThread(new Runnable() - { - public void run() - { + public void progress(final boolean progress) { + runOnUiThread(new Runnable() { + public void run() { setProgressBarIndeterminateVisibility(progress); } }); } - public void addAttachment(final View attachmentView) - { - runOnUiThread(new Runnable() - { - public void run() - { + public void addAttachment(final View attachmentView) { + runOnUiThread(new Runnable() { + public void run() { mAttachments.addView(attachmentView); mAttachments.setVisibility(View.VISIBLE); } }); } - public void removeAllAttachments() - { - runOnUiThread(new Runnable() - { - public void run() - { - for (int i = 0, count = mAttachments.getChildCount(); i < count; i++) - { + public void removeAllAttachments() { + runOnUiThread(new Runnable() { + public void run() { + for (int i = 0, count = mAttachments.getChildCount(); i < count; i++) { mAttachments.removeView(mAttachments.getChildAt(i)); } } }); } - public void setAttachmentsEnabled(final boolean enabled) - { - runOnUiThread(new Runnable() - { - public void run() - { - for (int i = 0, count = mAttachments.getChildCount(); i < count; i++) - { + public void setAttachmentsEnabled(final boolean enabled) { + runOnUiThread(new Runnable() { + public void run() { + for (int i = 0, count = mAttachments.getChildCount(); i < count; i++) { AttachmentView attachment = (AttachmentView) mAttachments.getChildAt(i); attachment.viewButton.setEnabled(enabled); attachment.downloadButton.setEnabled(enabled); @@ -387,24 +312,18 @@ public class MessageView extends K9Activity implements OnClickListener - public void networkError() - { - runOnUiThread(new Runnable() - { - public void run() - { + public void networkError() { + runOnUiThread(new Runnable() { + public void run() { Toast.makeText(MessageView.this, R.string.status_network_error, Toast.LENGTH_LONG).show(); } }); } - public void invalidIdError() - { - runOnUiThread(new Runnable() - { - public void run() - { + public void invalidIdError() { + runOnUiThread(new Runnable() { + public void run() { Toast.makeText(MessageView.this, R.string.status_invalid_id_error, Toast.LENGTH_LONG).show(); } @@ -412,12 +331,9 @@ public class MessageView extends K9Activity implements OnClickListener } - public void fetchingAttachment() - { - runOnUiThread(new Runnable() - { - public void run() - { + public void fetchingAttachment() { + runOnUiThread(new Runnable() { + public void run() { Toast.makeText(MessageView.this, getString(R.string.message_view_fetching_attachment_toast), Toast.LENGTH_SHORT).show(); @@ -425,12 +341,9 @@ public class MessageView extends K9Activity implements OnClickListener }); } - public void showShowPictures(final boolean show) - { - runOnUiThread(new Runnable() - { - public void run() - { + public void showShowPictures(final boolean show) { + runOnUiThread(new Runnable() { + public void run() { mShowPicturesSection.setVisibility(show ? View.VISIBLE : View.GONE); } }); @@ -438,26 +351,22 @@ public class MessageView extends K9Activity implements OnClickListener } - public static void actionView(Context context, MessageReference messRef, List messReferences) - { + public static void actionView(Context context, MessageReference messRef, List messReferences) { actionView(context, messRef, messReferences, null); } - public static void actionView(Context context, MessageReference messRef, List messReferences, Bundle extras) - { + public static void actionView(Context context, MessageReference messRef, List messReferences, Bundle extras) { Intent i = new Intent(context, MessageView.class); i.putExtra(EXTRA_MESSAGE_REFERENCE, messRef); i.putExtra(EXTRA_MESSAGE_REFERENCES, (Serializable) messReferences); - if (extras != null) - { + if (extras != null) { i.putExtras(extras); } context.startActivity(i); } @Override - public void onCreate(Bundle icicle) - { + public void onCreate(Bundle icicle) { super.onCreate(icicle, false); mContacts = Contacts.getInstance(this); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); @@ -470,13 +379,10 @@ public class MessageView extends K9Activity implements OnClickListener mHeaderContainer = (MessageHeader) findViewById(R.id.header_container); mScreenReaderEnabled = isScreenReaderActive(); - if (mScreenReaderEnabled) - { + if (mScreenReaderEnabled) { mAccessibleMessageContentView.setVisibility(View.VISIBLE); mMessageContentView.setVisibility(View.GONE); - } - else - { + } else { mAccessibleMessageContentView.setVisibility(View.GONE); mMessageContentView.setVisibility(View.VISIBLE); } @@ -486,23 +392,16 @@ public class MessageView extends K9Activity implements OnClickListener setTitle(""); Intent intent = getIntent(); Uri uri = intent.getData(); - if (icicle != null) - { + if (icicle != null) { restoreMessageReferences(icicle); mPgpData = (PgpData) icicle.getSerializable(STATE_PGP_DATA); updateDecryptLayout(); - } - else - { - if (uri == null) - { + } else { + if (uri == null) { restoreMessageReferencesExtra(intent); - } - else - { + } else { List segmentList = uri.getPathSegments(); - if (segmentList.size() != 3) - { + if (segmentList.size() != 3) { //TODO: Use ressource to externalize message Toast.makeText(this, "Invalid intent uri: " + uri.toString(), Toast.LENGTH_LONG).show(); return; @@ -511,17 +410,14 @@ public class MessageView extends K9Activity implements OnClickListener String accountId = segmentList.get(0); Collection accounts = Preferences.getPreferences(this).getAvailableAccounts(); boolean found = false; - for (Account account : accounts) - { - if (String.valueOf(account.getAccountNumber()).equals(accountId)) - { + for (Account account : accounts) { + if (String.valueOf(account.getAccountNumber()).equals(accountId)) { mAccount = account; found = true; break; } } - if (!found) - { + if (!found) { //TODO: Use ressource to externalize message Toast.makeText(this, "Invalid account id: " + accountId, Toast.LENGTH_LONG).show(); return; @@ -540,8 +436,7 @@ public class MessageView extends K9Activity implements OnClickListener if (K9.DEBUG) Log.d(K9.LOG_TAG, "MessageView got message " + mMessageReference); - if (intent.getBooleanExtra(EXTRA_NEXT, false)) - { + if (intent.getBooleanExtra(EXTRA_NEXT, false)) { next.requestFocus(); } @@ -552,21 +447,18 @@ public class MessageView extends K9Activity implements OnClickListener } @SuppressWarnings("unchecked") - private void restoreMessageReferences(Bundle icicle) - { + private void restoreMessageReferences(Bundle icicle) { mMessageReference = (MessageReference) icicle.getSerializable(EXTRA_MESSAGE_REFERENCE); mMessageReferences = (ArrayList) icicle.getSerializable(EXTRA_MESSAGE_REFERENCES); } @SuppressWarnings("unchecked") - private void restoreMessageReferencesExtra(Intent intent) - { + private void restoreMessageReferencesExtra(Intent intent) { mMessageReference = (MessageReference) intent.getSerializableExtra(EXTRA_MESSAGE_REFERENCE); mMessageReferences = (ArrayList) intent.getSerializableExtra(EXTRA_MESSAGE_REFERENCES); } - private void setupButtonViews() - { + private void setupButtonViews() { setOnClickListener(R.id.from); setOnClickListener(R.id.reply); setOnClickListener(R.id.reply_all); @@ -598,35 +490,26 @@ public class MessageView extends K9Activity implements OnClickListener ((Account.ScrollButtons.ALWAYS == scrollButtons) || (Account.ScrollButtons.KEYBOARD_AVAILABLE == scrollButtons && - (this.getResources().getConfiguration().hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO))) - { + (this.getResources().getConfiguration().hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO))) { scrollButtons(); - } - else // never or the keyboard is open - { + } else { // never or the keyboard is open staticButtons(); } Account.ScrollButtons scrollMoveButtons = mAccount.getScrollMessageViewMoveButtons(); if ((Account.ScrollButtons.ALWAYS == scrollMoveButtons) || (Account.ScrollButtons.KEYBOARD_AVAILABLE == scrollMoveButtons && - (this.getResources().getConfiguration().hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO))) - { + (this.getResources().getConfiguration().hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO))) { scrollMoveButtons(); - } - else - { + } else { staticMoveButtons(); } - if (!mAccount.getEnableMoveButtons()) - { + if (!mAccount.getEnableMoveButtons()) { View buttons = findViewById(R.id.move_buttons); - if (buttons != null) - { + if (buttons != null) { buttons.setVisibility(View.GONE); } buttons = findViewById(R.id.scrolling_move_buttons); - if (buttons != null) - { + if (buttons != null) { buttons.setVisibility(View.GONE); } } @@ -635,8 +518,7 @@ public class MessageView extends K9Activity implements OnClickListener } - private void setupHeaderLayout() - { + private void setupHeaderLayout() { mShowPicturesSection = findViewById(R.id.show_pictures_section); mShowPictures = false; @@ -650,31 +532,23 @@ public class MessageView extends K9Activity implements OnClickListener } - private void setupDecryptLayout() - { + private void setupDecryptLayout() { mDecryptLayout = findViewById(R.id.layout_decrypt); mDecryptButton = (Button) findViewById(R.id.btn_decrypt); - mDecryptButton.setOnClickListener(new OnClickListener() - { + mDecryptButton.setOnClickListener(new OnClickListener() { @Override - public void onClick(View v) - { - try - { + public void onClick(View v) { + try { String data = null; Part part = MimeUtility.findFirstPartByMimeType(mMessage, "text/plain"); - if (part == null) - { + if (part == null) { part = MimeUtility.findFirstPartByMimeType(mMessage, "text/html"); } - if (part != null) - { + if (part != null) { data = MimeUtility.getTextFromPart(part); } mAccount.getCryptoProvider().decrypt(MessageView.this, data, mPgpData); - } - catch (MessagingException me) - { + } catch (MessagingException me) { Log.e(K9.LOG_TAG, "Unable to decrypt email.", me); } } @@ -686,8 +560,7 @@ public class MessageView extends K9Activity implements OnClickListener mCryptoSignatureLayout.setVisibility(View.INVISIBLE); } - private boolean isScreenReaderActive() - { + private boolean isScreenReaderActive() { final String SCREENREADER_INTENT_ACTION = "android.accessibilityservice.AccessibilityService"; final String SCREENREADER_INTENT_CATEGORY = "android.accessibilityservice.category.FEEDBACK_SPOKEN"; // Restrict the set of intents to only accessibility services that have @@ -699,23 +572,20 @@ public class MessageView extends K9Activity implements OnClickListener ContentResolver cr = getContentResolver(); Cursor cursor = null; int status = 0; - for (ResolveInfo screenReader : screenReaders) - { + for (ResolveInfo screenReader : screenReaders) { // All screen readers are expected to implement a content provider // that responds to // content://.providers.StatusProvider cursor = cr.query(Uri.parse("content://" + screenReader.serviceInfo.packageName + ".providers.StatusProvider"), null, null, null, null); - if (cursor != null) - { + if (cursor != null) { cursor.moveToFirst(); // These content providers use a special cursor that only has // one element, // an integer that is 1 if the screen reader is running. status = cursor.getInt(0); cursor.close(); - if (status == 1) - { + if (status == 1) { return true; } } @@ -724,8 +594,7 @@ public class MessageView extends K9Activity implements OnClickListener } @Override - protected void onSaveInstanceState(Bundle outState) - { + protected void onSaveInstanceState(Bundle outState) { outState.putSerializable(EXTRA_MESSAGE_REFERENCE, mMessageReference); outState.putSerializable(EXTRA_MESSAGE_REFERENCES, mMessageReferences); outState.putSerializable(STATE_PGP_DATA, mPgpData); @@ -733,16 +602,14 @@ public class MessageView extends K9Activity implements OnClickListener } @Override - protected void onRestoreInstanceState(Bundle savedInstanceState) - { + protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); setLoadPictures(savedInstanceState.getBoolean(SHOW_PICTURES)); initializeCrypto((PgpData) savedInstanceState.getSerializable(STATE_PGP_DATA)); updateDecryptLayout(); } - private void displayMessage(MessageReference ref) - { + private void displayMessage(MessageReference ref) { mMessageReference = ref; if (K9.DEBUG) Log.d(K9.LOG_TAG, "MessageView displaying message " + mMessageReference); @@ -767,14 +634,12 @@ public class MessageView extends K9Activity implements OnClickListener setupDisplayMessageButtons(); } - private void setupDisplayMessageButtons() - { + private void setupDisplayMessageButtons() { mDelete.setEnabled(true); next.setEnabled(mNextMessage != null); previous.setEnabled(mPreviousMessage != null); // If moving isn't support at all, then all of them must be disabled anyway. - if (mController.isMoveCapable(mAccount)) - { + if (mController.isMoveCapable(mAccount)) { // Only enable the button if the Archive folder is not the current folder and not NONE. mArchive.setEnabled(!mMessageReference.folderName.equals(mAccount.getArchiveFolderName()) && !K9.FOLDER_NONE.equalsIgnoreCase(mAccount.getArchiveFolderName())); @@ -782,18 +647,14 @@ public class MessageView extends K9Activity implements OnClickListener mSpam.setEnabled(!mMessageReference.folderName.equals(mAccount.getSpamFolderName()) && !K9.FOLDER_NONE.equalsIgnoreCase(mAccount.getSpamFolderName())); mMove.setEnabled(true); - } - else - { + } else { disableMoveButtons(); } } - private void staticButtons() - { + private void staticButtons() { View buttons = findViewById(R.id.scrolling_buttons); - if (buttons != null) - { + if (buttons != null) { buttons.setVisibility(View.GONE); } next = findViewById(R.id.next); @@ -801,11 +662,9 @@ public class MessageView extends K9Activity implements OnClickListener mDelete = findViewById(R.id.delete); } - private void scrollButtons() - { + private void scrollButtons() { View buttons = findViewById(R.id.bottom_buttons); - if (buttons != null) - { + if (buttons != null) { buttons.setVisibility(View.GONE); } next = findViewById(R.id.next_scrolling); @@ -813,11 +672,9 @@ public class MessageView extends K9Activity implements OnClickListener mDelete = findViewById(R.id.delete_scrolling); } - private void staticMoveButtons() - { + private void staticMoveButtons() { View buttons = findViewById(R.id.scrolling_move_buttons); - if (buttons != null) - { + if (buttons != null) { buttons.setVisibility(View.GONE); } mArchive = findViewById(R.id.archive); @@ -825,11 +682,9 @@ public class MessageView extends K9Activity implements OnClickListener mSpam = findViewById(R.id.spam); } - private void scrollMoveButtons() - { + private void scrollMoveButtons() { View buttons = findViewById(R.id.move_buttons); - if (buttons != null) - { + if (buttons != null) { buttons.setVisibility(View.GONE); } mArchive = findViewById(R.id.archive_scrolling); @@ -837,8 +692,7 @@ public class MessageView extends K9Activity implements OnClickListener mSpam = findViewById(R.id.spam_scrolling); } - private void disableButtons() - { + private void disableButtons() { setLoadPictures(false); disableMoveButtons(); next.setEnabled(false); @@ -846,24 +700,20 @@ public class MessageView extends K9Activity implements OnClickListener mDelete.setEnabled(false); } - private void disableMoveButtons() - { + private void disableMoveButtons() { mArchive.setEnabled(false); mMove.setEnabled(false); mSpam.setEnabled(false); } - private void setOnClickListener(int viewCode) - { + private void setOnClickListener(int viewCode) { View thisView = findViewById(viewCode); - if (thisView != null) - { + if (thisView != null) { thisView.setOnClickListener(this); } } - private void findSurroundingMessagesUid() - { + private void findSurroundingMessagesUid() { mNextMessage = mPreviousMessage = null; int i = mMessageReferences.indexOf(mMessageReference); if (i < 0) @@ -875,11 +725,9 @@ public class MessageView extends K9Activity implements OnClickListener } @Override - public void onResume() - { + public void onResume() { super.onResume(); - if (!mAccount.isAvailable(this)) - { + if (!mAccount.isAvailable(this)) { onAccountUnavailable(); return; } @@ -887,14 +735,12 @@ public class MessageView extends K9Activity implements OnClickListener } @Override - protected void onPause() - { + protected void onPause() { StorageManager.getInstance(getApplication()).removeListener(mStorageListener); super.onPause(); } - protected void onAccountUnavailable() - { + protected void onAccountUnavailable() { finish(); // TODO inform user about account unavailability using Toast Accounts.listAccounts(this); @@ -903,14 +749,10 @@ public class MessageView extends K9Activity implements OnClickListener /** * Called from UI thread when user select Delete */ - private void onDelete() - { - if (K9.confirmDelete()) - { + private void onDelete() { + if (K9.confirmDelete()) { showDialog(R.id.dialog_confirm_delete); - } - else - { + } else { delete(); } } @@ -919,37 +761,30 @@ public class MessageView extends K9Activity implements OnClickListener * @param id * @return Never null */ - protected Dialog createConfirmDeleteDialog(final int id) - { + protected Dialog createConfirmDeleteDialog(final int id) { final AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.dialog_confirm_delete_title); builder.setMessage(R.string.dialog_confirm_delete_message); builder.setPositiveButton(R.string.dialog_confirm_delete_confirm_button, - new DialogInterface.OnClickListener() - { + new DialogInterface.OnClickListener() { @Override - public void onClick(DialogInterface dialog, int which) - { + public void onClick(DialogInterface dialog, int which) { dismissDialog(id); delete(); } }); builder.setNegativeButton(R.string.dialog_confirm_delete_cancel_button, - new DialogInterface.OnClickListener() - { + new DialogInterface.OnClickListener() { @Override - public void onClick(DialogInterface dialog, int which) - { + public void onClick(DialogInterface dialog, int which) { dismissDialog(id); } }); return builder.create(); } - private void delete() - { - if (mMessage != null) - { + private void delete() { + if (mMessage != null) { // Disable the delete button after it's tapped (to try to prevent // accidental clicks) disableButtons(); @@ -961,22 +796,18 @@ public class MessageView extends K9Activity implements OnClickListener } } - private void onRefile(String dstFolder) - { - if (!mController.isMoveCapable(mAccount)) - { + private void onRefile(String dstFolder) { + if (!mController.isMoveCapable(mAccount)) { return; } - if (!mController.isMoveCapable(mMessage)) - { + if (!mController.isMoveCapable(mMessage)) { Toast toast = Toast.makeText(this, R.string.move_copy_cannot_copy_unsynced_message, Toast.LENGTH_LONG); toast.show(); return; } String srcFolder = mMessageReference.folderName; Message messageToMove = mMessage; - if (K9.FOLDER_NONE.equalsIgnoreCase(dstFolder)) - { + if (K9.FOLDER_NONE.equalsIgnoreCase(dstFolder)) { return; } showNextMessageOrReturn(); @@ -986,100 +817,72 @@ public class MessageView extends K9Activity implements OnClickListener - private void showNextMessageOrReturn() - { - if (K9.messageViewReturnToList()) - { + private void showNextMessageOrReturn() { + if (K9.messageViewReturnToList()) { finish(); - } - else - { + } else { showNextMessage(); } } - private void showNextMessage() - { + private void showNextMessage() { findSurroundingMessagesUid(); mMessageReferences.remove(mMessageReference); - if (mLastDirection == NEXT && mNextMessage != null) - { + if (mLastDirection == NEXT && mNextMessage != null) { onNext(); - } - else if (mLastDirection == PREVIOUS && mPreviousMessage != null) - { + } else if (mLastDirection == PREVIOUS && mPreviousMessage != null) { onPrevious(); - } - else if (mNextMessage != null) - { + } else if (mNextMessage != null) { onNext(); - } - else if (mPreviousMessage != null) - { + } else if (mPreviousMessage != null) { onPrevious(); - } - else - { + } else { finish(); } } - private void onReply() - { - if (mMessage != null) - { + private void onReply() { + if (mMessage != null) { MessageCompose.actionReply(this, mAccount, mMessage, false, mPgpData.getDecryptedData()); finish(); } } - private void onReplyAll() - { - if (mMessage != null) - { + private void onReplyAll() { + if (mMessage != null) { MessageCompose.actionReply(this, mAccount, mMessage, true, mPgpData.getDecryptedData()); finish(); } } - private void onForward() - { - if (mMessage != null) - { + private void onForward() { + if (mMessage != null) { MessageCompose.actionForward(this, mAccount, mMessage, mPgpData.getDecryptedData()); finish(); } } - private void onFlag() - { - if (mMessage != null) - { + private void onFlag() { + if (mMessage != null) { mController.setFlag(mAccount, mMessage.getFolder().getName(), new String[] {mMessage.getUid()}, Flag.FLAGGED, !mMessage.isSet(Flag.FLAGGED)); - try - { + try { mMessage.setFlag(Flag.FLAGGED, !mMessage.isSet(Flag.FLAGGED)); - mHandler.setHeaders( mMessage); + mHandler.setHeaders(mMessage); prepareMenuItems(); - } - catch (MessagingException me) - { + } catch (MessagingException me) { Log.e(K9.LOG_TAG, "Could not set flag on local message", me); } } } - private void onMove() - { + private void onMove() { if ((!mController.isMoveCapable(mAccount)) - || (mMessage == null)) - { + || (mMessage == null)) { return; } - if (!mController.isMoveCapable(mMessage)) - { + if (!mController.isMoveCapable(mMessage)) { Toast toast = Toast.makeText(this, R.string.move_copy_cannot_copy_unsynced_message, Toast.LENGTH_LONG); toast.show(); return; @@ -1088,15 +891,12 @@ public class MessageView extends K9Activity implements OnClickListener startRefileActivity(ACTIVITY_CHOOSE_FOLDER_MOVE); } - private void onCopy() - { + private void onCopy() { if ((!mController.isCopyCapable(mAccount)) - || (mMessage == null)) - { + || (mMessage == null)) { return; } - if (!mController.isCopyCapable(mMessage)) - { + if (!mController.isCopyCapable(mMessage)) { Toast toast = Toast.makeText(this, R.string.move_copy_cannot_copy_unsynced_message, Toast.LENGTH_LONG); toast.show(); return; @@ -1105,8 +905,7 @@ public class MessageView extends K9Activity implements OnClickListener startRefileActivity(ACTIVITY_CHOOSE_FOLDER_COPY); } - private void startRefileActivity(int activity) - { + private void startRefileActivity(int activity) { Intent intent = new Intent(this, ChooseFolder.class); intent.putExtra(ChooseFolder.EXTRA_ACCOUNT, mAccount.getUuid()); intent.putExtra(ChooseFolder.EXTRA_CUR_FOLDER, mMessageReference.folderName); @@ -1117,64 +916,54 @@ public class MessageView extends K9Activity implements OnClickListener @Override - protected void onActivityResult(int requestCode, int resultCode, Intent data) - { - if (mAccount.getCryptoProvider().onActivityResult(this, requestCode, resultCode, data, mPgpData)) - { + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + if (mAccount.getCryptoProvider().onActivityResult(this, requestCode, resultCode, data, mPgpData)) { return; } if (resultCode != RESULT_OK) return; - switch (requestCode) - { - case ACTIVITY_CHOOSE_FOLDER_MOVE: - case ACTIVITY_CHOOSE_FOLDER_COPY: - if (data == null) - return; - String destFolderName = data.getStringExtra(ChooseFolder.EXTRA_NEW_FOLDER); - String srcFolderName = data.getStringExtra(ChooseFolder.EXTRA_CUR_FOLDER); - MessageReference ref = (MessageReference) data.getSerializableExtra(ChooseFolder.EXTRA_MESSAGE); - if (mMessageReference.equals(ref)) - { - mAccount.setLastSelectedFolderName(destFolderName); - switch (requestCode) - { - case ACTIVITY_CHOOSE_FOLDER_MOVE: - Message messageToMove = mMessage; - showNextMessageOrReturn(); - mController.moveMessage(mAccount, - srcFolderName, messageToMove, destFolderName, null); - break; - case ACTIVITY_CHOOSE_FOLDER_COPY: - mController.copyMessage(mAccount, - srcFolderName, mMessage, destFolderName, null); - break; - } + switch (requestCode) { + case ACTIVITY_CHOOSE_FOLDER_MOVE: + case ACTIVITY_CHOOSE_FOLDER_COPY: + if (data == null) + return; + String destFolderName = data.getStringExtra(ChooseFolder.EXTRA_NEW_FOLDER); + String srcFolderName = data.getStringExtra(ChooseFolder.EXTRA_CUR_FOLDER); + MessageReference ref = (MessageReference) data.getSerializableExtra(ChooseFolder.EXTRA_MESSAGE); + if (mMessageReference.equals(ref)) { + mAccount.setLastSelectedFolderName(destFolderName); + switch (requestCode) { + case ACTIVITY_CHOOSE_FOLDER_MOVE: + Message messageToMove = mMessage; + showNextMessageOrReturn(); + mController.moveMessage(mAccount, + srcFolderName, messageToMove, destFolderName, null); + break; + case ACTIVITY_CHOOSE_FOLDER_COPY: + mController.copyMessage(mAccount, + srcFolderName, mMessage, destFolderName, null); + break; } - break; + } + break; } } - private void onSendAlternate() - { - if (mMessage != null) - { + private void onSendAlternate() { + if (mMessage != null) { mController.sendAlternate(this, mAccount, mMessage); } } @Override - protected void onNext() - { - if (mNextMessage == null) - { + protected void onNext() { + if (mNextMessage == null) { Toast.makeText(this, getString(R.string.end_of_folder), Toast.LENGTH_SHORT).show(); return; } mLastDirection = NEXT; disableButtons(); - if (K9.showAnimations()) - { + if (K9.showAnimations()) { mTopView.startAnimation(outToLeftAnimation()); } displayMessage(mNextMessage); @@ -1182,52 +971,42 @@ public class MessageView extends K9Activity implements OnClickListener } @Override - protected void onPrevious() - { - if (mPreviousMessage == null) - { + protected void onPrevious() { + if (mPreviousMessage == null) { Toast.makeText(this, getString(R.string.end_of_folder), Toast.LENGTH_SHORT).show(); return; } mLastDirection = PREVIOUS; disableButtons(); - if (K9.showAnimations()) - { + if (K9.showAnimations()) { mTopView.startAnimation(inFromRightAnimation()); } displayMessage(mPreviousMessage); previous.requestFocus(); } - private void onMarkAsUnread() - { - if (mMessage != null) - { + private void onMarkAsUnread() { + if (mMessage != null) { mController.setFlag( mAccount, mMessageReference.folderName, new String[] { mMessage.getUid() }, Flag.SEEN, false); - try - { + try { mMessage.setFlag(Flag.SEEN, false); mHandler.setHeaders(mMessage); String subject = mMessage.getSubject(); setTitle(subject); - } - catch (Exception e) - { + } catch (Exception e) { Log.e(K9.LOG_TAG, "Unable to unset SEEN flag on message", e); } } } - private void onDownloadRemainder() - { - if (mMessage.isSet(Flag.X_DOWNLOADED_FULL)) - { + private void onDownloadRemainder() { + if (mMessage.isSet(Flag.X_DOWNLOADED_FULL)) { return; } mDownloadRemainder.setEnabled(false); @@ -1238,8 +1017,7 @@ public class MessageView extends K9Activity implements OnClickListener mListener); } - private void onShowPictures() - { + private void onShowPictures() { // TODO: Download attachments that are used as inline image setLoadPictures(true); } @@ -1251,152 +1029,139 @@ public class MessageView extends K9Activity implements OnClickListener * @param enable true, if (network) images should be loaded. * false, otherwise. */ - private void setLoadPictures(boolean enable) - { + private void setLoadPictures(boolean enable) { mMessageContentView.blockNetworkData(!enable); mShowPictures = enable; mHandler.showShowPictures(false); } - public void onClick(View view) - { - switch (view.getId()) - { - case R.id.reply: - case R.id.reply_scrolling: - onReply(); - break; - case R.id.reply_all: - onReplyAll(); - break; - case R.id.delete: - case R.id.delete_scrolling: - onDelete(); - break; - case R.id.forward: - case R.id.forward_scrolling: - onForward(); - break; - case R.id.archive: - case R.id.archive_scrolling: - onRefile(mAccount.getArchiveFolderName()); - break; - case R.id.spam: - case R.id.spam_scrolling: - onRefile(mAccount.getSpamFolderName()); - break; - case R.id.move: - case R.id.move_scrolling: - onMove(); - break; - case R.id.next: - case R.id.next_scrolling: - onNext(); - break; - case R.id.previous: - case R.id.previous_scrolling: - onPrevious(); - break; - case R.id.download: - ((AttachmentView)view).saveFile(); - break; - case R.id.show_pictures: - onShowPictures(); - break; - case R.id.download_remainder: - onDownloadRemainder(); - break; + public void onClick(View view) { + switch (view.getId()) { + case R.id.reply: + case R.id.reply_scrolling: + onReply(); + break; + case R.id.reply_all: + onReplyAll(); + break; + case R.id.delete: + case R.id.delete_scrolling: + onDelete(); + break; + case R.id.forward: + case R.id.forward_scrolling: + onForward(); + break; + case R.id.archive: + case R.id.archive_scrolling: + onRefile(mAccount.getArchiveFolderName()); + break; + case R.id.spam: + case R.id.spam_scrolling: + onRefile(mAccount.getSpamFolderName()); + break; + case R.id.move: + case R.id.move_scrolling: + onMove(); + break; + case R.id.next: + case R.id.next_scrolling: + onNext(); + break; + case R.id.previous: + case R.id.previous_scrolling: + onPrevious(); + break; + case R.id.download: + ((AttachmentView)view).saveFile(); + break; + case R.id.show_pictures: + onShowPictures(); + break; + case R.id.download_remainder: + onDownloadRemainder(); + break; } } @Override - public boolean onOptionsItemSelected(MenuItem item) - { - switch (item.getItemId()) - { - case R.id.delete: - onDelete(); - break; - case R.id.reply: - onReply(); - break; - case R.id.reply_all: - onReplyAll(); - break; - case R.id.forward: - onForward(); - break; - case R.id.send_alternate: - onSendAlternate(); - break; - case R.id.mark_as_unread: - onMarkAsUnread(); - break; - case R.id.flag: - onFlag(); - break; - case R.id.archive: - onRefile(mAccount.getArchiveFolderName()); - break; - case R.id.spam: - onRefile(mAccount.getSpamFolderName()); - break; - case R.id.move: - onMove(); - break; - case R.id.copy: - onCopy(); - break; - case R.id.show_full_header: - runOnUiThread(new Runnable() - { - @Override public void run() - { - mHeaderContainer.onShowAdditionalHeaders(); - } - }); - break; - case R.id.select_text: - mToggleScrollView.setScrolling(false); - mMessageContentView.emulateShiftHeld(); - break; - default: - return super.onOptionsItemSelected(item); + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + case R.id.delete: + onDelete(); + break; + case R.id.reply: + onReply(); + break; + case R.id.reply_all: + onReplyAll(); + break; + case R.id.forward: + onForward(); + break; + case R.id.send_alternate: + onSendAlternate(); + break; + case R.id.mark_as_unread: + onMarkAsUnread(); + break; + case R.id.flag: + onFlag(); + break; + case R.id.archive: + onRefile(mAccount.getArchiveFolderName()); + break; + case R.id.spam: + onRefile(mAccount.getSpamFolderName()); + break; + case R.id.move: + onMove(); + break; + case R.id.copy: + onCopy(); + break; + case R.id.show_full_header: + runOnUiThread(new Runnable() { + @Override public void run() { + mHeaderContainer.onShowAdditionalHeaders(); + } + }); + break; + case R.id.select_text: + mToggleScrollView.setScrolling(false); + mMessageContentView.emulateShiftHeld(); + break; + default: + return super.onOptionsItemSelected(item); } return true; } @Override - public boolean onCreateOptionsMenu(Menu menu) - { + public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.message_view_option, menu); optionsMenu = menu; prepareMenuItems(); - if (!mController.isCopyCapable(mAccount)) - { + if (!mController.isCopyCapable(mAccount)) { menu.findItem(R.id.copy).setVisible(false); } - if (!mController.isMoveCapable(mAccount)) - { + if (!mController.isMoveCapable(mAccount)) { menu.findItem(R.id.move).setVisible(false); menu.findItem(R.id.archive).setVisible(false); menu.findItem(R.id.spam).setVisible(false); } - if (K9.FOLDER_NONE.equalsIgnoreCase(mAccount.getArchiveFolderName())) - { + if (K9.FOLDER_NONE.equalsIgnoreCase(mAccount.getArchiveFolderName())) { menu.findItem(R.id.archive).setVisible(false); } - if (K9.FOLDER_NONE.equalsIgnoreCase(mAccount.getSpamFolderName())) - { + if (K9.FOLDER_NONE.equalsIgnoreCase(mAccount.getSpamFolderName())) { menu.findItem(R.id.spam).setVisible(false); } return true; } @Override - public boolean onPrepareOptionsMenu(Menu menu) - { + public boolean onPrepareOptionsMenu(Menu menu) { prepareMenuItems(); return super.onPrepareOptionsMenu(menu); } @@ -1408,77 +1173,58 @@ public class MessageView extends K9Activity implements OnClickListener * @see android.app.Activity#onCreateDialog(int) */ @Override - protected Dialog onCreateDialog(final int id) - { - switch (id) - { - case R.id.dialog_confirm_delete: - { - return createConfirmDeleteDialog(id); - } + protected Dialog onCreateDialog(final int id) { + switch (id) { + case R.id.dialog_confirm_delete: { + return createConfirmDeleteDialog(id); + } } return super.onCreateDialog(id); } - private void prepareMenuItems() - { + private void prepareMenuItems() { Menu menu = optionsMenu; - if (menu != null) - { + if (menu != null) { MenuItem flagItem = menu.findItem(R.id.flag); - if (flagItem != null && mMessage != null) - { + if (flagItem != null && mMessage != null) { flagItem.setTitle((mMessage.isSet(Flag.FLAGGED) ? R.string.unflag_action : R.string.flag_action)); } MenuItem additionalHeadersItem = menu.findItem(R.id.show_full_header); - if (additionalHeadersItem != null) - { + if (additionalHeadersItem != null) { additionalHeadersItem.setTitle(mHeaderContainer.additionalHeadersVisible() ? R.string.hide_full_header_action : R.string.show_full_header_action); } } } - public void displayMessage(Account account, String folder, String uid, Message message) - { - try - { + public void displayMessage(Account account, String folder, String uid, Message message) { + try { if (MessageView.this.mMessage != null && MessageView.this.mMessage.isSet(Flag.X_DOWNLOADED_PARTIAL) - && message.isSet(Flag.X_DOWNLOADED_FULL)) - { + && message.isSet(Flag.X_DOWNLOADED_FULL)) { mHandler.setHeaders(message); } MessageView.this.mMessage = message; mHandler.removeAllAttachments(); String text, type; - if (mPgpData.getDecryptedData() != null) - { + if (mPgpData.getDecryptedData() != null) { text = mPgpData.getDecryptedData(); type = "text/plain"; - } - else - { + } else { // getTextForDisplay() always returns HTML-ified content. text = ((LocalMessage) mMessage).getTextForDisplay(); type = "text/html"; } - if (text != null) - { + if (text != null) { final String emailText = text; final String contentType = type; - mHandler.post(new Runnable() - { - public void run() - { + mHandler.post(new Runnable() { + public void run() { mTopView.scrollTo(0, 0); - if (mScreenReaderEnabled) - { + if (mScreenReaderEnabled) { mAccessibleMessageContentView.loadDataWithBaseURL("http://", emailText, contentType, "utf-8", null); - } - else - { + } else { mMessageContentView.loadDataWithBaseURL("http://", emailText, contentType, "utf-8", null); mMessageContentView.scrollTo(0, 0); @@ -1489,97 +1235,72 @@ public class MessageView extends K9Activity implements OnClickListener // If the message contains external pictures and the "Show pictures" // button wasn't already pressed, see if the user's preferences has us // showing them anyway. - if (Utility.hasExternalImages(text) && !mShowPictures) - { + if (Utility.hasExternalImages(text) && !mShowPictures) { if ((account.getShowPictures() == Account.ShowPictures.ALWAYS) || ((account.getShowPictures() == Account.ShowPictures.ONLY_FROM_CONTACTS) && - mContacts.isInContacts(message.getFrom()[0].getAddress()))) - { + mContacts.isInContacts(message.getFrom()[0].getAddress()))) { onShowPictures(); - } - else - { + } else { mHandler.showShowPictures(true); } } - } - else - { - mHandler.post(new Runnable() - { - public void run() - { + } else { + mHandler.post(new Runnable() { + public void run() { mMessageContentView.loadUrl("file:///android_asset/empty.html"); updateDecryptLayout(); } }); } renderAttachments(mMessage, 0); - } - catch (Exception e) - { - if (Config.LOGV) - { + } catch (Exception e) { + if (Config.LOGV) { Log.v(K9.LOG_TAG, "loadMessageForViewBodyAvailable", e); } } } - private void renderAttachments(Part part, int depth) throws MessagingException - { - if (part.getBody() instanceof Multipart) - { + private void renderAttachments(Part part, int depth) throws MessagingException { + if (part.getBody() instanceof Multipart) { Multipart mp = (Multipart) part.getBody(); - for (int i = 0; i < mp.getCount(); i++) - { + for (int i = 0; i < mp.getCount(); i++) { renderAttachments(mp.getBodyPart(i), depth + 1); } - } - else if (part instanceof LocalAttachmentBodyPart) - { + } else if (part instanceof LocalAttachmentBodyPart) { String contentDisposition = MimeUtility.unfoldAndDecode(part.getDisposition()); // Inline parts with a content-id are almost certainly components of an HTML message // not attachments. Don't show attachment download buttons for them. if (contentDisposition != null && MimeUtility.getHeaderParameter(contentDisposition, null).matches("^(?i:inline)") - && part.getHeader("Content-ID") != null) - { + && part.getHeader("Content-ID") != null) { return; } renderPartAsAttachment(part); } } - private void renderPartAsAttachment(Part part) throws MessagingException - { + private void renderPartAsAttachment(Part part) throws MessagingException { LayoutInflater inflater = getLayoutInflater(); AttachmentView view = (AttachmentView)inflater.inflate(R.layout.message_view_attachment, null); - if (view.populateFromPart(part, mMessage, mAccount, mController, mListener)) - { + if (view.populateFromPart(part, mMessage, mAccount, mController, mListener)) { mHandler.addAttachment(view); } return; } - class Listener extends MessagingListener - { + class Listener extends MessagingListener { @Override public void loadMessageForViewHeadersAvailable(Account account, String folder, String uid, - final Message message) - { + final Message message) { if (!mMessageReference.uid.equals(uid) || !mMessageReference.folderName.equals(folder) - || !mMessageReference.accountUuid.equals(account.getUuid())) - { + || !mMessageReference.accountUuid.equals(account.getUuid())) { return; } MessageView.this.mMessage = message; if (!message.isSet(Flag.X_DOWNLOADED_FULL) - && !message.isSet(Flag.X_DOWNLOADED_PARTIAL)) - { - mHandler.post(new Runnable() - { - public void run() - { + && !message.isSet(Flag.X_DOWNLOADED_PARTIAL)) { + mHandler.post(new Runnable() { + public void run() { mMessageContentView.loadUrl("file:///android_asset/downloading.html"); updateDecryptLayout(); } @@ -1590,11 +1311,9 @@ public class MessageView extends K9Activity implements OnClickListener @Override public void loadMessageForViewBodyAvailable(Account account, String folder, String uid, - Message message) - { + Message message) { if (!mMessageReference.uid.equals(uid) || !mMessageReference.folderName.equals(folder) - || !mMessageReference.accountUuid.equals(account.getUuid())) - { + || !mMessageReference.accountUuid.equals(account.getUuid())) { return; } @@ -1605,29 +1324,21 @@ public class MessageView extends K9Activity implements OnClickListener @Override public void loadMessageForViewFailed(Account account, String folder, String uid, - final Throwable t) - { + final Throwable t) { if (!mMessageReference.uid.equals(uid) || !mMessageReference.folderName.equals(folder) - || !mMessageReference.accountUuid.equals(account.getUuid())) - { + || !mMessageReference.accountUuid.equals(account.getUuid())) { return; } - mHandler.post(new Runnable() - { - public void run() - { + mHandler.post(new Runnable() { + public void run() { setProgressBarIndeterminateVisibility(false); - if (t instanceof IllegalArgumentException) - { + if (t instanceof IllegalArgumentException) { mHandler.invalidIdError(); - } - else - { + } else { mHandler.networkError(); } if ((MessageView.this.mMessage == null) || - !MessageView.this.mMessage.isSet(Flag.X_DOWNLOADED_PARTIAL)) - { + !MessageView.this.mMessage.isSet(Flag.X_DOWNLOADED_PARTIAL)) { mMessageContentView.loadUrl("file:///android_asset/empty.html"); updateDecryptLayout(); } @@ -1637,34 +1348,26 @@ public class MessageView extends K9Activity implements OnClickListener @Override public void loadMessageForViewFinished(Account account, String folder, String uid, - Message message) - { + Message message) { if (!mMessageReference.uid.equals(uid) || !mMessageReference.folderName.equals(folder) - || !mMessageReference.accountUuid.equals(account.getUuid())) - { + || !mMessageReference.accountUuid.equals(account.getUuid())) { return; } - mHandler.post(new Runnable() - { - public void run() - { + mHandler.post(new Runnable() { + public void run() { setProgressBarIndeterminateVisibility(false); } }); } @Override - public void loadMessageForViewStarted(Account account, String folder, String uid) - { + public void loadMessageForViewStarted(Account account, String folder, String uid) { if (!mMessageReference.uid.equals(uid) || !mMessageReference.folderName.equals(folder) - || !mMessageReference.accountUuid.equals(account.getUuid())) - { + || !mMessageReference.accountUuid.equals(account.getUuid())) { return; } - mHandler.post(new Runnable() - { - public void run() - { + mHandler.post(new Runnable() { + public void run() { updateDecryptLayout(); setProgressBarIndeterminateVisibility(true); } @@ -1673,26 +1376,21 @@ public class MessageView extends K9Activity implements OnClickListener @Override public void loadAttachmentStarted(Account account, Message message, - Part part, Object tag, boolean requiresDownload) - { - if (mMessage != message) - { + Part part, Object tag, boolean requiresDownload) { + if (mMessage != message) { return; } mHandler.setAttachmentsEnabled(false); mHandler.progress(true); - if (requiresDownload) - { + if (requiresDownload) { mHandler.fetchingAttachment(); } } @Override public void loadAttachmentFinished(Account account, Message message, - Part part, Object tag) - { - if (mMessage != message) - { + Part part, Object tag) { + if (mMessage != message) { return; } mHandler.setAttachmentsEnabled(true); @@ -1700,23 +1398,18 @@ public class MessageView extends K9Activity implements OnClickListener Object[] params = (Object[]) tag; boolean download = (Boolean) params[0]; AttachmentView attachment = (AttachmentView) params[1]; - if (download) - { + if (download) { attachment.writeFile(); - } - else - { + } else { attachment.showFile(); } } @Override public void loadAttachmentFailed(Account account, Message message, Part part, - Object tag, String reason) - { - if (mMessage != message) - { + Object tag, String reason) { + if (mMessage != message) { return; } mHandler.setAttachmentsEnabled(true); @@ -1726,18 +1419,13 @@ public class MessageView extends K9Activity implements OnClickListener } - private void initializeCrypto(PgpData data) - { - if (data == null) - { - if (mAccount == null) - { + private void initializeCrypto(PgpData data) { + if (data == null) { + if (mAccount == null) { mAccount = Preferences.getPreferences(this).getAccount(mMessageReference.accountUuid); } mPgpData = new PgpData(); - } - else - { + } else { mPgpData = data; } } @@ -1746,56 +1434,40 @@ public class MessageView extends K9Activity implements OnClickListener * Fill the decrypt layout with signature data, if known, make controls visible, if * they should be visible. */ - public void updateDecryptLayout() - { - if (mPgpData.getSignatureKeyId() != 0) - { + public void updateDecryptLayout() { + if (mPgpData.getSignatureKeyId() != 0) { mCryptoSignatureUserIdRest.setText( getString(R.string.key_id, Long.toHexString(mPgpData.getSignatureKeyId() & 0xffffffffL))); String userId = mPgpData.getSignatureUserId(); - if (userId == null) - { + if (userId == null) { userId = getString(R.string.unknown_crypto_signature_user_id); } String chunks[] = userId.split(" <", 2); String name = chunks[0]; - if (chunks.length > 1) - { + if (chunks.length > 1) { mCryptoSignatureUserIdRest.setText("<" + chunks[1]); } mCryptoSignatureUserId.setText(name); - if (mPgpData.getSignatureSuccess()) - { + if (mPgpData.getSignatureSuccess()) { mCryptoSignatureStatusImage.setImageResource(R.drawable.overlay_ok); - } - else if (mPgpData.getSignatureUnknown()) - { + } else if (mPgpData.getSignatureUnknown()) { mCryptoSignatureStatusImage.setImageResource(R.drawable.overlay_error); - } - else - { + } else { mCryptoSignatureStatusImage.setImageResource(R.drawable.overlay_error); } mCryptoSignatureLayout.setVisibility(View.VISIBLE); mDecryptLayout.setVisibility(View.VISIBLE); - } - else - { + } else { mCryptoSignatureLayout.setVisibility(View.INVISIBLE); } - if (false || ((mMessage == null) && (mPgpData.getDecryptedData() == null))) - { + if (false || ((mMessage == null) && (mPgpData.getDecryptedData() == null))) { mDecryptLayout.setVisibility(View.GONE); return; } - if (mPgpData.getDecryptedData() != null) - { - if (mPgpData.getSignatureKeyId() == 0) - { + if (mPgpData.getDecryptedData() != null) { + if (mPgpData.getSignatureKeyId() == 0) { mDecryptLayout.setVisibility(View.GONE); - } - else - { + } else { // no need to show this after decryption/verification mDecryptButton.setVisibility(View.GONE); } @@ -1803,37 +1475,27 @@ public class MessageView extends K9Activity implements OnClickListener } mDecryptButton.setVisibility(View.VISIBLE); CryptoProvider crypto = mAccount.getCryptoProvider(); - if (crypto.isEncrypted(mMessage)) - { + if (crypto.isEncrypted(mMessage)) { mDecryptButton.setText(R.string.btn_decrypt); mDecryptLayout.setVisibility(View.VISIBLE); - } - else if (crypto.isSigned(mMessage)) - { + } else if (crypto.isSigned(mMessage)) { mDecryptButton.setText(R.string.btn_verify); mDecryptLayout.setVisibility(View.VISIBLE); - } - else - { + } else { mDecryptLayout.setVisibility(View.GONE); - try - { + try { // check for PGP/MIME encryption Part pgp = MimeUtility.findFirstPartByMimeType(mMessage, "application/pgp-encrypted"); - if (pgp != null) - { + if (pgp != null) { Toast.makeText(this, R.string.pgp_mime_unsupported, Toast.LENGTH_LONG).show(); } - } - catch (MessagingException e) - { + } catch (MessagingException e) { // nothing to do... } } } - public void onDecryptDone() - { + public void onDecryptDone() { // TODO: this might not be enough if the orientation was changed while in APG, // sometimes shows the original encrypted content mMessageContentView.loadDataWithBaseURL("email://", mPgpData.getDecryptedData(), "text/plain", "utf-8", null); diff --git a/src/com/fsck/k9/activity/ProgressListener.java b/src/com/fsck/k9/activity/ProgressListener.java index 6d8f6fdc3..5617b0616 100644 --- a/src/com/fsck/k9/activity/ProgressListener.java +++ b/src/com/fsck/k9/activity/ProgressListener.java @@ -6,8 +6,7 @@ import android.content.Context; /** * A listener that the user can register for global, persistent progress events. */ -public interface ProgressListener -{ +public interface ProgressListener { /** * @param context * @param title diff --git a/src/com/fsck/k9/activity/Search.java b/src/com/fsck/k9/activity/Search.java index 52f3c4a4d..3f2a2a077 100644 --- a/src/com/fsck/k9/activity/Search.java +++ b/src/com/fsck/k9/activity/Search.java @@ -2,7 +2,6 @@ package com.fsck.k9.activity; import com.fsck.k9.activity.MessageList; -public class Search extends MessageList -{ +public class Search extends MessageList { } diff --git a/src/com/fsck/k9/activity/SearchModifier.java b/src/com/fsck/k9/activity/SearchModifier.java index c9e48ca81..b23330c80 100644 --- a/src/com/fsck/k9/activity/SearchModifier.java +++ b/src/com/fsck/k9/activity/SearchModifier.java @@ -6,16 +6,14 @@ package com.fsck.k9.activity; import com.fsck.k9.R; import com.fsck.k9.mail.Flag; -enum SearchModifier -{ +enum SearchModifier { FLAGGED(R.string.flagged_modifier, new Flag[] { Flag.FLAGGED}, null), UNREAD(R.string.unread_modifier, null, new Flag[] { Flag.SEEN}); final int resId; final Flag[] requiredFlags; final Flag[] forbiddenFlags; - SearchModifier(int nResId, Flag[] nRequiredFlags, Flag[] nForbiddenFlags) - { + SearchModifier(int nResId, Flag[] nRequiredFlags, Flag[] nForbiddenFlags) { resId = nResId; requiredFlags = nRequiredFlags; forbiddenFlags = nForbiddenFlags; diff --git a/src/com/fsck/k9/activity/setup/AccountSettings.java b/src/com/fsck/k9/activity/setup/AccountSettings.java index ecf577fd8..84c452110 100644 --- a/src/com/fsck/k9/activity/setup/AccountSettings.java +++ b/src/com/fsck/k9/activity/setup/AccountSettings.java @@ -36,8 +36,7 @@ import com.fsck.k9.mail.store.StorageManager; import com.fsck.k9.mail.store.LocalStore.LocalFolder; -public class AccountSettings extends K9PreferenceActivity -{ +public class AccountSettings extends K9PreferenceActivity { private static final String EXTRA_ACCOUNT = "account"; private static final int SELECT_AUTO_EXPAND_FOLDER = 1; @@ -164,29 +163,24 @@ public class AccountSettings extends K9PreferenceActivity private ListPreference mTrashFolder; - public static void actionSettings(Context context, Account account) - { + public static void actionSettings(Context context, Account account) { Intent i = new Intent(context, AccountSettings.class); i.putExtra(EXTRA_ACCOUNT, account.getUuid()); context.startActivity(i); } @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); String accountUuid = getIntent().getStringExtra(EXTRA_ACCOUNT); mAccount = Preferences.getPreferences(this).getAccount(accountUuid); - try - { + try { final Store store = mAccount.getRemoteStore(); mIsPushCapable = store.isPushCapable(); mIsExpungeCapable = store.isExpungeCapable(); - } - catch (Exception e) - { + } catch (Exception e) { Log.e(K9.LOG_TAG, "Could not get remote store", e); } @@ -195,10 +189,8 @@ public class AccountSettings extends K9PreferenceActivity mAccountDescription = (EditTextPreference) findPreference(PREFERENCE_DESCRIPTION); mAccountDescription.setSummary(mAccount.getDescription()); mAccountDescription.setText(mAccount.getDescription()); - mAccountDescription.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() - { - public boolean onPreferenceChange(Preference preference, Object newValue) - { + mAccountDescription.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { + public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); mAccountDescription.setSummary(summary); mAccountDescription.setText(summary); @@ -209,10 +201,8 @@ public class AccountSettings extends K9PreferenceActivity mMessageFormat = (ListPreference) findPreference(PREFERENCE_MESSAGE_FORMAT); mMessageFormat.setValue(mAccount.getMessageFormat().name()); mMessageFormat.setSummary(mMessageFormat.getEntry()); - mMessageFormat.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() - { - public boolean onPreferenceChange(Preference preference, Object newValue) - { + mMessageFormat.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { + public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mMessageFormat.findIndexOfValue(summary); mMessageFormat.setSummary(mMessageFormat.getEntries()[index]); @@ -224,11 +214,9 @@ public class AccountSettings extends K9PreferenceActivity mAccountQuotePrefix = (EditTextPreference) findPreference(PREFERENCE_QUOTE_PREFIX); mAccountQuotePrefix.setSummary(mAccount.getQuotePrefix()); mAccountQuotePrefix.setText(mAccount.getQuotePrefix()); - mAccountQuotePrefix.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() - { + mAccountQuotePrefix.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override - public boolean onPreferenceChange(Preference preference, Object newValue) - { + public boolean onPreferenceChange(Preference preference, Object newValue) { final String value = newValue.toString(); mAccountQuotePrefix.setSummary(value); mAccountQuotePrefix.setText(value); @@ -241,21 +229,16 @@ public class AccountSettings extends K9PreferenceActivity mComposingScreen = (PreferenceScreen) findPreference(PREFERENCE_SCREEN_COMPOSING); - Preference.OnPreferenceChangeListener quoteStyleListener = new Preference.OnPreferenceChangeListener() - { + Preference.OnPreferenceChangeListener quoteStyleListener = new Preference.OnPreferenceChangeListener() { @Override - public boolean onPreferenceChange(Preference preference, Object newValue) - { + public boolean onPreferenceChange(Preference preference, Object newValue) { final QuoteStyle style = QuoteStyle.valueOf(newValue.toString()); int index = mQuoteStyle.findIndexOfValue(newValue.toString()); mQuoteStyle.setSummary(mQuoteStyle.getEntries()[index]); - if (style == QuoteStyle.PREFIX) - { + if (style == QuoteStyle.PREFIX) { mComposingScreen.addPreference(mAccountQuotePrefix); mComposingScreen.addPreference(mReplyAfterQuote); - } - else if (style == QuoteStyle.HEADER) - { + } else if (style == QuoteStyle.HEADER) { mComposingScreen.removePreference(mAccountQuotePrefix); mComposingScreen.removePreference(mReplyAfterQuote); } @@ -273,10 +256,8 @@ public class AccountSettings extends K9PreferenceActivity mCheckFrequency = (ListPreference) findPreference(PREFERENCE_FREQUENCY); mCheckFrequency.setValue(String.valueOf(mAccount.getAutomaticCheckIntervalMinutes())); mCheckFrequency.setSummary(mCheckFrequency.getEntry()); - mCheckFrequency.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() - { - public boolean onPreferenceChange(Preference preference, Object newValue) - { + mCheckFrequency.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { + public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mCheckFrequency.findIndexOfValue(summary); mCheckFrequency.setSummary(mCheckFrequency.getEntries()[index]); @@ -288,10 +269,8 @@ public class AccountSettings extends K9PreferenceActivity mDisplayMode = (ListPreference) findPreference(PREFERENCE_DISPLAY_MODE); mDisplayMode.setValue(mAccount.getFolderDisplayMode().name()); mDisplayMode.setSummary(mDisplayMode.getEntry()); - mDisplayMode.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() - { - public boolean onPreferenceChange(Preference preference, Object newValue) - { + mDisplayMode.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { + public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mDisplayMode.findIndexOfValue(summary); mDisplayMode.setSummary(mDisplayMode.getEntries()[index]); @@ -303,10 +282,8 @@ public class AccountSettings extends K9PreferenceActivity mSyncMode = (ListPreference) findPreference(PREFERENCE_SYNC_MODE); mSyncMode.setValue(mAccount.getFolderSyncMode().name()); mSyncMode.setSummary(mSyncMode.getEntry()); - mSyncMode.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() - { - public boolean onPreferenceChange(Preference preference, Object newValue) - { + mSyncMode.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { + public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mSyncMode.findIndexOfValue(summary); mSyncMode.setSummary(mSyncMode.getEntries()[index]); @@ -319,10 +296,8 @@ public class AccountSettings extends K9PreferenceActivity mPushMode.setEnabled(mIsPushCapable); mPushMode.setValue(mAccount.getFolderPushMode().name()); mPushMode.setSummary(mPushMode.getEntry()); - mPushMode.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() - { - public boolean onPreferenceChange(Preference preference, Object newValue) - { + mPushMode.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { + public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mPushMode.findIndexOfValue(summary); mPushMode.setSummary(mPushMode.getEntries()[index]); @@ -334,10 +309,8 @@ public class AccountSettings extends K9PreferenceActivity mTargetMode = (ListPreference) findPreference(PREFERENCE_TARGET_MODE); mTargetMode.setValue(mAccount.getFolderTargetMode().name()); mTargetMode.setSummary(mTargetMode.getEntry()); - mTargetMode.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() - { - public boolean onPreferenceChange(Preference preference, Object newValue) - { + mTargetMode.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { + public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mTargetMode.findIndexOfValue(summary); mTargetMode.setSummary(mTargetMode.getEntries()[index]); @@ -349,10 +322,8 @@ public class AccountSettings extends K9PreferenceActivity mDeletePolicy = (ListPreference) findPreference(PREFERENCE_DELETE_POLICY); mDeletePolicy.setValue("" + mAccount.getDeletePolicy()); mDeletePolicy.setSummary(mDeletePolicy.getEntry()); - mDeletePolicy.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() - { - public boolean onPreferenceChange(Preference preference, Object newValue) - { + mDeletePolicy.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { + public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mDeletePolicy.findIndexOfValue(summary); mDeletePolicy.setSummary(mDeletePolicy.getEntries()[index]); @@ -365,10 +336,8 @@ public class AccountSettings extends K9PreferenceActivity mExpungePolicy.setEnabled(mIsExpungeCapable); mExpungePolicy.setValue(mAccount.getExpungePolicy()); mExpungePolicy.setSummary(mExpungePolicy.getEntry()); - mExpungePolicy.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() - { - public boolean onPreferenceChange(Preference preference, Object newValue) - { + mExpungePolicy.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { + public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mExpungePolicy.findIndexOfValue(summary); mExpungePolicy.setSummary(mExpungePolicy.getEntries()[index]); @@ -386,10 +355,8 @@ public class AccountSettings extends K9PreferenceActivity mSearchableFolders = (ListPreference) findPreference(PREFERENCE_SEARCHABLE_FOLDERS); mSearchableFolders.setValue(mAccount.getSearchableFolders().name()); mSearchableFolders.setSummary(mSearchableFolders.getEntry()); - mSearchableFolders.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() - { - public boolean onPreferenceChange(Preference preference, Object newValue) - { + mSearchableFolders.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { + public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mSearchableFolders.findIndexOfValue(summary); mSearchableFolders.setSummary(mSearchableFolders.getEntries()[index]); @@ -401,10 +368,8 @@ public class AccountSettings extends K9PreferenceActivity mDisplayCount = (ListPreference) findPreference(PREFERENCE_DISPLAY_COUNT); mDisplayCount.setValue(String.valueOf(mAccount.getDisplayCount())); mDisplayCount.setSummary(mDisplayCount.getEntry()); - mDisplayCount.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() - { - public boolean onPreferenceChange(Preference preference, Object newValue) - { + mDisplayCount.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { + public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mDisplayCount.findIndexOfValue(summary); mDisplayCount.setSummary(mDisplayCount.getEntries()[index]); @@ -416,10 +381,8 @@ public class AccountSettings extends K9PreferenceActivity mMessageAge = (ListPreference) findPreference(PREFERENCE_MESSAGE_AGE); mMessageAge.setValue(String.valueOf(mAccount.getMaximumPolledMessageAge())); mMessageAge.setSummary(mMessageAge.getEntry()); - mMessageAge.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() - { - public boolean onPreferenceChange(Preference preference, Object newValue) - { + mMessageAge.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { + public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mMessageAge.findIndexOfValue(summary); mMessageAge.setSummary(mMessageAge.getEntries()[index]); @@ -431,10 +394,8 @@ public class AccountSettings extends K9PreferenceActivity mMessageSize = (ListPreference) findPreference(PREFERENCE_MESSAGE_SIZE); mMessageSize.setValue(String.valueOf(mAccount.getMaximumAutoDownloadMessageSize())); mMessageSize.setSummary(mMessageSize.getEntry()); - mMessageSize.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() - { - public boolean onPreferenceChange(Preference preference, Object newValue) - { + mMessageSize.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { + public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mMessageSize.findIndexOfValue(summary); mMessageSize.setSummary(mMessageSize.getEntries()[index]); @@ -450,10 +411,8 @@ public class AccountSettings extends K9PreferenceActivity mAccountScrollButtons = (ListPreference) findPreference(PREFERENCE_HIDE_BUTTONS); mAccountScrollButtons.setValue("" + mAccount.getScrollMessageViewButtons()); mAccountScrollButtons.setSummary(mAccountScrollButtons.getEntry()); - mAccountScrollButtons.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() - { - public boolean onPreferenceChange(Preference preference, Object newValue) - { + mAccountScrollButtons.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { + public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mAccountScrollButtons.findIndexOfValue(summary); mAccountScrollButtons.setSummary(mAccountScrollButtons.getEntries()[index]); @@ -468,10 +427,8 @@ public class AccountSettings extends K9PreferenceActivity mAccountScrollMoveButtons = (ListPreference) findPreference(PREFERENCE_HIDE_MOVE_BUTTONS); mAccountScrollMoveButtons.setValue("" + mAccount.getScrollMessageViewMoveButtons()); mAccountScrollMoveButtons.setSummary(mAccountScrollMoveButtons.getEntry()); - mAccountScrollMoveButtons.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() - { - public boolean onPreferenceChange(Preference preference, Object newValue) - { + mAccountScrollMoveButtons.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { + public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mAccountScrollMoveButtons.findIndexOfValue(summary); mAccountScrollMoveButtons.setSummary(mAccountScrollMoveButtons.getEntries()[index]); @@ -483,10 +440,8 @@ public class AccountSettings extends K9PreferenceActivity mAccountShowPictures = (ListPreference) findPreference(PREFERENCE_SHOW_PICTURES); mAccountShowPictures.setValue("" + mAccount.getShowPictures()); mAccountShowPictures.setSummary(mAccountShowPictures.getEntry()); - mAccountShowPictures.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() - { - public boolean onPreferenceChange(Preference preference, Object newValue) - { + mAccountShowPictures.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { + public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mAccountShowPictures.findIndexOfValue(summary); mAccountShowPictures.setSummary(mAccountShowPictures.getEntries()[index]); @@ -503,8 +458,7 @@ public class AccountSettings extends K9PreferenceActivity int i = 0; final String[] providerLabels = new String[providers.size()]; final String[] providerIds = new String[providers.size()]; - for (final Map.Entry entry : providers.entrySet()) - { + for (final Map.Entry entry : providers.entrySet()) { providerIds[i] = entry.getKey(); providerLabels[i] = entry.getValue(); i++; @@ -514,10 +468,8 @@ public class AccountSettings extends K9PreferenceActivity mLocalStorageProvider.setValue(mAccount.getLocalStorageProviderId()); mLocalStorageProvider.setSummary(providers.get(mAccount.getLocalStorageProviderId())); - mLocalStorageProvider.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() - { - public boolean onPreferenceChange(Preference preference, Object newValue) - { + mLocalStorageProvider.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { + public boolean onPreferenceChange(Preference preference, Object newValue) { mLocalStorageProvider.setSummary(providers.get(newValue)); return true; } @@ -528,16 +480,13 @@ public class AccountSettings extends K9PreferenceActivity mPushPollOnConnect = (CheckBoxPreference) findPreference(PREFERENCE_PUSH_POLL_ON_CONNECT); mIdleRefreshPeriod = (ListPreference) findPreference(PREFERENCE_IDLE_REFRESH_PERIOD); mMaxPushFolders = (ListPreference) findPreference(PREFERENCE_MAX_PUSH_FOLDERS); - if (mIsPushCapable) - { + if (mIsPushCapable) { mPushPollOnConnect.setChecked(mAccount.isPushPollOnConnect()); mIdleRefreshPeriod.setValue(String.valueOf(mAccount.getIdleRefreshMinutes())); mIdleRefreshPeriod.setSummary(mIdleRefreshPeriod.getEntry()); - mIdleRefreshPeriod.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() - { - public boolean onPreferenceChange(Preference preference, Object newValue) - { + mIdleRefreshPeriod.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { + public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mIdleRefreshPeriod.findIndexOfValue(summary); mIdleRefreshPeriod.setSummary(mIdleRefreshPeriod.getEntries()[index]); @@ -548,10 +497,8 @@ public class AccountSettings extends K9PreferenceActivity mMaxPushFolders.setValue(String.valueOf(mAccount.getMaxPushFolders())); mMaxPushFolders.setSummary(mMaxPushFolders.getEntry()); - mMaxPushFolders.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() - { - public boolean onPreferenceChange(Preference preference, Object newValue) - { + mMaxPushFolders.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { + public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mMaxPushFolders.findIndexOfValue(summary); mMaxPushFolders.setSummary(mMaxPushFolders.getEntries()[index]); @@ -559,9 +506,7 @@ public class AccountSettings extends K9PreferenceActivity return false; } }); - } - else - { + } else { mPushPollOnConnect.setEnabled(false); mMaxPushFolders.setEnabled(false); mIdleRefreshPeriod.setEnabled(false); @@ -590,10 +535,8 @@ public class AccountSettings extends K9PreferenceActivity mAccountVibratePattern = (ListPreference) findPreference(PREFERENCE_VIBRATE_PATTERN); mAccountVibratePattern.setValue(String.valueOf(mAccount.getNotificationSetting().getVibratePattern())); mAccountVibratePattern.setSummary(mAccountVibratePattern.getEntry()); - mAccountVibratePattern.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() - { - public boolean onPreferenceChange(Preference preference, Object newValue) - { + mAccountVibratePattern.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { + public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mAccountVibratePattern.findIndexOfValue(summary); mAccountVibratePattern.setSummary(mAccountVibratePattern.getEntries()[index]); @@ -606,11 +549,9 @@ public class AccountSettings extends K9PreferenceActivity mAccountVibrateTimes = (ListPreference) findPreference(PREFERENCE_VIBRATE_TIMES); mAccountVibrateTimes.setValue(String.valueOf(mAccount.getNotificationSetting().getVibrateTimes())); mAccountVibrateTimes.setSummary(String.valueOf(mAccount.getNotificationSetting().getVibrateTimes())); - mAccountVibrateTimes.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() - { + mAccountVibrateTimes.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override - public boolean onPreferenceChange(Preference preference, Object newValue) - { + public boolean onPreferenceChange(Preference preference, Object newValue) { final String value = newValue.toString(); mAccountVibrateTimes.setSummary(value); mAccountVibrateTimes.setValue(value); @@ -631,50 +572,40 @@ public class AccountSettings extends K9PreferenceActivity new PopulateFolderPrefsTask().execute(); mChipColor = findPreference(PREFERENCE_CHIP_COLOR); - mChipColor.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() - { - public boolean onPreferenceClick(Preference preference) - { + mChipColor.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { + public boolean onPreferenceClick(Preference preference) { onChooseChipColor(); return false; } }); mLedColor = findPreference(PREFERENCE_LED_COLOR); - mLedColor.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() - { - public boolean onPreferenceClick(Preference preference) - { + mLedColor.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { + public boolean onPreferenceClick(Preference preference) { onChooseLedColor(); return false; } }); findPreference(PREFERENCE_COMPOSITION).setOnPreferenceClickListener( - new Preference.OnPreferenceClickListener() - { - public boolean onPreferenceClick(Preference preference) - { + new Preference.OnPreferenceClickListener() { + public boolean onPreferenceClick(Preference preference) { onCompositionSettings(); return true; } }); findPreference(PREFERENCE_MANAGE_IDENTITIES).setOnPreferenceClickListener( - new Preference.OnPreferenceClickListener() - { - public boolean onPreferenceClick(Preference preference) - { + new Preference.OnPreferenceClickListener() { + public boolean onPreferenceClick(Preference preference) { onManageIdentities(); return true; } }); findPreference(PREFERENCE_INCOMING).setOnPreferenceClickListener( - new Preference.OnPreferenceClickListener() - { - public boolean onPreferenceClick(Preference preference) - { + new Preference.OnPreferenceClickListener() { + public boolean onPreferenceClick(Preference preference) { mIncomingChanged = true; onIncomingSettings(); return true; @@ -682,10 +613,8 @@ public class AccountSettings extends K9PreferenceActivity }); findPreference(PREFERENCE_OUTGOING).setOnPreferenceClickListener( - new Preference.OnPreferenceClickListener() - { - public boolean onPreferenceClick(Preference preference) - { + new Preference.OnPreferenceClickListener() { + public boolean onPreferenceClick(Preference preference) { onOutgoingSettings(); return true; } @@ -693,28 +622,23 @@ public class AccountSettings extends K9PreferenceActivity mCryptoApp = (ListPreference) findPreference(PREFERENCE_CRYPTO_APP); CharSequence cryptoAppEntries[] = mCryptoApp.getEntries(); - if (!new Apg().isAvailable(this)) - { + if (!new Apg().isAvailable(this)) { int apgIndex = mCryptoApp.findIndexOfValue(Apg.NAME); - if (apgIndex >= 0) - { + if (apgIndex >= 0) { cryptoAppEntries[apgIndex] = "APG (" + getResources().getString(R.string.account_settings_crypto_app_not_available) + ")"; mCryptoApp.setEntries(cryptoAppEntries); } } mCryptoApp.setValue(String.valueOf(mAccount.getCryptoApp())); mCryptoApp.setSummary(mCryptoApp.getEntry()); - mCryptoApp.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() - { - public boolean onPreferenceChange(Preference preference, Object newValue) - { + mCryptoApp.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { + public boolean onPreferenceChange(Preference preference, Object newValue) { String value = newValue.toString(); int index = mCryptoApp.findIndexOfValue(value); mCryptoApp.setSummary(mCryptoApp.getEntries()[index]); mCryptoApp.setValue(value); handleCryptoAppDependencies(); - if (Apg.NAME.equals(value)) - { + if (Apg.NAME.equals(value)) { Apg.createInstance(null).test(AccountSettings.this); } return false; @@ -727,28 +651,21 @@ public class AccountSettings extends K9PreferenceActivity handleCryptoAppDependencies(); } - private void handleCryptoAppDependencies() - { - if ("".equals(mCryptoApp.getValue())) - { + private void handleCryptoAppDependencies() { + if ("".equals(mCryptoApp.getValue())) { mCryptoAutoSignature.setEnabled(false); - } - else - { + } else { mCryptoAutoSignature.setEnabled(true); } } @Override - public void onResume() - { + public void onResume() { super.onResume(); } - private void saveSettings() - { - if (mAccountDefault.isChecked()) - { + private void saveSettings() { + if (mAccountDefault.isChecked()) { Preferences.getPreferences(this).setDefaultAccount(mAccount); } @@ -788,8 +705,7 @@ public class AccountSettings extends K9PreferenceActivity mAccount.setTrashFolderName(mTrashFolder.getValue()); - if (mIsPushCapable) - { + if (mIsPushCapable) { mAccount.setPushPollOnConnect(mPushPollOnConnect.isChecked()); mAccount.setIdleRefreshMinutes(Integer.parseInt(mIdleRefreshPeriod.getValue())); mAccount.setMaxPushFolders(Integer.parseInt(mMaxPushFolders.getValue())); @@ -801,23 +717,18 @@ public class AccountSettings extends K9PreferenceActivity boolean needsPushRestart = mAccount.setFolderPushMode(Account.FolderMode.valueOf(mPushMode.getValue())); boolean displayModeChanged = mAccount.setFolderDisplayMode(Account.FolderMode.valueOf(mDisplayMode.getValue())); - if (mAccount.getFolderPushMode() != FolderMode.NONE) - { + if (mAccount.getFolderPushMode() != FolderMode.NONE) { needsPushRestart |= displayModeChanged; needsPushRestart |= mIncomingChanged; } SharedPreferences prefs = mAccountRingtone.getPreferenceManager().getSharedPreferences(); String newRingtone = prefs.getString(PREFERENCE_RINGTONE, null); - if (newRingtone != null) - { + if (newRingtone != null) { mAccount.getNotificationSetting().setRing(true); mAccount.getNotificationSetting().setRingtone(newRingtone); - } - else - { - if (mAccount.getNotificationSetting().shouldRing()) - { + } else { + if (mAccount.getNotificationSetting().shouldRing()) { mAccount.getNotificationSetting().setRingtone(null); } } @@ -828,94 +739,73 @@ public class AccountSettings extends K9PreferenceActivity mAccount.setEnableMoveButtons(mAccountEnableMoveButtons.isChecked()); mAccount.save(Preferences.getPreferences(this)); - if (needsRefresh && needsPushRestart) - { + if (needsRefresh && needsPushRestart) { MailService.actionReset(this, null); - } - else if (needsRefresh) - { + } else if (needsRefresh) { MailService.actionReschedulePoll(this, null); - } - else if (needsPushRestart) - { + } else if (needsPushRestart) { MailService.actionRestartPushers(this, null); } // TODO: refresh folder list here } @Override - public void onActivityResult(int requestCode, int resultCode, Intent data) - { - if (resultCode == RESULT_OK) - { - switch (requestCode) - { - case SELECT_AUTO_EXPAND_FOLDER: - mAutoExpandFolder.setSummary(translateFolder(data.getStringExtra(ChooseFolder.EXTRA_NEW_FOLDER))); - break; + public void onActivityResult(int requestCode, int resultCode, Intent data) { + if (resultCode == RESULT_OK) { + switch (requestCode) { + case SELECT_AUTO_EXPAND_FOLDER: + mAutoExpandFolder.setSummary(translateFolder(data.getStringExtra(ChooseFolder.EXTRA_NEW_FOLDER))); + break; } } super.onActivityResult(requestCode, resultCode, data); } @Override - public boolean onKeyDown(int keyCode, KeyEvent event) - { - if (keyCode == KeyEvent.KEYCODE_BACK) - { + public boolean onKeyDown(int keyCode, KeyEvent event) { + if (keyCode == KeyEvent.KEYCODE_BACK) { saveSettings(); } return super.onKeyDown(keyCode, event); } - private void onCompositionSettings() - { + private void onCompositionSettings() { AccountSetupComposition.actionEditCompositionSettings(this, mAccount); } - private void onManageIdentities() - { + private void onManageIdentities() { Intent intent = new Intent(this, ManageIdentities.class); intent.putExtra(ChooseIdentity.EXTRA_ACCOUNT, mAccount.getUuid()); startActivityForResult(intent, ACTIVITY_MANAGE_IDENTITIES); } - private void onIncomingSettings() - { + private void onIncomingSettings() { AccountSetupIncoming.actionEditIncomingSettings(this, mAccount); } - private void onOutgoingSettings() - { + private void onOutgoingSettings() { AccountSetupOutgoing.actionEditOutgoingSettings(this, mAccount); } - public void onChooseChipColor() - { - new ColorPickerDialog(this, new ColorPickerDialog.OnColorChangedListener() - { - public void colorChanged(int color) - { + public void onChooseChipColor() { + new ColorPickerDialog(this, new ColorPickerDialog.OnColorChangedListener() { + public void colorChanged(int color) { mAccount.setChipColor(color); } }, mAccount.getChipColor()).show(); } - public void onChooseLedColor() - { - new ColorPickerDialog(this, new ColorPickerDialog.OnColorChangedListener() - { - public void colorChanged(int color) - { + public void onChooseLedColor() { + new ColorPickerDialog(this, new ColorPickerDialog.OnColorChangedListener() { + public void colorChanged(int color) { mAccount.getNotificationSetting().setLedColor(color); } }, mAccount.getNotificationSetting().getLedColor()).show(); } - public void onChooseAutoExpandFolder() - { + public void onChooseAutoExpandFolder() { Intent selectIntent = new Intent(this, ChooseFolder.class); selectIntent.putExtra(ChooseFolder.EXTRA_ACCOUNT, mAccount.getUuid()); @@ -926,32 +816,23 @@ public class AccountSettings extends K9PreferenceActivity startActivityForResult(selectIntent, SELECT_AUTO_EXPAND_FOLDER); } - private String translateFolder(String in) - { - if (K9.INBOX.equalsIgnoreCase(in)) - { + private String translateFolder(String in) { + if (K9.INBOX.equalsIgnoreCase(in)) { return getString(R.string.special_mailbox_name_inbox); - } - else - { + } else { return in; } } - private String reverseTranslateFolder(String in) - { - if (getString(R.string.special_mailbox_name_inbox).equals(in)) - { + private String reverseTranslateFolder(String in) { + if (getString(R.string.special_mailbox_name_inbox).equals(in)) { return K9.INBOX; - } - else - { + } else { return in; } } - private void doVibrateTest(Preference preference) - { + private void doVibrateTest(Preference preference) { // Do the vibration to show the user what it's like. Vibrator vibrate = (Vibrator)preference.getContext().getSystemService(Context.VIBRATOR_SERVICE); vibrate.vibrate(NotificationSetting.getVibration( @@ -959,21 +840,16 @@ public class AccountSettings extends K9PreferenceActivity Integer.parseInt(mAccountVibrateTimes.getValue())), -1); } - private class PopulateFolderPrefsTask extends AsyncTask - { - List folders = new LinkedList(); + private class PopulateFolderPrefsTask extends AsyncTask { + List folders = new LinkedList(); String[] allFolderValues; String[] allFolderLabels; @Override - protected Void doInBackground(Void... params) - { - try - { + protected Void doInBackground(Void... params) { + try { folders = mAccount.getLocalStore().getPersonalNamespaces(false); - } - catch (Exception e) - { + } catch (Exception e) { /// this can't be checked in } allFolderValues = new String[folders.size()+2]; @@ -987,9 +863,8 @@ public class AccountSettings extends K9PreferenceActivity allFolderLabels[1] = mAccount.getOutboxFolderName(); - int i =2; - for (Folder folder : folders) - { + int i = 2; + for (Folder folder : folders) { allFolderLabels[i] = folder.getName(); allFolderValues[i] = folder.getName(); i++; @@ -998,8 +873,7 @@ public class AccountSettings extends K9PreferenceActivity } @Override - protected void onPreExecute() - { + protected void onPreExecute() { mAutoExpandFolder = (ListPreference)findPreference(PREFERENCE_AUTO_EXPAND_FOLDER); mAutoExpandFolder.setEnabled(false); mArchiveFolder = (ListPreference)findPreference(PREFERENCE_ARCHIVE_FOLDER); @@ -1018,15 +892,14 @@ public class AccountSettings extends K9PreferenceActivity } @Override - protected void onPostExecute(Void res) - { - initListPreference(mAutoExpandFolder, mAccount.getAutoExpandFolderName(), allFolderLabels,allFolderValues); - initListPreference(mArchiveFolder, mAccount.getArchiveFolderName(), allFolderLabels,allFolderValues); - initListPreference(mDraftsFolder, mAccount.getDraftsFolderName(), allFolderLabels,allFolderValues); - initListPreference(mOutboxFolder, mAccount.getOutboxFolderName(), allFolderLabels,allFolderValues); - initListPreference(mSentFolder, mAccount.getSentFolderName(), allFolderLabels,allFolderValues); - initListPreference(mSpamFolder, mAccount.getSpamFolderName(), allFolderLabels,allFolderValues); - initListPreference(mTrashFolder, mAccount.getTrashFolderName(), allFolderLabels,allFolderValues); + protected void onPostExecute(Void res) { + initListPreference(mAutoExpandFolder, mAccount.getAutoExpandFolderName(), allFolderLabels, allFolderValues); + initListPreference(mArchiveFolder, mAccount.getArchiveFolderName(), allFolderLabels, allFolderValues); + initListPreference(mDraftsFolder, mAccount.getDraftsFolderName(), allFolderLabels, allFolderValues); + initListPreference(mOutboxFolder, mAccount.getOutboxFolderName(), allFolderLabels, allFolderValues); + initListPreference(mSentFolder, mAccount.getSentFolderName(), allFolderLabels, allFolderValues); + initListPreference(mSpamFolder, mAccount.getSpamFolderName(), allFolderLabels, allFolderValues); + initListPreference(mTrashFolder, mAccount.getTrashFolderName(), allFolderLabels, allFolderValues); mAutoExpandFolder.setEnabled(true); mArchiveFolder.setEnabled(true); mDraftsFolder.setEnabled(true); diff --git a/src/com/fsck/k9/activity/setup/AccountSetupAccountType.java b/src/com/fsck/k9/activity/setup/AccountSetupAccountType.java index 13dc1e9e0..f4a7f34cb 100644 --- a/src/com/fsck/k9/activity/setup/AccountSetupAccountType.java +++ b/src/com/fsck/k9/activity/setup/AccountSetupAccountType.java @@ -21,8 +21,7 @@ import java.net.URI; * passed in email address, password and makeDefault are then passed on to the * AccountSetupIncoming activity. */ -public class AccountSetupAccountType extends K9Activity implements OnClickListener -{ +public class AccountSetupAccountType extends K9Activity implements OnClickListener { private static final String EXTRA_ACCOUNT = "account"; private static final String EXTRA_MAKE_DEFAULT = "makeDefault"; @@ -31,8 +30,7 @@ public class AccountSetupAccountType extends K9Activity implements OnClickListen private boolean mMakeDefault; - public static void actionSelectAccountType(Context context, Account account, boolean makeDefault) - { + public static void actionSelectAccountType(Context context, Account account, boolean makeDefault) { Intent i = new Intent(context, AccountSetupAccountType.class); i.putExtra(EXTRA_ACCOUNT, account.getUuid()); i.putExtra(EXTRA_MAKE_DEFAULT, makeDefault); @@ -40,8 +38,7 @@ public class AccountSetupAccountType extends K9Activity implements OnClickListen } @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.account_setup_account_type); ((Button)findViewById(R.id.pop)).setOnClickListener(this); @@ -53,74 +50,59 @@ public class AccountSetupAccountType extends K9Activity implements OnClickListen mMakeDefault = getIntent().getBooleanExtra(EXTRA_MAKE_DEFAULT, false); } - private void onPop() - { - try - { + private void onPop() { + try { URI uri = new URI(mAccount.getStoreUri()); uri = new URI("pop3", uri.getUserInfo(), uri.getHost(), uri.getPort(), null, null, null); mAccount.setStoreUri(uri.toString()); AccountSetupIncoming.actionIncomingSettings(this, mAccount, mMakeDefault); finish(); - } - catch (Exception use) - { + } catch (Exception use) { failure(use); } } - private void onImap() - { - try - { + private void onImap() { + try { URI uri = new URI(mAccount.getStoreUri()); uri = new URI("imap", uri.getUserInfo(), uri.getHost(), uri.getPort(), null, null, null); mAccount.setStoreUri(uri.toString()); AccountSetupIncoming.actionIncomingSettings(this, mAccount, mMakeDefault); finish(); - } - catch (Exception use) - { + } catch (Exception use) { failure(use); } } - private void onWebDav() - { - try - { + private void onWebDav() { + try { URI uri = new URI(mAccount.getStoreUri()); uri = new URI("webdav", uri.getUserInfo(), uri.getHost(), uri.getPort(), null, null, null); mAccount.setStoreUri(uri.toString()); AccountSetupIncoming.actionIncomingSettings(this, mAccount, mMakeDefault); finish(); - } - catch (Exception use) - { + } catch (Exception use) { failure(use); } } - public void onClick(View v) - { - switch (v.getId()) - { - case R.id.pop: - onPop(); - break; - case R.id.imap: - onImap(); - break; - case R.id.webdav: - onWebDav(); - break; + public void onClick(View v) { + switch (v.getId()) { + case R.id.pop: + onPop(); + break; + case R.id.imap: + onImap(); + break; + case R.id.webdav: + onWebDav(); + break; } } - private void failure(Exception use) - { + private void failure(Exception use) { Log.e(K9.LOG_TAG, "Failure", use); String toastText = getString(R.string.account_setup_bad_uri, use.getMessage()); diff --git a/src/com/fsck/k9/activity/setup/AccountSetupBasics.java b/src/com/fsck/k9/activity/setup/AccountSetupBasics.java index 2df9c811a..aff63ee2d 100644 --- a/src/com/fsck/k9/activity/setup/AccountSetupBasics.java +++ b/src/com/fsck/k9/activity/setup/AccountSetupBasics.java @@ -35,8 +35,7 @@ import java.net.URLEncoder; * AccountSetupAccountType activity. */ public class AccountSetupBasics extends K9Activity - implements OnClickListener, TextWatcher -{ + implements OnClickListener, TextWatcher { private final static String EXTRA_ACCOUNT = "com.fsck.k9.AccountSetupBasics.account"; private final static int DIALOG_NOTE = 1; private final static String STATE_KEY_PROVIDER = @@ -53,15 +52,13 @@ public class AccountSetupBasics extends K9Activity private EmailAddressValidator mEmailValidator = new EmailAddressValidator(); - public static void actionNewAccount(Context context) - { + public static void actionNewAccount(Context context) { Intent i = new Intent(context, AccountSetupBasics.class); context.startActivity(i); } @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.account_setup_basics); mPrefs = Preferences.getPreferences(this); @@ -77,59 +74,48 @@ public class AccountSetupBasics extends K9Activity mEmailView.addTextChangedListener(this); mPasswordView.addTextChangedListener(this); - if (mPrefs.getAccounts().length > 0) - { + if (mPrefs.getAccounts().length > 0) { mDefaultView.setVisibility(View.VISIBLE); } - if (savedInstanceState != null && savedInstanceState.containsKey(EXTRA_ACCOUNT)) - { + if (savedInstanceState != null && savedInstanceState.containsKey(EXTRA_ACCOUNT)) { String accountUuid = savedInstanceState.getString(EXTRA_ACCOUNT); mAccount = Preferences.getPreferences(this).getAccount(accountUuid); } - if (savedInstanceState != null && savedInstanceState.containsKey(STATE_KEY_PROVIDER)) - { + if (savedInstanceState != null && savedInstanceState.containsKey(STATE_KEY_PROVIDER)) { mProvider = (Provider)savedInstanceState.getSerializable(STATE_KEY_PROVIDER); } } @Override - public void onResume() - { + public void onResume() { super.onResume(); validateFields(); } @Override - public void onSaveInstanceState(Bundle outState) - { + public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); - if (mAccount != null) - { + if (mAccount != null) { outState.putString(EXTRA_ACCOUNT, mAccount.getUuid()); } - if (mProvider != null) - { + if (mProvider != null) { outState.putSerializable(STATE_KEY_PROVIDER, mProvider); } } - public void afterTextChanged(Editable s) - { + public void afterTextChanged(Editable s) { validateFields(); } - public void beforeTextChanged(CharSequence s, int start, int count, int after) - { + public void beforeTextChanged(CharSequence s, int start, int count, int after) { } - public void onTextChanged(CharSequence s, int start, int before, int count) - { + public void onTextChanged(CharSequence s, int start, int before, int count) { } - private void validateFields() - { + private void validateFields() { String email = mEmailView.getText().toString(); boolean valid = Utility.requiredFieldValid(mEmailView) && Utility.requiredFieldValid(mPasswordView) @@ -145,61 +131,45 @@ public class AccountSetupBasics extends K9Activity Utility.setCompoundDrawablesAlpha(mNextButton, mNextButton.isEnabled() ? 255 : 128); } - private String getOwnerName() - { + private String getOwnerName() { String name = null; - try - { + try { name = Contacts.getInstance(this).getOwnerName(); - } - catch (Exception e) - { + } catch (Exception e) { Log.e(K9.LOG_TAG, "Could not get owner name, using default account name", e); } - if (name == null || name.length() == 0) - { - try - { + if (name == null || name.length() == 0) { + try { name = getDefaultAccountName(); - } - catch (Exception e) - { + } catch (Exception e) { Log.e(K9.LOG_TAG, "Could not get default account name", e); } } - if (name == null) - { + if (name == null) { name = ""; } return name; } - private String getDefaultAccountName() - { + private String getDefaultAccountName() { String name = null; Account account = Preferences.getPreferences(this).getDefaultAccount(); - if (account != null) - { + if (account != null) { name = account.getName(); } return name; } @Override - public Dialog onCreateDialog(int id) - { - if (id == DIALOG_NOTE) - { - if (mProvider != null && mProvider.note != null) - { + public Dialog onCreateDialog(int id) { + if (id == DIALOG_NOTE) { + if (mProvider != null && mProvider.note != null) { return new AlertDialog.Builder(this) .setMessage(mProvider.note) .setPositiveButton( getString(R.string.okay_action), - new DialogInterface.OnClickListener() - { - public void onClick(DialogInterface dialog, int which) - { + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { finishAutoSetup(); } }) @@ -212,8 +182,7 @@ public class AccountSetupBasics extends K9Activity return null; } - private void finishAutoSetup() - { + private void finishAutoSetup() { String email = mEmailView.getText().toString(); String password = mPasswordView.getText().toString(); String[] emailParts = splitEmail(email); @@ -221,8 +190,7 @@ public class AccountSetupBasics extends K9Activity String domain = emailParts[1]; URI incomingUri = null; URI outgoingUri = null; - try - { + try { String userEnc = URLEncoder.encode(user, "UTF-8"); String passwordEnc = URLEncoder.encode(password, "UTF-8"); @@ -258,14 +226,10 @@ public class AccountSetupBasics extends K9Activity mAccount.setOutboxFolderName(getString(R.string.special_mailbox_name_outbox)); mAccount.setSentFolderName(getString(R.string.special_mailbox_name_sent)); AccountSetupCheckSettings.actionCheckSettings(this, mAccount, true, true); - } - catch (UnsupportedEncodingException enc) - { + } catch (UnsupportedEncodingException enc) { // This really shouldn't happen since the encoding is hardcoded to UTF-8 Log.e(K9.LOG_TAG, "Couldn't urlencode username or password.", enc); - } - catch (URISyntaxException use) - { + } catch (URISyntaxException use) { /* * If there is some problem with the URI we give up and go on to * manual setup. @@ -275,14 +239,12 @@ public class AccountSetupBasics extends K9Activity } @Override - protected void onNext() - { + protected void onNext() { String email = mEmailView.getText().toString(); String[] emailParts = splitEmail(email); String domain = emailParts[1]; mProvider = findProviderForDomain(domain); - if (mProvider == null) - { + if (mProvider == null) { /* * We don't have default settings for this account, start the manual * setup process. @@ -291,25 +253,19 @@ public class AccountSetupBasics extends K9Activity return; } - if (mProvider.note != null) - { + if (mProvider.note != null) { showDialog(DIALOG_NOTE); - } - else - { + } else { finishAutoSetup(); } } @Override - public void onActivityResult(int requestCode, int resultCode, Intent data) - { - if (resultCode == RESULT_OK) - { + public void onActivityResult(int requestCode, int resultCode, Intent data) { + if (resultCode == RESULT_OK) { mAccount.setDescription(mAccount.getEmail()); mAccount.save(Preferences.getPreferences(this)); - if (mDefaultView.isChecked()) - { + if (mDefaultView.isChecked()) { Preferences.getPreferences(this).setDefaultAccount(mAccount); } K9.setServicesEnabled(this); @@ -318,8 +274,7 @@ public class AccountSetupBasics extends K9Activity } } - private void onManualSetup() - { + private void onManualSetup() { String email = mEmailView.getText().toString(); String password = mPasswordView.getText().toString(); String[] emailParts = splitEmail(email); @@ -329,8 +284,7 @@ public class AccountSetupBasics extends K9Activity mAccount = Preferences.getPreferences(this).newAccount(); mAccount.setName(getOwnerName()); mAccount.setEmail(email); - try - { + try { String userEnc = URLEncoder.encode(user, "UTF-8"); String passwordEnc = URLEncoder.encode(password, "UTF-8"); @@ -338,14 +292,10 @@ public class AccountSetupBasics extends K9Activity null, null); mAccount.setStoreUri(uri.toString()); mAccount.setTransportUri(uri.toString()); - } - catch (UnsupportedEncodingException enc) - { + } catch (UnsupportedEncodingException enc) { // This really shouldn't happen since the encoding is hardcoded to UTF-8 Log.e(K9.LOG_TAG, "Couldn't urlencode username or password.", enc); - } - catch (URISyntaxException use) - { + } catch (URISyntaxException use) { /* * If we can't set up the URL we just continue. It's only for * convenience. @@ -360,16 +310,14 @@ public class AccountSetupBasics extends K9Activity finish(); } - public void onClick(View v) - { - switch (v.getId()) - { - case R.id.next: - onNext(); - break; - case R.id.manual_setup: - onManualSetup(); - break; + public void onClick(View v) { + switch (v.getId()) { + case R.id.next: + onNext(); + break; + case R.id.manual_setup: + onManualSetup(); + break; } } @@ -380,69 +328,52 @@ public class AccountSetupBasics extends K9Activity * @param name * @return */ - private String getXmlAttribute(XmlResourceParser xml, String name) - { + private String getXmlAttribute(XmlResourceParser xml, String name) { int resId = xml.getAttributeResourceValue(null, name, 0); - if (resId == 0) - { + if (resId == 0) { return xml.getAttributeValue(null, name); - } - else - { + } else { return getString(resId); } } - private Provider findProviderForDomain(String domain) - { - try - { + private Provider findProviderForDomain(String domain) { + try { XmlResourceParser xml = getResources().getXml(R.xml.providers); int xmlEventType; Provider provider = null; - while ((xmlEventType = xml.next()) != XmlResourceParser.END_DOCUMENT) - { + while ((xmlEventType = xml.next()) != XmlResourceParser.END_DOCUMENT) { if (xmlEventType == XmlResourceParser.START_TAG && "provider".equals(xml.getName()) - && domain.equalsIgnoreCase(getXmlAttribute(xml, "domain"))) - { + && domain.equalsIgnoreCase(getXmlAttribute(xml, "domain"))) { provider = new Provider(); provider.id = getXmlAttribute(xml, "id"); provider.label = getXmlAttribute(xml, "label"); provider.domain = getXmlAttribute(xml, "domain"); provider.note = getXmlAttribute(xml, "note"); - } - else if (xmlEventType == XmlResourceParser.START_TAG - && "incoming".equals(xml.getName()) - && provider != null) - { + } else if (xmlEventType == XmlResourceParser.START_TAG + && "incoming".equals(xml.getName()) + && provider != null) { provider.incomingUriTemplate = new URI(getXmlAttribute(xml, "uri")); provider.incomingUsernameTemplate = getXmlAttribute(xml, "username"); - } - else if (xmlEventType == XmlResourceParser.START_TAG - && "outgoing".equals(xml.getName()) - && provider != null) - { + } else if (xmlEventType == XmlResourceParser.START_TAG + && "outgoing".equals(xml.getName()) + && provider != null) { provider.outgoingUriTemplate = new URI(getXmlAttribute(xml, "uri")); provider.outgoingUsernameTemplate = getXmlAttribute(xml, "username"); - } - else if (xmlEventType == XmlResourceParser.END_TAG - && "provider".equals(xml.getName()) - && provider != null) - { + } else if (xmlEventType == XmlResourceParser.END_TAG + && "provider".equals(xml.getName()) + && provider != null) { return provider; } } - } - catch (Exception e) - { + } catch (Exception e) { Log.e(K9.LOG_TAG, "Error while trying to load provider settings.", e); } return null; } - private String[] splitEmail(String email) - { + private String[] splitEmail(String email) { String[] retParts = new String[2]; String[] emailParts = email.split("@"); retParts[0] = (emailParts.length > 0) ? emailParts[0] : ""; @@ -450,8 +381,7 @@ public class AccountSetupBasics extends K9Activity return retParts; } - static class Provider implements Serializable - { + static class Provider implements Serializable { private static final long serialVersionUID = 8511656164616538989L; public String id; diff --git a/src/com/fsck/k9/activity/setup/AccountSetupCheckSettings.java b/src/com/fsck/k9/activity/setup/AccountSetupCheckSettings.java index 35015a1b0..facae58e2 100644 --- a/src/com/fsck/k9/activity/setup/AccountSetupCheckSettings.java +++ b/src/com/fsck/k9/activity/setup/AccountSetupCheckSettings.java @@ -34,8 +34,7 @@ import java.security.cert.X509Certificate; * XXX NOTE: The manifest for this app has it ignore config changes, because * it doesn't correctly deal with restarting while its thread is running. */ -public class AccountSetupCheckSettings extends K9Activity implements OnClickListener -{ +public class AccountSetupCheckSettings extends K9Activity implements OnClickListener { public static final int ACTIVITY_REQUEST_CODE = 1; @@ -62,8 +61,7 @@ public class AccountSetupCheckSettings extends K9Activity implements OnClickList private boolean mDestroyed; public static void actionCheckSettings(Activity context, Account account, - boolean checkIncoming, boolean checkOutgoing) - { + boolean checkIncoming, boolean checkOutgoing) { Intent i = new Intent(context, AccountSetupCheckSettings.class); i.putExtra(EXTRA_ACCOUNT, account.getUuid()); i.putExtra(EXTRA_CHECK_INCOMING, checkIncoming); @@ -72,8 +70,7 @@ public class AccountSetupCheckSettings extends K9Activity implements OnClickList } @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.account_setup_check_settings); mMessageView = (TextView)findViewById(R.id.message); @@ -88,58 +85,44 @@ public class AccountSetupCheckSettings extends K9Activity implements OnClickList mCheckIncoming = getIntent().getBooleanExtra(EXTRA_CHECK_INCOMING, false); mCheckOutgoing = getIntent().getBooleanExtra(EXTRA_CHECK_OUTGOING, false); - new Thread() - { + new Thread() { @Override - public void run() - { + public void run() { Store store = null; Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); - try - { - if (mDestroyed) - { + try { + if (mDestroyed) { return; } - if (mCanceled) - { + if (mCanceled) { finish(); return; } - if (mCheckIncoming) - { + if (mCheckIncoming) { store = mAccount.getRemoteStore(); - if (store instanceof WebDavStore) - { + if (store instanceof WebDavStore) { setMessage(R.string.account_setup_check_settings_authenticate); - } - else - { + } else { setMessage(R.string.account_setup_check_settings_check_incoming_msg); } store.checkSettings(); - if (store instanceof WebDavStore) - { + if (store instanceof WebDavStore) { setMessage(R.string.account_setup_check_settings_fetch); } MessagingController.getInstance(getApplication()).listFoldersSynchronous(mAccount, true, null); MessagingController.getInstance(getApplication()).synchronizeMailbox(mAccount, K9.INBOX , null, null); } - if (mDestroyed) - { + if (mDestroyed) { return; } - if (mCanceled) - { + if (mCanceled) { finish(); return; } - if (mCheckOutgoing) - { - if (!(mAccount.getRemoteStore() instanceof WebDavStore)) - { + if (mCheckOutgoing) { + if (!(mAccount.getRemoteStore() instanceof WebDavStore)) { setMessage(R.string.account_setup_check_settings_check_outgoing_msg); } Transport transport = Transport.getInstance(mAccount); @@ -147,34 +130,26 @@ public class AccountSetupCheckSettings extends K9Activity implements OnClickList transport.open(); transport.close(); } - if (mDestroyed) - { + if (mDestroyed) { return; } - if (mCanceled) - { + if (mCanceled) { finish(); return; } setResult(RESULT_OK); finish(); - } - catch (final AuthenticationFailedException afe) - { + } catch (final AuthenticationFailedException afe) { Log.e(K9.LOG_TAG, "Error while testing settings", afe); showErrorDialog( R.string.account_setup_failed_dlg_auth_message_fmt, afe.getMessage() == null ? "" : afe.getMessage()); - } - catch (final CertificateValidationException cve) - { + } catch (final CertificateValidationException cve) { Log.e(K9.LOG_TAG, "Error while testing settings", cve); acceptKeyDialog( R.string.account_setup_failed_dlg_certificate_message_fmt, cve); - } - catch (final Throwable t) - { + } catch (final Throwable t) { Log.e(K9.LOG_TAG, "Error while testing settings", t); showErrorDialog( R.string.account_setup_failed_dlg_server_message_fmt, @@ -188,21 +163,16 @@ public class AccountSetupCheckSettings extends K9Activity implements OnClickList } @Override - public void onDestroy() - { + public void onDestroy() { super.onDestroy(); mDestroyed = true; mCanceled = true; } - private void setMessage(final int resId) - { - mHandler.post(new Runnable() - { - public void run() - { - if (mDestroyed) - { + private void setMessage(final int resId) { + mHandler.post(new Runnable() { + public void run() { + if (mDestroyed) { return; } mMessageView.setText(getString(resId)); @@ -210,14 +180,10 @@ public class AccountSetupCheckSettings extends K9Activity implements OnClickList }); } - private void showErrorDialog(final int msgResId, final Object... args) - { - mHandler.post(new Runnable() - { - public void run() - { - if (mDestroyed) - { + private void showErrorDialog(final int msgResId, final Object... args) { + mHandler.post(new Runnable() { + public void run() { + if (mDestroyed) { return; } mProgressBar.setIndeterminate(false); @@ -228,21 +194,17 @@ public class AccountSetupCheckSettings extends K9Activity implements OnClickList .setNegativeButton( getString(R.string.account_setup_failed_dlg_continue_action), - new DialogInterface.OnClickListener() - { - public void onClick(DialogInterface dialog, int which) - { - mCanceled=false; + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + mCanceled = false; setResult(RESULT_OK); finish(); } }) .setPositiveButton( getString(R.string.account_setup_failed_dlg_edit_details_action), - new DialogInterface.OnClickListener() - { - public void onClick(DialogInterface dialog, int which) - { + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { finish(); } }) @@ -250,44 +212,32 @@ public class AccountSetupCheckSettings extends K9Activity implements OnClickList } }); } - private void acceptKeyDialog(final int msgResId, final Object... args) - { - mHandler.post(new Runnable() - { - public void run() - { - if (mDestroyed) - { + private void acceptKeyDialog(final int msgResId, final Object... args) { + mHandler.post(new Runnable() { + public void run() { + if (mDestroyed) { return; } final X509Certificate[] chain = TrustManagerFactory.getLastCertChain(); String exMessage = "Unknown Error"; Exception ex = ((Exception)args[0]); - if (ex != null) - { - if (ex.getCause() != null) - { - if (ex.getCause().getCause() != null) - { + if (ex != null) { + if (ex.getCause() != null) { + if (ex.getCause().getCause() != null) { exMessage = ex.getCause().getCause().getMessage(); - } - else - { + } else { exMessage = ex.getCause().getMessage(); } - } - else - { + } else { exMessage = ex.getMessage(); } } mProgressBar.setIndeterminate(false); StringBuffer chainInfo = new StringBuffer(100); - for (int i = 0; i < chain.length; i++) - { + for (int i = 0; i < chain.length; i++) { // display certificate chain information chainInfo.append("Certificate chain[" + i + "]:\n"); chainInfo.append("Subject: " + chain[i].getSubjectDN().toString() + "\n"); @@ -297,31 +247,24 @@ public class AccountSetupCheckSettings extends K9Activity implements OnClickList new AlertDialog.Builder(AccountSetupCheckSettings.this) .setTitle(getString(R.string.account_setup_failed_dlg_invalid_certificate_title)) //.setMessage(getString(R.string.account_setup_failed_dlg_invalid_certificate) - .setMessage(getString(msgResId,exMessage) + .setMessage(getString(msgResId, exMessage) + " " + chainInfo.toString() ) .setCancelable(true) .setPositiveButton( getString(R.string.account_setup_failed_dlg_invalid_certificate_accept), - new DialogInterface.OnClickListener() - { - public void onClick(DialogInterface dialog, int which) - { - try - { + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + try { String alias = mAccount.getUuid(); - if (mCheckIncoming) - { + if (mCheckIncoming) { alias = alias + ".incoming"; } - if (mCheckOutgoing) - { + if (mCheckOutgoing) { alias = alias + ".outgoing"; } TrustManagerFactory.addCertificateChain(alias, chain); - } - catch (CertificateException e) - { + } catch (CertificateException e) { showErrorDialog( R.string.account_setup_failed_dlg_certificate_message_fmt, e.getMessage() == null ? "" : e.getMessage()); @@ -332,10 +275,8 @@ public class AccountSetupCheckSettings extends K9Activity implements OnClickList }) .setNegativeButton( getString(R.string.account_setup_failed_dlg_invalid_certificate_reject), - new DialogInterface.OnClickListener() - { - public void onClick(DialogInterface dialog, int which) - { + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { finish(); } }) @@ -345,26 +286,22 @@ public class AccountSetupCheckSettings extends K9Activity implements OnClickList } @Override - public void onActivityResult(int reqCode, int resCode, Intent data) - { + public void onActivityResult(int reqCode, int resCode, Intent data) { setResult(resCode); finish(); } - private void onCancel() - { + private void onCancel() { mCanceled = true; setMessage(R.string.account_setup_check_settings_canceling_msg); } - public void onClick(View v) - { - switch (v.getId()) - { - case R.id.cancel: - onCancel(); - break; + public void onClick(View v) { + switch (v.getId()) { + case R.id.cancel: + onCancel(); + break; } } } diff --git a/src/com/fsck/k9/activity/setup/AccountSetupComposition.java b/src/com/fsck/k9/activity/setup/AccountSetupComposition.java index 933e35999..f0bed3220 100644 --- a/src/com/fsck/k9/activity/setup/AccountSetupComposition.java +++ b/src/com/fsck/k9/activity/setup/AccountSetupComposition.java @@ -15,8 +15,7 @@ import com.fsck.k9.Preferences; import com.fsck.k9.R; import com.fsck.k9.activity.K9Activity; -public class AccountSetupComposition extends K9Activity -{ +public class AccountSetupComposition extends K9Activity { private static final String EXTRA_ACCOUNT = "account"; @@ -31,8 +30,7 @@ public class AccountSetupComposition extends K9Activity private RadioButton mAccountSignatureAfterLocation; private LinearLayout mAccountSignatureLayout; - public static void actionEditCompositionSettings(Activity context, Account account) - { + public static void actionEditCompositionSettings(Activity context, Account account) { Intent i = new Intent(context, AccountSetupComposition.class); i.setAction(Intent.ACTION_EDIT); i.putExtra(EXTRA_ACCOUNT, account.getUuid()); @@ -41,8 +39,7 @@ public class AccountSetupComposition extends K9Activity @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); String accountUuid = getIntent().getStringExtra(EXTRA_ACCOUNT); @@ -54,8 +51,7 @@ public class AccountSetupComposition extends K9Activity * If we're being reloaded we override the original account with the one * we saved */ - if (savedInstanceState != null && savedInstanceState.containsKey(EXTRA_ACCOUNT)) - { + if (savedInstanceState != null && savedInstanceState.containsKey(EXTRA_ACCOUNT)) { accountUuid = savedInstanceState.getString(EXTRA_ACCOUNT); mAccount = Preferences.getPreferences(this).getAccount(accountUuid); } @@ -74,20 +70,15 @@ public class AccountSetupComposition extends K9Activity mAccountSignatureUse = (CheckBox)findViewById(R.id.account_signature_use); boolean useSignature = mAccount.getSignatureUse(); mAccountSignatureUse.setChecked(useSignature); - mAccountSignatureUse.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() - { - public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) - { - if (isChecked) - { + mAccountSignatureUse.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { + public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { + if (isChecked) { mAccountSignatureLayout.setVisibility(View.VISIBLE); mAccountSignature.setText(mAccount.getSignature()); boolean isSignatureBeforeQuotedText = mAccount.isSignatureBeforeQuotedText(); mAccountSignatureBeforeLocation.setChecked(isSignatureBeforeQuotedText); mAccountSignatureAfterLocation.setChecked(!isSignatureBeforeQuotedText); - } - else - { + } else { mAccountSignatureLayout.setVisibility(View.GONE); } } @@ -98,35 +89,29 @@ public class AccountSetupComposition extends K9Activity mAccountSignatureBeforeLocation = (RadioButton)findViewById(R.id.account_signature_location_before_quoted_text); mAccountSignatureAfterLocation = (RadioButton)findViewById(R.id.account_signature_location_after_quoted_text); - if (useSignature) - { + if (useSignature) { mAccountSignature.setText(mAccount.getSignature()); boolean isSignatureBeforeQuotedText = mAccount.isSignatureBeforeQuotedText(); mAccountSignatureBeforeLocation.setChecked(isSignatureBeforeQuotedText); mAccountSignatureAfterLocation.setChecked(!isSignatureBeforeQuotedText); - } - else - { + } else { mAccountSignatureLayout.setVisibility(View.GONE); } } @Override - public void onResume() - { + public void onResume() { super.onResume(); //mAccount.refresh(Preferences.getPreferences(this)); } - private void saveSettings() - { + private void saveSettings() { mAccount.setEmail(mAccountEmail.getText().toString()); mAccount.setAlwaysBcc(mAccountAlwaysBcc.getText().toString()); mAccount.setName(mAccountName.getText().toString()); mAccount.setSignatureUse(mAccountSignatureUse.isChecked()); - if (mAccountSignatureUse.isChecked()) - { + if (mAccountSignatureUse.isChecked()) { mAccount.setSignature(mAccountSignature.getText().toString()); boolean isSignatureBeforeQuotedText = mAccountSignatureBeforeLocation.isChecked(); mAccount.setSignatureBeforeQuotedText(isSignatureBeforeQuotedText); @@ -136,25 +121,21 @@ public class AccountSetupComposition extends K9Activity } @Override - public boolean onKeyDown(int keyCode, KeyEvent event) - { - if (keyCode == KeyEvent.KEYCODE_BACK) - { + public boolean onKeyDown(int keyCode, KeyEvent event) { + if (keyCode == KeyEvent.KEYCODE_BACK) { saveSettings(); } return super.onKeyDown(keyCode, event); } @Override - public void onSaveInstanceState(Bundle outState) - { + public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putSerializable(EXTRA_ACCOUNT, mAccount.getUuid()); } @Override - public void onActivityResult(int requestCode, int resultCode, Intent data) - { + public void onActivityResult(int requestCode, int resultCode, Intent data) { mAccount.save(Preferences.getPreferences(this)); finish(); } diff --git a/src/com/fsck/k9/activity/setup/AccountSetupIncoming.java b/src/com/fsck/k9/activity/setup/AccountSetupIncoming.java index a4ff63aad..7d9f28155 100644 --- a/src/com/fsck/k9/activity/setup/AccountSetupIncoming.java +++ b/src/com/fsck/k9/activity/setup/AccountSetupIncoming.java @@ -22,38 +22,30 @@ import java.net.URISyntaxException; import java.net.URLDecoder; import java.net.URLEncoder; -public class AccountSetupIncoming extends K9Activity implements OnClickListener -{ +public class AccountSetupIncoming extends K9Activity implements OnClickListener { private static final String EXTRA_ACCOUNT = "account"; private static final String EXTRA_MAKE_DEFAULT = "makeDefault"; - private static final int popPorts[] = - { + private static final int popPorts[] = { 110, 995, 995, 110, 110 }; - private static final String popSchemes[] = - { + private static final String popSchemes[] = { "pop3", "pop3+ssl", "pop3+ssl+", "pop3+tls", "pop3+tls+" }; - private static final int imapPorts[] = - { + private static final int imapPorts[] = { 143, 993, 993, 143, 143 }; - private static final String imapSchemes[] = - { + private static final String imapSchemes[] = { "imap", "imap+ssl", "imap+ssl+", "imap+tls", "imap+tls+" }; - private static final int webdavPorts[] = - { + private static final int webdavPorts[] = { 80, 443, 443, 443, 443 }; - private static final String webdavSchemes[] = - { + private static final String webdavSchemes[] = { "webdav", "webdav+ssl", "webdav+ssl+", "webdav+tls", "webdav+tls+" }; - private static final String authTypes[] = - { + private static final String authTypes[] = { "PLAIN", "CRAM_MD5" }; @@ -78,16 +70,14 @@ public class AccountSetupIncoming extends K9Activity implements OnClickListener private CheckBox compressionOther; private CheckBox subscribedFoldersOnly; - public static void actionIncomingSettings(Activity context, Account account, boolean makeDefault) - { + public static void actionIncomingSettings(Activity context, Account account, boolean makeDefault) { Intent i = new Intent(context, AccountSetupIncoming.class); i.putExtra(EXTRA_ACCOUNT, account.getUuid()); i.putExtra(EXTRA_MAKE_DEFAULT, makeDefault); context.startActivity(i); } - public static void actionEditIncomingSettings(Activity context, Account account) - { + public static void actionEditIncomingSettings(Activity context, Account account) { Intent i = new Intent(context, AccountSetupIncoming.class); i.setAction(Intent.ACTION_EDIT); i.putExtra(EXTRA_ACCOUNT, account.getUuid()); @@ -95,8 +85,7 @@ public class AccountSetupIncoming extends K9Activity implements OnClickListener } @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.account_setup_incoming); @@ -119,8 +108,7 @@ public class AccountSetupIncoming extends K9Activity implements OnClickListener mNextButton.setOnClickListener(this); - SpinnerOption securityTypes[] = - { + SpinnerOption securityTypes[] = { new SpinnerOption(0, getString(R.string.account_setup_incoming_security_none_label)), new SpinnerOption(1, getString(R.string.account_setup_incoming_security_ssl_optional_label)), @@ -132,8 +120,7 @@ public class AccountSetupIncoming extends K9Activity implements OnClickListener // This needs to be kept in sync with the list at the top of the file. // that makes me somewhat unhappy - SpinnerOption authTypeSpinnerOptions[] = - { + SpinnerOption authTypeSpinnerOptions[] = { new SpinnerOption(0, "PLAIN"), new SpinnerOption(1, "CRAM_MD5") }; @@ -152,15 +139,12 @@ public class AccountSetupIncoming extends K9Activity implements OnClickListener * Updates the port when the user changes the security type. This allows * us to show a reasonable default which the user can change. */ - mSecurityTypeView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() - { - public void onItemSelected(AdapterView parent, View view, int position, long id) - { + mSecurityTypeView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + public void onItemSelected(AdapterView parent, View view, int position, long id) { updatePortFromSecurityType(); } - public void onNothingSelected(AdapterView parent) - { + public void onNothingSelected(AdapterView parent) { } }); @@ -168,19 +152,15 @@ public class AccountSetupIncoming extends K9Activity implements OnClickListener * Calls validateFields() which enables or disables the Next button * based on the fields' validity. */ - TextWatcher validationTextWatcher = new TextWatcher() - { - public void afterTextChanged(Editable s) - { + TextWatcher validationTextWatcher = new TextWatcher() { + public void afterTextChanged(Editable s) { validateFields(); } - public void beforeTextChanged(CharSequence s, int start, int count, int after) - { + public void beforeTextChanged(CharSequence s, int start, int count, int after) { } - public void onTextChanged(CharSequence s, int start, int before, int count) - { + public void onTextChanged(CharSequence s, int start, int before, int count) { } }; mUsernameView.addTextChangedListener(validationTextWatcher); @@ -201,65 +181,51 @@ public class AccountSetupIncoming extends K9Activity implements OnClickListener * If we're being reloaded we override the original account with the one * we saved */ - if (savedInstanceState != null && savedInstanceState.containsKey(EXTRA_ACCOUNT)) - { + if (savedInstanceState != null && savedInstanceState.containsKey(EXTRA_ACCOUNT)) { accountUuid = savedInstanceState.getString(EXTRA_ACCOUNT); mAccount = Preferences.getPreferences(this).getAccount(accountUuid); } - try - { + try { URI uri = new URI(mAccount.getStoreUri()); String username = null; String password = null; String authType = null; - if (uri.getUserInfo() != null) - { + if (uri.getUserInfo() != null) { String[] userInfoParts = uri.getUserInfo().split(":"); - if (userInfoParts.length == 3) - { + if (userInfoParts.length == 3) { authType = userInfoParts[0]; username = URLDecoder.decode(userInfoParts[1], "UTF-8"); password = URLDecoder.decode(userInfoParts[2], "UTF-8"); - } - else if (userInfoParts.length == 2) - { + } else if (userInfoParts.length == 2) { username = URLDecoder.decode(userInfoParts[0], "UTF-8"); password = URLDecoder.decode(userInfoParts[1], "UTF-8"); - } - else if (userInfoParts.length == 1) - { + } else if (userInfoParts.length == 1) { username = URLDecoder.decode(userInfoParts[0], "UTF-8"); } } - if (username != null) - { + if (username != null) { mUsernameView.setText(username); } - if (password != null) - { + if (password != null) { mPasswordView.setText(password); } - if (authType != null) - { - for (int i = 0; i < authTypes.length; i++) - { - if (authTypes[i].equals(authType)) - { + if (authType != null) { + for (int i = 0; i < authTypes.length; i++) { + if (authTypes[i].equals(authType)) { SpinnerOption.setSpinnerOptionValue(mAuthTypeView, i); } } } - if (uri.getScheme().startsWith("pop3")) - { + if (uri.getScheme().startsWith("pop3")) { serverLabelView.setText(R.string.account_setup_incoming_pop_server_label); mAccountPorts = popPorts; mAccountSchemes = popSchemes; @@ -273,15 +239,12 @@ public class AccountSetupIncoming extends K9Activity implements OnClickListener findViewById(R.id.compression_section).setVisibility(View.GONE); findViewById(R.id.compression_label).setVisibility(View.GONE); mAccount.setDeletePolicy(Account.DELETE_POLICY_NEVER); - } - else if (uri.getScheme().startsWith("imap")) - { + } else if (uri.getScheme().startsWith("imap")) { serverLabelView.setText(R.string.account_setup_incoming_imap_server_label); mAccountPorts = imapPorts; mAccountSchemes = imapSchemes; - if (uri.getPath() != null && uri.getPath().length() > 0) - { + if (uri.getPath() != null && uri.getPath().length() > 0) { mImapPathPrefixView.setText(uri.getPath().substring(1)); } @@ -291,13 +254,10 @@ public class AccountSetupIncoming extends K9Activity implements OnClickListener findViewById(R.id.webdav_auth_path_section).setVisibility(View.GONE); mAccount.setDeletePolicy(Account.DELETE_POLICY_ON_DELETE); - if (!Intent.ACTION_EDIT.equals(getIntent().getAction())) - { + if (!Intent.ACTION_EDIT.equals(getIntent().getAction())) { findViewById(R.id.imap_folder_setup_section).setVisibility(View.GONE); } - } - else if (uri.getScheme().startsWith("webdav")) - { + } else if (uri.getScheme().startsWith("webdav")) { serverLabelView.setText(R.string.account_setup_incoming_webdav_server_label); mAccountPorts = webdavPorts; mAccountSchemes = webdavSchemes; @@ -309,49 +269,35 @@ public class AccountSetupIncoming extends K9Activity implements OnClickListener findViewById(R.id.compression_section).setVisibility(View.GONE); findViewById(R.id.compression_label).setVisibility(View.GONE); subscribedFoldersOnly.setVisibility(View.GONE); - if (uri.getPath() != null && uri.getPath().length() > 0) - { + if (uri.getPath() != null && uri.getPath().length() > 0) { String[] pathParts = uri.getPath().split("\\|"); - for (int i = 0, count = pathParts.length; i < count; i++) - { - if (i == 0) - { + for (int i = 0, count = pathParts.length; i < count; i++) { + if (i == 0) { if (pathParts[0] != null && - pathParts[0].length() > 1) - { + pathParts[0].length() > 1) { mWebdavPathPrefixView.setText(pathParts[0].substring(1)); } - } - else if (i == 1) - { + } else if (i == 1) { if (pathParts[1] != null && - pathParts[1].length() > 1) - { + pathParts[1].length() > 1) { mWebdavAuthPathView.setText(pathParts[1]); } - } - else if (i == 2) - { + } else if (i == 2) { if (pathParts[2] != null && - pathParts[2].length() > 1) - { + pathParts[2].length() > 1) { mWebdavMailboxPathView.setText(pathParts[2]); } } } } mAccount.setDeletePolicy(Account.DELETE_POLICY_ON_DELETE); - } - else - { + } else { throw new Exception("Unknown account type: " + mAccount.getStoreUri()); } - for (int i = 0; i < mAccountSchemes.length; i++) - { - if (mAccountSchemes[i].equals(uri.getScheme())) - { + for (int i = 0; i < mAccountSchemes.length; i++) { + if (mAccountSchemes[i].equals(uri.getScheme())) { SpinnerOption.setSpinnerOptionValue(mSecurityTypeView, i); } } @@ -359,39 +305,31 @@ public class AccountSetupIncoming extends K9Activity implements OnClickListener compressionWifi.setChecked(mAccount.useCompression(Account.TYPE_WIFI)); compressionOther.setChecked(mAccount.useCompression(Account.TYPE_OTHER)); - if (uri.getHost() != null) - { + if (uri.getHost() != null) { mServerView.setText(uri.getHost()); } - if (uri.getPort() != -1) - { + if (uri.getPort() != -1) { mPortView.setText(Integer.toString(uri.getPort())); - } - else - { + } else { updatePortFromSecurityType(); } subscribedFoldersOnly.setChecked(mAccount.subscribedFoldersOnly()); validateFields(); - } - catch (Exception e) - { + } catch (Exception e) { failure(e); } } @Override - public void onSaveInstanceState(Bundle outState) - { + public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString(EXTRA_ACCOUNT, mAccount.getUuid()); } - private void validateFields() - { + private void validateFields() { mNextButton .setEnabled(Utility.requiredFieldValid(mUsernameView) && Utility.requiredFieldValid(mPasswordView) @@ -400,33 +338,25 @@ public class AccountSetupIncoming extends K9Activity implements OnClickListener Utility.setCompoundDrawablesAlpha(mNextButton, mNextButton.isEnabled() ? 255 : 128); } - private void updatePortFromSecurityType() - { - if (mAccountPorts != null) - { + private void updatePortFromSecurityType() { + if (mAccountPorts != null) { int securityType = (Integer)((SpinnerOption)mSecurityTypeView.getSelectedItem()).value; mPortView.setText(Integer.toString(mAccountPorts[securityType])); } } @Override - public void onActivityResult(int requestCode, int resultCode, Intent data) - { - if (resultCode == RESULT_OK) - { - if (Intent.ACTION_EDIT.equals(getIntent().getAction())) - { + public void onActivityResult(int requestCode, int resultCode, Intent data) { + if (resultCode == RESULT_OK) { + if (Intent.ACTION_EDIT.equals(getIntent().getAction())) { mAccount.save(Preferences.getPreferences(this)); finish(); - } - else - { + } else { /* * Set the username and password for the outgoing settings to the username and * password the user just set for incoming. */ - try - { + try { String usernameEnc = URLEncoder.encode(mUsernameView.getText().toString(), "UTF-8"); String passwordEnc = URLEncoder.encode(mPasswordView.getText().toString(), "UTF-8"); URI oldUri = new URI(mAccount.getTransportUri()); @@ -439,14 +369,10 @@ public class AccountSetupIncoming extends K9Activity implements OnClickListener null, null); mAccount.setTransportUri(uri.toString()); - } - catch (UnsupportedEncodingException enc) - { + } catch (UnsupportedEncodingException enc) { // This really shouldn't happen since the encoding is hardcoded to UTF-8 Log.e(K9.LOG_TAG, "Couldn't urlencode username or password.", enc); - } - catch (URISyntaxException use) - { + } catch (URISyntaxException use) { /* * If we can't set up the URL we just continue. It's only for * convenience. @@ -461,18 +387,13 @@ public class AccountSetupIncoming extends K9Activity implements OnClickListener } @Override - protected void onNext() - { - try - { + protected void onNext() { + try { int securityType = (Integer)((SpinnerOption)mSecurityTypeView.getSelectedItem()).value; String path = null; - if (mAccountSchemes[securityType].startsWith("imap")) - { + if (mAccountSchemes[securityType].startsWith("imap")) { path = "/" + mImapPathPrefixView.getText(); - } - else if (mAccountSchemes[securityType].startsWith("webdav")) - { + } else if (mAccountSchemes[securityType].startsWith("webdav")) { path = "/" + mWebdavPathPrefixView.getText(); path = path + "|" + mWebdavAuthPathView.getText(); path = path + "|" + mWebdavMailboxPathView.getText(); @@ -484,13 +405,10 @@ public class AccountSetupIncoming extends K9Activity implements OnClickListener String userEnc = URLEncoder.encode(user, "UTF-8"); String passwordEnc = URLEncoder.encode(password, "UTF-8"); - if (mAccountSchemes[securityType].startsWith("imap")) - { + if (mAccountSchemes[securityType].startsWith("imap")) { String authType = ((SpinnerOption)mAuthTypeView.getSelectedItem()).label; userInfo = authType + ":" + userEnc + ":" + passwordEnc; - } - else - { + } else { userInfo = userEnc + ":" + passwordEnc; } URI uri = new URI( @@ -510,33 +428,25 @@ public class AccountSetupIncoming extends K9Activity implements OnClickListener mAccount.setSubscribedFoldersOnly(subscribedFoldersOnly.isChecked()); AccountSetupCheckSettings.actionCheckSettings(this, mAccount, true, false); - } - catch (Exception e) - { + } catch (Exception e) { failure(e); } } - public void onClick(View v) - { - try - { - switch (v.getId()) - { - case R.id.next: - onNext(); - break; + public void onClick(View v) { + try { + switch (v.getId()) { + case R.id.next: + onNext(); + break; } - } - catch (Exception e) - { + } catch (Exception e) { failure(e); } } - private void failure(Exception use) - { + private void failure(Exception use) { Log.e(K9.LOG_TAG, "Failure", use); String toastText = getString(R.string.account_setup_bad_uri, use.getMessage()); diff --git a/src/com/fsck/k9/activity/setup/AccountSetupNames.java b/src/com/fsck/k9/activity/setup/AccountSetupNames.java index 4b577e9b3..493633e99 100644 --- a/src/com/fsck/k9/activity/setup/AccountSetupNames.java +++ b/src/com/fsck/k9/activity/setup/AccountSetupNames.java @@ -16,8 +16,7 @@ import com.fsck.k9.*; import com.fsck.k9.activity.K9Activity; import com.fsck.k9.helper.Utility; -public class AccountSetupNames extends K9Activity implements OnClickListener -{ +public class AccountSetupNames extends K9Activity implements OnClickListener { private static final String EXTRA_ACCOUNT = "account"; private EditText mDescription; @@ -28,16 +27,14 @@ public class AccountSetupNames extends K9Activity implements OnClickListener private Button mDoneButton; - public static void actionSetNames(Context context, Account account) - { + public static void actionSetNames(Context context, Account account) { Intent i = new Intent(context, AccountSetupNames.class); i.putExtra(EXTRA_ACCOUNT, account.getUuid()); context.startActivity(i); } @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.account_setup_names); mDescription = (EditText)findViewById(R.id.account_description); @@ -45,19 +42,15 @@ public class AccountSetupNames extends K9Activity implements OnClickListener mDoneButton = (Button)findViewById(R.id.done); mDoneButton.setOnClickListener(this); - TextWatcher validationTextWatcher = new TextWatcher() - { - public void afterTextChanged(Editable s) - { + TextWatcher validationTextWatcher = new TextWatcher() { + public void afterTextChanged(Editable s) { validateFields(); } - public void beforeTextChanged(CharSequence s, int start, int count, int after) - { + public void beforeTextChanged(CharSequence s, int start, int count, int after) { } - public void onTextChanged(CharSequence s, int start, int before, int count) - { + public void onTextChanged(CharSequence s, int start, int before, int count) { } }; mName.addTextChangedListener(validationTextWatcher); @@ -73,27 +66,22 @@ public class AccountSetupNames extends K9Activity implements OnClickListener * just leave the saved value alone. */ // mDescription.setText(mAccount.getDescription()); - if (mAccount.getName() != null) - { + if (mAccount.getName() != null) { mName.setText(mAccount.getName()); } - if (!Utility.requiredFieldValid(mName)) - { + if (!Utility.requiredFieldValid(mName)) { mDoneButton.setEnabled(false); } } - private void validateFields() - { + private void validateFields() { mDoneButton.setEnabled(Utility.requiredFieldValid(mName)); Utility.setCompoundDrawablesAlpha(mDoneButton, mDoneButton.isEnabled() ? 255 : 128); } @Override - protected void onNext() - { - if (Utility.requiredFieldValid(mDescription)) - { + protected void onNext() { + if (Utility.requiredFieldValid(mDescription)) { mAccount.setDescription(mDescription.getText().toString()); } mAccount.setName(mName.getText().toString()); @@ -101,13 +89,11 @@ public class AccountSetupNames extends K9Activity implements OnClickListener finish(); } - public void onClick(View v) - { - switch (v.getId()) - { - case R.id.done: - onNext(); - break; + public void onClick(View v) { + switch (v.getId()) { + case R.id.done: + onNext(); + break; } } } diff --git a/src/com/fsck/k9/activity/setup/AccountSetupOptions.java b/src/com/fsck/k9/activity/setup/AccountSetupOptions.java index b8dbb9f6b..47cee8a8b 100644 --- a/src/com/fsck/k9/activity/setup/AccountSetupOptions.java +++ b/src/com/fsck/k9/activity/setup/AccountSetupOptions.java @@ -14,8 +14,7 @@ import com.fsck.k9.*; import com.fsck.k9.activity.K9Activity; import com.fsck.k9.mail.Store; -public class AccountSetupOptions extends K9Activity implements OnClickListener -{ +public class AccountSetupOptions extends K9Activity implements OnClickListener { private static final String EXTRA_ACCOUNT = "account"; private static final String EXTRA_MAKE_DEFAULT = "makeDefault"; @@ -31,8 +30,7 @@ public class AccountSetupOptions extends K9Activity implements OnClickListener private Account mAccount; - public static void actionOptions(Context context, Account account, boolean makeDefault) - { + public static void actionOptions(Context context, Account account, boolean makeDefault) { Intent i = new Intent(context, AccountSetupOptions.class); i.putExtra(EXTRA_ACCOUNT, account.getUuid()); i.putExtra(EXTRA_MAKE_DEFAULT, makeDefault); @@ -40,8 +38,7 @@ public class AccountSetupOptions extends K9Activity implements OnClickListener } @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.account_setup_options); @@ -53,8 +50,7 @@ public class AccountSetupOptions extends K9Activity implements OnClickListener findViewById(R.id.next).setOnClickListener(this); - SpinnerOption checkFrequencies[] = - { + SpinnerOption checkFrequencies[] = { new SpinnerOption(-1, getString(R.string.account_setup_options_mail_check_frequency_never)), new SpinnerOption(1, @@ -88,8 +84,7 @@ public class AccountSetupOptions extends K9Activity implements OnClickListener .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mCheckFrequencyView.setAdapter(checkFrequenciesAdapter); - SpinnerOption displayCounts[] = - { + SpinnerOption displayCounts[] = { new SpinnerOption(10, getString(R.string.account_setup_options_mail_display_count_10)), new SpinnerOption(25, getString(R.string.account_setup_options_mail_display_count_25)), new SpinnerOption(50, getString(R.string.account_setup_options_mail_display_count_50)), @@ -116,31 +111,24 @@ public class AccountSetupOptions extends K9Activity implements OnClickListener boolean isPushCapable = false; - try - { + try { Store store = mAccount.getRemoteStore(); isPushCapable = store.isPushCapable(); - } - catch (Exception e) - { + } catch (Exception e) { Log.e(K9.LOG_TAG, "Could not get remote store", e); } - if (!isPushCapable) - { + if (!isPushCapable) { mPushEnable.setVisibility(View.GONE); - } - else - { + } else { mPushEnable.setChecked(true); } } - private void onDone() - { + private void onDone() { mAccount.setDescription(mAccount.getEmail()); mAccount.setNotifyNewMail(mNotifyView.isChecked()); mAccount.setShowOngoing(mNotifySyncView.isChecked()); @@ -149,19 +137,15 @@ public class AccountSetupOptions extends K9Activity implements OnClickListener mAccount.setDisplayCount((Integer)((SpinnerOption)mDisplayCountView .getSelectedItem()).value); - if (mPushEnable.isChecked()) - { + if (mPushEnable.isChecked()) { mAccount.setFolderPushMode(Account.FolderMode.FIRST_CLASS); - } - else - { + } else { mAccount.setFolderPushMode(Account.FolderMode.NONE); } mAccount.save(Preferences.getPreferences(this)); if (mAccount.equals(Preferences.getPreferences(this).getDefaultAccount()) || - getIntent().getBooleanExtra(EXTRA_MAKE_DEFAULT, false)) - { + getIntent().getBooleanExtra(EXTRA_MAKE_DEFAULT, false)) { Preferences.getPreferences(this).setDefaultAccount(mAccount); } K9.setServicesEnabled(this); @@ -169,13 +153,11 @@ public class AccountSetupOptions extends K9Activity implements OnClickListener finish(); } - public void onClick(View v) - { - switch (v.getId()) - { - case R.id.next: - onDone(); - break; + public void onClick(View v) { + switch (v.getId()) { + case R.id.next: + onDone(); + break; } } } diff --git a/src/com/fsck/k9/activity/setup/AccountSetupOutgoing.java b/src/com/fsck/k9/activity/setup/AccountSetupOutgoing.java index 42a31d733..a89678a8c 100644 --- a/src/com/fsck/k9/activity/setup/AccountSetupOutgoing.java +++ b/src/com/fsck/k9/activity/setup/AccountSetupOutgoing.java @@ -23,19 +23,16 @@ import java.net.URLDecoder; import java.net.URLEncoder; public class AccountSetupOutgoing extends K9Activity implements OnClickListener, - OnCheckedChangeListener -{ + OnCheckedChangeListener { private static final String EXTRA_ACCOUNT = "account"; private static final String EXTRA_MAKE_DEFAULT = "makeDefault"; - private static final int smtpPorts[] = - { + private static final int smtpPorts[] = { 25, 465, 465, 25, 25 }; - private static final String smtpSchemes[] = - { + private static final String smtpSchemes[] = { "smtp", "smtp+ssl", "smtp+ssl+", "smtp+tls", "smtp+tls+" }; /* @@ -49,8 +46,7 @@ public class AccountSetupOutgoing extends K9Activity implements OnClickListener, }; */ - private static final String authTypes[] = - { + private static final String authTypes[] = { "PLAIN", "CRAM_MD5" }; private EditText mUsernameView; @@ -65,16 +61,14 @@ public class AccountSetupOutgoing extends K9Activity implements OnClickListener, private Account mAccount; private boolean mMakeDefault; - public static void actionOutgoingSettings(Context context, Account account, boolean makeDefault) - { + public static void actionOutgoingSettings(Context context, Account account, boolean makeDefault) { Intent i = new Intent(context, AccountSetupOutgoing.class); i.putExtra(EXTRA_ACCOUNT, account.getUuid()); i.putExtra(EXTRA_MAKE_DEFAULT, makeDefault); context.startActivity(i); } - public static void actionEditOutgoingSettings(Context context, Account account) - { + public static void actionEditOutgoingSettings(Context context, Account account) { Intent i = new Intent(context, AccountSetupOutgoing.class); i.setAction(Intent.ACTION_EDIT); i.putExtra(EXTRA_ACCOUNT, account.getUuid()); @@ -82,24 +76,19 @@ public class AccountSetupOutgoing extends K9Activity implements OnClickListener, } @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.account_setup_outgoing); String accountUuid = getIntent().getStringExtra(EXTRA_ACCOUNT); mAccount = Preferences.getPreferences(this).getAccount(accountUuid); - try - { - if (new URI(mAccount.getStoreUri()).getScheme().startsWith("webdav")) - { + try { + if (new URI(mAccount.getStoreUri()).getScheme().startsWith("webdav")) { mAccount.setTransportUri(mAccount.getStoreUri()); AccountSetupCheckSettings.actionCheckSettings(this, mAccount, false, true); } - } - catch (URISyntaxException e) - { + } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } @@ -118,8 +107,7 @@ public class AccountSetupOutgoing extends K9Activity implements OnClickListener, mNextButton.setOnClickListener(this); mRequireLoginView.setOnCheckedChangeListener(this); - SpinnerOption securityTypes[] = - { + SpinnerOption securityTypes[] = { new SpinnerOption(0, getString(R.string.account_setup_incoming_security_none_label)), new SpinnerOption(1, getString(R.string.account_setup_incoming_security_ssl_optional_label)), @@ -131,8 +119,7 @@ public class AccountSetupOutgoing extends K9Activity implements OnClickListener, // This needs to be kept in sync with the list at the top of the file. // that makes me somewhat unhappy - SpinnerOption authTypeSpinnerOptions[] = - { + SpinnerOption authTypeSpinnerOptions[] = { new SpinnerOption(0, "PLAIN"), new SpinnerOption(1, "CRAM_MD5") }; @@ -153,15 +140,12 @@ public class AccountSetupOutgoing extends K9Activity implements OnClickListener, * Updates the port when the user changes the security type. This allows * us to show a reasonable default which the user can change. */ - mSecurityTypeView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() - { - public void onItemSelected(AdapterView parent, View view, int position, long id) - { + mSecurityTypeView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + public void onItemSelected(AdapterView parent, View view, int position, long id) { updatePortFromSecurityType(); } - public void onNothingSelected(AdapterView parent) - { + public void onNothingSelected(AdapterView parent) { } }); @@ -169,19 +153,15 @@ public class AccountSetupOutgoing extends K9Activity implements OnClickListener, * Calls validateFields() which enables or disables the Next button * based on the fields' validity. */ - TextWatcher validationTextWatcher = new TextWatcher() - { - public void afterTextChanged(Editable s) - { + TextWatcher validationTextWatcher = new TextWatcher() { + public void afterTextChanged(Editable s) { validateFields(); } - public void beforeTextChanged(CharSequence s, int start, int count, int after) - { + public void beforeTextChanged(CharSequence s, int start, int count, int after) { } - public void onTextChanged(CharSequence s, int start, int before, int count) - { + public void onTextChanged(CharSequence s, int start, int before, int count) { } }; mUsernameView.addTextChangedListener(validationTextWatcher); @@ -203,82 +183,64 @@ public class AccountSetupOutgoing extends K9Activity implements OnClickListener, * If we're being reloaded we override the original account with the one * we saved */ - if (savedInstanceState != null && savedInstanceState.containsKey(EXTRA_ACCOUNT)) - { + if (savedInstanceState != null && savedInstanceState.containsKey(EXTRA_ACCOUNT)) { accountUuid = savedInstanceState.getString(EXTRA_ACCOUNT); mAccount = Preferences.getPreferences(this).getAccount(accountUuid); } - try - { + try { URI uri = new URI(mAccount.getTransportUri()); String username = null; String password = null; String authType = null; - if (uri.getUserInfo() != null) - { + if (uri.getUserInfo() != null) { String[] userInfoParts = uri.getUserInfo().split(":"); username = URLDecoder.decode(userInfoParts[0], "UTF-8"); - if (userInfoParts.length > 1) - { + if (userInfoParts.length > 1) { password = URLDecoder.decode(userInfoParts[1], "UTF-8"); } - if (userInfoParts.length > 2) - { + if (userInfoParts.length > 2) { authType = userInfoParts[2]; } } - if (username != null) - { + if (username != null) { mUsernameView.setText(username); mRequireLoginView.setChecked(true); } - if (password != null) - { + if (password != null) { mPasswordView.setText(password); } - if (authType != null) - { - for (int i = 0; i < authTypes.length; i++) - { - if (authTypes[i].equals(authType)) - { + if (authType != null) { + for (int i = 0; i < authTypes.length; i++) { + if (authTypes[i].equals(authType)) { SpinnerOption.setSpinnerOptionValue(mAuthTypeView, i); } } } - for (int i = 0; i < smtpSchemes.length; i++) - { - if (smtpSchemes[i].equals(uri.getScheme())) - { + for (int i = 0; i < smtpSchemes.length; i++) { + if (smtpSchemes[i].equals(uri.getScheme())) { SpinnerOption.setSpinnerOptionValue(mSecurityTypeView, i); } } - if (uri.getHost() != null) - { + if (uri.getHost() != null) { mServerView.setText(uri.getHost()); } - if (uri.getPort() != -1) - { + if (uri.getPort() != -1) { mPortView.setText(Integer.toString(uri.getPort())); - } - else - { + } else { updatePortFromSecurityType(); } validateFields(); - } - catch (Exception e) - { + } catch (Exception e) { /* * We should always be able to parse our own settings. */ @@ -288,14 +250,12 @@ public class AccountSetupOutgoing extends K9Activity implements OnClickListener, } @Override - public void onSaveInstanceState(Bundle outState) - { + public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString(EXTRA_ACCOUNT, mAccount.getUuid()); } - private void validateFields() - { + private void validateFields() { mNextButton .setEnabled( Utility.domainFieldValid(mServerView) && @@ -306,24 +266,18 @@ public class AccountSetupOutgoing extends K9Activity implements OnClickListener, Utility.setCompoundDrawablesAlpha(mNextButton, mNextButton.isEnabled() ? 255 : 128); } - private void updatePortFromSecurityType() - { + private void updatePortFromSecurityType() { int securityType = (Integer)((SpinnerOption)mSecurityTypeView.getSelectedItem()).value; mPortView.setText(Integer.toString(smtpPorts[securityType])); } @Override - public void onActivityResult(int requestCode, int resultCode, Intent data) - { - if (resultCode == RESULT_OK) - { - if (Intent.ACTION_EDIT.equals(getIntent().getAction())) - { + public void onActivityResult(int requestCode, int resultCode, Intent data) { + if (resultCode == RESULT_OK) { + if (Intent.ACTION_EDIT.equals(getIntent().getAction())) { mAccount.save(Preferences.getPreferences(this)); finish(); - } - else - { + } else { AccountSetupOptions.actionOptions(this, mAccount, mMakeDefault); finish(); } @@ -331,33 +285,26 @@ public class AccountSetupOutgoing extends K9Activity implements OnClickListener, } @Override - protected void onNext() - { + protected void onNext() { int securityType = (Integer)((SpinnerOption)mSecurityTypeView.getSelectedItem()).value; URI uri; - try - { + try { String usernameEnc = URLEncoder.encode(mUsernameView.getText().toString(), "UTF-8"); String passwordEnc = URLEncoder.encode(mPasswordView.getText().toString(), "UTF-8"); String userInfo = null; String authType = ((SpinnerOption)mAuthTypeView.getSelectedItem()).label; - if (mRequireLoginView.isChecked()) - { + if (mRequireLoginView.isChecked()) { userInfo = usernameEnc + ":" + passwordEnc + ":" + authType; } uri = new URI(smtpSchemes[securityType], userInfo, mServerView.getText().toString(), Integer.parseInt(mPortView.getText().toString()), null, null, null); mAccount.setTransportUri(uri.toString()); AccountSetupCheckSettings.actionCheckSettings(this, mAccount, false, true); - } - catch (UnsupportedEncodingException enc) - { + } catch (UnsupportedEncodingException enc) { // This really shouldn't happen since the encoding is hardcoded to UTF-8 Log.e(K9.LOG_TAG, "Couldn't urlencode username or password.", enc); - } - catch (Exception e) - { + } catch (Exception e) { /* * It's unrecoverable if we cannot create a URI from components that * we validated to be safe. @@ -367,23 +314,19 @@ public class AccountSetupOutgoing extends K9Activity implements OnClickListener, } - public void onClick(View v) - { - switch (v.getId()) - { - case R.id.next: - onNext(); - break; + public void onClick(View v) { + switch (v.getId()) { + case R.id.next: + onNext(); + break; } } - public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) - { + public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { mRequireLoginSettingsView.setVisibility(isChecked ? View.VISIBLE : View.GONE); validateFields(); } - private void failure(Exception use) - { + private void failure(Exception use) { Log.e(K9.LOG_TAG, "Failure", use); String toastText = getString(R.string.account_setup_bad_uri, use.getMessage()); diff --git a/src/com/fsck/k9/activity/setup/FolderSettings.java b/src/com/fsck/k9/activity/setup/FolderSettings.java index 29b6d51b5..cd48f0475 100644 --- a/src/com/fsck/k9/activity/setup/FolderSettings.java +++ b/src/com/fsck/k9/activity/setup/FolderSettings.java @@ -19,8 +19,7 @@ import com.fsck.k9.mail.store.LocalStore; import com.fsck.k9.mail.store.LocalStore.LocalFolder; import com.fsck.k9.service.MailService; -public class FolderSettings extends K9PreferenceActivity -{ +public class FolderSettings extends K9PreferenceActivity { private static final String EXTRA_FOLDER_NAME = "com.fsck.k9.folderName"; private static final String EXTRA_ACCOUNT = "com.fsck.k9.account"; @@ -40,8 +39,7 @@ public class FolderSettings extends K9PreferenceActivity private ListPreference mSyncClass; private ListPreference mPushClass; - public static void actionSettings(Context context, Account account, String folderName) - { + public static void actionSettings(Context context, Account account, String folderName) { Intent i = new Intent(context, FolderSettings.class); i.putExtra(EXTRA_FOLDER_NAME, folderName); i.putExtra(EXTRA_ACCOUNT, account.getUuid()); @@ -49,35 +47,28 @@ public class FolderSettings extends K9PreferenceActivity } @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); String folderName = (String)getIntent().getSerializableExtra(EXTRA_FOLDER_NAME); String accountUuid = getIntent().getStringExtra(EXTRA_ACCOUNT); Account mAccount = Preferences.getPreferences(this).getAccount(accountUuid); - try - { + try { LocalStore localStore = mAccount.getLocalStore(); mFolder = localStore.getFolder(folderName); mFolder.open(OpenMode.READ_WRITE); - } - catch (MessagingException me) - { + } catch (MessagingException me) { Log.e(K9.LOG_TAG, "Unable to edit folder " + folderName + " preferences", me); return; } boolean isPushCapable = false; Store store = null; - try - { + try { store = mAccount.getRemoteStore(); isPushCapable = store.isPushCapable(); - } - catch (Exception e) - { + } catch (Exception e) { Log.e(K9.LOG_TAG, "Could not get remote store", e); } @@ -95,10 +86,8 @@ public class FolderSettings extends K9PreferenceActivity mDisplayClass = (ListPreference) findPreference(PREFERENCE_DISPLAY_CLASS); mDisplayClass.setValue(mFolder.getDisplayClass().name()); mDisplayClass.setSummary(mDisplayClass.getEntry()); - mDisplayClass.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() - { - public boolean onPreferenceChange(Preference preference, Object newValue) - { + mDisplayClass.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { + public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mDisplayClass.findIndexOfValue(summary); mDisplayClass.setSummary(mDisplayClass.getEntries()[index]); @@ -110,10 +99,8 @@ public class FolderSettings extends K9PreferenceActivity mSyncClass = (ListPreference) findPreference(PREFERENCE_SYNC_CLASS); mSyncClass.setValue(mFolder.getRawSyncClass().name()); mSyncClass.setSummary(mSyncClass.getEntry()); - mSyncClass.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() - { - public boolean onPreferenceChange(Preference preference, Object newValue) - { + mSyncClass.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { + public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mSyncClass.findIndexOfValue(summary); mSyncClass.setSummary(mSyncClass.getEntries()[index]); @@ -126,10 +113,8 @@ public class FolderSettings extends K9PreferenceActivity mPushClass.setEnabled(isPushCapable); mPushClass.setValue(mFolder.getRawPushClass().name()); mPushClass.setSummary(mPushClass.getEntry()); - mPushClass.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() - { - public boolean onPreferenceChange(Preference preference, Object newValue) - { + mPushClass.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { + public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mPushClass.findIndexOfValue(summary); mPushClass.setSummary(mPushClass.getEntries()[index]); @@ -140,13 +125,11 @@ public class FolderSettings extends K9PreferenceActivity } @Override - public void onResume() - { + public void onResume() { super.onResume(); } - private void saveSettings() throws MessagingException - { + private void saveSettings() throws MessagingException { mFolder.setInTopGroup(mInTopGroup.isChecked()); mFolder.setIntegrate(mIntegrate.isChecked()); // We call getPushClass() because display class changes can affect push class when push class is set to inherit @@ -162,24 +145,18 @@ public class FolderSettings extends K9PreferenceActivity FolderClass newDisplayClass = mFolder.getDisplayClass(); if (oldPushClass != newPushClass - || (newPushClass != FolderClass.NO_CLASS && oldDisplayClass != newDisplayClass)) - { + || (newPushClass != FolderClass.NO_CLASS && oldDisplayClass != newDisplayClass)) { MailService.actionRestartPushers(getApplication(), null); } } @Override - public boolean onKeyDown(int keyCode, KeyEvent event) - { - if (keyCode == KeyEvent.KEYCODE_BACK) - { - try - { + public boolean onKeyDown(int keyCode, KeyEvent event) { + if (keyCode == KeyEvent.KEYCODE_BACK) { + try { saveSettings(); - } - catch (MessagingException e) - { - Log.e(K9.LOG_TAG,"Saving folder settings failed "+e); + } catch (MessagingException e) { + Log.e(K9.LOG_TAG, "Saving folder settings failed " + e); } } return super.onKeyDown(keyCode, event); diff --git a/src/com/fsck/k9/activity/setup/FontSizeSettings.java b/src/com/fsck/k9/activity/setup/FontSizeSettings.java index bf0369591..b51f2da99 100644 --- a/src/com/fsck/k9/activity/setup/FontSizeSettings.java +++ b/src/com/fsck/k9/activity/setup/FontSizeSettings.java @@ -17,8 +17,7 @@ import com.fsck.k9.activity.K9PreferenceActivity; * * @see FontSizes */ -public class FontSizeSettings extends K9PreferenceActivity -{ +public class FontSizeSettings extends K9PreferenceActivity { /* * Keys of the preferences defined in res/xml/font_preferences.xml */ @@ -62,15 +61,13 @@ public class FontSizeSettings extends K9PreferenceActivity * * @param context The application context. */ - public static void actionEditSettings(Context context) - { + public static void actionEditSettings(Context context) { Intent i = new Intent(context, FontSizeSettings.class); context.startActivity(i); } @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); FontSizes fontSizes = K9.getFontSizes(); @@ -133,8 +130,7 @@ public class FontSizeSettings extends K9PreferenceActivity * Update the global FontSize object and permanently store the (possibly * changed) font size settings. */ - private void saveSettings() - { + private void saveSettings() { FontSizes fontSizes = K9.getFontSizes(); fontSizes.setAccountName(Integer.parseInt(mAccountName.getValue())); @@ -164,10 +160,8 @@ public class FontSizeSettings extends K9PreferenceActivity } @Override - public boolean onKeyDown(int keyCode, KeyEvent event) - { - if (keyCode == KeyEvent.KEYCODE_BACK) - { + public boolean onKeyDown(int keyCode, KeyEvent event) { + if (keyCode == KeyEvent.KEYCODE_BACK) { saveSettings(); } return super.onKeyDown(keyCode, event); diff --git a/src/com/fsck/k9/activity/setup/Prefs.java b/src/com/fsck/k9/activity/setup/Prefs.java index 334084572..fdd190b54 100644 --- a/src/com/fsck/k9/activity/setup/Prefs.java +++ b/src/com/fsck/k9/activity/setup/Prefs.java @@ -29,8 +29,7 @@ import com.fsck.k9.preferences.TimePickerPreference; import com.fsck.k9.service.MailService; -public class Prefs extends K9PreferenceActivity -{ +public class Prefs extends K9PreferenceActivity { /** * Immutable empty {@link CharSequence} array @@ -57,7 +56,7 @@ public class Prefs extends K9PreferenceActivity private static final String PREFERENCE_MESSAGELIST_PREVIEW_LINES = "messagelist_preview_lines"; private static final String PREFERENCE_MESSAGELIST_STARS = "messagelist_stars"; private static final String PREFERENCE_MESSAGELIST_CHECKBOXES = "messagelist_checkboxes"; - private static final String PREFERENCE_MESSAGELIST_SHOW_CORRESPONDENT_NAMES= "messagelist_show_correspondent_names"; + private static final String PREFERENCE_MESSAGELIST_SHOW_CORRESPONDENT_NAMES = "messagelist_show_correspondent_names"; private static final String PREFERENCE_MESSAGELIST_SHOW_CONTACT_NAME = "messagelist_show_contact_name"; private static final String PREFERENCE_MESSAGELIST_CONTACT_NAME_COLOR = "messagelist_contact_name_color"; private static final String PREFERENCE_MESSAGEVIEW_FIXEDWIDTH = "messageview_fixedwidth_font"; @@ -112,15 +111,13 @@ public class Prefs extends K9PreferenceActivity - public static void actionPrefs(Context context) - { + public static void actionPrefs(Context context) { Intent i = new Intent(context, Prefs.class); context.startActivity(i); } @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.global_preferences); @@ -130,10 +127,8 @@ public class Prefs extends K9PreferenceActivity Vector entryValueVector = new Vector(Arrays.asList(mLanguage.getEntryValues())); String supportedLanguages[] = getResources().getStringArray(R.array.supported_languages); HashSet supportedLanguageSet = new HashSet(Arrays.asList(supportedLanguages)); - for (int i = entryVector.size() - 1; i > -1; --i) - { - if (!supportedLanguageSet.contains(entryValueVector.get(i))) - { + for (int i = entryVector.size() - 1; i > -1; --i) { + if (!supportedLanguageSet.contains(entryValueVector.get(i))) { entryVector.remove(i); entryValueVector.remove(i); } @@ -146,10 +141,8 @@ public class Prefs extends K9PreferenceActivity mTheme = setupListPreference(PREFERENCE_THEME, theme); findPreference(PREFERENCE_FONT_SIZE).setOnPreferenceClickListener( - new Preference.OnPreferenceClickListener() - { - public boolean onPreferenceClick(Preference preference) - { + new Preference.OnPreferenceClickListener() { + public boolean onPreferenceClick(Preference preference) { onFontSizeSettings(); return true; } @@ -159,8 +152,7 @@ public class Prefs extends K9PreferenceActivity String[] formats = DateFormatter.getFormats(this); CharSequence[] entries = new CharSequence[formats.length]; CharSequence[] values = new CharSequence[formats.length]; - for (int i = 0 ; i < formats.length; i++) - { + for (int i = 0 ; i < formats.length; i++) { String format = formats[i]; entries[i] = DateFormatter.getSampleDate(this, format); values[i] = format; @@ -172,7 +164,7 @@ public class Prefs extends K9PreferenceActivity mGestures = (CheckBoxPreference)findPreference(PREFERENCE_GESTURES); mGestures.setChecked(K9.gesturesEnabled()); - + compactLayouts = (CheckBoxPreference)findPreference(PREFERENCE_COMPACT_LAYOUTS); compactLayouts.setChecked(K9.useCompactLayouts()); @@ -219,26 +211,18 @@ public class Prefs extends K9PreferenceActivity mChangeContactNameColor = (CheckBoxPreference)findPreference(PREFERENCE_MESSAGELIST_CONTACT_NAME_COLOR); mChangeContactNameColor.setChecked(K9.changeContactNameColor()); - if (K9.changeContactNameColor()) - { + if (K9.changeContactNameColor()) { mChangeContactNameColor.setSummary(R.string.global_settings_registered_name_color_changed); - } - else - { + } else { mChangeContactNameColor.setSummary(R.string.global_settings_registered_name_color_default); } - mChangeContactNameColor.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() - { - public boolean onPreferenceChange(Preference preference, Object newValue) - { + mChangeContactNameColor.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { + public boolean onPreferenceChange(Preference preference, Object newValue) { final Boolean checked = (Boolean) newValue; - if (checked) - { + if (checked) { onChooseContactNameColor(); mChangeContactNameColor.setSummary(R.string.global_settings_registered_name_color_changed); - } - else - { + } else { mChangeContactNameColor.setSummary(R.string.global_settings_registered_name_color_default); } mChangeContactNameColor.setChecked(checked); @@ -256,8 +240,7 @@ public class Prefs extends K9PreferenceActivity mZoomControlsEnabled.setChecked(K9.zoomControlsEnabled()); mMobileOptimizedLayout = (CheckBoxPreference) findPreference(PREFERENCE_MESSAGEVIEW_MOBILE_LAYOUT); - if (Integer.parseInt(Build.VERSION.SDK) <= 7 ) - { + if (Integer.parseInt(Build.VERSION.SDK) <= 7) { mMobileOptimizedLayout.setEnabled(false); } @@ -270,10 +253,8 @@ public class Prefs extends K9PreferenceActivity mQuietTimeStarts = (TimePickerPreference) findPreference(PREFERENCE_QUIET_TIME_STARTS); mQuietTimeStarts.setDefaultValue(K9.getQuietTimeStarts()); mQuietTimeStarts.setSummary(K9.getQuietTimeStarts()); - mQuietTimeStarts.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() - { - public boolean onPreferenceChange(Preference preference, Object newValue) - { + mQuietTimeStarts.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { + public boolean onPreferenceChange(Preference preference, Object newValue) { final String time = (String) newValue; mQuietTimeStarts.setSummary(time); return false; @@ -283,10 +264,8 @@ public class Prefs extends K9PreferenceActivity mQuietTimeEnds = (TimePickerPreference) findPreference(PREFERENCE_QUIET_TIME_ENDS); mQuietTimeEnds.setSummary(K9.getQuietTimeEnds()); mQuietTimeEnds.setDefaultValue(K9.getQuietTimeEnds()); - mQuietTimeEnds.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() - { - public boolean onPreferenceChange(Preference preference, Object newValue) - { + mQuietTimeEnds.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { + public boolean onPreferenceChange(Preference preference, Object newValue) { final String time = (String) newValue; mQuietTimeEnds.setSummary(time); return false; @@ -308,8 +287,7 @@ public class Prefs extends K9PreferenceActivity mSensitiveLogging.setChecked(K9.DEBUG_SENSITIVE); } - private void saveSettings() - { + private void saveSettings() { SharedPreferences preferences = Preferences.getPreferences(this).getPreferences(); K9.setK9Language(mLanguage.getValue()); @@ -346,8 +324,7 @@ public class Prefs extends K9PreferenceActivity boolean needsRefresh = K9.setBackgroundOps(mBackgroundOps.getValue()); K9.setUseGalleryBugWorkaround(mUseGalleryBugWorkaround.isChecked()); - if (!K9.DEBUG && mDebugLogging.isChecked()) - { + if (!K9.DEBUG && mDebugLogging.isChecked()) { Toast.makeText(this, R.string.debug_logging_enabled, Toast.LENGTH_LONG).show(); } K9.DEBUG = mDebugLogging.isChecked(); @@ -358,20 +335,16 @@ public class Prefs extends K9PreferenceActivity DateFormatter.setDateFormat(editor, mDateFormat.getValue()); editor.commit(); - if (needsRefresh) - { + if (needsRefresh) { MailService.actionReset(this, null); } } @Override - public boolean onKeyDown(int keyCode, KeyEvent event) - { - if (keyCode == KeyEvent.KEYCODE_BACK) - { + public boolean onKeyDown(int keyCode, KeyEvent event) { + if (keyCode == KeyEvent.KEYCODE_BACK) { saveSettings(); - if (K9.manageBack()) - { + if (K9.manageBack()) { Accounts.listAccounts(this); finish(); return true; @@ -380,17 +353,13 @@ public class Prefs extends K9PreferenceActivity return super.onKeyDown(keyCode, event); } - private void onFontSizeSettings() - { + private void onFontSizeSettings() { FontSizeSettings.actionEditSettings(this); } - private void onChooseContactNameColor() - { - new ColorPickerDialog(this, new ColorPickerDialog.OnColorChangedListener() - { - public void colorChanged(int color) - { + private void onChooseContactNameColor() { + new ColorPickerDialog(this, new ColorPickerDialog.OnColorChangedListener() { + public void colorChanged(int color) { K9.setContactNameColor(color); } }, diff --git a/src/com/fsck/k9/activity/setup/SpinnerHelper.java b/src/com/fsck/k9/activity/setup/SpinnerHelper.java index 1d5431ed2..bcf70e1fc 100644 --- a/src/com/fsck/k9/activity/setup/SpinnerHelper.java +++ b/src/com/fsck/k9/activity/setup/SpinnerHelper.java @@ -7,29 +7,23 @@ import android.content.Context; import android.widget.ArrayAdapter; import android.widget.Spinner; -public class SpinnerHelper -{ - public static void initSpinner(Context context, Spinner spinner, int entryRes, int valueRes, String curVal) - { +public class SpinnerHelper { + public static void initSpinner(Context context, Spinner spinner, int entryRes, int valueRes, String curVal) { String[] entryArray = context.getResources().getStringArray(entryRes); String[] valueArray = context.getResources().getStringArray(valueRes); initSpinner(context, spinner, entryArray, valueArray, curVal); } - public static void initSpinner(Context context, Spinner spinner, String[] entryArray, String[] valueArray, String curVal) - { + public static void initSpinner(Context context, Spinner spinner, String[] entryArray, String[] valueArray, String curVal) { - if (entryArray.length != valueArray.length) - { + if (entryArray.length != valueArray.length) { throw new RuntimeException("Entry and value arrays are of unequal lenght"); } EntryValue[] entryValues = new EntryValue[entryArray.length]; int curSelection = 0; - for (int i = 0; i < entryArray.length; i++) - { + for (int i = 0; i < entryArray.length; i++) { entryValues[i] = new EntryValue(entryArray[i], valueArray[i]); - if (valueArray[i].equals(curVal)) - { + if (valueArray[i].equals(curVal)) { curSelection = i; } } @@ -40,50 +34,37 @@ public class SpinnerHelper spinner.setSelection(curSelection); } - public static String getSpinnerValue(Spinner spinner) - { + public static String getSpinnerValue(Spinner spinner) { EntryValue entryValue = (EntryValue)spinner.getSelectedItem(); - if (entryValue != null) - { + if (entryValue != null) { return entryValue.getValue(); - } - else - { + } else { return null; } } - public static String getSpinnerEntry(Spinner spinner) - { + public static String getSpinnerEntry(Spinner spinner) { EntryValue entryValue = (EntryValue)spinner.getSelectedItem(); - if (entryValue != null) - { + if (entryValue != null) { return entryValue.getEntry(); - } - else - { + } else { return null; } } - private static class EntryValue - { + private static class EntryValue { final String entry; final String value; - EntryValue(String entry, String value) - { + EntryValue(String entry, String value) { this.entry = entry; this.value = value; } @Override - public String toString() - { + public String toString() { return entry; } - public String getEntry() - { + public String getEntry() { return entry; } - public String getValue() - { + public String getValue() { return value; } } diff --git a/src/com/fsck/k9/activity/setup/SpinnerOption.java b/src/com/fsck/k9/activity/setup/SpinnerOption.java index 10a6c04c6..89275b974 100644 --- a/src/com/fsck/k9/activity/setup/SpinnerOption.java +++ b/src/com/fsck/k9/activity/setup/SpinnerOption.java @@ -6,34 +6,28 @@ package com.fsck.k9.activity.setup; import android.widget.Spinner; -public class SpinnerOption -{ +public class SpinnerOption { public Object value; public String label; - public static void setSpinnerOptionValue(Spinner spinner, Object value) - { - for (int i = 0, count = spinner.getCount(); i < count; i++) - { + public static void setSpinnerOptionValue(Spinner spinner, Object value) { + for (int i = 0, count = spinner.getCount(); i < count; i++) { SpinnerOption so = (SpinnerOption)spinner.getItemAtPosition(i); - if (so.value.equals(value)) - { + if (so.value.equals(value)) { spinner.setSelection(i, true); return; } } } - public SpinnerOption(Object value, String label) - { + public SpinnerOption(Object value, String label) { this.value = value; this.label = label; } @Override - public String toString() - { + public String toString() { return label; } } diff --git a/src/com/fsck/k9/controller/MessageDateComparator.java b/src/com/fsck/k9/controller/MessageDateComparator.java index 6b652bfea..ec45ce130 100644 --- a/src/com/fsck/k9/controller/MessageDateComparator.java +++ b/src/com/fsck/k9/controller/MessageDateComparator.java @@ -4,25 +4,16 @@ package com.fsck.k9.controller; import java.util.Comparator; import com.fsck.k9.mail.Message; -public class MessageDateComparator implements Comparator -{ - public int compare(Message o1, Message o2) - { - try - { - if (o1.getSentDate() == null) - { +public class MessageDateComparator implements Comparator { + public int compare(Message o1, Message o2) { + try { + if (o1.getSentDate() == null) { return 1; - } - else if (o2.getSentDate() == null) - { + } else if (o2.getSentDate() == null) { return -1; - } - else + } else return o2.getSentDate().compareTo(o1.getSentDate()); - } - catch (Exception e) - { + } catch (Exception e) { return 0; } } diff --git a/src/com/fsck/k9/controller/MessageRemovalListener.java b/src/com/fsck/k9/controller/MessageRemovalListener.java index efb018cfe..38973dde4 100644 --- a/src/com/fsck/k9/controller/MessageRemovalListener.java +++ b/src/com/fsck/k9/controller/MessageRemovalListener.java @@ -2,7 +2,6 @@ package com.fsck.k9.controller; import com.fsck.k9.mail.Message; -public interface MessageRemovalListener -{ +public interface MessageRemovalListener { public void messageRemoved(Message message); } diff --git a/src/com/fsck/k9/controller/MessageRetrievalListener.java b/src/com/fsck/k9/controller/MessageRetrievalListener.java index 17c9699a5..24ecb52e2 100644 --- a/src/com/fsck/k9/controller/MessageRetrievalListener.java +++ b/src/com/fsck/k9/controller/MessageRetrievalListener.java @@ -3,8 +3,7 @@ package com.fsck.k9.controller; import com.fsck.k9.mail.Message; -public interface MessageRetrievalListener -{ +public interface MessageRetrievalListener { public void messageStarted(String uid, int number, int ofTotal); public void messageFinished(Message message, int number, int ofTotal); diff --git a/src/com/fsck/k9/controller/MessagingController.java b/src/com/fsck/k9/controller/MessagingController.java index e8f063bb1..bb116ac63 100644 --- a/src/com/fsck/k9/controller/MessagingController.java +++ b/src/com/fsck/k9/controller/MessagingController.java @@ -76,8 +76,7 @@ import com.fsck.k9.mail.store.LocalStore.PendingCommand; * it removes itself. Thus, any commands that that activity submitted are * removed from the queue once the activity is no longer active. */ -public class MessagingController implements Runnable -{ +public class MessagingController implements Runnable { /** * Immutable empty {@link String} array @@ -141,8 +140,7 @@ public class MessagingController implements Runnable private final ExecutorService threadPool = Executors.newCachedThreadPool(); - public enum SORT_TYPE - { + public enum SORT_TYPE { SORT_DATE(R.string.sort_earliest_first, R.string.sort_latest_first, false), SORT_SUBJECT(R.string.sort_subject_alpha, R.string.sort_subject_re_alpha, true), SORT_SENDER(R.string.sort_sender_alpha, R.string.sort_sender_re_alpha, true), @@ -154,26 +152,20 @@ public class MessagingController implements Runnable private int descendingToast; private boolean defaultAscending; - SORT_TYPE(int ascending, int descending, boolean ndefaultAscending) - { + SORT_TYPE(int ascending, int descending, boolean ndefaultAscending) { ascendingToast = ascending; descendingToast = descending; defaultAscending = ndefaultAscending; } - public int getToast(boolean ascending) - { - if (ascending) - { + public int getToast(boolean ascending) { + if (ascending) { return ascendingToast; - } - else - { + } else { return descendingToast; } } - public boolean isDefaultAscending() - { + public boolean isDefaultAscending() { return defaultAscending; } } @@ -194,31 +186,25 @@ public class MessagingController implements Runnable // Key is accountUuid:folderName:messageUid , value is unimportant private ConcurrentHashMap deletedUids = new ConcurrentHashMap(); - private String createMessageKey(Account account, String folder, Message message) - { + private String createMessageKey(Account account, String folder, Message message) { return createMessageKey(account, folder, message.getUid()); } - private String createMessageKey(Account account, String folder, String uid) - { + private String createMessageKey(Account account, String folder, String uid) { return account.getUuid() + ":" + folder + ":" + uid; } - private void suppressMessage(Account account, String folder, Message message) - { + private void suppressMessage(Account account, String folder, Message message) { - if (account == null || folder == null || message == null) - { + if (account == null || folder == null || message == null) { return; } String messKey = createMessageKey(account, folder, message); deletedUids.put(messKey, "true"); } - private void unsuppressMessage(Account account, String folder, String uid) - { - if (account == null || folder == null || uid == null) - { + private void unsuppressMessage(Account account, String folder, String uid) { + if (account == null || folder == null || uid == null) { return; } String messKey = createMessageKey(account, folder, uid); @@ -226,16 +212,13 @@ public class MessagingController implements Runnable } - private boolean isMessageSuppressed(Account account, String folder, Message message) - { - if (account == null || folder == null || message == null) - { + private boolean isMessageSuppressed(Account account, String folder, Message message) { + if (account == null || folder == null || message == null) { return false; } String messKey = createMessageKey(account, folder, message); - if (deletedUids.containsKey(messKey)) - { + if (deletedUids.containsKey(messKey)) { return true; } @@ -245,14 +228,12 @@ public class MessagingController implements Runnable /** * @param application {@link K9} */ - private MessagingController(Application application) - { + private MessagingController(Application application) { mApplication = application; mThread = new Thread(this); mThread.setName("MessagingController"); mThread.start(); - if (memorizingListener != null) - { + if (memorizingListener != null) { addListener(memorizingListener); } } @@ -263,58 +244,43 @@ public class MessagingController implements Runnable * @param application {@link K9} * @return */ - public synchronized static MessagingController getInstance(Application application) - { - if (inst == null) - { + public synchronized static MessagingController getInstance(Application application) { + if (inst == null) { inst = new MessagingController(application); } return inst; } - public boolean isBusy() - { + public boolean isBusy() { return mBusy; } @Override - public void run() - { + public void run() { Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); - while (true) - { + while (true) { String commandDescription = null; - try - { + try { final Command command = mCommands.take(); - if (command != null) - { + if (command != null) { commandDescription = command.description; if (K9.DEBUG) Log.i(K9.LOG_TAG, "Running " + (command.isForeground ? "Foreground" : "Background") + " command '" + command.description + "', seq = " + command.sequence); mBusy = true; - try - { + try { command.runnable.run(); - } - catch (UnavailableAccountException e) - { + } catch (UnavailableAccountException e) { // retry later - new Thread() - { + new Thread() { @Override - public void run() - { - try - { + public void run() { + try { sleep(30 * 1000); mCommands.put(command); - } - catch (InterruptedException e) - { + } catch (InterruptedException e) { Log.e(K9.LOG_TAG, "interrupted while putting a pending command for" + " an unavailable account back into the queue." + " THIS SHOULD NEVER HAPPEN."); @@ -327,38 +293,30 @@ public class MessagingController implements Runnable Log.i(K9.LOG_TAG, (command.isForeground ? "Foreground" : "Background") + " Command '" + command.description + "' completed"); - for (MessagingListener l : getListeners(command.listener)) - { + for (MessagingListener l : getListeners(command.listener)) { l.controllerCommandCompleted(mCommands.size() > 0); } } - } - catch (Exception e) - { + } catch (Exception e) { Log.e(K9.LOG_TAG, "Error running command '" + commandDescription + "'", e); } mBusy = false; } } - private void put(String description, MessagingListener listener, Runnable runnable) - { + private void put(String description, MessagingListener listener, Runnable runnable) { putCommand(mCommands, description, listener, runnable, true); } - private void putBackground(String description, MessagingListener listener, Runnable runnable) - { + private void putBackground(String description, MessagingListener listener, Runnable runnable) { putCommand(mCommands, description, listener, runnable, false); } - private void putCommand(BlockingQueue queue, String description, MessagingListener listener, Runnable runnable, boolean isForeground) - { + private void putCommand(BlockingQueue queue, String description, MessagingListener listener, Runnable runnable, boolean isForeground) { int retries = 10; Exception e = null; - while (retries-- > 0) - { - try - { + while (retries-- > 0) { + try { Command command = new Command(); command.listener = listener; command.runnable = runnable; @@ -366,15 +324,10 @@ public class MessagingController implements Runnable command.isForeground = isForeground; queue.put(command); return; - } - catch (InterruptedException ie) - { - try - { + } catch (InterruptedException ie) { + try { Thread.sleep(200); - } - catch (InterruptedException ne) - { + } catch (InterruptedException ne) { } e = ie; } @@ -383,35 +336,28 @@ public class MessagingController implements Runnable } - public void addListener(MessagingListener listener) - { + public void addListener(MessagingListener listener) { mListeners.add(listener); refreshListener(listener); } - public void refreshListener(MessagingListener listener) - { - if (memorizingListener != null && listener != null) - { + public void refreshListener(MessagingListener listener) { + if (memorizingListener != null && listener != null) { memorizingListener.refreshOther(listener); } } - public void removeListener(MessagingListener listener) - { + public void removeListener(MessagingListener listener) { mListeners.remove(listener); } - public Set getListeners() - { + public Set getListeners() { return mListeners; } - public Set getListeners(MessagingListener listener) - { - if (listener == null) - { + public Set getListeners(MessagingListener listener) { + if (listener == null) { return mListeners; } @@ -434,13 +380,10 @@ public class MessagingController implements Runnable * @param listener * @throws MessagingException */ - public void listFolders(final Account account, final boolean refreshRemote, final MessagingListener listener) - { - threadPool.execute(new Runnable() - { + public void listFolders(final Account account, final boolean refreshRemote, final MessagingListener listener) { + threadPool.execute(new Runnable() { @Override - public void run() - { + public void run() { listFoldersSynchronous(account, refreshRemote, listener); } }); @@ -458,78 +401,58 @@ public class MessagingController implements Runnable * @param listener * @throws MessagingException */ - public void listFoldersSynchronous(final Account account, final boolean refreshRemote, final MessagingListener listener) - { - for (MessagingListener l : getListeners(listener)) - { + public void listFoldersSynchronous(final Account account, final boolean refreshRemote, final MessagingListener listener) { + for (MessagingListener l : getListeners(listener)) { l.listFoldersStarted(account); } - List localFolders = null; - if (!account.isAvailable(mApplication)) - { + List localFolders = null; + if (!account.isAvailable(mApplication)) { Log.i(K9.LOG_TAG, "not listing folders of unavailable account"); - } - else - { - try - { + } else { + try { Store localStore = account.getLocalStore(); localFolders = localStore.getPersonalNamespaces(false); Folder[] folderArray = localFolders.toArray(EMPTY_FOLDER_ARRAY); - if (refreshRemote || localFolders.size() == 0) - { + if (refreshRemote || localFolders.size() == 0) { doRefreshRemote(account, listener); return; } - for (MessagingListener l : getListeners(listener)) - { + for (MessagingListener l : getListeners(listener)) { l.listFolders(account, folderArray); } - } - catch (Exception e) - { - for (MessagingListener l : getListeners(listener)) - { + } catch (Exception e) { + for (MessagingListener l : getListeners(listener)) { l.listFoldersFailed(account, e.getMessage()); } addErrorMessage(account, null, e); return; - } - finally - { - if (localFolders != null) - { - for (Folder localFolder : localFolders) - { + } finally { + if (localFolders != null) { + for (Folder localFolder : localFolders) { closeFolder(localFolder); } } } } - for (MessagingListener l : getListeners(listener)) - { + for (MessagingListener l : getListeners(listener)) { l.listFoldersFinished(account); } } - private void doRefreshRemote(final Account account, MessagingListener listener) - { - put("doRefreshRemote", listener, new Runnable() - { + private void doRefreshRemote(final Account account, MessagingListener listener) { + put("doRefreshRemote", listener, new Runnable() { @Override - public void run() - { - List localFolders = null; - try - { + public void run() { + List localFolders = null; + try { Store store = account.getRemoteStore(); - List remoteFolders = store.getPersonalNamespaces(false); + List remoteFolders = store.getPersonalNamespaces(false); LocalStore localStore = account.getLocalStore(); HashSet remoteFolderNames = new HashSet(); @@ -537,14 +460,11 @@ public class MessagingController implements Runnable localFolders = localStore.getPersonalNamespaces(false); HashSet localFolderNames = new HashSet(); - for (Folder localFolder : localFolders) - { + for (Folder localFolder : localFolders) { localFolderNames.add(localFolder.getName()); } - for (Folder remoteFolder : remoteFolders) - { - if (localFolderNames.contains(remoteFolder.getName()) == false) - { + for (Folder remoteFolder : remoteFolders) { + if (localFolderNames.contains(remoteFolder.getName()) == false) { LocalFolder localFolder = localStore.getFolder(remoteFolder.getName()); foldersToCreate.add(localFolder); } @@ -557,11 +477,9 @@ public class MessagingController implements Runnable /* * Clear out any folders that are no longer on the remote store. */ - for (Folder localFolder : localFolders) - { + for (Folder localFolder : localFolders) { String localFolderName = localFolder.getName(); - if (!account.isSpecialFolder(localFolderName) && !remoteFolderNames.contains(localFolderName)) - { + if (!account.isSpecialFolder(localFolderName) && !remoteFolderNames.contains(localFolderName)) { localFolder.delete(false); } } @@ -569,29 +487,20 @@ public class MessagingController implements Runnable localFolders = localStore.getPersonalNamespaces(false); Folder[] folderArray = localFolders.toArray(EMPTY_FOLDER_ARRAY); - for (MessagingListener l : getListeners()) - { + for (MessagingListener l : getListeners()) { l.listFolders(account, folderArray); } - for (MessagingListener l : getListeners()) - { + for (MessagingListener l : getListeners()) { l.listFoldersFinished(account); } - } - catch (Exception e) - { - for (MessagingListener l : getListeners()) - { + } catch (Exception e) { + for (MessagingListener l : getListeners()) { l.listFoldersFailed(account, ""); } addErrorMessage(account, null, e); - } - finally - { - if (localFolders != null) - { - for (Folder localFolder : localFolders) - { + } finally { + if (localFolders != null) { + for (Folder localFolder : localFolders) { closeFolder(localFolder); } } @@ -610,13 +519,10 @@ public class MessagingController implements Runnable * @param listener * @throws MessagingException */ - public void listLocalMessages(final Account account, final String folder, final MessagingListener listener) - { - threadPool.execute(new Runnable() - { + public void listLocalMessages(final Account account, final String folder, final MessagingListener listener) { + threadPool.execute(new Runnable() { @Override - public void run() - { + public void run() { listLocalMessagesSynchronous(account, folder, listener); } }); @@ -631,18 +537,15 @@ public class MessagingController implements Runnable * @param listener * @throws MessagingException */ - public void listLocalMessagesSynchronous(final Account account, final String folder, final MessagingListener listener) - { + public void listLocalMessagesSynchronous(final Account account, final String folder, final MessagingListener listener) { - for (MessagingListener l : getListeners(listener)) - { + for (MessagingListener l : getListeners(listener)) { l.listLocalMessagesStarted(account, folder); } Folder localFolder = null; MessageRetrievalListener retrievalListener = - new MessageRetrievalListener() - { + new MessageRetrievalListener() { List pendingMessages = new ArrayList(); @@ -652,36 +555,27 @@ public class MessagingController implements Runnable @Override public void messageStarted(String message, int number, int ofTotal) {} @Override - public void messageFinished(Message message, int number, int ofTotal) - { + public void messageFinished(Message message, int number, int ofTotal) { - if (!isMessageSuppressed(account, folder, message)) - { + if (!isMessageSuppressed(account, folder, message)) { pendingMessages.add(message); totalDone++; - if (pendingMessages.size() > 10) - { + if (pendingMessages.size() > 10) { addPendingMessages(); } - } - else - { - for (MessagingListener l : getListeners(listener)) - { + } else { + for (MessagingListener l : getListeners(listener)) { l.listLocalMessagesRemoveMessage(account, folder, message); } } } @Override - public void messagesFinished(int number) - { + public void messagesFinished(int number) { addPendingMessages(); } - private void addPendingMessages() - { - for (MessagingListener l : getListeners(listener)) - { + private void addPendingMessages() { + for (MessagingListener l : getListeners(listener)) { l.listLocalMessagesAddMessages(account, folder, pendingMessages); } pendingMessages.clear(); @@ -690,8 +584,7 @@ public class MessagingController implements Runnable - try - { + try { Store localStore = account.getLocalStore(); localFolder = localStore.getFolder(folder); localFolder.open(OpenMode.READ_WRITE); @@ -703,27 +596,20 @@ public class MessagingController implements Runnable if (K9.DEBUG) Log.v(K9.LOG_TAG, "Got ack that callbackRunner finished"); - for (MessagingListener l : getListeners(listener)) - { + for (MessagingListener l : getListeners(listener)) { l.listLocalMessagesFinished(account, folder); } - } - catch (Exception e) - { - for (MessagingListener l : getListeners(listener)) - { + } catch (Exception e) { + for (MessagingListener l : getListeners(listener)) { l.listLocalMessagesFailed(account, folder, e.getMessage()); } addErrorMessage(account, null, e); - } - finally - { + } finally { closeFolder(localFolder); } } - public void searchLocalMessages(SearchSpecification searchSpecification, final Message[] messages, final MessagingListener listener) - { + public void searchLocalMessages(SearchSpecification searchSpecification, final Message[] messages, final MessagingListener listener) { searchLocalMessages(searchSpecification.getAccountUuids(), searchSpecification.getFolderNames(), messages, searchSpecification.getQuery(), searchSpecification.isIntegrate(), searchSpecification.getRequiredFlags(), searchSpecification.getForbiddenFlags(), listener); } @@ -734,10 +620,8 @@ public class MessagingController implements Runnable * @throws MessagingException */ public void searchLocalMessages(final String[] accountUuids, final String[] folderNames, final Message[] messages, final String query, final boolean integrate, - final Flag[] requiredFlags, final Flag[] forbiddenFlags, final MessagingListener listener) - { - if (K9.DEBUG) - { + final Flag[] requiredFlags, final Flag[] forbiddenFlags, final MessagingListener listener) { + if (K9.DEBUG) { Log.i(K9.LOG_TAG, "searchLocalMessages (" + "accountUuids=" + Utility.combine(accountUuids, ',') + ", folderNames = " + Utility.combine(folderNames, ',') @@ -749,22 +633,18 @@ public class MessagingController implements Runnable + ")"); } - threadPool.execute(new Runnable() - { + threadPool.execute(new Runnable() { @Override - public void run() - { - searchLocalMessagesSynchronous(accountUuids,folderNames, messages, query, integrate, requiredFlags, forbiddenFlags, listener); + public void run() { + searchLocalMessagesSynchronous(accountUuids, folderNames, messages, query, integrate, requiredFlags, forbiddenFlags, listener); } }); } - public void searchLocalMessagesSynchronous(final String[] accountUuids, final String[] folderNames, final Message[] messages, final String query, final boolean integrate, final Flag[] requiredFlags, final Flag[] forbiddenFlags, final MessagingListener listener) - { + public void searchLocalMessagesSynchronous(final String[] accountUuids, final String[] folderNames, final Message[] messages, final String query, final boolean integrate, final Flag[] requiredFlags, final Flag[] forbiddenFlags, final MessagingListener listener) { final AccountStats stats = new AccountStats(); final Set accountUuidsSet = new HashSet(); - if (accountUuids != null) - { + if (accountUuids != null) { accountUuidsSet.addAll(Arrays.asList(accountUuids)); } final Preferences prefs = Preferences.getPreferences(mApplication.getApplicationContext()); @@ -772,84 +652,64 @@ public class MessagingController implements Runnable List foldersToSearch = null; boolean displayableOnly = false; boolean noSpecialFolders = true; - for (final Account account : accounts) - { - if (!account.isAvailable(mApplication)) - { + for (final Account account : accounts) { + if (!account.isAvailable(mApplication)) { Log.d(K9.LOG_TAG, "searchLocalMessagesSynchronous() ignores account that is not available"); continue; } - if (accountUuids != null && !accountUuidsSet.contains(account.getUuid())) - { + if (accountUuids != null && !accountUuidsSet.contains(account.getUuid())) { continue; } - if (accountUuids != null && accountUuidsSet.contains(account.getUuid())) - { + if (accountUuids != null && accountUuidsSet.contains(account.getUuid())) { displayableOnly = true; noSpecialFolders = true; - } - else if (!integrate && folderNames == null) - { + } else if (!integrate && folderNames == null) { Account.Searchable searchableFolders = account.getSearchableFolders(); - switch (searchableFolders) - { - case NONE: - continue; - case DISPLAYABLE: - displayableOnly = true; - break; + switch (searchableFolders) { + case NONE: + continue; + case DISPLAYABLE: + displayableOnly = true; + break; } } List messagesToSearch = null; - if (messages != null) - { + if (messages != null) { messagesToSearch = new LinkedList(); - for (Message message : messages) - { - if (message.getFolder().getAccount().getUuid().equals(account.getUuid())) - { + for (Message message : messages) { + if (message.getFolder().getAccount().getUuid().equals(account.getUuid())) { messagesToSearch.add(message); } } - if (messagesToSearch.isEmpty()) - { + if (messagesToSearch.isEmpty()) { continue; } } - if (listener != null) - { + if (listener != null) { listener.listLocalMessagesStarted(account, null); } - if (integrate || displayableOnly || folderNames != null || noSpecialFolders) - { + if (integrate || displayableOnly || folderNames != null || noSpecialFolders) { List tmpFoldersToSearch = new LinkedList(); - try - { + try { LocalStore store = account.getLocalStore(); - List folders = store.getPersonalNamespaces(false); + List folders = store.getPersonalNamespaces(false); Set folderNameSet = null; - if (folderNames != null) - { + if (folderNames != null) { folderNameSet = new HashSet(); folderNameSet.addAll(Arrays.asList(folderNames)); } - for (Folder folder : folders) - { + for (Folder folder : folders) { LocalFolder localFolder = (LocalFolder)folder; boolean include = true; folder.refresh(prefs); String localFolderName = localFolder.getName(); - if (integrate) - { + if (integrate) { include = localFolder.isIntegrate(); - } - else - { - if (folderNameSet != null) - { + } else { + if (folderNameSet != null) { if (!folderNameSet.contains(localFolderName)) { @@ -858,118 +718,91 @@ public class MessagingController implements Runnable } // Never exclude the INBOX (see issue 1817) else if (noSpecialFolders && !localFolderName.equalsIgnoreCase(K9.INBOX) && - !localFolderName.equals(account.getArchiveFolderName()) && account.isSpecialFolder(localFolderName)) - { + !localFolderName.equals(account.getArchiveFolderName()) && account.isSpecialFolder(localFolderName)) { include = false; - } - else if (displayableOnly && modeMismatch(account.getFolderDisplayMode(), folder.getDisplayClass())) - { + } else if (displayableOnly && modeMismatch(account.getFolderDisplayMode(), folder.getDisplayClass())) { include = false; } } - if (include) - { + if (include) { tmpFoldersToSearch.add(localFolder); } } - if (tmpFoldersToSearch.size() < 1) - { + if (tmpFoldersToSearch.size() < 1) { continue; } foldersToSearch = tmpFoldersToSearch; - } - catch (MessagingException me) - { + } catch (MessagingException me) { Log.e(K9.LOG_TAG, "Unable to restrict search folders in Account " + account.getDescription() + ", searching all", me); addErrorMessage(account, null, me); } } - MessageRetrievalListener retrievalListener = new MessageRetrievalListener() - { + MessageRetrievalListener retrievalListener = new MessageRetrievalListener() { @Override public void messageStarted(String message, int number, int ofTotal) {} @Override - public void messageFinished(Message message, int number, int ofTotal) - { - if (!isMessageSuppressed(message.getFolder().getAccount(), message.getFolder().getName(), message)) - { + public void messageFinished(Message message, int number, int ofTotal) { + if (!isMessageSuppressed(message.getFolder().getAccount(), message.getFolder().getName(), message)) { List messages = new ArrayList(); messages.add(message); stats.unreadMessageCount += (!message.isSet(Flag.SEEN)) ? 1 : 0; stats.flaggedMessageCount += (message.isSet(Flag.FLAGGED)) ? 1 : 0; - if (listener != null) - { + if (listener != null) { listener.listLocalMessagesAddMessages(account, null, messages); } } } @Override - public void messagesFinished(int number) - { + public void messagesFinished(int number) { } }; - try - { - String[] queryFields = {"html_content","subject","sender_list"}; + try { + String[] queryFields = {"html_content", "subject", "sender_list"}; LocalStore localStore = account.getLocalStore(); localStore.searchForMessages(retrievalListener, queryFields , query, foldersToSearch, messagesToSearch == null ? null : messagesToSearch.toArray(EMPTY_MESSAGE_ARRAY), requiredFlags, forbiddenFlags); - } - catch (Exception e) - { - if (listener != null) - { + } catch (Exception e) { + if (listener != null) { listener.listLocalMessagesFailed(account, null, e.getMessage()); } addErrorMessage(account, null, e); - } - finally - { - if (listener != null) - { + } finally { + if (listener != null) { listener.listLocalMessagesFinished(account, null); } } } - if (listener != null) - { + if (listener != null) { listener.searchStats(stats); } } - public void loadMoreMessages(Account account, String folder, MessagingListener listener) - { - try - { + public void loadMoreMessages(Account account, String folder, MessagingListener listener) { + try { LocalStore localStore = account.getLocalStore(); LocalFolder localFolder = localStore.getFolder(folder); - if (localFolder.getVisibleLimit() > 0 ) - { + if (localFolder.getVisibleLimit() > 0) { localFolder.setVisibleLimit(localFolder.getVisibleLimit() + account.getDisplayCount()); } synchronizeMailbox(account, folder, listener, null); - } - catch (MessagingException me) - { + } catch (MessagingException me) { addErrorMessage(account, null, me); throw new RuntimeException("Unable to set visible limit on folder", me); } } - public void resetVisibleLimits(Collection accounts) - { - for (Account account : accounts) - { + public void resetVisibleLimits(Collection accounts) { + for (Account account : accounts) { account.resetVisibleLimits(); } } @@ -981,13 +814,10 @@ public class MessagingController implements Runnable * @param listener * @param providedRemoteFolder TODO */ - public void synchronizeMailbox(final Account account, final String folder, final MessagingListener listener, final Folder providedRemoteFolder) - { - putBackground("synchronizeMailbox", listener, new Runnable() - { + public void synchronizeMailbox(final Account account, final String folder, final MessagingListener listener, final Folder providedRemoteFolder) { + putBackground("synchronizeMailbox", listener, new Runnable() { @Override - public void run() - { + public void run() { synchronizeMailboxSynchronous(account, folder, listener, providedRemoteFolder); } }); @@ -1002,25 +832,21 @@ public class MessagingController implements Runnable * TODO Break this method up into smaller chunks. * @param providedRemoteFolder TODO */ - private void synchronizeMailboxSynchronous(final Account account, final String folder, final MessagingListener listener, Folder providedRemoteFolder) - { + private void synchronizeMailboxSynchronous(final Account account, final String folder, final MessagingListener listener, Folder providedRemoteFolder) { Folder remoteFolder = null; LocalFolder tLocalFolder = null; if (K9.DEBUG) Log.i(K9.LOG_TAG, "Synchronizing folder " + account.getDescription() + ":" + folder); - for (MessagingListener l : getListeners(listener)) - { + for (MessagingListener l : getListeners(listener)) { l.synchronizeMailboxStarted(account, folder); } /* * We don't ever sync the Outbox or errors folder */ - if (folder.equals(account.getOutboxFolderName()) || folder.equals(account.getErrorFolderName())) - { - for (MessagingListener l : getListeners(listener)) - { + if (folder.equals(account.getOutboxFolderName()) || folder.equals(account.getErrorFolderName())) { + for (MessagingListener l : getListeners(listener)) { l.synchronizeMailboxFinished(account, folder, 0, 0); } @@ -1028,17 +854,13 @@ public class MessagingController implements Runnable } Exception commandException = null; - try - { + try { if (K9.DEBUG) Log.d(K9.LOG_TAG, "SYNC: About to process pending commands for account " + account.getDescription()); - try - { + try { processPendingCommandsSynchronous(account); - } - catch (Exception e) - { + } catch (Exception e) { addErrorMessage(account, null, e); Log.e(K9.LOG_TAG, "Failure processing command, but allow message sync attempt", e); @@ -1059,27 +881,22 @@ public class MessagingController implements Runnable localFolder.updateLastUid(); Message[] localMessages = localFolder.getMessages(null); HashMap localUidMap = new HashMap(); - for (Message message : localMessages) - { + for (Message message : localMessages) { localUidMap.put(message.getUid(), message); } - if (providedRemoteFolder != null) - { + if (providedRemoteFolder != null) { if (K9.DEBUG) Log.v(K9.LOG_TAG, "SYNC: using providedRemoteFolder " + folder); remoteFolder = providedRemoteFolder; - } - else - { + } else { Store remoteStore = account.getRemoteStore(); if (K9.DEBUG) Log.v(K9.LOG_TAG, "SYNC: About to get remote folder " + folder); remoteFolder = remoteStore.getFolder(folder); - if (! verifyOrCreateRemoteSpecialFolder(account, folder, remoteFolder, listener)) - { + if (! verifyOrCreateRemoteSpecialFolder(account, folder, remoteFolder, listener)) { return; } @@ -1109,8 +926,7 @@ public class MessagingController implements Runnable Log.v(K9.LOG_TAG, "SYNC: About to open remote folder " + folder); remoteFolder.open(OpenMode.READ_WRITE); - if (Account.EXPUNGE_ON_POLL.equals(account.getExpungePolicy())) - { + if (Account.EXPUNGE_ON_POLL.equals(account.getExpungePolicy())) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "SYNC: Expunging folder " + account.getDescription() + ":" + folder); remoteFolder.expunge(); @@ -1125,8 +941,7 @@ public class MessagingController implements Runnable int visibleLimit = localFolder.getVisibleLimit(); - if (visibleLimit < 0) - { + if (visibleLimit < 0) { visibleLimit = K9.DEFAULT_VISIBLE_LIMIT; } @@ -1139,16 +954,12 @@ public class MessagingController implements Runnable final Date earliestDate = account.getEarliestPollDate(); - if (remoteMessageCount > 0) - { + if (remoteMessageCount > 0) { /* Message numbers start at 1. */ int remoteStart; - if (visibleLimit > 0 ) - { + if (visibleLimit > 0) { remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; - } - else - { + } else { remoteStart = 1; } int remoteEnd = remoteMessageCount; @@ -1157,8 +968,7 @@ public class MessagingController implements Runnable Log.v(K9.LOG_TAG, "SYNC: About to get messages " + remoteStart + " through " + remoteEnd + " for folder " + folder); final AtomicInteger headerProgress = new AtomicInteger(0); - for (MessagingListener l : getListeners(listener)) - { + for (MessagingListener l : getListeners(listener)) { l.synchronizeMailboxHeadersStarted(account, folder); } @@ -1167,16 +977,13 @@ public class MessagingController implements Runnable int messageCount = remoteMessageArray.length; - for (Message thisMess : remoteMessageArray) - { + for (Message thisMess : remoteMessageArray) { headerProgress.incrementAndGet(); - for (MessagingListener l : getListeners(listener)) - { + for (MessagingListener l : getListeners(listener)) { l.synchronizeMailboxHeadersProgress(account, folder, headerProgress.get(), messageCount); } Message localMessage = localUidMap.get(thisMess.getUid()); - if (localMessage == null || !localMessage.olderThan(earliestDate)) - { + if (localMessage == null || !localMessage.olderThan(earliestDate)) { remoteMessages.add(thisMess); remoteUidMap.put(thisMess.getUid(), thisMess); } @@ -1185,30 +992,23 @@ public class MessagingController implements Runnable Log.v(K9.LOG_TAG, "SYNC: Got " + remoteUidMap.size() + " messages for folder " + folder); remoteMessageArray = null; - for (MessagingListener l : getListeners(listener)) - { + for (MessagingListener l : getListeners(listener)) { l.synchronizeMailboxHeadersFinished(account, folder, headerProgress.get(), remoteUidMap.size()); } - } - else if (remoteMessageCount < 0) - { + } else if (remoteMessageCount < 0) { throw new Exception("Message count " + remoteMessageCount + " for folder " + folder); } /* * Remove any messages that are in the local store but no longer on the remote store or are too old */ - if (account.syncRemoteDeletions()) - { - for (Message localMessage : localMessages) - { - if (remoteUidMap.get(localMessage.getUid()) == null) - { + if (account.syncRemoteDeletions()) { + for (Message localMessage : localMessages) { + if (remoteUidMap.get(localMessage.getUid()) == null) { localMessage.destroy(); - for (MessagingListener l : getListeners(listener)) - { + for (MessagingListener l : getListeners(listener)) { l.synchronizeMailboxRemovedMessage(account, folder, localMessage); } } @@ -1225,8 +1025,7 @@ public class MessagingController implements Runnable setLocalFlaggedCountToRemote(localFolder, remoteFolder); - for (MessagingListener l : getListeners()) - { + for (MessagingListener l : getListeners()) { l.folderStatusChanged(account, folder, unreadMessageCount); } @@ -1239,20 +1038,17 @@ public class MessagingController implements Runnable Log.d(K9.LOG_TAG, "Done synchronizing folder " + account.getDescription() + ":" + folder + " @ " + new Date() + " with " + newMessages + " new messages"); - for (MessagingListener l : getListeners(listener)) - { + for (MessagingListener l : getListeners(listener)) { l.synchronizeMailboxFinished(account, folder, remoteMessageCount, newMessages); } - if (commandException != null) - { + if (commandException != null) { String rootMessage = getRootCauseMessage(commandException); Log.e(K9.LOG_TAG, "Root cause failure in " + account.getDescription() + ":" + tLocalFolder.getName() + " was '" + rootMessage + "'"); localFolder.setStatus(rootMessage); - for (MessagingListener l : getListeners(listener)) - { + for (MessagingListener l : getListeners(listener)) { l.synchronizeMailboxFailed(account, folder, rootMessage); } } @@ -1260,39 +1056,29 @@ public class MessagingController implements Runnable if (K9.DEBUG) Log.i(K9.LOG_TAG, "Done synchronizing folder " + account.getDescription() + ":" + folder); - } - catch (Exception e) - { + } catch (Exception e) { Log.e(K9.LOG_TAG, "synchronizeMailbox", e); // If we don't set the last checked, it can try too often during // failure conditions String rootMessage = getRootCauseMessage(e); - if (tLocalFolder != null) - { - try - { + if (tLocalFolder != null) { + try { tLocalFolder.setStatus(rootMessage); tLocalFolder.setLastChecked(System.currentTimeMillis()); - } - catch (MessagingException me) - { + } catch (MessagingException me) { Log.e(K9.LOG_TAG, "Could not set last checked on folder " + account.getDescription() + ":" + tLocalFolder.getName(), e); } } - for (MessagingListener l : getListeners(listener)) - { - l.synchronizeMailboxFailed( account, folder, rootMessage); + for (MessagingListener l : getListeners(listener)) { + l.synchronizeMailboxFailed(account, folder, rootMessage); } addErrorMessage(account, null, e); Log.e(K9.LOG_TAG, "Failed synchronizing folder " + account.getDescription() + ":" + folder + " @ " + new Date()); - } - finally - { - if (providedRemoteFolder == null) - { + } finally { + if (providedRemoteFolder == null) { closeFolder(remoteFolder); } @@ -1302,10 +1088,8 @@ public class MessagingController implements Runnable } - private void closeFolder(Folder f) - { - if (f != null) - { + private void closeFolder(Folder f) { + if (f != null) { f.close(); } } @@ -1318,18 +1102,13 @@ public class MessagingController implements Runnable * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ - private boolean verifyOrCreateRemoteSpecialFolder(final Account account, final String folder, final Folder remoteFolder, final MessagingListener listener) throws MessagingException - { + private boolean verifyOrCreateRemoteSpecialFolder(final Account account, final String folder, final Folder remoteFolder, final MessagingListener listener) throws MessagingException { if (folder.equals(account.getTrashFolderName()) || folder.equals(account.getSentFolderName()) || - folder.equals(account.getDraftsFolderName())) - { - if (!remoteFolder.exists()) - { - if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) - { - for (MessagingListener l : getListeners(listener)) - { + folder.equals(account.getDraftsFolderName())) { + if (!remoteFolder.exists()) { + if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { + for (MessagingListener l : getListeners(listener)) { l.synchronizeMailboxFinished(account, folder, 0, 0); } if (K9.DEBUG) @@ -1341,21 +1120,15 @@ public class MessagingController implements Runnable } return true; } - private int setLocalUnreadCountToRemote(LocalFolder localFolder, Folder remoteFolder, int newMessageCount) throws MessagingException - { + private int setLocalUnreadCountToRemote(LocalFolder localFolder, Folder remoteFolder, int newMessageCount) throws MessagingException { int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount(); - if (remoteUnreadMessageCount != -1) - { + if (remoteUnreadMessageCount != -1) { localFolder.setUnreadMessageCount(remoteUnreadMessageCount); - } - else - { + } else { int unreadCount = 0; Message[] messages = localFolder.getMessages(null, false); - for (Message message : messages) - { - if (!message.isSet(Flag.SEEN) && !message.isSet(Flag.DELETED)) - { + for (Message message : messages) { + if (!message.isSet(Flag.SEEN) && !message.isSet(Flag.DELETED)) { unreadCount++; } } @@ -1364,21 +1137,15 @@ public class MessagingController implements Runnable return localFolder.getUnreadMessageCount(); } - private void setLocalFlaggedCountToRemote(LocalFolder localFolder, Folder remoteFolder) throws MessagingException - { + private void setLocalFlaggedCountToRemote(LocalFolder localFolder, Folder remoteFolder) throws MessagingException { int remoteFlaggedMessageCount = remoteFolder.getFlaggedMessageCount(); - if (remoteFlaggedMessageCount != -1) - { + if (remoteFlaggedMessageCount != -1) { localFolder.setFlaggedMessageCount(remoteFlaggedMessageCount); - } - else - { + } else { int flaggedCount = 0; Message[] messages = localFolder.getMessages(null, false); - for (Message message : messages) - { - if (message.isSet(Flag.FLAGGED) && !message.isSet(Flag.DELETED)) - { + for (Message message : messages) { + if (message.isSet(Flag.FLAGGED) && !message.isSet(Flag.DELETED)) { flaggedCount++; } } @@ -1387,30 +1154,24 @@ public class MessagingController implements Runnable } private int downloadMessages(final Account account, final Folder remoteFolder, - final LocalFolder localFolder, List inputMessages, boolean flagSyncOnly) throws MessagingException - { + final LocalFolder localFolder, List inputMessages, boolean flagSyncOnly) throws MessagingException { final Date earliestDate = account.getEarliestPollDate(); Date downloadStarted = new Date(); // now - if (earliestDate != null) - { - if (K9.DEBUG) - { + if (earliestDate != null) { + if (K9.DEBUG) { Log.d(K9.LOG_TAG, "Only syncing messages after " + earliestDate); } } final String folder = remoteFolder.getName(); int unreadBeforeStart = 0; - try - { + try { AccountStats stats = account.getStats(mApplication); unreadBeforeStart = stats.unreadMessageCount; - } - catch (MessagingException e) - { + } catch (MessagingException e) { Log.e(K9.LOG_TAG, "Unable to getUnreadMessageCount for account: " + account, e); } @@ -1420,15 +1181,13 @@ public class MessagingController implements Runnable List messages = new ArrayList(inputMessages); - for (Message message : messages) - { - evaluateMessageForDownload(message, folder,localFolder, remoteFolder, account,unsyncedMessages, syncFlagMessages ,flagSyncOnly); + for (Message message : messages) { + evaluateMessageForDownload(message, folder, localFolder, remoteFolder, account, unsyncedMessages, syncFlagMessages , flagSyncOnly); } final AtomicInteger progress = new AtomicInteger(0); final int todo = unsyncedMessages.size() + syncFlagMessages.size(); - for (MessagingListener l : getListeners()) - { + for (MessagingListener l : getListeners()) { l.synchronizeMailboxProgress(account, folder, progress.get(), todo); } @@ -1438,8 +1197,7 @@ public class MessagingController implements Runnable messages.clear(); final ArrayList largeMessages = new ArrayList(); final ArrayList smallMessages = new ArrayList(); - if (unsyncedMessages.size() > 0) - { + if (unsyncedMessages.size() > 0) { /* * Reverse the order of the messages. Depending on the server this may get us @@ -1449,14 +1207,12 @@ public class MessagingController implements Runnable int visibleLimit = localFolder.getVisibleLimit(); int listSize = unsyncedMessages.size(); - if ((visibleLimit > 0) && (listSize > visibleLimit)) - { + if ((visibleLimit > 0) && (listSize > visibleLimit)) { unsyncedMessages = unsyncedMessages.subList(listSize - visibleLimit, listSize); } FetchProfile fp = new FetchProfile(); - if (remoteFolder.supportsFetchingFlags()) - { + if (remoteFolder.supportsFetchingFlags()) { fp.add(FetchProfile.Item.FLAGS); } fp.add(FetchProfile.Item.ENVELOPE); @@ -1465,20 +1221,17 @@ public class MessagingController implements Runnable Log.d(K9.LOG_TAG, "SYNC: About to fetch " + unsyncedMessages.size() + " unsynced messages for folder " + folder); - fetchUnsyncedMessages(account, remoteFolder, localFolder, unsyncedMessages, smallMessages,largeMessages, progress, todo, fp); + fetchUnsyncedMessages(account, remoteFolder, localFolder, unsyncedMessages, smallMessages, largeMessages, progress, todo, fp); // If a message didn't exist, messageFinished won't be called, but we shouldn't try again // If we got here, nothing failed - for (Message message : unsyncedMessages) - { + for (Message message : unsyncedMessages) { String newPushState = remoteFolder.getNewPushState(localFolder.getPushState(), message); - if (newPushState != null) - { + if (newPushState != null) { localFolder.setPushState(newPushState); } } - if (K9.DEBUG) - { + if (K9.DEBUG) { Log.d(K9.LOG_TAG, "SYNC: Synced unsynced messages for folder " + folder); } @@ -1519,18 +1272,15 @@ public class MessagingController implements Runnable * download. */ - refreshLocalMessageFlags(account,remoteFolder,localFolder,syncFlagMessages,progress,todo); + refreshLocalMessageFlags(account, remoteFolder, localFolder, syncFlagMessages, progress, todo); if (K9.DEBUG) Log.d(K9.LOG_TAG, "SYNC: Synced remote messages for folder " + folder + ", " + newMessages.get() + " new messages"); - localFolder.purgeToVisibleLimit(new MessageRemovalListener() - { + localFolder.purgeToVisibleLimit(new MessageRemovalListener() { @Override - public void messageRemoved(Message message) - { - for (MessagingListener l : getListeners()) - { + public void messageRemoved(Message message) { + for (MessagingListener l : getListeners()) { l.synchronizeMailboxRemovedMessage(account, folder, message); } } @@ -1545,12 +1295,10 @@ public class MessagingController implements Runnable // fortunately, we just don't care. Long oldestMessageTime = localFolder.getOldestMessageDate(); - if (oldestMessageTime != null) - { + if (oldestMessageTime != null) { Date oldestExtantMessage = new Date(oldestMessageTime); - if (oldestExtantMessage.before(downloadStarted) && - oldestExtantMessage.after(new Date(account.getLatestOldMessageSeenTime()))) - { + if (oldestExtantMessage.before(downloadStarted) && + oldestExtantMessage.after(new Date(account.getLatestOldMessageSeenTime()))) { account.setLatestOldMessageSeenTime(oldestExtantMessage.getTime()); account.save(Preferences.getPreferences(mApplication.getApplicationContext())); } @@ -1564,33 +1312,24 @@ public class MessagingController implements Runnable final Account account, final List unsyncedMessages, final ArrayList syncFlagMessages, - boolean flagSyncOnly) throws MessagingException - { - if (message.isSet(Flag.DELETED)) - { + boolean flagSyncOnly) throws MessagingException { + if (message.isSet(Flag.DELETED)) { syncFlagMessages.add(message); return; - } - else if (isMessageSuppressed(account, folder, message)) - { + } else if (isMessageSuppressed(account, folder, message)) { return; } Message localMessage = localFolder.getMessage(message.getUid()); - if (localMessage == null) - { - if (!flagSyncOnly) - { - if (!message.isSet(Flag.X_DOWNLOADED_FULL) && !message.isSet(Flag.X_DOWNLOADED_PARTIAL)) - { + if (localMessage == null) { + if (!flagSyncOnly) { + if (!message.isSet(Flag.X_DOWNLOADED_FULL) && !message.isSet(Flag.X_DOWNLOADED_PARTIAL)) { if (K9.DEBUG) Log.v(K9.LOG_TAG, "Message with uid " + message.getUid() + " has not yet been downloaded"); unsyncedMessages.add(message); - } - else - { + } else { if (K9.DEBUG) Log.v(K9.LOG_TAG, "Message with uid " + message.getUid() + " is partially or fully downloaded"); @@ -1602,35 +1341,27 @@ public class MessagingController implements Runnable localMessage.setFlag(Flag.X_DOWNLOADED_FULL, message.isSet(Flag.X_DOWNLOADED_FULL)); localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, message.isSet(Flag.X_DOWNLOADED_PARTIAL)); - for (MessagingListener l : getListeners()) - { + for (MessagingListener l : getListeners()) { l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage); - if (!localMessage.isSet(Flag.SEEN)) - { + if (!localMessage.isSet(Flag.SEEN)) { l.synchronizeMailboxNewMessage(account, folder, localMessage); } } } } - } - else if (!localMessage.isSet(Flag.DELETED)) - { + } else if (!localMessage.isSet(Flag.DELETED)) { if (K9.DEBUG) Log.v(K9.LOG_TAG, "Message with uid " + message.getUid() + " is present in the local store"); - if (!localMessage.isSet(Flag.X_DOWNLOADED_FULL) && !localMessage.isSet(Flag.X_DOWNLOADED_PARTIAL)) - { + if (!localMessage.isSet(Flag.X_DOWNLOADED_FULL) && !localMessage.isSet(Flag.X_DOWNLOADED_PARTIAL)) { if (K9.DEBUG) Log.v(K9.LOG_TAG, "Message with uid " + message.getUid() + " is not downloaded, even partially; trying again"); unsyncedMessages.add(message); - } - else - { + } else { String newPushState = remoteFolder.getNewPushState(localFolder.getPushState(), message); - if (newPushState != null) - { + if (newPushState != null) { localFolder.setPushState(newPushState); } syncFlagMessages.add(message); @@ -1645,8 +1376,7 @@ public class MessagingController implements Runnable final ArrayList largeMessages, final AtomicInteger progress, final int todo, - FetchProfile fp) throws MessagingException - { + FetchProfile fp) throws MessagingException { final String folder = remoteFolder.getName(); final Date earliestDate = account.getEarliestPollDate(); @@ -1657,75 +1387,57 @@ public class MessagingController implements Runnable final List chunk = new ArrayList(UNSYNC_CHUNK_SIZE); remoteFolder.fetch(unsyncedMessages.toArray(EMPTY_MESSAGE_ARRAY), fp, - new MessageRetrievalListener() - { + new MessageRetrievalListener() { @Override - public void messageFinished(Message message, int number, int ofTotal) - { - try - { + public void messageFinished(Message message, int number, int ofTotal) { + try { String newPushState = remoteFolder.getNewPushState(localFolder.getPushState(), message); - if (newPushState != null) - { + if (newPushState != null) { localFolder.setPushState(newPushState); } - if (message.isSet(Flag.DELETED) || message.olderThan(earliestDate)) - { + if (message.isSet(Flag.DELETED) || message.olderThan(earliestDate)) { - if (K9.DEBUG) - { - if (message.isSet(Flag.DELETED)) - { + if (K9.DEBUG) { + if (message.isSet(Flag.DELETED)) { Log.v(K9.LOG_TAG, "Newly downloaded message " + account + ":" + folder + ":" + message.getUid() + " was marked deleted on server, skipping"); - } - else - { + } else { Log.d(K9.LOG_TAG, "Newly downloaded message " + message.getUid() + " is older than " + earliestDate + ", skipping"); } } progress.incrementAndGet(); - for (MessagingListener l : getListeners()) - { + for (MessagingListener l : getListeners()) { l.synchronizeMailboxProgress(account, folder, progress.get(), todo); } return; } - if (message.getSize() > account.getMaximumAutoDownloadMessageSize()) - { + if (message.getSize() > account.getMaximumAutoDownloadMessageSize()) { largeMessages.add(message); - } - else - { + } else { smallMessages.add(message); } // And include it in the view - if (message.getSubject() != null && message.getFrom() != null) - { + if (message.getSubject() != null && message.getFrom() != null) { /* * We check to make sure that we got something worth * showing (subject and from) because some protocols * (POP) may not be able to give us headers for * ENVELOPE, only size. */ - if (!isMessageSuppressed(account, folder, message)) - { + if (!isMessageSuppressed(account, folder, message)) { // keep message for delayed storing chunk.add(message); - if (chunk.size() >= UNSYNC_CHUNK_SIZE) - { + if (chunk.size() >= UNSYNC_CHUNK_SIZE) { writeUnsyncedMessages(chunk, localFolder, account, folder); chunk.clear(); } } } - } - catch (Exception e) - { + } catch (Exception e) { Log.e(K9.LOG_TAG, "Error while storing downloaded message.", e); addErrorMessage(account, null, e); } @@ -1735,14 +1447,12 @@ public class MessagingController implements Runnable public void messageStarted(String uid, int number, int ofTotal) {} @Override - public void messagesFinished(int total) - { + public void messagesFinished(int total) { // FIXME this method is almost never invoked by various Stores! Don't rely on it unless fixed!! } }); - if (chunk.size() > 0) - { + if (chunk.size() > 0) { writeUnsyncedMessages(chunk, localFolder, account, folder); chunk.clear(); } @@ -1759,56 +1469,44 @@ public class MessagingController implements Runnable * @param account * @param folder */ - private void writeUnsyncedMessages(final List messages, final LocalFolder localFolder, final Account account, final String folder) - { - if (K9.DEBUG) - { + private void writeUnsyncedMessages(final List messages, final LocalFolder localFolder, final Account account, final String folder) { + if (K9.DEBUG) { Log.v(K9.LOG_TAG, "Batch writing " + Integer.toString(messages.size()) + " messages"); } - try - { + try { // Store the new message locally localFolder.appendMessages(messages.toArray(new Message[messages.size()])); - for (final Message message : messages) - { + for (final Message message : messages) { final Message localMessage = localFolder.getMessage(message.getUid()); syncFlags(localMessage, message); if (K9.DEBUG) Log.v(K9.LOG_TAG, "About to notify listeners that we got a new unsynced message " + account + ":" + folder + ":" + message.getUid()); - for (final MessagingListener l : getListeners()) - { + for (final MessagingListener l : getListeners()) { l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage); } } - } - catch (final Exception e) - { + } catch (final Exception e) { Log.e(K9.LOG_TAG, "Error while storing downloaded message.", e); addErrorMessage(account, null, e); } } - private boolean shouldImportMessage(final Account account, final String folder, final Message message, final AtomicInteger progress, final Date earliestDate) - { + private boolean shouldImportMessage(final Account account, final String folder, final Message message, final AtomicInteger progress, final Date earliestDate) { - if (isMessageSuppressed(account, folder, message)) - { - if (K9.DEBUG) - { - Log.d(K9.LOG_TAG, "Message " + message.getUid() + " was suppressed "+ - "but just downloaded. "+ + if (isMessageSuppressed(account, folder, message)) { + if (K9.DEBUG) { + Log.d(K9.LOG_TAG, "Message " + message.getUid() + " was suppressed " + + "but just downloaded. " + "The race condition means we wasted some bandwidth. Oh well."); } return false; } - if (message.olderThan(earliestDate)) - { - if (K9.DEBUG) - { + if (message.olderThan(earliestDate)) { + if (K9.DEBUG) { Log.d(K9.LOG_TAG, "Message " + message.getUid() + " is older than " + earliestDate + ", hence not saving"); } @@ -1824,8 +1522,7 @@ public class MessagingController implements Runnable final int unreadBeforeStart, final AtomicInteger newMessages, final int todo, - FetchProfile fp) throws MessagingException - { + FetchProfile fp) throws MessagingException { final String folder = remoteFolder.getName(); final Date earliestDate = account.getEarliestPollDate(); @@ -1834,27 +1531,21 @@ public class MessagingController implements Runnable Log.d(K9.LOG_TAG, "SYNC: Fetching small messages for folder " + folder); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), - fp, new MessageRetrievalListener() - { + fp, new MessageRetrievalListener() { @Override - public void messageFinished(Message message, int number, int ofTotal) - { - try - { + public void messageFinished(Message message, int number, int ofTotal) { + try { - if (!shouldImportMessage(account, folder, message, progress, earliestDate)) - { + if (!shouldImportMessage(account, folder, message, progress, earliestDate)) { progress.incrementAndGet(); return; } // Store the updated message locally - final Message localMessage = localFolder.storeSmallMessage(message, new Runnable() - { + final Message localMessage = localFolder.storeSmallMessage(message, new Runnable() { @Override - public void run() - { + public void run() { progress.incrementAndGet(); } }); @@ -1863,26 +1554,21 @@ public class MessagingController implements Runnable + account + ":" + folder + ":" + message.getUid()); // Update the listener with what we've found - for (MessagingListener l : getListeners()) - { + for (MessagingListener l : getListeners()) { l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage); l.synchronizeMailboxProgress(account, folder, progress.get(), todo); - if (!localMessage.isSet(Flag.SEEN)) - { + if (!localMessage.isSet(Flag.SEEN)) { l.synchronizeMailboxNewMessage(account, folder, localMessage); } } // Send a notification of this message - if (shouldNotifyForMessage(account, localFolder, message)) - { + if (shouldNotifyForMessage(account, localFolder, message)) { newMessages.incrementAndGet(); notifyAccount(mApplication, account, message, unreadBeforeStart, newMessages); } - } - catch (MessagingException me) - { + } catch (MessagingException me) { addErrorMessage(account, null, me); Log.e(K9.LOG_TAG, "SYNC: fetch small messages", me); } @@ -1908,8 +1594,7 @@ public class MessagingController implements Runnable final int unreadBeforeStart, final AtomicInteger newMessages, final int todo, - FetchProfile fp) throws MessagingException - { + FetchProfile fp) throws MessagingException { final String folder = remoteFolder.getName(); final Date earliestDate = account.getEarliestPollDate(); @@ -1918,17 +1603,14 @@ public class MessagingController implements Runnable Log.d(K9.LOG_TAG, "SYNC: Fetching large messages for folder " + folder); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); - for (Message message : largeMessages) - { + for (Message message : largeMessages) { - if (!shouldImportMessage(account, folder, message, progress, earliestDate)) - { + if (!shouldImportMessage(account, folder, message, progress, earliestDate)) { progress.incrementAndGet(); continue; } - if (message.getBody() == null) - { + if (message.getBody() == null) { /* * The provider was unable to get the structure of the message, so * we'll download a reasonable portion of the messge and mark it as @@ -1952,28 +1634,22 @@ public class MessagingController implements Runnable // Certain (POP3) servers give you the whole message even when you ask for only the first x Kb - if (!message.isSet(Flag.X_DOWNLOADED_FULL)) - { + if (!message.isSet(Flag.X_DOWNLOADED_FULL)) { /* * Mark the message as fully downloaded if the message size is smaller than * the account's autodownload size limit, otherwise mark as only a partial * download. This will prevent the system from downloading the same message * twice. */ - if (message.getSize() < account.getMaximumAutoDownloadMessageSize()) - { + if (message.getSize() < account.getMaximumAutoDownloadMessageSize()) { localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); - } - else - { + } else { // Set a flag indicating that the message has been partially downloaded and // is ready for view. localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true); } } - } - else - { + } else { /* * We have a structure to deal with, from which * we can pull down the parts we want to actually store. @@ -1988,8 +1664,7 @@ public class MessagingController implements Runnable /* * Now download the parts we're interested in storing. */ - for (Part part : viewables) - { + for (Part part : viewables) { remoteFolder.fetchPart(message, part, null); } // Store the updated message locally @@ -2008,19 +1683,16 @@ public class MessagingController implements Runnable // Update the listener with what we've found progress.incrementAndGet(); Message localMessage = localFolder.getMessage(message.getUid()); - for (MessagingListener l : getListeners()) - { + for (MessagingListener l : getListeners()) { l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage); l.synchronizeMailboxProgress(account, folder, progress.get(), todo); - if (!localMessage.isSet(Flag.SEEN)) - { + if (!localMessage.isSet(Flag.SEEN)) { l.synchronizeMailboxNewMessage(account, folder, localMessage); } } // Send a notification of this message - if (shouldNotifyForMessage(account, localFolder, message)) - { + if (shouldNotifyForMessage(account, localFolder, message)) { newMessages.incrementAndGet(); notifyAccount(mApplication, account, message, unreadBeforeStart, newMessages); } @@ -2036,12 +1708,10 @@ public class MessagingController implements Runnable ArrayList syncFlagMessages, final AtomicInteger progress, final int todo - ) throws MessagingException - { + ) throws MessagingException { final String folder = remoteFolder.getName(); - if (remoteFolder.supportsFetchingFlags()) - { + if (remoteFolder.supportsFetchingFlags()) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "SYNC: About to sync flags for " + syncFlagMessages.size() + " remote messages for folder " + folder); @@ -2050,67 +1720,49 @@ public class MessagingController implements Runnable fp.add(FetchProfile.Item.FLAGS); List undeletedMessages = new LinkedList(); - for (Message message : syncFlagMessages) - { - if (!message.isSet(Flag.DELETED)) - { + for (Message message : syncFlagMessages) { + if (!message.isSet(Flag.DELETED)) { undeletedMessages.add(message); } } remoteFolder.fetch(undeletedMessages.toArray(EMPTY_MESSAGE_ARRAY), fp, null); - for (Message remoteMessage : syncFlagMessages) - { + for (Message remoteMessage : syncFlagMessages) { Message localMessage = localFolder.getMessage(remoteMessage.getUid()); boolean messageChanged = syncFlags(localMessage, remoteMessage); - if (messageChanged) - { - if (localMessage.isSet(Flag.DELETED) || isMessageSuppressed(account, folder, localMessage)) - { - for (MessagingListener l : getListeners()) - { + if (messageChanged) { + if (localMessage.isSet(Flag.DELETED) || isMessageSuppressed(account, folder, localMessage)) { + for (MessagingListener l : getListeners()) { l.synchronizeMailboxRemovedMessage(account, folder, localMessage); } - } - else - { - for (MessagingListener l : getListeners()) - { + } else { + for (MessagingListener l : getListeners()) { l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage); } } } progress.incrementAndGet(); - for (MessagingListener l : getListeners()) - { + for (MessagingListener l : getListeners()) { l.synchronizeMailboxProgress(account, folder, progress.get(), todo); } } } } - private boolean syncFlags(Message localMessage, Message remoteMessage) throws MessagingException - { + private boolean syncFlags(Message localMessage, Message remoteMessage) throws MessagingException { boolean messageChanged = false; - if (localMessage == null || localMessage.isSet(Flag.DELETED)) - { + if (localMessage == null || localMessage.isSet(Flag.DELETED)) { return false; } - if (remoteMessage.isSet(Flag.DELETED)) - { - if (localMessage.getFolder().getAccount().syncRemoteDeletions()) - { + if (remoteMessage.isSet(Flag.DELETED)) { + if (localMessage.getFolder().getAccount().syncRemoteDeletions()) { localMessage.setFlag(Flag.DELETED, true); messageChanged = true; } - } - else - { - for (Flag flag : new Flag[] { Flag.SEEN, Flag.FLAGGED, Flag.ANSWERED }) - { - if (remoteMessage.isSet(flag) != localMessage.isSet(flag)) - { + } else { + for (Flag flag : new Flag[] { Flag.SEEN, Flag.FLAGGED, Flag.ANSWERED }) { + if (remoteMessage.isSet(flag) != localMessage.isSet(flag)) { localMessage.setFlag(flag, remoteMessage.isSet(flag)); messageChanged = true; } @@ -2118,55 +1770,39 @@ public class MessagingController implements Runnable } return messageChanged; } - private String getRootCauseMessage(Throwable t) - { + private String getRootCauseMessage(Throwable t) { Throwable rootCause = t; Throwable nextCause = rootCause; - do - { + do { nextCause = rootCause.getCause(); - if (nextCause != null) - { + if (nextCause != null) { rootCause = nextCause; } - } - while (nextCause != null); + } while (nextCause != null); return rootCause.getMessage(); } - private void queuePendingCommand(Account account, PendingCommand command) - { - try - { + private void queuePendingCommand(Account account, PendingCommand command) { + try { LocalStore localStore = account.getLocalStore(); localStore.addPendingCommand(command); - } - catch (Exception e) - { + } catch (Exception e) { addErrorMessage(account, null, e); throw new RuntimeException("Unable to enqueue pending command", e); } } - private void processPendingCommands(final Account account) - { - putBackground("processPendingCommands", null, new Runnable() - { + private void processPendingCommands(final Account account) { + putBackground("processPendingCommands", null, new Runnable() { @Override - public void run() - { - try - { + public void run() { + try { processPendingCommandsSynchronous(account); - } - catch (UnavailableStorageException e) - { + } catch (UnavailableStorageException e) { Log.i(K9.LOG_TAG, "Failed to process pending command because storage is not available - trying again later."); throw new UnavailableAccountException(e); - } - catch (MessagingException me) - { + } catch (MessagingException me) { Log.e(K9.LOG_TAG, "processPendingCommands", me); addErrorMessage(account, null, me); @@ -2180,37 +1816,31 @@ public class MessagingController implements Runnable }); } - private void processPendingCommandsSynchronous(Account account) throws MessagingException - { + private void processPendingCommandsSynchronous(Account account) throws MessagingException { LocalStore localStore = account.getLocalStore(); ArrayList commands = localStore.getPendingCommands(); int progress = 0; int todo = commands.size(); - if (todo == 0) - { + if (todo == 0) { return; } - for (MessagingListener l : getListeners()) - { + for (MessagingListener l : getListeners()) { l.pendingCommandsProcessing(account); l.synchronizeMailboxProgress(account, null, progress, todo); } PendingCommand processingCommand = null; - try - { - for (PendingCommand command : commands) - { + try { + for (PendingCommand command : commands) { processingCommand = command; if (K9.DEBUG) Log.d(K9.LOG_TAG, "Processing pending command '" + command + "'"); String[] components = command.command.split("\\."); String commandTitle = components[components.length - 1]; - for (MessagingListener l : getListeners()) - { + for (MessagingListener l : getListeners()) { l.pendingCommandStarted(account, commandTitle); } /* @@ -2218,78 +1848,49 @@ public class MessagingController implements Runnable * most likely due to a server or IO error and it must be retried before any * other command processes. This maintains the order of the commands. */ - try - { - if (PENDING_COMMAND_APPEND.equals(command.command)) - { + try { + if (PENDING_COMMAND_APPEND.equals(command.command)) { processPendingAppend(command, account); - } - else if (PENDING_COMMAND_SET_FLAG_BULK.equals(command.command)) - { + } else if (PENDING_COMMAND_SET_FLAG_BULK.equals(command.command)) { processPendingSetFlag(command, account); - } - else if (PENDING_COMMAND_SET_FLAG.equals(command.command)) - { + } else if (PENDING_COMMAND_SET_FLAG.equals(command.command)) { processPendingSetFlagOld(command, account); - } - else if (PENDING_COMMAND_MARK_ALL_AS_READ.equals(command.command)) - { + } else if (PENDING_COMMAND_MARK_ALL_AS_READ.equals(command.command)) { processPendingMarkAllAsRead(command, account); - } - else if (PENDING_COMMAND_MOVE_OR_COPY_BULK.equals(command.command)) - { + } else if (PENDING_COMMAND_MOVE_OR_COPY_BULK.equals(command.command)) { processPendingMoveOrCopy(command, account); - } - else if (PENDING_COMMAND_MOVE_OR_COPY.equals(command.command)) - { + } else if (PENDING_COMMAND_MOVE_OR_COPY.equals(command.command)) { processPendingMoveOrCopyOld(command, account); - } - else if (PENDING_COMMAND_EMPTY_TRASH.equals(command.command)) - { + } else if (PENDING_COMMAND_EMPTY_TRASH.equals(command.command)) { processPendingEmptyTrash(command, account); - } - else if (PENDING_COMMAND_EXPUNGE.equals(command.command)) - { + } else if (PENDING_COMMAND_EXPUNGE.equals(command.command)) { processPendingExpunge(command, account); } localStore.removePendingCommand(command); if (K9.DEBUG) Log.d(K9.LOG_TAG, "Done processing pending command '" + command + "'"); - } - catch (MessagingException me) - { - if (me.isPermanentFailure()) - { + } catch (MessagingException me) { + if (me.isPermanentFailure()) { addErrorMessage(account, null, me); Log.e(K9.LOG_TAG, "Failure of command '" + command + "' was permanent, removing command from queue"); localStore.removePendingCommand(processingCommand); - } - else - { + } else { throw me; } - } - finally - { + } finally { progress++; - for (MessagingListener l : getListeners()) - { + for (MessagingListener l : getListeners()) { l.synchronizeMailboxProgress(account, null, progress, todo); l.pendingCommandCompleted(account, commandTitle); } } } - } - catch (MessagingException me) - { + } catch (MessagingException me) { addErrorMessage(account, null, me); Log.e(K9.LOG_TAG, "Could not process command '" + processingCommand + "'", me); throw me; - } - finally - { - for (MessagingListener l : getListeners()) - { + } finally { + for (MessagingListener l : getListeners()) { l.pendingCommandsFinished(account); } } @@ -2308,18 +1909,15 @@ public class MessagingController implements Runnable * @throws MessagingException */ private void processPendingAppend(PendingCommand command, Account account) - throws MessagingException - { + throws MessagingException { Folder remoteFolder = null; LocalFolder localFolder = null; - try - { + try { String folder = command.arguments[0]; String uid = command.arguments[1]; - if (account.getErrorFolderName().equals(folder)) - { + if (account.getErrorFolderName().equals(folder)) { return; } @@ -2327,56 +1925,45 @@ public class MessagingController implements Runnable localFolder = localStore.getFolder(folder); LocalMessage localMessage = (LocalMessage) localFolder.getMessage(uid); - if (localMessage == null) - { + if (localMessage == null) { return; } Store remoteStore = account.getRemoteStore(); remoteFolder = remoteStore.getFolder(folder); - if (!remoteFolder.exists()) - { - if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) - { + if (!remoteFolder.exists()) { + if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return; } } remoteFolder.open(OpenMode.READ_WRITE); - if (remoteFolder.getMode() != OpenMode.READ_WRITE) - { + if (remoteFolder.getMode() != OpenMode.READ_WRITE) { return; } Message remoteMessage = null; - if (!localMessage.getUid().startsWith(K9.LOCAL_UID_PREFIX)) - { + if (!localMessage.getUid().startsWith(K9.LOCAL_UID_PREFIX)) { remoteMessage = remoteFolder.getMessage(localMessage.getUid()); } - if (remoteMessage == null) - { - if (localMessage.isSet(Flag.X_REMOTE_COPY_STARTED)) - { + if (remoteMessage == null) { + if (localMessage.isSet(Flag.X_REMOTE_COPY_STARTED)) { Log.w(K9.LOG_TAG, "Local message with uid " + localMessage.getUid() + " has flag " + Flag.X_REMOTE_COPY_STARTED + " already set, checking for remote message with " + " same message id"); String rUid = remoteFolder.getUidFromMessageId(localMessage); - if (rUid != null) - { + if (rUid != null) { Log.w(K9.LOG_TAG, "Local message has flag " + Flag.X_REMOTE_COPY_STARTED + " already set, and there is a remote message with " + " uid " + rUid + ", assuming message was already copied and aborting this copy"); String oldUid = localMessage.getUid(); localMessage.setUid(rUid); localFolder.changeUid(localMessage); - for (MessagingListener l : getListeners()) - { + for (MessagingListener l : getListeners()) { l.messageUidChanged(account, folder, oldUid, localMessage.getUid()); } return; - } - else - { + } else { Log.w(K9.LOG_TAG, "No remote message with message-id found, proceeding with append"); } } @@ -2393,13 +1980,10 @@ public class MessagingController implements Runnable remoteFolder.appendMessages(new Message[] { localMessage }); localFolder.changeUid(localMessage); - for (MessagingListener l : getListeners()) - { + for (MessagingListener l : getListeners()) { l.messageUidChanged(account, folder, oldUid, localMessage.getUid()); } - } - else - { + } else { /* * If the remote message exists we need to determine which copy to keep. */ @@ -2411,17 +1995,14 @@ public class MessagingController implements Runnable remoteFolder.fetch(new Message[] { remoteMessage }, fp, null); Date localDate = localMessage.getInternalDate(); Date remoteDate = remoteMessage.getInternalDate(); - if (remoteDate != null && remoteDate.compareTo(localDate) > 0) - { + if (remoteDate != null && remoteDate.compareTo(localDate) > 0) { /* * If the remote message is newer than ours we'll just * delete ours and move on. A sync will get the server message * if we need to be able to see it. */ localMessage.destroy(); - } - else - { + } else { /* * Otherwise we'll upload our message and then delete the remote message. */ @@ -2435,31 +2016,24 @@ public class MessagingController implements Runnable remoteFolder.appendMessages(new Message[] { localMessage }); localFolder.changeUid(localMessage); - for (MessagingListener l : getListeners()) - { + for (MessagingListener l : getListeners()) { l.messageUidChanged(account, folder, oldUid, localMessage.getUid()); } - if (remoteDate != null) - { + if (remoteDate != null) { remoteMessage.setFlag(Flag.DELETED, true); - if (Account.EXPUNGE_IMMEDIATELY.equals(account.getExpungePolicy())) - { + if (Account.EXPUNGE_IMMEDIATELY.equals(account.getExpungePolicy())) { remoteFolder.expunge(); } } } } - } - finally - { + } finally { closeFolder(remoteFolder); closeFolder(localFolder); } } - private void queueMoveOrCopy(Account account, String srcFolder, String destFolder, boolean isCopy, String uids[]) - { - if (account.getErrorFolderName().equals(srcFolder)) - { + private void queueMoveOrCopy(Account account, String srcFolder, String destFolder, boolean isCopy, String uids[]) { + if (account.getErrorFolderName().equals(srcFolder)) { return; } PendingCommand command = new PendingCommand(); @@ -2481,15 +2055,12 @@ public class MessagingController implements Runnable * @throws MessagingException */ private void processPendingMoveOrCopy(PendingCommand command, Account account) - throws MessagingException - { + throws MessagingException { Folder remoteSrcFolder = null; Folder remoteDestFolder = null; - try - { + try { String srcFolder = command.arguments[0]; - if (account.getErrorFolderName().equals(srcFolder)) - { + if (account.getErrorFolderName().equals(srcFolder)) { return; } String destFolder = command.arguments[1]; @@ -2498,28 +2069,23 @@ public class MessagingController implements Runnable remoteSrcFolder = remoteStore.getFolder(srcFolder); List messages = new ArrayList(); - for (int i = 3; i < command.arguments.length; i++) - { + for (int i = 3; i < command.arguments.length; i++) { String uid = command.arguments[i]; - if (!uid.startsWith(K9.LOCAL_UID_PREFIX)) - { + if (!uid.startsWith(K9.LOCAL_UID_PREFIX)) { messages.add(remoteSrcFolder.getMessage(uid)); } } boolean isCopy = false; - if (isCopyS != null) - { + if (isCopyS != null) { isCopy = Boolean.parseBoolean(isCopyS); } - if (!remoteSrcFolder.exists()) - { + if (!remoteSrcFolder.exists()) { throw new MessagingException("processingPendingMoveOrCopy: remoteFolder " + srcFolder + " does not exist", true); } remoteSrcFolder.open(OpenMode.READ_WRITE); - if (remoteSrcFolder.getMode() != OpenMode.READ_WRITE) - { + if (remoteSrcFolder.getMode() != OpenMode.READ_WRITE) { throw new MessagingException("processingPendingMoveOrCopy: could not open remoteSrcFolder " + srcFolder + " read/write", true); } @@ -2527,41 +2093,31 @@ public class MessagingController implements Runnable Log.d(K9.LOG_TAG, "processingPendingMoveOrCopy: source folder = " + srcFolder + ", " + messages.size() + " messages, destination folder = " + destFolder + ", isCopy = " + isCopy); - if (!isCopy && destFolder.equals(account.getTrashFolderName())) - { + if (!isCopy && destFolder.equals(account.getTrashFolderName())) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "processingPendingMoveOrCopy doing special case for deleting message"); String destFolderName = destFolder; - if (K9.FOLDER_NONE.equals(destFolderName)) - { + if (K9.FOLDER_NONE.equals(destFolderName)) { destFolderName = null; } remoteSrcFolder.delete(messages.toArray(EMPTY_MESSAGE_ARRAY), destFolderName); - } - else - { + } else { remoteDestFolder = remoteStore.getFolder(destFolder); - if (isCopy) - { + if (isCopy) { remoteSrcFolder.copyMessages(messages.toArray(EMPTY_MESSAGE_ARRAY), remoteDestFolder); - } - else - { + } else { remoteSrcFolder.moveMessages(messages.toArray(EMPTY_MESSAGE_ARRAY), remoteDestFolder); } } - if (!isCopy && Account.EXPUNGE_IMMEDIATELY.equals(account.getExpungePolicy())) - { + if (!isCopy && Account.EXPUNGE_IMMEDIATELY.equals(account.getExpungePolicy())) { if (K9.DEBUG) Log.i(K9.LOG_TAG, "processingPendingMoveOrCopy expunging folder " + account.getDescription() + ":" + srcFolder); remoteSrcFolder.expunge(); } - } - finally - { + } finally { closeFolder(remoteSrcFolder); closeFolder(remoteDestFolder); } @@ -2569,13 +2125,10 @@ public class MessagingController implements Runnable } - private void queueSetFlag(final Account account, final String folderName, final String newState, final String flag, final String[] uids) - { - putBackground("queueSetFlag " + account.getDescription() + ":" + folderName, null, new Runnable() - { + private void queueSetFlag(final Account account, final String folderName, final String newState, final String flag, final String[] uids) { + putBackground("queueSetFlag " + account.getDescription() + ":" + folderName, null, new Runnable() { @Override - public void run() - { + public void run() { PendingCommand command = new PendingCommand(); command.command = PENDING_COMMAND_SET_FLAG_BULK; int length = 3 + uids.length; @@ -2596,12 +2149,10 @@ public class MessagingController implements Runnable * @param account */ private void processPendingSetFlag(PendingCommand command, Account account) - throws MessagingException - { + throws MessagingException { String folder = command.arguments[0]; - if (account.getErrorFolderName().equals(folder)) - { + if (account.getErrorFolderName().equals(folder)) { return; } @@ -2618,36 +2169,28 @@ public class MessagingController implements Runnable * unnecessary connections to POP3 servers. */ // TODO: This should actually call a supportsSettingFlag(flag) method. - (!remoteFolder.supportsFetchingFlags() && !Flag.DELETED.equals(flag))) - { + (!remoteFolder.supportsFetchingFlags() && !Flag.DELETED.equals(flag))) { return; } - try - { + try { remoteFolder.open(OpenMode.READ_WRITE); - if (remoteFolder.getMode() != OpenMode.READ_WRITE) - { + if (remoteFolder.getMode() != OpenMode.READ_WRITE) { return; } List messages = new ArrayList(); - for (int i = 3; i < command.arguments.length; i++) - { + for (int i = 3; i < command.arguments.length; i++) { String uid = command.arguments[i]; - if (!uid.startsWith(K9.LOCAL_UID_PREFIX)) - { + if (!uid.startsWith(K9.LOCAL_UID_PREFIX)) { messages.add(remoteFolder.getMessage(uid)); } } - if (messages.size() == 0) - { + if (messages.size() == 0) { return; } remoteFolder.setFlags(messages.toArray(EMPTY_MESSAGE_ARRAY), new Flag[] { flag }, newState); - } - finally - { + } finally { closeFolder(remoteFolder); } } @@ -2655,13 +2198,11 @@ public class MessagingController implements Runnable // TODO: This method is obsolete and is only for transition from K-9 2.0 to K-9 2.1 // Eventually, it should be removed private void processPendingSetFlagOld(PendingCommand command, Account account) - throws MessagingException - { + throws MessagingException { String folder = command.arguments[0]; String uid = command.arguments[1]; - if (account.getErrorFolderName().equals(folder)) - { + if (account.getErrorFolderName().equals(folder)) { return; } if (K9.DEBUG) @@ -2671,42 +2212,32 @@ public class MessagingController implements Runnable Flag flag = Flag.valueOf(command.arguments[3]); Folder remoteFolder = null; - try - { + try { Store remoteStore = account.getRemoteStore(); remoteFolder = remoteStore.getFolder(folder); - if (!remoteFolder.exists()) - { + if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE); - if (remoteFolder.getMode() != OpenMode.READ_WRITE) - { + if (remoteFolder.getMode() != OpenMode.READ_WRITE) { return; } Message remoteMessage = null; - if (!uid.startsWith(K9.LOCAL_UID_PREFIX)) - { + if (!uid.startsWith(K9.LOCAL_UID_PREFIX)) { remoteMessage = remoteFolder.getMessage(uid); } - if (remoteMessage == null) - { + if (remoteMessage == null) { return; } remoteMessage.setFlag(flag, newState); - } - finally - { + } finally { closeFolder(remoteFolder); } } - private void queueExpunge(final Account account, final String folderName) - { - putBackground("queueExpunge " + account.getDescription() + ":" + folderName, null, new Runnable() - { + private void queueExpunge(final Account account, final String folderName) { + putBackground("queueExpunge " + account.getDescription() + ":" + folderName, null, new Runnable() { @Override - public void run() - { + public void run() { PendingCommand command = new PendingCommand(); command.command = PENDING_COMMAND_EXPUNGE; @@ -2719,12 +2250,10 @@ public class MessagingController implements Runnable }); } private void processPendingExpunge(PendingCommand command, Account account) - throws MessagingException - { + throws MessagingException { String folder = command.arguments[0]; - if (account.getErrorFolderName().equals(folder)) - { + if (account.getErrorFolderName().equals(folder)) { return; } if (K9.DEBUG) @@ -2732,23 +2261,18 @@ public class MessagingController implements Runnable Store remoteStore = account.getRemoteStore(); Folder remoteFolder = remoteStore.getFolder(folder); - try - { - if (!remoteFolder.exists()) - { + try { + if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE); - if (remoteFolder.getMode() != OpenMode.READ_WRITE) - { + if (remoteFolder.getMode() != OpenMode.READ_WRITE) { return; } remoteFolder.expunge(); if (K9.DEBUG) Log.d(K9.LOG_TAG, "processPendingExpunge: complete for folder = " + folder); - } - finally - { + } finally { closeFolder(remoteFolder); } } @@ -2757,21 +2281,18 @@ public class MessagingController implements Runnable // TODO: This method is obsolete and is only for transition from K-9 2.0 to K-9 2.1 // Eventually, it should be removed private void processPendingMoveOrCopyOld(PendingCommand command, Account account) - throws MessagingException - { + throws MessagingException { String srcFolder = command.arguments[0]; String uid = command.arguments[1]; String destFolder = command.arguments[2]; String isCopyS = command.arguments[3]; boolean isCopy = false; - if (isCopyS != null) - { + if (isCopyS != null) { isCopy = Boolean.parseBoolean(isCopyS); } - if (account.getErrorFolderName().equals(srcFolder)) - { + if (account.getErrorFolderName().equals(srcFolder)) { return; } @@ -2779,23 +2300,19 @@ public class MessagingController implements Runnable Folder remoteSrcFolder = remoteStore.getFolder(srcFolder); Folder remoteDestFolder = remoteStore.getFolder(destFolder); - if (!remoteSrcFolder.exists()) - { + if (!remoteSrcFolder.exists()) { throw new MessagingException("processPendingMoveOrCopyOld: remoteFolder " + srcFolder + " does not exist", true); } remoteSrcFolder.open(OpenMode.READ_WRITE); - if (remoteSrcFolder.getMode() != OpenMode.READ_WRITE) - { + if (remoteSrcFolder.getMode() != OpenMode.READ_WRITE) { throw new MessagingException("processPendingMoveOrCopyOld: could not open remoteSrcFolder " + srcFolder + " read/write", true); } Message remoteMessage = null; - if (!uid.startsWith(K9.LOCAL_UID_PREFIX)) - { + if (!uid.startsWith(K9.LOCAL_UID_PREFIX)) { remoteMessage = remoteSrcFolder.getMessage(uid); } - if (remoteMessage == null) - { + if (remoteMessage == null) { throw new MessagingException("processPendingMoveOrCopyOld: remoteMessage " + uid + " does not exist", true); } @@ -2803,8 +2320,7 @@ public class MessagingController implements Runnable Log.d(K9.LOG_TAG, "processPendingMoveOrCopyOld: source folder = " + srcFolder + ", uid = " + uid + ", destination folder = " + destFolder + ", isCopy = " + isCopy); - if (!isCopy && destFolder.equals(account.getTrashFolderName())) - { + if (!isCopy && destFolder.equals(account.getTrashFolderName())) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "processPendingMoveOrCopyOld doing special case for deleting message"); @@ -2814,79 +2330,62 @@ public class MessagingController implements Runnable } remoteDestFolder.open(OpenMode.READ_WRITE); - if (remoteDestFolder.getMode() != OpenMode.READ_WRITE) - { + if (remoteDestFolder.getMode() != OpenMode.READ_WRITE) { throw new MessagingException("processPendingMoveOrCopyOld: could not open remoteDestFolder " + srcFolder + " read/write", true); } - if (isCopy) - { + if (isCopy) { remoteSrcFolder.copyMessages(new Message[] { remoteMessage }, remoteDestFolder); - } - else - { + } else { remoteSrcFolder.moveMessages(new Message[] { remoteMessage }, remoteDestFolder); } remoteSrcFolder.close(); remoteDestFolder.close(); } - private void processPendingMarkAllAsRead(PendingCommand command, Account account) throws MessagingException - { + private void processPendingMarkAllAsRead(PendingCommand command, Account account) throws MessagingException { String folder = command.arguments[0]; Folder remoteFolder = null; LocalFolder localFolder = null; - try - { + try { Store localStore = account.getLocalStore(); localFolder = (LocalFolder) localStore.getFolder(folder); localFolder.open(OpenMode.READ_WRITE); Message[] messages = localFolder.getMessages(null, false); - for (Message message : messages) - { - if (!message.isSet(Flag.SEEN)) - { + for (Message message : messages) { + if (!message.isSet(Flag.SEEN)) { message.setFlag(Flag.SEEN, true); - for (MessagingListener l : getListeners()) - { + for (MessagingListener l : getListeners()) { l.listLocalMessagesUpdateMessage(account, folder, message); } } } localFolder.setUnreadMessageCount(0); - for (MessagingListener l : getListeners()) - { + for (MessagingListener l : getListeners()) { l.folderStatusChanged(account, folder, 0); } - if (account.getErrorFolderName().equals(folder)) - { + if (account.getErrorFolderName().equals(folder)) { return; } Store remoteStore = account.getRemoteStore(); remoteFolder = remoteStore.getFolder(folder); - if (!remoteFolder.exists()) - { + if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE); - if (remoteFolder.getMode() != OpenMode.READ_WRITE) - { + if (remoteFolder.getMode() != OpenMode.READ_WRITE) { return; } remoteFolder.setFlags(new Flag[] {Flag.SEEN}, true); remoteFolder.close(); - } - catch (UnsupportedOperationException uoe) - { + } catch (UnsupportedOperationException uoe) { Log.w(K9.LOG_TAG, "Could not mark all server-side as read because store doesn't support operation", uoe); - } - finally - { + } finally { closeFolder(localFolder); closeFolder(remoteFolder); } @@ -2894,16 +2393,12 @@ public class MessagingController implements Runnable static long uidfill = 0; static AtomicBoolean loopCatch = new AtomicBoolean(); - public void addErrorMessage(Account account, String subject, Throwable t) - { - if (!loopCatch.compareAndSet(false, true)) - { + public void addErrorMessage(Account account, String subject, Throwable t) { + if (!loopCatch.compareAndSet(false, true)) { return; } - try - { - if (t == null) - { + try { + if (t == null) { return; } @@ -2912,37 +2407,27 @@ public class MessagingController implements Runnable t.printStackTrace(ps); ps.close(); - if (subject == null) - { + if (subject == null) { subject = getRootCauseMessage(t); } addErrorMessage(account, subject, baos.toString()); - } - catch (Throwable it) - { + } catch (Throwable it) { Log.e(K9.LOG_TAG, "Could not save error message to " + account.getErrorFolderName(), it); - } - finally - { + } finally { loopCatch.set(false); } } - public void addErrorMessage(Account account, String subject, String body) - { - if (!K9.ENABLE_ERROR_FOLDER) - { + public void addErrorMessage(Account account, String subject, String body) { + if (!K9.ENABLE_ERROR_FOLDER) { return; } - if (!loopCatch.compareAndSet(false, true)) - { + if (!loopCatch.compareAndSet(false, true)) { return; } - try - { - if (body == null || body.length() < 1) - { + try { + if (body == null || body.length() < 1) { return; } @@ -2967,21 +2452,16 @@ public class MessagingController implements Runnable localFolder.clearMessagesOlderThan(nowTime - (15 * 60 * 1000)); - } - catch (Throwable it) - { + } catch (Throwable it) { Log.e(K9.LOG_TAG, "Could not save error message to " + account.getErrorFolderName(), it); - } - finally - { + } finally { loopCatch.set(false); } } - public void markAllMessagesRead(final Account account, final String folder) - { + public void markAllMessagesRead(final Account account, final String folder) { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Marking all messages in " + account.getDescription() + ":" + folder + " as read"); @@ -2997,17 +2477,13 @@ public class MessagingController implements Runnable public void setFlag( final Message[] messages, final Flag flag, - final boolean newState) - { - actOnMessages(messages, new MessageActor() - { + final boolean newState) { + actOnMessages(messages, new MessageActor() { @Override public void act(final Account account, final Folder folder, - final List messages) - { + final List messages) { String[] uids = new String[messages.size()]; - for (int i = 0; i < messages.size(); i++) - { + for (int i = 0; i < messages.size(); i++) { uids[i] = messages.get(i).getUid(); } setFlag(account, folder.getName(), uids, flag, newState); @@ -3022,29 +2498,24 @@ public class MessagingController implements Runnable final String folderName, final String[] uids, final Flag flag, - final boolean newState) - { + final boolean newState) { // TODO: put this into the background, but right now that causes odd behavior // because the FolderMessageList doesn't have its own cache of the flag states Folder localFolder = null; - try - { + try { Store localStore = account.getLocalStore(); localFolder = localStore.getFolder(folderName); localFolder.open(OpenMode.READ_WRITE); ArrayList messages = new ArrayList(); - for (String uid : uids) - { + for (String uid : uids) { // Allows for re-allowing sending of messages that could not be sent if (flag == Flag.FLAGGED && !newState && uid != null - && account.getOutboxFolderName().equals(folderName)) - { + && account.getOutboxFolderName().equals(folderName)) { sendCount.remove(uid); } Message msg = localFolder.getMessage(uid); - if (msg != null) - { + if (msg != null) { messages.add(msg); } } @@ -3052,66 +2523,51 @@ public class MessagingController implements Runnable localFolder.setFlags(messages.toArray(EMPTY_MESSAGE_ARRAY), new Flag[] {flag}, newState); - for (MessagingListener l : getListeners()) - { + for (MessagingListener l : getListeners()) { l.folderStatusChanged(account, folderName, localFolder.getUnreadMessageCount()); } - if (account.getErrorFolderName().equals(folderName)) - { + if (account.getErrorFolderName().equals(folderName)) { return; } queueSetFlag(account, folderName, Boolean.toString(newState), flag.toString(), uids); processPendingCommands(account); - } - catch (MessagingException me) - { + } catch (MessagingException me) { addErrorMessage(account, null, me); throw new RuntimeException(me); - } - finally - { + } finally { closeFolder(localFolder); } }//setMesssageFlag - public void clearAllPending(final Account account) - { - try - { + public void clearAllPending(final Account account) { + try { Log.w(K9.LOG_TAG, "Clearing pending commands!"); LocalStore localStore = account.getLocalStore(); localStore.removePendingCommands(); - } - catch (MessagingException me) - { + } catch (MessagingException me) { Log.e(K9.LOG_TAG, "Unable to clear pending command", me); addErrorMessage(account, null, me); } } public void loadMessageForViewRemote(final Account account, final String folder, - final String uid, final MessagingListener listener) - { - put("loadMessageForViewRemote", listener, new Runnable() - { + final String uid, final MessagingListener listener) { + put("loadMessageForViewRemote", listener, new Runnable() { @Override - public void run() - { + public void run() { Folder remoteFolder = null; LocalFolder localFolder = null; - try - { + try { LocalStore localStore = account.getLocalStore(); localFolder = localStore.getFolder(folder); localFolder.open(OpenMode.READ_WRITE); Message message = localFolder.getMessage(uid); - if (message.isSet(Flag.X_DOWNLOADED_FULL)) - { + if (message.isSet(Flag.X_DOWNLOADED_FULL)) { /* * If the message has been synchronized since we were called we'll * just hand it back cause it's ready to go. @@ -3120,9 +2576,7 @@ public class MessagingController implements Runnable fp.add(FetchProfile.Item.ENVELOPE); fp.add(FetchProfile.Item.BODY); localFolder.fetch(new Message[] { message }, fp, null); - } - else - { + } else { /* * At this point the message is not available, so we need to download it * fully if possible. @@ -3149,31 +2603,23 @@ public class MessagingController implements Runnable } // now that we have the full message, refresh the headers - for (MessagingListener l : getListeners(listener)) - { + for (MessagingListener l : getListeners(listener)) { l.loadMessageForViewHeadersAvailable(account, folder, uid, message); } - for (MessagingListener l : getListeners(listener)) - { + for (MessagingListener l : getListeners(listener)) { l.loadMessageForViewBodyAvailable(account, folder, uid, message); } - for (MessagingListener l : getListeners(listener)) - { + for (MessagingListener l : getListeners(listener)) { l.loadMessageForViewFinished(account, folder, uid, message); } - } - catch (Exception e) - { - for (MessagingListener l : getListeners(listener)) - { + } catch (Exception e) { + for (MessagingListener l : getListeners(listener)) { l.loadMessageForViewFailed(account, folder, uid, e); } addErrorMessage(account, null, e); - } - finally - { + } finally { closeFolder(remoteFolder); closeFolder(localFolder); } @@ -3182,65 +2628,51 @@ public class MessagingController implements Runnable } public void loadMessageForView(final Account account, final String folder, final String uid, - final MessagingListener listener) - { - for (MessagingListener l : getListeners(listener)) - { + final MessagingListener listener) { + for (MessagingListener l : getListeners(listener)) { l.loadMessageForViewStarted(account, folder, uid); } - threadPool.execute(new Runnable() - { + threadPool.execute(new Runnable() { @Override - public void run() - { + public void run() { - try - { + try { LocalStore localStore = account.getLocalStore(); LocalFolder localFolder = localStore.getFolder(folder); localFolder.open(OpenMode.READ_WRITE); LocalMessage message = (LocalMessage)localFolder.getMessage(uid); - if (message==null - || message.getId()==0) - { + if (message == null + || message.getId() == 0) { throw new IllegalArgumentException("Message not found: folder=" + folder + ", uid=" + uid); } - if (!message.isSet(Flag.SEEN)) - { + if (!message.isSet(Flag.SEEN)) { message.setFlag(Flag.SEEN, true); setFlag(new Message[] { message }, Flag.SEEN, true); } - for (MessagingListener l : getListeners(listener)) - { + for (MessagingListener l : getListeners(listener)) { l.loadMessageForViewHeadersAvailable(account, folder, uid, message); } FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.ENVELOPE); fp.add(FetchProfile.Item.BODY); - localFolder.fetch(new Message[] - { + localFolder.fetch(new Message[] { message }, fp, null); localFolder.close(); - for (MessagingListener l : getListeners(listener)) - { + for (MessagingListener l : getListeners(listener)) { l.loadMessageForViewBodyAvailable(account, folder, uid, message); } - for (MessagingListener l : getListeners(listener)) - { + for (MessagingListener l : getListeners(listener)) { l.loadMessageForViewFinished(account, folder, uid, message); } - } - catch (Exception e) - { - for (MessagingListener l : getListeners(listener)) - { + } catch (Exception e) { + for (MessagingListener l : getListeners(listener)) { l.loadMessageForViewFailed(account, folder, uid, e); } addErrorMessage(account, null, e); @@ -3262,31 +2694,25 @@ public class MessagingController implements Runnable final Message message, final Part part, final Object tag, - final MessagingListener listener) - { + final MessagingListener listener) { /* * Check if the attachment has already been downloaded. If it has there's no reason to * download it, so we just tell the listener that it's ready to go. */ - if (part.getBody() != null) - { - for (MessagingListener l : getListeners()) - { + if (part.getBody() != null) { + for (MessagingListener l : getListeners()) { l.loadAttachmentStarted(account, message, part, tag, false); } - if (listener != null) - { + if (listener != null) { listener.loadAttachmentStarted(account, message, part, tag, false); } - for (MessagingListener l : getListeners()) - { + for (MessagingListener l : getListeners()) { l.loadAttachmentFinished(account, message, part, tag); } - if (listener != null) - { + if (listener != null) { listener.loadAttachmentFinished(account, message, part, tag); } return; @@ -3294,31 +2720,25 @@ public class MessagingController implements Runnable - for (MessagingListener l : getListeners()) - { + for (MessagingListener l : getListeners()) { l.loadAttachmentStarted(account, message, part, tag, true); } - if (listener != null) - { + if (listener != null) { listener.loadAttachmentStarted(account, message, part, tag, false); } - put("loadAttachment", listener, new Runnable() - { + put("loadAttachment", listener, new Runnable() { @Override - public void run() - { + public void run() { Folder remoteFolder = null; LocalFolder localFolder = null; - try - { + try { LocalStore localStore = account.getLocalStore(); ArrayList viewables = new ArrayList(); ArrayList attachments = new ArrayList(); MimeUtility.collectParts(message, viewables, attachments); - for (Part attachment : attachments) - { + for (Part attachment : attachments) { attachment.setBody(null); } Store remoteStore = account.getRemoteStore(); @@ -3332,33 +2752,25 @@ public class MessagingController implements Runnable remoteFolder.fetchPart(remoteMessage, part, null); localFolder.updateMessage((LocalMessage)message); - for (MessagingListener l : getListeners()) - { + for (MessagingListener l : getListeners()) { l.loadAttachmentFinished(account, message, part, tag); } - if (listener != null) - { + if (listener != null) { listener.loadAttachmentFinished(account, message, part, tag); } - } - catch (MessagingException me) - { + } catch (MessagingException me) { if (K9.DEBUG) Log.v(K9.LOG_TAG, "Exception loading attachment", me); - for (MessagingListener l : getListeners()) - { + for (MessagingListener l : getListeners()) { l.loadAttachmentFailed(account, message, part, tag, me.getMessage()); } - if (listener != null) - { + if (listener != null) { listener.loadAttachmentFailed(account, message, part, tag, me.getMessage()); } addErrorMessage(account, null, me); - } - finally - { + } finally { closeFolder(localFolder); closeFolder(remoteFolder); } @@ -3375,10 +2787,8 @@ public class MessagingController implements Runnable */ public void sendMessage(final Account account, final Message message, - MessagingListener listener) - { - try - { + MessagingListener listener) { + try { LocalStore localStore = account.getLocalStore(); LocalFolder localFolder = localStore.getFolder(account.getOutboxFolderName()); localFolder.open(OpenMode.READ_WRITE); @@ -3387,9 +2797,7 @@ public class MessagingController implements Runnable localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); localFolder.close(); sendPendingMessages(account, listener); - } - catch (Exception e) - { + } catch (Exception e) { /* for (MessagingListener l : getListeners()) { @@ -3402,12 +2810,10 @@ public class MessagingController implements Runnable } - public void sendPendingMessages(MessagingListener listener) - { + public void sendPendingMessages(MessagingListener listener) { final Preferences prefs = Preferences.getPreferences(mApplication.getApplicationContext()); Account[] accounts = prefs.getAccounts(); - for (Account account : accounts) - { + for (Account account : accounts) { sendPendingMessages(account, listener); } } @@ -3419,29 +2825,21 @@ public class MessagingController implements Runnable * @param listener */ public void sendPendingMessages(final Account account, - MessagingListener listener) - { - putBackground("sendPendingMessages", listener, new Runnable() - { + MessagingListener listener) { + putBackground("sendPendingMessages", listener, new Runnable() { @Override - public void run() - { - if (!account.isAvailable(mApplication)) - { + public void run() { + if (!account.isAvailable(mApplication)) { throw new UnavailableAccountException(); } - if (messagesPendingSend(account)) - { + if (messagesPendingSend(account)) { notifyWhileSending(account); - try - { + try { sendPendingMessagesSynchronous(account); - } - finally - { + } finally { notifyWhileSendingDone(account); } } @@ -3449,26 +2847,21 @@ public class MessagingController implements Runnable }); } - private void cancelNotification(int id) - { + private void cancelNotification(int id) { NotificationManager notifMgr = (NotificationManager)mApplication.getSystemService(Context.NOTIFICATION_SERVICE); notifMgr.cancel(id); } - private void notifyWhileSendingDone(Account account) - { - if (account.isShowOngoing()) - { + private void notifyWhileSendingDone(Account account) { + if (account.isShowOngoing()) { cancelNotification(K9.FETCHING_EMAIL_NOTIFICATION - account.getAccountNumber()); } } - private void notifyWhileSending(Account account) - { - if (!account.isShowOngoing()) - { + private void notifyWhileSending(Account account) { + if (!account.isShowOngoing()) { return; } NotificationManager notifMgr = @@ -3481,16 +2874,14 @@ public class MessagingController implements Runnable account.getDescription() , pi); notif.flags = Notification.FLAG_ONGOING_EVENT; - if (K9.NOTIFICATION_LED_WHILE_SYNCING) - { + if (K9.NOTIFICATION_LED_WHILE_SYNCING) { configureNotification(notif, null, null, account.getNotificationSetting().getLedColor(), K9.NOTIFICATION_LED_BLINK_FAST, true); } notifMgr.notify(K9.FETCHING_EMAIL_NOTIFICATION - account.getAccountNumber(), notif); } - private void notifySendFailed(Account account, Exception lastFailure) - { + private void notifySendFailed(Account account, Exception lastFailure) { NotificationManager notifMgr = (NotificationManager)mApplication.getSystemService(Context.NOTIFICATION_SERVICE); Notification notif = new Notification(R.drawable.stat_notify_email_generic, mApplication.getString(R.string.send_failure_subject), System.currentTimeMillis()); @@ -3506,10 +2897,8 @@ public class MessagingController implements Runnable } - private void notifyFetchingMail(final Account account, final Folder folder) - { - if (account.isShowOngoing()) - { + private void notifyFetchingMail(final Account account, final Folder folder) { + if (account.isShowOngoing()) { final NotificationManager notifMgr = (NotificationManager)mApplication .getSystemService(Context.NOTIFICATION_SERVICE); Notification notif = new Notification(R.drawable.ic_menu_refresh, @@ -3521,47 +2910,36 @@ public class MessagingController implements Runnable + mApplication.getString(R.string.notification_bg_title_separator) + folder.getName(), pi); notif.flags = Notification.FLAG_ONGOING_EVENT; - if (K9.NOTIFICATION_LED_WHILE_SYNCING) - { + if (K9.NOTIFICATION_LED_WHILE_SYNCING) { configureNotification(notif, null, null, account.getNotificationSetting().getLedColor(), K9.NOTIFICATION_LED_BLINK_FAST, true); } notifMgr.notify(K9.FETCHING_EMAIL_NOTIFICATION - account.getAccountNumber(), notif); } } - private void notifyFetchingMailCancel (final Account account) - { - if (account.isShowOngoing()) - { + private void notifyFetchingMailCancel(final Account account) { + if (account.isShowOngoing()) { cancelNotification(K9.FETCHING_EMAIL_NOTIFICATION - account.getAccountNumber()); } } - public boolean messagesPendingSend(final Account account) - { + public boolean messagesPendingSend(final Account account) { Folder localFolder = null; - try - { + try { localFolder = account.getLocalStore().getFolder( account.getOutboxFolderName()); - if (!localFolder.exists()) - { + if (!localFolder.exists()) { return false; } localFolder.open(OpenMode.READ_WRITE); - if (localFolder.getMessageCount() > 0) - { + if (localFolder.getMessageCount() > 0) { return true; } - } - catch (Exception e) - { + } catch (Exception e) { Log.e(K9.LOG_TAG, "Exception while checking for unsent messages", e); - } - finally - { + } finally { closeFolder(localFolder); } return false; @@ -3571,21 +2949,17 @@ public class MessagingController implements Runnable * Attempt to send any messages that are sitting in the Outbox. * @param account */ - public void sendPendingMessagesSynchronous(final Account account) - { + public void sendPendingMessagesSynchronous(final Account account) { Folder localFolder = null; Exception lastFailure = null; - try - { + try { Store localStore = account.getLocalStore(); localFolder = localStore.getFolder( account.getOutboxFolderName()); - if (!localFolder.exists()) - { + if (!localFolder.exists()) { return; } - for (MessagingListener l : getListeners()) - { + for (MessagingListener l : getListeners()) { l.sendPendingMessagesStarted(account); } localFolder.open(OpenMode.READ_WRITE); @@ -3593,8 +2967,7 @@ public class MessagingController implements Runnable Message[] localMessages = localFolder.getMessages(null); int progress = 0; int todo = localMessages.length; - for (MessagingListener l : getListeners()) - { + for (MessagingListener l : getListeners()) { l.synchronizeMailboxProgress(account, account.getSentFolderName(), progress, todo); } /* @@ -3609,19 +2982,15 @@ public class MessagingController implements Runnable Log.i(K9.LOG_TAG, "Scanning folder '" + account.getOutboxFolderName() + "' (" + ((LocalFolder)localFolder).getId() + ") for messages to send"); Transport transport = Transport.getInstance(account); - for (Message message : localMessages) - { - if (message.isSet(Flag.DELETED)) - { + for (Message message : localMessages) { + if (message.isSet(Flag.DELETED)) { message.destroy(); continue; } - try - { + try { AtomicInteger count = new AtomicInteger(0); AtomicInteger oldCount = sendCount.putIfAbsent(message.getUid(), count); - if (oldCount != null) - { + if (oldCount != null) { count = oldCount; } @@ -3629,8 +2998,7 @@ public class MessagingController implements Runnable Log.i(K9.LOG_TAG, "Send count for message " + message.getUid() + " is " + count.get()); localFolder.fetch(new Message[] { message }, fp, null); - try - { + try { message.setFlag(Flag.X_SEND_IN_PROGRESS, true); if (K9.DEBUG) Log.i(K9.LOG_TAG, "Sending message with UID " + message.getUid()); @@ -3638,23 +3006,19 @@ public class MessagingController implements Runnable message.setFlag(Flag.X_SEND_IN_PROGRESS, false); message.setFlag(Flag.SEEN, true); progress++; - for (MessagingListener l : getListeners()) - { + for (MessagingListener l : getListeners()) { l.synchronizeMailboxProgress(account, account.getSentFolderName(), progress, todo); } - if (K9.FOLDER_NONE.equals(account.getSentFolderName())) - { + if (K9.FOLDER_NONE.equals(account.getSentFolderName())) { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Sent folder set to " + K9.FOLDER_NONE + ", deleting sent message"); message.setFlag(Flag.DELETED, true); - } - else - { - LocalFolder localSentFolder = (LocalFolder) localStore.getFolder( account.getSentFolderName()); + } else { + LocalFolder localSentFolder = (LocalFolder) localStore.getFolder(account.getSentFolderName()); if (K9.DEBUG) Log.i(K9.LOG_TAG, "Moving sent message to folder '" + account.getSentFolderName() + "' (" + localSentFolder.getId() + ") "); - localFolder.moveMessages( new Message[] { message }, localSentFolder); + localFolder.moveMessages(new Message[] { message }, localSentFolder); if (K9.DEBUG) Log.i(K9.LOG_TAG, "Moved sent message to folder '" + account.getSentFolderName() + "' (" + localSentFolder.getId() + ") "); @@ -3666,55 +3030,39 @@ public class MessagingController implements Runnable processPendingCommands(account); } - } - catch (Exception e) - { + } catch (Exception e) { message.setFlag(Flag.X_SEND_FAILED, true); Log.e(K9.LOG_TAG, "Failed to send message", e); - for (MessagingListener l : getListeners()) - { - l.synchronizeMailboxFailed( account, localFolder.getName(), getRootCauseMessage(e)); + for (MessagingListener l : getListeners()) { + l.synchronizeMailboxFailed(account, localFolder.getName(), getRootCauseMessage(e)); } lastFailure = e; } - } - catch (Exception e) - { + } catch (Exception e) { Log.e(K9.LOG_TAG, "Failed to fetch message for sending", e); - for (MessagingListener l : getListeners()) - { - l.synchronizeMailboxFailed( account, localFolder.getName(), getRootCauseMessage(e)); + for (MessagingListener l : getListeners()) { + l.synchronizeMailboxFailed(account, localFolder.getName(), getRootCauseMessage(e)); } lastFailure = e; } } - for (MessagingListener l : getListeners()) - { + for (MessagingListener l : getListeners()) { l.sendPendingMessagesCompleted(account); } - if (lastFailure != null) - { + if (lastFailure != null) { notifySendFailed(account, lastFailure); } - } - catch (UnavailableStorageException e) - { + } catch (UnavailableStorageException e) { Log.i(K9.LOG_TAG, "Failed to send pending messages because storage is not available - trying again later."); throw new UnavailableAccountException(e); - } - catch (Exception e) - { - for (MessagingListener l : getListeners()) - { + } catch (Exception e) { + for (MessagingListener l : getListeners()) { l.sendPendingMessagesFailed(account); } addErrorMessage(account, null, e); - } - finally - { - if (lastFailure == null) - { + } finally { + if (lastFailure == null) { cancelNotification(K9.SEND_FAILED_NOTIFICATION - account.getAccountNumber()); } closeFolder(localFolder); @@ -3722,20 +3070,14 @@ public class MessagingController implements Runnable } public void getAccountStats(final Context context, final Account account, - final MessagingListener l) - { - Runnable unreadRunnable = new Runnable() - { + final MessagingListener l) { + Runnable unreadRunnable = new Runnable() { @Override - public void run() - { - try - { + public void run() { + try { AccountStats stats = account.getStats(context); l.accountStatusChanged(account, stats); - } - catch (MessagingException me) - { + } catch (MessagingException me) { Log.e(K9.LOG_TAG, "Count not get unread count for account " + account.getDescription(), me); } @@ -3747,22 +3089,16 @@ public class MessagingController implements Runnable } public void getFolderUnreadMessageCount(final Account account, final String folderName, - final MessagingListener l) - { - Runnable unreadRunnable = new Runnable() - { + final MessagingListener l) { + Runnable unreadRunnable = new Runnable() { @Override - public void run() - { + public void run() { int unreadMessageCount = 0; - try - { + try { Folder localFolder = account.getLocalStore().getFolder(folderName); unreadMessageCount = localFolder.getUnreadMessageCount(); - } - catch (MessagingException me) - { + } catch (MessagingException me) { Log.e(K9.LOG_TAG, "Count not get unread count for account " + account.getDescription(), me); } l.folderStatusChanged(account, folderName, unreadMessageCount); @@ -3775,98 +3111,75 @@ public class MessagingController implements Runnable - public boolean isMoveCapable(Message message) - { + public boolean isMoveCapable(Message message) { return !message.getUid().startsWith(K9.LOCAL_UID_PREFIX); } - public boolean isCopyCapable(Message message) - { + public boolean isCopyCapable(Message message) { return isMoveCapable(message); } - public boolean isMoveCapable(final Account account) - { - try - { + public boolean isMoveCapable(final Account account) { + try { Store localStore = account.getLocalStore(); Store remoteStore = account.getRemoteStore(); return localStore.isMoveCapable() && remoteStore.isMoveCapable(); - } - catch (MessagingException me) - { + } catch (MessagingException me) { Log.e(K9.LOG_TAG, "Exception while ascertaining move capability", me); return false; } } - public boolean isCopyCapable(final Account account) - { - try - { + public boolean isCopyCapable(final Account account) { + try { Store localStore = account.getLocalStore(); Store remoteStore = account.getRemoteStore(); return localStore.isCopyCapable() && remoteStore.isCopyCapable(); - } - catch (MessagingException me) - { + } catch (MessagingException me) { Log.e(K9.LOG_TAG, "Exception while ascertaining copy capability", me); return false; } } public void moveMessages(final Account account, final String srcFolder, final Message[] messages, final String destFolder, - final MessagingListener listener) - { - for (Message message : messages) - { + final MessagingListener listener) { + for (Message message : messages) { suppressMessage(account, srcFolder, message); } - putBackground("moveMessages", null, new Runnable() - { + putBackground("moveMessages", null, new Runnable() { @Override - public void run() - { + public void run() { moveOrCopyMessageSynchronous(account, srcFolder, messages, destFolder, false, listener); } }); } public void moveMessage(final Account account, final String srcFolder, final Message message, final String destFolder, - final MessagingListener listener) - { + final MessagingListener listener) { moveMessages(account, srcFolder, new Message[] { message }, destFolder, listener); } public void copyMessages(final Account account, final String srcFolder, final Message[] messages, final String destFolder, - final MessagingListener listener) - { - putBackground("copyMessages", null, new Runnable() - { + final MessagingListener listener) { + putBackground("copyMessages", null, new Runnable() { @Override - public void run() - { + public void run() { moveOrCopyMessageSynchronous(account, srcFolder, messages, destFolder, true, listener); } }); } public void copyMessage(final Account account, final String srcFolder, final Message message, final String destFolder, - final MessagingListener listener) - { + final MessagingListener listener) { copyMessages(account, srcFolder, new Message[] { message }, destFolder, listener); } private void moveOrCopyMessageSynchronous(final Account account, final String srcFolder, final Message[] inMessages, - final String destFolder, final boolean isCopy, MessagingListener listener) - { - try - { + final String destFolder, final boolean isCopy, MessagingListener listener) { + try { Store localStore = account.getLocalStore(); Store remoteStore = account.getRemoteStore(); - if (!isCopy && (!remoteStore.isMoveCapable() || !localStore.isMoveCapable())) - { + if (!isCopy && (!remoteStore.isMoveCapable() || !localStore.isMoveCapable())) { return; } - if (isCopy && (!remoteStore.isCopyCapable() || !localStore.isCopyCapable())) - { + if (isCopy && (!remoteStore.isCopyCapable() || !localStore.isCopyCapable())) { return; } @@ -3874,22 +3187,18 @@ public class MessagingController implements Runnable Folder localDestFolder = localStore.getFolder(destFolder); List uids = new LinkedList(); - for (Message message : inMessages) - { + for (Message message : inMessages) { String uid = message.getUid(); - if (!uid.startsWith(K9.LOCAL_UID_PREFIX)) - { + if (!uid.startsWith(K9.LOCAL_UID_PREFIX)) { uids.add(uid); } } Message[] messages = localSrcFolder.getMessages(uids.toArray(EMPTY_STRING_ARRAY), null); - if (messages.length > 0) - { + if (messages.length > 0) { Map origUidMap = new HashMap(); - for (Message message : messages) - { + for (Message message : messages) { origUidMap.put(message.getUid(), message); } @@ -3897,21 +3206,16 @@ public class MessagingController implements Runnable Log.i(K9.LOG_TAG, "moveOrCopyMessageSynchronous: source folder = " + srcFolder + ", " + messages.length + " messages, " + ", destination folder = " + destFolder + ", isCopy = " + isCopy); - if (isCopy) - { + if (isCopy) { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.ENVELOPE); fp.add(FetchProfile.Item.BODY); localSrcFolder.fetch(messages, fp, null); localSrcFolder.copyMessages(messages, localDestFolder); - } - else - { + } else { localSrcFolder.moveMessages(messages, localDestFolder); - for (String origUid : origUidMap.keySet()) - { - for (MessagingListener l : getListeners()) - { + for (String origUid : origUidMap.keySet()) { + for (MessagingListener l : getListeners()) { l.messageUidChanged(account, srcFolder, origUid, origUidMap.get(origUid).getUid()); } unsuppressMessage(account, srcFolder, origUid); @@ -3922,75 +3226,55 @@ public class MessagingController implements Runnable } processPendingCommands(account); - } - catch (UnavailableStorageException e) - { + } catch (UnavailableStorageException e) { Log.i(K9.LOG_TAG, "Failed to move/copy message because storage is not available - trying again later."); throw new UnavailableAccountException(e); - } - catch (MessagingException me) - { + } catch (MessagingException me) { addErrorMessage(account, null, me); throw new RuntimeException("Error moving message", me); } } - public void expunge(final Account account, final String folder, final MessagingListener listener) - { - putBackground("expunge", null, new Runnable() - { + public void expunge(final Account account, final String folder, final MessagingListener listener) { + putBackground("expunge", null, new Runnable() { @Override - public void run() - { + public void run() { queueExpunge(account, folder); } }); } - public void deleteDraft(final Account account, String uid) - { + public void deleteDraft(final Account account, String uid) { LocalFolder localFolder = null; - try - { + try { LocalStore localStore = account.getLocalStore(); localFolder = localStore.getFolder(account.getDraftsFolderName()); localFolder.open(OpenMode.READ_WRITE); Message message = localFolder.getMessage(uid); - if (message != null) - { + if (message != null) { deleteMessages(new Message[] { message }, null); } - } - catch (MessagingException me) - { + } catch (MessagingException me) { addErrorMessage(account, null, me); - } - finally - { + } finally { closeFolder(localFolder); } } - public void deleteMessages(final Message[] messages, final MessagingListener listener) - { - actOnMessages(messages, new MessageActor() - { + public void deleteMessages(final Message[] messages, final MessagingListener listener) { + actOnMessages(messages, new MessageActor() { @Override public void act(final Account account, final Folder folder, - final List messages) - { - for (Message message : messages) - { + final List messages) { + for (Message message : messages) { suppressMessage(account, folder.getName(), message); } - putBackground("deleteMessages", null, new Runnable() - { + putBackground("deleteMessages", null, new Runnable() { @Override - public void run() - { + public void run() { deleteMessagesSynchronous(account, folder.getName(), messages.toArray(EMPTY_MESSAGE_ARRAY), listener); } }); @@ -4001,44 +3285,34 @@ public class MessagingController implements Runnable } private void deleteMessagesSynchronous(final Account account, final String folder, final Message[] messages, - MessagingListener listener) - { + MessagingListener listener) { Folder localFolder = null; Folder localTrashFolder = null; String[] uids = getUidsFromMessages(messages); - try - { + try { //We need to make these callbacks before moving the messages to the trash //as messages get a new UID after being moved - for (Message message : messages) - { - if (listener != null) - { + for (Message message : messages) { + if (listener != null) { listener.messageDeleted(account, folder, message); } - for (MessagingListener l : getListeners()) - { + for (MessagingListener l : getListeners()) { l.messageDeleted(account, folder, message); } } Store localStore = account.getLocalStore(); localFolder = localStore.getFolder(folder); - if (folder.equals(account.getTrashFolderName()) || K9.FOLDER_NONE.equals(account.getTrashFolderName())) - { + if (folder.equals(account.getTrashFolderName()) || K9.FOLDER_NONE.equals(account.getTrashFolderName())) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "Deleting messages in trash folder or trash set to -None-, not copying"); localFolder.setFlags(messages, new Flag[] { Flag.DELETED }, true); - } - else - { + } else { localTrashFolder = localStore.getFolder(account.getTrashFolderName()); - if (!localTrashFolder.exists()) - { + if (!localTrashFolder.exists()) { localTrashFolder.create(Folder.FolderType.HOLDS_MESSAGES); } - if (localTrashFolder.exists()) - { + if (localTrashFolder.exists()) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "Deleting messages in normal folder, moving"); @@ -4047,11 +3321,9 @@ public class MessagingController implements Runnable } } - for (MessagingListener l : getListeners()) - { + for (MessagingListener l : getListeners()) { l.folderStatusChanged(account, folder, localFolder.getUnreadMessageCount()); - if (localTrashFolder != null) - { + if (localTrashFolder != null) { l.folderStatusChanged(account, account.getTrashFolderName(), localTrashFolder.getUnreadMessageCount()); } } @@ -4059,92 +3331,67 @@ public class MessagingController implements Runnable if (K9.DEBUG) Log.d(K9.LOG_TAG, "Delete policy for account " + account.getDescription() + " is " + account.getDeletePolicy()); - if (folder.equals(account.getOutboxFolderName())) - { - for (Message message : messages) - { + if (folder.equals(account.getOutboxFolderName())) { + for (Message message : messages) { // If the message was in the Outbox, then it has been copied to local Trash, and has // to be copied to remote trash PendingCommand command = new PendingCommand(); command.command = PENDING_COMMAND_APPEND; command.arguments = - new String[] - { + new String[] { account.getTrashFolderName(), message.getUid() }; queuePendingCommand(account, command); } processPendingCommands(account); - } - else if ( account.getDeletePolicy() == Account.DELETE_POLICY_ON_DELETE) - { - if (folder.equals(account.getTrashFolderName())) - { + } else if (account.getDeletePolicy() == Account.DELETE_POLICY_ON_DELETE) { + if (folder.equals(account.getTrashFolderName())) { queueSetFlag(account, folder, Boolean.toString(true), Flag.DELETED.toString(), uids); - } - else - { + } else { queueMoveOrCopy(account, folder, account.getTrashFolderName(), false, uids); } processPendingCommands(account); - } - else if (account.getDeletePolicy() == Account.DELETE_POLICY_MARK_AS_READ) - { + } else if (account.getDeletePolicy() == Account.DELETE_POLICY_MARK_AS_READ) { queueSetFlag(account, folder, Boolean.toString(true), Flag.SEEN.toString(), uids); processPendingCommands(account); - } - else - { + } else { if (K9.DEBUG) Log.d(K9.LOG_TAG, "Delete policy " + account.getDeletePolicy() + " prevents delete from server"); } - for (String uid : uids) - { + for (String uid : uids) { unsuppressMessage(account, folder, uid); } - } - catch (UnavailableStorageException e) - { + } catch (UnavailableStorageException e) { Log.i(K9.LOG_TAG, "Failed to delete message because storage is not available - trying again later."); throw new UnavailableAccountException(e); - } - catch (MessagingException me) - { + } catch (MessagingException me) { addErrorMessage(account, null, me); throw new RuntimeException("Error deleting message from local store.", me); - } - finally - { + } finally { closeFolder(localFolder); closeFolder(localTrashFolder); } } - private String[] getUidsFromMessages(Message[] messages) - { + private String[] getUidsFromMessages(Message[] messages) { String[] uids = new String[messages.length]; - for (int i = 0; i < messages.length; i++) - { + for (int i = 0; i < messages.length; i++) { uids[i] = messages[i].getUid(); } return uids; } - private void processPendingEmptyTrash(PendingCommand command, Account account) throws MessagingException - { + private void processPendingEmptyTrash(PendingCommand command, Account account) throws MessagingException { Store remoteStore = account.getRemoteStore(); Folder remoteFolder = remoteStore.getFolder(account.getTrashFolderName()); - try - { - if (remoteFolder.exists()) - { + try { + if (remoteFolder.exists()) { remoteFolder.open(OpenMode.READ_WRITE); remoteFolder.setFlags(new Flag [] { Flag.DELETED }, true); - if (Account.EXPUNGE_IMMEDIATELY.equals(account.getExpungePolicy())) - { + if (Account.EXPUNGE_IMMEDIATELY.equals(account.getExpungePolicy())) { remoteFolder.expunge(); } @@ -4155,30 +3402,23 @@ public class MessagingController implements Runnable } - } - finally - { + } finally { closeFolder(remoteFolder); } } - public void emptyTrash(final Account account, MessagingListener listener) - { - putBackground("emptyTrash", listener, new Runnable() - { + public void emptyTrash(final Account account, MessagingListener listener) { + putBackground("emptyTrash", listener, new Runnable() { @Override - public void run() - { + public void run() { Folder localFolder = null; - try - { + try { Store localStore = account.getLocalStore(); localFolder = localStore.getFolder(account.getTrashFolderName()); localFolder.open(OpenMode.READ_WRITE); localFolder.setFlags(new Flag[] { Flag.DELETED }, true); - for (MessagingListener l : getListeners()) - { + for (MessagingListener l : getListeners()) { l.emptyTrashCompleted(account); } List args = new ArrayList(); @@ -4187,67 +3427,52 @@ public class MessagingController implements Runnable command.arguments = args.toArray(EMPTY_STRING_ARRAY); queuePendingCommand(account, command); processPendingCommands(account); - } - catch (UnavailableStorageException e) - { + } catch (UnavailableStorageException e) { Log.i(K9.LOG_TAG, "Failed to empty trash because storage is not available - trying again later."); throw new UnavailableAccountException(e); - } - catch (Exception e) - { + } catch (Exception e) { Log.e(K9.LOG_TAG, "emptyTrash failed", e); addErrorMessage(account, null, e); - } - finally - { + } finally { closeFolder(localFolder); } } }); } - public void sendAlternate(final Context context, Account account, Message message) - { + public void sendAlternate(final Context context, Account account, Message message) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "About to load message " + account.getDescription() + ":" + message.getFolder().getName() + ":" + message.getUid() + " for sendAlternate"); loadMessageForView(account, message.getFolder().getName(), - message.getUid(), new MessagingListener() - { + message.getUid(), new MessagingListener() { @Override public void loadMessageForViewBodyAvailable(Account account, String folder, String uid, - Message message) - { + Message message) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "Got message " + account.getDescription() + ":" + folder + ":" + message.getUid() + " for sendAlternate"); - try - { - Intent msg=new Intent(Intent.ACTION_SEND); + try { + Intent msg = new Intent(Intent.ACTION_SEND); String quotedText = null; Part part = MimeUtility.findFirstPartByMimeType(message, "text/plain"); - if (part == null) - { + if (part == null) { part = MimeUtility.findFirstPartByMimeType(message, "text/html"); } - if (part != null) - { + if (part != null) { quotedText = MimeUtility.getTextFromPart(part); } - if (quotedText != null) - { + if (quotedText != null) { msg.putExtra(Intent.EXTRA_TEXT, quotedText); } msg.putExtra(Intent.EXTRA_SUBJECT, "Fwd: " + message.getSubject()); msg.setType("text/plain"); context.startActivity(Intent.createChooser(msg, context.getString(R.string.send_alternate_chooser_title))); - } - catch (MessagingException me) - { + } catch (MessagingException me) { Log.e(K9.LOG_TAG, "Unable to send email through alternate program", me); } } @@ -4266,12 +3491,10 @@ public class MessagingController implements Runnable public void checkMail(final Context context, final Account account, final boolean ignoreLastCheckedTime, final boolean useManualWakeLock, - final MessagingListener listener) - { + final MessagingListener listener) { TracingWakeLock twakeLock = null; - if (useManualWakeLock) - { + if (useManualWakeLock) { TracingPowerManager pm = TracingPowerManager.getPowerManager(context); twakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "K9 MessagingController.checkMail"); @@ -4280,61 +3503,46 @@ public class MessagingController implements Runnable } final TracingWakeLock wakeLock = twakeLock; - for (MessagingListener l : getListeners()) - { + for (MessagingListener l : getListeners()) { l.checkMailStarted(context, account); } - putBackground("checkMail", listener, new Runnable() - { + putBackground("checkMail", listener, new Runnable() { @Override - public void run() - { + public void run() { - try - { + try { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Starting mail check"); Preferences prefs = Preferences.getPreferences(context); Account[] accounts; - if (account != null) - { - accounts = new Account[] - { + if (account != null) { + accounts = new Account[] { account }; - } - else - { + } else { accounts = prefs.getAccounts(); } - for (final Account account : accounts) - { - checkMailForAccount(context, account,ignoreLastCheckedTime, prefs, listener); + for (final Account account : accounts) { + checkMailForAccount(context, account, ignoreLastCheckedTime, prefs, listener); } - } - catch (Exception e) - { + } catch (Exception e) { Log.e(K9.LOG_TAG, "Unable to synchronize mail", e); addErrorMessage(account, null, e); } - putBackground("finalize sync", null, new Runnable() - { + putBackground("finalize sync", null, new Runnable() { @Override - public void run() - { + public void run() { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Finished mail sync"); - if (wakeLock != null) - { + if (wakeLock != null) { wakeLock.release(); } - for (MessagingListener l : getListeners()) - { + for (MessagingListener l : getListeners()) { l.checkMailFinished(context, account); } @@ -4350,19 +3558,15 @@ public class MessagingController implements Runnable private void checkMailForAccount(final Context context, final Account account, final boolean ignoreLastCheckedTime, final Preferences prefs, - final MessagingListener listener) - { - if (!account.isAvailable(context)) - { - if (K9.DEBUG) - { + final MessagingListener listener) { + if (!account.isAvailable(context)) { + if (K9.DEBUG) { Log.i(K9.LOG_TAG, "Skipping synchronizing unavailable account " + account.getDescription()); } return; } final long accountInterval = account.getAutomaticCheckIntervalMinutes() * 60 * 1000; - if (!ignoreLastCheckedTime && accountInterval <= 0) - { + if (!ignoreLastCheckedTime && accountInterval <= 0) { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Skipping synchronizing account " + account.getDescription()); return; @@ -4375,22 +3579,19 @@ public class MessagingController implements Runnable sendPendingMessages(account, listener); - try - { + try { Account.FolderMode aDisplayMode = account.getFolderDisplayMode(); Account.FolderMode aSyncMode = account.getFolderSyncMode(); Store localStore = account.getLocalStore(); - for (final Folder folder : localStore.getPersonalNamespaces(false)) - { + for (final Folder folder : localStore.getPersonalNamespaces(false)) { folder.open(Folder.OpenMode.READ_WRITE); folder.refresh(prefs); Folder.FolderClass fDisplayClass = folder.getDisplayClass(); Folder.FolderClass fSyncClass = folder.getSyncClass(); - if (modeMismatch(aDisplayMode, fDisplayClass)) - { + if (modeMismatch(aDisplayMode, fDisplayClass)) { // Never sync a folder that isn't displayed /* if (K9.DEBUG) @@ -4401,8 +3602,7 @@ public class MessagingController implements Runnable continue; } - if (modeMismatch(aSyncMode, fSyncClass)) - { + if (modeMismatch(aSyncMode, fSyncClass)) { // Do not sync folders in the wrong class /* if (K9.DEBUG) @@ -4414,32 +3614,22 @@ public class MessagingController implements Runnable } synchronizeFolder(account, folder, ignoreLastCheckedTime, accountInterval, listener); } - } - catch (MessagingException e) - { + } catch (MessagingException e) { Log.e(K9.LOG_TAG, "Unable to synchronize account " + account.getName(), e); addErrorMessage(account, null, e); - } - finally - { - putBackground("clear notification flag for " + account.getDescription(), null, new Runnable() - { + } finally { + putBackground("clear notification flag for " + account.getDescription(), null, new Runnable() { @Override - public void run() - { + public void run() { if (K9.DEBUG) Log.v(K9.LOG_TAG, "Clearing notification flag for " + account.getDescription()); account.setRingNotified(false); - try - { + try { AccountStats stats = account.getStats(context); - if (stats == null || stats.unreadMessageCount == 0) - { + if (stats == null || stats.unreadMessageCount == 0) { notifyAccountCancel(context, account); } - } - catch (MessagingException e) - { + } catch (MessagingException e) { Log.e(K9.LOG_TAG, "Unable to getUnreadMessageCount for account: " + account, e); } } @@ -4456,8 +3646,7 @@ public class MessagingController implements Runnable final Folder folder, final boolean ignoreLastCheckedTime, final long accountInterval, - final MessagingListener listener ) - { + final MessagingListener listener) { if (K9.DEBUG) @@ -4465,8 +3654,7 @@ public class MessagingController implements Runnable new Date(folder.getLastChecked())); if (!ignoreLastCheckedTime && folder.getLastChecked() > - (System.currentTimeMillis() - accountInterval)) - { + (System.currentTimeMillis() - accountInterval)) { if (K9.DEBUG) Log.v(K9.LOG_TAG, "Not syncing folder " + folder.getName() + ", previously synced @ " + new Date(folder.getLastChecked()) @@ -4474,14 +3662,11 @@ public class MessagingController implements Runnable return; } - putBackground("sync" + folder.getName(), null, new Runnable() - { + putBackground("sync" + folder.getName(), null, new Runnable() { @Override - public void run() - { + public void run() { LocalFolder tLocalFolder = null; - try - { + try { // In case multiple Commands get enqueued, don't run more than // once final LocalStore localStore = account.getLocalStore(); @@ -4489,8 +3674,7 @@ public class MessagingController implements Runnable tLocalFolder.open(Folder.OpenMode.READ_WRITE); if (!ignoreLastCheckedTime && tLocalFolder.getLastChecked() > - (System.currentTimeMillis() - accountInterval)) - { + (System.currentTimeMillis() - accountInterval)) { if (K9.DEBUG) Log.v(K9.LOG_TAG, "Not running Command for folder " + folder.getName() + ", previously synced @ " + new Date(folder.getLastChecked()) @@ -4498,24 +3682,17 @@ public class MessagingController implements Runnable return; } notifyFetchingMail(account, folder); - try - { + try { synchronizeMailboxSynchronous(account, folder.getName(), listener, null); - } - finally - { + } finally { notifyFetchingMailCancel(account); } - } - catch (Exception e) - { + } catch (Exception e) { Log.e(K9.LOG_TAG, "Exception while processing folder " + account.getDescription() + ":" + folder.getName(), e); addErrorMessage(account, null, e); - } - finally - { + } finally { closeFolder(tLocalFolder); } } @@ -4527,50 +3704,36 @@ public class MessagingController implements Runnable - public void compact(final Account account, final MessagingListener ml) - { - putBackground("compact:" + account.getDescription(), ml, new Runnable() - { + public void compact(final Account account, final MessagingListener ml) { + putBackground("compact:" + account.getDescription(), ml, new Runnable() { @Override - public void run() - { - try - { + public void run() { + try { LocalStore localStore = account.getLocalStore(); long oldSize = localStore.getSize(); localStore.compact(); long newSize = localStore.getSize(); - if (ml != null) - { + if (ml != null) { ml.accountSizeChanged(account, oldSize, newSize); } - for (MessagingListener l : getListeners()) - { + for (MessagingListener l : getListeners()) { l.accountSizeChanged(account, oldSize, newSize); } - } - catch (UnavailableStorageException e) - { + } catch (UnavailableStorageException e) { Log.i(K9.LOG_TAG, "Failed to compact account because storage is not available - trying again later."); throw new UnavailableAccountException(e); - } - catch (Exception e) - { + } catch (Exception e) { Log.e(K9.LOG_TAG, "Failed to compact account " + account.getDescription(), e); } } }); } - public void clear(final Account account, final MessagingListener ml) - { - putBackground("clear:" + account.getDescription(), ml, new Runnable() - { + public void clear(final Account account, final MessagingListener ml) { + putBackground("clear:" + account.getDescription(), ml, new Runnable() { @Override - public void run() - { - try - { + public void run() { + try { LocalStore localStore = account.getLocalStore(); long oldSize = localStore.getSize(); localStore.clear(); @@ -4580,39 +3743,29 @@ public class MessagingController implements Runnable stats.size = newSize; stats.unreadMessageCount = 0; stats.flaggedMessageCount = 0; - if (ml != null) - { + if (ml != null) { ml.accountSizeChanged(account, oldSize, newSize); ml.accountStatusChanged(account, stats); } - for (MessagingListener l : getListeners()) - { + for (MessagingListener l : getListeners()) { l.accountSizeChanged(account, oldSize, newSize); l.accountStatusChanged(account, stats); } - } - catch (UnavailableStorageException e) - { + } catch (UnavailableStorageException e) { Log.i(K9.LOG_TAG, "Failed to clear account because storage is not available - trying again later."); throw new UnavailableAccountException(e); - } - catch (Exception e) - { + } catch (Exception e) { Log.e(K9.LOG_TAG, "Failed to clear account " + account.getDescription(), e); } } }); } - public void recreate(final Account account, final MessagingListener ml) - { - putBackground("recreate:" + account.getDescription(), ml, new Runnable() - { + public void recreate(final Account account, final MessagingListener ml) { + putBackground("recreate:" + account.getDescription(), ml, new Runnable() { @Override - public void run() - { - try - { + public void run() { + try { LocalStore localStore = account.getLocalStore(); long oldSize = localStore.getSize(); localStore.recreate(); @@ -4622,24 +3775,18 @@ public class MessagingController implements Runnable stats.size = newSize; stats.unreadMessageCount = 0; stats.flaggedMessageCount = 0; - if (ml != null) - { + if (ml != null) { ml.accountSizeChanged(account, oldSize, newSize); ml.accountStatusChanged(account, stats); } - for (MessagingListener l : getListeners()) - { + for (MessagingListener l : getListeners()) { l.accountSizeChanged(account, oldSize, newSize); l.accountStatusChanged(account, stats); } - } - catch (UnavailableStorageException e) - { + } catch (UnavailableStorageException e) { Log.i(K9.LOG_TAG, "Failed to recreate an account because storage is not available - trying again later."); throw new UnavailableAccountException(e); - } - catch (Exception e) - { + } catch (Exception e) { Log.e(K9.LOG_TAG, "Failed to recreate account " + account.getDescription(), e); } } @@ -4647,18 +3794,15 @@ public class MessagingController implements Runnable } - private boolean shouldNotifyForMessage(Account account, LocalFolder localFolder, Message message) - { + private boolean shouldNotifyForMessage(Account account, LocalFolder localFolder, Message message) { // Do not notify if the user does not have notifications // enabled or if the message has been read - if (!account.isNotifyNewMail() || message.isSet(Flag.SEEN) || (account.getName() == null)) - { + if (!account.isNotifyNewMail() || message.isSet(Flag.SEEN) || (account.getName() == null)) { return false; } Folder folder = message.getFolder(); - if (folder != null) - { + if (folder != null) { // No notification for new messages in Trash, Drafts, Spam or Sent folder. // But do notify if it's the INBOX (see issue 1817). String folderName = folder.getName(); @@ -4666,26 +3810,20 @@ public class MessagingController implements Runnable (account.getTrashFolderName().equals(folderName) || account.getDraftsFolderName().equals(folderName) || account.getSpamFolderName().equals(folderName) - || account.getSentFolderName().equals(folderName))) - { + || account.getSentFolderName().equals(folderName))) { return false; } } - if (message.getUid() != null && localFolder.getLastUid() != null) - { - try - { + if (message.getUid() != null && localFolder.getLastUid() != null) { + try { Integer messageUid = Integer.parseInt(message.getUid()); - if (messageUid <= localFolder.getLastUid()) - { - if(K9.DEBUG) + if (messageUid <= localFolder.getLastUid()) { + if (K9.DEBUG) Log.d(K9.LOG_TAG, "Message uid is " + messageUid + ", max message uid is " + localFolder.getLastUid() + ". Skipping notification."); return false; } - } - catch (NumberFormatException e) - { + } catch (NumberFormatException e) { // Nothing to be done here. } } @@ -4699,22 +3837,18 @@ public class MessagingController implements Runnable /** Creates a notification of new email messages * ringtone, lights, and vibration to be played */ - private boolean notifyAccount(Context context, Account account, Message message, int previousUnreadMessageCount, AtomicInteger newMessageCount) - { + private boolean notifyAccount(Context context, Account account, Message message, int previousUnreadMessageCount, AtomicInteger newMessageCount) { // If we don't even have an account name, don't show the notification // (This happens during initial account setup) // - if (account.getName() == null) - { + if (account.getName() == null) { return false; } // If the account us a POP3 account and the message is older than // the oldest message we've previously seen then don't notify about it - if (account.getStoreUri().startsWith("pop3") ) - { - if ( message.olderThan(new Date(account.getLatestOldMessageSeenTime()))) - { + if (account.getStoreUri().startsWith("pop3")) { + if (message.olderThan(new Date(account.getLatestOldMessageSeenTime()))) { return false; } } @@ -4723,41 +3857,31 @@ public class MessagingController implements Runnable // If we have a message, set the notification to ": " StringBuilder messageNotice = new StringBuilder(); final KeyguardManager keyguardService = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE); - try - { - if (message.getFrom() != null) - { + try { + if (message.getFrom() != null) { Address[] fromAddrs = message.getFrom(); String from = fromAddrs.length > 0 ? fromAddrs[0].toFriendly().toString() : null; String subject = message.getSubject(); - if (subject == null) - { + if (subject == null) { subject = context.getString(R.string.general_no_subject); } - if (from != null) - { + if (from != null) { // Show From: address by default - if (!account.isAnIdentity(fromAddrs)) - { + if (!account.isAnIdentity(fromAddrs)) { messageNotice.append(from).append(": ").append(subject); } // show To: if the message was sent from me - else - { - if (!account.isNotifySelfNewMail()) - { + else { + if (!account.isNotifySelfNewMail()) { return false; } Address[] rcpts = message.getRecipients(Message.RecipientType.TO); String to = rcpts.length > 0 ? rcpts[0].toFriendly().toString() : null; - if (to != null) - { + if (to != null) { messageNotice.append(String.format(context.getString(R.string.message_to_fmt), to)).append(": ").append(subject); - } - else - { + } else { messageNotice.append(context.getString(R.string.general_no_sender)).append(": ").append(subject); } @@ -4765,17 +3889,14 @@ public class MessagingController implements Runnable } } } - } - catch (MessagingException e) - { + } catch (MessagingException e) { Log.e(K9.LOG_TAG, "Unable to get message information for notification.", e); } // If privacy mode active and keyguard active // OR // If we could not set a per-message notification, revert to a default message - if ((K9.keyguardPrivacy() && keyguardService.inKeyguardRestrictedInputMode()) || messageNotice.length() == 0) - { + if ((K9.keyguardPrivacy() && keyguardService.inKeyguardRestrictedInputMode()) || messageNotice.length() == 0) { messageNotice = new StringBuilder(context.getString(R.string.notification_new_title)); } @@ -4783,8 +3904,7 @@ public class MessagingController implements Runnable (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE); Notification notif = new Notification(R.drawable.stat_notify_email_generic, messageNotice, System.currentTimeMillis()); final int unreadCount = previousUnreadMessageCount + newMessageCount.get(); - if (account.isNotificationShowsUnreadCount()) - { + if (account.isNotificationShowsUnreadCount()) { notif.number = unreadCount; } @@ -4797,15 +3917,14 @@ public class MessagingController implements Runnable // Only ring or vibrate if we have not done so already on this // account and fetch boolean ringAndVibrate = false; - if (!account.isRingNotified()) - { + if (!account.isRingNotified()) { account.setRingNotified(true); ringAndVibrate = true; } NotificationSetting n = account.getNotificationSetting(); - configureNotification(notif, ( n.shouldRing() ? n.getRingtone() : null), (n.shouldVibrate() ? n.getVibration() : null), (n.isLed() ? n.getLedColor() : null), K9.NOTIFICATION_LED_BLINK_SLOW, ringAndVibrate); + configureNotification(notif, (n.shouldRing() ? n.getRingtone() : null), (n.shouldVibrate() ? n.getVibration() : null), (n.isLed() ? n.getLedColor() : null), K9.NOTIFICATION_LED_BLINK_SLOW, ringAndVibrate); notifMgr.notify(account.getAccountNumber(), notif); return true; @@ -4832,39 +3951,30 @@ public class MessagingController implements Runnable final Integer ledColor, final int ledSpeed, - final boolean ringAndVibrate) - { + final boolean ringAndVibrate) { // if it's quiet time, then we shouldn't be ringing, buzzing or flashing - if (K9.isQuietTime()) - { + if (K9.isQuietTime()) { return; } - if (ringAndVibrate) - { - if (ringtone != null) - { + if (ringAndVibrate) { + if (ringtone != null) { notification.sound = TextUtils.isEmpty(ringtone) ? null : Uri.parse(ringtone); notification.audioStreamType = AudioManager.STREAM_NOTIFICATION; } - if (vibrationPattern != null ) - { + if (vibrationPattern != null) { notification.vibrate = vibrationPattern; } } - if (ledColor != null ) - { + if (ledColor != null) { notification.flags |= Notification.FLAG_SHOW_LIGHTS; notification.ledARGB = ledColor; - if (ledSpeed == K9.NOTIFICATION_LED_BLINK_SLOW) - { + if (ledSpeed == K9.NOTIFICATION_LED_BLINK_SLOW) { notification.ledOnMS = K9.NOTIFICATION_LED_ON_TIME; notification.ledOffMS = K9.NOTIFICATION_LED_OFF_TIME; - } - else if (ledSpeed == K9.NOTIFICATION_LED_BLINK_FAST) - { + } else if (ledSpeed == K9.NOTIFICATION_LED_BLINK_FAST) { notification.ledOnMS = K9.NOTIFICATION_LED_FAST_ON_TIME; notification.ledOffMS = K9.NOTIFICATION_LED_FAST_OFF_TIME; } @@ -4872,8 +3982,7 @@ public class MessagingController implements Runnable } /** Cancel a notification of new email messages */ - public void notifyAccountCancel(Context context, Account account) - { + public void notifyAccountCancel(Context context, Account account) { NotificationManager notifMgr = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE); notifMgr.cancel(account.getAccountNumber()); @@ -4886,17 +3995,14 @@ public class MessagingController implements Runnable * @param message Message to save. * @return Message representing the entry in the local store. */ - public Message saveDraft(final Account account, final Message message) - { + public Message saveDraft(final Account account, final Message message) { Message localMessage = null; - try - { + try { LocalStore localStore = account.getLocalStore(); LocalFolder localFolder = localStore.getFolder(account.getDraftsFolderName()); localFolder.open(OpenMode.READ_WRITE); // Save the message to the store. - localFolder.appendMessages(new Message[] - { + localFolder.appendMessages(new Message[] { message }); // Fetch the message back from the store. This is the Message that's returned to the caller. @@ -4905,25 +4011,21 @@ public class MessagingController implements Runnable PendingCommand command = new PendingCommand(); command.command = PENDING_COMMAND_APPEND; - command.arguments = new String[] - { + command.arguments = new String[] { localFolder.getName(), localMessage.getUid() }; queuePendingCommand(account, command); processPendingCommands(account); - } - catch (MessagingException e) - { + } catch (MessagingException e) { Log.e(K9.LOG_TAG, "Unable to save message as draft.", e); addErrorMessage(account, null, e); } return localMessage; } - public boolean modeMismatch(Account.FolderMode aMode, Folder.FolderClass fMode) - { + public boolean modeMismatch(Account.FolderMode aMode, Folder.FolderClass fMode) { if (aMode == Account.FolderMode.NONE || (aMode == Account.FolderMode.FIRST_CLASS && fMode != Folder.FolderClass.FIRST_CLASS) @@ -4931,19 +4033,15 @@ public class MessagingController implements Runnable fMode != Folder.FolderClass.FIRST_CLASS && fMode != Folder.FolderClass.SECOND_CLASS) || (aMode == Account.FolderMode.NOT_SECOND_CLASS && - fMode == Folder.FolderClass.SECOND_CLASS)) - { + fMode == Folder.FolderClass.SECOND_CLASS)) { return true; - } - else - { + } else { return false; } } static AtomicInteger sequencing = new AtomicInteger(0); - static class Command implements Comparable - { + static class Command implements Comparable { public Runnable runnable; public MessagingListener listener; @@ -4955,78 +4053,58 @@ public class MessagingController implements Runnable int sequence = sequencing.getAndIncrement(); @Override - public int compareTo(Command other) - { - if (other.isForeground && !isForeground) - { + public int compareTo(Command other) { + if (other.isForeground && !isForeground) { return 1; - } - else if (!other.isForeground && isForeground) - { + } else if (!other.isForeground && isForeground) { return -1; - } - else - { + } else { return (sequence - other.sequence); } } } - public MessagingListener getCheckMailListener() - { + public MessagingListener getCheckMailListener() { return checkMailListener; } - public void setCheckMailListener(MessagingListener checkMailListener) - { - if (this.checkMailListener != null) - { + public void setCheckMailListener(MessagingListener checkMailListener) { + if (this.checkMailListener != null) { removeListener(this.checkMailListener); } this.checkMailListener = checkMailListener; - if (this.checkMailListener != null) - { + if (this.checkMailListener != null) { addListener(this.checkMailListener); } } - public SORT_TYPE getSortType() - { + public SORT_TYPE getSortType() { return sortType; } - public void setSortType(SORT_TYPE sortType) - { + public void setSortType(SORT_TYPE sortType) { this.sortType = sortType; } - public boolean isSortAscending(SORT_TYPE sortType) - { + public boolean isSortAscending(SORT_TYPE sortType) { Boolean sortAsc = sortAscending.get(sortType); - if (sortAsc == null) - { + if (sortAsc == null) { return sortType.isDefaultAscending(); - } - else return sortAsc; + } else return sortAsc; } - public void setSortAscending(SORT_TYPE sortType, boolean nsortAscending) - { + public void setSortAscending(SORT_TYPE sortType, boolean nsortAscending) { sortAscending.put(sortType, nsortAscending); } - public Collection getPushers() - { + public Collection getPushers() { return pushers.values(); } - public boolean setupPushing(final Account account) - { - try - { + public boolean setupPushing(final Account account) { + try { Pusher previousPusher = pushers.remove(account); - if (previousPusher != null) - { + if (previousPusher != null) { previousPusher.stop(); } Preferences prefs = Preferences.getPreferences(mApplication); @@ -5037,11 +4115,9 @@ public class MessagingController implements Runnable List names = new ArrayList(); Store localStore = account.getLocalStore(); - for (final Folder folder : localStore.getPersonalNamespaces(false)) - { + for (final Folder folder : localStore.getPersonalNamespaces(false)) { if (folder.getName().equals(account.getErrorFolderName()) - || folder.getName().equals(account.getOutboxFolderName())) - { + || folder.getName().equals(account.getOutboxFolderName())) { /* if (K9.DEBUG) Log.v(K9.LOG_TAG, "Not pushing folder " + folder.getName() + @@ -5056,8 +4132,7 @@ public class MessagingController implements Runnable Folder.FolderClass fDisplayClass = folder.getDisplayClass(); Folder.FolderClass fPushClass = folder.getPushClass(); - if (modeMismatch(aDisplayMode, fDisplayClass)) - { + if (modeMismatch(aDisplayMode, fDisplayClass)) { // Never push a folder that isn't displayed /* if (K9.DEBUG) @@ -5068,8 +4143,7 @@ public class MessagingController implements Runnable continue; } - if (modeMismatch(aPushMode, fPushClass)) - { + if (modeMismatch(aPushMode, fPushClass)) { // Do not push folders in the wrong class /* if (K9.DEBUG) @@ -5085,13 +4159,11 @@ public class MessagingController implements Runnable names.add(folder.getName()); } - if (names.size() > 0) - { + if (names.size() > 0) { PushReceiver receiver = new MessagingControllerPushReceiver(mApplication, account, this); int maxPushFolders = account.getMaxPushFolders(); - if (names.size() > maxPushFolders) - { + if (names.size() > maxPushFolders) { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Count of folders to push for account " + account.getDescription() + " is " + names.size() + ", greater than limit of " + maxPushFolders + ", truncating"); @@ -5099,79 +4171,63 @@ public class MessagingController implements Runnable names = names.subList(0, maxPushFolders); } - try - { + try { Store store = account.getRemoteStore(); - if (!store.isPushCapable()) - { + if (!store.isPushCapable()) { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Account " + account.getDescription() + " is not push capable, skipping"); return false; } Pusher pusher = store.getPusher(receiver); - if (pusher != null) - { + if (pusher != null) { Pusher oldPusher = pushers.putIfAbsent(account, pusher); - if (oldPusher == null) - { + if (oldPusher == null) { pusher.start(names); } } - } - catch (Exception e) - { + } catch (Exception e) { Log.e(K9.LOG_TAG, "Could not get remote store", e); return false; } return true; - } - else - { + } else { if (K9.DEBUG) Log.i(K9.LOG_TAG, "No folders are configured for pushing in account " + account.getDescription()); return false; } - } - catch (Exception e) - { + } catch (Exception e) { Log.e(K9.LOG_TAG, "Got exception while setting up pushing", e); } return false; } - public void stopAllPushing() - { + public void stopAllPushing() { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Stopping all pushers"); Iterator iter = pushers.values().iterator(); - while (iter.hasNext()) - { + while (iter.hasNext()) { Pusher pusher = iter.next(); iter.remove(); pusher.stop(); } } - public void messagesArrived(final Account account, final Folder remoteFolder, final List messages, final boolean flagSyncOnly) - { + public void messagesArrived(final Account account, final Folder remoteFolder, final List messages, final boolean flagSyncOnly) { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Got new pushed email messages for account " + account.getDescription() + ", folder " + remoteFolder.getName()); final CountDownLatch latch = new CountDownLatch(1); putBackground("Push messageArrived of account " + account.getDescription() - + ", folder " + remoteFolder.getName(), null, new Runnable() - { + + ", folder " + remoteFolder.getName(), null, new Runnable() { @Override - public void run() - { + public void run() { LocalFolder localFolder = null; - try - { + try { LocalStore localStore = account.getLocalStore(); localFolder = localStore.getFolder(remoteFolder.getName()); localFolder.open(OpenMode.READ_WRITE); @@ -5188,70 +4244,54 @@ public class MessagingController implements Runnable if (K9.DEBUG) Log.i(K9.LOG_TAG, "messagesArrived newCount = " + newCount + ", unread count = " + unreadMessageCount); - if (unreadMessageCount == 0) - { + if (unreadMessageCount == 0) { notifyAccountCancel(mApplication, account); } - for (MessagingListener l : getListeners()) - { + for (MessagingListener l : getListeners()) { l.folderStatusChanged(account, remoteFolder.getName(), unreadMessageCount); } - } - catch (Exception e) - { + } catch (Exception e) { String rootMessage = getRootCauseMessage(e); String errorMessage = "Push failed: " + rootMessage; - try - { + try { // Oddly enough, using a local variable gets rid of a // potential null pointer access warning with Eclipse. LocalFolder folder = localFolder; folder.setStatus(errorMessage); - } - catch (Exception se) - { + } catch (Exception se) { Log.e(K9.LOG_TAG, "Unable to set failed status on localFolder", se); } - for (MessagingListener l : getListeners()) - { + for (MessagingListener l : getListeners()) { l.synchronizeMailboxFailed(account, remoteFolder.getName(), errorMessage); } addErrorMessage(account, null, e); - } - finally - { + } finally { closeFolder(localFolder); latch.countDown(); } } }); - try - { + try { latch.await(); - } - catch (Exception e) - { + } catch (Exception e) { Log.e(K9.LOG_TAG, "Interrupted while awaiting latch release", e); } if (K9.DEBUG) Log.i(K9.LOG_TAG, "MessagingController.messagesArrivedLatch released"); } - public void systemStatusChanged() - { - for (MessagingListener l : getListeners()) - { + public void systemStatusChanged() { + for (MessagingListener l : getListeners()) { l.systemStatusChanged(); } } enum MemorizingState { STARTED, FINISHED, FAILED } - static class Memory - { + static class Memory { Account account; String folderName; MemorizingState syncingState = null; @@ -5267,32 +4307,26 @@ public class MessagingController implements Runnable int folderTotal = 0; String processingCommandTitle = null; - Memory(Account nAccount, String nFolderName) - { + Memory(Account nAccount, String nFolderName) { account = nAccount; folderName = nFolderName; } - String getKey() - { + String getKey() { return getMemoryKey(account, folderName); } } - static String getMemoryKey(Account taccount, String tfolderName) - { + static String getMemoryKey(Account taccount, String tfolderName) { return taccount.getDescription() + ":" + tfolderName; } - static class MemorizingListener extends MessagingListener - { + static class MemorizingListener extends MessagingListener { HashMap memories = new HashMap(31); - Memory getMemory(Account account, String folderName) - { + Memory getMemory(Account account, String folderName) { Memory memory = memories.get(getMemoryKey(account, folderName)); - if (memory == null) - { + if (memory == null) { memory = new Memory(account, folderName); memories.put(memory.getKey(), memory); } @@ -5300,8 +4334,7 @@ public class MessagingController implements Runnable } @Override - public synchronized void synchronizeMailboxStarted(Account account, String folder) - { + public synchronized void synchronizeMailboxStarted(Account account, String folder) { Memory memory = getMemory(account, folder); memory.syncingState = MemorizingState.STARTED; memory.folderCompleted = 0; @@ -5310,8 +4343,7 @@ public class MessagingController implements Runnable @Override public synchronized void synchronizeMailboxFinished(Account account, String folder, - int totalMessagesInMailbox, int numNewMessages) - { + int totalMessagesInMailbox, int numNewMessages) { Memory memory = getMemory(account, folder); memory.syncingState = MemorizingState.FINISHED; memory.syncingTotalMessagesInMailbox = totalMessagesInMailbox; @@ -5320,126 +4352,105 @@ public class MessagingController implements Runnable @Override public synchronized void synchronizeMailboxFailed(Account account, String folder, - String message) - { + String message) { Memory memory = getMemory(account, folder); memory.syncingState = MemorizingState.FAILED; memory.failureMessage = message; } - synchronized void refreshOther(MessagingListener other) - { - if (other != null) - { + synchronized void refreshOther(MessagingListener other) { + if (other != null) { Memory syncStarted = null; Memory sendStarted = null; Memory processingStarted = null; - for (Memory memory : memories.values()) - { + for (Memory memory : memories.values()) { - if (memory.syncingState != null) - { - switch (memory.syncingState) - { - case STARTED: - syncStarted = memory; - break; - case FINISHED: - other.synchronizeMailboxFinished(memory.account, memory.folderName, - memory.syncingTotalMessagesInMailbox, memory.syncingNumNewMessages); - break; - case FAILED: - other.synchronizeMailboxFailed(memory.account, memory.folderName, - memory.failureMessage); - break; + if (memory.syncingState != null) { + switch (memory.syncingState) { + case STARTED: + syncStarted = memory; + break; + case FINISHED: + other.synchronizeMailboxFinished(memory.account, memory.folderName, + memory.syncingTotalMessagesInMailbox, memory.syncingNumNewMessages); + break; + case FAILED: + other.synchronizeMailboxFailed(memory.account, memory.folderName, + memory.failureMessage); + break; } } - if (memory.sendingState != null) - { - switch (memory.sendingState) - { - case STARTED: - sendStarted = memory; - break; - case FINISHED: - other.sendPendingMessagesCompleted(memory.account); - break; - case FAILED: - other.sendPendingMessagesFailed(memory.account); - break; + if (memory.sendingState != null) { + switch (memory.sendingState) { + case STARTED: + sendStarted = memory; + break; + case FINISHED: + other.sendPendingMessagesCompleted(memory.account); + break; + case FAILED: + other.sendPendingMessagesFailed(memory.account); + break; } } - if (memory.pushingState != null) - { - switch (memory.pushingState) - { - case STARTED: - other.setPushActive(memory.account, memory.folderName, true); - break; - case FINISHED: - other.setPushActive(memory.account, memory.folderName, false); - break; + if (memory.pushingState != null) { + switch (memory.pushingState) { + case STARTED: + other.setPushActive(memory.account, memory.folderName, true); + break; + case FINISHED: + other.setPushActive(memory.account, memory.folderName, false); + break; } } - if (memory.processingState != null) - { - switch (memory.processingState) - { - case STARTED: - processingStarted = memory; - break; - case FINISHED: - case FAILED: - other.pendingCommandsFinished(memory.account); - break; + if (memory.processingState != null) { + switch (memory.processingState) { + case STARTED: + processingStarted = memory; + break; + case FINISHED: + case FAILED: + other.pendingCommandsFinished(memory.account); + break; } } } Memory somethingStarted = null; - if (syncStarted != null) - { + if (syncStarted != null) { other.synchronizeMailboxStarted(syncStarted.account, syncStarted.folderName); somethingStarted = syncStarted; } - if (sendStarted != null) - { + if (sendStarted != null) { other.sendPendingMessagesStarted(sendStarted.account); somethingStarted = sendStarted; } - if (processingStarted != null) - { + if (processingStarted != null) { other.pendingCommandsProcessing(processingStarted.account); - if (processingStarted.processingCommandTitle != null) - { + if (processingStarted.processingCommandTitle != null) { other.pendingCommandStarted(processingStarted.account, processingStarted.processingCommandTitle); - } - else - { + } else { other.pendingCommandCompleted(processingStarted.account, processingStarted.processingCommandTitle); } somethingStarted = processingStarted; } - if (somethingStarted != null && somethingStarted.folderTotal > 0) - { + if (somethingStarted != null && somethingStarted.folderTotal > 0) { other.synchronizeMailboxProgress(somethingStarted.account, somethingStarted.folderName, somethingStarted.folderCompleted, somethingStarted.folderTotal); } } } @Override - public synchronized void setPushActive(Account account, String folderName, boolean active) - { + public synchronized void setPushActive(Account account, String folderName, boolean active) { Memory memory = getMemory(account, folderName); memory.pushingState = (active ? MemorizingState.STARTED : MemorizingState.FINISHED); } @Override - public synchronized void sendPendingMessagesStarted(Account account) - { + public synchronized void sendPendingMessagesStarted(Account account) { Memory memory = getMemory(account, null); memory.sendingState = MemorizingState.STARTED; memory.folderCompleted = 0; @@ -5447,23 +4458,20 @@ public class MessagingController implements Runnable } @Override - public synchronized void sendPendingMessagesCompleted(Account account) - { + public synchronized void sendPendingMessagesCompleted(Account account) { Memory memory = getMemory(account, null); memory.sendingState = MemorizingState.FINISHED; } @Override - public synchronized void sendPendingMessagesFailed(Account account) - { + public synchronized void sendPendingMessagesFailed(Account account) { Memory memory = getMemory(account, null); memory.sendingState = MemorizingState.FAILED; } @Override - public synchronized void synchronizeMailboxProgress(Account account, String folderName, int completed, int total) - { + public synchronized void synchronizeMailboxProgress(Account account, String folderName, int completed, int total) { Memory memory = getMemory(account, folderName); memory.folderCompleted = completed; memory.folderTotal = total; @@ -5471,67 +4479,57 @@ public class MessagingController implements Runnable @Override - public synchronized void pendingCommandsProcessing(Account account) - { + public synchronized void pendingCommandsProcessing(Account account) { Memory memory = getMemory(account, null); memory.processingState = MemorizingState.STARTED; memory.folderCompleted = 0; memory.folderTotal = 0; } @Override - public synchronized void pendingCommandsFinished(Account account) - { + public synchronized void pendingCommandsFinished(Account account) { Memory memory = getMemory(account, null); memory.processingState = MemorizingState.FINISHED; } @Override - public synchronized void pendingCommandStarted(Account account, String commandTitle) - { + public synchronized void pendingCommandStarted(Account account, String commandTitle) { Memory memory = getMemory(account, null); memory.processingCommandTitle = commandTitle; } @Override - public synchronized void pendingCommandCompleted(Account account, String commandTitle) - { + public synchronized void pendingCommandCompleted(Account account, String commandTitle) { Memory memory = getMemory(account, null); memory.processingCommandTitle = null; } } - private void actOnMessages(Message[] messages, MessageActor actor) - { + private void actOnMessages(Message[] messages, MessageActor actor) { Map>> accountMap = new HashMap>>(); - for (Message message : messages) - { + for (Message message : messages) { Folder folder = message.getFolder(); Account account = folder.getAccount(); Map> folderMap = accountMap.get(account); - if (folderMap == null) - { + if (folderMap == null) { folderMap = new HashMap>(); accountMap.put(account, folderMap); } List messageList = folderMap.get(folder); - if (messageList == null) - { + if (messageList == null) { messageList = new LinkedList(); folderMap.put(folder, messageList); } messageList.add(message); } - for (Map.Entry>> entry : accountMap.entrySet()) - { + for (Map.Entry>> entry : accountMap.entrySet()) { Account account = entry.getKey(); //account.refresh(Preferences.getPreferences(K9.app)); Map> folderMap = entry.getValue(); - for (Map.Entry> folderEntry : folderMap.entrySet()) - { + for (Map.Entry> folderEntry : folderMap.entrySet()) { Folder folder = folderEntry.getKey(); List messageList = folderEntry.getValue(); actor.act(account, folder, messageList); @@ -5539,8 +4537,7 @@ public class MessagingController implements Runnable } } - interface MessageActor - { + interface MessageActor { public void act(final Account account, final Folder folder, final List messages); } } diff --git a/src/com/fsck/k9/controller/MessagingControllerPushReceiver.java b/src/com/fsck/k9/controller/MessagingControllerPushReceiver.java index e18339e42..5f7abef57 100644 --- a/src/com/fsck/k9/controller/MessagingControllerPushReceiver.java +++ b/src/com/fsck/k9/controller/MessagingControllerPushReceiver.java @@ -18,122 +18,97 @@ import com.fsck.k9.service.SleepService; import java.util.List; import java.util.concurrent.CountDownLatch; -public class MessagingControllerPushReceiver implements PushReceiver -{ +public class MessagingControllerPushReceiver implements PushReceiver { final Account account; final MessagingController controller; final Application mApplication; - public MessagingControllerPushReceiver(Application nApplication, Account nAccount, MessagingController nController) - { + public MessagingControllerPushReceiver(Application nApplication, Account nAccount, MessagingController nController) { account = nAccount; controller = nController; mApplication = nApplication; } public void messagesFlagsChanged(Folder folder, - List messages) - { + List messages) { controller.messagesArrived(account, folder, messages, true); } - public void messagesArrived(Folder folder, List messages) - { + public void messagesArrived(Folder folder, List messages) { controller.messagesArrived(account, folder, messages, false); } - public void messagesRemoved(Folder folder, List messages) - { + public void messagesRemoved(Folder folder, List messages) { controller.messagesArrived(account, folder, messages, true); } - public void syncFolder(Folder folder) - { + public void syncFolder(Folder folder) { if (K9.DEBUG) Log.v(K9.LOG_TAG, "syncFolder(" + folder.getName() + ")"); final CountDownLatch latch = new CountDownLatch(1); - controller.synchronizeMailbox(account, folder.getName(), new MessagingListener() - { + controller.synchronizeMailbox(account, folder.getName(), new MessagingListener() { @Override public void synchronizeMailboxFinished(Account account, String folder, - int totalMessagesInMailbox, int numNewMessages) - { + int totalMessagesInMailbox, int numNewMessages) { latch.countDown(); } @Override public void synchronizeMailboxFailed(Account account, String folder, - String message) - { + String message) { latch.countDown(); } }, folder); if (K9.DEBUG) Log.v(K9.LOG_TAG, "syncFolder(" + folder.getName() + ") about to await latch release"); - try - { + try { latch.await(); if (K9.DEBUG) Log.v(K9.LOG_TAG, "syncFolder(" + folder.getName() + ") got latch release"); - } - catch (Exception e) - { + } catch (Exception e) { Log.e(K9.LOG_TAG, "Interrupted while awaiting latch release", e); } } @Override - public void sleep(TracingWakeLock wakeLock, long millis) - { + public void sleep(TracingWakeLock wakeLock, long millis) { SleepService.sleep(mApplication, millis, wakeLock, K9.PUSH_WAKE_LOCK_TIMEOUT); } - public void pushError(String errorMessage, Exception e) - { + public void pushError(String errorMessage, Exception e) { String errMess = errorMessage; - if (errMess == null && e != null) - { + if (errMess == null && e != null) { errMess = e.getMessage(); } controller.addErrorMessage(account, errMess, e); } - public String getPushState(String folderName) - { + public String getPushState(String folderName) { LocalFolder localFolder = null; - try - { + try { LocalStore localStore = account.getLocalStore(); localFolder = localStore.getFolder(folderName); localFolder.open(OpenMode.READ_WRITE); return localFolder.getPushState(); - } - catch (Exception e) - { + } catch (Exception e) { Log.e(K9.LOG_TAG, "Unable to get push state from account " + account.getDescription() + ", folder " + folderName, e); return null; - } - finally - { - if (localFolder != null) - { + } finally { + if (localFolder != null) { localFolder.close(); } } } - public void setPushActive(String folderName, boolean enabled) - { - for (MessagingListener l : controller.getListeners()) - { + public void setPushActive(String folderName, boolean enabled) { + for (MessagingListener l : controller.getListeners()) { l.setPushActive(account, folderName, enabled); } } @Override - public Context getContext() - { + public Context getContext() { return mApplication; } diff --git a/src/com/fsck/k9/controller/MessagingListener.java b/src/com/fsck/k9/controller/MessagingListener.java index 4efb39f24..bed951a2a 100644 --- a/src/com/fsck/k9/controller/MessagingListener.java +++ b/src/com/fsck/k9/controller/MessagingListener.java @@ -18,179 +18,138 @@ import java.util.List; * this interface use the @Override annotation in their implementations to avoid being caught by * changes in this class. */ -public class MessagingListener -{ +public class MessagingListener { public void searchStats(AccountStats stats) {} - public void accountStatusChanged(BaseAccount account, AccountStats stats) - { + public void accountStatusChanged(BaseAccount account, AccountStats stats) { } - public void accountSizeChanged(Account account, long oldSize, long newSize) - { + public void accountSizeChanged(Account account, long oldSize, long newSize) { } - public void listFoldersStarted(Account account) - { + public void listFoldersStarted(Account account) { } - public void listFolders(Account account, Folder[] folders) - { + public void listFolders(Account account, Folder[] folders) { } - public void listFoldersFailed(Account account, String message) - { + public void listFoldersFailed(Account account, String message) { } - public void listFoldersFinished(Account account) - { + public void listFoldersFinished(Account account) { } - public void listLocalMessagesStarted(Account account, String folder) - { + public void listLocalMessagesStarted(Account account, String folder) { } - public void listLocalMessages(Account account, String folder, Message[] messages) - { + public void listLocalMessages(Account account, String folder, Message[] messages) { } - public void listLocalMessagesAddMessages(Account account, String folder, List messages) - { + public void listLocalMessagesAddMessages(Account account, String folder, List messages) { } - public void listLocalMessagesUpdateMessage(Account account, String folder, Message message) - { + public void listLocalMessagesUpdateMessage(Account account, String folder, Message message) { } - public void listLocalMessagesRemoveMessage(Account account, String folder, Message message) - { + public void listLocalMessagesRemoveMessage(Account account, String folder, Message message) { } - public void listLocalMessagesFailed(Account account, String folder, String message) - { + public void listLocalMessagesFailed(Account account, String folder, String message) { } - public void listLocalMessagesFinished(Account account, String folder) - { + public void listLocalMessagesFinished(Account account, String folder) { } - public void synchronizeMailboxStarted(Account account, String folder) - { + public void synchronizeMailboxStarted(Account account, String folder) { } - public void synchronizeMailboxHeadersStarted(Account account, String folder) - { + public void synchronizeMailboxHeadersStarted(Account account, String folder) { } - public void synchronizeMailboxHeadersProgress(Account account, String folder, int completed, int total) - { + public void synchronizeMailboxHeadersProgress(Account account, String folder, int completed, int total) { } public void synchronizeMailboxHeadersFinished(Account account, String folder, - int totalMessagesInMailbox, int numNewMessages) - { + int totalMessagesInMailbox, int numNewMessages) { } public void synchronizeMailboxProgress(Account account, String folder, int completed, int total) {} - public void synchronizeMailboxNewMessage(Account account, String folder, Message message) - { + public void synchronizeMailboxNewMessage(Account account, String folder, Message message) { } - public void synchronizeMailboxAddOrUpdateMessage(Account account, String folder, Message message) - { + public void synchronizeMailboxAddOrUpdateMessage(Account account, String folder, Message message) { } - public void synchronizeMailboxRemovedMessage(Account account, String folder,Message message) - { + public void synchronizeMailboxRemovedMessage(Account account, String folder, Message message) { } public void synchronizeMailboxFinished(Account account, String folder, - int totalMessagesInMailbox, int numNewMessages) - { + int totalMessagesInMailbox, int numNewMessages) { } public void synchronizeMailboxFailed(Account account, String folder, - String message) - { + String message) { } - public void loadMessageForViewStarted(Account account, String folder, String uid) - { + public void loadMessageForViewStarted(Account account, String folder, String uid) { } public void loadMessageForViewHeadersAvailable(Account account, String folder, String uid, - Message message) - { + Message message) { } public void loadMessageForViewBodyAvailable(Account account, String folder, String uid, - Message message) - { + Message message) { } public void loadMessageForViewFinished(Account account, String folder, String uid, - Message message) - { + Message message) { } - public void loadMessageForViewFailed(Account account, String folder, String uid, Throwable t) - { + public void loadMessageForViewFailed(Account account, String folder, String uid, Throwable t) { } - public void checkMailStarted(Context context, Account account) - { + public void checkMailStarted(Context context, Account account) { } - public void checkMailFinished(Context context, Account account) - { + public void checkMailFinished(Context context, Account account) { } - public void checkMailFailed(Context context, Account account, String reason) - { + public void checkMailFailed(Context context, Account account, String reason) { } - public void sendPendingMessagesStarted(Account account) - { + public void sendPendingMessagesStarted(Account account) { } - public void sendPendingMessagesCompleted(Account account) - { + public void sendPendingMessagesCompleted(Account account) { } - public void sendPendingMessagesFailed(Account account) - { + public void sendPendingMessagesFailed(Account account) { } - public void messageDeleted(Account account, String folder, Message message) - { + public void messageDeleted(Account account, String folder, Message message) { } - public void emptyTrashCompleted(Account account) - { + public void emptyTrashCompleted(Account account) { } - public void folderStatusChanged(Account account, String folderName, int unreadMessageCount) - { + public void folderStatusChanged(Account account, String folderName, int unreadMessageCount) { } - public void folderStatusChanged(Account account, String folderName) - { + public void folderStatusChanged(Account account, String folderName) { } - public void systemStatusChanged() - { + public void systemStatusChanged() { } - public void messageUidChanged(Account account, String folder, String oldUid, String newUid) - { + public void messageUidChanged(Account account, String folder, String oldUid, String newUid) { } - public void setPushActive(Account account, String folderName, boolean enabled) - { + public void setPushActive(Account account, String folderName, boolean enabled) { } @@ -199,16 +158,14 @@ public class MessagingListener Message message, Part part, Object tag, - boolean requiresDownload) - { + boolean requiresDownload) { } public void loadAttachmentFinished( Account account, Message message, Part part, - Object tag) - { + Object tag) { } public void loadAttachmentFailed( @@ -216,8 +173,7 @@ public class MessagingListener Message message, Part part, Object tag, - String reason) - { + String reason) { } public void pendingCommandsProcessing(Account account) {} @@ -235,8 +191,7 @@ public class MessagingListener * @param moreCommandsToRun True if the controller will continue on to another command * immediately. */ - public void controllerCommandCompleted(boolean moreCommandsToRun) - { + public void controllerCommandCompleted(boolean moreCommandsToRun) { } } diff --git a/src/com/fsck/k9/crypto/Apg.java b/src/com/fsck/k9/crypto/Apg.java index ebdb883ca..3540faeae 100644 --- a/src/com/fsck/k9/crypto/Apg.java +++ b/src/com/fsck/k9/crypto/Apg.java @@ -25,8 +25,7 @@ import com.fsck.k9.mail.internet.MimeUtility; /** * APG integration. */ -public class Apg extends CryptoProvider -{ +public class Apg extends CryptoProvider { static final long serialVersionUID = 0x21071235; public static final String NAME = "apg"; @@ -44,8 +43,7 @@ public class Apg extends CryptoProvider public static final Uri CONTENT_URI_PUBLIC_KEY_RING_BY_EMAILS = Uri.parse("content://" + AUTHORITY + "/key_rings/public/emails/"); - public static class Intent - { + public static class Intent { public static final String DECRYPT = "org.thialfihar.android.apg.intent.DECRYPT"; public static final String ENCRYPT = "org.thialfihar.android.apg.intent.ENCRYPT"; public static final String DECRYPT_FILE = "org.thialfihar.android.apg.intent.DECRYPT_FILE"; @@ -88,8 +86,7 @@ public class Apg extends CryptoProvider Pattern.compile(".*?(-----BEGIN PGP SIGNED MESSAGE-----.*?-----BEGIN PGP SIGNATURE-----.*?-----END PGP SIGNATURE-----).*", Pattern.DOTALL); - public static Apg createInstance() - { + public static Apg createInstance() { return new Apg(); } @@ -100,23 +97,16 @@ public class Apg extends CryptoProvider * @return whether a suitable version of APG was found */ @Override - public boolean isAvailable(Context context) - { - try - { + public boolean isAvailable(Context context) { + try { PackageInfo pi = context.getPackageManager().getPackageInfo(mApgPackageName, 0); - if (pi.versionCode >= mMinRequiredVersion) - { + if (pi.versionCode >= mMinRequiredVersion) { return true; - } - else - { + } else { Toast.makeText(context, R.string.error_apg_version_not_supported, Toast.LENGTH_SHORT).show(); } - } - catch (NameNotFoundException e) - { + } catch (NameNotFoundException e) { // not found } @@ -131,17 +121,13 @@ public class Apg extends CryptoProvider * @return success or failure */ @Override - public boolean selectSecretKey(Activity activity, PgpData pgpData) - { + public boolean selectSecretKey(Activity activity, PgpData pgpData) { android.content.Intent intent = new android.content.Intent(Intent.SELECT_SECRET_KEY); intent.putExtra(EXTRA_INTENT_VERSION, INTENT_VERSION); - try - { + try { activity.startActivityForResult(intent, Apg.SELECT_SECRET_KEY); return true; - } - catch (ActivityNotFoundException e) - { + } catch (ActivityNotFoundException e) { Toast.makeText(activity, R.string.error_activity_not_found, Toast.LENGTH_SHORT).show(); @@ -158,67 +144,51 @@ public class Apg extends CryptoProvider * @return success or failure */ @Override - public boolean selectEncryptionKeys(Activity activity, String emails, PgpData pgpData) - { + public boolean selectEncryptionKeys(Activity activity, String emails, PgpData pgpData) { android.content.Intent intent = new android.content.Intent(Apg.Intent.SELECT_PUBLIC_KEYS); intent.putExtra(EXTRA_INTENT_VERSION, INTENT_VERSION); long[] initialKeyIds = null; - if (!pgpData.hasEncryptionKeys()) - { + if (!pgpData.hasEncryptionKeys()) { Vector keyIds = new Vector(); - if (pgpData.hasSignatureKey()) - { + if (pgpData.hasSignatureKey()) { keyIds.add(pgpData.getSignatureKeyId()); } - try - { + try { Uri contentUri = Uri.withAppendedPath( Apg.CONTENT_URI_PUBLIC_KEY_RING_BY_EMAILS, emails); Cursor c = activity.getContentResolver().query(contentUri, new String[] { "master_key_id" }, null, null, null); - if (c != null) - { - while (c.moveToNext()) - { + if (c != null) { + while (c.moveToNext()) { keyIds.add(c.getLong(0)); } } - if (c != null) - { + if (c != null) { c.close(); } - } - catch (SecurityException e) - { + } catch (SecurityException e) { Toast.makeText(activity, activity.getResources().getString(R.string.insufficient_apg_permissions), Toast.LENGTH_LONG).show(); } - if (keyIds.size() > 0) - { + if (keyIds.size() > 0) { initialKeyIds = new long[keyIds.size()]; - for (int i = 0, size = keyIds.size(); i < size; ++i) - { + for (int i = 0, size = keyIds.size(); i < size; ++i) { initialKeyIds[i] = keyIds.get(i); } } - } - else - { + } else { initialKeyIds = pgpData.getEncryptionKeys(); } intent.putExtra(Apg.EXTRA_SELECTION, initialKeyIds); - try - { + try { activity.startActivityForResult(intent, Apg.SELECT_PUBLIC_KEYS); return true; - } - catch (ActivityNotFoundException e) - { + } catch (ActivityNotFoundException e) { Toast.makeText(activity, R.string.error_activity_not_found, Toast.LENGTH_SHORT).show(); @@ -234,32 +204,25 @@ public class Apg extends CryptoProvider * @return key ids */ @Override - public long[] getSecretKeyIdsFromEmail(Context context, String email) - { + public long[] getSecretKeyIdsFromEmail(Context context, String email) { long ids[] = null; - try - { + try { Uri contentUri = Uri.withAppendedPath(Apg.CONTENT_URI_SECRET_KEY_RING_BY_EMAILS, email); Cursor c = context.getContentResolver().query(contentUri, new String[] { "master_key_id" }, null, null, null); - if (c != null && c.getCount() > 0) - { + if (c != null && c.getCount() > 0) { ids = new long[c.getCount()]; - while (c.moveToNext()) - { + while (c.moveToNext()) { ids[c.getPosition()] = c.getLong(0); } } - if (c != null) - { + if (c != null) { c.close(); } - } - catch (SecurityException e) - { + } catch (SecurityException e) { Toast.makeText(context, context.getResources().getString(R.string.insufficient_apg_permissions), Toast.LENGTH_LONG).show(); @@ -276,36 +239,29 @@ public class Apg extends CryptoProvider * @return user id */ @Override - public String getUserId(Context context, long keyId) - { + public String getUserId(Context context, long keyId) { String userId = null; - try - { + try { Uri contentUri = ContentUris.withAppendedId( Apg.CONTENT_URI_SECRET_KEY_RING_BY_KEY_ID, keyId); Cursor c = context.getContentResolver().query(contentUri, new String[] { "user_id" }, null, null, null); - if (c != null && c.moveToFirst()) - { + if (c != null && c.moveToFirst()) { userId = c.getString(0); } - if (c != null) - { + if (c != null) { c.close(); } - } - catch (SecurityException e) - { + } catch (SecurityException e) { Toast.makeText(context, context.getResources().getString(R.string.insufficient_apg_permissions), Toast.LENGTH_LONG).show(); } - if (userId == null) - { + if (userId == null) { userId = context.getString(R.string.unknown_crypto_signature_user_id); } return userId; @@ -322,69 +278,61 @@ public class Apg extends CryptoProvider */ @Override public boolean onActivityResult(Activity activity, int requestCode, int resultCode, - android.content.Intent data, PgpData pgpData) - { - switch (requestCode) - { - case Apg.SELECT_SECRET_KEY: - if (resultCode != Activity.RESULT_OK || data == null) - { - break; - } - pgpData.setSignatureKeyId(data.getLongExtra(Apg.EXTRA_KEY_ID, 0)); - pgpData.setSignatureUserId(data.getStringExtra(Apg.EXTRA_USER_ID)); - ((MessageCompose) activity).updateEncryptLayout(); + android.content.Intent data, PgpData pgpData) { + switch (requestCode) { + case Apg.SELECT_SECRET_KEY: + if (resultCode != Activity.RESULT_OK || data == null) { break; + } + pgpData.setSignatureKeyId(data.getLongExtra(Apg.EXTRA_KEY_ID, 0)); + pgpData.setSignatureUserId(data.getStringExtra(Apg.EXTRA_USER_ID)); + ((MessageCompose) activity).updateEncryptLayout(); + break; - case Apg.SELECT_PUBLIC_KEYS: - if (resultCode != Activity.RESULT_OK || data == null) - { - pgpData.setEncryptionKeys(null); - ((MessageCompose) activity).onEncryptionKeySelectionDone(); - break; - } - pgpData.setEncryptionKeys(data.getLongArrayExtra(Apg.EXTRA_SELECTION)); + case Apg.SELECT_PUBLIC_KEYS: + if (resultCode != Activity.RESULT_OK || data == null) { + pgpData.setEncryptionKeys(null); ((MessageCompose) activity).onEncryptionKeySelectionDone(); break; + } + pgpData.setEncryptionKeys(data.getLongArrayExtra(Apg.EXTRA_SELECTION)); + ((MessageCompose) activity).onEncryptionKeySelectionDone(); + break; - case Apg.ENCRYPT_MESSAGE: - if (resultCode != Activity.RESULT_OK || data == null) - { - pgpData.setEncryptionKeys(null); - ((MessageCompose) activity).onEncryptDone(); - break; - } - pgpData.setEncryptedData(data.getStringExtra(Apg.EXTRA_ENCRYPTED_MESSAGE)); - // this was a stupid bug in an earlier version, just gonna leave this in for an APG - // version or two - if (pgpData.getEncryptedData() == null) - { - pgpData.setEncryptedData(data.getStringExtra(Apg.EXTRA_DECRYPTED_MESSAGE)); - } - if (pgpData.getEncryptedData() != null) - { - ((MessageCompose) activity).onEncryptDone(); - } + case Apg.ENCRYPT_MESSAGE: + if (resultCode != Activity.RESULT_OK || data == null) { + pgpData.setEncryptionKeys(null); + ((MessageCompose) activity).onEncryptDone(); break; + } + pgpData.setEncryptedData(data.getStringExtra(Apg.EXTRA_ENCRYPTED_MESSAGE)); + // this was a stupid bug in an earlier version, just gonna leave this in for an APG + // version or two + if (pgpData.getEncryptedData() == null) { + pgpData.setEncryptedData(data.getStringExtra(Apg.EXTRA_DECRYPTED_MESSAGE)); + } + if (pgpData.getEncryptedData() != null) { + ((MessageCompose) activity).onEncryptDone(); + } + break; - case Apg.DECRYPT_MESSAGE: - if (resultCode != Activity.RESULT_OK || data == null) - { - break; - } - - pgpData.setSignatureUserId(data.getStringExtra(Apg.EXTRA_SIGNATURE_USER_ID)); - pgpData.setSignatureKeyId(data.getLongExtra(Apg.EXTRA_SIGNATURE_KEY_ID, 0)); - pgpData.setSignatureSuccess(data.getBooleanExtra(Apg.EXTRA_SIGNATURE_SUCCESS, false)); - pgpData.setSignatureUnknown(data.getBooleanExtra(Apg.EXTRA_SIGNATURE_UNKNOWN, false)); - - pgpData.setDecryptedData(data.getStringExtra(Apg.EXTRA_DECRYPTED_MESSAGE)); - ((MessageView) activity).onDecryptDone(); - + case Apg.DECRYPT_MESSAGE: + if (resultCode != Activity.RESULT_OK || data == null) { break; + } - default: - return false; + pgpData.setSignatureUserId(data.getStringExtra(Apg.EXTRA_SIGNATURE_USER_ID)); + pgpData.setSignatureKeyId(data.getLongExtra(Apg.EXTRA_SIGNATURE_KEY_ID, 0)); + pgpData.setSignatureSuccess(data.getBooleanExtra(Apg.EXTRA_SIGNATURE_SUCCESS, false)); + pgpData.setSignatureUnknown(data.getBooleanExtra(Apg.EXTRA_SIGNATURE_UNKNOWN, false)); + + pgpData.setDecryptedData(data.getStringExtra(Apg.EXTRA_DECRYPTED_MESSAGE)); + ((MessageView) activity).onDecryptDone(); + + break; + + default: + return false; } return true; @@ -399,21 +347,17 @@ public class Apg extends CryptoProvider * @return success or failure */ @Override - public boolean encrypt(Activity activity, String data, PgpData pgpData) - { + public boolean encrypt(Activity activity, String data, PgpData pgpData) { android.content.Intent intent = new android.content.Intent(Intent.ENCRYPT_AND_RETURN); intent.putExtra(EXTRA_INTENT_VERSION, INTENT_VERSION); intent.setType("text/plain"); intent.putExtra(Apg.EXTRA_TEXT, data); intent.putExtra(Apg.EXTRA_ENCRYPTION_KEY_IDS, pgpData.getEncryptionKeys()); intent.putExtra(Apg.EXTRA_SIGNATURE_KEY_ID, pgpData.getSignatureKeyId()); - try - { + try { activity.startActivityForResult(intent, Apg.ENCRYPT_MESSAGE); return true; - } - catch (ActivityNotFoundException e) - { + } catch (ActivityNotFoundException e) { Toast.makeText(activity, R.string.error_activity_not_found, Toast.LENGTH_SHORT).show(); @@ -430,23 +374,18 @@ public class Apg extends CryptoProvider * @return success or failure */ @Override - public boolean decrypt(Activity activity, String data, PgpData pgpData) - { + public boolean decrypt(Activity activity, String data, PgpData pgpData) { android.content.Intent intent = new android.content.Intent(Apg.Intent.DECRYPT_AND_RETURN); intent.putExtra(EXTRA_INTENT_VERSION, INTENT_VERSION); intent.setType("text/plain"); - if (data == null) - { + if (data == null) { return false; } - try - { + try { intent.putExtra(EXTRA_TEXT, data); activity.startActivityForResult(intent, Apg.DECRYPT_MESSAGE); return true; - } - catch (ActivityNotFoundException e) - { + } catch (ActivityNotFoundException e) { Toast.makeText(activity, R.string.error_activity_not_found, Toast.LENGTH_SHORT).show(); @@ -455,29 +394,22 @@ public class Apg extends CryptoProvider } @Override - public boolean isEncrypted(Message message) - { + public boolean isEncrypted(Message message) { String data = null; - try - { + try { Part part = MimeUtility.findFirstPartByMimeType(message, "text/plain"); - if (part == null) - { + if (part == null) { part = MimeUtility.findFirstPartByMimeType(message, "text/html"); } - if (part != null) - { + if (part != null) { data = MimeUtility.getTextFromPart(part); } - } - catch (MessagingException e) - { + } catch (MessagingException e) { // guess not... // TODO: maybe log this? } - if (data == null) - { + if (data == null) { return false; } @@ -486,29 +418,22 @@ public class Apg extends CryptoProvider } @Override - public boolean isSigned(Message message) - { + public boolean isSigned(Message message) { String data = null; - try - { + try { Part part = MimeUtility.findFirstPartByMimeType(message, "text/plain"); - if (part == null) - { + if (part == null) { part = MimeUtility.findFirstPartByMimeType(message, "text/html"); } - if (part != null) - { + if (part != null) { data = MimeUtility.getTextFromPart(part); } - } - catch (MessagingException e) - { + } catch (MessagingException e) { // guess not... // TODO: maybe log this? } - if (data == null) - { + if (data == null) { return false; } @@ -522,8 +447,7 @@ public class Apg extends CryptoProvider * @return provider name */ @Override - public String getName() - { + public String getName() { return NAME; } @@ -533,15 +457,12 @@ public class Apg extends CryptoProvider * @return success or failure */ @Override - public boolean test(Context context) - { - if (!isAvailable(context)) - { + public boolean test(Context context) { + if (!isAvailable(context)) { return false; } - try - { + try { // try out one content provider to check permissions Uri contentUri = ContentUris.withAppendedId( Apg.CONTENT_URI_SECRET_KEY_RING_BY_KEY_ID, @@ -549,13 +470,10 @@ public class Apg extends CryptoProvider Cursor c = context.getContentResolver().query(contentUri, new String[] { "user_id" }, null, null, null); - if (c != null) - { + if (c != null) { c.close(); } - } - catch (SecurityException e) - { + } catch (SecurityException e) { // if there was a problem, then let the user know, this will not stop K9/APG from // working, but some features won't be available, so we can still return "true" Toast.makeText(context, diff --git a/src/com/fsck/k9/crypto/CryptoProvider.java b/src/com/fsck/k9/crypto/CryptoProvider.java index 0ed25ca6b..79401b154 100644 --- a/src/com/fsck/k9/crypto/CryptoProvider.java +++ b/src/com/fsck/k9/crypto/CryptoProvider.java @@ -11,8 +11,7 @@ import com.fsck.k9.mail.Message; * It currently also stores the results of such encryption or decryption. * TODO: separate the storage from the provider */ -abstract public class CryptoProvider -{ +abstract public class CryptoProvider { static final long serialVersionUID = 0x21071234; abstract public boolean isAvailable(Context context); @@ -29,10 +28,8 @@ abstract public class CryptoProvider abstract public String getName(); abstract public boolean test(Context context); - public static CryptoProvider createInstance(String name) - { - if (Apg.NAME.equals(name)) - { + public static CryptoProvider createInstance(String name) { + if (Apg.NAME.equals(name)) { return Apg.createInstance(); } diff --git a/src/com/fsck/k9/crypto/None.java b/src/com/fsck/k9/crypto/None.java index 5b14a6fb5..eb83d9261 100644 --- a/src/com/fsck/k9/crypto/None.java +++ b/src/com/fsck/k9/crypto/None.java @@ -9,86 +9,72 @@ import com.fsck.k9.mail.Message; * Dummy CryptoProvider for when cryptography is disabled. It is never "available" and doesn't * do anything. */ -public class None extends CryptoProvider -{ +public class None extends CryptoProvider { static final long serialVersionUID = 0x21071230; public static final String NAME = ""; - public static None createInstance() - { + public static None createInstance() { return new None(); } @Override - public boolean isAvailable(Context context) - { + public boolean isAvailable(Context context) { return false; } @Override - public boolean selectSecretKey(Activity activity, PgpData pgpData) - { + public boolean selectSecretKey(Activity activity, PgpData pgpData) { return false; } @Override - public boolean selectEncryptionKeys(Activity activity, String emails, PgpData pgpData) - { + public boolean selectEncryptionKeys(Activity activity, String emails, PgpData pgpData) { return false; } @Override - public long[] getSecretKeyIdsFromEmail(Context context, String email) - { + public long[] getSecretKeyIdsFromEmail(Context context, String email) { return null; } @Override - public String getUserId(Context context, long keyId) - { + public String getUserId(Context context, long keyId) { return null; } @Override public boolean onActivityResult(Activity activity, int requestCode, int resultCode, - android.content.Intent data, PgpData pgpData) - { + android.content.Intent data, PgpData pgpData) { return false; } @Override - public boolean encrypt(Activity activity, String data, PgpData pgpData) - { + public boolean encrypt(Activity activity, String data, PgpData pgpData) { return false; } @Override - public boolean decrypt(Activity activity, String data, PgpData pgpData) - { + public boolean decrypt(Activity activity, String data, PgpData pgpData) { return false; } @Override - public boolean isEncrypted(Message message) - { + public boolean isEncrypted(Message message) { return false; } @Override - public boolean isSigned(Message message) - { + public boolean isSigned(Message message) { return false; } @Override - public String getName() - { + public String getName() { return NAME; } @Override - public boolean test(Context context) - { + public boolean test(Context context) { return true; } } diff --git a/src/com/fsck/k9/crypto/PgpData.java b/src/com/fsck/k9/crypto/PgpData.java index a52622cc5..8573fae7c 100644 --- a/src/com/fsck/k9/crypto/PgpData.java +++ b/src/com/fsck/k9/crypto/PgpData.java @@ -2,8 +2,7 @@ package com.fsck.k9.crypto; import java.io.Serializable; -public class PgpData implements Serializable -{ +public class PgpData implements Serializable { private static final long serialVersionUID = 6314045536470848410L; protected long mEncryptionKeyIds[] = null; protected long mSignatureKeyId = 0; @@ -13,83 +12,67 @@ public class PgpData implements Serializable protected String mDecryptedData = null; protected String mEncryptedData = null; - public void setSignatureKeyId(long keyId) - { + public void setSignatureKeyId(long keyId) { mSignatureKeyId = keyId; } - public long getSignatureKeyId() - { + public long getSignatureKeyId() { return mSignatureKeyId; } - public void setEncryptionKeys(long keyIds[]) - { + public void setEncryptionKeys(long keyIds[]) { mEncryptionKeyIds = keyIds; } - public long[] getEncryptionKeys() - { + public long[] getEncryptionKeys() { return mEncryptionKeyIds; } - public boolean hasSignatureKey() - { + public boolean hasSignatureKey() { return mSignatureKeyId != 0; } - public boolean hasEncryptionKeys() - { + public boolean hasEncryptionKeys() { return (mEncryptionKeyIds != null) && (mEncryptionKeyIds.length > 0); } - public String getEncryptedData() - { + public String getEncryptedData() { return mEncryptedData; } - public void setEncryptedData(String data) - { + public void setEncryptedData(String data) { mEncryptedData = data; } - public String getDecryptedData() - { + public String getDecryptedData() { return mDecryptedData; } - public void setDecryptedData(String data) - { + public void setDecryptedData(String data) { mDecryptedData = data; } - public void setSignatureUserId(String userId) - { + public void setSignatureUserId(String userId) { mSignatureUserId = userId; } - public String getSignatureUserId() - { + public String getSignatureUserId() { return mSignatureUserId; } - public boolean getSignatureSuccess() - { + public boolean getSignatureSuccess() { return mSignatureSuccess; } - public void setSignatureSuccess(boolean success) - { + public void setSignatureSuccess(boolean success) { mSignatureSuccess = success; } - public boolean getSignatureUnknown() - { + public boolean getSignatureUnknown() { return mSignatureUnknown; } - public void setSignatureUnknown(boolean unknown) - { + public void setSignatureUnknown(boolean unknown) { mSignatureUnknown = unknown; } } diff --git a/src/com/fsck/k9/helper/AutoSyncHelper.java b/src/com/fsck/k9/helper/AutoSyncHelper.java index 829130a06..84b728d5d 100644 --- a/src/com/fsck/k9/helper/AutoSyncHelper.java +++ b/src/com/fsck/k9/helper/AutoSyncHelper.java @@ -7,8 +7,7 @@ import android.util.Log; /** * Helper class to get the current state of the auto-sync setting. */ -public class AutoSyncHelper -{ +public class AutoSyncHelper { /** * False, if we never tried to load the class for this SDK version. * True, otherwise. @@ -34,8 +33,7 @@ public class AutoSyncHelper * @return the IAutoSync object for this SDK version, or null if something * went wrong. */ - private static IAutoSync loadAutoSync() - { + private static IAutoSync loadAutoSync() { /* * We're trying to load the class for this SDK version. If anything * goes wrong after this point, we don't want to try again. @@ -49,48 +47,33 @@ public class AutoSyncHelper int sdkVersion = Integer.parseInt(Build.VERSION.SDK); String className = null; - if (sdkVersion == Build.VERSION_CODES.CUPCAKE) - { + if (sdkVersion == Build.VERSION_CODES.CUPCAKE) { className = "com.fsck.k9.helper.AutoSyncSdk3"; - } - else if (sdkVersion == Build.VERSION_CODES.DONUT) - { + } else if (sdkVersion == Build.VERSION_CODES.DONUT) { className = "com.fsck.k9.helper.AutoSyncSdk4"; - } - else if (sdkVersion >= Build.VERSION_CODES.ECLAIR) - { + } else if (sdkVersion >= Build.VERSION_CODES.ECLAIR) { className = "com.fsck.k9.helper.AutoSyncSdk5"; } /* * Find the required class by name and instantiate it. */ - try - { - Class clazz = + try { + Class clazz = Class.forName(className).asSubclass(IAutoSync.class); IAutoSync autoSync = clazz.newInstance(); autoSync.initialize(K9.app); return autoSync; - } - catch (ClassNotFoundException e) - { + } catch (ClassNotFoundException e) { Log.e(K9.LOG_TAG, "Couldn't find class: " + className, e); - } - catch (InstantiationException e) - { + } catch (InstantiationException e) { Log.e(K9.LOG_TAG, "Couldn't instantiate class: " + className, e); - } - catch (IllegalAccessException e) - { + } catch (IllegalAccessException e) { Log.e(K9.LOG_TAG, "Couldn't access class: " + className, e); - } - catch (NoSuchMethodException e) - { - if (K9.DEBUG) - { + } catch (NoSuchMethodException e) { + if (K9.DEBUG) { Log.d(K9.LOG_TAG, "Couldn't load method to get auto-sync state", e); } } @@ -104,10 +87,8 @@ public class AutoSyncHelper * @return true, if calls to getMasterSyncAutomatically() will return the * state of the auto-sync setting. false, otherwise. */ - public static boolean isAvailable() - { - if (!sChecked) - { + public static boolean isAvailable() { + if (!sChecked) { sAutoSync = loadAutoSync(); } return (sAutoSync != null); @@ -119,15 +100,12 @@ public class AutoSyncHelper * @return the state of the auto-sync setting. * @see IAutoSync */ - public static boolean getMasterSyncAutomatically() - { - if (!sChecked) - { + public static boolean getMasterSyncAutomatically() { + if (!sChecked) { sAutoSync = loadAutoSync(); } - if (sAutoSync == null) - { + if (sAutoSync == null) { throw new RuntimeException( "Called getMasterSyncAutomatically() before checking if it's available."); } diff --git a/src/com/fsck/k9/helper/AutoSyncSdk3.java b/src/com/fsck/k9/helper/AutoSyncSdk3.java index a317a4781..7fc636199 100644 --- a/src/com/fsck/k9/helper/AutoSyncSdk3.java +++ b/src/com/fsck/k9/helper/AutoSyncSdk3.java @@ -6,13 +6,11 @@ import android.content.ContentResolver; import android.content.Context; import android.os.Handler; -public class AutoSyncSdk3 implements IAutoSync -{ +public class AutoSyncSdk3 implements IAutoSync { private Method mGetListenForNetworkTickles; private Object mQueryMap; - public void initialize(Context context) throws NoSuchMethodException - { + public void initialize(Context context) throws NoSuchMethodException { /* * There's no documented/official way to query the state of the * auto-sync setting for a normal application in SDK 1.5/API 3. @@ -21,27 +19,20 @@ public class AutoSyncSdk3 implements IAutoSync * can call its getListenForNetworkTickles() method. This will return * the current auto-sync state. */ - try - { + try { Class clazz = Class.forName("android.provider.Sync$Settings$QueryMap"); Constructor c = clazz.getConstructor(ContentResolver.class, boolean.class, Handler.class); mQueryMap = c.newInstance(context.getContentResolver(), true, null); mGetListenForNetworkTickles = mQueryMap.getClass().getMethod("getListenForNetworkTickles"); - } - catch (Exception e) - { + } catch (Exception e) { throw new NoSuchMethodException(); } } - public boolean getMasterSyncAutomatically() - { - try - { + public boolean getMasterSyncAutomatically() { + try { return (Boolean) mGetListenForNetworkTickles.invoke(mQueryMap); - } - catch (Exception e) - { + } catch (Exception e) { return false; } } diff --git a/src/com/fsck/k9/helper/AutoSyncSdk4.java b/src/com/fsck/k9/helper/AutoSyncSdk4.java index f0bb766c3..d5c9ac89b 100644 --- a/src/com/fsck/k9/helper/AutoSyncSdk4.java +++ b/src/com/fsck/k9/helper/AutoSyncSdk4.java @@ -8,13 +8,11 @@ import android.content.ContentResolver; import android.content.Context; import android.util.Log; -public class AutoSyncSdk4 implements IAutoSync -{ +public class AutoSyncSdk4 implements IAutoSync { private Method mGetListenForNetworkTickles; private Object mContentService; - public void initialize(Context context) throws NoSuchMethodException - { + public void initialize(Context context) throws NoSuchMethodException { /* * There's no documented/official way to query the state of the * auto-sync setting for a normal application in SDK 1.6/API 4. @@ -23,26 +21,19 @@ public class AutoSyncSdk4 implements IAutoSync * getListenForNetworkTickles() method. This will return the current * auto-sync state. */ - try - { + try { Method getContentService = ContentResolver.class.getMethod("getContentService"); mContentService = getContentService.invoke(null); mGetListenForNetworkTickles = mContentService.getClass().getMethod("getListenForNetworkTickles"); - } - catch (Exception e) - { + } catch (Exception e) { throw new NoSuchMethodException(); } } - public boolean getMasterSyncAutomatically() - { - try - { + public boolean getMasterSyncAutomatically() { + try { return (Boolean) mGetListenForNetworkTickles.invoke(mContentService); - } - catch (Exception e) - { + } catch (Exception e) { Log.e(K9.LOG_TAG, "Could not query for network tickle", e); return true; } diff --git a/src/com/fsck/k9/helper/AutoSyncSdk5.java b/src/com/fsck/k9/helper/AutoSyncSdk5.java index 1468cdcf0..d6e6d684d 100644 --- a/src/com/fsck/k9/helper/AutoSyncSdk5.java +++ b/src/com/fsck/k9/helper/AutoSyncSdk5.java @@ -3,15 +3,12 @@ package com.fsck.k9.helper; import android.content.ContentResolver; import android.content.Context; -public class AutoSyncSdk5 implements IAutoSync -{ - public void initialize(Context context) throws NoSuchMethodException - { +public class AutoSyncSdk5 implements IAutoSync { + public void initialize(Context context) throws NoSuchMethodException { // Nothing to do here } - public boolean getMasterSyncAutomatically() - { + public boolean getMasterSyncAutomatically() { /* * SDK 2.0/API 5 introduced an official method to query the auto-sync * state. diff --git a/src/com/fsck/k9/helper/Contacts.java b/src/com/fsck/k9/helper/Contacts.java index 31f5f53d9..f413639cd 100644 --- a/src/com/fsck/k9/helper/Contacts.java +++ b/src/com/fsck/k9/helper/Contacts.java @@ -20,8 +20,7 @@ import com.fsck.k9.mail.Address; * @see ContactsSdk3_4 * @see ContactsSdk5 */ -public abstract class Contacts -{ +public abstract class Contacts { /** * Instance of the SDK specific class that interfaces with the contacts * API. @@ -34,10 +33,8 @@ public abstract class Contacts * @param context A {@link Context} instance. * @return Appropriate {@link Contacts} instance for this device. */ - public static Contacts getInstance(Context context) - { - if (sInstance == null) - { + public static Contacts getInstance(Context context) { + if (sInstance == null) { /* * Check the version of the SDK we are running on. Choose an * implementation class designed for that version of the SDK. @@ -45,56 +42,38 @@ public abstract class Contacts int sdkVersion = Integer.parseInt(Build.VERSION.SDK); String className = null; - if (sdkVersion <= Build.VERSION_CODES.DONUT) - { + if (sdkVersion <= Build.VERSION_CODES.DONUT) { className = "com.fsck.k9.helper.ContactsSdk3_4"; - } - else if (sdkVersion <= Build.VERSION_CODES.ECLAIR_MR1) - { + } else if (sdkVersion <= Build.VERSION_CODES.ECLAIR_MR1) { /* * The new API was introduced with SDK 5. But Android versions < 2.2 * need some additional code to be able to search for phonetic names. */ className = "com.fsck.k9.helper.ContactsSdk5p"; - } - else - { + } else { className = "com.fsck.k9.helper.ContactsSdk5"; } /* * Find the required class by name and instantiate it. */ - try - { - Class clazz = + try { + Class clazz = Class.forName(className).asSubclass(Contacts.class); - Constructor constructor = clazz.getConstructor(Context.class); + Constructor constructor = clazz.getConstructor(Context.class); sInstance = constructor.newInstance(context); - } - catch (ClassNotFoundException e) - { + } catch (ClassNotFoundException e) { Log.e(K9.LOG_TAG, "Couldn't find class: " + className, e); - } - catch (InstantiationException e) - { + } catch (InstantiationException e) { Log.e(K9.LOG_TAG, "Couldn't instantiate class: " + className, e); - } - catch (IllegalAccessException e) - { + } catch (IllegalAccessException e) { Log.e(K9.LOG_TAG, "Couldn't access class: " + className, e); - } - catch (NoSuchMethodException e) - { + } catch (NoSuchMethodException e) { Log.e(K9.LOG_TAG, "Couldn't find constructor of class: " + className, e); - } - catch (IllegalArgumentException e) - { + } catch (IllegalArgumentException e) { Log.e(K9.LOG_TAG, "Wrong arguments for constructor of class: " + className, e); - } - catch (InvocationTargetException e) - { + } catch (InvocationTargetException e) { Log.e(K9.LOG_TAG, "Couldn't invoke constructor of class: " + className, e); } } @@ -111,8 +90,7 @@ public abstract class Contacts * * @param context A {@link Context} instance. */ - protected Contacts(Context context) - { + protected Contacts(Context context) { mContext = context; mContentResolver = context.getContentResolver(); } diff --git a/src/com/fsck/k9/helper/ContactsSdk3_4.java b/src/com/fsck/k9/helper/ContactsSdk3_4.java index a6e03e7c3..908664cf7 100644 --- a/src/com/fsck/k9/helper/ContactsSdk3_4.java +++ b/src/com/fsck/k9/helper/ContactsSdk3_4.java @@ -13,8 +13,7 @@ import com.fsck.k9.mail.Address; * @see android.provider.Contacts */ @SuppressWarnings("deprecation") -public class ContactsSdk3_4 extends com.fsck.k9.helper.Contacts -{ +public class ContactsSdk3_4 extends com.fsck.k9.helper.Contacts { /** * The order in which the search results are returned by * {@link #searchContacts(CharSequence)}. @@ -31,8 +30,7 @@ public class ContactsSdk3_4 extends com.fsck.k9.helper.Contacts * {@link com.fsck.k9.EmailAddressAdapter} or more specificly by * {@link android.widget.ResourceCursorAdapter}. */ - private static final String PROJECTION[] = - { + private static final String PROJECTION[] = { Contacts.ContactMethods._ID, Contacts.ContactMethods.DISPLAY_NAME, Contacts.ContactMethods.DATA, @@ -58,14 +56,12 @@ public class ContactsSdk3_4 extends com.fsck.k9.helper.Contacts private static final int CONTACT_ID_INDEX = 3; - public ContactsSdk3_4(final Context context) - { + public ContactsSdk3_4(final Context context) { super(context); } @Override - public void createContact(final Address email) - { + public void createContact(final Address email) { final Uri contactUri = Uri.fromParts("mailto", email.getAddress(), null); final Intent contactIntent = new Intent(Contacts.Intents.SHOW_OR_CREATE_CONTACT); @@ -77,8 +73,7 @@ public class ContactsSdk3_4 extends com.fsck.k9.helper.Contacts // Only provide personal name hint if we have one final String senderPersonal = email.getPersonal(); - if (senderPersonal != null) - { + if (senderPersonal != null) { contactIntent.putExtra(Contacts.Intents.Insert.NAME, senderPersonal); } @@ -86,8 +81,7 @@ public class ContactsSdk3_4 extends com.fsck.k9.helper.Contacts } @Override - public String getOwnerName() - { + public String getOwnerName() { String name = null; final Cursor c = mContentResolver.query( Uri.withAppendedPath(Contacts.People.CONTENT_URI, "owner"), @@ -96,10 +90,8 @@ public class ContactsSdk3_4 extends com.fsck.k9.helper.Contacts null, null); - if (c != null) - { - if (c.getCount() > 0) - { + if (c != null) { + if (c.getCount() > 0) { c.moveToFirst(); name = c.getString(0); // owner's display name } @@ -110,16 +102,13 @@ public class ContactsSdk3_4 extends com.fsck.k9.helper.Contacts } @Override - public boolean isInContacts(final String emailAddress) - { + public boolean isInContacts(final String emailAddress) { boolean result = false; final Cursor c = getContactByAddress(emailAddress); - if (c != null) - { - if (c.getCount() > 0) - { + if (c != null) { + if (c.getCount() > 0) { result = true; } c.close(); @@ -129,17 +118,13 @@ public class ContactsSdk3_4 extends com.fsck.k9.helper.Contacts } @Override - public Cursor searchContacts(final CharSequence constraint) - { + public Cursor searchContacts(final CharSequence constraint) { final String where; final String[] args; - if (constraint == null) - { + if (constraint == null) { where = Contacts.ContactMethods.KIND + " = " + Contacts.KIND_EMAIL; args = null; - } - else - { + } else { where = Contacts.ContactMethods.KIND + " = " + Contacts.KIND_EMAIL + " AND " + "(" + @@ -170,8 +155,7 @@ public class ContactsSdk3_4 extends com.fsck.k9.helper.Contacts args, SORT_ORDER); - if (c != null) - { + if (c != null) { /* * To prevent expensive execution in the UI thread: * Cursors get lazily executed, so if you don't call anything on @@ -187,20 +171,16 @@ public class ContactsSdk3_4 extends com.fsck.k9.helper.Contacts } @Override - public String getNameForAddress(String address) - { - if (address == null) - { + public String getNameForAddress(String address) { + if (address == null) { return null; } final Cursor c = getContactByAddress(address); String name = null; - if (c != null) - { - if (c.getCount() > 0) - { + if (c != null) { + if (c.getCount() > 0) { c.moveToFirst(); name = getName(c); } @@ -211,29 +191,23 @@ public class ContactsSdk3_4 extends com.fsck.k9.helper.Contacts } @Override - public String getName(Cursor c) - { + public String getName(Cursor c) { return c.getString(NAME_INDEX); } @Override - public String getEmail(Cursor c) - { + public String getEmail(Cursor c) { return c.getString(EMAIL_INDEX); } @Override - public void markAsContacted(final Address[] addresses) - { + public void markAsContacted(final Address[] addresses) { //TODO: Optimize! Potentially a lot of database queries - for (final Address address : addresses) - { + for (final Address address : addresses) { final Cursor c = getContactByAddress(address.getAddress()); - if (c != null) - { - if (c.getCount() > 0) - { + if (c != null) { + if (c.getCount() > 0) { c.moveToFirst(); final long personId = c.getLong(CONTACT_ID_INDEX); Contacts.People.markAsContacted(mContentResolver, personId); @@ -251,8 +225,7 @@ public class ContactsSdk3_4 extends com.fsck.k9.helper.Contacts * @return A {@link Cursor} instance that can be used to fetch information * about the contact with the given email address */ - private Cursor getContactByAddress(String address) - { + private Cursor getContactByAddress(String address) { final String where = Contacts.ContactMethods.KIND + " = " + Contacts.KIND_EMAIL + " AND " + Contacts.ContactMethods.DATA + " = ?"; diff --git a/src/com/fsck/k9/helper/ContactsSdk5.java b/src/com/fsck/k9/helper/ContactsSdk5.java index ce4085cc1..444820e39 100644 --- a/src/com/fsck/k9/helper/ContactsSdk5.java +++ b/src/com/fsck/k9/helper/ContactsSdk5.java @@ -17,8 +17,7 @@ import com.fsck.k9.mail.Address; * * @see android.provider.ContactsContract */ -public class ContactsSdk5 extends com.fsck.k9.helper.Contacts -{ +public class ContactsSdk5 extends com.fsck.k9.helper.Contacts { /** * The order in which the search results are returned by * {@link #searchContacts(CharSequence)}. @@ -35,8 +34,7 @@ public class ContactsSdk5 extends com.fsck.k9.helper.Contacts * {@link com.fsck.k9.EmailAddressAdapter} or more specificly by * {@link android.widget.ResourceCursorAdapter}. */ - protected static final String PROJECTION[] = - { + protected static final String PROJECTION[] = { Email._ID, Contacts.DISPLAY_NAME, Email.DATA, @@ -62,14 +60,12 @@ public class ContactsSdk5 extends com.fsck.k9.helper.Contacts protected static final int CONTACT_ID_INDEX = 3; - public ContactsSdk5(final Context context) - { + public ContactsSdk5(final Context context) { super(context); } @Override - public void createContact(final Address email) - { + public void createContact(final Address email) { final Uri contactUri = Uri.fromParts("mailto", email.getAddress(), null); final Intent contactIntent = new Intent(Intents.SHOW_OR_CREATE_CONTACT); @@ -81,8 +77,7 @@ public class ContactsSdk5 extends com.fsck.k9.helper.Contacts // Only provide personal name hint if we have one final String senderPersonal = email.getPersonal(); - if (senderPersonal != null) - { + if (senderPersonal != null) { contactIntent.putExtra(Intents.Insert.NAME, senderPersonal); } @@ -90,16 +85,13 @@ public class ContactsSdk5 extends com.fsck.k9.helper.Contacts } @Override - public String getOwnerName() - { + public String getOwnerName() { String name = null; // Get the name of the first account that has one. Account[] accounts = AccountManager.get(mContext).getAccounts(); - for (final Account account : accounts) - { - if (account.name != null) - { + for (final Account account : accounts) { + if (account.name != null) { name = account.name; break; } @@ -109,16 +101,13 @@ public class ContactsSdk5 extends com.fsck.k9.helper.Contacts } @Override - public boolean isInContacts(final String emailAddress) - { + public boolean isInContacts(final String emailAddress) { boolean result = false; final Cursor c = getContactByAddress(emailAddress); - if (c != null) - { - if (c.getCount() > 0) - { + if (c != null) { + if (c.getCount() > 0) { result = true; } c.close(); @@ -128,8 +117,7 @@ public class ContactsSdk5 extends com.fsck.k9.helper.Contacts } @Override - public Cursor searchContacts(final CharSequence constraint) - { + public Cursor searchContacts(final CharSequence constraint) { final String filter = (constraint == null) ? "" : constraint.toString(); final Uri uri = Uri.withAppendedPath(Email.CONTENT_FILTER_URI, Uri.encode(filter)); final Cursor c = mContentResolver.query( @@ -139,8 +127,7 @@ public class ContactsSdk5 extends com.fsck.k9.helper.Contacts null, SORT_ORDER); - if (c != null) - { + if (c != null) { /* * To prevent expensive execution in the UI thread: * Cursors get lazily executed, so if you don't call anything on @@ -156,20 +143,16 @@ public class ContactsSdk5 extends com.fsck.k9.helper.Contacts } @Override - public String getNameForAddress(String address) - { - if (address == null) - { + public String getNameForAddress(String address) { + if (address == null) { return null; } final Cursor c = getContactByAddress(address); String name = null; - if (c != null) - { - if (c.getCount() > 0) - { + if (c != null) { + if (c.getCount() > 0) { c.moveToFirst(); name = getName(c); } @@ -180,29 +163,23 @@ public class ContactsSdk5 extends com.fsck.k9.helper.Contacts } @Override - public String getName(Cursor c) - { + public String getName(Cursor c) { return c.getString(NAME_INDEX); } @Override - public String getEmail(Cursor c) - { + public String getEmail(Cursor c) { return c.getString(EMAIL_INDEX); } @Override - public void markAsContacted(final Address[] addresses) - { + public void markAsContacted(final Address[] addresses) { //TODO: Optimize! Potentially a lot of database queries - for (final Address address : addresses) - { + for (final Address address : addresses) { final Cursor c = getContactByAddress(address.getAddress()); - if (c != null) - { - if (c.getCount() > 0) - { + if (c != null) { + if (c.getCount() > 0) { c.moveToFirst(); final long personId = c.getLong(CONTACT_ID_INDEX); ContactsContract.Contacts.markAsContacted(mContentResolver, personId); @@ -220,8 +197,7 @@ public class ContactsSdk5 extends com.fsck.k9.helper.Contacts * @return A {@link Cursor} instance that can be used to fetch information * about the contact with the given email address */ - private Cursor getContactByAddress(final String address) - { + private Cursor getContactByAddress(final String address) { final Uri uri = Uri.withAppendedPath(Email.CONTENT_LOOKUP_URI, Uri.encode(address)); final Cursor c = mContentResolver.query( uri, diff --git a/src/com/fsck/k9/helper/ContactsSdk5p.java b/src/com/fsck/k9/helper/ContactsSdk5p.java index 258f65216..bb5db650a 100644 --- a/src/com/fsck/k9/helper/ContactsSdk5p.java +++ b/src/com/fsck/k9/helper/ContactsSdk5p.java @@ -16,18 +16,14 @@ import android.provider.ContactsContract.CommonDataKinds.StructuredName; * * @see android.provider.ContactsContract */ -public class ContactsSdk5p extends ContactsSdk5 -{ - public ContactsSdk5p(final Context context) - { +public class ContactsSdk5p extends ContactsSdk5 { + public ContactsSdk5p(final Context context) { super(context); } @Override - public Cursor searchContacts(final CharSequence constraint) - { - if (constraint == null) - { + public Cursor searchContacts(final CharSequence constraint) { + if (constraint == null) { return null; } @@ -43,17 +39,12 @@ public class ContactsSdk5p extends ContactsSdk5 null); final StringBuilder matches = new StringBuilder(); - if ((cursor != null) && (cursor.getCount() > 0)) - { + if ((cursor != null) && (cursor.getCount() > 0)) { boolean first = true; - while (cursor.moveToNext()) - { - if (first) - { + while (cursor.moveToNext()) { + if (first) { first = false; - } - else - { + } else { matches.append(","); } matches.append(cursor.getLong(0)); @@ -97,8 +88,7 @@ public class ContactsSdk5p extends ContactsSdk5 args, SORT_ORDER); - if (c != null) - { + if (c != null) { /* * To prevent expensive execution in the UI thread: * Cursors get lazily executed, so if you don't call anything on diff --git a/src/com/fsck/k9/helper/DateFormatter.java b/src/com/fsck/k9/helper/DateFormatter.java index b386310ac..12a9e1a31 100644 --- a/src/com/fsck/k9/helper/DateFormatter.java +++ b/src/com/fsck/k9/helper/DateFormatter.java @@ -11,14 +11,11 @@ import java.util.Calendar; import java.util.HashMap; import java.util.Map; -public class DateFormatter -{ - private DateFormatter() - { +public class DateFormatter { + private DateFormatter() { } private final static Calendar SAMPLE_DATE = Calendar.getInstance(); - static - { + static { SAMPLE_DATE.set(SAMPLE_DATE.get(Calendar.YEAR), SAMPLE_DATE.getActualMaximum(Calendar.MONTH), SAMPLE_DATE.getActualMaximum(Calendar.DAY_OF_MONTH)); } @@ -30,45 +27,34 @@ public class DateFormatter private static volatile String sChosenFormat = null; - public static String getSampleDate(Context context, String formatString) - { + public static String getSampleDate(Context context, String formatString) { java.text.DateFormat formatter = getDateFormat(context, formatString); return formatter.format(SAMPLE_DATE.getTime()); } - public static String[] getFormats(Context context) - { + public static String[] getFormats(Context context) { return context.getResources().getStringArray(R.array.date_formats); } - private static ThreadLocal> storedFormats = new ThreadLocal>() - { + private static ThreadLocal> storedFormats = new ThreadLocal>() { @Override - public synchronized Map initialValue() - { + public synchronized Map initialValue() { return new HashMap(); } }; - public static DateFormat getDateFormat(Context context, String formatString) - { + public static DateFormat getDateFormat(Context context, String formatString) { java.text.DateFormat dateFormat; - if (SHORT_FORMAT.equals(formatString)) - { + if (SHORT_FORMAT.equals(formatString)) { dateFormat = android.text.format.DateFormat.getDateFormat(context); - } - else if (MEDIUM_FORMAT.equals(formatString)) - { + } else if (MEDIUM_FORMAT.equals(formatString)) { dateFormat = android.text.format.DateFormat.getMediumDateFormat(context); - } - else - { + } else { Map formatMap = storedFormats.get(); dateFormat = formatMap.get(formatString); - if (dateFormat == null) - { + if (dateFormat == null) { dateFormat = new SimpleDateFormat(formatString); formatMap.put(formatString, dateFormat); } @@ -76,24 +62,20 @@ public class DateFormatter return dateFormat; } - public static void setDateFormat(Editor editor, String formatString) - { + public static void setDateFormat(Editor editor, String formatString) { sChosenFormat = formatString; editor.putString(PREF_KEY, formatString); } - public static String getFormat(Context context) - { - if (sChosenFormat == null) - { + public static String getFormat(Context context) { + if (sChosenFormat == null) { Preferences prefs = Preferences.getPreferences(context); sChosenFormat = prefs.getPreferences().getString(PREF_KEY, DEFAULT_FORMAT); } return sChosenFormat; } - public static DateFormat getDateFormat(Context context) - { + public static DateFormat getDateFormat(Context context) { String formatString = getFormat(context); return getDateFormat(context, formatString); } diff --git a/src/com/fsck/k9/helper/DomainNameChecker.java b/src/com/fsck/k9/helper/DomainNameChecker.java index bb0e7b8fd..267e4222e 100644 --- a/src/com/fsck/k9/helper/DomainNameChecker.java +++ b/src/com/fsck/k9/helper/DomainNameChecker.java @@ -33,17 +33,12 @@ import java.util.Vector; /** * Implements basic domain-name validation as specified by RFC2818. */ -public class DomainNameChecker -{ +public class DomainNameChecker { private static Pattern QUICK_IP_PATTERN; - static - { - try - { + static { + try { QUICK_IP_PATTERN = Pattern.compile("^[a-f0-9\\.:]+$"); - } - catch (PatternSyntaxException e) - { + } catch (PatternSyntaxException e) { } } @@ -60,21 +55,16 @@ public class DomainNameChecker * The domain name of the site being visited * @return True iff if there is a domain match as specified by RFC2818 */ - public static boolean match(X509Certificate certificate, String thisDomain) - { + public static boolean match(X509Certificate certificate, String thisDomain) { if ((certificate == null) || (thisDomain == null) - || (thisDomain.length() == 0)) - { + || (thisDomain.length() == 0)) { return false; } thisDomain = thisDomain.toLowerCase(); - if (!isIpAddress(thisDomain)) - { + if (!isIpAddress(thisDomain)) { return matchDns(certificate, thisDomain); - } - else - { + } else { return matchIpAddress(certificate, thisDomain); } } @@ -82,34 +72,26 @@ public class DomainNameChecker /** * @return True iff the domain name is specified as an IP address */ - private static boolean isIpAddress(String domain) - { - if ((domain == null) || (domain.length() == 0)) - { + private static boolean isIpAddress(String domain) { + if ((domain == null) || (domain.length() == 0)) { return false; } boolean rval; - try - { + try { // do a quick-dirty IP match first to avoid DNS lookup rval = QUICK_IP_PATTERN.matcher(domain).matches(); - if (rval) - { + if (rval) { rval = domain.equals(InetAddress.getByName(domain) .getHostAddress()); } - } - catch (UnknownHostException e) - { + } catch (UnknownHostException e) { String errorMessage = e.getMessage(); - if (errorMessage == null) - { + if (errorMessage == null) { errorMessage = "unknown host exception"; } - if (K9.DEBUG) - { + if (K9.DEBUG) { Log.v(K9.LOG_TAG, "DomainNameChecker.isIpAddress(): " + errorMessage); } @@ -130,37 +112,26 @@ public class DomainNameChecker * The DNS domain name of the site being visited * @return True iff if there is a domain match as specified by RFC2818 */ - private static boolean matchIpAddress(X509Certificate certificate, String thisDomain) - { - if (K9.DEBUG) - { + private static boolean matchIpAddress(X509Certificate certificate, String thisDomain) { + if (K9.DEBUG) { Log.v(K9.LOG_TAG, "DomainNameChecker.matchIpAddress(): this domain: " + thisDomain); } - try - { + try { Collection subjectAltNames = certificate.getSubjectAlternativeNames(); - if (subjectAltNames != null) - { - for (Object subjectAltName : subjectAltNames) - { - List altNameEntry = (List) (subjectAltName); - if ((altNameEntry != null) && (2 <= altNameEntry.size())) - { - Integer altNameType = (Integer) (altNameEntry.get(0)); - if (altNameType != null) - { - if (altNameType == ALT_IPA_NAME) - { - String altName = (String) (altNameEntry.get(1)); - if (altName != null) - { - if (K9.DEBUG) - { + if (subjectAltNames != null) { + for (Object subjectAltName : subjectAltNames) { + List altNameEntry = (List)(subjectAltName); + if ((altNameEntry != null) && (2 <= altNameEntry.size())) { + Integer altNameType = (Integer)(altNameEntry.get(0)); + if (altNameType != null) { + if (altNameType == ALT_IPA_NAME) { + String altName = (String)(altNameEntry.get(1)); + if (altName != null) { + if (K9.DEBUG) { Log.v(K9.LOG_TAG, "alternative IP: " + altName); } - if (thisDomain.equalsIgnoreCase(altName)) - { + if (thisDomain.equalsIgnoreCase(altName)) { return true; } } @@ -169,9 +140,7 @@ public class DomainNameChecker } } } - } - catch (CertificateParsingException e) - { + } catch (CertificateParsingException e) { } return false; @@ -187,31 +156,22 @@ public class DomainNameChecker * The DNS domain name of the site being visited * @return True iff if there is a domain match as specified by RFC2818 */ - private static boolean matchDns(X509Certificate certificate, String thisDomain) - { + private static boolean matchDns(X509Certificate certificate, String thisDomain) { boolean hasDns = false; - try - { + try { Collection subjectAltNames = certificate.getSubjectAlternativeNames(); - if (subjectAltNames != null) - { + if (subjectAltNames != null) { Iterator i = subjectAltNames.iterator(); - while (i.hasNext()) - { + while (i.hasNext()) { List altNameEntry = (List)(i.next()); - if ((altNameEntry != null) && (2 <= altNameEntry.size())) - { + if ((altNameEntry != null) && (2 <= altNameEntry.size())) { Integer altNameType = (Integer)(altNameEntry.get(0)); - if (altNameType != null) - { - if (altNameType.intValue() == ALT_DNS_NAME) - { + if (altNameType != null) { + if (altNameType.intValue() == ALT_DNS_NAME) { hasDns = true; String altName = (String)(altNameEntry.get(1)); - if (altName != null) - { - if (matchDns(thisDomain, altName)) - { + if (altName != null) { + if (matchDns(thisDomain, altName)) { return true; } } @@ -220,19 +180,15 @@ public class DomainNameChecker } } } - } - catch (CertificateParsingException e) - { + } catch (CertificateParsingException e) { // one way we can get here is if an alternative name starts with // '*' character, which is contrary to one interpretation of the // spec (a valid DNS name must start with a letter); there is no // good way around this, and in order to be compatible we proceed // to check the common name (ie, ignore alternative names) - if (K9.DEBUG) - { + if (K9.DEBUG) { String errorMessage = e.getMessage(); - if (errorMessage == null) - { + if (errorMessage == null) { errorMessage = "failed to parse certificate"; } @@ -241,15 +197,12 @@ public class DomainNameChecker } } - if (!hasDns) - { + if (!hasDns) { X509Name xName = new X509Name(certificate.getSubjectDN().getName()); Vector val = xName.getValues(); Vector oid = xName.getOIDs(); - for (int i = 0; i < oid.size(); i++) - { - if (oid.elementAt(i).equals(X509Name.CN)) - { + for (int i = 0; i < oid.size(); i++) { + if (oid.elementAt(i).equals(X509Name.CN)) { return matchDns(thisDomain, (String)(val.elementAt(i))); } } @@ -265,18 +218,15 @@ public class DomainNameChecker * The domain name from the certificate * @return True iff thisDomain matches thatDomain as specified by RFC2818 */ - private static boolean matchDns(String thisDomain, String thatDomain) - { - if (K9.DEBUG) - { + private static boolean matchDns(String thisDomain, String thatDomain) { + if (K9.DEBUG) { Log.v(K9.LOG_TAG, "DomainNameChecker.matchDns():" + " this domain: " + thisDomain + " that domain: " + thatDomain); } if ((thisDomain == null) || (thisDomain.length() == 0) - || (thatDomain == null) || (thatDomain.length() == 0)) - { + || (thatDomain == null) || (thatDomain.length() == 0)) { return false; } @@ -284,8 +234,7 @@ public class DomainNameChecker // (a) domain name strings are equal, ignoring case: X matches X boolean rval = thisDomain.equals(thatDomain); - if (!rval) - { + if (!rval) { String[] thisDomainTokens = thisDomain.split("\\."); String[] thatDomainTokens = thatDomain.split("\\."); @@ -293,21 +242,16 @@ public class DomainNameChecker int thatDomainTokensNum = thatDomainTokens.length; // (b) OR thatHost is a '.'-suffix of thisHost: Z.Y.X matches X - if (thisDomainTokensNum >= thatDomainTokensNum) - { - for (int i = thatDomainTokensNum - 1; i >= 0; --i) - { + if (thisDomainTokensNum >= thatDomainTokensNum) { + for (int i = thatDomainTokensNum - 1; i >= 0; --i) { rval = thisDomainTokens[i].equals(thatDomainTokens[i]); - if (!rval) - { + if (!rval) { // (c) OR we have a special *-match: // Z.Y.X matches *.Y.X but does not match *.X rval = ((i == 0) && (thisDomainTokensNum == thatDomainTokensNum)); - if (rval) - { + if (rval) { rval = thatDomainTokens[0].equals("*"); - if (!rval) - { + if (!rval) { // (d) OR we have a *-component match: // f*.com matches foo.com but not bar.com rval = domainTokenMatch(thisDomainTokens[0], @@ -333,15 +277,11 @@ public class DomainNameChecker * wildcard match as specified by RFC2818-3.1. For example, f*.com * must match foo.com but not bar.com */ - private static boolean domainTokenMatch(String thisDomainToken, String thatDomainToken) - { - if ((thisDomainToken != null) && (thatDomainToken != null)) - { + private static boolean domainTokenMatch(String thisDomainToken, String thatDomainToken) { + if ((thisDomainToken != null) && (thatDomainToken != null)) { int starIndex = thatDomainToken.indexOf('*'); - if (starIndex >= 0) - { - if (thatDomainToken.length() - 1 <= thisDomainToken.length()) - { + if (starIndex >= 0) { + if (thatDomainToken.length() - 1 <= thisDomainToken.length()) { String prefix = thatDomainToken.substring(0, starIndex); String suffix = thatDomainToken.substring(starIndex + 1); diff --git a/src/com/fsck/k9/helper/HtmlConverter.java b/src/com/fsck/k9/helper/HtmlConverter.java index 781a227a9..08ddd057d 100644 --- a/src/com/fsck/k9/helper/HtmlConverter.java +++ b/src/com/fsck/k9/helper/HtmlConverter.java @@ -15,8 +15,7 @@ import java.util.regex.Matcher; /** * Contains common routines to convert html to text and vice versa. */ -public class HtmlConverter -{ +public class HtmlConverter { /** * When generating previews, Spannable objects that can't be converted into a String are * represented as 0xfffc. When displayed, these show up as undisplayed squares. These constants @@ -40,8 +39,7 @@ public class HtmlConverter * @param html HTML string to convert. * @return Plain text result. */ - public static String htmlToText(final String html) - { + public static String htmlToText(final String html) { return Html.fromHtml(html, null, new HtmlToTextTagHandler()).toString() .replace(PREVIEW_OBJECT_CHARACTER, PREVIEW_OBJECT_REPLACEMENT) .replace(NBSP_CHARACTER, NBSP_REPLACEMENT); @@ -52,11 +50,9 @@ public class HtmlConverter * representations of HTML tags that Android's built-in parser doesn't understand and hides code * contained in STYLE and SCRIPT blocks. */ - private static class HtmlToTextTagHandler implements Html.TagHandler - { + private static class HtmlToTextTagHandler implements Html.TagHandler { // List of tags whose content should be ignored. - private static final Set TAGS_WITH_IGNORED_CONTENT = Collections.unmodifiableSet(new HashSet() - { + private static final Set TAGS_WITH_IGNORED_CONTENT = Collections.unmodifiableSet(new HashSet() { { add("style"); add("script"); @@ -66,17 +62,13 @@ public class HtmlConverter }); @Override - public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader) - { + public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader) { tag = tag.toLowerCase(); - if (tag.equals("hr") && opening) - { + if (tag.equals("hr") && opening) { // In the case of an
    , replace it with a bunch of underscores. This is roughly // the behaviour of Outlook in Rich Text mode. output.append("_____________________________________________\n"); - } - else if (TAGS_WITH_IGNORED_CONTENT.contains(tag)) - { + } else if (TAGS_WITH_IGNORED_CONTENT.contains(tag)) { handleIgnoredTag(opening, output); } } @@ -92,19 +84,14 @@ public class HtmlConverter * @param opening If this is an opening tag or not. * @param output Spannable string that we're working with. */ - private void handleIgnoredTag(boolean opening, Editable output) - { + private void handleIgnoredTag(boolean opening, Editable output) { int len = output.length(); - if (opening) - { + if (opening) { output.setSpan(new Annotation(IGNORED_ANNOTATION_KEY, IGNORED_ANNOTATION_VALUE), len, len, Spannable.SPAN_MARK_MARK); - } - else - { + } else { Object start = getOpeningAnnotation(output); - if (start != null) - { + if (start != null) { int where = output.getSpanStart(start); // Remove the temporary Annotation span. output.removeSpan(start); @@ -120,16 +107,13 @@ public class HtmlConverter * @param output Spannable string we're working with. * @return Starting Annotation object. */ - private Object getOpeningAnnotation(Editable output) - { + private Object getOpeningAnnotation(Editable output) { Object[] objs = output.getSpans(0, output.length(), Annotation.class); - for (int i = objs.length - 1; i >= 0; i--) - { + for (int i = objs.length - 1; i >= 0; i--) { Annotation span = (Annotation) objs[i]; if (output.getSpanFlags(objs[i]) == Spannable.SPAN_MARK_MARK && span.getKey().equals(IGNORED_ANNOTATION_KEY) - && span.getValue().equals(IGNORED_ANNOTATION_VALUE)) - { + && span.getValue().equals(IGNORED_ANNOTATION_VALUE)) { return objs[i]; } } @@ -146,14 +130,12 @@ public class HtmlConverter * @param text Plain text string. * @return HTML string. */ - public static String textToHtml(String text) - { + public static String textToHtml(String text) { // Our HTMLification code is somewhat memory intensive // and was causing lots of OOM errors on the market // if the message is big and plain text, just do // a trivial htmlification - if (text.length() > MAX_SMART_HTMLIFY_MESSAGE_LENGTH) - { + if (text.length() > MAX_SMART_HTMLIFY_MESSAGE_LENGTH) { return "" + htmlifyMessageHeader() + text + @@ -163,37 +145,32 @@ public class HtmlConverter StringReader reader = new StringReader(text); StringBuilder buff = new StringBuilder(text.length() + TEXT_TO_HTML_EXTRA_BUFFER_LENGTH); int c; - try - { - while ((c = reader.read()) != -1) - { - switch (c) - { - case '&': - buff.append("&"); - break; - case '<': - buff.append("<"); - break; - case '>': - buff.append(">"); - break; - case '\r': - break; - default: - buff.append((char)c); + try { + while ((c = reader.read()) != -1) { + switch (c) { + case '&': + buff.append("&"); + break; + case '<': + buff.append("<"); + break; + case '>': + buff.append(">"); + break; + case '\r': + break; + default: + buff.append((char)c); }//switch } - } - catch (IOException e) - { + } catch (IOException e) { //Should never happen Log.e(K9.LOG_TAG, "Could not read string to convert text to HTML:", e); } text = buff.toString(); - text = text.replaceAll("\\s*([-=_]{30,}+)\\s*","
    "); - text = text.replaceAll("(?m)^([^\r\n]{4,}[\\s\\w,:;+/])(?:\r\n|\n|\r)(?=[a-z]\\S{0,10}[\\s\\n\\r])","$1 "); - text = text.replaceAll("(?m)(\r\n|\n|\r){4,}","\n\n"); + text = text.replaceAll("\\s*([-=_]{30,}+)\\s*", "
    "); + text = text.replaceAll("(?m)^([^\r\n]{4,}[\\s\\w,:;+/])(?:\r\n|\n|\r)(?=[a-z]\\S{0,10}[\\s\\n\\r])", "$1 "); + text = text.replaceAll("(?m)(\r\n|\n|\r){4,}", "\n\n"); StringBuffer sb = new StringBuffer(text.length() + TEXT_TO_HTML_EXTRA_BUFFER_LENGTH); sb.append(""); @@ -214,22 +191,15 @@ public class HtmlConverter */ private static void linkifyText(final String text, final StringBuffer outputBuffer) { Matcher m = Regex.WEB_URL_PATTERN.matcher(text); - while (m.find()) - { + while (m.find()) { int start = m.start(); - if (start == 0 || (start != 0 && text.charAt(start - 1) != '@')) - { - if (m.group().indexOf(':') > 0) // With no URI-schema we may get "http:/" links with the second / missing - { + if (start == 0 || (start != 0 && text.charAt(start - 1) != '@')) { + if (m.group().indexOf(':') > 0) { // With no URI-schema we may get "http:/" links with the second / missing m.appendReplacement(outputBuffer, "$0"); - } - else - { + } else { m.appendReplacement(outputBuffer, "$0"); } - } - else - { + } else { m.appendReplacement(outputBuffer, "$0"); } } @@ -242,10 +212,8 @@ public class HtmlConverter * Useful to avoid calling the heavyweight convertEmoji2Img method. * We don't use String.codePointAt here for performance reasons. */ - private static boolean hasEmoji(String html) - { - for (int i = 0; i < html.length(); ++i) - { + private static boolean hasEmoji(String html) { + for (int i = 0; i < html.length(); ++i) { char c = html.charAt(i); if (c >= 0xDBB8 && c < 0xDBBC) return true; @@ -253,16 +221,13 @@ public class HtmlConverter return false; } - public static String convertEmoji2Img(String html) - { - if (!hasEmoji(html)) - { + public static String convertEmoji2Img(String html) { + if (!hasEmoji(html)) { return html; } StringBuilder buff = new StringBuilder(html.length() + 512); - for (int i = 0; i < html.length(); i = html.offsetByCodePoints(i, 1)) - { + for (int i = 0; i < html.length(); i = html.offsetByCodePoints(i, 1)) { int codePoint = html.codePointAt(i); String emoji = getEmojiForCodePoint(codePoint); if (emoji != null) @@ -274,861 +239,851 @@ public class HtmlConverter return buff.toString(); } - private static String getEmojiForCodePoint(int codePoint) - { + private static String getEmojiForCodePoint(int codePoint) { // Derived from http://code.google.com/p/emoji4unicode/source/browse/trunk/data/emoji4unicode.xml // XXX: This doesn't cover all the characters. More emoticons are wanted. - switch (codePoint) - { - case 0xFE000: - return "sun"; - case 0xFE001: - return "cloud"; - case 0xFE002: - return "rain"; - case 0xFE003: - return "snow"; - case 0xFE004: - return "thunder"; - case 0xFE005: - return "typhoon"; - case 0xFE006: - return "mist"; - case 0xFE007: - return "sprinkle"; - case 0xFE008: - return "night"; - case 0xFE009: - return "sun"; - case 0xFE00A: - return "sun"; - case 0xFE00C: - return "sun"; - case 0xFE010: - return "night"; - case 0xFE011: - return "newmoon"; - case 0xFE012: - return "moon1"; - case 0xFE013: - return "moon2"; - case 0xFE014: - return "moon3"; - case 0xFE015: - return "fullmoon"; - case 0xFE016: - return "moon2"; - case 0xFE018: - return "soon"; - case 0xFE019: - return "on"; - case 0xFE01A: - return "end"; - case 0xFE01B: - return "sandclock"; - case 0xFE01C: - return "sandclock"; - case 0xFE01D: - return "watch"; - case 0xFE01E: - return "clock"; - case 0xFE01F: - return "clock"; - case 0xFE020: - return "clock"; - case 0xFE021: - return "clock"; - case 0xFE022: - return "clock"; - case 0xFE023: - return "clock"; - case 0xFE024: - return "clock"; - case 0xFE025: - return "clock"; - case 0xFE026: - return "clock"; - case 0xFE027: - return "clock"; - case 0xFE028: - return "clock"; - case 0xFE029: - return "clock"; - case 0xFE02A: - return "clock"; - case 0xFE02B: - return "aries"; - case 0xFE02C: - return "taurus"; - case 0xFE02D: - return "gemini"; - case 0xFE02E: - return "cancer"; - case 0xFE02F: - return "leo"; - case 0xFE030: - return "virgo"; - case 0xFE031: - return "libra"; - case 0xFE032: - return "scorpius"; - case 0xFE033: - return "sagittarius"; - case 0xFE034: - return "capricornus"; - case 0xFE035: - return "aquarius"; - case 0xFE036: - return "pisces"; - case 0xFE038: - return "wave"; - case 0xFE03B: - return "night"; - case 0xFE03C: - return "clover"; - case 0xFE03D: - return "tulip"; - case 0xFE03E: - return "bud"; - case 0xFE03F: - return "maple"; - case 0xFE040: - return "cherryblossom"; - case 0xFE042: - return "maple"; - case 0xFE04E: - return "clover"; - case 0xFE04F: - return "cherry"; - case 0xFE050: - return "banana"; - case 0xFE051: - return "apple"; - case 0xFE05B: - return "apple"; - case 0xFE190: - return "eye"; - case 0xFE191: - return "ear"; - case 0xFE193: - return "kissmark"; - case 0xFE194: - return "bleah"; - case 0xFE195: - return "rouge"; - case 0xFE198: - return "hairsalon"; - case 0xFE19A: - return "shadow"; - case 0xFE19B: - return "happy01"; - case 0xFE19C: - return "happy01"; - case 0xFE19D: - return "happy01"; - case 0xFE19E: - return "happy01"; - case 0xFE1B7: - return "dog"; - case 0xFE1B8: - return "cat"; - case 0xFE1B9: - return "snail"; - case 0xFE1BA: - return "chick"; - case 0xFE1BB: - return "chick"; - case 0xFE1BC: - return "penguin"; - case 0xFE1BD: - return "fish"; - case 0xFE1BE: - return "horse"; - case 0xFE1BF: - return "pig"; - case 0xFE1C8: - return "chick"; - case 0xFE1C9: - return "fish"; - case 0xFE1CF: - return "aries"; - case 0xFE1D0: - return "dog"; - case 0xFE1D8: - return "dog"; - case 0xFE1D9: - return "fish"; - case 0xFE1DB: - return "foot"; - case 0xFE1DD: - return "chick"; - case 0xFE1E0: - return "pig"; - case 0xFE1E3: - return "cancer"; - case 0xFE320: - return "angry"; - case 0xFE321: - return "sad"; - case 0xFE322: - return "wobbly"; - case 0xFE323: - return "despair"; - case 0xFE324: - return "wobbly"; - case 0xFE325: - return "coldsweats02"; - case 0xFE326: - return "gawk"; - case 0xFE327: - return "lovely"; - case 0xFE328: - return "smile"; - case 0xFE329: - return "bleah"; - case 0xFE32A: - return "bleah"; - case 0xFE32B: - return "delicious"; - case 0xFE32C: - return "lovely"; - case 0xFE32D: - return "lovely"; - case 0xFE32F: - return "happy02"; - case 0xFE330: - return "happy01"; - case 0xFE331: - return "coldsweats01"; - case 0xFE332: - return "happy02"; - case 0xFE333: - return "smile"; - case 0xFE334: - return "happy02"; - case 0xFE335: - return "delicious"; - case 0xFE336: - return "happy01"; - case 0xFE337: - return "happy01"; - case 0xFE338: - return "coldsweats01"; - case 0xFE339: - return "weep"; - case 0xFE33A: - return "crying"; - case 0xFE33B: - return "shock"; - case 0xFE33C: - return "bearing"; - case 0xFE33D: - return "pout"; - case 0xFE33E: - return "confident"; - case 0xFE33F: - return "sad"; - case 0xFE340: - return "think"; - case 0xFE341: - return "shock"; - case 0xFE342: - return "sleepy"; - case 0xFE343: - return "catface"; - case 0xFE344: - return "coldsweats02"; - case 0xFE345: - return "coldsweats02"; - case 0xFE346: - return "bearing"; - case 0xFE347: - return "wink"; - case 0xFE348: - return "happy01"; - case 0xFE349: - return "smile"; - case 0xFE34A: - return "happy02"; - case 0xFE34B: - return "lovely"; - case 0xFE34C: - return "lovely"; - case 0xFE34D: - return "weep"; - case 0xFE34E: - return "pout"; - case 0xFE34F: - return "smile"; - case 0xFE350: - return "sad"; - case 0xFE351: - return "ng"; - case 0xFE352: - return "ok"; - case 0xFE357: - return "paper"; - case 0xFE359: - return "sad"; - case 0xFE35A: - return "angry"; - case 0xFE4B0: - return "house"; - case 0xFE4B1: - return "house"; - case 0xFE4B2: - return "building"; - case 0xFE4B3: - return "postoffice"; - case 0xFE4B4: - return "hospital"; - case 0xFE4B5: - return "bank"; - case 0xFE4B6: - return "atm"; - case 0xFE4B7: - return "hotel"; - case 0xFE4B9: - return "24hours"; - case 0xFE4BA: - return "school"; - case 0xFE4C1: - return "ship"; - case 0xFE4C2: - return "bottle"; - case 0xFE4C3: - return "fuji"; - case 0xFE4C9: - return "wrench"; - case 0xFE4CC: - return "shoe"; - case 0xFE4CD: - return "shoe"; - case 0xFE4CE: - return "eyeglass"; - case 0xFE4CF: - return "t-shirt"; - case 0xFE4D0: - return "denim"; - case 0xFE4D1: - return "crown"; - case 0xFE4D2: - return "crown"; - case 0xFE4D6: - return "boutique"; - case 0xFE4D7: - return "boutique"; - case 0xFE4DB: - return "t-shirt"; - case 0xFE4DC: - return "moneybag"; - case 0xFE4DD: - return "dollar"; - case 0xFE4E0: - return "dollar"; - case 0xFE4E2: - return "yen"; - case 0xFE4E3: - return "dollar"; - case 0xFE4EF: - return "camera"; - case 0xFE4F0: - return "bag"; - case 0xFE4F1: - return "pouch"; - case 0xFE4F2: - return "bell"; - case 0xFE4F3: - return "door"; - case 0xFE4F9: - return "movie"; - case 0xFE4FB: - return "flair"; - case 0xFE4FD: - return "sign05"; - case 0xFE4FF: - return "book"; - case 0xFE500: - return "book"; - case 0xFE501: - return "book"; - case 0xFE502: - return "book"; - case 0xFE503: - return "book"; - case 0xFE505: - return "spa"; - case 0xFE506: - return "toilet"; - case 0xFE507: - return "toilet"; - case 0xFE508: - return "toilet"; - case 0xFE50F: - return "ribbon"; - case 0xFE510: - return "present"; - case 0xFE511: - return "birthday"; - case 0xFE512: - return "xmas"; - case 0xFE522: - return "pocketbell"; - case 0xFE523: - return "telephone"; - case 0xFE524: - return "telephone"; - case 0xFE525: - return "mobilephone"; - case 0xFE526: - return "phoneto"; - case 0xFE527: - return "memo"; - case 0xFE528: - return "faxto"; - case 0xFE529: - return "mail"; - case 0xFE52A: - return "mailto"; - case 0xFE52B: - return "mailto"; - case 0xFE52C: - return "postoffice"; - case 0xFE52D: - return "postoffice"; - case 0xFE52E: - return "postoffice"; - case 0xFE535: - return "present"; - case 0xFE536: - return "pen"; - case 0xFE537: - return "chair"; - case 0xFE538: - return "pc"; - case 0xFE539: - return "pencil"; - case 0xFE53A: - return "clip"; - case 0xFE53B: - return "bag"; - case 0xFE53E: - return "hairsalon"; - case 0xFE540: - return "memo"; - case 0xFE541: - return "memo"; - case 0xFE545: - return "book"; - case 0xFE546: - return "book"; - case 0xFE547: - return "book"; - case 0xFE548: - return "memo"; - case 0xFE54D: - return "book"; - case 0xFE54F: - return "book"; - case 0xFE552: - return "memo"; - case 0xFE553: - return "foot"; - case 0xFE7D0: - return "sports"; - case 0xFE7D1: - return "baseball"; - case 0xFE7D2: - return "golf"; - case 0xFE7D3: - return "tennis"; - case 0xFE7D4: - return "soccer"; - case 0xFE7D5: - return "ski"; - case 0xFE7D6: - return "basketball"; - case 0xFE7D7: - return "motorsports"; - case 0xFE7D8: - return "snowboard"; - case 0xFE7D9: - return "run"; - case 0xFE7DA: - return "snowboard"; - case 0xFE7DC: - return "horse"; - case 0xFE7DF: - return "train"; - case 0xFE7E0: - return "subway"; - case 0xFE7E1: - return "subway"; - case 0xFE7E2: - return "bullettrain"; - case 0xFE7E3: - return "bullettrain"; - case 0xFE7E4: - return "car"; - case 0xFE7E5: - return "rvcar"; - case 0xFE7E6: - return "bus"; - case 0xFE7E8: - return "ship"; - case 0xFE7E9: - return "airplane"; - case 0xFE7EA: - return "yacht"; - case 0xFE7EB: - return "bicycle"; - case 0xFE7EE: - return "yacht"; - case 0xFE7EF: - return "car"; - case 0xFE7F0: - return "run"; - case 0xFE7F5: - return "gasstation"; - case 0xFE7F6: - return "parking"; - case 0xFE7F7: - return "signaler"; - case 0xFE7FA: - return "spa"; - case 0xFE7FC: - return "carouselpony"; - case 0xFE7FF: - return "fish"; - case 0xFE800: - return "karaoke"; - case 0xFE801: - return "movie"; - case 0xFE802: - return "movie"; - case 0xFE803: - return "music"; - case 0xFE804: - return "art"; - case 0xFE805: - return "drama"; - case 0xFE806: - return "event"; - case 0xFE807: - return "ticket"; - case 0xFE808: - return "slate"; - case 0xFE809: - return "drama"; - case 0xFE80A: - return "game"; - case 0xFE813: - return "note"; - case 0xFE814: - return "notes"; - case 0xFE81A: - return "notes"; - case 0xFE81C: - return "tv"; - case 0xFE81D: - return "cd"; - case 0xFE81E: - return "cd"; - case 0xFE823: - return "kissmark"; - case 0xFE824: - return "loveletter"; - case 0xFE825: - return "ring"; - case 0xFE826: - return "ring"; - case 0xFE827: - return "kissmark"; - case 0xFE829: - return "heart02"; - case 0xFE82B: - return "freedial"; - case 0xFE82C: - return "sharp"; - case 0xFE82D: - return "mobaq"; - case 0xFE82E: - return "one"; - case 0xFE82F: - return "two"; - case 0xFE830: - return "three"; - case 0xFE831: - return "four"; - case 0xFE832: - return "five"; - case 0xFE833: - return "six"; - case 0xFE834: - return "seven"; - case 0xFE835: - return "eight"; - case 0xFE836: - return "nine"; - case 0xFE837: - return "zero"; - case 0xFE960: - return "fastfood"; - case 0xFE961: - return "riceball"; - case 0xFE962: - return "cake"; - case 0xFE963: - return "noodle"; - case 0xFE964: - return "bread"; - case 0xFE96A: - return "noodle"; - case 0xFE973: - return "typhoon"; - case 0xFE980: - return "restaurant"; - case 0xFE981: - return "cafe"; - case 0xFE982: - return "bar"; - case 0xFE983: - return "beer"; - case 0xFE984: - return "japanesetea"; - case 0xFE985: - return "bottle"; - case 0xFE986: - return "wine"; - case 0xFE987: - return "beer"; - case 0xFE988: - return "bar"; - case 0xFEAF0: - return "upwardright"; - case 0xFEAF1: - return "downwardright"; - case 0xFEAF2: - return "upwardleft"; - case 0xFEAF3: - return "downwardleft"; - case 0xFEAF4: - return "up"; - case 0xFEAF5: - return "down"; - case 0xFEAF6: - return "leftright"; - case 0xFEAF7: - return "updown"; - case 0xFEB04: - return "sign01"; - case 0xFEB05: - return "sign02"; - case 0xFEB06: - return "sign03"; - case 0xFEB07: - return "sign04"; - case 0xFEB08: - return "sign05"; - case 0xFEB0B: - return "sign01"; - case 0xFEB0C: - return "heart01"; - case 0xFEB0D: - return "heart02"; - case 0xFEB0E: - return "heart03"; - case 0xFEB0F: - return "heart04"; - case 0xFEB10: - return "heart01"; - case 0xFEB11: - return "heart02"; - case 0xFEB12: - return "heart01"; - case 0xFEB13: - return "heart01"; - case 0xFEB14: - return "heart01"; - case 0xFEB15: - return "heart01"; - case 0xFEB16: - return "heart01"; - case 0xFEB17: - return "heart01"; - case 0xFEB18: - return "heart02"; - case 0xFEB19: - return "cute"; - case 0xFEB1A: - return "heart"; - case 0xFEB1B: - return "spade"; - case 0xFEB1C: - return "diamond"; - case 0xFEB1D: - return "club"; - case 0xFEB1E: - return "smoking"; - case 0xFEB1F: - return "nosmoking"; - case 0xFEB20: - return "wheelchair"; - case 0xFEB21: - return "free"; - case 0xFEB22: - return "flag"; - case 0xFEB23: - return "danger"; - case 0xFEB26: - return "ng"; - case 0xFEB27: - return "ok"; - case 0xFEB28: - return "ng"; - case 0xFEB29: - return "copyright"; - case 0xFEB2A: - return "tm"; - case 0xFEB2B: - return "secret"; - case 0xFEB2C: - return "recycle"; - case 0xFEB2D: - return "r-mark"; - case 0xFEB2E: - return "ban"; - case 0xFEB2F: - return "empty"; - case 0xFEB30: - return "pass"; - case 0xFEB31: - return "full"; - case 0xFEB36: - return "new"; - case 0xFEB44: - return "fullmoon"; - case 0xFEB48: - return "ban"; - case 0xFEB55: - return "cute"; - case 0xFEB56: - return "flair"; - case 0xFEB57: - return "annoy"; - case 0xFEB58: - return "bomb"; - case 0xFEB59: - return "sleepy"; - case 0xFEB5A: - return "impact"; - case 0xFEB5B: - return "sweat01"; - case 0xFEB5C: - return "sweat02"; - case 0xFEB5D: - return "dash"; - case 0xFEB5F: - return "sad"; - case 0xFEB60: - return "shine"; - case 0xFEB61: - return "cute"; - case 0xFEB62: - return "cute"; - case 0xFEB63: - return "newmoon"; - case 0xFEB64: - return "newmoon"; - case 0xFEB65: - return "newmoon"; - case 0xFEB66: - return "newmoon"; - case 0xFEB67: - return "newmoon"; - case 0xFEB77: - return "shine"; - case 0xFEB81: - return "id"; - case 0xFEB82: - return "key"; - case 0xFEB83: - return "enter"; - case 0xFEB84: - return "clear"; - case 0xFEB85: - return "search"; - case 0xFEB86: - return "key"; - case 0xFEB87: - return "key"; - case 0xFEB8A: - return "key"; - case 0xFEB8D: - return "search"; - case 0xFEB90: - return "key"; - case 0xFEB91: - return "recycle"; - case 0xFEB92: - return "mail"; - case 0xFEB93: - return "rock"; - case 0xFEB94: - return "scissors"; - case 0xFEB95: - return "paper"; - case 0xFEB96: - return "punch"; - case 0xFEB97: - return "good"; - case 0xFEB9D: - return "paper"; - case 0xFEB9F: - return "ok"; - case 0xFEBA0: - return "down"; - case 0xFEBA1: - return "paper"; - case 0xFEE10: - return "info01"; - case 0xFEE11: - return "info02"; - case 0xFEE12: - return "by-d"; - case 0xFEE13: - return "d-point"; - case 0xFEE14: - return "appli01"; - case 0xFEE15: - return "appli02"; - case 0xFEE1C: - return "movie"; - default: - return null; + switch (codePoint) { + case 0xFE000: + return "sun"; + case 0xFE001: + return "cloud"; + case 0xFE002: + return "rain"; + case 0xFE003: + return "snow"; + case 0xFE004: + return "thunder"; + case 0xFE005: + return "typhoon"; + case 0xFE006: + return "mist"; + case 0xFE007: + return "sprinkle"; + case 0xFE008: + return "night"; + case 0xFE009: + return "sun"; + case 0xFE00A: + return "sun"; + case 0xFE00C: + return "sun"; + case 0xFE010: + return "night"; + case 0xFE011: + return "newmoon"; + case 0xFE012: + return "moon1"; + case 0xFE013: + return "moon2"; + case 0xFE014: + return "moon3"; + case 0xFE015: + return "fullmoon"; + case 0xFE016: + return "moon2"; + case 0xFE018: + return "soon"; + case 0xFE019: + return "on"; + case 0xFE01A: + return "end"; + case 0xFE01B: + return "sandclock"; + case 0xFE01C: + return "sandclock"; + case 0xFE01D: + return "watch"; + case 0xFE01E: + return "clock"; + case 0xFE01F: + return "clock"; + case 0xFE020: + return "clock"; + case 0xFE021: + return "clock"; + case 0xFE022: + return "clock"; + case 0xFE023: + return "clock"; + case 0xFE024: + return "clock"; + case 0xFE025: + return "clock"; + case 0xFE026: + return "clock"; + case 0xFE027: + return "clock"; + case 0xFE028: + return "clock"; + case 0xFE029: + return "clock"; + case 0xFE02A: + return "clock"; + case 0xFE02B: + return "aries"; + case 0xFE02C: + return "taurus"; + case 0xFE02D: + return "gemini"; + case 0xFE02E: + return "cancer"; + case 0xFE02F: + return "leo"; + case 0xFE030: + return "virgo"; + case 0xFE031: + return "libra"; + case 0xFE032: + return "scorpius"; + case 0xFE033: + return "sagittarius"; + case 0xFE034: + return "capricornus"; + case 0xFE035: + return "aquarius"; + case 0xFE036: + return "pisces"; + case 0xFE038: + return "wave"; + case 0xFE03B: + return "night"; + case 0xFE03C: + return "clover"; + case 0xFE03D: + return "tulip"; + case 0xFE03E: + return "bud"; + case 0xFE03F: + return "maple"; + case 0xFE040: + return "cherryblossom"; + case 0xFE042: + return "maple"; + case 0xFE04E: + return "clover"; + case 0xFE04F: + return "cherry"; + case 0xFE050: + return "banana"; + case 0xFE051: + return "apple"; + case 0xFE05B: + return "apple"; + case 0xFE190: + return "eye"; + case 0xFE191: + return "ear"; + case 0xFE193: + return "kissmark"; + case 0xFE194: + return "bleah"; + case 0xFE195: + return "rouge"; + case 0xFE198: + return "hairsalon"; + case 0xFE19A: + return "shadow"; + case 0xFE19B: + return "happy01"; + case 0xFE19C: + return "happy01"; + case 0xFE19D: + return "happy01"; + case 0xFE19E: + return "happy01"; + case 0xFE1B7: + return "dog"; + case 0xFE1B8: + return "cat"; + case 0xFE1B9: + return "snail"; + case 0xFE1BA: + return "chick"; + case 0xFE1BB: + return "chick"; + case 0xFE1BC: + return "penguin"; + case 0xFE1BD: + return "fish"; + case 0xFE1BE: + return "horse"; + case 0xFE1BF: + return "pig"; + case 0xFE1C8: + return "chick"; + case 0xFE1C9: + return "fish"; + case 0xFE1CF: + return "aries"; + case 0xFE1D0: + return "dog"; + case 0xFE1D8: + return "dog"; + case 0xFE1D9: + return "fish"; + case 0xFE1DB: + return "foot"; + case 0xFE1DD: + return "chick"; + case 0xFE1E0: + return "pig"; + case 0xFE1E3: + return "cancer"; + case 0xFE320: + return "angry"; + case 0xFE321: + return "sad"; + case 0xFE322: + return "wobbly"; + case 0xFE323: + return "despair"; + case 0xFE324: + return "wobbly"; + case 0xFE325: + return "coldsweats02"; + case 0xFE326: + return "gawk"; + case 0xFE327: + return "lovely"; + case 0xFE328: + return "smile"; + case 0xFE329: + return "bleah"; + case 0xFE32A: + return "bleah"; + case 0xFE32B: + return "delicious"; + case 0xFE32C: + return "lovely"; + case 0xFE32D: + return "lovely"; + case 0xFE32F: + return "happy02"; + case 0xFE330: + return "happy01"; + case 0xFE331: + return "coldsweats01"; + case 0xFE332: + return "happy02"; + case 0xFE333: + return "smile"; + case 0xFE334: + return "happy02"; + case 0xFE335: + return "delicious"; + case 0xFE336: + return "happy01"; + case 0xFE337: + return "happy01"; + case 0xFE338: + return "coldsweats01"; + case 0xFE339: + return "weep"; + case 0xFE33A: + return "crying"; + case 0xFE33B: + return "shock"; + case 0xFE33C: + return "bearing"; + case 0xFE33D: + return "pout"; + case 0xFE33E: + return "confident"; + case 0xFE33F: + return "sad"; + case 0xFE340: + return "think"; + case 0xFE341: + return "shock"; + case 0xFE342: + return "sleepy"; + case 0xFE343: + return "catface"; + case 0xFE344: + return "coldsweats02"; + case 0xFE345: + return "coldsweats02"; + case 0xFE346: + return "bearing"; + case 0xFE347: + return "wink"; + case 0xFE348: + return "happy01"; + case 0xFE349: + return "smile"; + case 0xFE34A: + return "happy02"; + case 0xFE34B: + return "lovely"; + case 0xFE34C: + return "lovely"; + case 0xFE34D: + return "weep"; + case 0xFE34E: + return "pout"; + case 0xFE34F: + return "smile"; + case 0xFE350: + return "sad"; + case 0xFE351: + return "ng"; + case 0xFE352: + return "ok"; + case 0xFE357: + return "paper"; + case 0xFE359: + return "sad"; + case 0xFE35A: + return "angry"; + case 0xFE4B0: + return "house"; + case 0xFE4B1: + return "house"; + case 0xFE4B2: + return "building"; + case 0xFE4B3: + return "postoffice"; + case 0xFE4B4: + return "hospital"; + case 0xFE4B5: + return "bank"; + case 0xFE4B6: + return "atm"; + case 0xFE4B7: + return "hotel"; + case 0xFE4B9: + return "24hours"; + case 0xFE4BA: + return "school"; + case 0xFE4C1: + return "ship"; + case 0xFE4C2: + return "bottle"; + case 0xFE4C3: + return "fuji"; + case 0xFE4C9: + return "wrench"; + case 0xFE4CC: + return "shoe"; + case 0xFE4CD: + return "shoe"; + case 0xFE4CE: + return "eyeglass"; + case 0xFE4CF: + return "t-shirt"; + case 0xFE4D0: + return "denim"; + case 0xFE4D1: + return "crown"; + case 0xFE4D2: + return "crown"; + case 0xFE4D6: + return "boutique"; + case 0xFE4D7: + return "boutique"; + case 0xFE4DB: + return "t-shirt"; + case 0xFE4DC: + return "moneybag"; + case 0xFE4DD: + return "dollar"; + case 0xFE4E0: + return "dollar"; + case 0xFE4E2: + return "yen"; + case 0xFE4E3: + return "dollar"; + case 0xFE4EF: + return "camera"; + case 0xFE4F0: + return "bag"; + case 0xFE4F1: + return "pouch"; + case 0xFE4F2: + return "bell"; + case 0xFE4F3: + return "door"; + case 0xFE4F9: + return "movie"; + case 0xFE4FB: + return "flair"; + case 0xFE4FD: + return "sign05"; + case 0xFE4FF: + return "book"; + case 0xFE500: + return "book"; + case 0xFE501: + return "book"; + case 0xFE502: + return "book"; + case 0xFE503: + return "book"; + case 0xFE505: + return "spa"; + case 0xFE506: + return "toilet"; + case 0xFE507: + return "toilet"; + case 0xFE508: + return "toilet"; + case 0xFE50F: + return "ribbon"; + case 0xFE510: + return "present"; + case 0xFE511: + return "birthday"; + case 0xFE512: + return "xmas"; + case 0xFE522: + return "pocketbell"; + case 0xFE523: + return "telephone"; + case 0xFE524: + return "telephone"; + case 0xFE525: + return "mobilephone"; + case 0xFE526: + return "phoneto"; + case 0xFE527: + return "memo"; + case 0xFE528: + return "faxto"; + case 0xFE529: + return "mail"; + case 0xFE52A: + return "mailto"; + case 0xFE52B: + return "mailto"; + case 0xFE52C: + return "postoffice"; + case 0xFE52D: + return "postoffice"; + case 0xFE52E: + return "postoffice"; + case 0xFE535: + return "present"; + case 0xFE536: + return "pen"; + case 0xFE537: + return "chair"; + case 0xFE538: + return "pc"; + case 0xFE539: + return "pencil"; + case 0xFE53A: + return "clip"; + case 0xFE53B: + return "bag"; + case 0xFE53E: + return "hairsalon"; + case 0xFE540: + return "memo"; + case 0xFE541: + return "memo"; + case 0xFE545: + return "book"; + case 0xFE546: + return "book"; + case 0xFE547: + return "book"; + case 0xFE548: + return "memo"; + case 0xFE54D: + return "book"; + case 0xFE54F: + return "book"; + case 0xFE552: + return "memo"; + case 0xFE553: + return "foot"; + case 0xFE7D0: + return "sports"; + case 0xFE7D1: + return "baseball"; + case 0xFE7D2: + return "golf"; + case 0xFE7D3: + return "tennis"; + case 0xFE7D4: + return "soccer"; + case 0xFE7D5: + return "ski"; + case 0xFE7D6: + return "basketball"; + case 0xFE7D7: + return "motorsports"; + case 0xFE7D8: + return "snowboard"; + case 0xFE7D9: + return "run"; + case 0xFE7DA: + return "snowboard"; + case 0xFE7DC: + return "horse"; + case 0xFE7DF: + return "train"; + case 0xFE7E0: + return "subway"; + case 0xFE7E1: + return "subway"; + case 0xFE7E2: + return "bullettrain"; + case 0xFE7E3: + return "bullettrain"; + case 0xFE7E4: + return "car"; + case 0xFE7E5: + return "rvcar"; + case 0xFE7E6: + return "bus"; + case 0xFE7E8: + return "ship"; + case 0xFE7E9: + return "airplane"; + case 0xFE7EA: + return "yacht"; + case 0xFE7EB: + return "bicycle"; + case 0xFE7EE: + return "yacht"; + case 0xFE7EF: + return "car"; + case 0xFE7F0: + return "run"; + case 0xFE7F5: + return "gasstation"; + case 0xFE7F6: + return "parking"; + case 0xFE7F7: + return "signaler"; + case 0xFE7FA: + return "spa"; + case 0xFE7FC: + return "carouselpony"; + case 0xFE7FF: + return "fish"; + case 0xFE800: + return "karaoke"; + case 0xFE801: + return "movie"; + case 0xFE802: + return "movie"; + case 0xFE803: + return "music"; + case 0xFE804: + return "art"; + case 0xFE805: + return "drama"; + case 0xFE806: + return "event"; + case 0xFE807: + return "ticket"; + case 0xFE808: + return "slate"; + case 0xFE809: + return "drama"; + case 0xFE80A: + return "game"; + case 0xFE813: + return "note"; + case 0xFE814: + return "notes"; + case 0xFE81A: + return "notes"; + case 0xFE81C: + return "tv"; + case 0xFE81D: + return "cd"; + case 0xFE81E: + return "cd"; + case 0xFE823: + return "kissmark"; + case 0xFE824: + return "loveletter"; + case 0xFE825: + return "ring"; + case 0xFE826: + return "ring"; + case 0xFE827: + return "kissmark"; + case 0xFE829: + return "heart02"; + case 0xFE82B: + return "freedial"; + case 0xFE82C: + return "sharp"; + case 0xFE82D: + return "mobaq"; + case 0xFE82E: + return "one"; + case 0xFE82F: + return "two"; + case 0xFE830: + return "three"; + case 0xFE831: + return "four"; + case 0xFE832: + return "five"; + case 0xFE833: + return "six"; + case 0xFE834: + return "seven"; + case 0xFE835: + return "eight"; + case 0xFE836: + return "nine"; + case 0xFE837: + return "zero"; + case 0xFE960: + return "fastfood"; + case 0xFE961: + return "riceball"; + case 0xFE962: + return "cake"; + case 0xFE963: + return "noodle"; + case 0xFE964: + return "bread"; + case 0xFE96A: + return "noodle"; + case 0xFE973: + return "typhoon"; + case 0xFE980: + return "restaurant"; + case 0xFE981: + return "cafe"; + case 0xFE982: + return "bar"; + case 0xFE983: + return "beer"; + case 0xFE984: + return "japanesetea"; + case 0xFE985: + return "bottle"; + case 0xFE986: + return "wine"; + case 0xFE987: + return "beer"; + case 0xFE988: + return "bar"; + case 0xFEAF0: + return "upwardright"; + case 0xFEAF1: + return "downwardright"; + case 0xFEAF2: + return "upwardleft"; + case 0xFEAF3: + return "downwardleft"; + case 0xFEAF4: + return "up"; + case 0xFEAF5: + return "down"; + case 0xFEAF6: + return "leftright"; + case 0xFEAF7: + return "updown"; + case 0xFEB04: + return "sign01"; + case 0xFEB05: + return "sign02"; + case 0xFEB06: + return "sign03"; + case 0xFEB07: + return "sign04"; + case 0xFEB08: + return "sign05"; + case 0xFEB0B: + return "sign01"; + case 0xFEB0C: + return "heart01"; + case 0xFEB0D: + return "heart02"; + case 0xFEB0E: + return "heart03"; + case 0xFEB0F: + return "heart04"; + case 0xFEB10: + return "heart01"; + case 0xFEB11: + return "heart02"; + case 0xFEB12: + return "heart01"; + case 0xFEB13: + return "heart01"; + case 0xFEB14: + return "heart01"; + case 0xFEB15: + return "heart01"; + case 0xFEB16: + return "heart01"; + case 0xFEB17: + return "heart01"; + case 0xFEB18: + return "heart02"; + case 0xFEB19: + return "cute"; + case 0xFEB1A: + return "heart"; + case 0xFEB1B: + return "spade"; + case 0xFEB1C: + return "diamond"; + case 0xFEB1D: + return "club"; + case 0xFEB1E: + return "smoking"; + case 0xFEB1F: + return "nosmoking"; + case 0xFEB20: + return "wheelchair"; + case 0xFEB21: + return "free"; + case 0xFEB22: + return "flag"; + case 0xFEB23: + return "danger"; + case 0xFEB26: + return "ng"; + case 0xFEB27: + return "ok"; + case 0xFEB28: + return "ng"; + case 0xFEB29: + return "copyright"; + case 0xFEB2A: + return "tm"; + case 0xFEB2B: + return "secret"; + case 0xFEB2C: + return "recycle"; + case 0xFEB2D: + return "r-mark"; + case 0xFEB2E: + return "ban"; + case 0xFEB2F: + return "empty"; + case 0xFEB30: + return "pass"; + case 0xFEB31: + return "full"; + case 0xFEB36: + return "new"; + case 0xFEB44: + return "fullmoon"; + case 0xFEB48: + return "ban"; + case 0xFEB55: + return "cute"; + case 0xFEB56: + return "flair"; + case 0xFEB57: + return "annoy"; + case 0xFEB58: + return "bomb"; + case 0xFEB59: + return "sleepy"; + case 0xFEB5A: + return "impact"; + case 0xFEB5B: + return "sweat01"; + case 0xFEB5C: + return "sweat02"; + case 0xFEB5D: + return "dash"; + case 0xFEB5F: + return "sad"; + case 0xFEB60: + return "shine"; + case 0xFEB61: + return "cute"; + case 0xFEB62: + return "cute"; + case 0xFEB63: + return "newmoon"; + case 0xFEB64: + return "newmoon"; + case 0xFEB65: + return "newmoon"; + case 0xFEB66: + return "newmoon"; + case 0xFEB67: + return "newmoon"; + case 0xFEB77: + return "shine"; + case 0xFEB81: + return "id"; + case 0xFEB82: + return "key"; + case 0xFEB83: + return "enter"; + case 0xFEB84: + return "clear"; + case 0xFEB85: + return "search"; + case 0xFEB86: + return "key"; + case 0xFEB87: + return "key"; + case 0xFEB8A: + return "key"; + case 0xFEB8D: + return "search"; + case 0xFEB90: + return "key"; + case 0xFEB91: + return "recycle"; + case 0xFEB92: + return "mail"; + case 0xFEB93: + return "rock"; + case 0xFEB94: + return "scissors"; + case 0xFEB95: + return "paper"; + case 0xFEB96: + return "punch"; + case 0xFEB97: + return "good"; + case 0xFEB9D: + return "paper"; + case 0xFEB9F: + return "ok"; + case 0xFEBA0: + return "down"; + case 0xFEBA1: + return "paper"; + case 0xFEE10: + return "info01"; + case 0xFEE11: + return "info02"; + case 0xFEE12: + return "by-d"; + case 0xFEE13: + return "d-point"; + case 0xFEE14: + return "appli01"; + case 0xFEE15: + return "appli02"; + case 0xFEE1C: + return "movie"; + default: + return null; } } - private static String htmlifyMessageHeader() - { - if (K9.messageViewFixedWidthFont()) - { + private static String htmlifyMessageHeader() { + if (K9.messageViewFixedWidthFont()) { return "
    ";
    -        }
    -        else
    -        {
    +        } else {
                 return "
    "; } } - private static String htmlifyMessageFooter() - { - if (K9.messageViewFixedWidthFont()) - { + private static String htmlifyMessageFooter() { + if (K9.messageViewFixedWidthFont()) { return "
    "; - } - else - { + } else { return "
    "; } } @@ -1138,8 +1093,7 @@ public class HtmlConverter * @param text Plain text. * @return HTML fragment. */ - public static String textToHtmlFragment(final String text) - { + public static String textToHtmlFragment(final String text) { // Escape the entities and add newlines. String htmlified = TextUtils.htmlEncode(text); diff --git a/src/com/fsck/k9/helper/IAutoSync.java b/src/com/fsck/k9/helper/IAutoSync.java index 76d643087..660da060d 100644 --- a/src/com/fsck/k9/helper/IAutoSync.java +++ b/src/com/fsck/k9/helper/IAutoSync.java @@ -7,8 +7,7 @@ import android.content.Context; * current state of the auto-sync setting. This method differs from SDK 3 to * SDK 5, so there are specialized implementations for each SDK version. */ -public interface IAutoSync -{ +public interface IAutoSync { /** * Do the necessary reflection magic to get the necessary objects and/or * methods to later query the state of the auto-sync setting. diff --git a/src/com/fsck/k9/helper/MediaScannerNotifier.java b/src/com/fsck/k9/helper/MediaScannerNotifier.java index 1a9c5436d..8229b8297 100644 --- a/src/com/fsck/k9/helper/MediaScannerNotifier.java +++ b/src/com/fsck/k9/helper/MediaScannerNotifier.java @@ -9,14 +9,12 @@ import android.net.Uri; import java.io.File; -public class MediaScannerNotifier implements MediaScannerConnectionClient -{ +public class MediaScannerNotifier implements MediaScannerConnectionClient { private MediaScannerConnection mConnection; private File mFile; private Context mContext; - public MediaScannerNotifier(Context context, File file) - { + public MediaScannerNotifier(Context context, File file) { mFile = file; mConnection = new MediaScannerConnection(context, this); mConnection.connect(); @@ -24,24 +22,18 @@ public class MediaScannerNotifier implements MediaScannerConnectionClient } - public void onMediaScannerConnected() - { + public void onMediaScannerConnected() { mConnection.scanFile(mFile.getAbsolutePath(), null); } - public void onScanCompleted(String path, Uri uri) - { - try - { - if (uri != null) - { + public void onScanCompleted(String path, Uri uri) { + try { + if (uri != null) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(uri); mContext.startActivity(intent); } - } - finally - { + } finally { mConnection.disconnect(); } } diff --git a/src/com/fsck/k9/helper/MessageHelper.java b/src/com/fsck/k9/helper/MessageHelper.java index c9b0c84de..412796336 100644 --- a/src/com/fsck/k9/helper/MessageHelper.java +++ b/src/com/fsck/k9/helper/MessageHelper.java @@ -20,15 +20,12 @@ import com.fsck.k9.mail.Message.RecipientType; import com.fsck.k9.mail.store.LocalStore.LocalMessage; import com.fsck.k9.helper.DateFormatter; -public class MessageHelper -{ +public class MessageHelper { private static MessageHelper sInstance; - public synchronized static MessageHelper getInstance(final Context context) - { - if (sInstance == null) - { + public synchronized static MessageHelper getInstance(final Context context) { + if (sInstance == null) { sInstance = new MessageHelper(context); } return sInstance; @@ -40,24 +37,20 @@ public class MessageHelper private DateFormat mDateFormat; - private MessageHelper(final Context context) - { + private MessageHelper(final Context context) { mContext = context; mDateFormat = DateFormatter.getDateFormat(mContext); mTodayDateFormat = android.text.format.DateFormat.getTimeFormat(mContext); } public void populate(final MessageInfoHolder target, final Message m, - final FolderInfoHolder folder, final Account account) - { + final FolderInfoHolder folder, final Account account) { final Contacts contactHelper = K9.showContactName() ? Contacts.getInstance(mContext) : null; - try - { + try { LocalMessage message = (LocalMessage) m; target.message = message; target.compareDate = message.getSentDate(); - if (target.compareDate == null) - { + if (target.compareDate == null) { target.compareDate = message.getInternalDate(); } @@ -71,24 +64,18 @@ public class MessageHelper Address[] addrs = message.getFrom(); - if (addrs.length > 0 && account.isAnIdentity(addrs[0])) - { + if (addrs.length > 0 && account.isAnIdentity(addrs[0])) { CharSequence to = Address.toFriendly(message .getRecipients(RecipientType.TO), contactHelper); target.compareCounterparty = to.toString(); target.sender = new SpannableStringBuilder(mContext.getString(R.string.message_to_label)).append(to); - } - else - { + } else { target.sender = Address.toFriendly(addrs, contactHelper); target.compareCounterparty = target.sender.toString(); } - if (addrs.length > 0) - { + if (addrs.length > 0) { target.senderAddress = addrs[0].getAddress(); - } - else - { + } else { // a reasonable fallback "whomever we were corresponding with target.senderAddress = target.compareCounterparty; } @@ -101,20 +88,14 @@ public class MessageHelper target.account = account.getDescription(); target.uri = "email://messages/" + account.getAccountNumber() + "/" + m.getFolder().getName() + "/" + m.getUid(); - } - catch (MessagingException me) - { + } catch (MessagingException me) { Log.w(K9.LOG_TAG, "Unable to load message info", me); } } - public String formatDate(Date date) - { - if (Utility.isDateToday(date)) - { + public String formatDate(Date date) { + if (Utility.isDateToday(date)) { return mTodayDateFormat.format(date); - } - else - { + } else { return mDateFormat.format(date); } } diff --git a/src/com/fsck/k9/helper/Regex.java b/src/com/fsck/k9/helper/Regex.java index a768c09d7..ef6f8cf3c 100644 --- a/src/com/fsck/k9/helper/Regex.java +++ b/src/com/fsck/k9/helper/Regex.java @@ -27,8 +27,7 @@ import java.util.regex.Pattern; /** * Commonly used regular expression patterns. */ -public class Regex -{ +public class Regex { /** * Regular expression to match all IANA top-level domains. @@ -190,19 +189,16 @@ public class Regex * @return A String comprising all of the non-null matched * groups concatenated together */ - public static final String concatGroups(Matcher matcher) - { + public static final String concatGroups(Matcher matcher) { StringBuilder b = new StringBuilder(); final int numGroups = matcher.groupCount(); - for (int i = 1; i <= numGroups; i++) - { + for (int i = 1; i <= numGroups; i++) { String s = matcher.group(i); System.err.println("Group(" + i + ") : " + s); - if (s != null) - { + if (s != null) { b.append(s); } } @@ -220,17 +216,14 @@ public class Regex * @return A String comprising all of the digits and plus in * the match */ - public static final String digitsAndPlusOnly(Matcher matcher) - { + public static final String digitsAndPlusOnly(Matcher matcher) { StringBuilder buffer = new StringBuilder(); String matchingRegion = matcher.group(); - for (int i = 0, size = matchingRegion.length(); i < size; i++) - { + for (int i = 0, size = matchingRegion.length(); i < size; i++) { char character = matchingRegion.charAt(i); - if (character == '+' || Character.isDigit(character)) - { + if (character == '+' || Character.isDigit(character)) { buffer.append(character); } } diff --git a/src/com/fsck/k9/helper/SizeFormatter.java b/src/com/fsck/k9/helper/SizeFormatter.java index e4ad3a6e8..08c7f1a11 100644 --- a/src/com/fsck/k9/helper/SizeFormatter.java +++ b/src/com/fsck/k9/helper/SizeFormatter.java @@ -3,24 +3,19 @@ package com.fsck.k9.helper; import android.content.Context; import com.fsck.k9.R; -public class SizeFormatter -{ +public class SizeFormatter { /* * Formats the given size as a String in bytes, kB, MB or GB with a single digit * of precision. Ex: 12,315,000 = 12.3 MB */ - public static String formatSize(Context context, long size) - { - if (size > 1024000000) - { + public static String formatSize(Context context, long size) { + if (size > 1024000000) { return ((float)(size / 102400000) / 10) + context.getString(R.string.abbrev_gigabytes); } - if (size > 1024000) - { + if (size > 1024000) { return ((float)(size / 102400) / 10) + context.getString(R.string.abbrev_megabytes); } - if (size > 1024) - { + if (size > 1024) { return ((float)(size / 102) / 10) + context.getString(R.string.abbrev_kilobytes); } return size + context.getString(R.string.abbrev_bytes); diff --git a/src/com/fsck/k9/helper/Utility.java b/src/com/fsck/k9/helper/Utility.java index 5249ab138..c1faa8d91 100644 --- a/src/com/fsck/k9/helper/Utility.java +++ b/src/com/fsck/k9/helper/Utility.java @@ -20,8 +20,7 @@ import java.util.Date; import java.util.regex.Matcher; import java.util.regex.Pattern; -public class Utility -{ +public class Utility { // \u00A0 (non-breaking space) happens to be used by French MUA @@ -37,25 +36,20 @@ public class Utility private static final Pattern TAG_PATTERN = Pattern.compile("\\[[-_a-z0-9]+\\] ", Pattern.CASE_INSENSITIVE); - public static String readInputStream(InputStream in, String encoding) throws IOException - { + public static String readInputStream(InputStream in, String encoding) throws IOException { InputStreamReader reader = new InputStreamReader(in, encoding); StringBuffer sb = new StringBuffer(); int count; char[] buf = new char[512]; - while ((count = reader.read(buf)) != -1) - { + while ((count = reader.read(buf)) != -1) { sb.append(buf, 0, count); } return sb.toString(); } - public static boolean arrayContains(Object[] a, Object o) - { - for (Object element : a) - { - if (element.equals(o)) - { + public static boolean arrayContains(Object[] a, Object o) { + for (Object element : a) { + if (element.equals(o)) { return true; } } @@ -71,70 +65,55 @@ public class Utility * @param seperator * @return */ - public static String combine(Object[] parts, char seperator) - { - if (parts == null) - { + public static String combine(Object[] parts, char seperator) { + if (parts == null) { return null; } StringBuffer sb = new StringBuffer(); - for (int i = 0; i < parts.length; i++) - { + for (int i = 0; i < parts.length; i++) { sb.append(parts[i].toString()); - if (i < parts.length - 1) - { + if (i < parts.length - 1) { sb.append(seperator); } } return sb.toString(); } - public static String base64Decode(String encoded) - { - if (encoded == null) - { + public static String base64Decode(String encoded) { + if (encoded == null) { return null; } byte[] decoded = new Base64().decode(encoded.getBytes()); return new String(decoded); } - public static String base64Encode(String s) - { - if (s == null) - { + public static String base64Encode(String s) { + if (s == null) { return s; } byte[] encoded = new Base64().encode(s.getBytes()); return new String(encoded); } - public static boolean requiredFieldValid(TextView view) - { + public static boolean requiredFieldValid(TextView view) { return view.getText() != null && view.getText().length() > 0; } - public static boolean requiredFieldValid(Editable s) - { + public static boolean requiredFieldValid(Editable s) { return s != null && s.length() > 0; } - public static boolean domainFieldValid(EditText view) - { - if (view.getText() != null) - { + public static boolean domainFieldValid(EditText view) { + if (view.getText() != null) { String s = view.getText().toString(); - if (s.matches("^([a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,6}$")) - { + if (s.matches("^([a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,6}$")) { return true; } - if (s.matches("^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$")) - { + if (s.matches("^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$")) { return true; } - if ((s.equalsIgnoreCase("localhost"))||(s.equalsIgnoreCase("localhost.localdomain"))) - { + if ((s.equalsIgnoreCase("localhost")) || (s.equalsIgnoreCase("localhost.localdomain"))) { return true; } } @@ -150,14 +129,10 @@ public class Utility * @param text String to quote. * @return Possibly quoted string. */ - public static String quoteAtoms(final String text) - { - if (ATOM.matcher(text).matches()) - { + public static String quoteAtoms(final String text) { + if (ATOM.matcher(text).matches()) { return text; - } - else - { + } else { return quoteString(text); } } @@ -176,18 +151,13 @@ public class Utility * @param s * @return */ - public static String quoteString(String s) - { - if (s == null) - { + public static String quoteString(String s) { + if (s == null) { return null; } - if (!s.matches("^\".*\"$")) - { + if (!s.matches("^\".*\"$")) { return "\"" + s + "\""; - } - else - { + } else { return s; } } @@ -197,45 +167,33 @@ public class Utility * allocations. This version is around 3x as fast as the standard one and I'm using it * hundreds of times in places that slow down the UI, so it helps. */ - public static String fastUrlDecode(String s) - { - try - { + public static String fastUrlDecode(String s) { + try { byte[] bytes = s.getBytes("UTF-8"); byte ch; int length = 0; - for (int i = 0, count = bytes.length; i < count; i++) - { + for (int i = 0, count = bytes.length; i < count; i++) { ch = bytes[i]; - if (ch == '%') - { + if (ch == '%') { int h = (bytes[i + 1] - '0'); int l = (bytes[i + 2] - '0'); - if (h > 9) - { + if (h > 9) { h -= 7; } - if (l > 9) - { + if (l > 9) { l -= 7; } bytes[length] = (byte)((h << 4) | l); i += 2; - } - else if (ch == '+') - { + } else if (ch == '+') { bytes[length] = ' '; - } - else - { + } else { bytes[length] = bytes[i]; } length++; } return new String(bytes, 0, length, "UTF-8"); - } - catch (UnsupportedEncodingException uee) - { + } catch (UnsupportedEncodingException uee) { return null; } } @@ -245,15 +203,11 @@ public class Utility * @param date * @return */ - public static boolean isDateToday(Date date) - { + public static boolean isDateToday(Date date) { Date now = new Date(); - if (now.getTime() - 64800000 > date.getTime() || now.getTime() + 64800000 < date.getTime()) - { + if (now.getTime() - 64800000 > date.getTime() || now.getTime() + 64800000 < date.getTime()) { return false; - } - else - { + } else { return true; } } @@ -262,8 +216,7 @@ public class Utility * TODO disabled this method globally. It is used in all the settings screens but I just * noticed that an unrelated icon was dimmed. Android must share drawables internally. */ - public static void setCompoundDrawablesAlpha(TextView view, int alpha) - { + public static void setCompoundDrawablesAlpha(TextView view, int alpha) { // Drawable[] drawables = view.getCompoundDrawables(); // for (Drawable drawable : drawables) { // if (drawable != null) { @@ -311,11 +264,9 @@ public class Utility * @return a line with newlines inserted, null if null input */ private static final String NEWLINE_REGEX = "(?:\\r?\\n)"; - public static String wrap(String str, int wrapLength) - { + public static String wrap(String str, int wrapLength) { StringBuilder result = new StringBuilder(); - for (String piece : str.split(NEWLINE_REGEX)) - { + for (String piece : str.split(NEWLINE_REGEX)) { result.append(wrap(piece, wrapLength, null, false)); result.append("\n"); } @@ -360,62 +311,47 @@ public class Utility * @param wrapLongWords true if long words (such as URLs) should be wrapped * @return a line with newlines inserted, null if null input */ - public static String wrap(String str, int wrapLength, String newLineStr, boolean wrapLongWords) - { - if (str == null) - { + public static String wrap(String str, int wrapLength, String newLineStr, boolean wrapLongWords) { + if (str == null) { return null; } - if (newLineStr == null) - { + if (newLineStr == null) { newLineStr = "\n"; } - if (wrapLength < 1) - { + if (wrapLength < 1) { wrapLength = 1; } int inputLineLength = str.length(); int offset = 0; StringBuilder wrappedLine = new StringBuilder(inputLineLength + 32); - while ((inputLineLength - offset) > wrapLength) - { - if (str.charAt(offset) == ' ') - { + while ((inputLineLength - offset) > wrapLength) { + if (str.charAt(offset) == ' ') { offset++; continue; } int spaceToWrapAt = str.lastIndexOf(' ', wrapLength + offset); - if (spaceToWrapAt >= offset) - { + if (spaceToWrapAt >= offset) { // normal case wrappedLine.append(str.substring(offset, spaceToWrapAt)); wrappedLine.append(newLineStr); offset = spaceToWrapAt + 1; - } - else - { + } else { // really long word or URL - if (wrapLongWords) - { + if (wrapLongWords) { // wrap really long word one line at a time wrappedLine.append(str.substring(offset, wrapLength + offset)); wrappedLine.append(newLineStr); offset += wrapLength; - } - else - { + } else { // do not wrap really long word, just extend beyond limit spaceToWrapAt = str.indexOf(' ', wrapLength + offset); - if (spaceToWrapAt >= 0) - { + if (spaceToWrapAt >= 0) { wrappedLine.append(str.substring(offset, spaceToWrapAt)); wrappedLine.append(newLineStr); offset = spaceToWrapAt + 1; - } - else - { + } else { wrappedLine.append(str.substring(offset)); offset = inputLineLength; } @@ -442,8 +378,7 @@ public class Utility * Never null. * @return Never null. */ - public static String stripSubject(final String subject) - { + public static String stripSubject(final String subject) { int lastPrefix = 0; final Matcher tagMatcher = TAG_PATTERN.matcher(subject); @@ -452,11 +387,9 @@ public class Utility boolean tagPresent = false; // whether the last action stripped a tag boolean tagStripped = false; - if (tagMatcher.find(0)) - { + if (tagMatcher.find(0)) { tagPresent = true; - if (tagMatcher.start() == 0) - { + if (tagMatcher.start() == 0) { // found at beginning of subject, considering it an actual tag tag = tagMatcher.group(); @@ -478,25 +411,19 @@ public class Utility && matcher.find(lastPrefix) && matcher.start() == lastPrefix && (!tagPresent || tag == null || subject.regionMatches(matcher.end(), tag, 0, - tag.length()))) - { + tag.length()))) { lastPrefix = matcher.end(); - if (tagPresent) - { + if (tagPresent) { tagStripped = false; - if (tag == null) - { + if (tag == null) { // attempt to find tag - if (tagMatcher.start() == lastPrefix) - { + if (tagMatcher.start() == lastPrefix) { tag = tagMatcher.group(); lastPrefix += tag.length(); tagStripped = true; } - } - else if (lastPrefix < subject.length() - 1 && subject.startsWith(tag, lastPrefix)) - { + } else if (lastPrefix < subject.length() - 1 && subject.startsWith(tag, lastPrefix)) { // Re: [foo] Re: [foo] blah blah blah // ^ ^ // ^ ^ @@ -509,17 +436,13 @@ public class Utility } } // Null pointer check is to make the static analysis component of Eclipse happy. - if (tagStripped && (tag != null)) - { + if (tagStripped && (tag != null)) { // restore the last tag lastPrefix -= tag.length(); } - if (lastPrefix > -1 && lastPrefix < subject.length() - 1) - { + if (lastPrefix > -1 && lastPrefix < subject.length() - 1) { return subject.substring(lastPrefix).trim(); - } - else - { + } else { return subject.trim(); } } @@ -529,22 +452,15 @@ public class Utility * @param name * Never null. */ - public static void touchFile(final File parentDir, final String name) - { + public static void touchFile(final File parentDir, final String name) { final File file = new File(parentDir, name); - try - { - if (!file.exists()) - { + try { + if (!file.exists()) { file.createNewFile(); - } - else - { + } else { file.setLastModified(System.currentTimeMillis()); } - } - catch (Exception e) - { + } catch (Exception e) { Log.d(K9.LOG_TAG, "Unable to touch file: " + file.getAbsolutePath(), e); } } @@ -557,31 +473,24 @@ public class Utility * @param filename * @return */ - public static File createUniqueFile(File directory, String filename) - { + public static File createUniqueFile(File directory, String filename) { File file = new File(directory, filename); - if (!file.exists()) - { + if (!file.exists()) { return file; } // Get the extension of the file, if any. int index = filename.lastIndexOf('.'); String format; - if (index != -1) - { + if (index != -1) { String name = filename.substring(0, index); String extension = filename.substring(index); format = name + "-%d" + extension; - } - else - { + } else { format = filename + "-%d"; } - for (int i = 2; i < Integer.MAX_VALUE; i++) - { + for (int i = 2; i < Integer.MAX_VALUE; i++) { file = new File(directory, String.format(format, i)); - if (!file.exists()) - { + if (!file.exists()) { return file; } } @@ -595,31 +504,25 @@ public class Utility * @param to * @return */ - public static boolean move(final File from, final File to) - { - if (to.exists()) - { + public static boolean move(final File from, final File to) { + if (to.exists()) { to.delete(); } to.getParentFile().mkdirs(); - try - { + try { FileInputStream in = new FileInputStream(from); FileOutputStream out = new FileOutputStream(to); byte[] buffer = new byte[1024]; int count = -1; - while ((count = in.read(buffer)) > 0) - { + while ((count = in.read(buffer)) > 0) { out.write(buffer, 0, count); } out.close(); in.close(); from.delete(); return true; - } - catch (Exception e) - { + } catch (Exception e) { Log.w(K9.LOG_TAG, "cannot move " + from.getAbsolutePath() + " to " + to.getAbsolutePath(), e); return false; } @@ -630,59 +533,44 @@ public class Utility * @param fromDir * @param toDir */ - public static void moveRecursive(final File fromDir, final File toDir) - { - if (!fromDir.exists()) - { + public static void moveRecursive(final File fromDir, final File toDir) { + if (!fromDir.exists()) { return; } - if (!fromDir.isDirectory()) - { - if (toDir.exists()) - { - if (!toDir.delete()) - { + if (!fromDir.isDirectory()) { + if (toDir.exists()) { + if (!toDir.delete()) { Log.w(K9.LOG_TAG, "cannot delete already existing file/directory " + toDir.getAbsolutePath()); } } - if (!fromDir.renameTo(toDir)) - { + if (!fromDir.renameTo(toDir)) { Log.w(K9.LOG_TAG, "cannot rename " + fromDir.getAbsolutePath() + " to " + toDir.getAbsolutePath() + " - moving instead"); move(fromDir, toDir); } return; } - if (!toDir.exists() || !toDir.isDirectory()) - { - if (toDir.exists() ) - { + if (!toDir.exists() || !toDir.isDirectory()) { + if (toDir.exists()) { toDir.delete(); } - if (!toDir.mkdirs()) - { + if (!toDir.mkdirs()) { Log.w(K9.LOG_TAG, "cannot create directory " + toDir.getAbsolutePath()); } } File[] files = fromDir.listFiles(); - for (File file : files) - { - if (file.isDirectory()) - { + for (File file : files) { + if (file.isDirectory()) { moveRecursive(file, new File(toDir, file.getName())); file.delete(); - } - else - { + } else { File target = new File(toDir, file.getName()); - if (!file.renameTo(target)) - { + if (!file.renameTo(target)) { Log.w(K9.LOG_TAG, "cannot rename " + file.getAbsolutePath() + " to " + target.getAbsolutePath() + " - moving instead"); move(file, target); } } } - if (!fromDir.delete()) - { + if (!fromDir.delete()) { Log.w(K9.LOG_TAG, "cannot delete " + fromDir.getAbsolutePath()); } } @@ -695,22 +583,17 @@ public class Utility * @param message Content to evaluate * @return True if it has external images; false otherwise. */ - public static boolean hasExternalImages(final String message) - { + public static boolean hasExternalImages(final String message) { Matcher imgMatches = IMG_PATTERN.matcher(message); - while (imgMatches.find()) - { - if (!imgMatches.group(1).equals("content")) - { - if (K9.DEBUG) - { + while (imgMatches.find()) { + if (!imgMatches.group(1).equals("content")) { + if (K9.DEBUG) { Log.d(K9.LOG_TAG, "External images found"); } return true; } } - if (K9.DEBUG) - { + if (K9.DEBUG) { Log.d(K9.LOG_TAG, "No external images."); } return false; diff --git a/src/com/fsck/k9/helper/power/TracingPowerManager.java b/src/com/fsck/k9/helper/power/TracingPowerManager.java index d2b66f052..718f7cfdc 100644 --- a/src/com/fsck/k9/helper/power/TracingPowerManager.java +++ b/src/com/fsck/k9/helper/power/TracingPowerManager.java @@ -10,20 +10,16 @@ import android.os.PowerManager; import android.os.PowerManager.WakeLock; import android.util.Log; -public class TracingPowerManager -{ +public class TracingPowerManager { private final static boolean TRACE = false; public static AtomicInteger wakeLockId = new AtomicInteger(0); PowerManager pm = null; private static TracingPowerManager tracingPowerManager; private Timer timer = null; - public static synchronized TracingPowerManager getPowerManager(Context context) - { - if (tracingPowerManager == null) - { - if (K9.DEBUG) - { + public static synchronized TracingPowerManager getPowerManager(Context context) { + if (tracingPowerManager == null) { + if (K9.DEBUG) { Log.v(K9.LOG_TAG, "Creating TracingPowerManager"); } tracingPowerManager = new TracingPowerManager(context); @@ -32,140 +28,104 @@ public class TracingPowerManager } - private TracingPowerManager(Context context) - { + private TracingPowerManager(Context context) { pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); - if (TRACE) - { + if (TRACE) { timer = new Timer(); } } - public TracingWakeLock newWakeLock(int flags, String tag) - { + public TracingWakeLock newWakeLock(int flags, String tag) { return new TracingWakeLock(flags, tag); } - public class TracingWakeLock - { + public class TracingWakeLock { final WakeLock wakeLock; final int id; final String tag; volatile TimerTask timerTask; volatile Long startTime = null; volatile Long timeout = null; - public TracingWakeLock(int flags, String ntag) - { + public TracingWakeLock(int flags, String ntag) { tag = ntag; wakeLock = pm.newWakeLock(flags, tag); id = wakeLockId.getAndIncrement(); - if (K9.DEBUG) - { - Log.v(K9.LOG_TAG, "TracingWakeLock for tag " + tag + " / id " + id+ ": Create"); + if (K9.DEBUG) { + Log.v(K9.LOG_TAG, "TracingWakeLock for tag " + tag + " / id " + id + ": Create"); } } - public void acquire(long timeout) - { - synchronized (wakeLock) - { + public void acquire(long timeout) { + synchronized (wakeLock) { wakeLock.acquire(timeout); } - if (K9.DEBUG) - { + if (K9.DEBUG) { Log.v(K9.LOG_TAG, "TracingWakeLock for tag " + tag + " / id " + id + " for " + timeout + " ms: acquired"); } raiseNotification(); - if (startTime == null) - { + if (startTime == null) { startTime = System.currentTimeMillis(); } this.timeout = timeout; } - public void acquire() - { - synchronized (wakeLock) - { + public void acquire() { + synchronized (wakeLock) { wakeLock.acquire(); } raiseNotification(); - if (K9.DEBUG) - { + if (K9.DEBUG) { Log.w(K9.LOG_TAG, "TracingWakeLock for tag " + tag + " / id " + id + ": acquired with no timeout. K-9 Mail should not do this"); } - if (startTime == null) - { + if (startTime == null) { startTime = System.currentTimeMillis(); } timeout = null; } - public void setReferenceCounted(boolean counted) - { - synchronized (wakeLock) - { + public void setReferenceCounted(boolean counted) { + synchronized (wakeLock) { wakeLock.setReferenceCounted(counted); } } - public void release() - { - if (startTime != null) - { + public void release() { + if (startTime != null) { Long endTime = System.currentTimeMillis(); - if (K9.DEBUG) - { + if (K9.DEBUG) { Log.v(K9.LOG_TAG, "TracingWakeLock for tag " + tag + " / id " + id + ": releasing after " + (endTime - startTime) + " ms, timeout = " + timeout + " ms"); } - } - else - { - if (K9.DEBUG) - { + } else { + if (K9.DEBUG) { Log.v(K9.LOG_TAG, "TracingWakeLock for tag " + tag + " / id " + id + ", timeout = " + timeout + " ms: releasing"); } } cancelNotification(); - synchronized (wakeLock) - { + synchronized (wakeLock) { wakeLock.release(); } startTime = null; } - private void cancelNotification() - { - if (timer != null) - { - synchronized (timer) - { - if (timerTask != null) - { + private void cancelNotification() { + if (timer != null) { + synchronized (timer) { + if (timerTask != null) { timerTask.cancel(); } } } } - private void raiseNotification() - { - if (timer != null) - { - synchronized (timer) - { - if (timerTask != null) - { + private void raiseNotification() { + if (timer != null) { + synchronized (timer) { + if (timerTask != null) { timerTask.cancel(); timerTask = null; } - timerTask = new TimerTask() - { + timerTask = new TimerTask() { @Override - public void run() - { - if (startTime != null) - { + public void run() { + if (startTime != null) { Long endTime = System.currentTimeMillis(); Log.i(K9.LOG_TAG, "TracingWakeLock for tag " + tag + " / id " + id + ": has been active for " + (endTime - startTime) + " ms, timeout = " + timeout + " ms"); - } - else - { + } else { Log.i(K9.LOG_TAG, "TracingWakeLock for tag " + tag + " / id " + id + ": still active, timeout = " + timeout + " ms"); } } diff --git a/src/com/fsck/k9/mail/Address.java b/src/com/fsck/k9/mail/Address.java index 0ec02f7c1..b4f11c078 100644 --- a/src/com/fsck/k9/mail/Address.java +++ b/src/com/fsck/k9/mail/Address.java @@ -21,8 +21,7 @@ import org.apache.james.mime4j.MimeException; import java.util.ArrayList; import java.util.List; -public class Address -{ +public class Address { /** * If the number of addresses exceeds this value the addresses aren't * resolved to the names of Android contacts. @@ -45,28 +44,22 @@ public class Address String mPersonal; - public Address(String address, String personal) - { + public Address(String address, String personal) { this(address, personal, true); } - public Address(String address) - { + public Address(String address) { this(address, null); } - private Address(String address, String personal, boolean parse) - { - if (parse) - { + private Address(String address, String personal, boolean parse) { + if (parse) { Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(address); - if (tokens.length > 0) - { + if (tokens.length > 0) { Rfc822Token token = tokens[0]; mAddress = token.getAddress(); String name = token.getName(); - if ((name != null) && !("".equals(name))) - { + if ((name != null) && !("".equals(name))) { /* * Don't use the "personal" argument if "address" is of the form: * James Bond @@ -74,47 +67,35 @@ public class Address * See issue 2920 */ mPersonal = name; - } - else - { + } else { mPersonal = (personal == null) ? null : personal.trim(); } - } - else - { + } else { // This should be an error } - } - else - { + } else { mAddress = address; mPersonal = personal; } } - public String getAddress() - { + public String getAddress() { return mAddress; } - public void setAddress(String address) - { + public void setAddress(String address) { this.mAddress = address; } - public String getPersonal() - { + public String getPersonal() { return mPersonal; } - public void setPersonal(String personal) - { - if ("".equals(personal)) - { + public void setPersonal(String personal) { + if ("".equals(personal)) { personal = null; } - if (personal != null) - { + if (personal != null) { personal = personal.trim(); } this.mPersonal = personal; @@ -127,17 +108,13 @@ public class Address * @param addressList * @return An array of 0 or more Addresses. */ - public static Address[] parseUnencoded(String addressList) - { + public static Address[] parseUnencoded(String addressList) { List
    addresses = new ArrayList
    (); - if ((addressList != null) && !("".equals(addressList))) - { + if ((addressList != null) && !("".equals(addressList))) { Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(addressList); - for (Rfc822Token token : tokens) - { + for (Rfc822Token token : tokens) { String address = token.getAddress(); - if ((address != null) && !("".equals(address))) - { + if ((address != null) && !("".equals(address))) { addresses.add(new Address(token.getAddress(), token.getName(), false)); } } @@ -152,109 +129,81 @@ public class Address * @param addressList * @return An array of 0 or more Addresses. */ - public static Address[] parse(String addressList) - { + public static Address[] parse(String addressList) { ArrayList
    addresses = new ArrayList
    (); - if ((addressList == null) && !("".equals(addressList))) - { + if ((addressList == null) && !("".equals(addressList))) { return EMPTY_ADDRESS_ARRAY; } - try - { + try { MailboxList parsedList = AddressBuilder.parseAddressList(addressList).flatten(); - for (int i = 0, count = parsedList.size(); i < count; i++) - { + for (int i = 0, count = parsedList.size(); i < count; i++) { org.apache.james.mime4j.dom.address.Address address = parsedList.get(i); - if (address instanceof Mailbox) - { + if (address instanceof Mailbox) { Mailbox mailbox = (Mailbox)address; addresses.add(new Address(mailbox.getLocalPart() + "@" + mailbox.getDomain(), mailbox.getName(), false)); - } - else - { + } else { Log.e(K9.LOG_TAG, "Unknown address type from Mime4J: " + address.getClass().toString()); } } - } - catch (MimeException pe) - { + } catch (MimeException pe) { Log.e(K9.LOG_TAG, "MimeException in Address.parse()", pe); } return addresses.toArray(EMPTY_ADDRESS_ARRAY); } @Override - public boolean equals(Object o) - { - if (o instanceof Address) - { + public boolean equals(Object o) { + if (o instanceof Address) { return getAddress().equals(((Address) o).getAddress()); } return super.equals(o); } @Override - public int hashCode() - { + public int hashCode() { return getAddress().hashCode(); } @Override - public String toString() - { - if (mPersonal != null && !mPersonal.equals("")) - { + public String toString() { + if (mPersonal != null && !mPersonal.equals("")) { return Utility.quoteAtoms(mPersonal) + " <" + mAddress + ">"; - } - else - { + } else { return mAddress; } } - public static String toString(Address[] addresses) - { - if (addresses == null) - { + public static String toString(Address[] addresses) { + if (addresses == null) { return null; } StringBuffer sb = new StringBuffer(); - for (int i = 0; i < addresses.length; i++) - { + for (int i = 0; i < addresses.length; i++) { sb.append(addresses[i].toString()); - if (i < addresses.length - 1) - { + if (i < addresses.length - 1) { sb.append(", "); } } return sb.toString(); } - public String toEncodedString() - { - if (mPersonal != null) - { + public String toEncodedString() { + if (mPersonal != null) { return EncoderUtil.encodeAddressDisplayName(mPersonal) + " <" + mAddress + ">"; - } - else - { + } else { return mAddress; } } - public static String toEncodedString(Address[] addresses) - { - if (addresses == null) - { + public static String toEncodedString(Address[] addresses) { + if (addresses == null) { return null; } StringBuffer sb = new StringBuffer(); - for (int i = 0; i < addresses.length; i++) - { + for (int i = 0; i < addresses.length; i++) { sb.append(addresses[i].toEncodedString()); - if (i < addresses.length - 1) - { + if (i < addresses.length - 1) { sb.append(','); } } @@ -266,8 +215,7 @@ public class Address * is not available. * @return */ - public CharSequence toFriendly() - { + public CharSequence toFriendly() { return toFriendly((Contacts)null); } @@ -283,23 +231,17 @@ public class Address * @return * A "friendly" name for this {@link Address}. */ - public CharSequence toFriendly(final Contacts contacts) - { - if (!K9.showCorrespondentNames()) - { + public CharSequence toFriendly(final Contacts contacts) { + if (!K9.showCorrespondentNames()) { return mAddress; - } - else if (contacts != null) - { + } else if (contacts != null) { final String name = contacts.getNameForAddress(mAddress); // TODO: The results should probably be cached for performance reasons. - if (name != null) - { - if (K9.changeContactNameColor()) - { + if (name != null) { + if (K9.changeContactNameColor()) { final SpannableString coloredName = new SpannableString(name); coloredName.setSpan(new ForegroundColorSpan(K9.getContactNameColor()), 0, @@ -307,9 +249,7 @@ public class Address Spannable.SPAN_EXCLUSIVE_EXCLUSIVE ); return coloredName; - } - else - { + } else { return name; } } @@ -318,30 +258,24 @@ public class Address return ((mPersonal != null) && (mPersonal.length() > 0)) ? mPersonal : mAddress; } - public static CharSequence toFriendly(Address[] addresses) - { + public static CharSequence toFriendly(Address[] addresses) { return toFriendly(addresses, null); } - public static CharSequence toFriendly(Address[] addresses, Contacts contacts) - { - if (addresses == null) - { + public static CharSequence toFriendly(Address[] addresses, Contacts contacts) { + if (addresses == null) { return null; } - if (addresses.length >= TOO_MANY_ADDRESSES) - { + if (addresses.length >= TOO_MANY_ADDRESSES) { // Don't look up contacts if the number of addresses is very high. contacts = null; } SpannableStringBuilder sb = new SpannableStringBuilder(); - for (int i = 0; i < addresses.length; i++) - { + for (int i = 0; i < addresses.length; i++) { sb.append(addresses[i].toFriendly(contacts)); - if (i < addresses.length - 1) - { + if (i < addresses.length - 1) { sb.append(','); } } @@ -353,10 +287,8 @@ public class Address * @param addressList Packed address list. * @return Unpacked list. */ - public static Address[] unpack(String addressList) - { - if (addressList == null) - { + public static Address[] unpack(String addressList) { + if (addressList == null) { return new Address[] { }; } ArrayList
    addresses = new ArrayList
    (); @@ -364,24 +296,19 @@ public class Address int pairStartIndex = 0; int pairEndIndex = 0; int addressEndIndex = 0; - while (pairStartIndex < length) - { + while (pairStartIndex < length) { pairEndIndex = addressList.indexOf(",\u0000", pairStartIndex); - if (pairEndIndex == -1) - { + if (pairEndIndex == -1) { pairEndIndex = length; } addressEndIndex = addressList.indexOf(";\u0000", pairStartIndex); String address = null; String personal = null; - if (addressEndIndex == -1 || addressEndIndex > pairEndIndex) - { + if (addressEndIndex == -1 || addressEndIndex > pairEndIndex) { address = addressList.substring(pairStartIndex, pairEndIndex); - } - else - { + } else { address = addressList.substring(pairStartIndex, addressEndIndex); - personal =addressList.substring(addressEndIndex + 2, pairEndIndex); + personal = addressList.substring(addressEndIndex + 2, pairEndIndex); } addresses.add(new Address(address, personal)); pairStartIndex = pairEndIndex + 2; @@ -397,27 +324,22 @@ public class Address * @param addresses Array of addresses to pack. * @return Packed addresses. */ - public static String pack(Address[] addresses) - { - if (addresses == null) - { + public static String pack(Address[] addresses) { + if (addresses == null) { return null; } StringBuilder sb = new StringBuilder(); - for (int i = 0, count = addresses.length; i < count; i++) - { + for (int i = 0, count = addresses.length; i < count; i++) { Address address = addresses[i]; sb.append(address.getAddress()); String personal = address.getPersonal(); - if (personal != null) - { + if (personal != null) { sb.append(";\u0000"); // Escape quotes in the address part on the way in - personal = personal.replaceAll("\"","\\\""); + personal = personal.replaceAll("\"", "\\\""); sb.append(personal); } - if (i < count - 1) - { + if (i < count - 1) { sb.append(",\u0000"); } } diff --git a/src/com/fsck/k9/mail/AuthenticationFailedException.java b/src/com/fsck/k9/mail/AuthenticationFailedException.java index 1df57277d..006063a14 100644 --- a/src/com/fsck/k9/mail/AuthenticationFailedException.java +++ b/src/com/fsck/k9/mail/AuthenticationFailedException.java @@ -1,17 +1,14 @@ package com.fsck.k9.mail; -public class AuthenticationFailedException extends MessagingException -{ +public class AuthenticationFailedException extends MessagingException { public static final long serialVersionUID = -1; - public AuthenticationFailedException(String message) - { + public AuthenticationFailedException(String message) { super(message); } - public AuthenticationFailedException(String message, Throwable throwable) - { + public AuthenticationFailedException(String message, Throwable throwable) { super(message, throwable); } } diff --git a/src/com/fsck/k9/mail/Body.java b/src/com/fsck/k9/mail/Body.java index 21d671d99..7deb2a1eb 100644 --- a/src/com/fsck/k9/mail/Body.java +++ b/src/com/fsck/k9/mail/Body.java @@ -5,8 +5,7 @@ import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; -public interface Body -{ +public interface Body { public InputStream getInputStream() throws MessagingException; public void writeTo(OutputStream out) throws IOException, MessagingException; } diff --git a/src/com/fsck/k9/mail/BodyPart.java b/src/com/fsck/k9/mail/BodyPart.java index 18e680a77..e59aaf344 100644 --- a/src/com/fsck/k9/mail/BodyPart.java +++ b/src/com/fsck/k9/mail/BodyPart.java @@ -1,17 +1,14 @@ package com.fsck.k9.mail; -public abstract class BodyPart implements Part -{ +public abstract class BodyPart implements Part { private Multipart mParent; - public Multipart getParent() - { + public Multipart getParent() { return mParent; } - public void setParent(Multipart parent) - { + public void setParent(Multipart parent) { mParent = parent; } } diff --git a/src/com/fsck/k9/mail/CertificateValidationException.java b/src/com/fsck/k9/mail/CertificateValidationException.java index 983010953..ed35cf8ac 100644 --- a/src/com/fsck/k9/mail/CertificateValidationException.java +++ b/src/com/fsck/k9/mail/CertificateValidationException.java @@ -1,17 +1,14 @@ package com.fsck.k9.mail; -public class CertificateValidationException extends MessagingException -{ +public class CertificateValidationException extends MessagingException { public static final long serialVersionUID = -1; - public CertificateValidationException(String message) - { + public CertificateValidationException(String message) { super(message); } - public CertificateValidationException(String message, Throwable throwable) - { + public CertificateValidationException(String message, Throwable throwable) { super(message, throwable); } } \ No newline at end of file diff --git a/src/com/fsck/k9/mail/FetchProfile.java b/src/com/fsck/k9/mail/FetchProfile.java index f8231b6db..1f4da62a2 100644 --- a/src/com/fsck/k9/mail/FetchProfile.java +++ b/src/com/fsck/k9/mail/FetchProfile.java @@ -15,8 +15,7 @@ import java.util.ArrayList; * any information it needs to download the content. * */ -public class FetchProfile extends ArrayList -{ +public class FetchProfile extends ArrayList { private static final long serialVersionUID = -5520076119120964166L; /** @@ -24,8 +23,7 @@ public class FetchProfile extends ArrayList * item fetched by using these items could potentially include all of the * previous items. */ - public enum Item - { + public enum Item { /** * Download the flags of the message. */ diff --git a/src/com/fsck/k9/mail/Flag.java b/src/com/fsck/k9/mail/Flag.java index 9291fcecf..1ffa49b70 100644 --- a/src/com/fsck/k9/mail/Flag.java +++ b/src/com/fsck/k9/mail/Flag.java @@ -4,8 +4,7 @@ package com.fsck.k9.mail; /** * Flags that can be applied to Messages. */ -public enum Flag -{ +public enum Flag { DELETED, SEEN, ANSWERED, diff --git a/src/com/fsck/k9/mail/Folder.java b/src/com/fsck/k9/mail/Folder.java index 308523f9f..7e338400b 100644 --- a/src/com/fsck/k9/mail/Folder.java +++ b/src/com/fsck/k9/mail/Folder.java @@ -9,30 +9,25 @@ import com.fsck.k9.Preferences; import com.fsck.k9.controller.MessageRetrievalListener; -public abstract class Folder -{ +public abstract class Folder { protected final Account mAccount; private String status = null; private long lastChecked = 0; private long lastPush = 0; - public enum OpenMode - { + public enum OpenMode { READ_WRITE, READ_ONLY, } // NONE is obsolete, it will be translated to NO_CLASS for display and to INHERITED for sync and push - public enum FolderClass - { + public enum FolderClass { NONE, NO_CLASS, INHERITED, FIRST_CLASS, SECOND_CLASS } - public enum FolderType - { + public enum FolderType { HOLDS_FOLDERS, HOLDS_MESSAGES, } - protected Folder(Account account) - { + protected Folder(Account account) { mAccount = account; } @@ -69,8 +64,7 @@ public abstract class Folder * Create a new folder with a specified display limit. Not abstract to allow * remote folders to not override or worry about this call if they don't care to. */ - public boolean create(FolderType type, int displayLimit) throws MessagingException - { + public boolean create(FolderType type, int displayLimit) throws MessagingException { return create(type); } @@ -101,8 +95,7 @@ public abstract class Folder public abstract Message[] getMessages(MessageRetrievalListener listener) throws MessagingException; - public Message[] getMessages(MessageRetrievalListener listener, boolean includeDeleted) throws MessagingException - { + public Message[] getMessages(MessageRetrievalListener listener, boolean includeDeleted) throws MessagingException { return getMessages(listener); } @@ -115,10 +108,8 @@ public abstract class Folder public void moveMessages(Message[] msgs, Folder folder) throws MessagingException {} - public void delete(Message[] msgs, String trashFolderName) throws MessagingException - { - for (Message message : msgs) - { + public void delete(Message[] msgs, String trashFolderName) throws MessagingException { + for (Message message : msgs) { Message myMessage = getMessage(message.getUid()); myMessage.delete(trashFolderName); } @@ -138,8 +129,7 @@ public abstract class Folder MessageRetrievalListener listener) throws MessagingException; public void fetchPart(Message message, Part part, - MessageRetrievalListener listener) throws MessagingException - { + MessageRetrievalListener listener) throws MessagingException { // This is causing trouble. Disabled for now. See issue 1733 //throw new RuntimeException("fetchPart() not implemented."); @@ -159,83 +149,67 @@ public abstract class Folder * @param message * @return empty string to clear the pushState, null to leave the state as-is */ - public String getNewPushState(String oldPushState, Message message) - { + public String getNewPushState(String oldPushState, Message message) { return null; } - public boolean supportsFetchingFlags() - { + public boolean supportsFetchingFlags() { return true; }//isFlagSupported @Override - public String toString() - { + public String toString() { return getName(); } - public long getLastChecked() - { + public long getLastChecked() { return lastChecked; } - public void setLastChecked(long lastChecked) throws MessagingException - { + public void setLastChecked(long lastChecked) throws MessagingException { this.lastChecked = lastChecked; } - public long getLastPush() - { + public long getLastPush() { return lastPush; } - public void setLastPush(long lastCheckedDisplay) throws MessagingException - { + public void setLastPush(long lastCheckedDisplay) throws MessagingException { this.lastPush = lastCheckedDisplay; } - public long getLastUpdate() - { + public long getLastUpdate() { return Math.max(getLastChecked(), getLastPush()); } - public FolderClass getDisplayClass() - { + public FolderClass getDisplayClass() { return FolderClass.NO_CLASS; } - public FolderClass getSyncClass() - { + public FolderClass getSyncClass() { return getDisplayClass(); } - public FolderClass getPushClass() - { + public FolderClass getPushClass() { return getSyncClass(); } - public void refresh(Preferences preferences) throws MessagingException - { + public void refresh(Preferences preferences) throws MessagingException { } - public boolean isInTopGroup() - { + public boolean isInTopGroup() { return false; } - public String getStatus() - { + public String getStatus() { return status; } - public void setStatus(String status) throws MessagingException - { + public void setStatus(String status) throws MessagingException { this.status = status; } - public Account getAccount() - { + public Account getAccount() { return mAccount; } } diff --git a/src/com/fsck/k9/mail/Message.java b/src/com/fsck/k9/mail/Message.java index 56aeacdcf..b5adc6c85 100644 --- a/src/com/fsck/k9/mail/Message.java +++ b/src/com/fsck/k9/mail/Message.java @@ -7,14 +7,12 @@ import java.util.Set; import com.fsck.k9.activity.MessageReference; import com.fsck.k9.mail.store.UnavailableStorageException; -public abstract class Message implements Part, Body -{ +public abstract class Message implements Part, Body { private static final Flag[] EMPTY_FLAG_ARRAY = new Flag[0]; private MessageReference mReference = null; - public enum RecipientType - { + public enum RecipientType { TO, CC, BCC, } @@ -26,28 +24,22 @@ public abstract class Message implements Part, Body protected Folder mFolder; - public boolean olderThan(Date earliestDate) - { - if (earliestDate == null) - { + public boolean olderThan(Date earliestDate) { + if (earliestDate == null) { return false; } Date myDate = getSentDate(); - if (myDate == null) - { + if (myDate == null) { myDate = getInternalDate(); } - if (myDate != null) - { + if (myDate != null) { return myDate.before(earliestDate); } return false; } @Override - public boolean equals(Object o) - { - if (o == null || !(o instanceof Message)) - { + public boolean equals(Object o) { + if (o == null || !(o instanceof Message)) { return false; } Message other = (Message)o; @@ -57,8 +49,7 @@ public abstract class Message implements Part, Body } @Override - public int hashCode() - { + public int hashCode() { final int MULTIPLIER = 31; int result = 1; @@ -68,19 +59,16 @@ public abstract class Message implements Part, Body return result; } - public String getUid() - { + public String getUid() { return mUid; } - public void setUid(String uid) - { + public void setUid(String uid) { mReference = null; this.mUid = uid; } - public Folder getFolder() - { + public Folder getFolder() { return mFolder; } @@ -88,13 +76,11 @@ public abstract class Message implements Part, Body public abstract void setSubject(String subject) throws MessagingException; - public Date getInternalDate() - { + public Date getInternalDate() { return mInternalDate; } - public void setInternalDate(Date internalDate) - { + public void setInternalDate(Date internalDate) { this.mInternalDate = internalDate; } @@ -107,10 +93,8 @@ public abstract class Message implements Part, Body public abstract void setRecipients(RecipientType type, Address[] addresses) throws MessagingException; - public void setRecipient(RecipientType type, Address address) throws MessagingException - { - setRecipients(type, new Address[] - { + public void setRecipient(RecipientType type, Address address) throws MessagingException { + setRecipients(type, new Address[] { address }); } @@ -147,8 +131,7 @@ public abstract class Message implements Part, Body public abstract void setBody(Body body) throws MessagingException; - public boolean isMimeType(String mimeType) throws MessagingException - { + public boolean isMimeType(String mimeType) throws MessagingException { return getContentType().startsWith(mimeType); } @@ -157,8 +140,7 @@ public abstract class Message implements Part, Body /* * TODO Refactor Flags at some point to be able to store user defined flags. */ - public Flag[] getFlags() - { + public Flag[] getFlags() { return mFlags.toArray(EMPTY_FLAG_ARRAY); } @@ -170,14 +152,10 @@ public abstract class Message implements Part, Body * , the flag is removed. * @throws MessagingException */ - public void setFlag(Flag flag, boolean set) throws MessagingException - { - if (set) - { + public void setFlag(Flag flag, boolean set) throws MessagingException { + if (set) { mFlags.add(flag); - } - else - { + } else { mFlags.remove(flag); } } @@ -187,16 +165,13 @@ public abstract class Message implements Part, Body * @param flags * @param set */ - public void setFlags(Flag[] flags, boolean set) throws MessagingException - { - for (Flag flag : flags) - { + public void setFlags(Flag[] flags, boolean set) throws MessagingException { + for (Flag flag : flags) { setFlag(flag, set); } } - public boolean isSet(Flag flag) - { + public boolean isSet(Flag flag) { return mFlags.contains(flag); } @@ -209,10 +184,8 @@ public abstract class Message implements Part, Body public abstract void setCharset(String charset) throws MessagingException; - public MessageReference makeMessageReference() - { - if (mReference == null) - { + public MessageReference makeMessageReference() { + if (mReference == null) { mReference = new MessageReference(); mReference.accountUuid = getFolder().getAccount().getUuid(); mReference.folderName = getFolder().getName(); @@ -221,8 +194,7 @@ public abstract class Message implements Part, Body return mReference; } - public boolean equalsReference(MessageReference ref) - { + public boolean equalsReference(MessageReference ref) { MessageReference tmpReference = makeMessageReference(); return tmpReference.equals(ref); } diff --git a/src/com/fsck/k9/mail/MessagingException.java b/src/com/fsck/k9/mail/MessagingException.java index 7654f9155..b5f563a1b 100644 --- a/src/com/fsck/k9/mail/MessagingException.java +++ b/src/com/fsck/k9/mail/MessagingException.java @@ -1,41 +1,34 @@ package com.fsck.k9.mail; -public class MessagingException extends Exception -{ +public class MessagingException extends Exception { public static final long serialVersionUID = -1; boolean permanentFailure = false; - public MessagingException(String message) - { + public MessagingException(String message) { super(message); } - public MessagingException(String message, boolean perm) - { + public MessagingException(String message, boolean perm) { super(message); permanentFailure = perm; } - public MessagingException(String message, Throwable throwable) - { + public MessagingException(String message, Throwable throwable) { super(message, throwable); } - public MessagingException(String message, boolean perm, Throwable throwable) - { + public MessagingException(String message, boolean perm, Throwable throwable) { super(message, throwable); permanentFailure = perm; } - public boolean isPermanentFailure() - { + public boolean isPermanentFailure() { return permanentFailure; } - public void setPermanentFailure(boolean permanentFailure) - { + public void setPermanentFailure(boolean permanentFailure) { this.permanentFailure = permanentFailure; } diff --git a/src/com/fsck/k9/mail/Multipart.java b/src/com/fsck/k9/mail/Multipart.java index a83337f7f..895d76d12 100644 --- a/src/com/fsck/k9/mail/Multipart.java +++ b/src/com/fsck/k9/mail/Multipart.java @@ -7,93 +7,75 @@ import com.fsck.k9.mail.internet.MimeHeader; import com.fsck.k9.mail.internet.MimeUtility; import com.fsck.k9.mail.internet.TextBody; -public abstract class Multipart implements Body -{ +public abstract class Multipart implements Body { protected Part mParent; protected ArrayList mParts = new ArrayList(); protected String mContentType; - public void addBodyPart(BodyPart part) - { + public void addBodyPart(BodyPart part) { mParts.add(part); part.setParent(this); } - public void addBodyPart(BodyPart part, int index) - { + public void addBodyPart(BodyPart part, int index) { mParts.add(index, part); part.setParent(this); } - public BodyPart getBodyPart(int index) - { + public BodyPart getBodyPart(int index) { return mParts.get(index); } - public String getContentType() - { + public String getContentType() { return mContentType; } - public int getCount() - { + public int getCount() { return mParts.size(); } - public boolean removeBodyPart(BodyPart part) - { + public boolean removeBodyPart(BodyPart part) { part.setParent(null); return mParts.remove(part); } - public void removeBodyPart(int index) - { + public void removeBodyPart(int index) { mParts.get(index).setParent(null); mParts.remove(index); } - public Part getParent() - { + public Part getParent() { return mParent; } - public void setParent(Part parent) - { + public void setParent(Part parent) { this.mParent = parent; } - public void setEncoding(String encoding) - { - for (BodyPart part : mParts) - { - try - { + public void setEncoding(String encoding) { + for (BodyPart part : mParts) { + try { Body body = part.getBody(); - if (body instanceof TextBody) - { + if (body instanceof TextBody) { part.setHeader(MimeHeader.HEADER_CONTENT_TRANSFER_ENCODING, encoding); ((TextBody)body).setEncoding(encoding); } - } - catch (MessagingException e) - { + } catch (MessagingException e) { // Ignore } } } - public void setCharset(String charset) throws MessagingException - { + public void setCharset(String charset) throws MessagingException { if (mParts.isEmpty()) return; BodyPart part = mParts.get(0); Body body = part.getBody(); - if (body instanceof TextBody) - { + if (body instanceof TextBody) { MimeUtility.setCharset(charset, part); ((TextBody)body).setCharset(charset); } diff --git a/src/com/fsck/k9/mail/Part.java b/src/com/fsck/k9/mail/Part.java index 5141e823c..9dad93a04 100644 --- a/src/com/fsck/k9/mail/Part.java +++ b/src/com/fsck/k9/mail/Part.java @@ -4,8 +4,7 @@ package com.fsck.k9.mail; import java.io.IOException; import java.io.OutputStream; -public interface Part -{ +public interface Part { public void addHeader(String name, String value) throws MessagingException; public void removeHeader(String name) throws MessagingException; diff --git a/src/com/fsck/k9/mail/PushReceiver.java b/src/com/fsck/k9/mail/PushReceiver.java index c66754d6d..8c3e0dcde 100644 --- a/src/com/fsck/k9/mail/PushReceiver.java +++ b/src/com/fsck/k9/mail/PushReceiver.java @@ -6,8 +6,7 @@ import com.fsck.k9.helper.power.TracingPowerManager.TracingWakeLock; import android.content.Context; -public interface PushReceiver -{ +public interface PushReceiver { public Context getContext(); public void syncFolder(Folder folder); public void messagesArrived(Folder folder, List mess); diff --git a/src/com/fsck/k9/mail/Pusher.java b/src/com/fsck/k9/mail/Pusher.java index 42ed525ea..6381ccbe4 100644 --- a/src/com/fsck/k9/mail/Pusher.java +++ b/src/com/fsck/k9/mail/Pusher.java @@ -3,8 +3,7 @@ package com.fsck.k9.mail; import java.util.List; -public interface Pusher -{ +public interface Pusher { public void start(List folderNames); public void refresh(); public void stop(); diff --git a/src/com/fsck/k9/mail/Store.java b/src/com/fsck/k9/mail/Store.java index f59f6ae9e..904a16baa 100644 --- a/src/com/fsck/k9/mail/Store.java +++ b/src/com/fsck/k9/mail/Store.java @@ -22,8 +22,7 @@ import java.util.List; * performance on mobile devices. Implementations of this class should focus on * making as few network connections as possible. */ -public abstract class Store -{ +public abstract class Store { protected static final int SOCKET_CONNECT_TIMEOUT = 30000; protected static final int SOCKET_READ_TIMEOUT = 60000; @@ -38,47 +37,36 @@ public abstract class Store protected final Account mAccount; - protected Store(Account account) - { + protected Store(Account account) { mAccount = account; } /** * Get an instance of a remote mail store. */ - public synchronized static Store getRemoteInstance(Account account) throws MessagingException - { + public synchronized static Store getRemoteInstance(Account account) throws MessagingException { String uri = account.getStoreUri(); - if (uri.startsWith("local")) - { + if (uri.startsWith("local")) { throw new RuntimeException("Asked to get non-local Store object but given LocalStore URI"); } Store store = mStores.get(uri); - if (store == null) - { - if (uri.startsWith("imap")) - { + if (store == null) { + if (uri.startsWith("imap")) { store = new ImapStore(account); - } - else if (uri.startsWith("pop3")) - { + } else if (uri.startsWith("pop3")) { store = new Pop3Store(account); - } - else if (uri.startsWith("webdav")) - { + } else if (uri.startsWith("webdav")) { store = new WebDavStore(account); } - if (store != null) - { + if (store != null) { mStores.put(uri, store); } } - if (store == null) - { + if (store == null) { throw new MessagingException("Unable to locate an applicable Store for " + uri); } @@ -89,11 +77,9 @@ public abstract class Store * Get an instance of a local mail store. * @throws UnavailableStorageException if not {@link StorageProvider#isReady(Context)} */ - public synchronized static LocalStore getLocalInstance(Account account, Application application) throws MessagingException - { + public synchronized static LocalStore getLocalInstance(Account account, Application application) throws MessagingException { Store store = mLocalStores.get(account.getUuid()); - if (store == null) - { + if (store == null) { store = new LocalStore(account, application); mLocalStores.put(account.getUuid(), store); } @@ -103,43 +89,35 @@ public abstract class Store public abstract Folder getFolder(String name); - public abstract List getPersonalNamespaces(boolean forceListAll) throws MessagingException; + public abstract List getPersonalNamespaces(boolean forceListAll) throws MessagingException; public abstract void checkSettings() throws MessagingException; - public boolean isCopyCapable() - { + public boolean isCopyCapable() { return false; } - public boolean isMoveCapable() - { + public boolean isMoveCapable() { return false; } - public boolean isPushCapable() - { + public boolean isPushCapable() { return false; } - public boolean isSendCapable() - { + public boolean isSendCapable() { return false; } - public boolean isExpungeCapable() - { + public boolean isExpungeCapable() { return false; } - public void sendMessages(Message[] messages) throws MessagingException - { + public void sendMessages(Message[] messages) throws MessagingException { } - public Pusher getPusher(PushReceiver receiver) - { + public Pusher getPusher(PushReceiver receiver) { return null; } - public Account getAccount() - { + public Account getAccount() { return mAccount; } } diff --git a/src/com/fsck/k9/mail/Transport.java b/src/com/fsck/k9/mail/Transport.java index 35d5c3380..04634f01e 100644 --- a/src/com/fsck/k9/mail/Transport.java +++ b/src/com/fsck/k9/mail/Transport.java @@ -5,26 +5,19 @@ import com.fsck.k9.Account; import com.fsck.k9.mail.transport.SmtpTransport; import com.fsck.k9.mail.transport.WebDavTransport; -public abstract class Transport -{ +public abstract class Transport { protected static final int SOCKET_CONNECT_TIMEOUT = 10000; // RFC 1047 protected static final int SOCKET_READ_TIMEOUT = 300000; - public synchronized static Transport getInstance(Account account) throws MessagingException - { + public synchronized static Transport getInstance(Account account) throws MessagingException { String uri = account.getTransportUri(); - if (uri.startsWith("smtp")) - { + if (uri.startsWith("smtp")) { return new SmtpTransport(uri); - } - else if (uri.startsWith("webdav")) - { + } else if (uri.startsWith("webdav")) { return new WebDavTransport(account); - } - else - { + } else { throw new MessagingException("Unable to locate an applicable Transport for " + uri); } } diff --git a/src/com/fsck/k9/mail/filter/Base64.java b/src/com/fsck/k9/mail/filter/Base64.java index e78f7934f..6c8bf7ac1 100644 --- a/src/com/fsck/k9/mail/filter/Base64.java +++ b/src/com/fsck/k9/mail/filter/Base64.java @@ -38,8 +38,7 @@ import java.math.BigInteger; * @since 1.0-dev * @version $Id$ */ -public class Base64 implements BinaryEncoder, BinaryDecoder -{ +public class Base64 implements BinaryEncoder, BinaryDecoder { /** * Chunk size per RFC 2045 section 6.8. * @@ -57,7 +56,7 @@ public class Base64 implements BinaryEncoder, BinaryDecoder * * @see RFC 2045 section 2.1 */ - static final byte[] CHUNK_SEPARATOR = {'\r','\n'}; + static final byte[] CHUNK_SEPARATOR = {'\r', '\n'}; /** * This array is a lookup table that translates 6-bit positive integer @@ -67,8 +66,7 @@ public class Base64 implements BinaryEncoder, BinaryDecoder * Thanks to "commons" project in ws.apache.org for this code. * http://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/ */ - private static final byte[] intToBase64 = - { + private static final byte[] intToBase64 = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', @@ -91,8 +89,7 @@ public class Base64 implements BinaryEncoder, BinaryDecoder * Thanks to "commons" project in ws.apache.org for this code. * http://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/ */ - private static final byte[] base64ToInt = - { + private static final byte[] base64ToInt = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, @@ -181,8 +178,7 @@ public class Base64 implements BinaryEncoder, BinaryDecoder * Default constructor: lineLength is 76, and the lineSeparator is CRLF * when encoding, and all forms can be decoded. */ - public Base64() - { + public Base64() { this(CHUNK_SIZE, CHUNK_SEPARATOR); } @@ -201,8 +197,7 @@ public class Base64 implements BinaryEncoder, BinaryDecoder * If lineLength <= 0, then the output will not be divided into lines (chunks). * Ignored when decoding. */ - public Base64(int lineLength) - { + public Base64(int lineLength) { this(lineLength, CHUNK_SEPARATOR); } @@ -224,29 +219,21 @@ public class Base64 implements BinaryEncoder, BinaryDecoder * @throws IllegalArgumentException The provided lineSeparator included * some base64 characters. That's not going to work! */ - public Base64(int lineLength, byte[] lineSeparator) - { + public Base64(int lineLength, byte[] lineSeparator) { this.lineLength = lineLength; this.lineSeparator = new byte[lineSeparator.length]; System.arraycopy(lineSeparator, 0, this.lineSeparator, 0, lineSeparator.length); - if (lineLength > 0) - { + if (lineLength > 0) { this.encodeSize = 4 + lineSeparator.length; - } - else - { + } else { this.encodeSize = 4; } this.decodeSize = encodeSize - 1; - if (containsBase64Byte(lineSeparator)) - { + if (containsBase64Byte(lineSeparator)) { String sep; - try - { + try { sep = new String(lineSeparator, "UTF-8"); - } - catch (UnsupportedEncodingException uee) - { + } catch (UnsupportedEncodingException uee) { sep = new String(lineSeparator); } throw new IllegalArgumentException("lineSeperator must not contain base64 characters: [" + sep + "]"); @@ -258,8 +245,7 @@ public class Base64 implements BinaryEncoder, BinaryDecoder * * @return true if there is Base64 object still available for reading. */ - boolean hasData() - { + boolean hasData() { return buf != null; } @@ -268,22 +254,17 @@ public class Base64 implements BinaryEncoder, BinaryDecoder * * @return The amount of buffered data available for reading. */ - int avail() - { + int avail() { return buf != null ? pos - readPos : 0; } /** Doubles our buffer. */ - private void resizeBuf() - { - if (buf == null) - { + private void resizeBuf() { + if (buf == null) { buf = new byte[8192]; pos = 0; readPos = 0; - } - else - { + } else { byte[] b = new byte[buf.length * 2]; System.arraycopy(buf, 0, b, 0, buf.length); buf = b; @@ -302,30 +283,22 @@ public class Base64 implements BinaryEncoder, BinaryDecoder * @return The number of bytes successfully extracted into the provided * byte[] array. */ - int readResults(byte[] b, int bPos, int bAvail) - { - if (buf != null) - { + int readResults(byte[] b, int bPos, int bAvail) { + if (buf != null) { int len = Math.min(avail(), bAvail); - if (buf != b) - { + if (buf != b) { System.arraycopy(buf, readPos, b, bPos, len); readPos += len; - if (readPos >= pos) - { + if (readPos >= pos) { buf = null; } - } - else - { + } else { // Re-using the original consumer's output array is only // allowed for one round. buf = null; } return len; - } - else - { + } else { return eof ? -1 : 0; } } @@ -339,12 +312,10 @@ public class Base64 implements BinaryEncoder, BinaryDecoder * @param outPos Position to start buffering into. * @param outAvail Amount of bytes available for direct buffering. */ - void setInitialBuffer(byte[] out, int outPos, int outAvail) - { + void setInitialBuffer(byte[] out, int outPos, int outAvail) { // We can re-use consumer's original output array under // special circumstances, saving on some System.arraycopy(). - if (out != null && out.length == outAvail) - { + if (out != null && out.length == outAvail) { buf = out; pos = outPos; readPos = outPos; @@ -367,68 +338,55 @@ public class Base64 implements BinaryEncoder, BinaryDecoder * @param inPos Position to start reading data from. * @param inAvail Amount of bytes available from input for encoding. */ - void encode(byte[] in, int inPos, int inAvail) - { - if (eof) - { + void encode(byte[] in, int inPos, int inAvail) { + if (eof) { return; } // inAvail < 0 is how we're informed of EOF in the underlying data we're // encoding. - if (inAvail < 0) - { + if (inAvail < 0) { eof = true; - if (buf == null || buf.length - pos < encodeSize) - { + if (buf == null || buf.length - pos < encodeSize) { resizeBuf(); } - switch (modulus) - { - case 1: - buf[pos++] = intToBase64[(x >> 2) & MASK_6BITS]; - buf[pos++] = intToBase64[(x << 4) & MASK_6BITS]; - buf[pos++] = PAD; - buf[pos++] = PAD; - break; + switch (modulus) { + case 1: + buf[pos++] = intToBase64[(x >> 2) & MASK_6BITS]; + buf[pos++] = intToBase64[(x << 4) & MASK_6BITS]; + buf[pos++] = PAD; + buf[pos++] = PAD; + break; - case 2: - buf[pos++] = intToBase64[(x >> 10) & MASK_6BITS]; - buf[pos++] = intToBase64[(x >> 4) & MASK_6BITS]; - buf[pos++] = intToBase64[(x << 2) & MASK_6BITS]; - buf[pos++] = PAD; - break; + case 2: + buf[pos++] = intToBase64[(x >> 10) & MASK_6BITS]; + buf[pos++] = intToBase64[(x >> 4) & MASK_6BITS]; + buf[pos++] = intToBase64[(x << 2) & MASK_6BITS]; + buf[pos++] = PAD; + break; } - if (lineLength > 0) - { + if (lineLength > 0) { System.arraycopy(lineSeparator, 0, buf, pos, lineSeparator.length); pos += lineSeparator.length; } - } - else - { - for (int i = 0; i < inAvail; i++) - { - if (buf == null || buf.length - pos < encodeSize) - { + } else { + for (int i = 0; i < inAvail; i++) { + if (buf == null || buf.length - pos < encodeSize) { resizeBuf(); } modulus = (++modulus) % 3; int b = in[inPos++]; - if (b < 0) - { + if (b < 0) { b += 256; } x = (x << 8) + b; - if (0 == modulus) - { + if (0 == modulus) { buf[pos++] = intToBase64[(x >> 18) & MASK_6BITS]; buf[pos++] = intToBase64[(x >> 12) & MASK_6BITS]; buf[pos++] = intToBase64[(x >> 6) & MASK_6BITS]; buf[pos++] = intToBase64[x & MASK_6BITS]; currentLinePos += 4; - if (lineLength > 0 && lineLength <= currentLinePos) - { + if (lineLength > 0 && lineLength <= currentLinePos) { System.arraycopy(lineSeparator, 0, buf, pos, lineSeparator.length); pos += lineSeparator.length; currentLinePos = 0; @@ -459,52 +417,40 @@ public class Base64 implements BinaryEncoder, BinaryDecoder * @param inPos Position to start reading data from. * @param inAvail Amount of bytes available from input for encoding. */ - void decode(byte[] in, int inPos, int inAvail) - { - if (eof) - { + void decode(byte[] in, int inPos, int inAvail) { + if (eof) { return; } - if (inAvail < 0) - { + if (inAvail < 0) { eof = true; } - for (int i = 0; i < inAvail; i++) - { - if (buf == null || buf.length - pos < decodeSize) - { + for (int i = 0; i < inAvail; i++) { + if (buf == null || buf.length - pos < decodeSize) { resizeBuf(); } byte b = in[inPos++]; - if (b == PAD) - { + if (b == PAD) { x = x << 6; - switch (modulus) - { - case 2: - x = x << 6; - buf[pos++] = (byte)((x >> 16) & MASK_8BITS); - break; - case 3: - buf[pos++] = (byte)((x >> 16) & MASK_8BITS); - buf[pos++] = (byte)((x >> 8) & MASK_8BITS); - break; + switch (modulus) { + case 2: + x = x << 6; + buf[pos++] = (byte)((x >> 16) & MASK_8BITS); + break; + case 3: + buf[pos++] = (byte)((x >> 16) & MASK_8BITS); + buf[pos++] = (byte)((x >> 8) & MASK_8BITS); + break; } // WE'RE DONE!!!! eof = true; return; - } - else - { - if (b >= 0 && b < base64ToInt.length) - { + } else { + if (b >= 0 && b < base64ToInt.length) { int result = base64ToInt[b]; - if (result >= 0) - { + if (result >= 0) { modulus = (++modulus) % 4; x = (x << 6) + result; - if (modulus == 0) - { + if (modulus == 0) { buf[pos++] = (byte)((x >> 16) & MASK_8BITS); buf[pos++] = (byte)((x >> 8) & MASK_8BITS); buf[pos++] = (byte)(x & MASK_8BITS); @@ -522,8 +468,7 @@ public class Base64 implements BinaryEncoder, BinaryDecoder * The value to test * @return true if the value is defined in the the base 64 alphabet, false otherwise. */ - public static boolean isBase64(byte octet) - { + public static boolean isBase64(byte octet) { return octet == PAD || (octet >= 0 && octet < base64ToInt.length && base64ToInt[octet] != -1); } @@ -536,12 +481,9 @@ public class Base64 implements BinaryEncoder, BinaryDecoder * @return true if all bytes are valid characters in the Base64 alphabet or if the byte array is * empty; false, otherwise */ - public static boolean isArrayByteBase64(byte[] arrayOctet) - { - for (byte anArrayOctet : arrayOctet) - { - if (!isBase64(anArrayOctet) && !isWhiteSpace(anArrayOctet)) - { + public static boolean isArrayByteBase64(byte[] arrayOctet) { + for (byte anArrayOctet : arrayOctet) { + if (!isBase64(anArrayOctet) && !isWhiteSpace(anArrayOctet)) { return false; } } @@ -555,12 +497,9 @@ public class Base64 implements BinaryEncoder, BinaryDecoder * byte array to test * @return true if any byte is a valid character in the Base64 alphabet; false herwise */ - private static boolean containsBase64Byte(byte[] arrayOctet) - { - for (byte element : arrayOctet) - { - if (isBase64(element)) - { + private static boolean containsBase64Byte(byte[] arrayOctet) { + for (byte element : arrayOctet) { + if (isBase64(element)) { return true; } } @@ -574,8 +513,7 @@ public class Base64 implements BinaryEncoder, BinaryDecoder * binary data to encode * @return Base64 characters */ - public static byte[] encodeBase64(byte[] binaryData) - { + public static byte[] encodeBase64(byte[] binaryData) { return encodeBase64(binaryData, false); } @@ -586,8 +524,7 @@ public class Base64 implements BinaryEncoder, BinaryDecoder * binary data to encode * @return Base64 characters chunked in 76 character blocks */ - public static byte[] encodeBase64Chunked(byte[] binaryData) - { + public static byte[] encodeBase64Chunked(byte[] binaryData) { return encodeBase64(binaryData, true); } @@ -601,10 +538,8 @@ public class Base64 implements BinaryEncoder, BinaryDecoder * @throws DecoderException * if the parameter supplied is not of type byte[] */ - public Object decode(Object pObject) throws DecoderException - { - if (!(pObject instanceof byte[])) - { + public Object decode(Object pObject) throws DecoderException { + if (!(pObject instanceof byte[])) { throw new DecoderException("Parameter supplied to Base64 decode is not a byte[]"); } return decode((byte[]) pObject); @@ -617,8 +552,7 @@ public class Base64 implements BinaryEncoder, BinaryDecoder * A byte array containing Base64 character data * @return a byte array containing binary data */ - public byte[] decode(byte[] pArray) - { + public byte[] decode(byte[] pArray) { return decodeBase64(pArray); } @@ -633,27 +567,22 @@ public class Base64 implements BinaryEncoder, BinaryDecoder * @throws IllegalArgumentException * Thrown when the input array needs an output array bigger than {@link Integer#MAX_VALUE} */ - public static byte[] encodeBase64(byte[] binaryData, boolean isChunked) - { - if (binaryData == null || binaryData.length == 0) - { + public static byte[] encodeBase64(byte[] binaryData, boolean isChunked) { + if (binaryData == null || binaryData.length == 0) { return binaryData; } Base64 b64 = isChunked ? new Base64() : new Base64(0); long len = (binaryData.length * 4) / 3; long mod = len % 4; - if (mod != 0) - { + if (mod != 0) { len += 4 - mod; } - if (isChunked) - { + if (isChunked) { len += (1 + (len / CHUNK_SIZE)) * CHUNK_SEPARATOR.length; } - if (len > Integer.MAX_VALUE) - { + if (len > Integer.MAX_VALUE) { throw new IllegalArgumentException( "Input array too big, output array would be bigger than Integer.MAX_VALUE=" + Integer.MAX_VALUE); } @@ -663,8 +592,7 @@ public class Base64 implements BinaryEncoder, BinaryDecoder b64.encode(binaryData, 0, -1); // Notify encoder of EOF. // Encoder might have resized, even though it was unnecessary. - if (b64.buf != buf) - { + if (b64.buf != buf) { b64.readResults(buf, 0, buf.length); } return buf; @@ -676,10 +604,8 @@ public class Base64 implements BinaryEncoder, BinaryDecoder * @param base64Data Byte array containing Base64 data * @return Array containing decoded data. */ - public static byte[] decodeBase64(byte[] base64Data) - { - if (base64Data == null || base64Data.length == 0) - { + public static byte[] decodeBase64(byte[] base64Data) { + if (base64Data == null || base64Data.length == 0) { return base64Data; } Base64 b64 = new Base64(); @@ -703,17 +629,15 @@ public class Base64 implements BinaryEncoder, BinaryDecoder * @param byteToCheck the byte to check * @return true if byte is whitespace, false otherwise */ - private static boolean isWhiteSpace(byte byteToCheck) - { - switch (byteToCheck) - { - case ' ' : - case '\n' : - case '\r' : - case '\t' : - return true; - default : - return false; + private static boolean isWhiteSpace(byte byteToCheck) { + switch (byteToCheck) { + case ' ' : + case '\n' : + case '\r' : + case '\t' : + return true; + default : + return false; } } @@ -725,15 +649,12 @@ public class Base64 implements BinaryEncoder, BinaryDecoder * The base-64 encoded data to groom * @return The data, less non-base64 characters (see RFC 2045). */ - static byte[] discardNonBase64(byte[] data) - { + static byte[] discardNonBase64(byte[] data) { byte groomedData[] = new byte[data.length]; int bytesCopied = 0; - for (byte element : data) - { - if (isBase64(element)) - { + for (byte element : data) { + if (isBase64(element)) { groomedData[bytesCopied++] = element; } } @@ -757,10 +678,8 @@ public class Base64 implements BinaryEncoder, BinaryDecoder * @throws EncoderException * if the parameter supplied is not of type byte[] */ - public Object encode(Object pObject) throws EncoderException - { - if (!(pObject instanceof byte[])) - { + public Object encode(Object pObject) throws EncoderException { + if (!(pObject instanceof byte[])) { throw new EncoderException("Parameter supplied to Base64 encode is not a byte[]"); } return encode((byte[]) pObject); @@ -773,8 +692,7 @@ public class Base64 implements BinaryEncoder, BinaryDecoder * a byte array containing binary data * @return A byte array containing only Base64 character data */ - public byte[] encode(byte[] pArray) - { + public byte[] encode(byte[] pArray) { return encodeBase64(pArray, false); } @@ -786,8 +704,7 @@ public class Base64 implements BinaryEncoder, BinaryDecoder * @param pArray a byte array containing base64 character data * @return A BigInteger */ - public static BigInteger decodeInteger(byte[] pArray) - { + public static BigInteger decodeInteger(byte[] pArray) { return new BigInteger(1, decodeBase64(pArray)); } @@ -799,10 +716,8 @@ public class Base64 implements BinaryEncoder, BinaryDecoder * @return A byte array containing base64 character data * @throws NullPointerException if null is passed in */ - public static byte[] encodeInteger(BigInteger bigInt) - { - if (bigInt == null) - { + public static byte[] encodeInteger(BigInteger bigInt) { + if (bigInt == null) { throw new NullPointerException("encodeInteger called with null parameter"); } @@ -816,16 +731,14 @@ public class Base64 implements BinaryEncoder, BinaryDecoder * @param bigInt BigInteger to be converted * @return a byte array representation of the BigInteger parameter */ - static byte[] toIntegerBytes(BigInteger bigInt) - { + static byte[] toIntegerBytes(BigInteger bigInt) { int bitlen = bigInt.bitLength(); // round bitlen bitlen = ((bitlen + 7) >> 3) << 3; byte[] bigBytes = bigInt.toByteArray(); if (((bigInt.bitLength() % 8) != 0) && - (((bigInt.bitLength() / 8) + 1) == (bitlen / 8))) - { + (((bigInt.bitLength() / 8) + 1) == (bitlen / 8))) { return bigBytes; } @@ -834,8 +747,7 @@ public class Base64 implements BinaryEncoder, BinaryDecoder int len = bigBytes.length; // if bigInt is exactly byte-aligned, just skip signbit in copy - if ((bigInt.bitLength() % 8) == 0) - { + if ((bigInt.bitLength() % 8) == 0) { startSrc = 1; len--; } diff --git a/src/com/fsck/k9/mail/filter/Base64OutputStream.java b/src/com/fsck/k9/mail/filter/Base64OutputStream.java index 34007d168..0dff4e8f9 100644 --- a/src/com/fsck/k9/mail/filter/Base64OutputStream.java +++ b/src/com/fsck/k9/mail/filter/Base64OutputStream.java @@ -40,8 +40,7 @@ import java.io.OutputStream; * @see RFC 2045 * @since 1.0-dev */ -public class Base64OutputStream extends FilterOutputStream -{ +public class Base64OutputStream extends FilterOutputStream { private final boolean doEncode; private final Base64 base64; private final byte[] singleByte = new byte[1]; @@ -52,8 +51,7 @@ public class Base64OutputStream extends FilterOutputStream * * @param out OutputStream to wrap. */ - public Base64OutputStream(OutputStream out) - { + public Base64OutputStream(OutputStream out) { this(out, true); } @@ -65,8 +63,7 @@ public class Base64OutputStream extends FilterOutputStream * @param doEncode true if we should encode all data written to us, * false if we should decode. */ - public Base64OutputStream(OutputStream out, boolean doEncode) - { + public Base64OutputStream(OutputStream out, boolean doEncode) { super(out); this.doEncode = doEncode; this.base64 = new Base64(); @@ -88,8 +85,7 @@ public class Base64OutputStream extends FilterOutputStream * If lineLength <= 0, the lineSeparator is not used. * If doEncode is false lineSeparator is ignored. */ - public Base64OutputStream(OutputStream out, boolean doEncode, int lineLength, byte[] lineSeparator) - { + public Base64OutputStream(OutputStream out, boolean doEncode, int lineLength, byte[] lineSeparator) { super(out); this.doEncode = doEncode; this.base64 = new Base64(lineLength, lineSeparator); @@ -99,8 +95,7 @@ public class Base64OutputStream extends FilterOutputStream * Writes the specified byte to this output stream. */ @Override - public void write(int i) throws IOException - { + public void write(int i) throws IOException { singleByte[0] = (byte) i; write(singleByte, 0, 1); } @@ -119,28 +114,17 @@ public class Base64OutputStream extends FilterOutputStream * @throws IndexOutOfBoundsException if offset, len or buffer size are invalid */ @Override - public void write(byte b[], int offset, int len) throws IOException - { - if (b == null) - { + public void write(byte b[], int offset, int len) throws IOException { + if (b == null) { throw new NullPointerException(); - } - else if (offset < 0 || len < 0 || offset + len < 0) - { + } else if (offset < 0 || len < 0 || offset + len < 0) { throw new IndexOutOfBoundsException(); - } - else if (offset > b.length || offset + len > b.length) - { + } else if (offset > b.length || offset + len > b.length) { throw new IndexOutOfBoundsException(); - } - else if (len > 0) - { - if (doEncode) - { + } else if (len > 0) { + if (doEncode) { base64.encode(b, offset, len); - } - else - { + } else { base64.decode(b, offset, len); } flush(false); @@ -156,20 +140,16 @@ public class Base64OutputStream extends FilterOutputStream * OutputStream should also be flushed. * @throws IOException if an I/O error occurs. */ - private void flush(boolean propogate) throws IOException - { + private void flush(boolean propogate) throws IOException { int avail = base64.avail(); - if (avail > 0) - { + if (avail > 0) { byte[] buf = new byte[avail]; int c = base64.readResults(buf, 0, avail); - if (c > 0) - { + if (c > 0) { out.write(buf, 0, c); } } - if (propogate) - { + if (propogate) { out.flush(); } } @@ -181,8 +161,7 @@ public class Base64OutputStream extends FilterOutputStream * @throws IOException if an I/O error occurs. */ @Override - public void flush() throws IOException - { + public void flush() throws IOException { flush(true); } @@ -191,15 +170,11 @@ public class Base64OutputStream extends FilterOutputStream * underlying stream is flushed but not closed. */ @Override - public void close() throws IOException - { + public void close() throws IOException { // Notify encoder of EOF (-1). - if (doEncode) - { + if (doEncode) { base64.encode(singleByte, 0, -1); - } - else - { + } else { base64.decode(singleByte, 0, -1); } flush(); diff --git a/src/com/fsck/k9/mail/filter/CountingOutputStream.java b/src/com/fsck/k9/mail/filter/CountingOutputStream.java index 4b6df027d..19a5d7661 100644 --- a/src/com/fsck/k9/mail/filter/CountingOutputStream.java +++ b/src/com/fsck/k9/mail/filter/CountingOutputStream.java @@ -7,22 +7,18 @@ import java.io.OutputStream; * A simple OutputStream that does nothing but count how many bytes are written to it and * makes that count available to callers. */ -public class CountingOutputStream extends OutputStream -{ +public class CountingOutputStream extends OutputStream { private long mCount; - public CountingOutputStream() - { + public CountingOutputStream() { } - public long getCount() - { + public long getCount() { return mCount; } @Override - public void write(int oneByte) throws IOException - { + public void write(int oneByte) throws IOException { mCount++; } } diff --git a/src/com/fsck/k9/mail/filter/EOLConvertingOutputStream.java b/src/com/fsck/k9/mail/filter/EOLConvertingOutputStream.java index dc6733ca7..ea89c3083 100644 --- a/src/com/fsck/k9/mail/filter/EOLConvertingOutputStream.java +++ b/src/com/fsck/k9/mail/filter/EOLConvertingOutputStream.java @@ -4,23 +4,18 @@ import java.io.FilterOutputStream; import java.io.IOException; import java.io.OutputStream; -public class EOLConvertingOutputStream extends FilterOutputStream -{ +public class EOLConvertingOutputStream extends FilterOutputStream { private int lastChar; private boolean ignoreNextIfLF = false; - public EOLConvertingOutputStream(OutputStream out) - { + public EOLConvertingOutputStream(OutputStream out) { super(out); } @Override - public void write(int oneByte) throws IOException - { - if (!ignoreNextIfLF) - { - if ((oneByte == '\n') && (lastChar != '\r')) - { + public void write(int oneByte) throws IOException { + if (!ignoreNextIfLF) { + if ((oneByte == '\n') && (lastChar != '\r')) { super.write('\r'); } super.write(oneByte); @@ -30,10 +25,8 @@ public class EOLConvertingOutputStream extends FilterOutputStream } @Override - public void flush() throws IOException - { - if (lastChar == '\r') - { + public void flush() throws IOException { + if (lastChar == '\r') { super.write('\n'); lastChar = '\n'; diff --git a/src/com/fsck/k9/mail/filter/FixedLengthInputStream.java b/src/com/fsck/k9/mail/filter/FixedLengthInputStream.java index 9c5c0db40..f1cc21d90 100644 --- a/src/com/fsck/k9/mail/filter/FixedLengthInputStream.java +++ b/src/com/fsck/k9/mail/filter/FixedLengthInputStream.java @@ -9,69 +9,53 @@ import java.io.InputStream; * is used to allow a client to read directly from an underlying protocol stream without reading * past where the protocol handler intended the client to read. */ -public class FixedLengthInputStream extends InputStream -{ +public class FixedLengthInputStream extends InputStream { private InputStream mIn; private int mLength; private int mCount; - public FixedLengthInputStream(InputStream in, int length) - { + public FixedLengthInputStream(InputStream in, int length) { this.mIn = in; this.mLength = length; } @Override - public int available() throws IOException - { + public int available() throws IOException { return mLength - mCount; } @Override - public int read() throws IOException - { - if (mCount < mLength) - { + public int read() throws IOException { + if (mCount < mLength) { mCount++; return mIn.read(); - } - else - { + } else { return -1; } } @Override - public int read(byte[] b, int offset, int length) throws IOException - { - if (mCount < mLength) - { + public int read(byte[] b, int offset, int length) throws IOException { + if (mCount < mLength) { int d = mIn.read(b, offset, Math.min(mLength - mCount, length)); - if (d == -1) - { + if (d == -1) { return -1; - } - else - { + } else { mCount += d; return d; } - } - else - { + } else { return -1; } } @Override - public int read(byte[] b) throws IOException - { + public int read(byte[] b) throws IOException { return read(b, 0, b.length); } @Override - public String toString() - { + public String toString() { return String.format("FixedLengthInputStream(in=%s, length=%d)", mIn.toString(), mLength); } } diff --git a/src/com/fsck/k9/mail/filter/LineWrapOutputStream.java b/src/com/fsck/k9/mail/filter/LineWrapOutputStream.java index 9b7c3ed5b..5e8d87643 100644 --- a/src/com/fsck/k9/mail/filter/LineWrapOutputStream.java +++ b/src/com/fsck/k9/mail/filter/LineWrapOutputStream.java @@ -4,8 +4,7 @@ import java.io.FilterOutputStream; import java.io.IOException; import java.io.OutputStream; -public class LineWrapOutputStream extends FilterOutputStream -{ +public class LineWrapOutputStream extends FilterOutputStream { private static final byte[] CRLF = new byte[] {'\r', '\n'}; private byte[] buffer; @@ -14,21 +13,17 @@ public class LineWrapOutputStream extends FilterOutputStream private int endOfLastWord = 0; - public LineWrapOutputStream(OutputStream out, int maxLineLength) - { + public LineWrapOutputStream(OutputStream out, int maxLineLength) { super(out); buffer = new byte[maxLineLength - 2]; } @Override - public void write(int oneByte) throws IOException - { + public void write(int oneByte) throws IOException { // Buffer full? - if (lineLength == buffer.length) - { + if (lineLength == buffer.length) { // Usable word-boundary found earlier? - if (endOfLastWord > 0) - { + if (endOfLastWord > 0) { // Yes, so output everything up to that word-boundary out.write(buffer, bufferStart, endOfLastWord - bufferStart); out.write(CRLF); @@ -38,15 +33,12 @@ public class LineWrapOutputStream extends FilterOutputStream // Skip the in the buffer endOfLastWord++; lineLength = buffer.length - endOfLastWord; - if (lineLength > 0) - { + if (lineLength > 0) { // Copy rest of the buffer to the front System.arraycopy(buffer, endOfLastWord + 0, buffer, 0, lineLength); } endOfLastWord = 0; - } - else - { + } else { // No word-boundary found, so output whole buffer out.write(buffer, bufferStart, buffer.length - bufferStart); out.write(CRLF); @@ -55,11 +47,9 @@ public class LineWrapOutputStream extends FilterOutputStream } } - if ((oneByte == '\n') || (oneByte == '\r')) - { + if ((oneByte == '\n') || (oneByte == '\r')) { // or character found, so output buffer ... - if (lineLength - bufferStart > 0) - { + if (lineLength - bufferStart > 0) { out.write(buffer, bufferStart, lineLength - bufferStart); } // ... and that character @@ -67,12 +57,9 @@ public class LineWrapOutputStream extends FilterOutputStream lineLength = 0; bufferStart = 0; endOfLastWord = 0; - } - else - { + } else { // Remember this position as last word-boundary if found - if (oneByte == ' ') - { + if (oneByte == ' ') { endOfLastWord = lineLength; } @@ -83,11 +70,9 @@ public class LineWrapOutputStream extends FilterOutputStream } @Override - public void flush() throws IOException - { + public void flush() throws IOException { // Buffer empty? - if (lineLength > bufferStart) - { + if (lineLength > bufferStart) { // Output everything we have up till now out.write(buffer, bufferStart, lineLength - bufferStart); diff --git a/src/com/fsck/k9/mail/filter/PeekableInputStream.java b/src/com/fsck/k9/mail/filter/PeekableInputStream.java index 479b42a28..9ef98abe3 100644 --- a/src/com/fsck/k9/mail/filter/PeekableInputStream.java +++ b/src/com/fsck/k9/mail/filter/PeekableInputStream.java @@ -9,35 +9,27 @@ import java.io.InputStream; * client of this stream can call peek() to see the next available byte in the stream * and a subsequent read will still return the peeked byte. */ -public class PeekableInputStream extends InputStream -{ +public class PeekableInputStream extends InputStream { private InputStream mIn; private boolean mPeeked; private int mPeekedByte; - public PeekableInputStream(InputStream in) - { + public PeekableInputStream(InputStream in) { this.mIn = in; } @Override - public int read() throws IOException - { - if (!mPeeked) - { + public int read() throws IOException { + if (!mPeeked) { return mIn.read(); - } - else - { + } else { mPeeked = false; return mPeekedByte; } } - public int peek() throws IOException - { - if (!mPeeked) - { + public int peek() throws IOException { + if (!mPeeked) { mPeekedByte = read(); mPeeked = true; } @@ -45,37 +37,28 @@ public class PeekableInputStream extends InputStream } @Override - public int read(byte[] b, int offset, int length) throws IOException - { - if (!mPeeked) - { + public int read(byte[] b, int offset, int length) throws IOException { + if (!mPeeked) { return mIn.read(b, offset, length); - } - else - { + } else { b[0] = (byte)mPeekedByte; mPeeked = false; int r = mIn.read(b, offset + 1, length - 1); - if (r == -1) - { + if (r == -1) { return 1; - } - else - { + } else { return r + 1; } } } @Override - public int read(byte[] b) throws IOException - { + public int read(byte[] b) throws IOException { return read(b, 0, b.length); } @Override - public String toString() - { + public String toString() { return String.format("PeekableInputStream(in=%s, peeked=%b, peekedByte=%d)", mIn.toString(), mPeeked, mPeekedByte); } diff --git a/src/com/fsck/k9/mail/filter/SmtpDataStuffing.java b/src/com/fsck/k9/mail/filter/SmtpDataStuffing.java index c212082a8..bc155c6a1 100644 --- a/src/com/fsck/k9/mail/filter/SmtpDataStuffing.java +++ b/src/com/fsck/k9/mail/filter/SmtpDataStuffing.java @@ -4,38 +4,28 @@ import java.io.FilterOutputStream; import java.io.IOException; import java.io.OutputStream; -public class SmtpDataStuffing extends FilterOutputStream -{ +public class SmtpDataStuffing extends FilterOutputStream { private static final int STATE_NORMAL = 0; private static final int STATE_CR = 1; private static final int STATE_CRLF = 2; private int state = STATE_NORMAL; - public SmtpDataStuffing(OutputStream out) - { + public SmtpDataStuffing(OutputStream out) { super(out); } @Override - public void write(int oneByte) throws IOException - { - if (oneByte == '\r') - { + public void write(int oneByte) throws IOException { + if (oneByte == '\r') { state = STATE_CR; - } - else if ((state == STATE_CR) && (oneByte == '\n')) - { + } else if ((state == STATE_CR) && (oneByte == '\n')) { state = STATE_CRLF; - } - else if ((state == STATE_CRLF) && (oneByte == '.')) - { + } else if ((state == STATE_CRLF) && (oneByte == '.')) { // Read so this line needs an additional period. super.write('.'); state = STATE_NORMAL; - } - else - { + } else { state = STATE_NORMAL; } super.write(oneByte); diff --git a/src/com/fsck/k9/mail/filter/StatusOutputStream.java b/src/com/fsck/k9/mail/filter/StatusOutputStream.java index a3c95f118..db66b6520 100644 --- a/src/com/fsck/k9/mail/filter/StatusOutputStream.java +++ b/src/com/fsck/k9/mail/filter/StatusOutputStream.java @@ -8,24 +8,19 @@ import java.io.FilterOutputStream; import java.io.IOException; import java.io.OutputStream; -public class StatusOutputStream extends FilterOutputStream -{ +public class StatusOutputStream extends FilterOutputStream { private long mCount = 0; - public StatusOutputStream(OutputStream out) - { + public StatusOutputStream(OutputStream out) { super(out); } @Override - public void write(int oneByte) throws IOException - { + public void write(int oneByte) throws IOException { super.write(oneByte); mCount++; - if (Config.LOGV) - { - if (mCount % 1024 == 0) - { + if (Config.LOGV) { + if (mCount % 1024 == 0) { Log.v(K9.LOG_TAG, "# " + mCount); } } diff --git a/src/com/fsck/k9/mail/internet/BinaryTempFileBody.java b/src/com/fsck/k9/mail/internet/BinaryTempFileBody.java index f7fdf52e7..4ee161cbc 100644 --- a/src/com/fsck/k9/mail/internet/BinaryTempFileBody.java +++ b/src/com/fsck/k9/mail/internet/BinaryTempFileBody.java @@ -13,47 +13,37 @@ import java.io.*; * and writeTo one time. After writeTo is called, or the InputStream returned from * getInputStream is closed the file is deleted and the Body should be considered disposed of. */ -public class BinaryTempFileBody implements Body -{ +public class BinaryTempFileBody implements Body { private static File mTempDirectory; private File mFile; - public static void setTempDirectory(File tempDirectory) - { + public static void setTempDirectory(File tempDirectory) { mTempDirectory = tempDirectory; } - public BinaryTempFileBody() - { - if (mTempDirectory == null) - { + public BinaryTempFileBody() { + if (mTempDirectory == null) { throw new RuntimeException("setTempDirectory has not been called on BinaryTempFileBody!"); } } - public OutputStream getOutputStream() throws IOException - { + public OutputStream getOutputStream() throws IOException { mFile = File.createTempFile("body", null, mTempDirectory); mFile.deleteOnExit(); return new FileOutputStream(mFile); } - public InputStream getInputStream() throws MessagingException - { - try - { + public InputStream getInputStream() throws MessagingException { + try { return new BinaryTempFileBodyInputStream(new FileInputStream(mFile)); - } - catch (IOException ioe) - { + } catch (IOException ioe) { throw new MessagingException("Unable to open body", ioe); } } - public void writeTo(OutputStream out) throws IOException, MessagingException - { + public void writeTo(OutputStream out) throws IOException, MessagingException { InputStream in = getInputStream(); Base64OutputStream base64Out = new Base64OutputStream(out); IOUtils.copy(in, base64Out); @@ -61,16 +51,13 @@ public class BinaryTempFileBody implements Body mFile.delete(); } - class BinaryTempFileBodyInputStream extends FilterInputStream - { - public BinaryTempFileBodyInputStream(InputStream in) - { + class BinaryTempFileBodyInputStream extends FilterInputStream { + public BinaryTempFileBodyInputStream(InputStream in) { super(in); } @Override - public void close() throws IOException - { + public void close() throws IOException { super.close(); mFile.delete(); } diff --git a/src/com/fsck/k9/mail/internet/DecoderUtil.java b/src/com/fsck/k9/mail/internet/DecoderUtil.java index 7590c45a7..6580199e9 100644 --- a/src/com/fsck/k9/mail/internet/DecoderUtil.java +++ b/src/com/fsck/k9/mail/internet/DecoderUtil.java @@ -20,8 +20,7 @@ import org.apache.james.mime4j.util.CharsetUtil; * decode emoji characters in the Subject headers. The method to decode emoji depends on the MimeMessage class because * it has to be determined with the sender address, the mailer and so on. */ -public class DecoderUtil -{ +public class DecoderUtil { /** * Decodes an encoded word encoded with the 'B' encoding (described in * RFC 2047) found in a header field body. @@ -30,25 +29,18 @@ public class DecoderUtil * @param charset the Java charset to use. * @return the decoded string. */ - private static String decodeB(String encodedWord, String charset) - { + private static String decodeB(String encodedWord, String charset) { byte[] bytes; - try - { + try { bytes = encodedWord.getBytes("US-ASCII"); - } - catch (UnsupportedEncodingException e) - { + } catch (UnsupportedEncodingException e) { return null; } Base64InputStream is = new Base64InputStream(new ByteArrayInputStream(bytes)); - try - { + try { return MimeUtility.readToString(is, charset); - } - catch (IOException e) - { + } catch (IOException e) { return null; } } @@ -61,43 +53,32 @@ public class DecoderUtil * @param charset the Java charset to use. * @return the decoded string. */ - private static String decodeQ(String encodedWord, String charset) - { + private static String decodeQ(String encodedWord, String charset) { /* * Replace _ with =20 */ StringBuffer sb = new StringBuffer(); - for (int i = 0; i < encodedWord.length(); i++) - { + for (int i = 0; i < encodedWord.length(); i++) { char c = encodedWord.charAt(i); - if (c == '_') - { + if (c == '_') { sb.append("=20"); - } - else - { + } else { sb.append(c); } } byte[] bytes; - try - { + try { bytes = sb.toString().getBytes("US-ASCII"); - } - catch (UnsupportedEncodingException e) - { + } catch (UnsupportedEncodingException e) { return null; } QuotedPrintableInputStream is = new QuotedPrintableInputStream(new ByteArrayInputStream(bytes)); - try - { + try { return MimeUtility.readToString(is, charset); - } - catch (IOException e) - { + } catch (IOException e) { return null; } } @@ -114,13 +95,11 @@ public class DecoderUtil * @param message the message which has the string. * @return the decoded string. */ - public static String decodeEncodedWords(String body, Message message) - { + public static String decodeEncodedWords(String body, Message message) { // ANDROID: Most strings will not include "=?" so a quick test can prevent unneeded // object creation. This could also be handled via lazy creation of the StringBuilder. - if (body.indexOf("=?") == -1) - { + if (body.indexOf("=?") == -1) { return body; } @@ -129,27 +108,23 @@ public class DecoderUtil StringBuilder sb = new StringBuilder(); - while (true) - { + while (true) { int begin = body.indexOf("=?", previousEnd); // ANDROID: The mime4j original version has an error here. It gets confused if // the encoded string begins with an '=' (just after "?Q?"). This patch seeks forward // to find the two '?' in the "header", before looking for the final "?=". int endScan = begin + 2; - if (begin != -1) - { + if (begin != -1) { int qm1 = body.indexOf('?', endScan + 2); int qm2 = body.indexOf('?', qm1 + 1); - if (qm2 != -1) - { + if (qm2 != -1) { endScan = qm2 + 1; } } int end = begin == -1 ? -1 : body.indexOf("?=", endScan); - if (end == -1) - { + if (end == -1) { if (previousEnd == 0) return body; @@ -161,15 +136,11 @@ public class DecoderUtil String sep = body.substring(previousEnd, begin); String decoded = decodeEncodedWord(body, begin, end, message); - if (decoded == null) - { + if (decoded == null) { sb.append(sep); sb.append(body.substring(begin, end)); - } - else - { - if (!previousWasEncoded || !CharsetUtil.isWhitespace(sep)) - { + } else { + if (!previousWasEncoded || !CharsetUtil.isWhitespace(sep)) { sb.append(sep); } sb.append(decoded); @@ -181,8 +152,7 @@ public class DecoderUtil } // return null on error - private static String decodeEncodedWord(String body, int begin, int end, Message message) - { + private static String decodeEncodedWord(String body, int begin, int end, Message message) { int qm1 = body.indexOf('?', begin + 2); if (qm1 == end - 2) return null; @@ -196,31 +166,22 @@ public class DecoderUtil String encodedText = body.substring(qm2 + 1, end - 2); String charset; - try - { + try { charset = MimeUtility.fixupCharset(mimeCharset, message); - } - catch (MessagingException e) - { + } catch (MessagingException e) { return null; } - if (encodedText.length() == 0) - { + if (encodedText.length() == 0) { Log.w(K9.LOG_TAG, "Missing encoded text in encoded word: '" + body.substring(begin, end) + "'"); return null; } - if (encoding.equalsIgnoreCase("Q")) - { + if (encoding.equalsIgnoreCase("Q")) { return decodeQ(encodedText, charset); - } - else if (encoding.equalsIgnoreCase("B")) - { + } else if (encoding.equalsIgnoreCase("B")) { return DecoderUtil.decodeB(encodedText, charset); - } - else - { + } else { Log.w(K9.LOG_TAG, "Warning: Unknown encoding in encoded word '" + body.substring(begin, end) + "'"); return null; } diff --git a/src/com/fsck/k9/mail/internet/Iso2022JpToShiftJisInputStream.java b/src/com/fsck/k9/mail/internet/Iso2022JpToShiftJisInputStream.java index b5585898b..804a9434b 100644 --- a/src/com/fsck/k9/mail/internet/Iso2022JpToShiftJisInputStream.java +++ b/src/com/fsck/k9/mail/internet/Iso2022JpToShiftJisInputStream.java @@ -4,10 +4,8 @@ import java.io.IOException; import java.io.InputStream; import java.nio.charset.MalformedInputException; -class Iso2022JpToShiftJisInputStream extends InputStream -{ - private enum Charset - { +class Iso2022JpToShiftJisInputStream extends InputStream { + private enum Charset { ASCII, JISX0201, JISX0208, } @@ -16,26 +14,21 @@ class Iso2022JpToShiftJisInputStream extends InputStream private int out; private boolean hasOut = false; - public Iso2022JpToShiftJisInputStream(InputStream in) - { + public Iso2022JpToShiftJisInputStream(InputStream in) { mIn = in; } @Override - public int read() throws IOException - { - if (hasOut) - { + public int read() throws IOException { + if (hasOut) { hasOut = false; return out; } int in1 = mIn.read(); - if (in1 == 0x1b) - { + if (in1 == 0x1b) { in1 = mIn.read(); - if (in1 == '(') - { + if (in1 == '(') { in1 = mIn.read(); if (in1 == 'B' || in1 == 'J') charset = Charset.ASCII; @@ -43,16 +36,13 @@ class Iso2022JpToShiftJisInputStream extends InputStream charset = Charset.JISX0201; else throw new MalformedInputException(0); - } - else if (in1 == '$') - { + } else if (in1 == '$') { in1 = mIn.read(); if (in1 == '@' || in1 == 'B') charset = Charset.JISX0208; else throw new MalformedInputException(0); - } - else + } else throw new MalformedInputException(0); in1 = mIn.read(); } @@ -63,26 +53,25 @@ class Iso2022JpToShiftJisInputStream extends InputStream if (in1 < 0x21 || in1 >= 0x7f) return in1; - switch (charset) - { - case ASCII: - return in1; - case JISX0201: - return in1 + 0x80; - case JISX0208: - int in2 = mIn.read(); - if (in2 < 0x21 || in2 >= 0x7f) - throw new MalformedInputException(0); + switch (charset) { + case ASCII: + return in1; + case JISX0201: + return in1 + 0x80; + case JISX0208: + int in2 = mIn.read(); + if (in2 < 0x21 || in2 >= 0x7f) + throw new MalformedInputException(0); - int out1 = (in1 + 1) / 2 + (in1 < 0x5f ? 0x70 : 0xb0); - int out2 = in2 + (in1 % 2 == 0 ? 0x7e : in2 < 0x60 ? 0x1f : 0x20); + int out1 = (in1 + 1) / 2 + (in1 < 0x5f ? 0x70 : 0xb0); + int out2 = in2 + (in1 % 2 == 0 ? 0x7e : in2 < 0x60 ? 0x1f : 0x20); - out = out2; - hasOut = true; + out = out2; + hasOut = true; - return out1; - default: - throw new RuntimeException(); + return out1; + default: + throw new RuntimeException(); } } } diff --git a/src/com/fsck/k9/mail/internet/MimeBodyPart.java b/src/com/fsck/k9/mail/internet/MimeBodyPart.java index e58d44e08..bc8c058f0 100644 --- a/src/com/fsck/k9/mail/internet/MimeBodyPart.java +++ b/src/com/fsck/k9/mail/internet/MimeBodyPart.java @@ -14,76 +14,60 @@ import java.io.OutputStreamWriter; * TODO this is a close approximation of Message, need to update along with * Message. */ -public class MimeBodyPart extends BodyPart -{ +public class MimeBodyPart extends BodyPart { protected MimeHeader mHeader = new MimeHeader(); protected Body mBody; protected int mSize; - public MimeBodyPart() throws MessagingException - { + public MimeBodyPart() throws MessagingException { this(null); } - public MimeBodyPart(Body body) throws MessagingException - { + public MimeBodyPart(Body body) throws MessagingException { this(body, null); } - public MimeBodyPart(Body body, String mimeType) throws MessagingException - { - if (mimeType != null) - { + public MimeBodyPart(Body body, String mimeType) throws MessagingException { + if (mimeType != null) { addHeader(MimeHeader.HEADER_CONTENT_TYPE, mimeType); } setBody(body); } - protected String getFirstHeader(String name) - { + protected String getFirstHeader(String name) { return mHeader.getFirstHeader(name); } - public void addHeader(String name, String value) throws MessagingException - { + public void addHeader(String name, String value) throws MessagingException { mHeader.addHeader(name, value); } - public void setHeader(String name, String value) throws MessagingException - { + public void setHeader(String name, String value) throws MessagingException { mHeader.setHeader(name, value); } - public String[] getHeader(String name) throws MessagingException - { + public String[] getHeader(String name) throws MessagingException { return mHeader.getHeader(name); } - public void removeHeader(String name) throws MessagingException - { + public void removeHeader(String name) throws MessagingException { mHeader.removeHeader(name); } - public Body getBody() - { + public Body getBody() { return mBody; } - public void setBody(Body body) throws MessagingException - { + public void setBody(Body body) throws MessagingException { this.mBody = body; - if (body instanceof com.fsck.k9.mail.Multipart) - { + if (body instanceof com.fsck.k9.mail.Multipart) { com.fsck.k9.mail.Multipart multipart = ((com.fsck.k9.mail.Multipart)body); multipart.setParent(this); setHeader(MimeHeader.HEADER_CONTENT_TYPE, multipart.getContentType()); - } - else if (body instanceof TextBody) - { + } else if (body instanceof TextBody) { String contentType = String.format("%s;\n charset=utf-8", getMimeType()); String name = MimeUtility.getHeaderParameter(getContentType(), "name"); - if (name != null) - { + if (name != null) { contentType += String.format(";\n name=\"%s\"", name); } setHeader(MimeHeader.HEADER_CONTENT_TYPE, contentType); @@ -91,80 +75,60 @@ public class MimeBodyPart extends BodyPart } } - public String getContentType() throws MessagingException - { + public String getContentType() throws MessagingException { String contentType = getFirstHeader(MimeHeader.HEADER_CONTENT_TYPE); - if (contentType == null) - { + if (contentType == null) { return "text/plain"; - } - else - { + } else { return contentType; } } - public String getDisposition() throws MessagingException - { + public String getDisposition() throws MessagingException { String contentDisposition = getFirstHeader(MimeHeader.HEADER_CONTENT_DISPOSITION); - if (contentDisposition == null) - { + if (contentDisposition == null) { return null; - } - else - { + } else { return contentDisposition; } } - public String getContentId() throws MessagingException - { + public String getContentId() throws MessagingException { String contentId = getFirstHeader(MimeHeader.HEADER_CONTENT_ID); - if (contentId == null) - { + if (contentId == null) { return null; - } - else - { + } else { int first = contentId.indexOf('<'); int last = contentId.lastIndexOf('>'); - if (first != -1 && last != -1) - { - return contentId.substring(first+1, last); - } - else - { + if (first != -1 && last != -1) { + return contentId.substring(first + 1, last); + } else { return contentId; } } } - public String getMimeType() throws MessagingException - { + public String getMimeType() throws MessagingException { return MimeUtility.getHeaderParameter(getContentType(), null); } - public boolean isMimeType(String mimeType) throws MessagingException - { + public boolean isMimeType(String mimeType) throws MessagingException { return getMimeType().equals(mimeType); } - public int getSize() - { + public int getSize() { return mSize; } /** * Write the MimeMessage out in MIME format. */ - public void writeTo(OutputStream out) throws IOException, MessagingException - { + public void writeTo(OutputStream out) throws IOException, MessagingException { BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out), 1024); mHeader.writeTo(out); writer.write("\r\n"); writer.flush(); - if (mBody != null) - { + if (mBody != null) { mBody.writeTo(out); } } diff --git a/src/com/fsck/k9/mail/internet/MimeHeader.java b/src/com/fsck/k9/mail/internet/MimeHeader.java index 1f4e905a5..d45a9b6a0 100644 --- a/src/com/fsck/k9/mail/internet/MimeHeader.java +++ b/src/com/fsck/k9/mail/internet/MimeHeader.java @@ -10,8 +10,7 @@ import java.io.OutputStream; import java.io.OutputStreamWriter; import java.util.*; -public class MimeHeader -{ +public class MimeHeader { private static final String[] EMPTY_STRING_ARRAY = new String[0]; /** @@ -31,8 +30,7 @@ public class MimeHeader /** * Fields that should be omitted when writing the header using writeTo() */ - private static final String[] writeOmitFields = - { + private static final String[] writeOmitFields = { // HEADER_ANDROID_ATTACHMENT_DOWNLOADED, // HEADER_ANDROID_ATTACHMENT_ID, HEADER_ANDROID_ATTACHMENT_STORE_DATA @@ -40,87 +38,68 @@ public class MimeHeader protected ArrayList mFields = new ArrayList(); - public void clear() - { + public void clear() { mFields.clear(); } - public String getFirstHeader(String name) - { + public String getFirstHeader(String name) { String[] header = getHeader(name); - if (header == null) - { + if (header == null) { return null; } return header[0]; } - public void addHeader(String name, String value) - { + public void addHeader(String name, String value) { mFields.add(new Field(name, MimeUtility.foldAndEncode(value))); } - public void setHeader(String name, String value) - { - if (name == null || value == null) - { + public void setHeader(String name, String value) { + if (name == null || value == null) { return; } removeHeader(name); addHeader(name, value); } - public Set getHeaderNames() - { + public Set getHeaderNames() { Set names = new HashSet(); - for (Field field : mFields) - { + for (Field field : mFields) { names.add(field.name); } return names; } - public String[] getHeader(String name) - { + public String[] getHeader(String name) { ArrayList values = new ArrayList(); - for (Field field : mFields) - { - if (field.name.equalsIgnoreCase(name)) - { + for (Field field : mFields) { + if (field.name.equalsIgnoreCase(name)) { values.add(field.value); } } - if (values.size() == 0) - { + if (values.size() == 0) { return null; } return values.toArray(EMPTY_STRING_ARRAY); } - public void removeHeader(String name) - { + public void removeHeader(String name) { ArrayList removeFields = new ArrayList(); - for (Field field : mFields) - { - if (field.name.equalsIgnoreCase(name)) - { + for (Field field : mFields) { + if (field.name.equalsIgnoreCase(name)) { removeFields.add(field); } } mFields.removeAll(removeFields); } - public void writeTo(OutputStream out) throws IOException - { + public void writeTo(OutputStream out) throws IOException { BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out), 1024); - for (Field field : mFields) - { - if (!Utility.arrayContains(writeOmitFields, field.name)) - { + for (Field field : mFields) { + if (!Utility.arrayContains(writeOmitFields, field.name)) { String v = field.value; - if (hasToBeEncoded(v)) - { + if (hasToBeEncoded(v)) { v = EncoderUtil.encodeEncodedWord( field.value, EncoderUtil.Usage.WORD_ENTITY @@ -134,15 +113,11 @@ public class MimeHeader } // encode non printable characters except LF/CR codes. - public boolean hasToBeEncoded(String text) - { - for (int i = 0; i < text.length(); i++) - { + public boolean hasToBeEncoded(String text) { + for (int i = 0; i < text.length(); i++) { char c = text.charAt(i); - if (c < 0x20 || 0x7e < c) // non printable - { - if (c != 0x0a && c != 0x0d) // non LF/CR - { + if (c < 0x20 || 0x7e < c) { // non printable + if (c != 0x0a && c != 0x0d) { // non LF/CR return true; } } @@ -151,21 +126,18 @@ public class MimeHeader return false; } - static class Field - { + static class Field { String name; String value; - public Field(String name, String value) - { + public Field(String name, String value) { this.name = name; this.value = value; } @Override - public String toString() - { + public String toString() { StringBuilder sb = new StringBuilder("("); sb.append(name).append('=').append(value).append(')'); return sb.toString(); diff --git a/src/com/fsck/k9/mail/internet/MimeMessage.java b/src/com/fsck/k9/mail/internet/MimeMessage.java index 7f2b0cffa..fbf6ad16b 100644 --- a/src/com/fsck/k9/mail/internet/MimeMessage.java +++ b/src/com/fsck/k9/mail/internet/MimeMessage.java @@ -24,8 +24,7 @@ import java.util.*; * An implementation of Message that stores all of it's metadata in RFC 822 and * RFC 2045 style headers. */ -public class MimeMessage extends Message -{ +public class MimeMessage extends Message { protected MimeHeader mHeader = new MimeHeader(); protected Address[] mFrom; protected Address[] mTo; @@ -43,8 +42,7 @@ public class MimeMessage extends Message protected Body mBody; protected int mSize; - public MimeMessage() - { + public MimeMessage() { } @@ -55,13 +53,11 @@ public class MimeMessage extends Message * @throws IOException * @throws MessagingException */ - public MimeMessage(InputStream in) throws IOException, MessagingException - { + public MimeMessage(InputStream in) throws IOException, MessagingException { parse(in); } - protected void parse(InputStream in) throws IOException, MessagingException - { + protected void parse(InputStream in) throws IOException, MessagingException { mHeader.clear(); mFrom = null; mTo = null; @@ -80,33 +76,25 @@ public class MimeMessage extends Message MimeEntityConfig parserConfig = new MimeEntityConfig(); parserConfig.setMaxHeaderLen(-1); // The default is a mere 10k parserConfig.setMaxLineLen(-1); // The default is 1000 characters. Some MUAs generate - // REALLY long References: headers + // REALLY long References: headers MimeStreamParser parser = new MimeStreamParser(parserConfig); parser.setContentHandler(new MimeMessageBuilder()); - try - { + try { parser.parse(new EOLConvertingInputStream(in)); - } - catch (MimeException me) - { + } catch (MimeException me) { throw new Error(me); } } @Override - public Date getSentDate() - { - if (mSentDate == null) - { - try - { + public Date getSentDate() { + if (mSentDate == null) { + try { DateTimeField field = (DateTimeField)DefaultFieldParser.parse("Date: " + MimeUtility.unfoldAndDecode(getFirstHeader("Date"))); mSentDate = field.getDate(); - } - catch (Exception e) - { + } catch (Exception e) { } } @@ -121,10 +109,8 @@ public class MimeMessage extends Message * @param sentDate * @throws com.fsck.k9.mail.MessagingException */ - public void addSentDate(Date sentDate) throws MessagingException - { - if (mDateFormat == null) - { + public void addSentDate(Date sentDate) throws MessagingException { + if (mDateFormat == null) { mDateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.US); } addHeader("Date", mDateFormat.format(sentDate)); @@ -132,54 +118,41 @@ public class MimeMessage extends Message } @Override - public void setSentDate(Date sentDate) throws MessagingException - { + public void setSentDate(Date sentDate) throws MessagingException { removeHeader("Date"); addSentDate(sentDate); } - public void setInternalSentDate(Date sentDate) - { + public void setInternalSentDate(Date sentDate) { this.mSentDate = sentDate; } @Override - public String getContentType() throws MessagingException - { + public String getContentType() throws MessagingException { String contentType = getFirstHeader(MimeHeader.HEADER_CONTENT_TYPE); - if (contentType == null) - { + if (contentType == null) { return "text/plain"; - } - else - { + } else { return contentType.toLowerCase(); } } - public String getDisposition() throws MessagingException - { + public String getDisposition() throws MessagingException { String contentDisposition = getFirstHeader(MimeHeader.HEADER_CONTENT_DISPOSITION); - if (contentDisposition == null) - { + if (contentDisposition == null) { return null; - } - else - { + } else { return contentDisposition; } } - public String getContentId() throws MessagingException - { + public String getContentId() throws MessagingException { return null; } - public String getMimeType() throws MessagingException - { + public String getMimeType() throws MessagingException { return MimeUtility.getHeaderParameter(getContentType(), null); } - public int getSize() - { + public int getSize() { return mSize; } @@ -188,82 +161,54 @@ public class MimeMessage extends Message * found the method returns an empty array. */ @Override - public Address[] getRecipients(RecipientType type) throws MessagingException - { - if (type == RecipientType.TO) - { - if (mTo == null) - { + public Address[] getRecipients(RecipientType type) throws MessagingException { + if (type == RecipientType.TO) { + if (mTo == null) { mTo = Address.parse(MimeUtility.unfold(getFirstHeader("To"))); } return mTo; - } - else if (type == RecipientType.CC) - { - if (mCc == null) - { + } else if (type == RecipientType.CC) { + if (mCc == null) { mCc = Address.parse(MimeUtility.unfold(getFirstHeader("CC"))); } return mCc; - } - else if (type == RecipientType.BCC) - { - if (mBcc == null) - { + } else if (type == RecipientType.BCC) { + if (mBcc == null) { mBcc = Address.parse(MimeUtility.unfold(getFirstHeader("BCC"))); } return mBcc; - } - else - { + } else { throw new MessagingException("Unrecognized recipient type."); } } @Override - public void setRecipients(RecipientType type, Address[] addresses) throws MessagingException - { - if (type == RecipientType.TO) - { - if (addresses == null || addresses.length == 0) - { + public void setRecipients(RecipientType type, Address[] addresses) throws MessagingException { + if (type == RecipientType.TO) { + if (addresses == null || addresses.length == 0) { removeHeader("To"); this.mTo = null; - } - else - { + } else { setHeader("To", Address.toEncodedString(addresses)); this.mTo = addresses; } - } - else if (type == RecipientType.CC) - { - if (addresses == null || addresses.length == 0) - { + } else if (type == RecipientType.CC) { + if (addresses == null || addresses.length == 0) { removeHeader("CC"); this.mCc = null; - } - else - { + } else { setHeader("CC", Address.toEncodedString(addresses)); this.mCc = addresses; } - } - else if (type == RecipientType.BCC) - { - if (addresses == null || addresses.length == 0) - { + } else if (type == RecipientType.BCC) { + if (addresses == null || addresses.length == 0) { removeHeader("BCC"); this.mBcc = null; - } - else - { + } else { setHeader("BCC", Address.toEncodedString(addresses)); this.mBcc = addresses; } - } - else - { + } else { throw new MessagingException("Unrecognized recipient type."); } } @@ -272,25 +217,20 @@ public class MimeMessage extends Message * Returns the unfolded, decoded value of the Subject header. */ @Override - public String getSubject() - { + public String getSubject() { return MimeUtility.unfoldAndDecode(getFirstHeader("Subject"), this); } @Override - public void setSubject(String subject) throws MessagingException - { + public void setSubject(String subject) throws MessagingException { setHeader("Subject", subject); } @Override - public Address[] getFrom() - { - if (mFrom == null) - { + public Address[] getFrom() { + if (mFrom == null) { String list = MimeUtility.unfold(getFirstHeader("From")); - if (list == null || list.length() == 0) - { + if (list == null || list.length() == 0) { list = MimeUtility.unfold(getFirstHeader("Sender")); } mFrom = Address.parse(list); @@ -299,91 +239,71 @@ public class MimeMessage extends Message } @Override - public void setFrom(Address from) throws MessagingException - { - if (from != null) - { + public void setFrom(Address from) throws MessagingException { + if (from != null) { setHeader("From", from.toEncodedString()); - this.mFrom = new Address[] - { + this.mFrom = new Address[] { from }; - } - else - { + } else { this.mFrom = null; } } @Override - public Address[] getReplyTo() - { - if (mReplyTo == null) - { + public Address[] getReplyTo() { + if (mReplyTo == null) { mReplyTo = Address.parse(MimeUtility.unfold(getFirstHeader("Reply-to"))); } return mReplyTo; } @Override - public void setReplyTo(Address[] replyTo) throws MessagingException - { - if (replyTo == null || replyTo.length == 0) - { + public void setReplyTo(Address[] replyTo) throws MessagingException { + if (replyTo == null || replyTo.length == 0) { removeHeader("Reply-to"); mReplyTo = null; - } - else - { + } else { setHeader("Reply-to", Address.toEncodedString(replyTo)); mReplyTo = replyTo; } } @Override - public String getMessageId() throws MessagingException - { - if (mMessageId == null) - { + public String getMessageId() throws MessagingException { + if (mMessageId == null) { mMessageId = getFirstHeader("Message-ID"); } - if (mMessageId == null) // even after checking the header - { + if (mMessageId == null) { // even after checking the header setMessageId(generateMessageId()); } return mMessageId; } - private String generateMessageId() - { - return "<"+UUID.randomUUID().toString()+"@email.android.com>"; + private String generateMessageId() { + return "<" + UUID.randomUUID().toString() + "@email.android.com>"; } - public void setMessageId(String messageId) throws UnavailableStorageException - { + public void setMessageId(String messageId) throws UnavailableStorageException { setHeader("Message-ID", messageId); mMessageId = messageId; } @Override - public void setInReplyTo(String inReplyTo) throws MessagingException - { + public void setInReplyTo(String inReplyTo) throws MessagingException { setHeader("In-Reply-To", inReplyTo); } @Override - public String[] getReferences() throws MessagingException - { - if (mReferences == null) - { + public String[] getReferences() throws MessagingException { + if (mReferences == null) { mReferences = getHeader("References"); } return mReferences; } @Override - public void setReferences(String references) throws MessagingException - { + public void setReferences(String references) throws MessagingException { /* * Make sure the References header doesn't exceed the maximum header * line length and won't get (Q-)encoded later. Otherwise some clients @@ -402,8 +322,7 @@ public class MimeMessage extends Message */ final int limit = 1000 - 2 /* CRLF */ - 12 /* "References: " */ - 1 /* Off-by-one bugs */; final int originalLength = references.length(); - if (originalLength >= limit) - { + if (originalLength >= limit) { // Find start of first reference final int start = references.indexOf('<'); @@ -421,289 +340,223 @@ public class MimeMessage extends Message } @Override - public void saveChanges() throws MessagingException - { + public void saveChanges() throws MessagingException { throw new MessagingException("saveChanges not yet implemented"); } @Override - public Body getBody() - { + public Body getBody() { return mBody; } @Override - public void setBody(Body body) throws MessagingException - { + public void setBody(Body body) throws MessagingException { this.mBody = body; setHeader("MIME-Version", "1.0"); - if (body instanceof Multipart) - { + if (body instanceof Multipart) { Multipart multipart = ((Multipart)body); multipart.setParent(this); setHeader(MimeHeader.HEADER_CONTENT_TYPE, multipart.getContentType()); - } - else if (body instanceof TextBody) - { + } else if (body instanceof TextBody) { setHeader(MimeHeader.HEADER_CONTENT_TYPE, String.format("%s;\n charset=utf-8", getMimeType())); setHeader(MimeHeader.HEADER_CONTENT_TRANSFER_ENCODING, "quoted-printable"); } } - protected String getFirstHeader(String name) - { + protected String getFirstHeader(String name) { return mHeader.getFirstHeader(name); } @Override - public void addHeader(String name, String value) throws UnavailableStorageException - { + public void addHeader(String name, String value) throws UnavailableStorageException { mHeader.addHeader(name, value); } @Override - public void setHeader(String name, String value) throws UnavailableStorageException - { + public void setHeader(String name, String value) throws UnavailableStorageException { mHeader.setHeader(name, value); } @Override - public String[] getHeader(String name) throws UnavailableStorageException - { + public String[] getHeader(String name) throws UnavailableStorageException { return mHeader.getHeader(name); } @Override - public void removeHeader(String name) throws UnavailableStorageException - { + public void removeHeader(String name) throws UnavailableStorageException { mHeader.removeHeader(name); } @Override - public Set getHeaderNames() throws UnavailableStorageException - { + public Set getHeaderNames() throws UnavailableStorageException { return mHeader.getHeaderNames(); } - public void writeTo(OutputStream out) throws IOException, MessagingException - { + public void writeTo(OutputStream out) throws IOException, MessagingException { BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out), 1024); mHeader.writeTo(out); writer.write("\r\n"); writer.flush(); - if (mBody != null) - { + if (mBody != null) { mBody.writeTo(out); } } - public InputStream getInputStream() throws MessagingException - { + public InputStream getInputStream() throws MessagingException { return null; } @Override - public void setEncoding(String encoding) throws UnavailableStorageException - { - if (mBody instanceof Multipart) - { + public void setEncoding(String encoding) throws UnavailableStorageException { + if (mBody instanceof Multipart) { ((Multipart)mBody).setEncoding(encoding); - } - else if (mBody instanceof TextBody) - { + } else if (mBody instanceof TextBody) { setHeader(MimeHeader.HEADER_CONTENT_TRANSFER_ENCODING, encoding); ((TextBody)mBody).setEncoding(encoding); } } @Override - public void setCharset(String charset) throws MessagingException - { - if (mBody instanceof Multipart) - { + public void setCharset(String charset) throws MessagingException { + if (mBody instanceof Multipart) { ((Multipart)mBody).setCharset(charset); - } - else if (mBody instanceof TextBody) - { + } else if (mBody instanceof TextBody) { MimeUtility.setCharset(charset, this); ((TextBody)mBody).setCharset(charset); } } - class MimeMessageBuilder implements ContentHandler - { + class MimeMessageBuilder implements ContentHandler { private Stack stack = new Stack(); - public MimeMessageBuilder() - { + public MimeMessageBuilder() { } - private void expect(Class c) - { - if (!c.isInstance(stack.peek())) - { + private void expect(Class c) { + if (!c.isInstance(stack.peek())) { throw new IllegalStateException("Internal stack error: " + "Expected '" + c.getName() + "' found '" + stack.peek().getClass().getName() + "'"); } } - public void startMessage() - { - if (stack.isEmpty()) - { + public void startMessage() { + if (stack.isEmpty()) { stack.push(MimeMessage.this); - } - else - { + } else { expect(Part.class); - try - { + try { MimeMessage m = new MimeMessage(); ((Part)stack.peek()).setBody(m); stack.push(m); - } - catch (MessagingException me) - { + } catch (MessagingException me) { throw new Error(me); } } } - public void endMessage() - { + public void endMessage() { expect(MimeMessage.class); stack.pop(); } - public void startHeader() - { + public void startHeader() { expect(Part.class); } - public void field(RawField field) - { + public void field(RawField field) { expect(Part.class); - try - { + try { Field parsedField = DefaultFieldParser.parse(field.getRaw(), null); ((Part)stack.peek()).addHeader(parsedField.getName(), parsedField.getBody().trim()); - } - catch (MessagingException me) - { + } catch (MessagingException me) { throw new Error(me); - } - catch (MimeException me) - { + } catch (MimeException me) { throw new Error(me); } } - public void field(String fieldData) - { + public void field(String fieldData) { expect(Part.class); - try - { + try { String[] tokens = fieldData.split(":", 2); ((Part)stack.peek()).addHeader(tokens[0], tokens[1].trim()); - } - catch (MessagingException me) - { + } catch (MessagingException me) { throw new Error(me); } } - public void endHeader() - { + public void endHeader() { expect(Part.class); } - public void startMultipart(BodyDescriptor bd) - { + public void startMultipart(BodyDescriptor bd) { expect(Part.class); Part e = (Part)stack.peek(); - try - { + try { MimeMultipart multiPart = new MimeMultipart(e.getContentType()); e.setBody(multiPart); stack.push(multiPart); - } - catch (MessagingException me) - { + } catch (MessagingException me) { throw new Error(me); } } - public void body(BodyDescriptor bd, InputStream in) throws IOException - { + public void body(BodyDescriptor bd, InputStream in) throws IOException { expect(Part.class); Body body = MimeUtility.decodeBody(in, bd.getTransferEncoding()); - try - { + try { ((Part)stack.peek()).setBody(body); - } - catch (MessagingException me) - { + } catch (MessagingException me) { throw new Error(me); } } - public void endMultipart() - { + public void endMultipart() { stack.pop(); } - public void startBodyPart() - { + public void startBodyPart() { expect(MimeMultipart.class); - try - { + try { MimeBodyPart bodyPart = new MimeBodyPart(); ((MimeMultipart)stack.peek()).addBodyPart(bodyPart); stack.push(bodyPart); - } - catch (MessagingException me) - { + } catch (MessagingException me) { throw new Error(me); } } - public void endBodyPart() - { + public void endBodyPart() { expect(BodyPart.class); stack.pop(); } - public void epilogue(InputStream is) throws IOException - { + public void epilogue(InputStream is) throws IOException { expect(MimeMultipart.class); StringBuffer sb = new StringBuffer(); int b; - while ((b = is.read()) != -1) - { + while ((b = is.read()) != -1) { sb.append((char)b); } // ((Multipart) stack.peek()).setEpilogue(sb.toString()); } - public void preamble(InputStream is) throws IOException - { + public void preamble(InputStream is) throws IOException { expect(MimeMultipart.class); StringBuffer sb = new StringBuffer(); int b; - while ((b = is.read()) != -1) - { + while ((b = is.read()) != -1) { sb.append((char)b); } ((MimeMultipart)stack.peek()).setPreamble(sb.toString()); } - public void raw(InputStream is) throws IOException - { + public void raw(InputStream is) throws IOException { throw new UnsupportedOperationException("Not supported"); } } diff --git a/src/com/fsck/k9/mail/internet/MimeMultipart.java b/src/com/fsck/k9/mail/internet/MimeMultipart.java index 907d0240c..7ee7be0da 100644 --- a/src/com/fsck/k9/mail/internet/MimeMultipart.java +++ b/src/com/fsck/k9/mail/internet/MimeMultipart.java @@ -7,8 +7,7 @@ import com.fsck.k9.mail.Multipart; import java.io.*; -public class MimeMultipart extends Multipart -{ +public class MimeMultipart extends Multipart { protected String mPreamble; protected String mContentType; @@ -17,81 +16,65 @@ public class MimeMultipart extends Multipart protected String mSubType; - public MimeMultipart() throws MessagingException - { + public MimeMultipart() throws MessagingException { mBoundary = generateBoundary(); setSubType("mixed"); } - public MimeMultipart(String contentType) throws MessagingException - { + public MimeMultipart(String contentType) throws MessagingException { this.mContentType = contentType; - try - { + try { mSubType = MimeUtility.getHeaderParameter(contentType, null).split("/")[1]; mBoundary = MimeUtility.getHeaderParameter(contentType, "boundary"); - if (mBoundary == null) - { + if (mBoundary == null) { throw new MessagingException("MultiPart does not contain boundary: " + contentType); } - } - catch (Exception e) - { + } catch (Exception e) { throw new MessagingException( "Invalid MultiPart Content-Type; must contain subtype and boundary. (" + contentType + ")", e); } } - public String generateBoundary() - { + public String generateBoundary() { StringBuffer sb = new StringBuffer(); sb.append("----"); - for (int i = 0; i < 30; i++) - { + for (int i = 0; i < 30; i++) { sb.append(Integer.toString((int)(Math.random() * 35), 36)); } return sb.toString().toUpperCase(); } - public String getPreamble() - { + public String getPreamble() { return mPreamble; } - public void setPreamble(String preamble) - { + public void setPreamble(String preamble) { this.mPreamble = preamble; } @Override - public String getContentType() - { + public String getContentType() { return mContentType; } - public void setSubType(String subType) - { + public void setSubType(String subType) { this.mSubType = subType; mContentType = String.format("multipart/%s; boundary=\"%s\"", subType, mBoundary); } - public void writeTo(OutputStream out) throws IOException, MessagingException - { + public void writeTo(OutputStream out) throws IOException, MessagingException { BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out), 1024); - if (mPreamble != null) - { + if (mPreamble != null) { writer.write(mPreamble + "\r\n"); } - if (mParts.size() == 0) - { + if (mParts.size() == 0) { writer.write("--" + mBoundary + "\r\n"); } - for (int i = 0, count = mParts.size(); i < count; i++) - { + for (int i = 0, count = mParts.size(); i < count; i++) { BodyPart bodyPart = mParts.get(i); writer.write("--" + mBoundary + "\r\n"); writer.flush(); @@ -103,8 +86,7 @@ public class MimeMultipart extends Multipart writer.flush(); } - public InputStream getInputStream() throws MessagingException - { + public InputStream getInputStream() throws MessagingException { return null; } } diff --git a/src/com/fsck/k9/mail/internet/MimeUtility.java b/src/com/fsck/k9/mail/internet/MimeUtility.java index 1c39da32c..1addaa2b6 100644 --- a/src/com/fsck/k9/mail/internet/MimeUtility.java +++ b/src/com/fsck/k9/mail/internet/MimeUtility.java @@ -16,8 +16,7 @@ import java.util.regex.Pattern; import java.nio.charset.Charset; -public class MimeUtility -{ +public class MimeUtility { public static final String DEFAULT_ATTACHMENT_MIME_TYPE = "application/octet-stream"; @@ -27,8 +26,7 @@ public class MimeUtility * + * http://www.stdicon.com/mimetypes */ - public static final String[][] MIME_TYPE_BY_EXTENSION_MAP = new String[][] - { + public static final String[][] MIME_TYPE_BY_EXTENSION_MAP = new String[][] { { "", "application/octet-stream" }, { "123", "application/vnd.lotus-1-2-3"}, { "323", "text/h323"}, @@ -880,43 +878,35 @@ public class MimeUtility - public static String unfold(String s) - { - if (s == null) - { + public static String unfold(String s) { + if (s == null) { return null; } return s.replaceAll("\r|\n", ""); } - public static String decode(String s) - { + public static String decode(String s) { return decode(s, null); } - public static String decode(String s, Message message) - { - if (s == null) - { + public static String decode(String s, Message message) { + if (s == null) { return null; } return DecoderUtil.decodeEncodedWords(s, message); } - public static String unfoldAndDecode(String s) - { + public static String unfoldAndDecode(String s) { return unfoldAndDecode(s, null); } - public static String unfoldAndDecode(String s, Message message) - { + public static String unfoldAndDecode(String s, Message message) { return decode(unfold(s), message); } // TODO implement proper foldAndEncode - public static String foldAndEncode(String s) - { + public static String foldAndEncode(String s) { return s; } @@ -931,29 +921,21 @@ public class MimeUtility * @param name * @return */ - public static String getHeaderParameter(String header, String name) - { - if (header == null) - { + public static String getHeaderParameter(String header, String name) { + if (header == null) { return null; } header = header.replaceAll("\r|\n", ""); String[] parts = header.split(";"); - if (name == null) - { + if (name == null) { return parts[0]; } - for (String part : parts) - { - if (part.trim().toLowerCase().startsWith(name.toLowerCase())) - { + for (String part : parts) { + if (part.trim().toLowerCase().startsWith(name.toLowerCase())) { String parameter = part.split("=", 2)[1].trim(); - if (parameter.startsWith("\"") && parameter.endsWith("\"")) - { + if (parameter.startsWith("\"") && parameter.endsWith("\"")) { return parameter.substring(1, parameter.length() - 1); - } - else - { + } else { return parameter; } } @@ -962,50 +944,37 @@ public class MimeUtility } public static Part findFirstPartByMimeType(Part part, String mimeType) - throws MessagingException - { - if (part.getBody() instanceof Multipart) - { + throws MessagingException { + if (part.getBody() instanceof Multipart) { Multipart multipart = (Multipart)part.getBody(); - for (int i = 0, count = multipart.getCount(); i < count; i++) - { + for (int i = 0, count = multipart.getCount(); i < count; i++) { BodyPart bodyPart = multipart.getBodyPart(i); Part ret = findFirstPartByMimeType(bodyPart, mimeType); - if (ret != null) - { + if (ret != null) { return ret; } } - } - else if (part.getMimeType().equalsIgnoreCase(mimeType)) - { + } else if (part.getMimeType().equalsIgnoreCase(mimeType)) { return part; } return null; } - public static Part findPartByContentId(Part part, String contentId) throws Exception - { - if (part.getBody() instanceof Multipart) - { + public static Part findPartByContentId(Part part, String contentId) throws Exception { + if (part.getBody() instanceof Multipart) { Multipart multipart = (Multipart)part.getBody(); - for (int i = 0, count = multipart.getCount(); i < count; i++) - { + for (int i = 0, count = multipart.getCount(); i < count; i++) { BodyPart bodyPart = multipart.getBodyPart(i); Part ret = findPartByContentId(bodyPart, contentId); - if (ret != null) - { + if (ret != null) { return ret; } } } String[] header = part.getHeader("Content-ID"); - if (header != null) - { - for (String s : header) - { - if (s.equals(contentId)) - { + if (header != null) { + for (String s : header) { + if (s.equals(contentId)) { return part; } } @@ -1020,21 +989,16 @@ public class MimeUtility * @return a String containing the converted text in the body, or null if there was no text * or an error during conversion. */ - public static String getTextFromPart(Part part) - { - try - { - if ((part != null) && (part.getBody() != null)) - { + public static String getTextFromPart(Part part) { + try { + if ((part != null) && (part.getBody() != null)) { final Body body = part.getBody(); - if (body instanceof TextBody) - { + if (body instanceof TextBody) { return ((TextBody)body).getText(); } final String mimeType = part.getMimeType(); - if ((mimeType != null) && MimeUtility.mimeTypeMatches(mimeType, "text/*")) - { + if ((mimeType != null) && MimeUtility.mimeTypeMatches(mimeType, "text/*")) { /* * We've got a text part, so let's see if it needs to be processed further. */ @@ -1050,17 +1014,13 @@ public class MimeUtility } } - } - catch (OutOfMemoryError oom) - { + } catch (OutOfMemoryError oom) { /* * If we are not able to process the body there's nothing we can do about it. Return * null and let the upper layers handle the missing content. */ Log.e(K9.LOG_TAG, "Unable to getTextFromPart " + oom.toString()); - } - catch (Exception e) - { + } catch (Exception e) { /* * If we are not able to process the body there's nothing we can do about it. Return * null and let the upper layers handle the missing content. @@ -1077,8 +1037,7 @@ public class MimeUtility * * /*. * @return */ - public static boolean mimeTypeMatches(String mimeType, String matchAgainst) - { + public static boolean mimeTypeMatches(String mimeType, String matchAgainst) { Pattern p = Pattern.compile(matchAgainst.replaceAll("\\*", "\\.\\*"), Pattern.CASE_INSENSITIVE); return p.matcher(mimeType).matches(); } @@ -1090,12 +1049,9 @@ public class MimeUtility * as image/* or * /*. * @return */ - public static boolean mimeTypeMatches(String mimeType, String[] matchAgainst) - { - for (String matchType : matchAgainst) - { - if (mimeTypeMatches(mimeType, matchType)) - { + public static boolean mimeTypeMatches(String mimeType, String[] matchAgainst) { + for (String matchType : matchAgainst) { + if (mimeTypeMatches(mimeType, matchType)) { return true; } } @@ -1106,21 +1062,16 @@ public class MimeUtility * Removes any content transfer encoding from the stream and returns a Body. */ public static Body decodeBody(InputStream in, String contentTransferEncoding) - throws IOException - { + throws IOException { /* * We'll remove any transfer encoding by wrapping the stream. */ - if (contentTransferEncoding != null) - { + if (contentTransferEncoding != null) { contentTransferEncoding = MimeUtility.getHeaderParameter(contentTransferEncoding, null); - if ("quoted-printable".equalsIgnoreCase(contentTransferEncoding)) - { + if ("quoted-printable".equalsIgnoreCase(contentTransferEncoding)) { in = new QuotedPrintableInputStream(in); - } - else if ("base64".equalsIgnoreCase(contentTransferEncoding)) - { + } else if ("base64".equalsIgnoreCase(contentTransferEncoding)) { in = new Base64InputStream(in); } } @@ -1143,18 +1094,15 @@ public class MimeUtility * @throws MessagingException */ public static void collectParts(Part part, ArrayList viewables, - ArrayList attachments) throws MessagingException - { + ArrayList attachments) throws MessagingException { /* * If the part is Multipart but not alternative it's either mixed or * something we don't know about, which means we treat it as mixed * per the spec. We just process it's pieces recursively. */ - if (part.getBody() instanceof Multipart) - { + if (part.getBody() instanceof Multipart) { Multipart mp = (Multipart)part.getBody(); - for (int i = 0; i < mp.getCount(); i++) - { + for (int i = 0; i < mp.getCount(); i++) { collectParts(mp.getBodyPart(i), viewables, attachments); } } @@ -1162,8 +1110,7 @@ public class MimeUtility * If the part is an embedded message we just continue to process * it, pulling any viewables or attachments into the running list. */ - else if (part.getBody() instanceof Message) - { + else if (part.getBody() instanceof Message) { Message message = (Message)part.getBody(); collectParts(message, viewables, attachments); } @@ -1171,25 +1118,20 @@ public class MimeUtility * If the part is HTML and it got this far it's part of a mixed (et * al) and should be rendered inline. */ - else if (isPartTextualBody(part)) - { + else if (isPartTextualBody(part)) { viewables.add(part); - } - else - { + } else { attachments.add(part); } } - public static Boolean isPartTextualBody(Part part) throws MessagingException - { + public static Boolean isPartTextualBody(Part part) throws MessagingException { String disposition = part.getDisposition(); String dispositionType = null; String dispositionFilename = null; - if (disposition != null) - { + if (disposition != null) { dispositionType = MimeUtility.getHeaderParameter(disposition, null); dispositionFilename = MimeUtility.getHeaderParameter(disposition, "filename"); } @@ -1199,32 +1141,27 @@ public class MimeUtility */ boolean attachment = ("attachment".equalsIgnoreCase(dispositionType) || (dispositionFilename != null)); - if ((!attachment) && (part.getMimeType().equalsIgnoreCase("text/html"))) - { + if ((!attachment) && (part.getMimeType().equalsIgnoreCase("text/html"))) { return true; } /* * If the part is plain text and it got this far it's part of a * mixed (et al) and should be rendered inline. */ - else if ((!attachment) && (part.getMimeType().equalsIgnoreCase("text/plain"))) - { + else if ((!attachment) && (part.getMimeType().equalsIgnoreCase("text/plain"))) { return true; } /* * Finally, if it's nothing else we will include it as an attachment. */ - else - { + else { return false; } } - public static String getCharsetFromAddress(String address) - { + public static String getCharsetFromAddress(String address) { String variant = getJisVariantFromAddress(address); - if (variant != null) - { + if (variant != null) { String charset = "x-" + variant + "-shift_jis-2007"; if (Charset.isSupported(charset)) return charset; @@ -1233,26 +1170,19 @@ public class MimeUtility return "UTF-8"; } - public static String getMimeTypeByExtension(String filename) - { + public static String getMimeTypeByExtension(String filename) { String returnedType = null; String extension = null; - if (filename != null && filename.lastIndexOf('.') != -1) - { - extension = filename.substring(filename.lastIndexOf('.')+1).toLowerCase(); + if (filename != null && filename.lastIndexOf('.') != -1) { + extension = filename.substring(filename.lastIndexOf('.') + 1).toLowerCase(); returnedType = android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); } - if (returnedType != null) - { + if (returnedType != null) { return returnedType; - } - else if (extension != null) - { - for (String[] contentTypeMapEntry : MIME_TYPE_BY_EXTENSION_MAP) - { - if (contentTypeMapEntry[0].equals(extension)) - { + } else if (extension != null) { + for (String[] contentTypeMapEntry : MIME_TYPE_BY_EXTENSION_MAP) { + if (contentTypeMapEntry[0].equals(extension)) { return contentTypeMapEntry[1]; } } @@ -1261,10 +1191,8 @@ public class MimeUtility return DEFAULT_ATTACHMENT_MIME_TYPE; } - private static Message getMessageFromPart(Part part) - { - while (part != null) - { + private static Message getMessageFromPart(Part part) { + while (part != null) { if (part instanceof Message) return (Message)part; @@ -1280,8 +1208,7 @@ public class MimeUtility return null; } - public static String fixupCharset(String charset, Message message) throws MessagingException - { + public static String fixupCharset(String charset, Message message) throws MessagingException { if (charset == null || "0".equals(charset)) charset = "US-ASCII"; // No encoding, so use us-ascii, which is the standard. @@ -1291,8 +1218,7 @@ public class MimeUtility else if (charset.equals("koi8-u")) charset = "koi8-r"; - if (charset.equals("shift_jis") || charset.equals("iso-2022-jp")) - { + if (charset.equals("shift_jis") || charset.equals("iso-2022-jp")) { String variant = getJisVariantFromMessage(message); if (variant != null) charset = "x-" + variant + "-" + charset + "-2007"; @@ -1300,8 +1226,7 @@ public class MimeUtility return charset; } - private static String getJisVariantFromMessage(Message message) throws MessagingException - { + private static String getJisVariantFromMessage(Message message) throws MessagingException { if (message == null) return null; @@ -1320,14 +1245,12 @@ public class MimeUtility return getJisVariantFromMailerHeaders(message); } - private static String getJisVariantFromReceivedHeaders(Message message) throws MessagingException - { + private static String getJisVariantFromReceivedHeaders(Message message) throws MessagingException { String receivedHeaders[] = message.getHeader("Received"); if (receivedHeaders == null) return null; - for (String receivedHeader : receivedHeaders) - { + for (String receivedHeader : receivedHeaders) { String address = getAddressFromReceivedHeader(receivedHeader); if (address == null) continue; @@ -1338,14 +1261,12 @@ public class MimeUtility return null; } - private static String getAddressFromReceivedHeader(String receivedHeader) - { + private static String getAddressFromReceivedHeader(String receivedHeader) { // Not implemented yet! Extract an address from the FOR clause of the given Received header. return null; } - private static String getJisVariantFromFromHeaders(Message message) throws MessagingException - { + private static String getJisVariantFromFromHeaders(Message message) throws MessagingException { Address addresses[] = message.getFrom(); if (addresses == null || addresses.length == 0) return null; @@ -1353,8 +1274,7 @@ public class MimeUtility return getJisVariantFromAddress(addresses[0].getAddress()); } - private static String getJisVariantFromAddress(String address) - { + private static String getJisVariantFromAddress(String address) { if (isInDomain(address, "docomo.ne.jp") || isInDomain(address, "dwmail.jp") || isInDomain(address, "pdx.ne.jp") || isInDomain(address, "willcom.com")) return "docomo"; @@ -1366,8 +1286,7 @@ public class MimeUtility return null; } - private static boolean isInDomain(String address, String domain) - { + private static boolean isInDomain(String address, String domain) { int index = address.length() - domain.length() - 1; if (index < 0) return false; @@ -1379,8 +1298,7 @@ public class MimeUtility return address.endsWith(domain); } - private static String getJisVariantFromMailerHeaders(Message message) throws MessagingException - { + private static String getJisVariantFromMailerHeaders(Message message) throws MessagingException { String mailerHeaders[] = message.getHeader("X-Mailer"); if (mailerHeaders == null || mailerHeaders.length == 0) return null; @@ -1391,22 +1309,19 @@ public class MimeUtility return null; } - public static String readToString(InputStream in, String charset) throws IOException - { + public static String readToString(InputStream in, String charset) throws IOException { boolean isIphoneString = false; // iso-2022-jp variants are supported by no versions as of Dec 2010. if (charset.length() > 19 && charset.startsWith("x-") && - charset.endsWith("-iso-2022-jp-2007") && !Charset.isSupported(charset)) - { + charset.endsWith("-iso-2022-jp-2007") && !Charset.isSupported(charset)) { in = new Iso2022JpToShiftJisInputStream(in); charset = "x-" + charset.substring(2, charset.length() - 17) + "-shift_jis-2007"; } // shift_jis variants are supported by Eclair and later. if (charset.length() > 17 && charset.startsWith("x-") && - charset.endsWith("-shift_jis-2007") && !Charset.isSupported(charset)) - { + charset.endsWith("-shift_jis-2007") && !Charset.isSupported(charset)) { // If the JIS variant is iPhone, map the Unicode private use area in iPhone to the one in Android after // converting the character set from the standard Shift JIS to Unicode. if (charset.substring(2, charset.length() - 15).equals("iphone")) @@ -1418,8 +1333,7 @@ public class MimeUtility /* * See if there is conversion from the MIME charset to the Java one. */ - if (!Charset.isSupported(charset)) - { + if (!Charset.isSupported(charset)) { Log.e(K9.LOG_TAG, "I don't know how to deal with the charset " + charset + ". Falling back to US-ASCII"); charset = "US-ASCII"; @@ -1435,1004 +1349,998 @@ public class MimeUtility return str; } - static private String importStringFromIphone(String str) - { + static private String importStringFromIphone(String str) { StringBuilder buff = new StringBuilder(str.length()); - for (int i = 0; i < str.length(); i = str.offsetByCodePoints(i, 1)) - { + for (int i = 0; i < str.length(); i = str.offsetByCodePoints(i, 1)) { int codePoint = str.codePointAt(i); buff.appendCodePoint(importCodePointFromIphone(codePoint)); } return buff.toString(); } - static private int importCodePointFromIphone(int codePoint) - { - switch (codePoint) - { - case 0xE001: - return 0xFE19B; - case 0xE002: - return 0xFE19C; - case 0xE003: - return 0xFE823; - case 0xE004: - return 0xFE19D; - case 0xE005: - return 0xFE19E; - case 0xE006: - return 0xFE4CF; - case 0xE007: - return 0xFE4CD; - case 0xE008: - return 0xFE4EF; - case 0xE009: - return 0xFE523; - case 0xE00A: - return 0xFE525; - case 0xE00B: - return 0xFE528; - case 0xE00C: - return 0xFE538; - case 0xE00D: - return 0xFEB96; - case 0xE00E: - return 0xFEB97; - case 0xE00F: - return 0xFEB98; - case 0xE010: - return 0xFEB93; - case 0xE011: - return 0xFEB94; - case 0xE012: - return 0xFEB95; - case 0xE013: - return 0xFE7D5; - case 0xE014: - return 0xFE7D2; - case 0xE015: - return 0xFE7D3; - case 0xE016: - return 0xFE7D1; - case 0xE017: - return 0xFE7DA; - case 0xE018: - return 0xFE7D4; - case 0xE019: - return 0xFE1BD; - case 0xE01A: - return 0xFE1BE; - case 0xE01B: - return 0xFE7E4; - case 0xE01C: - return 0xFE7EA; - case 0xE01D: - return 0xFE7E9; - case 0xE01E: - return 0xFE7DF; - case 0xE01F: - return 0xFE7E3; - case 0xE020: - return 0xFEB09; - case 0xE021: - return 0xFEB04; - case 0xE022: - return 0xFEB0C; - case 0xE023: - return 0xFEB0E; - case 0xE024: - return 0xFE01E; - case 0xE025: - return 0xFE01F; - case 0xE026: - return 0xFE020; - case 0xE027: - return 0xFE021; - case 0xE028: - return 0xFE022; - case 0xE029: - return 0xFE023; - case 0xE02A: - return 0xFE024; - case 0xE02B: - return 0xFE025; - case 0xE02C: - return 0xFE026; - case 0xE02D: - return 0xFE027; - case 0xE02E: - return 0xFE028; - case 0xE02F: - return 0xFE029; - case 0xE030: - return 0xFE040; - case 0xE031: - return 0xFE4D2; - case 0xE032: - return 0xFE041; - case 0xE033: - return 0xFE512; - case 0xE034: - return 0xFE825; - case 0xE035: - return 0xFE826; - case 0xE036: - return 0xFE4B0; - case 0xE037: - return 0xFE4BB; - case 0xE038: - return 0xFE4B2; - case 0xE039: - return 0xFE7EC; - case 0xE03A: - return 0xFE7F5; - case 0xE03B: - return 0xFE4C3; - case 0xE03C: - return 0xFE800; - case 0xE03D: - return 0xFE801; - case 0xE03E: - return 0xFE813; - case 0xE03F: - return 0xFEB82; - case 0xE040: - return 0xFE815; - case 0xE041: - return 0xFE816; - case 0xE042: - return 0xFE818; - case 0xE043: - return 0xFE980; - case 0xE044: - return 0xFE982; - case 0xE045: - return 0xFE981; - case 0xE046: - return 0xFE962; - case 0xE047: - return 0xFE983; - case 0xE048: - return 0xFE003; - case 0xE049: - return 0xFE001; - case 0xE04A: - return 0xFE000; - case 0xE04B: - return 0xFE002; - case 0xE04C: - return 0xFE014; - case 0xE04D: - return 0xFE009; - case 0xE04E: - return 0xFE1AF; - case 0xE04F: - return 0xFE1B8; - case 0xE050: - return 0xFE1C0; - case 0xE051: - return 0xFE1C1; - case 0xE052: - return 0xFE1B7; - case 0xE053: - return 0xFE1C2; - case 0xE054: - return 0xFE1C3; - case 0xE055: - return 0xFE1BC; - case 0xE056: - return 0xFE335; - case 0xE057: - return 0xFE330; - case 0xE058: - return 0xFE323; - case 0xE059: - return 0xFE320; - case 0xE05A: - return 0xFE4F4; - case 0xE101: - return 0xFE52D; - case 0xE102: - return 0xFE52E; - case 0xE103: - return 0xFE52B; - case 0xE104: - return 0xFE526; - case 0xE105: - return 0xFE329; - case 0xE106: - return 0xFE327; - case 0xE107: - return 0xFE341; - case 0xE108: - return 0xFE344; - case 0xE109: - return 0xFE1C4; - case 0xE10A: - return 0xFE1C5; - case 0xE10B: - return 0xFE1BF; - case 0xE10C: - return 0xFE1B0; - case 0xE10D: - return 0xFE7ED; - case 0xE10E: - return 0xFE4D1; - case 0xE10F: - return 0xFEB56; - case 0xE110: - return 0xFE03C; - case 0xE111: - return 0xFE827; - case 0xE112: - return 0xFE510; - case 0xE113: - return 0xFE4F5; - case 0xE114: - return 0xFEB85; - case 0xE115: - return 0xFE7D9; - case 0xE116: - return 0xFE4CA; - case 0xE117: - return 0xFE515; - case 0xE118: - return 0xFE03F; - case 0xE119: - return 0xFE042; - case 0xE11A: - return 0xFE1B2; - case 0xE11B: - return 0xFE1AE; - case 0xE11C: - return 0xFE1B3; - case 0xE11D: - return 0xFE4F6; - case 0xE11E: - return 0xFE53B; - case 0xE11F: - return 0xFE537; - case 0xE120: - return 0xFE960; - case 0xE121: - return 0xFE4BC; - case 0xE122: - return 0xFE7FB; - case 0xE123: - return 0xFE7FA; - case 0xE124: - return 0xFE7FD; - case 0xE125: - return 0xFE807; - case 0xE126: - return 0xFE81D; - case 0xE127: - return 0xFE81E; - case 0xE128: - return 0xFE81F; - case 0xE129: - return 0xFE820; - case 0xE12A: - return 0xFE81C; - case 0xE12B: - return 0xFE1B1; - case 0xE12C: - return 0xFE81B; - case 0xE12D: - return 0xFE80B; - case 0xE12E: - return 0xFEB32; - case 0xE12F: - return 0xFE4DD; - case 0xE130: - return 0xFE80C; - case 0xE131: - return 0xFE7DB; - case 0xE132: - return 0xFE7D7; - case 0xE133: - return 0xFE80D; - case 0xE134: - return 0xFE7DC; - case 0xE135: - return 0xFE7EE; - case 0xE136: - return 0xFE7EB; - case 0xE137: - return 0xFE7F8; - case 0xE138: - return 0xFEB33; - case 0xE139: - return 0xFEB34; - case 0xE13A: - return 0xFEB35; - case 0xE13B: - return 0xFE509; - case 0xE13C: - return 0xFEB59; - case 0xE13D: - return 0xFE004; - case 0xE13E: - return 0xFE4D6; - case 0xE13F: - return 0xFE505; - case 0xE140: - return 0xFE507; - case 0xE141: - return 0xFE821; - case 0xE142: - return 0xFE52F; - case 0xE143: - return 0xFE514; - case 0xE144: - return 0xFEB86; - case 0xE145: - return 0xFEB87; - case 0xE146: - return 0xFE00B; - case 0xE147: - return 0xFE965; - case 0xE148: - return 0xFE546; - case 0xE149: - return 0xFE4DE; - case 0xE14A: - return 0xFE4DF; - case 0xE14B: - return 0xFE531; - case 0xE14C: - return 0xFEB5E; - case 0xE14D: - return 0xFE4B5; - case 0xE14E: - return 0xFE7F7; - case 0xE14F: - return 0xFE7F6; - case 0xE150: - return 0xFE7E7; - case 0xE151: - return 0xFE506; - case 0xE152: - return 0xFE1A1; - case 0xE153: - return 0xFE4B3; - case 0xE154: - return 0xFE4B6; - case 0xE155: - return 0xFE4B4; - case 0xE156: - return 0xFE4B9; - case 0xE157: - return 0xFE4BA; - case 0xE158: - return 0xFE4B7; - case 0xE159: - return 0xFE7E6; - case 0xE15A: - return 0xFE7EF; - case 0xE201: - return 0xFE7F0; - case 0xE202: - return 0xFE7E8; - case 0xE203: - return 0xFEB24; - case 0xE204: - return 0xFEB19; - case 0xE205: - return 0xFEB61; - case 0xE206: - return 0xFEB62; - case 0xE207: - return 0xFEB25; - case 0xE208: - return 0xFEB1F; - case 0xE209: - return 0xFE044; - case 0xE20A: - return 0xFEB20; - case 0xE20B: - return 0xFE838; - case 0xE20C: - return 0xFEB1A; - case 0xE20D: - return 0xFEB1C; - case 0xE20E: - return 0xFEB1B; - case 0xE20F: - return 0xFEB1D; - case 0xE210: - return 0xFE82C; - case 0xE211: - return 0xFE82B; - case 0xE212: - return 0xFEB36; - case 0xE213: - return 0xFEB37; - case 0xE214: - return 0xFEB38; - case 0xE215: - return 0xFEB39; - case 0xE216: - return 0xFEB3A; - case 0xE217: - return 0xFEB3B; - case 0xE218: - return 0xFEB3C; - case 0xE219: - return 0xFEB63; - case 0xE21A: - return 0xFEB64; - case 0xE21B: - return 0xFEB67; - case 0xE21C: - return 0xFE82E; - case 0xE21D: - return 0xFE82F; - case 0xE21E: - return 0xFE830; - case 0xE21F: - return 0xFE831; - case 0xE220: - return 0xFE832; - case 0xE221: - return 0xFE833; - case 0xE222: - return 0xFE834; - case 0xE223: - return 0xFE835; - case 0xE224: - return 0xFE836; - case 0xE225: - return 0xFE837; - case 0xE226: - return 0xFEB3D; - case 0xE227: - return 0xFEB3E; - case 0xE228: - return 0xFEB3F; - case 0xE229: - return 0xFEB81; - case 0xE22A: - return 0xFEB31; - case 0xE22B: - return 0xFEB2F; - case 0xE22C: - return 0xFEB40; - case 0xE22D: - return 0xFEB41; - case 0xE22E: - return 0xFEB99; - case 0xE22F: - return 0xFEB9A; - case 0xE230: - return 0xFEB9B; - case 0xE231: - return 0xFEB9C; - case 0xE232: - return 0xFEAF8; - case 0xE233: - return 0xFEAF9; - case 0xE234: - return 0xFEAFA; - case 0xE235: - return 0xFEAFB; - case 0xE236: - return 0xFEAF0; - case 0xE237: - return 0xFEAF2; - case 0xE238: - return 0xFEAF1; - case 0xE239: - return 0xFEAF3; - case 0xE23A: - return 0xFEAFC; - case 0xE23B: - return 0xFEAFD; - case 0xE23C: - return 0xFEAFE; - case 0xE23D: - return 0xFEAFF; - case 0xE23E: - return 0xFE4F8; - case 0xE23F: - return 0xFE02B; - case 0xE240: - return 0xFE02C; - case 0xE241: - return 0xFE02D; - case 0xE242: - return 0xFE02E; - case 0xE243: - return 0xFE02F; - case 0xE244: - return 0xFE030; - case 0xE245: - return 0xFE031; - case 0xE246: - return 0xFE032; - case 0xE247: - return 0xFE033; - case 0xE248: - return 0xFE034; - case 0xE249: - return 0xFE035; - case 0xE24A: - return 0xFE036; - case 0xE24B: - return 0xFE037; - case 0xE24C: - return 0xFEB42; - case 0xE24D: - return 0xFEB27; - case 0xE24E: - return 0xFEB29; - case 0xE24F: - return 0xFEB2D; - case 0xE250: - return 0xFE839; - case 0xE251: - return 0xFE83A; - case 0xE252: - return 0xFEB23; - case 0xE253: - return 0xFE1B4; - case 0xE254: - return 0xFEE77; - case 0xE255: - return 0xFEE78; - case 0xE256: - return 0xFEE79; - case 0xE257: - return 0xFEE7A; - case 0xE258: - return 0xFEE7B; - case 0xE259: - return 0xFEE7C; - case 0xE25A: - return 0xFEE7D; - case 0xE301: - return 0xFE527; - case 0xE302: - return 0xFE4D3; - case 0xE303: - return 0xFE045; - case 0xE304: - return 0xFE03D; - case 0xE305: - return 0xFE046; - case 0xE306: - return 0xFE828; - case 0xE307: - return 0xFE047; - case 0xE308: - return 0xFE048; - case 0xE309: - return 0xFE508; - case 0xE30A: - return 0xFE803; - case 0xE30B: - return 0xFE985; - case 0xE30C: - return 0xFE987; - case 0xE30D: - return 0xFEB43; - case 0xE30E: - return 0xFEB1E; - case 0xE30F: - return 0xFE50A; - case 0xE310: - return 0xFE516; - case 0xE311: - return 0xFEB58; - case 0xE312: - return 0xFE517; - case 0xE313: - return 0xFE53E; - case 0xE314: - return 0xFE50F; - case 0xE315: - return 0xFEB2B; - case 0xE316: - return 0xFE53C; - case 0xE317: - return 0xFE530; - case 0xE318: - return 0xFE4D4; - case 0xE319: - return 0xFE4D5; - case 0xE31A: - return 0xFE4D7; - case 0xE31B: - return 0xFE4D8; - case 0xE31C: - return 0xFE195; - case 0xE31D: - return 0xFE196; - case 0xE31E: - return 0xFE197; - case 0xE31F: - return 0xFE198; - case 0xE320: - return 0xFE199; - case 0xE321: - return 0xFE4D9; - case 0xE322: - return 0xFE4DA; - case 0xE323: - return 0xFE4F0; - case 0xE324: - return 0xFE808; - case 0xE325: - return 0xFE4F2; - case 0xE326: - return 0xFE814; - case 0xE327: - return 0xFEB0D; - case 0xE328: - return 0xFEB11; - case 0xE329: - return 0xFEB12; - case 0xE32A: - return 0xFEB13; - case 0xE32B: - return 0xFEB14; - case 0xE32C: - return 0xFEB15; - case 0xE32D: - return 0xFEB16; - case 0xE32E: - return 0xFEB60; - case 0xE32F: - return 0xFEB68; - case 0xE330: - return 0xFEB5D; - case 0xE331: - return 0xFEB5B; - case 0xE332: - return 0xFEB44; - case 0xE333: - return 0xFEB45; - case 0xE334: - return 0xFEB57; - case 0xE335: - return 0xFEB69; - case 0xE336: - return 0xFEB0A; - case 0xE337: - return 0xFEB0B; - case 0xE338: - return 0xFE984; - case 0xE339: - return 0xFE964; - case 0xE33A: - return 0xFE966; - case 0xE33B: - return 0xFE967; - case 0xE33C: - return 0xFE968; - case 0xE33D: - return 0xFE969; - case 0xE33E: - return 0xFE96A; - case 0xE33F: - return 0xFE96B; - case 0xE340: - return 0xFE963; - case 0xE341: - return 0xFE96C; - case 0xE342: - return 0xFE961; - case 0xE343: - return 0xFE96D; - case 0xE344: - return 0xFE96E; - case 0xE345: - return 0xFE051; - case 0xE346: - return 0xFE052; - case 0xE347: - return 0xFE053; - case 0xE348: - return 0xFE054; - case 0xE349: - return 0xFE055; - case 0xE34A: - return 0xFE056; - case 0xE34B: - return 0xFE511; - case 0xE34C: - return 0xFE96F; - case 0xE34D: - return 0xFE970; - case 0xE401: - return 0xFE345; - case 0xE402: - return 0xFE343; - case 0xE403: - return 0xFE340; - case 0xE404: - return 0xFE333; - case 0xE405: - return 0xFE347; - case 0xE406: - return 0xFE33C; - case 0xE407: - return 0xFE33F; - case 0xE408: - return 0xFE342; - case 0xE409: - return 0xFE32A; - case 0xE40A: - return 0xFE33E; - case 0xE40B: - return 0xFE33B; - case 0xE40C: - return 0xFE32E; - case 0xE40D: - return 0xFE32F; - case 0xE40E: - return 0xFE326; - case 0xE40F: - return 0xFE325; - case 0xE410: - return 0xFE322; - case 0xE411: - return 0xFE33A; - case 0xE412: - return 0xFE334; - case 0xE413: - return 0xFE339; - case 0xE414: - return 0xFE336; - case 0xE415: - return 0xFE338; - case 0xE416: - return 0xFE33D; - case 0xE417: - return 0xFE32D; - case 0xE418: - return 0xFE32C; - case 0xE419: - return 0xFE190; - case 0xE41A: - return 0xFE192; - case 0xE41B: - return 0xFE191; - case 0xE41C: - return 0xFE193; - case 0xE41D: - return 0xFE35B; - case 0xE41E: - return 0xFEB9D; - case 0xE41F: - return 0xFEB9E; - case 0xE420: - return 0xFEB9F; - case 0xE421: - return 0xFEBA0; - case 0xE422: - return 0xFEBA1; - case 0xE423: - return 0xFE351; - case 0xE424: - return 0xFE352; - case 0xE425: - return 0xFE829; - case 0xE426: - return 0xFE353; - case 0xE427: - return 0xFE358; - case 0xE428: - return 0xFE1A0; - case 0xE429: - return 0xFE1A2; - case 0xE42A: - return 0xFE7D6; - case 0xE42B: - return 0xFE7DD; - case 0xE42C: - return 0xFE80E; - case 0xE42D: - return 0xFE7DE; - case 0xE42E: - return 0xFE7E5; - case 0xE42F: - return 0xFE7F1; - case 0xE430: - return 0xFE7F2; - case 0xE431: - return 0xFE7F3; - case 0xE432: - return 0xFE7F4; - case 0xE433: - return 0xFE7FE; - case 0xE434: - return 0xFE7E0; - case 0xE435: - return 0xFE7E2; - case 0xE436: - return 0xFE518; - case 0xE437: - return 0xFEB17; - case 0xE438: - return 0xFE519; - case 0xE439: - return 0xFE51A; - case 0xE43A: - return 0xFE51B; - case 0xE43B: - return 0xFE51C; - case 0xE43C: - return 0xFE007; - case 0xE43D: - return 0xFE82A; - case 0xE43E: - return 0xFE038; - case 0xE43F: - return 0xFE971; - case 0xE440: - return 0xFE51D; - case 0xE441: - return 0xFE1C6; - case 0xE442: - return 0xFE51E; - case 0xE443: - return 0xFE005; - case 0xE444: - return 0xFE049; - case 0xE445: - return 0xFE51F; - case 0xE446: - return 0xFE017; - case 0xE447: - return 0xFE043; - case 0xE448: - return 0xFE513; - case 0xE449: - return 0xFE00A; - case 0xE44A: - return 0xFE00C; - case 0xE44B: - return 0xFE008; - case 0xE44C: - return 0xFE00D; - case 0xE501: - return 0xFE4B8; - case 0xE502: - return 0xFE804; - case 0xE503: - return 0xFE805; - case 0xE504: - return 0xFE4BD; - case 0xE505: - return 0xFE4BE; - case 0xE506: - return 0xFE4BF; - case 0xE507: - return 0xFE802; - case 0xE508: - return 0xFE4C0; - case 0xE509: - return 0xFE4C4; - case 0xE50A: - return 0xFE4C5; - case 0xE50B: - return 0xFE4E5; - case 0xE50C: - return 0xFE4E6; - case 0xE50D: - return 0xFE4E7; - case 0xE50E: - return 0xFE4E8; - case 0xE50F: - return 0xFE4E9; - case 0xE510: - return 0xFE4EA; - case 0xE511: - return 0xFE4EB; - case 0xE512: - return 0xFE4EC; - case 0xE513: - return 0xFE4ED; - case 0xE514: - return 0xFE4EE; - case 0xE515: - return 0xFE1A4; - case 0xE516: - return 0xFE1A5; - case 0xE517: - return 0xFE1A6; - case 0xE518: - return 0xFE1A7; - case 0xE519: - return 0xFE1A8; - case 0xE51A: - return 0xFE1A9; - case 0xE51B: - return 0xFE1AA; - case 0xE51C: - return 0xFE1AB; - case 0xE51D: - return 0xFE4C6; - case 0xE51E: - return 0xFE1B5; - case 0xE51F: - return 0xFE1B6; - case 0xE520: - return 0xFE1C7; - case 0xE521: - return 0xFE1C8; - case 0xE522: - return 0xFE1C9; - case 0xE523: - return 0xFE1BA; - case 0xE524: - return 0xFE1CA; - case 0xE525: - return 0xFE1CB; - case 0xE526: - return 0xFE1CC; - case 0xE527: - return 0xFE1CD; - case 0xE528: - return 0xFE1CE; - case 0xE529: - return 0xFE1CF; - case 0xE52A: - return 0xFE1D0; - case 0xE52B: - return 0xFE1D1; - case 0xE52C: - return 0xFE1D2; - case 0xE52D: - return 0xFE1D3; - case 0xE52E: - return 0xFE1D4; - case 0xE52F: - return 0xFE1D5; - case 0xE530: - return 0xFE1D6; - case 0xE531: - return 0xFE1D7; - case 0xE532: - return 0xFE50B; - case 0xE533: - return 0xFE50C; - case 0xE534: - return 0xFE50D; - case 0xE535: - return 0xFE50E; - case 0xE536: - return 0xFE553; - case 0xE537: - return 0xFEB2A; - case 0xE538: - return 0xFEE70; - case 0xE539: - return 0xFEE71; - case 0xE53A: - return 0xFEE72; - case 0xE53B: - return 0xFEE73; - case 0xE53C: - return 0xFEE74; - case 0xE53D: - return 0xFEE75; - case 0xE53E: - return 0xFEE76; - default: - return codePoint; + static private int importCodePointFromIphone(int codePoint) { + switch (codePoint) { + case 0xE001: + return 0xFE19B; + case 0xE002: + return 0xFE19C; + case 0xE003: + return 0xFE823; + case 0xE004: + return 0xFE19D; + case 0xE005: + return 0xFE19E; + case 0xE006: + return 0xFE4CF; + case 0xE007: + return 0xFE4CD; + case 0xE008: + return 0xFE4EF; + case 0xE009: + return 0xFE523; + case 0xE00A: + return 0xFE525; + case 0xE00B: + return 0xFE528; + case 0xE00C: + return 0xFE538; + case 0xE00D: + return 0xFEB96; + case 0xE00E: + return 0xFEB97; + case 0xE00F: + return 0xFEB98; + case 0xE010: + return 0xFEB93; + case 0xE011: + return 0xFEB94; + case 0xE012: + return 0xFEB95; + case 0xE013: + return 0xFE7D5; + case 0xE014: + return 0xFE7D2; + case 0xE015: + return 0xFE7D3; + case 0xE016: + return 0xFE7D1; + case 0xE017: + return 0xFE7DA; + case 0xE018: + return 0xFE7D4; + case 0xE019: + return 0xFE1BD; + case 0xE01A: + return 0xFE1BE; + case 0xE01B: + return 0xFE7E4; + case 0xE01C: + return 0xFE7EA; + case 0xE01D: + return 0xFE7E9; + case 0xE01E: + return 0xFE7DF; + case 0xE01F: + return 0xFE7E3; + case 0xE020: + return 0xFEB09; + case 0xE021: + return 0xFEB04; + case 0xE022: + return 0xFEB0C; + case 0xE023: + return 0xFEB0E; + case 0xE024: + return 0xFE01E; + case 0xE025: + return 0xFE01F; + case 0xE026: + return 0xFE020; + case 0xE027: + return 0xFE021; + case 0xE028: + return 0xFE022; + case 0xE029: + return 0xFE023; + case 0xE02A: + return 0xFE024; + case 0xE02B: + return 0xFE025; + case 0xE02C: + return 0xFE026; + case 0xE02D: + return 0xFE027; + case 0xE02E: + return 0xFE028; + case 0xE02F: + return 0xFE029; + case 0xE030: + return 0xFE040; + case 0xE031: + return 0xFE4D2; + case 0xE032: + return 0xFE041; + case 0xE033: + return 0xFE512; + case 0xE034: + return 0xFE825; + case 0xE035: + return 0xFE826; + case 0xE036: + return 0xFE4B0; + case 0xE037: + return 0xFE4BB; + case 0xE038: + return 0xFE4B2; + case 0xE039: + return 0xFE7EC; + case 0xE03A: + return 0xFE7F5; + case 0xE03B: + return 0xFE4C3; + case 0xE03C: + return 0xFE800; + case 0xE03D: + return 0xFE801; + case 0xE03E: + return 0xFE813; + case 0xE03F: + return 0xFEB82; + case 0xE040: + return 0xFE815; + case 0xE041: + return 0xFE816; + case 0xE042: + return 0xFE818; + case 0xE043: + return 0xFE980; + case 0xE044: + return 0xFE982; + case 0xE045: + return 0xFE981; + case 0xE046: + return 0xFE962; + case 0xE047: + return 0xFE983; + case 0xE048: + return 0xFE003; + case 0xE049: + return 0xFE001; + case 0xE04A: + return 0xFE000; + case 0xE04B: + return 0xFE002; + case 0xE04C: + return 0xFE014; + case 0xE04D: + return 0xFE009; + case 0xE04E: + return 0xFE1AF; + case 0xE04F: + return 0xFE1B8; + case 0xE050: + return 0xFE1C0; + case 0xE051: + return 0xFE1C1; + case 0xE052: + return 0xFE1B7; + case 0xE053: + return 0xFE1C2; + case 0xE054: + return 0xFE1C3; + case 0xE055: + return 0xFE1BC; + case 0xE056: + return 0xFE335; + case 0xE057: + return 0xFE330; + case 0xE058: + return 0xFE323; + case 0xE059: + return 0xFE320; + case 0xE05A: + return 0xFE4F4; + case 0xE101: + return 0xFE52D; + case 0xE102: + return 0xFE52E; + case 0xE103: + return 0xFE52B; + case 0xE104: + return 0xFE526; + case 0xE105: + return 0xFE329; + case 0xE106: + return 0xFE327; + case 0xE107: + return 0xFE341; + case 0xE108: + return 0xFE344; + case 0xE109: + return 0xFE1C4; + case 0xE10A: + return 0xFE1C5; + case 0xE10B: + return 0xFE1BF; + case 0xE10C: + return 0xFE1B0; + case 0xE10D: + return 0xFE7ED; + case 0xE10E: + return 0xFE4D1; + case 0xE10F: + return 0xFEB56; + case 0xE110: + return 0xFE03C; + case 0xE111: + return 0xFE827; + case 0xE112: + return 0xFE510; + case 0xE113: + return 0xFE4F5; + case 0xE114: + return 0xFEB85; + case 0xE115: + return 0xFE7D9; + case 0xE116: + return 0xFE4CA; + case 0xE117: + return 0xFE515; + case 0xE118: + return 0xFE03F; + case 0xE119: + return 0xFE042; + case 0xE11A: + return 0xFE1B2; + case 0xE11B: + return 0xFE1AE; + case 0xE11C: + return 0xFE1B3; + case 0xE11D: + return 0xFE4F6; + case 0xE11E: + return 0xFE53B; + case 0xE11F: + return 0xFE537; + case 0xE120: + return 0xFE960; + case 0xE121: + return 0xFE4BC; + case 0xE122: + return 0xFE7FB; + case 0xE123: + return 0xFE7FA; + case 0xE124: + return 0xFE7FD; + case 0xE125: + return 0xFE807; + case 0xE126: + return 0xFE81D; + case 0xE127: + return 0xFE81E; + case 0xE128: + return 0xFE81F; + case 0xE129: + return 0xFE820; + case 0xE12A: + return 0xFE81C; + case 0xE12B: + return 0xFE1B1; + case 0xE12C: + return 0xFE81B; + case 0xE12D: + return 0xFE80B; + case 0xE12E: + return 0xFEB32; + case 0xE12F: + return 0xFE4DD; + case 0xE130: + return 0xFE80C; + case 0xE131: + return 0xFE7DB; + case 0xE132: + return 0xFE7D7; + case 0xE133: + return 0xFE80D; + case 0xE134: + return 0xFE7DC; + case 0xE135: + return 0xFE7EE; + case 0xE136: + return 0xFE7EB; + case 0xE137: + return 0xFE7F8; + case 0xE138: + return 0xFEB33; + case 0xE139: + return 0xFEB34; + case 0xE13A: + return 0xFEB35; + case 0xE13B: + return 0xFE509; + case 0xE13C: + return 0xFEB59; + case 0xE13D: + return 0xFE004; + case 0xE13E: + return 0xFE4D6; + case 0xE13F: + return 0xFE505; + case 0xE140: + return 0xFE507; + case 0xE141: + return 0xFE821; + case 0xE142: + return 0xFE52F; + case 0xE143: + return 0xFE514; + case 0xE144: + return 0xFEB86; + case 0xE145: + return 0xFEB87; + case 0xE146: + return 0xFE00B; + case 0xE147: + return 0xFE965; + case 0xE148: + return 0xFE546; + case 0xE149: + return 0xFE4DE; + case 0xE14A: + return 0xFE4DF; + case 0xE14B: + return 0xFE531; + case 0xE14C: + return 0xFEB5E; + case 0xE14D: + return 0xFE4B5; + case 0xE14E: + return 0xFE7F7; + case 0xE14F: + return 0xFE7F6; + case 0xE150: + return 0xFE7E7; + case 0xE151: + return 0xFE506; + case 0xE152: + return 0xFE1A1; + case 0xE153: + return 0xFE4B3; + case 0xE154: + return 0xFE4B6; + case 0xE155: + return 0xFE4B4; + case 0xE156: + return 0xFE4B9; + case 0xE157: + return 0xFE4BA; + case 0xE158: + return 0xFE4B7; + case 0xE159: + return 0xFE7E6; + case 0xE15A: + return 0xFE7EF; + case 0xE201: + return 0xFE7F0; + case 0xE202: + return 0xFE7E8; + case 0xE203: + return 0xFEB24; + case 0xE204: + return 0xFEB19; + case 0xE205: + return 0xFEB61; + case 0xE206: + return 0xFEB62; + case 0xE207: + return 0xFEB25; + case 0xE208: + return 0xFEB1F; + case 0xE209: + return 0xFE044; + case 0xE20A: + return 0xFEB20; + case 0xE20B: + return 0xFE838; + case 0xE20C: + return 0xFEB1A; + case 0xE20D: + return 0xFEB1C; + case 0xE20E: + return 0xFEB1B; + case 0xE20F: + return 0xFEB1D; + case 0xE210: + return 0xFE82C; + case 0xE211: + return 0xFE82B; + case 0xE212: + return 0xFEB36; + case 0xE213: + return 0xFEB37; + case 0xE214: + return 0xFEB38; + case 0xE215: + return 0xFEB39; + case 0xE216: + return 0xFEB3A; + case 0xE217: + return 0xFEB3B; + case 0xE218: + return 0xFEB3C; + case 0xE219: + return 0xFEB63; + case 0xE21A: + return 0xFEB64; + case 0xE21B: + return 0xFEB67; + case 0xE21C: + return 0xFE82E; + case 0xE21D: + return 0xFE82F; + case 0xE21E: + return 0xFE830; + case 0xE21F: + return 0xFE831; + case 0xE220: + return 0xFE832; + case 0xE221: + return 0xFE833; + case 0xE222: + return 0xFE834; + case 0xE223: + return 0xFE835; + case 0xE224: + return 0xFE836; + case 0xE225: + return 0xFE837; + case 0xE226: + return 0xFEB3D; + case 0xE227: + return 0xFEB3E; + case 0xE228: + return 0xFEB3F; + case 0xE229: + return 0xFEB81; + case 0xE22A: + return 0xFEB31; + case 0xE22B: + return 0xFEB2F; + case 0xE22C: + return 0xFEB40; + case 0xE22D: + return 0xFEB41; + case 0xE22E: + return 0xFEB99; + case 0xE22F: + return 0xFEB9A; + case 0xE230: + return 0xFEB9B; + case 0xE231: + return 0xFEB9C; + case 0xE232: + return 0xFEAF8; + case 0xE233: + return 0xFEAF9; + case 0xE234: + return 0xFEAFA; + case 0xE235: + return 0xFEAFB; + case 0xE236: + return 0xFEAF0; + case 0xE237: + return 0xFEAF2; + case 0xE238: + return 0xFEAF1; + case 0xE239: + return 0xFEAF3; + case 0xE23A: + return 0xFEAFC; + case 0xE23B: + return 0xFEAFD; + case 0xE23C: + return 0xFEAFE; + case 0xE23D: + return 0xFEAFF; + case 0xE23E: + return 0xFE4F8; + case 0xE23F: + return 0xFE02B; + case 0xE240: + return 0xFE02C; + case 0xE241: + return 0xFE02D; + case 0xE242: + return 0xFE02E; + case 0xE243: + return 0xFE02F; + case 0xE244: + return 0xFE030; + case 0xE245: + return 0xFE031; + case 0xE246: + return 0xFE032; + case 0xE247: + return 0xFE033; + case 0xE248: + return 0xFE034; + case 0xE249: + return 0xFE035; + case 0xE24A: + return 0xFE036; + case 0xE24B: + return 0xFE037; + case 0xE24C: + return 0xFEB42; + case 0xE24D: + return 0xFEB27; + case 0xE24E: + return 0xFEB29; + case 0xE24F: + return 0xFEB2D; + case 0xE250: + return 0xFE839; + case 0xE251: + return 0xFE83A; + case 0xE252: + return 0xFEB23; + case 0xE253: + return 0xFE1B4; + case 0xE254: + return 0xFEE77; + case 0xE255: + return 0xFEE78; + case 0xE256: + return 0xFEE79; + case 0xE257: + return 0xFEE7A; + case 0xE258: + return 0xFEE7B; + case 0xE259: + return 0xFEE7C; + case 0xE25A: + return 0xFEE7D; + case 0xE301: + return 0xFE527; + case 0xE302: + return 0xFE4D3; + case 0xE303: + return 0xFE045; + case 0xE304: + return 0xFE03D; + case 0xE305: + return 0xFE046; + case 0xE306: + return 0xFE828; + case 0xE307: + return 0xFE047; + case 0xE308: + return 0xFE048; + case 0xE309: + return 0xFE508; + case 0xE30A: + return 0xFE803; + case 0xE30B: + return 0xFE985; + case 0xE30C: + return 0xFE987; + case 0xE30D: + return 0xFEB43; + case 0xE30E: + return 0xFEB1E; + case 0xE30F: + return 0xFE50A; + case 0xE310: + return 0xFE516; + case 0xE311: + return 0xFEB58; + case 0xE312: + return 0xFE517; + case 0xE313: + return 0xFE53E; + case 0xE314: + return 0xFE50F; + case 0xE315: + return 0xFEB2B; + case 0xE316: + return 0xFE53C; + case 0xE317: + return 0xFE530; + case 0xE318: + return 0xFE4D4; + case 0xE319: + return 0xFE4D5; + case 0xE31A: + return 0xFE4D7; + case 0xE31B: + return 0xFE4D8; + case 0xE31C: + return 0xFE195; + case 0xE31D: + return 0xFE196; + case 0xE31E: + return 0xFE197; + case 0xE31F: + return 0xFE198; + case 0xE320: + return 0xFE199; + case 0xE321: + return 0xFE4D9; + case 0xE322: + return 0xFE4DA; + case 0xE323: + return 0xFE4F0; + case 0xE324: + return 0xFE808; + case 0xE325: + return 0xFE4F2; + case 0xE326: + return 0xFE814; + case 0xE327: + return 0xFEB0D; + case 0xE328: + return 0xFEB11; + case 0xE329: + return 0xFEB12; + case 0xE32A: + return 0xFEB13; + case 0xE32B: + return 0xFEB14; + case 0xE32C: + return 0xFEB15; + case 0xE32D: + return 0xFEB16; + case 0xE32E: + return 0xFEB60; + case 0xE32F: + return 0xFEB68; + case 0xE330: + return 0xFEB5D; + case 0xE331: + return 0xFEB5B; + case 0xE332: + return 0xFEB44; + case 0xE333: + return 0xFEB45; + case 0xE334: + return 0xFEB57; + case 0xE335: + return 0xFEB69; + case 0xE336: + return 0xFEB0A; + case 0xE337: + return 0xFEB0B; + case 0xE338: + return 0xFE984; + case 0xE339: + return 0xFE964; + case 0xE33A: + return 0xFE966; + case 0xE33B: + return 0xFE967; + case 0xE33C: + return 0xFE968; + case 0xE33D: + return 0xFE969; + case 0xE33E: + return 0xFE96A; + case 0xE33F: + return 0xFE96B; + case 0xE340: + return 0xFE963; + case 0xE341: + return 0xFE96C; + case 0xE342: + return 0xFE961; + case 0xE343: + return 0xFE96D; + case 0xE344: + return 0xFE96E; + case 0xE345: + return 0xFE051; + case 0xE346: + return 0xFE052; + case 0xE347: + return 0xFE053; + case 0xE348: + return 0xFE054; + case 0xE349: + return 0xFE055; + case 0xE34A: + return 0xFE056; + case 0xE34B: + return 0xFE511; + case 0xE34C: + return 0xFE96F; + case 0xE34D: + return 0xFE970; + case 0xE401: + return 0xFE345; + case 0xE402: + return 0xFE343; + case 0xE403: + return 0xFE340; + case 0xE404: + return 0xFE333; + case 0xE405: + return 0xFE347; + case 0xE406: + return 0xFE33C; + case 0xE407: + return 0xFE33F; + case 0xE408: + return 0xFE342; + case 0xE409: + return 0xFE32A; + case 0xE40A: + return 0xFE33E; + case 0xE40B: + return 0xFE33B; + case 0xE40C: + return 0xFE32E; + case 0xE40D: + return 0xFE32F; + case 0xE40E: + return 0xFE326; + case 0xE40F: + return 0xFE325; + case 0xE410: + return 0xFE322; + case 0xE411: + return 0xFE33A; + case 0xE412: + return 0xFE334; + case 0xE413: + return 0xFE339; + case 0xE414: + return 0xFE336; + case 0xE415: + return 0xFE338; + case 0xE416: + return 0xFE33D; + case 0xE417: + return 0xFE32D; + case 0xE418: + return 0xFE32C; + case 0xE419: + return 0xFE190; + case 0xE41A: + return 0xFE192; + case 0xE41B: + return 0xFE191; + case 0xE41C: + return 0xFE193; + case 0xE41D: + return 0xFE35B; + case 0xE41E: + return 0xFEB9D; + case 0xE41F: + return 0xFEB9E; + case 0xE420: + return 0xFEB9F; + case 0xE421: + return 0xFEBA0; + case 0xE422: + return 0xFEBA1; + case 0xE423: + return 0xFE351; + case 0xE424: + return 0xFE352; + case 0xE425: + return 0xFE829; + case 0xE426: + return 0xFE353; + case 0xE427: + return 0xFE358; + case 0xE428: + return 0xFE1A0; + case 0xE429: + return 0xFE1A2; + case 0xE42A: + return 0xFE7D6; + case 0xE42B: + return 0xFE7DD; + case 0xE42C: + return 0xFE80E; + case 0xE42D: + return 0xFE7DE; + case 0xE42E: + return 0xFE7E5; + case 0xE42F: + return 0xFE7F1; + case 0xE430: + return 0xFE7F2; + case 0xE431: + return 0xFE7F3; + case 0xE432: + return 0xFE7F4; + case 0xE433: + return 0xFE7FE; + case 0xE434: + return 0xFE7E0; + case 0xE435: + return 0xFE7E2; + case 0xE436: + return 0xFE518; + case 0xE437: + return 0xFEB17; + case 0xE438: + return 0xFE519; + case 0xE439: + return 0xFE51A; + case 0xE43A: + return 0xFE51B; + case 0xE43B: + return 0xFE51C; + case 0xE43C: + return 0xFE007; + case 0xE43D: + return 0xFE82A; + case 0xE43E: + return 0xFE038; + case 0xE43F: + return 0xFE971; + case 0xE440: + return 0xFE51D; + case 0xE441: + return 0xFE1C6; + case 0xE442: + return 0xFE51E; + case 0xE443: + return 0xFE005; + case 0xE444: + return 0xFE049; + case 0xE445: + return 0xFE51F; + case 0xE446: + return 0xFE017; + case 0xE447: + return 0xFE043; + case 0xE448: + return 0xFE513; + case 0xE449: + return 0xFE00A; + case 0xE44A: + return 0xFE00C; + case 0xE44B: + return 0xFE008; + case 0xE44C: + return 0xFE00D; + case 0xE501: + return 0xFE4B8; + case 0xE502: + return 0xFE804; + case 0xE503: + return 0xFE805; + case 0xE504: + return 0xFE4BD; + case 0xE505: + return 0xFE4BE; + case 0xE506: + return 0xFE4BF; + case 0xE507: + return 0xFE802; + case 0xE508: + return 0xFE4C0; + case 0xE509: + return 0xFE4C4; + case 0xE50A: + return 0xFE4C5; + case 0xE50B: + return 0xFE4E5; + case 0xE50C: + return 0xFE4E6; + case 0xE50D: + return 0xFE4E7; + case 0xE50E: + return 0xFE4E8; + case 0xE50F: + return 0xFE4E9; + case 0xE510: + return 0xFE4EA; + case 0xE511: + return 0xFE4EB; + case 0xE512: + return 0xFE4EC; + case 0xE513: + return 0xFE4ED; + case 0xE514: + return 0xFE4EE; + case 0xE515: + return 0xFE1A4; + case 0xE516: + return 0xFE1A5; + case 0xE517: + return 0xFE1A6; + case 0xE518: + return 0xFE1A7; + case 0xE519: + return 0xFE1A8; + case 0xE51A: + return 0xFE1A9; + case 0xE51B: + return 0xFE1AA; + case 0xE51C: + return 0xFE1AB; + case 0xE51D: + return 0xFE4C6; + case 0xE51E: + return 0xFE1B5; + case 0xE51F: + return 0xFE1B6; + case 0xE520: + return 0xFE1C7; + case 0xE521: + return 0xFE1C8; + case 0xE522: + return 0xFE1C9; + case 0xE523: + return 0xFE1BA; + case 0xE524: + return 0xFE1CA; + case 0xE525: + return 0xFE1CB; + case 0xE526: + return 0xFE1CC; + case 0xE527: + return 0xFE1CD; + case 0xE528: + return 0xFE1CE; + case 0xE529: + return 0xFE1CF; + case 0xE52A: + return 0xFE1D0; + case 0xE52B: + return 0xFE1D1; + case 0xE52C: + return 0xFE1D2; + case 0xE52D: + return 0xFE1D3; + case 0xE52E: + return 0xFE1D4; + case 0xE52F: + return 0xFE1D5; + case 0xE530: + return 0xFE1D6; + case 0xE531: + return 0xFE1D7; + case 0xE532: + return 0xFE50B; + case 0xE533: + return 0xFE50C; + case 0xE534: + return 0xFE50D; + case 0xE535: + return 0xFE50E; + case 0xE536: + return 0xFE553; + case 0xE537: + return 0xFEB2A; + case 0xE538: + return 0xFEE70; + case 0xE539: + return 0xFEE71; + case 0xE53A: + return 0xFEE72; + case 0xE53B: + return 0xFEE73; + case 0xE53C: + return 0xFEE74; + case 0xE53D: + return 0xFEE75; + case 0xE53E: + return 0xFEE76; + default: + return codePoint; } } - public static void setCharset(String charset, Part part) throws MessagingException - { + public static void setCharset(String charset, Part part) throws MessagingException { part.setHeader(MimeHeader.HEADER_CONTENT_TYPE, part.getMimeType() + ";\n charset=" + getExternalCharset(charset)); } - public static String getExternalCharset(String charset) - { + public static String getExternalCharset(String charset) { if (charset.length() > 17 && charset.startsWith("x-") && charset.endsWith("-shift_jis-2007")) return "shift_jis"; diff --git a/src/com/fsck/k9/mail/internet/TextBody.java b/src/com/fsck/k9/mail/internet/TextBody.java index bd2971c86..f89b8aad2 100644 --- a/src/com/fsck/k9/mail/internet/TextBody.java +++ b/src/com/fsck/k9/mail/internet/TextBody.java @@ -8,8 +8,7 @@ import java.io.*; import org.apache.james.mime4j.codec.QuotedPrintableOutputStream; -public class TextBody implements Body -{ +public class TextBody implements Body { /** * Immutable empty byte array @@ -25,22 +24,16 @@ public class TextBody implements Body // Offset from position 0 where the composed message begins. private Integer mComposedMessageOffset; - public TextBody(String body) - { + public TextBody(String body) { this.mBody = body; } - public void writeTo(OutputStream out) throws IOException, MessagingException - { - if (mBody != null) - { + public void writeTo(OutputStream out) throws IOException, MessagingException { + if (mBody != null) { byte[] bytes = mBody.getBytes(mCharset); - if ("8bit".equals(mEncoding)) - { + if ("8bit".equals(mEncoding)) { out.write(bytes); - } - else - { + } else { QuotedPrintableOutputStream qp = new QuotedPrintableOutputStream(out, false); qp.write(bytes); qp.flush(); @@ -52,62 +45,48 @@ public class TextBody implements Body * Get the text of the body in it's unencoded format. * @return */ - public String getText() - { + public String getText() { return mBody; } /** * Returns an InputStream that reads this body's text. */ - public InputStream getInputStream() throws MessagingException - { - try - { + public InputStream getInputStream() throws MessagingException { + try { byte[] b; - if (mBody!=null) - { + if (mBody != null) { b = mBody.getBytes(mCharset); - } - else - { + } else { b = EMPTY_BYTE_ARRAY; } return new ByteArrayInputStream(b); - } - catch (UnsupportedEncodingException usee) - { + } catch (UnsupportedEncodingException usee) { return null; } } - public void setEncoding(String encoding) - { + public void setEncoding(String encoding) { mEncoding = encoding; } - public void setCharset(String charset) - { + public void setCharset(String charset) { mCharset = charset; } - public Integer getComposedMessageLength() - { + public Integer getComposedMessageLength() { return mComposedMessageLength; } - public void setComposedMessageLength(Integer composedMessageLength) - { + public void setComposedMessageLength(Integer composedMessageLength) { this.mComposedMessageLength = composedMessageLength; } - public Integer getComposedMessageOffset() - { + public Integer getComposedMessageOffset() { return mComposedMessageOffset; } - public void setComposedMessageOffset(Integer composedMessageOffset) - { + public void setComposedMessageOffset(Integer composedMessageOffset) { this.mComposedMessageOffset = composedMessageOffset; } } diff --git a/src/com/fsck/k9/mail/store/ImapResponseParser.java b/src/com/fsck/k9/mail/store/ImapResponseParser.java index 86f39b026..93d9d79a3 100644 --- a/src/com/fsck/k9/mail/store/ImapResponseParser.java +++ b/src/com/fsck/k9/mail/store/ImapResponseParser.java @@ -11,8 +11,7 @@ import java.util.ArrayList; import java.util.Date; import java.util.Locale; -public class ImapResponseParser -{ +public class ImapResponseParser { private static final SimpleDateFormat mDateTimeFormat = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss Z", Locale.US); private static final SimpleDateFormat badDateTimeFormat = new SimpleDateFormat("dd MMM yyyy HH:mm:ss Z", Locale.US); private static final SimpleDateFormat badDateTimeFormat2 = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss Z", Locale.US); @@ -21,13 +20,11 @@ public class ImapResponseParser private ImapResponse mResponse; private Exception mException; - public ImapResponseParser(PeekableInputStream in) - { + public ImapResponseParser(PeekableInputStream in) { this.mIn = in; } - public ImapResponse readResponse() throws IOException - { + public ImapResponse readResponse() throws IOException { return readResponse(null); } @@ -35,56 +32,43 @@ public class ImapResponseParser * Reads the next response available on the stream and returns an * ImapResponse object that represents it. */ - public ImapResponse readResponse(IImapResponseCallback callback) throws IOException - { - try - { + public ImapResponse readResponse(IImapResponseCallback callback) throws IOException { + try { ImapResponse response = new ImapResponse(); mResponse = response; mResponse.mCallback = callback; int ch = mIn.peek(); - if (ch == '*') - { + if (ch == '*') { parseUntaggedResponse(); readTokens(response); - } - else if (ch == '+') - { + } else if (ch == '+') { response.mCommandContinuationRequested = parseCommandContinuationRequest(); //TODO: Add special "resp-text" parsing readTokens(response); - } - else - { + } else { response.mTag = parseTaggedResponse(); readTokens(response); } - if (mException != null) - { + if (mException != null) { throw new RuntimeException("readResponse(): Exception in callback method", mException); } return response; - } - finally - { + } finally { mResponse.mCallback = null; mResponse = null; mException = null; } } - private void readTokens(ImapResponse response) throws IOException - { + private void readTokens(ImapResponse response) throws IOException { response.clear(); Object token; - while ((token = readToken(response)) != null) - { - if (!(token instanceof ImapList)) - { + while ((token = readToken(response)) != null) { + if (!(token instanceof ImapList)) { response.add(token); } @@ -109,184 +93,129 @@ public class ImapResponseParser * @return The next token in the response or null if there are no more * tokens. */ - private Object readToken(ImapResponse response) throws IOException - { - while (true) - { + private Object readToken(ImapResponse response) throws IOException { + while (true) { Object token = parseToken(response); - if (token == null || !(token.equals(")") || token.equals("]"))) - { + if (token == null || !(token.equals(")") || token.equals("]"))) { return token; } } } - private Object parseToken(ImapList parent) throws IOException - { - while (true) - { + private Object parseToken(ImapList parent) throws IOException { + while (true) { int ch = mIn.peek(); - if (ch == '(') - { + if (ch == '(') { return parseList(parent); - } - else if (ch == '[') - { + } else if (ch == '[') { return parseSequence(parent); - } - else if (ch == ')') - { + } else if (ch == ')') { expect(')'); return ")"; - } - else if (ch == ']') - { + } else if (ch == ']') { expect(']'); return "]"; - } - else if (ch == '"') - { + } else if (ch == '"') { return parseQuoted(); - } - else if (ch == '{') - { + } else if (ch == '{') { return parseLiteral(); - } - else if (ch == ' ') - { + } else if (ch == ' ') { expect(' '); - } - else if (ch == '\r') - { + } else if (ch == '\r') { expect('\r'); expect('\n'); return null; - } - else if (ch == '\n') - { + } else if (ch == '\n') { expect('\n'); return null; - } - else if (ch == '\t') - { + } else if (ch == '\t') { expect('\t'); - } - else - { + } else { return parseAtom(); } } } - private boolean parseCommandContinuationRequest() throws IOException - { + private boolean parseCommandContinuationRequest() throws IOException { expect('+'); return true; } // * OK [UIDNEXT 175] Predicted next UID - private void parseUntaggedResponse() throws IOException - { + private void parseUntaggedResponse() throws IOException { expect('*'); expect(' '); } // 3 OK [READ-WRITE] Select completed. - private String parseTaggedResponse() throws IOException - { + private String parseTaggedResponse() throws IOException { String tag = readStringUntil(' '); return tag; } - private ImapList parseList(ImapList parent) throws IOException - { + private ImapList parseList(ImapList parent) throws IOException { expect('('); ImapList list = new ImapList(); parent.add(list); Object token; - while (true) - { + while (true) { token = parseToken(list); - if (token == null) - { + if (token == null) { return null; - } - else if (token.equals(")")) - { + } else if (token.equals(")")) { break; - } - else if (token instanceof ImapList) - { + } else if (token instanceof ImapList) { // Do nothing - } - else - { + } else { list.add(token); } } return list; } - private ImapList parseSequence(ImapList parent) throws IOException - { + private ImapList parseSequence(ImapList parent) throws IOException { expect('['); ImapList list = new ImapList(); parent.add(list); Object token; - while (true) - { + while (true) { token = parseToken(list); - if (token == null) - { + if (token == null) { return null; - } - else if (token.equals("]")) - { + } else if (token.equals("]")) { break; - } - else if (token instanceof ImapList) - { + } else if (token instanceof ImapList) { // Do nothing - } - else - { + } else { list.add(token); } } return list; } - private String parseAtom() throws IOException - { + private String parseAtom() throws IOException { StringBuffer sb = new StringBuffer(); int ch; - while (true) - { + while (true) { ch = mIn.peek(); - if (ch == -1) - { + if (ch == -1) { throw new IOException("parseAtom(): end of stream reached"); - } - else if (ch == '(' || ch == ')' || ch == '{' || ch == ' ' || - ch == '[' || ch == ']' || - // docs claim that flags are \ atom but atom isn't supposed to - // contain - // * and some falgs contain * - // ch == '%' || ch == '*' || + } else if (ch == '(' || ch == ')' || ch == '{' || ch == ' ' || + ch == '[' || ch == ']' || + // docs claim that flags are \ atom but atom isn't supposed to + // contain + // * and some falgs contain * + // ch == '%' || ch == '*' || // ch == '%' || - // TODO probably should not allow \ and should recognize - // it as a flag instead - // ch == '"' || ch == '\' || - ch == '"' || (ch >= 0x00 && ch <= 0x1f) || ch == 0x7f) - { - if (sb.length() == 0) - { + // TODO probably should not allow \ and should recognize + // it as a flag instead + // ch == '"' || ch == '\' || + ch == '"' || (ch >= 0x00 && ch <= 0x1f) || ch == 0x7f) { + if (sb.length() == 0) { throw new IOException(String.format("parseAtom(): (%04x %c)", ch, ch)); } return sb.toString(); - } - else - { + } else { sb.append((char)mIn.read()); } } @@ -296,34 +225,26 @@ public class ImapResponseParser * A "{" has been read. Read the rest of the size string, the space and then * notify the callback with an InputStream. */ - private Object parseLiteral() throws IOException - { + private Object parseLiteral() throws IOException { expect('{'); int size = Integer.parseInt(readStringUntil('}')); expect('\r'); expect('\n'); - if (size == 0) - { + if (size == 0) { return ""; } - if (mResponse.mCallback != null) - { + if (mResponse.mCallback != null) { FixedLengthInputStream fixed = new FixedLengthInputStream(mIn, size); Object result = null; - try - { + try { result = mResponse.mCallback.foundLiteral(mResponse, fixed); - } - catch (IOException e) - { + } catch (IOException e) { // Pass IOExceptions through throw e; - } - catch (Exception e) - { + } catch (Exception e) { // Catch everything else and save it for later. mException = e; //Log.e(K9.LOG_TAG, "parseLiteral(): Exception in callback method", e); @@ -331,28 +252,23 @@ public class ImapResponseParser // Check if only some of the literal data was read int available = fixed.available(); - if ((available > 0) && (available != size)) - { + if ((available > 0) && (available != size)) { // If so, skip the rest - while (fixed.available() > 0) - { + while (fixed.available() > 0) { fixed.skip(fixed.available()); } } - if (result != null) - { + if (result != null) { return result; } } byte[] data = new byte[size]; int read = 0; - while (read != size) - { + while (read != size) { int count = mIn.read(data, read, size - read); - if (count == -1) - { + if (count == -1) { throw new IOException("parseLiteral(): end of stream reached"); } read += count; @@ -361,26 +277,19 @@ public class ImapResponseParser return new String(data, "US-ASCII"); } - private String parseQuoted() throws IOException - { + private String parseQuoted() throws IOException { expect('"'); StringBuffer sb = new StringBuffer(); int ch; boolean escape = false; - while ((ch = mIn.read()) != -1) - { - if (!escape && (ch == '\\')) - { + while ((ch = mIn.read()) != -1) { + if (!escape && (ch == '\\')) { // Found the escape character escape = true; - } - else if (!escape && (ch == '"')) - { + } else if (!escape && (ch == '"')) { return sb.toString(); - } - else - { + } else { sb.append((char)ch); escape = false; } @@ -388,29 +297,22 @@ public class ImapResponseParser throw new IOException("parseQuoted(): end of stream reached"); } - private String readStringUntil(char end) throws IOException - { + private String readStringUntil(char end) throws IOException { StringBuffer sb = new StringBuffer(); int ch; - while ((ch = mIn.read()) != -1) - { - if (ch == end) - { + while ((ch = mIn.read()) != -1) { + if (ch == end) { return sb.toString(); - } - else - { + } else { sb.append((char)ch); } } throw new IOException("readStringUntil(): end of stream reached"); } - private int expect(char ch) throws IOException - { + private int expect(char ch) throws IOException { int d; - if ((d = mIn.read()) != ch) - { + if ((d = mIn.read()) != ch) { throw new IOException(String.format("Expected %04x (%c) but got %04x (%c)", (int)ch, ch, d, (char)d)); } @@ -421,119 +323,90 @@ public class ImapResponseParser * Represents an IMAP list response and is also the base class for the * ImapResponse. */ - public class ImapList extends ArrayList - { + public class ImapList extends ArrayList { private static final long serialVersionUID = -4067248341419617583L; - public ImapList getList(int index) - { + public ImapList getList(int index) { return (ImapList)get(index); } - public Object getObject(int index) - { + public Object getObject(int index) { return get(index); } - public String getString(int index) - { + public String getString(int index) { return (String)get(index); } - public InputStream getLiteral(int index) - { + public InputStream getLiteral(int index) { return (InputStream)get(index); } - public int getNumber(int index) - { + public int getNumber(int index) { return Integer.parseInt(getString(index)); } - public Date getDate(int index) throws MessagingException - { - try - { + public Date getDate(int index) throws MessagingException { + try { return parseDate(getString(index)); - } - catch (ParseException pe) - { + } catch (ParseException pe) { throw new MessagingException("Unable to parse IMAP datetime", pe); } } - public Object getKeyedValue(Object key) - { - for (int i = 0, count = size(); i < count; i++) - { - if (equalsIgnoreCase(get(i), key)) - { + public Object getKeyedValue(Object key) { + for (int i = 0, count = size(); i < count; i++) { + if (equalsIgnoreCase(get(i), key)) { return get(i + 1); } } return null; } - public ImapList getKeyedList(Object key) - { + public ImapList getKeyedList(Object key) { return (ImapList)getKeyedValue(key); } - public String getKeyedString(Object key) - { + public String getKeyedString(Object key) { return (String)getKeyedValue(key); } - public InputStream getKeyedLiteral(Object key) - { + public InputStream getKeyedLiteral(Object key) { return (InputStream)getKeyedValue(key); } - public int getKeyedNumber(Object key) - { + public int getKeyedNumber(Object key) { return Integer.parseInt(getKeyedString(key)); } - public Date getKeyedDate(Object key) throws MessagingException - { - try - { + public Date getKeyedDate(Object key) throws MessagingException { + try { String value = getKeyedString(key); - if (value == null) - { + if (value == null) { return null; } return parseDate(value); - } - catch (ParseException pe) - { + } catch (ParseException pe) { throw new MessagingException("Unable to parse IMAP datetime", pe); } } - public boolean containsKey(Object key) - { - if (key == null) - { + public boolean containsKey(Object key) { + if (key == null) { return false; } - for (int i = 0, count = size(); i < count; i++) - { - if (equalsIgnoreCase(key, get(i))) - { + for (int i = 0, count = size(); i < count; i++) { + if (equalsIgnoreCase(key, get(i))) { return true; } } return false; } - public int getKeyIndex(Object key) - { - for (int i = 0, count = size(); i < count; i++) - { - if (equalsIgnoreCase(key, get(i))) - { + public int getKeyIndex(Object key) { + for (int i = 0, count = size(); i < count; i++) { + if (equalsIgnoreCase(key, get(i))) { return i; } } @@ -541,29 +414,19 @@ public class ImapResponseParser throw new IllegalArgumentException("getKeyIndex() only works for keys that are in the collection."); } - private Date parseDate(String value) throws ParseException - { + private Date parseDate(String value) throws ParseException { //TODO: clean this up a bit - try - { - synchronized (mDateTimeFormat) - { + try { + synchronized (mDateTimeFormat) { return mDateTimeFormat.parse(value); } - } - catch (Exception e) - { - try - { - synchronized (badDateTimeFormat) - { + } catch (Exception e) { + try { + synchronized (badDateTimeFormat) { return badDateTimeFormat.parse(value); } - } - catch (Exception e2) - { - synchronized (badDateTimeFormat2) - { + } catch (Exception e2) { + synchronized (badDateTimeFormat2) { return badDateTimeFormat2.parse(value); } } @@ -580,8 +443,7 @@ public class ImapResponseParser * does not contain the entire response the caller must call more() to * continue reading the response until more returns false. */ - public class ImapResponse extends ImapList - { + public class ImapResponse extends ImapList { /** * */ @@ -592,66 +454,49 @@ public class ImapResponseParser boolean mCommandContinuationRequested; String mTag; - public boolean more() throws IOException - { - if (mCompleted) - { + public boolean more() throws IOException { + if (mCompleted) { return false; } readTokens(this); return true; } - public String getAlertText() - { - if (size() > 1 && equalsIgnoreCase("[ALERT]", get(1))) - { + public String getAlertText() { + if (size() > 1 && equalsIgnoreCase("[ALERT]", get(1))) { StringBuffer sb = new StringBuffer(); - for (int i = 2, count = size(); i < count; i++) - { + for (int i = 2, count = size(); i < count; i++) { sb.append(get(i).toString()); sb.append(' '); } return sb.toString(); - } - else - { + } else { return null; } } @Override - public String toString() - { + public String toString() { return "#" + (mCommandContinuationRequested ? "+" : mTag) + "# " + super.toString(); } } - public static boolean equalsIgnoreCase(Object o1, Object o2) - { - if (o1 != null && o2 != null && o1 instanceof String && o2 instanceof String) - { + public static boolean equalsIgnoreCase(Object o1, Object o2) { + if (o1 != null && o2 != null && o1 instanceof String && o2 instanceof String) { String s1 = (String)o1; String s2 = (String)o2; return s1.equalsIgnoreCase(s2); - } - else if (o1 != null) - { + } else if (o1 != null) { return o1.equals(o2); - } - else if (o2 != null) - { + } else if (o2 != null) { return o2.equals(o1); - } - else - { + } else { // Both o1 and o2 are null return true; } } - public interface IImapResponseCallback - { + public interface IImapResponseCallback { /** * Callback method that is called by the parser when a literal string * is found in an IMAP response. diff --git a/src/com/fsck/k9/mail/store/ImapStore.java b/src/com/fsck/k9/mail/store/ImapStore.java index 271b5c74e..2a5dd2a27 100644 --- a/src/com/fsck/k9/mail/store/ImapStore.java +++ b/src/com/fsck/k9/mail/store/ImapStore.java @@ -98,8 +98,7 @@ import com.jcraft.jzlib.ZOutputStream; * TODO Need a default response handler for things like folder updates * */ -public class ImapStore extends Store -{ +public class ImapStore extends Store { public static final int CONNECTION_SECURITY_NONE = 0; public static final int CONNECTION_SECURITY_TLS_OPTIONAL = 1; public static final int CONNECTION_SECURITY_TLS_REQUIRED = 2; @@ -142,84 +141,70 @@ public class ImapStore extends Store private volatile String mCombinedPrefix = null; private volatile String mPathDelimeter = null; - public class StoreImapSettings implements ImapSettings - { + public class StoreImapSettings implements ImapSettings { @Override - public String getHost() - { + public String getHost() { return mHost; } @Override - public int getPort() - { + public int getPort() { return mPort; } @Override - public int getConnectionSecurity() - { + public int getConnectionSecurity() { return mConnectionSecurity; } @Override - public AuthType getAuthType() - { + public AuthType getAuthType() { return mAuthType; } @Override - public String getUsername() - { + public String getUsername() { return mUsername; } @Override - public String getPassword() - { + public String getPassword() { return mPassword; } @Override - public boolean useCompression(final int type) - { + public boolean useCompression(final int type) { return mAccount.useCompression(type); } @Override - public String getPathPrefix() - { + public String getPathPrefix() { return mPathPrefix; } @Override - public void setPathPrefix(String prefix) - { + public void setPathPrefix(String prefix) { mPathPrefix = prefix; } @Override - public String getPathDelimeter() - { + public String getPathDelimeter() { return mPathDelimeter; } @Override - public void setPathDelimeter(String delimeter) - { + public void setPathDelimeter(String delimeter) { mPathDelimeter = delimeter; } @Override - public String getCombinedPrefix() - { + public String getCombinedPrefix() { return mCombinedPrefix; } @Override - public void setCombinedPrefix(String prefix) - { + public void setCombinedPrefix(String prefix) { mCombinedPrefix = prefix; } @@ -252,87 +237,62 @@ public class ImapStore extends Store * * @param _uri */ - public ImapStore(Account account) throws MessagingException - { + public ImapStore(Account account) throws MessagingException { super(account); URI uri; - try - { + try { uri = new URI(mAccount.getStoreUri()); - } - catch (URISyntaxException use) - { + } catch (URISyntaxException use) { throw new MessagingException("Invalid ImapStore URI", use); } String scheme = uri.getScheme(); - if (scheme.equals("imap")) - { + if (scheme.equals("imap")) { mConnectionSecurity = CONNECTION_SECURITY_NONE; mPort = 143; - } - else if (scheme.equals("imap+tls")) - { + } else if (scheme.equals("imap+tls")) { mConnectionSecurity = CONNECTION_SECURITY_TLS_OPTIONAL; mPort = 143; - } - else if (scheme.equals("imap+tls+")) - { + } else if (scheme.equals("imap+tls+")) { mConnectionSecurity = CONNECTION_SECURITY_TLS_REQUIRED; mPort = 143; - } - else if (scheme.equals("imap+ssl+")) - { + } else if (scheme.equals("imap+ssl+")) { mConnectionSecurity = CONNECTION_SECURITY_SSL_REQUIRED; mPort = 993; - } - else if (scheme.equals("imap+ssl")) - { + } else if (scheme.equals("imap+ssl")) { mConnectionSecurity = CONNECTION_SECURITY_SSL_OPTIONAL; mPort = 993; - } - else - { + } else { throw new MessagingException("Unsupported protocol"); } mHost = uri.getHost(); - if (uri.getPort() != -1) - { + if (uri.getPort() != -1) { mPort = uri.getPort(); } - if (uri.getUserInfo() != null) - { - try - { + if (uri.getUserInfo() != null) { + try { String[] userInfoParts = uri.getUserInfo().split(":"); - if (userInfoParts.length == 2) - { + if (userInfoParts.length == 2) { mAuthType = AuthType.PLAIN; mUsername = URLDecoder.decode(userInfoParts[0], "UTF-8"); mPassword = URLDecoder.decode(userInfoParts[1], "UTF-8"); - } - else - { + } else { mAuthType = AuthType.valueOf(userInfoParts[0]); mUsername = URLDecoder.decode(userInfoParts[1], "UTF-8"); mPassword = URLDecoder.decode(userInfoParts[2], "UTF-8"); } - } - catch (UnsupportedEncodingException enc) - { + } catch (UnsupportedEncodingException enc) { // This shouldn't happen since the encoding is hardcoded to UTF-8 Log.e(K9.LOG_TAG, "Couldn't urldecode username or password.", enc); } } - if ((uri.getPath() != null) && (uri.getPath().length() > 0)) - { + if ((uri.getPath() != null) && (uri.getPath().length() > 0)) { mPathPrefix = uri.getPath().substring(1); - if (mPathPrefix != null && mPathPrefix.trim().length() == 0) - { + if (mPathPrefix != null && mPathPrefix.trim().length() == 0) { mPathPrefix = null; } } @@ -341,14 +301,11 @@ public class ImapStore extends Store } @Override - public Folder getFolder(String name) - { + public Folder getFolder(String name) { ImapFolder folder; - synchronized (mFolderCache) - { + synchronized (mFolderCache) { folder = mFolderCache.get(name); - if (folder == null) - { + if (folder == null) { folder = new ImapFolder(this, name); mFolderCache.put(name, folder); } @@ -356,29 +313,19 @@ public class ImapStore extends Store return folder; } - private String getCombinedPrefix() - { - if (mCombinedPrefix == null) - { - if (mPathPrefix != null) - { + private String getCombinedPrefix() { + if (mCombinedPrefix == null) { + if (mPathPrefix != null) { String tmpPrefix = mPathPrefix.trim(); String tmpDelim = (mPathDelimeter != null ? mPathDelimeter.trim() : ""); - if (tmpPrefix.endsWith(tmpDelim)) - { + if (tmpPrefix.endsWith(tmpDelim)) { mCombinedPrefix = tmpPrefix; - } - else if (tmpPrefix.length() > 0) - { + } else if (tmpPrefix.length() > 0) { mCombinedPrefix = tmpPrefix + tmpDelim; - } - else - { + } else { mCombinedPrefix = ""; } - } - else - { + } else { mCombinedPrefix = ""; } } @@ -386,54 +333,39 @@ public class ImapStore extends Store } @Override - public List getPersonalNamespaces(boolean forceListAll) throws MessagingException - { + public List getPersonalNamespaces(boolean forceListAll) throws MessagingException { ImapConnection connection = getConnection(); - try - { - List allFolders = listFolders(connection, false); - if (forceListAll || !mAccount.subscribedFoldersOnly()) - { + try { + List allFolders = listFolders(connection, false); + if (forceListAll || !mAccount.subscribedFoldersOnly()) { return allFolders; - } - else - { + } else { List resultFolders = new LinkedList(); HashSet subscribedFolderNames = new HashSet(); - List subscribedFolders = listFolders(connection, true); - for (Folder subscribedFolder : subscribedFolders) - { + List subscribedFolders = listFolders(connection, true); + for (Folder subscribedFolder : subscribedFolders) { subscribedFolderNames.add(subscribedFolder.getName()); } - for (Folder folder : allFolders) - { - if (subscribedFolderNames.contains(folder.getName())) - { + for (Folder folder : allFolders) { + if (subscribedFolderNames.contains(folder.getName())) { resultFolders.add(folder); } } return resultFolders; } - } - catch (IOException ioe) - { + } catch (IOException ioe) { connection.close(); throw new MessagingException("Unable to get folder list.", ioe); - } - catch (MessagingException me) - { + } catch (MessagingException me) { connection.close(); throw new MessagingException("Unable to get folder list.", me); - } - finally - { + } finally { releaseConnection(connection); } } - private List listFolders(ImapConnection connection, boolean LSUB) throws IOException, MessagingException - { + private List listFolders(ImapConnection connection, boolean LSUB) throws IOException, MessagingException { String commandResponse = LSUB ? "LSUB" : "LIST"; LinkedList folders = new LinkedList(); @@ -442,50 +374,38 @@ public class ImapStore extends Store connection.executeSimpleCommand(String.format(commandResponse + " \"\" %s", encodeString(getCombinedPrefix() + "*"))); - for (ImapResponse response : responses) - { - if (ImapResponseParser.equalsIgnoreCase(response.get(0), commandResponse)) - { + for (ImapResponse response : responses) { + if (ImapResponseParser.equalsIgnoreCase(response.get(0), commandResponse)) { boolean includeFolder = true; String folder = decodeFolderName(response.getString(3)); - if (mPathDelimeter == null) - { + if (mPathDelimeter == null) { mPathDelimeter = response.getString(2); mCombinedPrefix = null; } - if (folder.equalsIgnoreCase(K9.INBOX)) - { + if (folder.equalsIgnoreCase(K9.INBOX)) { continue; - } - else - { + } else { - if (getCombinedPrefix().length() > 0) - { - if (folder.length() >= getCombinedPrefix().length()) - { + if (getCombinedPrefix().length() > 0) { + if (folder.length() >= getCombinedPrefix().length()) { folder = folder.substring(getCombinedPrefix().length()); } - if (!decodeFolderName(response.getString(3)).equalsIgnoreCase(getCombinedPrefix() + folder)) - { + if (!decodeFolderName(response.getString(3)).equalsIgnoreCase(getCombinedPrefix() + folder)) { includeFolder = false; } } } ImapList attributes = response.getList(1); - for (int i = 0, count = attributes.size(); i < count; i++) - { + for (int i = 0, count = attributes.size(); i < count; i++) { String attribute = attributes.getString(i); - if (attribute.equalsIgnoreCase("\\NoSelect")) - { + if (attribute.equalsIgnoreCase("\\NoSelect")) { includeFolder = false; } } - if (includeFolder) - { + if (includeFolder) { folders.add(getFolder(folder)); } } @@ -496,16 +416,12 @@ public class ImapStore extends Store } @Override - public void checkSettings() throws MessagingException - { - try - { + public void checkSettings() throws MessagingException { + try { ImapConnection connection = new ImapConnection(new StoreImapSettings()); connection.open(); connection.close(); - } - catch (IOException ioe) - { + } catch (IOException ioe) { throw new MessagingException(K9.app.getString(R.string.error_unable_to_connect), ioe); } } @@ -514,37 +430,27 @@ public class ImapStore extends Store * Gets a connection if one is available for reuse, or creates a new one if not. * @return */ - private ImapConnection getConnection() throws MessagingException - { - synchronized (mConnections) - { + private ImapConnection getConnection() throws MessagingException { + synchronized (mConnections) { ImapConnection connection = null; - while ((connection = mConnections.poll()) != null) - { - try - { + while ((connection = mConnections.poll()) != null) { + try { connection.executeSimpleCommand("NOOP"); break; - } - catch (IOException ioe) - { + } catch (IOException ioe) { connection.close(); } } - if (connection == null) - { + if (connection == null) { connection = new ImapConnection(new StoreImapSettings()); } return connection; } } - private void releaseConnection(ImapConnection connection) - { - if (connection != null && connection.isOpen()) - { - synchronized (mConnections) - { + private void releaseConnection(ImapConnection connection) { + if (connection != null && connection.isOpen()) { + synchronized (mConnections) { mConnections.offer(connection); } } @@ -564,22 +470,17 @@ public class ImapStore extends Store * @return * The string encoded as quoted (IMAP) string. */ - private static String encodeString(String str) - { + private static String encodeString(String str) { return "\"" + str.replace("\\", "\\\\").replace("\"", "\\\"") + "\""; } - private String encodeFolderName(String name) - { - try - { + private String encodeFolderName(String name) { + try { ByteBuffer bb = mModifiedUtf7Charset.encode(name); byte[] b = new byte[bb.limit()]; bb.get(b); return new String(b, "US-ASCII"); - } - catch (UnsupportedEncodingException uee) - { + } catch (UnsupportedEncodingException uee) { /* * The only thing that can throw this is getBytes("US-ASCII") and if US-ASCII doesn't * exist we're totally screwed. @@ -588,20 +489,16 @@ public class ImapStore extends Store } } - private String decodeFolderName(String name) - { + private String decodeFolderName(String name) { /* * Convert the encoded name to US-ASCII, then pass it through the modified UTF-7 * decoder and return the Unicode String. */ - try - { + try { byte[] encoded = name.getBytes("US-ASCII"); CharBuffer cb = mModifiedUtf7Charset.decode(ByteBuffer.wrap(encoded)); return cb.toString(); - } - catch (UnsupportedEncodingException uee) - { + } catch (UnsupportedEncodingException uee) { /* * The only thing that can throw this is getBytes("US-ASCII") and if US-ASCII doesn't * exist we're totally screwed. @@ -611,30 +508,25 @@ public class ImapStore extends Store } @Override - public boolean isMoveCapable() - { + public boolean isMoveCapable() { return true; } @Override - public boolean isCopyCapable() - { + public boolean isCopyCapable() { return true; } @Override - public boolean isPushCapable() - { + public boolean isPushCapable() { return true; } @Override - public boolean isExpungeCapable() - { + public boolean isExpungeCapable() { return true; } - class ImapFolder extends Folder - { + class ImapFolder extends Folder { private String mName; protected volatile int mMessageCount = -1; protected volatile int uidNext = -1; @@ -645,43 +537,30 @@ public class ImapStore extends Store Map msgSeqUidMap = new ConcurrentHashMap(); - public ImapFolder(ImapStore nStore, String name) - { + public ImapFolder(ImapStore nStore, String name) { super(nStore.getAccount()); store = nStore; this.mName = name; } - public String getPrefixedName() throws MessagingException - { + public String getPrefixedName() throws MessagingException { String prefixedName = ""; - if (!K9.INBOX.equalsIgnoreCase(mName)) - { + if (!K9.INBOX.equalsIgnoreCase(mName)) { ImapConnection connection = null; - synchronized (this) - { - if (mConnection == null) - { + synchronized (this) { + if (mConnection == null) { connection = getConnection(); - } - else - { + } else { connection = mConnection; } } - try - { + try { connection.open(); - } - catch (IOException ioe) - { + } catch (IOException ioe) { throw new MessagingException("Unable to get IMAP prefix", ioe); - } - finally - { - if (mConnection == null) - { + } finally { + if (mConnection == null) { releaseConnection(connection); } } @@ -692,47 +571,37 @@ public class ImapStore extends Store return prefixedName; } - protected List executeSimpleCommand(String command) throws MessagingException, IOException - { + protected List executeSimpleCommand(String command) throws MessagingException, IOException { return handleUntaggedResponses(mConnection.executeSimpleCommand(command)); } - protected List executeSimpleCommand(String command, boolean sensitve, UntaggedHandler untaggedHandler) throws MessagingException, IOException - { + protected List executeSimpleCommand(String command, boolean sensitve, UntaggedHandler untaggedHandler) throws MessagingException, IOException { return handleUntaggedResponses(mConnection.executeSimpleCommand(command, sensitve, untaggedHandler)); } @Override - public void open(OpenMode mode) throws MessagingException - { + public void open(OpenMode mode) throws MessagingException { internalOpen(mode); - if (mMessageCount == -1) - { + if (mMessageCount == -1) { throw new MessagingException( "Did not find message count during open"); } } - public List internalOpen(OpenMode mode) throws MessagingException - { - if (isOpen() && mMode == mode) - { + public List internalOpen(OpenMode mode) throws MessagingException { + if (isOpen() && mMode == mode) { // Make sure the connection is valid. If it's not we'll close it down and continue // on to get a new one. - try - { + try { List responses = executeSimpleCommand("NOOP"); return responses; - } - catch (IOException ioe) - { + } catch (IOException ioe) { ioExceptionHandler(mConnection, ioe); } } releaseConnection(mConnection); - synchronized (this) - { + synchronized (this) { mConnection = getConnection(); } // * FLAGS (\Answered \Flagged \Deleted \Seen \Draft NonJunk @@ -744,8 +613,7 @@ public class ImapStore extends Store // * OK [UIDVALIDITY 1125022061] UIDs valid // * OK [UIDNEXT 57576] Predicted next UID // 2 OK [READ-WRITE] Select completed. - try - { + try { msgSeqUidMap.clear(); String command = String.format((mode == OpenMode.READ_WRITE ? "SELECT" : "EXAMINE") + " %s", encodeString(encodeFolderName(getPrefixedName()))); @@ -758,28 +626,20 @@ public class ImapStore extends Store */ mMode = mode; - for (ImapResponse response : responses) - { - if (response.mTag != null && response.size() >= 2) - { + for (ImapResponse response : responses) { + if (response.mTag != null && response.size() >= 2) { Object bracketedObj = response.get(1); - if (bracketedObj instanceof ImapList) - { + if (bracketedObj instanceof ImapList) { ImapList bracketed = (ImapList)bracketedObj; - if (bracketed.size() > 0) - { + if (bracketed.size() > 0) { Object keyObj = bracketed.get(0); - if (keyObj instanceof String) - { + if (keyObj instanceof String) { String key = (String)keyObj; - if ("READ-ONLY".equalsIgnoreCase(key)) - { + if ("READ-ONLY".equalsIgnoreCase(key)) { mMode = OpenMode.READ_ONLY; - } - else if ("READ-WRITE".equalsIgnoreCase(key)) - { + } else if ("READ-WRITE".equalsIgnoreCase(key)) { mMode = OpenMode.READ_WRITE; } } @@ -791,13 +651,9 @@ public class ImapStore extends Store mExists = true; return responses; - } - catch (IOException ioe) - { + } catch (IOException ioe) { throw ioExceptionHandler(mConnection, ioe); - } - catch (MessagingException me) - { + } catch (MessagingException me) { Log.e(K9.LOG_TAG, "Unable to open connection for " + getLogId(), me); throw me; } @@ -805,39 +661,32 @@ public class ImapStore extends Store } @Override - public boolean isOpen() - { + public boolean isOpen() { return mConnection != null; } @Override - public OpenMode getMode() - { + public OpenMode getMode() { return mMode; } @Override - public void close() - { - if (mMessageCount != -1) - { + public void close() { + if (mMessageCount != -1) { mMessageCount = -1; } - if (!isOpen()) - { + if (!isOpen()) { return; } - synchronized (this) - { + synchronized (this) { releaseConnection(mConnection); mConnection = null; } } @Override - public String getName() - { + public String getName() { return mName; } @@ -851,31 +700,23 @@ public class ImapStore extends Store * @return * {@code True}, if the folder exists. {@code False}, otherwise. */ - private boolean exists(String folderName) throws MessagingException - { - try - { + private boolean exists(String folderName) throws MessagingException { + try { // Since we don't care about RECENT, we'll use that for the check, because we're checking // a folder other than ourself, and don't want any untagged responses to cause a change // in our own fields mConnection.executeSimpleCommand(String.format("STATUS %s (RECENT)", folderName)); return true; - } - catch (IOException ioe) - { + } catch (IOException ioe) { throw ioExceptionHandler(mConnection, ioe); - } - catch (MessagingException me) - { + } catch (MessagingException me) { return false; } } @Override - public boolean exists() throws MessagingException - { - if (mExists) - { + public boolean exists() throws MessagingException { + if (mExists) { return true; } /* @@ -884,89 +725,62 @@ public class ImapStore extends Store * not calling checkOpen() since we don't care if the folder is open. */ ImapConnection connection = null; - synchronized (this) - { - if (mConnection == null) - { + synchronized (this) { + if (mConnection == null) { connection = getConnection(); - } - else - { + } else { connection = mConnection; } } - try - { + try { connection.executeSimpleCommand(String.format("STATUS %s (UIDVALIDITY)", encodeString(encodeFolderName(getPrefixedName())))); mExists = true; return true; - } - catch (MessagingException me) - { + } catch (MessagingException me) { return false; - } - catch (IOException ioe) - { + } catch (IOException ioe) { throw ioExceptionHandler(connection, ioe); - } - finally - { - if (mConnection == null) - { + } finally { + if (mConnection == null) { releaseConnection(connection); } } } @Override - public boolean create(FolderType type) throws MessagingException - { + public boolean create(FolderType type) throws MessagingException { /* * This method needs to operate in the unselected mode as well as the selected mode * so we must get the connection ourselves if it's not there. We are specifically * not calling checkOpen() since we don't care if the folder is open. */ ImapConnection connection = null; - synchronized (this) - { - if (mConnection == null) - { + synchronized (this) { + if (mConnection == null) { connection = getConnection(); - } - else - { + } else { connection = mConnection; } } - try - { + try { connection.executeSimpleCommand(String.format("CREATE %s", encodeString(encodeFolderName(getPrefixedName())))); return true; - } - catch (MessagingException me) - { + } catch (MessagingException me) { return false; - } - catch (IOException ioe) - { + } catch (IOException ioe) { throw ioExceptionHandler(mConnection, ioe); - } - finally - { - if (mConnection == null) - { + } finally { + if (mConnection == null) { releaseConnection(connection); } } } @Override - public void copyMessages(Message[] messages, Folder folder) throws MessagingException - { - if (!(folder instanceof ImapFolder)) - { + public void copyMessages(Message[] messages, Folder folder) throws MessagingException { + if (!(folder instanceof ImapFolder)) { throw new MessagingException("ImapFolder.copyMessages passed non-ImapFolder"); } @@ -976,16 +790,13 @@ public class ImapStore extends Store ImapFolder iFolder = (ImapFolder)folder; checkOpen(); String[] uids = new String[messages.length]; - for (int i = 0, count = messages.length; i < count; i++) - { + for (int i = 0, count = messages.length; i < count; i++) { uids[i] = messages[i].getUid(); } - try - { + try { String remoteDestName = encodeString(encodeFolderName(iFolder.getPrefixedName())); - if (!exists(remoteDestName)) - { + if (!exists(remoteDestName)) { /* * If the remote trash folder doesn't exist we try to create it. */ @@ -994,28 +805,22 @@ public class ImapStore extends Store iFolder.create(FolderType.HOLDS_MESSAGES); } - if (exists(remoteDestName)) - { + if (exists(remoteDestName)) { executeSimpleCommand(String.format("UID COPY %s %s", Utility.combine(uids, ','), remoteDestName)); - } - else - { + } else { throw new MessagingException("IMAPMessage.copyMessages: remote destination folder " + folder.getName() + " does not exist and could not be created for " + getLogId() , true); } - } - catch (IOException ioe) - { + } catch (IOException ioe) { throw ioExceptionHandler(mConnection, ioe); } } @Override - public void moveMessages(Message[] messages, Folder folder) throws MessagingException - { + public void moveMessages(Message[] messages, Folder folder) throws MessagingException { if (messages.length == 0) return; copyMessages(messages, folder); @@ -1023,22 +828,17 @@ public class ImapStore extends Store } @Override - public void delete(Message[] messages, String trashFolderName) throws MessagingException - { + public void delete(Message[] messages, String trashFolderName) throws MessagingException { if (messages.length == 0) return; - if (trashFolderName == null || getName().equalsIgnoreCase(trashFolderName)) - { + if (trashFolderName == null || getName().equalsIgnoreCase(trashFolderName)) { setFlags(messages, new Flag[] { Flag.DELETED }, true); - } - else - { + } else { ImapFolder remoteTrashFolder = (ImapFolder)getStore().getFolder(trashFolderName); String remoteTrashName = encodeString(encodeFolderName(remoteTrashFolder.getPrefixedName())); - if (!exists(remoteTrashName)) - { + if (!exists(remoteTrashName)) { /* * If the remote trash folder doesn't exist we try to create it. */ @@ -1047,15 +847,12 @@ public class ImapStore extends Store remoteTrashFolder.create(FolderType.HOLDS_MESSAGES); } - if (exists(remoteTrashName)) - { + if (exists(remoteTrashName)) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "IMAPMessage.delete: copying remote " + messages.length + " messages to '" + trashFolderName + "' for " + getLogId()); moveMessages(messages, remoteTrashFolder); - } - else - { + } else { throw new MessagingException("IMAPMessage.delete: remote Trash folder " + trashFolderName + " does not exist and could not be created for " + getLogId() , true); } @@ -1064,32 +861,25 @@ public class ImapStore extends Store @Override - public int getMessageCount() - { + public int getMessageCount() { return mMessageCount; } - private int getRemoteMessageCount(String criteria) throws MessagingException - { + private int getRemoteMessageCount(String criteria) throws MessagingException { checkOpen(); - try - { + try { int count = 0; int start = 1; - List responses = executeSimpleCommand(String.format("SEARCH %d:* "+criteria, start)); - for (ImapResponse response : responses) - { - if (ImapResponseParser.equalsIgnoreCase(response.get(0), "SEARCH")) - { + List responses = executeSimpleCommand(String.format("SEARCH %d:* " + criteria, start)); + for (ImapResponse response : responses) { + if (ImapResponseParser.equalsIgnoreCase(response.get(0), "SEARCH")) { count += response.size() - 1; } } return count; - } - catch (IOException ioe) - { + } catch (IOException ioe) { throw ioExceptionHandler(mConnection, ioe); } @@ -1097,36 +887,27 @@ public class ImapStore extends Store } @Override - public int getUnreadMessageCount() throws MessagingException - { + public int getUnreadMessageCount() throws MessagingException { return getRemoteMessageCount("UNSEEN NOT DELETED"); } @Override - public int getFlaggedMessageCount() throws MessagingException - { + public int getFlaggedMessageCount() throws MessagingException { return getRemoteMessageCount("FLAGGED NOT DELETED"); } - protected int getHighestUid() - { - try - { - ImapSearcher searcher = new ImapSearcher() - { - public List search() throws IOException, MessagingException - { + protected int getHighestUid() { + try { + ImapSearcher searcher = new ImapSearcher() { + public List search() throws IOException, MessagingException { return executeSimpleCommand(String.format("UID SEARCH *:* ")); } }; Message[] messages = search(searcher, null); - if (messages.length > 0) - { + if (messages.length > 0) { return Integer.parseInt(messages[0].getUid()); } - } - catch (Exception e) - { + } catch (Exception e) { Log.e(K9.LOG_TAG, "Unable to find highest UID in folder " + getName(), e); } return -1; @@ -1134,49 +915,40 @@ public class ImapStore extends Store } @Override - public void delete(boolean recurse) throws MessagingException - { + public void delete(boolean recurse) throws MessagingException { throw new Error("ImapStore.delete() not yet implemented"); } @Override - public Message getMessage(String uid) throws MessagingException - { + public Message getMessage(String uid) throws MessagingException { return new ImapMessage(uid, this); } @Override public Message[] getMessages(int start, int end, Date earliestDate, MessageRetrievalListener listener) - throws MessagingException - { + throws MessagingException { return getMessages(start, end, earliestDate, false, listener); } protected Message[] getMessages(final int start, final int end, Date earliestDate, final boolean includeDeleted, final MessageRetrievalListener listener) - throws MessagingException - { - if (start < 1 || end < 1 || end < start) - { + throws MessagingException { + if (start < 1 || end < 1 || end < start) { throw new MessagingException( String.format("Invalid message set %d %d", start, end)); } final StringBuilder dateSearchString = new StringBuilder(); - if (earliestDate != null) - { + if (earliestDate != null) { dateSearchString.append(" SINCE "); - synchronized (RFC3501_DATE) - { + synchronized (RFC3501_DATE) { dateSearchString.append(RFC3501_DATE.format(earliestDate)); } } - ImapSearcher searcher = new ImapSearcher() - { - public List search() throws IOException, MessagingException - { + ImapSearcher searcher = new ImapSearcher() { + public List search() throws IOException, MessagingException { return executeSimpleCommand(String.format("UID SEARCH %d:%d%s" + (includeDeleted ? "" : " NOT DELETED"), start, end, dateSearchString)); } }; @@ -1184,12 +956,9 @@ public class ImapStore extends Store } protected Message[] getMessages(final List mesgSeqs, final boolean includeDeleted, final MessageRetrievalListener listener) - throws MessagingException - { - ImapSearcher searcher = new ImapSearcher() - { - public List search() throws IOException, MessagingException - { + throws MessagingException { + ImapSearcher searcher = new ImapSearcher() { + public List search() throws IOException, MessagingException { return executeSimpleCommand(String.format("UID SEARCH %s" + (includeDeleted ? "" : " NOT DELETED"), Utility.combine(mesgSeqs.toArray(), ','))); } }; @@ -1197,35 +966,26 @@ public class ImapStore extends Store } protected Message[] getMessagesFromUids(final List mesgUids, final boolean includeDeleted, final MessageRetrievalListener listener) - throws MessagingException - { - ImapSearcher searcher = new ImapSearcher() - { - public List search() throws IOException, MessagingException - { + throws MessagingException { + ImapSearcher searcher = new ImapSearcher() { + public List search() throws IOException, MessagingException { return executeSimpleCommand(String.format("UID SEARCH UID %s" + (includeDeleted ? "" : " NOT DELETED"), Utility.combine(mesgUids.toArray(), ','))); } }; return search(searcher, listener); } - private Message[] search(ImapSearcher searcher, MessageRetrievalListener listener) throws MessagingException - { + private Message[] search(ImapSearcher searcher, MessageRetrievalListener listener) throws MessagingException { checkOpen(); ArrayList messages = new ArrayList(); - try - { + try { ArrayList uids = new ArrayList(); List responses = searcher.search(); // - for (ImapResponse response : responses) - { - if (response.mTag == null) - { - if (ImapResponseParser.equalsIgnoreCase(response.get(0), "SEARCH")) - { - for (int i = 1, count = response.size(); i < count; i++) - { + for (ImapResponse response : responses) { + if (response.mTag == null) { + if (ImapResponseParser.equalsIgnoreCase(response.get(0), "SEARCH")) { + for (int i = 1, count = response.size(); i < count; i++) { uids.add(Integer.parseInt(response.getString(i))); } } @@ -1234,22 +994,17 @@ public class ImapStore extends Store // Sort the uids in numerically ascending order Collections.sort(uids); - for (int i = 0, count = uids.size(); i < count; i++) - { - if (listener != null) - { + for (int i = 0, count = uids.size(); i < count; i++) { + if (listener != null) { listener.messageStarted("" + uids.get(i), i, count); } ImapMessage message = new ImapMessage("" + uids.get(i), this); messages.add(message); - if (listener != null) - { + if (listener != null) { listener.messageFinished(message, i, count); } } - } - catch (IOException ioe) - { + } catch (IOException ioe) { throw ioExceptionHandler(mConnection, ioe); } return messages.toArray(EMPTY_MESSAGE_ARRAY); @@ -1257,51 +1012,39 @@ public class ImapStore extends Store @Override - public Message[] getMessages(MessageRetrievalListener listener) throws MessagingException - { + public Message[] getMessages(MessageRetrievalListener listener) throws MessagingException { return getMessages(null, listener); } @Override public Message[] getMessages(String[] uids, MessageRetrievalListener listener) - throws MessagingException - { + throws MessagingException { checkOpen(); ArrayList messages = new ArrayList(); - try - { - if (uids == null) - { + try { + if (uids == null) { List responses = executeSimpleCommand("UID SEARCH 1:* NOT DELETED"); ArrayList tempUids = new ArrayList(); - for (ImapResponse response : responses) - { - if (ImapResponseParser.equalsIgnoreCase(response.get(0), "SEARCH")) - { - for (int i = 1, count = response.size(); i < count; i++) - { + for (ImapResponse response : responses) { + if (ImapResponseParser.equalsIgnoreCase(response.get(0), "SEARCH")) { + for (int i = 1, count = response.size(); i < count; i++) { tempUids.add(response.getString(i)); } } } uids = tempUids.toArray(EMPTY_STRING_ARRAY); } - for (int i = 0, count = uids.length; i < count; i++) - { - if (listener != null) - { + for (int i = 0, count = uids.length; i < count; i++) { + if (listener != null) { listener.messageStarted(uids[i], i, count); } ImapMessage message = new ImapMessage(uids[i], this); messages.add(message); - if (listener != null) - { + if (listener != null) { listener.messageFinished(message, i, count); } } - } - catch (IOException ioe) - { + } catch (IOException ioe) { throw ioExceptionHandler(mConnection, ioe); } return messages.toArray(EMPTY_MESSAGE_ARRAY); @@ -1309,17 +1052,14 @@ public class ImapStore extends Store @Override public void fetch(Message[] messages, FetchProfile fp, MessageRetrievalListener listener) - throws MessagingException - { - if (messages == null || messages.length == 0) - { + throws MessagingException { + if (messages == null || messages.length == 0) { return; } checkOpen(); List uids = new ArrayList(messages.length); HashMap messageMap = new HashMap(); - for (int i = 0, count = messages.length; i < count; i++) - { + for (int i = 0, count = messages.length; i < count; i++) { String uid = messages[i].getUid(); uids.add(uid); @@ -1334,38 +1074,31 @@ public class ImapStore extends Store */ LinkedHashSet fetchFields = new LinkedHashSet(); fetchFields.add("UID"); - if (fp.contains(FetchProfile.Item.FLAGS)) - { + if (fp.contains(FetchProfile.Item.FLAGS)) { fetchFields.add("FLAGS"); } - if (fp.contains(FetchProfile.Item.ENVELOPE)) - { + if (fp.contains(FetchProfile.Item.ENVELOPE)) { fetchFields.add("INTERNALDATE"); fetchFields.add("RFC822.SIZE"); fetchFields.add("BODY.PEEK[HEADER.FIELDS (date subject from content-type to cc reply-to " + K9.IDENTITY_HEADER + ")]"); } - if (fp.contains(FetchProfile.Item.STRUCTURE)) - { + if (fp.contains(FetchProfile.Item.STRUCTURE)) { fetchFields.add("BODYSTRUCTURE"); } - if (fp.contains(FetchProfile.Item.BODY_SANE)) - { + if (fp.contains(FetchProfile.Item.BODY_SANE)) { fetchFields.add(String.format("BODY.PEEK[]<0.%d>", mAccount.getMaximumAutoDownloadMessageSize())); } - if (fp.contains(FetchProfile.Item.BODY)) - { + if (fp.contains(FetchProfile.Item.BODY)) { fetchFields.add("BODY.PEEK[]"); } - for (int windowStart=0; windowStart <= messages.length; windowStart += (FETCH_WINDOW_SIZE)) - { - List uidWindow = uids.subList(windowStart, Math.min((windowStart+FETCH_WINDOW_SIZE),messages.length)); + for (int windowStart = 0; windowStart <= messages.length; windowStart += (FETCH_WINDOW_SIZE)) { + List uidWindow = uids.subList(windowStart, Math.min((windowStart + FETCH_WINDOW_SIZE), messages.length)); - try - { + try { mConnection.sendCommand(String.format("UID FETCH %s (%s)", Utility.combine(uidWindow.toArray(new String[uidWindow.size()]), ','), Utility.combine(fetchFields.toArray(new String[fetchFields.size()]), ' ') @@ -1374,47 +1107,37 @@ public class ImapStore extends Store int messageNumber = 0; ImapResponseParser.IImapResponseCallback callback = null; - if (fp.contains(FetchProfile.Item.BODY) || fp.contains(FetchProfile.Item.BODY_SANE)) - { + if (fp.contains(FetchProfile.Item.BODY) || fp.contains(FetchProfile.Item.BODY_SANE)) { callback = new FetchBodyCallback(messageMap); } - do - { + do { response = mConnection.readResponse(callback); - if (response.mTag == null && ImapResponseParser.equalsIgnoreCase(response.get(1), "FETCH")) - { + if (response.mTag == null && ImapResponseParser.equalsIgnoreCase(response.get(1), "FETCH")) { ImapList fetchList = (ImapList)response.getKeyedValue("FETCH"); String uid = fetchList.getKeyedString("UID"); int msgSeq = response.getNumber(0); - if (uid != null) - { - try - { + if (uid != null) { + try { msgSeqUidMap.put(msgSeq, uid); - if (K9.DEBUG) - { + if (K9.DEBUG) { Log.v(K9.LOG_TAG, "Stored uid '" + uid + "' for msgSeq " + msgSeq + " into map " /*+ msgSeqUidMap.toString() */); } - } - catch (Exception e) - { + } catch (Exception e) { Log.e(K9.LOG_TAG, "Unable to store uid '" + uid + "' for msgSeq " + msgSeq); } } Message message = messageMap.get(uid); - if (message == null) - { + if (message == null) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "Do not have message in messageMap for UID " + uid + " for " + getLogId()); handleUntaggedResponse(response); continue; } - if (listener != null) - { + if (listener != null) { listener.messageStarted(uid, messageNumber++, messageMap.size()); } @@ -1422,42 +1145,30 @@ public class ImapStore extends Store Object literal = handleFetchResponse(imapMessage, fetchList); - if (literal != null) - { - if (literal instanceof String) - { + if (literal != null) { + if (literal instanceof String) { String bodyString = (String)literal; InputStream bodyStream = new ByteArrayInputStream(bodyString.getBytes()); imapMessage.parse(bodyStream); - } - else if (literal instanceof Integer) - { + } else if (literal instanceof Integer) { // All the work was done in FetchBodyCallback.foundLiteral() - } - else - { + } else { // This shouldn't happen throw new MessagingException("Got FETCH response with bogus parameters"); } } - if (listener != null) - { + if (listener != null) { listener.messageFinished(message, messageNumber, messageMap.size()); } - } - else - { + } else { handleUntaggedResponse(response); } while (response.more()); - } - while (response.mTag == null); - } - catch (IOException ioe) - { + } while (response.mTag == null); + } catch (IOException ioe) { throw ioExceptionHandler(mConnection, ioe); } } @@ -1466,29 +1177,23 @@ public class ImapStore extends Store @Override public void fetchPart(Message message, Part part, MessageRetrievalListener listener) - throws MessagingException - { + throws MessagingException { checkOpen(); String[] parts = part.getHeader(MimeHeader.HEADER_ANDROID_ATTACHMENT_STORE_DATA); - if (parts == null) - { + if (parts == null) { return; } String fetch; String partId = parts[0]; - if ("TEXT".equalsIgnoreCase(partId)) - { + if ("TEXT".equalsIgnoreCase(partId)) { fetch = String.format("BODY.PEEK[TEXT]<0.%d>", mAccount.getMaximumAutoDownloadMessageSize()); - } - else - { + } else { fetch = String.format("BODY.PEEK[%s]", partId); } - try - { + try { mConnection.sendCommand( String.format("UID FETCH %s (UID %s)", message.getUid(), fetch), false); @@ -1498,26 +1203,22 @@ public class ImapStore extends Store ImapResponseParser.IImapResponseCallback callback = new FetchPartCallback(part); - do - { + do { response = mConnection.readResponse(callback); if ((response.mTag == null) && - (ImapResponseParser.equalsIgnoreCase(response.get(1), "FETCH"))) - { + (ImapResponseParser.equalsIgnoreCase(response.get(1), "FETCH"))) { ImapList fetchList = (ImapList)response.getKeyedValue("FETCH"); String uid = fetchList.getKeyedString("UID"); - if (!message.getUid().equals(uid)) - { + if (!message.getUid().equals(uid)) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "Did not ask for UID " + uid + " for " + getLogId()); handleUntaggedResponse(response); continue; } - if (listener != null) - { + if (listener != null) { listener.messageStarted(uid, messageNumber++, 1); } @@ -1525,105 +1226,75 @@ public class ImapStore extends Store Object literal = handleFetchResponse(imapMessage, fetchList); - if (literal != null) - { - if (literal instanceof Body) - { + if (literal != null) { + if (literal instanceof Body) { // Most of the work was done in FetchAttchmentCallback.foundLiteral() part.setBody((Body)literal); - } - else if (literal instanceof String) - { + } else if (literal instanceof String) { String bodyString = (String)literal; InputStream bodyStream = new ByteArrayInputStream(bodyString.getBytes()); String contentTransferEncoding = part.getHeader( MimeHeader.HEADER_CONTENT_TRANSFER_ENCODING)[0]; part.setBody(MimeUtility.decodeBody(bodyStream, contentTransferEncoding)); - } - else - { + } else { // This shouldn't happen throw new MessagingException("Got FETCH response with bogus parameters"); } } - if (listener != null) - { + if (listener != null) { listener.messageFinished(message, messageNumber, 1); } - } - else - { + } else { handleUntaggedResponse(response); } while (response.more()); - } - while (response.mTag == null); - } - catch (IOException ioe) - { + } while (response.mTag == null); + } catch (IOException ioe) { throw ioExceptionHandler(mConnection, ioe); } } // Returns value of body field - private Object handleFetchResponse(ImapMessage message, ImapList fetchList) throws MessagingException - { + private Object handleFetchResponse(ImapMessage message, ImapList fetchList) throws MessagingException { Object result = null; - if (fetchList.containsKey("FLAGS")) - { + if (fetchList.containsKey("FLAGS")) { ImapList flags = fetchList.getKeyedList("FLAGS"); - if (flags != null) - { - for (int i = 0, count = flags.size(); i < count; i++) - { + if (flags != null) { + for (int i = 0, count = flags.size(); i < count; i++) { String flag = flags.getString(i); - if (flag.equalsIgnoreCase("\\Deleted")) - { + if (flag.equalsIgnoreCase("\\Deleted")) { message.setFlagInternal(Flag.DELETED, true); - } - else if (flag.equalsIgnoreCase("\\Answered")) - { + } else if (flag.equalsIgnoreCase("\\Answered")) { message.setFlagInternal(Flag.ANSWERED, true); - } - else if (flag.equalsIgnoreCase("\\Seen")) - { + } else if (flag.equalsIgnoreCase("\\Seen")) { message.setFlagInternal(Flag.SEEN, true); - } - else if (flag.equalsIgnoreCase("\\Flagged")) - { + } else if (flag.equalsIgnoreCase("\\Flagged")) { message.setFlagInternal(Flag.FLAGGED, true); } } } } - if (fetchList.containsKey("INTERNALDATE")) - { + if (fetchList.containsKey("INTERNALDATE")) { Date internalDate = fetchList.getKeyedDate("INTERNALDATE"); message.setInternalDate(internalDate); } - if (fetchList.containsKey("RFC822.SIZE")) - { + if (fetchList.containsKey("RFC822.SIZE")) { int size = fetchList.getKeyedNumber("RFC822.SIZE"); message.setSize(size); } - if (fetchList.containsKey("BODYSTRUCTURE")) - { + if (fetchList.containsKey("BODYSTRUCTURE")) { ImapList bs = fetchList.getKeyedList("BODYSTRUCTURE"); - if (bs != null) - { - try - { + if (bs != null) { + try { parseBodyStructure(bs, message, "TEXT"); - } - catch (MessagingException e) - { + } catch (MessagingException e) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "Error handling message for " + getLogId(), e); message.setBody(null); @@ -1631,17 +1302,14 @@ public class ImapStore extends Store } } - if (fetchList.containsKey("BODY")) - { + if (fetchList.containsKey("BODY")) { int index = fetchList.getKeyIndex("BODY") + 2; result = fetchList.getObject(index); // Check if there's an origin octet - if (result instanceof String) - { + if (result instanceof String) { String originOctet = (String)result; - if (originOctet.startsWith("<")) - { + if (originOctet.startsWith("<")) { result = fetchList.getObject(index + 1); } } @@ -1651,8 +1319,7 @@ public class ImapStore extends Store } @Override - public Flag[] getPermanentFlags() - { + public Flag[] getPermanentFlags() { return PERMANENT_FLAGS; } @@ -1660,32 +1327,24 @@ public class ImapStore extends Store * Handle any untagged responses that the caller doesn't care to handle themselves. * @param responses */ - protected List handleUntaggedResponses(List responses) - { - for (ImapResponse response : responses) - { + protected List handleUntaggedResponses(List responses) { + for (ImapResponse response : responses) { handleUntaggedResponse(response); } return responses; } - protected void handlePossibleUidNext(ImapResponse response) - { - if (ImapResponseParser.equalsIgnoreCase(response.get(0), "OK") && response.size() > 1) - { + protected void handlePossibleUidNext(ImapResponse response) { + if (ImapResponseParser.equalsIgnoreCase(response.get(0), "OK") && response.size() > 1) { Object bracketedObj = response.get(1); - if (bracketedObj instanceof ImapList) - { + if (bracketedObj instanceof ImapList) { ImapList bracketed = (ImapList)bracketedObj; - if (bracketed.size() > 1) - { + if (bracketed.size() > 1) { Object keyObj = bracketed.get(0); - if (keyObj instanceof String) - { + if (keyObj instanceof String) { String key = (String)keyObj; - if ("UIDNEXT".equalsIgnoreCase(key)) - { + if ("UIDNEXT".equalsIgnoreCase(key)) { uidNext = bracketed.getNumber(1); if (K9.DEBUG) Log.d(K9.LOG_TAG, "Got UidNext = " + uidNext + " for " + getLogId()); @@ -1702,20 +1361,16 @@ public class ImapStore extends Store * Handle an untagged response that the caller doesn't care to handle themselves. * @param response */ - protected void handleUntaggedResponse(ImapResponse response) - { - if (response.mTag == null && response.size() > 1) - { - if (ImapResponseParser.equalsIgnoreCase(response.get(1), "EXISTS")) - { + protected void handleUntaggedResponse(ImapResponse response) { + if (response.mTag == null && response.size() > 1) { + if (ImapResponseParser.equalsIgnoreCase(response.get(1), "EXISTS")) { mMessageCount = response.getNumber(0); if (K9.DEBUG) Log.d(K9.LOG_TAG, "Got untagged EXISTS with value " + mMessageCount + " for " + getLogId()); } handlePossibleUidNext(response); - if (ImapResponseParser.equalsIgnoreCase(response.get(1), "EXPUNGE") && mMessageCount > 0) - { + if (ImapResponseParser.equalsIgnoreCase(response.get(1), "EXPUNGE") && mMessageCount > 0) { mMessageCount--; if (K9.DEBUG) Log.d(K9.LOG_TAG, "Got untagged EXPUNGE with mMessageCount " + mMessageCount + " for " + getLogId()); @@ -1753,35 +1408,26 @@ public class ImapStore extends Store } private void parseBodyStructure(ImapList bs, Part part, String id) - throws MessagingException - { - if (bs.get(0) instanceof ImapList) - { + throws MessagingException { + if (bs.get(0) instanceof ImapList) { /* * This is a multipart/* */ MimeMultipart mp = new MimeMultipart(); - for (int i = 0, count = bs.size(); i < count; i++) - { - if (bs.get(i) instanceof ImapList) - { + for (int i = 0, count = bs.size(); i < count; i++) { + if (bs.get(i) instanceof ImapList) { /* * For each part in the message we're going to add a new BodyPart and parse * into it. */ ImapBodyPart bp = new ImapBodyPart(); - if (id.equalsIgnoreCase("TEXT")) - { + if (id.equalsIgnoreCase("TEXT")) { parseBodyStructure(bs.getList(i), bp, Integer.toString(i + 1)); - } - else - { + } else { parseBodyStructure(bs.getList(i), bp, id + "." + (i + 1)); } mp.addBodyPart(bp); - } - else - { + } else { /* * We've got to the end of the children of the part, so now we can find out * what type it is and bail out. @@ -1792,9 +1438,7 @@ public class ImapStore extends Store } } part.setBody(mp); - } - else - { + } else { /* * This is a body. We need to add as much information as we can find out about * it to the Part. @@ -1816,15 +1460,13 @@ public class ImapStore extends Store String mimeType = (type + "/" + subType).toLowerCase(); ImapList bodyParams = null; - if (bs.get(2) instanceof ImapList) - { + if (bs.get(2) instanceof ImapList) { bodyParams = bs.getList(2); } String encoding = bs.getString(5); int size = bs.getNumber(6); - if (MimeUtility.mimeTypeMatches(mimeType, "message/rfc822")) - { + if (MimeUtility.mimeTypeMatches(mimeType, "message/rfc822")) { // A body type of type MESSAGE and subtype RFC822 // contains, immediately after the basic fields, the // envelope structure, body structure, and size in @@ -1841,14 +1483,12 @@ public class ImapStore extends Store */ String contentType = String.format("%s", mimeType); - if (bodyParams != null) - { + if (bodyParams != null) { /* * If there are body params we might be able to get some more information out * of them. */ - for (int i = 0, count = bodyParams.size(); i < count; i += 2) - { + for (int i = 0, count = bodyParams.size(); i < count; i += 2) { contentType += String.format(";\n %s=\"%s\"", bodyParams.getString(i), bodyParams.getString(i + 1)); @@ -1861,36 +1501,29 @@ public class ImapStore extends Store ImapList bodyDisposition = null; if (("text".equalsIgnoreCase(type)) && (bs.size() > 8) - && (bs.get(9) instanceof ImapList)) - { + && (bs.get(9) instanceof ImapList)) { bodyDisposition = bs.getList(9); - } - else if (!("text".equalsIgnoreCase(type)) - && (bs.size() > 7) - && (bs.get(8) instanceof ImapList)) - { + } else if (!("text".equalsIgnoreCase(type)) + && (bs.size() > 7) + && (bs.get(8) instanceof ImapList)) { bodyDisposition = bs.getList(8); } String contentDisposition = ""; - if (bodyDisposition != null && bodyDisposition.size() > 0) - { - if (!"NIL".equalsIgnoreCase(bodyDisposition.getString(0))) - { + if (bodyDisposition != null && bodyDisposition.size() > 0) { + if (!"NIL".equalsIgnoreCase(bodyDisposition.getString(0))) { contentDisposition = bodyDisposition.getString(0).toLowerCase(); } if ((bodyDisposition.size() > 1) - && (bodyDisposition.get(1) instanceof ImapList)) - { + && (bodyDisposition.get(1) instanceof ImapList)) { ImapList bodyDispositionParams = bodyDisposition.getList(1); /* * If there is body disposition information we can pull some more information * about the attachment out. */ - for (int i = 0, count = bodyDispositionParams.size(); i < count; i += 2) - { + for (int i = 0, count = bodyDispositionParams.size(); i < count; i += 2) { contentDisposition += String.format(";\n %s=\"%s\"", bodyDispositionParams.getString(i).toLowerCase(), bodyDispositionParams.getString(i + 1)); @@ -1898,8 +1531,7 @@ public class ImapStore extends Store } } - if (MimeUtility.getHeaderParameter(contentDisposition, "size") == null) - { + if (MimeUtility.getHeaderParameter(contentDisposition, "size") == null) { contentDisposition += String.format(";\n size=%d", size); } @@ -1916,16 +1548,11 @@ public class ImapStore extends Store */ part.setHeader(MimeHeader.HEADER_CONTENT_TRANSFER_ENCODING, encoding); - if (part instanceof ImapMessage) - { + if (part instanceof ImapMessage) { ((ImapMessage) part).setSize(size); - } - else if (part instanceof ImapBodyPart) - { + } else if (part instanceof ImapBodyPart) { ((ImapBodyPart) part).setSize(size); - } - else - { + } else { throw new MessagingException("Unknown part type " + part.toString()); } part.setHeader(MimeHeader.HEADER_ANDROID_ATTACHMENT_STORE_DATA, id); @@ -1939,13 +1566,10 @@ public class ImapStore extends Store * new server UID. */ @Override - public void appendMessages(Message[] messages) throws MessagingException - { + public void appendMessages(Message[] messages) throws MessagingException { checkOpen(); - try - { - for (Message message : messages) - { + try { + for (Message message : messages) { CountingOutputStream out = new CountingOutputStream(); EOLConvertingOutputStream eolOut = new EOLConvertingOutputStream(out); message.writeTo(eolOut); @@ -1957,12 +1581,10 @@ public class ImapStore extends Store combineFlags(message.getFlags()), out.getCount()), false); ImapResponse response; - do - { + do { response = mConnection.readResponse(); handleUntaggedResponse(response); - if (response.mCommandContinuationRequested) - { + if (response.mCommandContinuationRequested) { eolOut = new EOLConvertingOutputStream(mConnection.mOut); message.writeTo(eolOut); eolOut.write('\r'); @@ -1970,40 +1592,33 @@ public class ImapStore extends Store eolOut.flush(); } while (response.more()); - } - while (response.mTag == null); + } while (response.mTag == null); String newUid = getUidFromMessageId(message); if (K9.DEBUG) Log.d(K9.LOG_TAG, "Got UID " + newUid + " for message for " + getLogId()); - if (newUid != null) - { + if (newUid != null) { message.setUid(newUid); } } - } - catch (IOException ioe) - { + } catch (IOException ioe) { throw ioExceptionHandler(mConnection, ioe); } } @Override - public String getUidFromMessageId(Message message) throws MessagingException - { - try - { + public String getUidFromMessageId(Message message) throws MessagingException { + try { /* * Try to find the UID of the message we just appended using the * Message-ID header. */ String[] messageIdHeader = message.getHeader("Message-ID"); - if (messageIdHeader == null || messageIdHeader.length == 0) - { + if (messageIdHeader == null || messageIdHeader.length == 0) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "Did not get a message-id in order to search for UID for " + getLogId()); return null; @@ -2015,56 +1630,39 @@ public class ImapStore extends Store List responses = executeSimpleCommand( String.format("UID SEARCH HEADER MESSAGE-ID %s", messageId)); - for (ImapResponse response1 : responses) - { + for (ImapResponse response1 : responses) { if (response1.mTag == null && ImapResponseParser.equalsIgnoreCase(response1.get(0), "SEARCH") - && response1.size() > 1) - { + && response1.size() > 1) { return response1.getString(1); } } return null; - } - catch (IOException ioe) - { + } catch (IOException ioe) { throw new MessagingException("Could not find UID for message based on Message-ID", ioe); } } @Override - public void expunge() throws MessagingException - { + public void expunge() throws MessagingException { checkOpen(); - try - { + try { executeSimpleCommand("EXPUNGE"); - } - catch (IOException ioe) - { + } catch (IOException ioe) { throw ioExceptionHandler(mConnection, ioe); } } - private String combineFlags(Flag[] flags) - { + private String combineFlags(Flag[] flags) { ArrayList flagNames = new ArrayList(); - for (Flag flag : flags) - { - if (flag == Flag.SEEN) - { + for (Flag flag : flags) { + if (flag == Flag.SEEN) { flagNames.add("\\Seen"); - } - else if (flag == Flag.DELETED) - { + } else if (flag == Flag.DELETED) { flagNames.add("\\Deleted"); - } - else if (flag == Flag.ANSWERED) - { + } else if (flag == Flag.ANSWERED) { flagNames.add("\\Answered"); - } - else if (flag == Flag.FLAGGED) - { + } else if (flag == Flag.FLAGGED) { flagNames.add("\\Flagged"); } @@ -2075,43 +1673,32 @@ public class ImapStore extends Store @Override public void setFlags(Flag[] flags, boolean value) - throws MessagingException - { + throws MessagingException { checkOpen(); - try - { + try { executeSimpleCommand(String.format("UID STORE 1:* %sFLAGS.SILENT (%s)", value ? "+" : "-", combineFlags(flags))); - } - catch (IOException ioe) - { + } catch (IOException ioe) { throw ioExceptionHandler(mConnection, ioe); } } @Override - public String getNewPushState(String oldPushStateS, Message message) - { - try - { + public String getNewPushState(String oldPushStateS, Message message) { + try { String messageUidS = message.getUid(); int messageUid = Integer.parseInt(messageUidS); ImapPushState oldPushState = ImapPushState.parse(oldPushStateS); - if (messageUid >= oldPushState.uidNext) - { + if (messageUid >= oldPushState.uidNext) { int uidNext = messageUid + 1; ImapPushState newPushState = new ImapPushState(uidNext); return newPushState.toString(); - } - else - { + } else { return null; } - } - catch (Exception e) - { + } catch (Exception e) { Log.e(K9.LOG_TAG, "Exception while updated push state for " + getLogId(), e); return null; } @@ -2120,60 +1707,43 @@ public class ImapStore extends Store @Override public void setFlags(Message[] messages, Flag[] flags, boolean value) - throws MessagingException - { + throws MessagingException { checkOpen(); String[] uids = new String[messages.length]; - for (int i = 0, count = messages.length; i < count; i++) - { + for (int i = 0, count = messages.length; i < count; i++) { uids[i] = messages[i].getUid(); } ArrayList flagNames = new ArrayList(); - for (Flag flag : flags) - { - if (flag == Flag.SEEN) - { + for (Flag flag : flags) { + if (flag == Flag.SEEN) { flagNames.add("\\Seen"); - } - else if (flag == Flag.DELETED) - { + } else if (flag == Flag.DELETED) { flagNames.add("\\Deleted"); - } - else if (flag == Flag.ANSWERED) - { + } else if (flag == Flag.ANSWERED) { flagNames.add("\\Answered"); - } - else if (flag == Flag.FLAGGED) - { + } else if (flag == Flag.FLAGGED) { flagNames.add("\\Flagged"); } } - try - { + try { executeSimpleCommand(String.format("UID STORE %s %sFLAGS.SILENT (%s)", Utility.combine(uids, ','), value ? "+" : "-", Utility.combine(flagNames.toArray(new String[flagNames.size()]), ' '))); - } - catch (IOException ioe) - { + } catch (IOException ioe) { throw ioExceptionHandler(mConnection, ioe); } } - private void checkOpen() throws MessagingException - { - if (!isOpen()) - { + private void checkOpen() throws MessagingException { + if (!isOpen()) { throw new MessagingException("Folder " + getPrefixedName() + " is not open."); } } - private MessagingException ioExceptionHandler(ImapConnection connection, IOException ioe) - { + private MessagingException ioExceptionHandler(ImapConnection connection, IOException ioe) { Log.e(K9.LOG_TAG, "IOException for " + getLogId(), ioe); - if (connection != null) - { + if (connection != null) { connection.close(); } close(); @@ -2181,31 +1751,25 @@ public class ImapStore extends Store } @Override - public boolean equals(Object o) - { - if (o instanceof ImapFolder) - { + public boolean equals(Object o) { + if (o instanceof ImapFolder) { return ((ImapFolder)o).getName().equalsIgnoreCase(getName()); } return super.equals(o); } @Override - public int hashCode() - { + public int hashCode() { return getName().hashCode(); } - protected ImapStore getStore() - { + protected ImapStore getStore() { return store; } - protected String getLogId() - { + protected String getLogId() { String id = getAccount().getDescription() + ":" + getName() + "/" + Thread.currentThread().getName(); - if (mConnection != null) - { + if (mConnection != null) { id += "/" + mConnection.getLogId(); } return id; @@ -2215,8 +1779,7 @@ public class ImapStore extends Store /** * A cacheable class that stores the details for a single IMAP connection. */ - public static class ImapConnection - { + public static class ImapConnection { protected Socket mSocket; protected PeekableInputStream mIn; protected OutputStream mOut; @@ -2226,53 +1789,38 @@ public class ImapStore extends Store private ImapSettings mSettings; - public ImapConnection(final ImapSettings settings) - { + public ImapConnection(final ImapSettings settings) { this.mSettings = settings; } - protected String getLogId() - { + protected String getLogId() { return "conn" + hashCode(); } - private List receiveCapabilities(List responses) - { - for (ImapResponse response : responses) - { + private List receiveCapabilities(List responses) { + for (ImapResponse response : responses) { ImapList capabilityList = null; - if (response.size() > 0 && ImapResponseParser.equalsIgnoreCase(response.get(0), "OK")) - { - for (Object thisPart : response) - { - if (thisPart instanceof ImapList) - { + if (response.size() > 0 && ImapResponseParser.equalsIgnoreCase(response.get(0), "OK")) { + for (Object thisPart : response) { + if (thisPart instanceof ImapList) { ImapList thisList = (ImapList)thisPart; - if (ImapResponseParser.equalsIgnoreCase(thisList.get(0), CAPABILITY_CAPABILITY)) - { + if (ImapResponseParser.equalsIgnoreCase(thisList.get(0), CAPABILITY_CAPABILITY)) { capabilityList = thisList; break; } } } - } - else if (response.mTag == null) - { + } else if (response.mTag == null) { capabilityList = response; } - if (capabilityList != null) - { - if (capabilityList.size() > 0 && ImapResponseParser.equalsIgnoreCase(capabilityList.get(0), CAPABILITY_CAPABILITY)) - { - if (K9.DEBUG) - { + if (capabilityList != null) { + if (capabilityList.size() > 0 && ImapResponseParser.equalsIgnoreCase(capabilityList.get(0), CAPABILITY_CAPABILITY)) { + if (K9.DEBUG) { Log.d(K9.LOG_TAG, "Saving " + capabilityList.size() + " capabilities for " + getLogId()); } - for (Object capability : capabilityList) - { - if (capability instanceof String) - { + for (Object capability : capabilityList) { + if (capability instanceof String) { // if (K9.DEBUG) // { // Log.v(K9.LOG_TAG, "Saving capability '" + capability + "' for " + getLogId()); @@ -2287,39 +1835,30 @@ public class ImapStore extends Store return responses; } - public void open() throws IOException, MessagingException - { - if (isOpen()) - { + public void open() throws IOException, MessagingException { + if (isOpen()) { return; } boolean authSuccess = false; mNextCommandTag = 1; - try - { + try { Security.setProperty("networkaddress.cache.ttl", "0"); - } - catch (Exception e) - { + } catch (Exception e) { Log.w(K9.LOG_TAG, "Could not set DNS ttl to 0 for " + getLogId(), e); } - try - { + try { Security.setProperty("networkaddress.cache.negative.ttl", "0"); - } - catch (Exception e) - { + } catch (Exception e) { Log.w(K9.LOG_TAG, "Could not set DNS negative ttl to 0 for " + getLogId(), e); } - try - { + try { SocketAddress socketAddress = new InetSocketAddress(mSettings.getHost(), mSettings.getPort()); @@ -2327,19 +1866,15 @@ public class ImapStore extends Store Log.i(K9.LOG_TAG, "Connection " + getLogId() + " connecting to " + mSettings.getHost() + " @ IP addr " + socketAddress); if (mSettings.getConnectionSecurity() == CONNECTION_SECURITY_SSL_REQUIRED || - mSettings.getConnectionSecurity() == CONNECTION_SECURITY_SSL_OPTIONAL) - { + mSettings.getConnectionSecurity() == CONNECTION_SECURITY_SSL_OPTIONAL) { SSLContext sslContext = SSLContext.getInstance("TLS"); final boolean secure = mSettings.getConnectionSecurity() == CONNECTION_SECURITY_SSL_REQUIRED; - sslContext.init(null, new TrustManager[] - { + sslContext.init(null, new TrustManager[] { TrustManagerFactory.get(mSettings.getHost(), secure) }, new SecureRandom()); mSocket = sslContext.getSocketFactory().createSocket(); mSocket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); - } - else - { + } else { mSocket = new Socket(); mSocket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } @@ -2360,30 +1895,25 @@ public class ImapStore extends Store nullResponses.add(nullResponse); receiveCapabilities(nullResponses); - if (!hasCapability(CAPABILITY_CAPABILITY)) - { + if (!hasCapability(CAPABILITY_CAPABILITY)) { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Did not get capabilities in banner, requesting CAPABILITY for " + getLogId()); List responses = receiveCapabilities(executeSimpleCommand(COMMAND_CAPABILITY)); - if (responses.size() != 2) - { + if (responses.size() != 2) { throw new MessagingException("Invalid CAPABILITY response received"); } } if (mSettings.getConnectionSecurity() == CONNECTION_SECURITY_TLS_OPTIONAL - || mSettings.getConnectionSecurity() == CONNECTION_SECURITY_TLS_REQUIRED) - { + || mSettings.getConnectionSecurity() == CONNECTION_SECURITY_TLS_REQUIRED) { - if (hasCapability("STARTTLS")) - { + if (hasCapability("STARTTLS")) { // STARTTLS executeSimpleCommand("STARTTLS"); SSLContext sslContext = SSLContext.getInstance("TLS"); boolean secure = mSettings.getConnectionSecurity() == CONNECTION_SECURITY_TLS_REQUIRED; - sslContext.init(null, new TrustManager[] - { + sslContext.init(null, new TrustManager[] { TrustManagerFactory.get(mSettings.getHost(), secure) }, new SecureRandom()); mSocket = sslContext.getSocketFactory().createSocket(mSocket, mSettings.getHost(), mSettings.getPort(), @@ -2393,26 +1923,21 @@ public class ImapStore extends Store .getInputStream(), 1024)); mParser = new ImapResponseParser(mIn); mOut = mSocket.getOutputStream(); - } - else if (mSettings.getConnectionSecurity() == CONNECTION_SECURITY_TLS_REQUIRED) - { + } else if (mSettings.getConnectionSecurity() == CONNECTION_SECURITY_TLS_REQUIRED) { throw new MessagingException("TLS not supported but required"); } } mOut = new BufferedOutputStream(mOut, 1024); - try - { + try { // Yahoo! requires a custom IMAP command to work right over a non-3G network - if (mSettings.getHost().endsWith("yahoo.com")) - { + if (mSettings.getHost().endsWith("yahoo.com")) { if (K9.DEBUG) Log.v(K9.LOG_TAG, "Found Yahoo! account. Sending proprietary commands."); executeSimpleCommand("ID (\"GUID\" \"1\")"); } - if (mSettings.getAuthType() == AuthType.CRAM_MD5) - { + if (mSettings.getAuthType() == AuthType.CRAM_MD5) { authCramMD5(); // The authCramMD5 method called on the previous line does not allow for handling updated capabilities // sent by the server. So, to make sure we update to the post-authentication capability list @@ -2420,39 +1945,29 @@ public class ImapStore extends Store if (K9.DEBUG) Log.i(K9.LOG_TAG, "Updating capabilities after CRAM-MD5 authentication for " + getLogId()); List responses = receiveCapabilities(executeSimpleCommand(COMMAND_CAPABILITY)); - if (responses.size() != 2) - { + if (responses.size() != 2) { throw new MessagingException("Invalid CAPABILITY response received"); } - } - else if (mSettings.getAuthType() == AuthType.PLAIN) - { + } else if (mSettings.getAuthType() == AuthType.PLAIN) { receiveCapabilities(executeSimpleCommand(String.format("LOGIN %s %s", ImapStore.encodeString(mSettings.getUsername()), ImapStore.encodeString(mSettings.getPassword())), true)); } authSuccess = true; - } - catch (ImapException ie) - { + } catch (ImapException ie) { throw new AuthenticationFailedException(ie.getAlertText(), ie); - } - catch (MessagingException me) - { + } catch (MessagingException me) { throw new AuthenticationFailedException(null, me); } - if (K9.DEBUG) - { + if (K9.DEBUG) { Log.d(K9.LOG_TAG, CAPABILITY_COMPRESS_DEFLATE + " = " + hasCapability(CAPABILITY_COMPRESS_DEFLATE)); } - if (hasCapability(CAPABILITY_COMPRESS_DEFLATE)) - { + if (hasCapability(CAPABILITY_COMPRESS_DEFLATE)) { ConnectivityManager connectivityManager = (ConnectivityManager)K9.app.getSystemService(Context.CONNECTIVITY_SERVICE); boolean useCompression = true; NetworkInfo netInfo = connectivityManager.getActiveNetworkInfo(); - if (netInfo != null) - { + if (netInfo != null) { int type = netInfo.getType(); if (K9.DEBUG) Log.d(K9.LOG_TAG, "On network type " + type); @@ -2461,10 +1976,8 @@ public class ImapStore extends Store } if (K9.DEBUG) Log.d(K9.LOG_TAG, "useCompression " + useCompression); - if (useCompression) - { - try - { + if (useCompression) { + try { executeSimpleCommand(COMMAND_COMPRESS_DEFLATE); ZInputStream zInputStream = new ZInputStream(mSocket.getInputStream(), true); zInputStream.setFlushMode(JZlib.Z_PARTIAL_FLUSH); @@ -2473,13 +1986,10 @@ public class ImapStore extends Store ZOutputStream zOutputStream = new ZOutputStream(mSocket.getOutputStream(), JZlib.Z_BEST_SPEED, true); mOut = new BufferedOutputStream(zOutputStream, 1024); zOutputStream.setFlushMode(JZlib.Z_PARTIAL_FLUSH); - if (K9.DEBUG) - { + if (K9.DEBUG) { Log.i(K9.LOG_TAG, "Compression enabled for " + getLogId()); } - } - catch (Exception e) - { + } catch (Exception e) { Log.e(K9.LOG_TAG, "Unable to negotiate compression", e); } } @@ -2490,30 +2000,24 @@ public class ImapStore extends Store Log.d(K9.LOG_TAG, "NAMESPACE = " + hasCapability(CAPABILITY_NAMESPACE) + ", mPathPrefix = " + mSettings.getPathPrefix()); - if (mSettings.getPathPrefix() == null) - { - if (hasCapability(CAPABILITY_NAMESPACE)) - { + if (mSettings.getPathPrefix() == null) { + if (hasCapability(CAPABILITY_NAMESPACE)) { if (K9.DEBUG) Log.i(K9.LOG_TAG, "mPathPrefix is unset and server has NAMESPACE capability"); List namespaceResponses = executeSimpleCommand(COMMAND_NAMESPACE); - for (ImapResponse response : namespaceResponses) - { - if (ImapResponseParser.equalsIgnoreCase(response.get(0), COMMAND_NAMESPACE)) - { + for (ImapResponse response : namespaceResponses) { + if (ImapResponseParser.equalsIgnoreCase(response.get(0), COMMAND_NAMESPACE)) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "Got NAMESPACE response " + response + " on " + getLogId()); Object personalNamespaces = response.get(1); - if (personalNamespaces != null && personalNamespaces instanceof ImapList) - { + if (personalNamespaces != null && personalNamespaces instanceof ImapList) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "Got personal namespaces: " + personalNamespaces); ImapList bracketed = (ImapList)personalNamespaces; Object firstNamespace = bracketed.get(0); - if (firstNamespace != null && firstNamespace instanceof ImapList) - { + if (firstNamespace != null && firstNamespace instanceof ImapList) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "Got first personal namespaces: " + firstNamespace); bracketed = (ImapList)firstNamespace; @@ -2526,97 +2030,71 @@ public class ImapStore extends Store } } } - } - else - { + } else { if (K9.DEBUG) Log.i(K9.LOG_TAG, "mPathPrefix is unset but server does not have NAMESPACE capability"); mSettings.setPathPrefix(""); } } - if (mSettings.getPathDelimeter() == null) - { - try - { + if (mSettings.getPathDelimeter() == null) { + try { List nameResponses = executeSimpleCommand(String.format("LIST \"\" \"\"")); - for (ImapResponse response : nameResponses) - { - if (ImapResponseParser.equalsIgnoreCase(response.get(0), "LIST")) - { + for (ImapResponse response : nameResponses) { + if (ImapResponseParser.equalsIgnoreCase(response.get(0), "LIST")) { mSettings.setPathDelimeter(response.getString(2)); mSettings.setCombinedPrefix(null); if (K9.DEBUG) Log.d(K9.LOG_TAG, "Got path delimeter '" + mSettings.getPathDelimeter() + "' for " + getLogId()); } } - } - catch (Exception e) - { + } catch (Exception e) { Log.e(K9.LOG_TAG, "Unable to get path delimeter using LIST", e); } } - } - catch (SSLException e) - { + } catch (SSLException e) { throw new CertificateValidationException(e.getMessage(), e); - } - catch (GeneralSecurityException gse) - { + } catch (GeneralSecurityException gse) { throw new MessagingException( "Unable to open connection to IMAP server due to security error.", gse); - } - catch (ConnectException ce) - { + } catch (ConnectException ce) { String ceMess = ce.getMessage(); String[] tokens = ceMess.split("-"); - if (tokens != null && tokens.length > 1 && tokens[1] != null) - { + if (tokens != null && tokens.length > 1 && tokens[1] != null) { Log.e(K9.LOG_TAG, "Stripping host/port from ConnectionException for " + getLogId(), ce); throw new ConnectException(tokens[1].trim()); - } - else - { + } else { throw ce; } - } - finally - { - if (!authSuccess) - { + } finally { + if (!authSuccess) { Log.e(K9.LOG_TAG, "Failed to login, closing connection for " + getLogId()); close(); } } } - protected void authCramMD5() throws AuthenticationFailedException, MessagingException - { - try - { + protected void authCramMD5() throws AuthenticationFailedException, MessagingException { + try { String tag = sendCommand("AUTHENTICATE CRAM-MD5", false); byte[] buf = new byte[ 1024 ]; int b64NonceLen = 0; - for (int i = 0; i < buf.length; i++) - { + for (int i = 0; i < buf.length; i++) { buf[ i ] = (byte)mIn.read(); - if (buf[i] == 0x0a) - { + if (buf[i] == 0x0a) { b64NonceLen = i; break; } } - if (b64NonceLen == 0) - { + if (b64NonceLen == 0) { throw new AuthenticationFailedException("Error negotiating CRAM-MD5: nonce too long."); } byte[] b64NonceTrim = new byte[ b64NonceLen - 2 ]; System.arraycopy(buf, 1, b64NonceTrim, 0, b64NonceLen - 2); byte[] nonce = Base64.decodeBase64(b64NonceTrim); - if (K9.DEBUG) - { + if (K9.DEBUG) { Log.d(K9.LOG_TAG, "Got nonce: " + new String(b64NonceTrim, "US-ASCII")); Log.d(K9.LOG_TAG, "Plaintext nonce: " + new String(nonce, "US-ASCII")); } @@ -2625,8 +2103,7 @@ public class ImapStore extends Store byte[] opad = new byte[64]; byte[] secretBytes = mSettings.getPassword().getBytes("US-ASCII"); MessageDigest md = MessageDigest.getInstance("MD5"); - if (secretBytes.length > 64) - { + if (secretBytes.length > 64) { secretBytes = md.digest(secretBytes); } System.arraycopy(secretBytes, 0, ipad, 0, secretBytes.length); @@ -2639,8 +2116,7 @@ public class ImapStore extends Store byte[] result = md.digest(firstPass); String plainCRAM = mSettings.getUsername() + " " + new String(Hex.encodeHex(result)); byte[] b64CRAM = Base64.encodeBase64(plainCRAM.getBytes("US-ASCII")); - if (K9.DEBUG) - { + if (K9.DEBUG) { Log.d(K9.LOG_TAG, "Username == " + mSettings.getUsername()); Log.d(K9.LOG_TAG, "plainCRAM: " + plainCRAM); Log.d(K9.LOG_TAG, "b64CRAM: " + new String(b64CRAM, "US-ASCII")); @@ -2650,61 +2126,48 @@ public class ImapStore extends Store mOut.write(new byte[] { 0x0d, 0x0a }); mOut.flush(); int respLen = 0; - for (int i = 0; i < buf.length; i++) - { + for (int i = 0; i < buf.length; i++) { buf[ i ] = (byte)mIn.read(); - if (buf[i] == 0x0a) - { + if (buf[i] == 0x0a) { respLen = i; break; } } String toMatch = tag + " OK"; String respStr = new String(buf, 0, respLen); - if (!respStr.startsWith(toMatch)) - { + if (!respStr.startsWith(toMatch)) { throw new AuthenticationFailedException("CRAM-MD5 error: " + respStr); } - } - catch (IOException ioe) - { + } catch (IOException ioe) { throw new AuthenticationFailedException("CRAM-MD5 Auth Failed."); - } - catch (NoSuchAlgorithmException nsae) - { + } catch (NoSuchAlgorithmException nsae) { throw new AuthenticationFailedException("MD5 Not Available."); } } - protected void setReadTimeout(int millis) throws SocketException - { + protected void setReadTimeout(int millis) throws SocketException { Socket sock = mSocket; - if (sock != null) - { + if (sock != null) { sock.setSoTimeout(millis); } } - protected boolean isIdleCapable() - { + protected boolean isIdleCapable() { if (K9.DEBUG) Log.v(K9.LOG_TAG, "Connection " + getLogId() + " has " + capabilities.size() + " capabilities"); return capabilities.contains(CAPABILITY_IDLE); } - protected boolean hasCapability(String capability) - { + protected boolean hasCapability(String capability) { return capabilities.contains(capability.toUpperCase()); } - public boolean isOpen() - { + public boolean isOpen() { return (mIn != null && mOut != null && mSocket != null && mSocket.isConnected() && !mSocket.isClosed()); } - public void close() - { + public void close() { // if (isOpen()) { // try { // executeSimpleCommand("LOGOUT"); @@ -2712,28 +2175,19 @@ public class ImapStore extends Store // // } // } - try - { + try { mIn.close(); - } - catch (Exception e) - { + } catch (Exception e) { } - try - { + try { mOut.close(); - } - catch (Exception e) - { + } catch (Exception e) { } - try - { + try { mSocket.close(); - } - catch (Exception e) - { + } catch (Exception e) { } mIn = null; @@ -2741,30 +2195,24 @@ public class ImapStore extends Store mSocket = null; } - public ImapResponse readResponse() throws IOException, MessagingException - { + public ImapResponse readResponse() throws IOException, MessagingException { return readResponse(null); } - public ImapResponse readResponse(ImapResponseParser.IImapResponseCallback callback) throws IOException - { - try - { + public ImapResponse readResponse(ImapResponseParser.IImapResponseCallback callback) throws IOException { + try { ImapResponse response = mParser.readResponse(callback); if (K9.DEBUG && K9.DEBUG_PROTOCOL_IMAP) Log.v(K9.LOG_TAG, getLogId() + "<<<" + response); return response; - } - catch (IOException ioe) - { + } catch (IOException ioe) { close(); throw ioe; } } - public void sendContinuation(String continuation) throws IOException - { + public void sendContinuation(String continuation) throws IOException { mOut.write(continuation.getBytes()); mOut.write('\r'); mOut.write('\n'); @@ -2776,10 +2224,8 @@ public class ImapStore extends Store } public String sendCommand(String command, boolean sensitive) - throws MessagingException, IOException - { - try - { + throws MessagingException, IOException { + try { open(); String tag = Integer.toString(mNextCommandTag++); String commandToSend = tag + " " + command; @@ -2788,56 +2234,42 @@ public class ImapStore extends Store mOut.write('\n'); mOut.flush(); - if (K9.DEBUG && K9.DEBUG_PROTOCOL_IMAP) - { - if (sensitive && !K9.DEBUG_SENSITIVE) - { + if (K9.DEBUG && K9.DEBUG_PROTOCOL_IMAP) { + if (sensitive && !K9.DEBUG_SENSITIVE) { Log.v(K9.LOG_TAG, getLogId() + ">>> " + "[Command Hidden, Enable Sensitive Debug Logging To Show]"); - } - else - { + } else { Log.v(K9.LOG_TAG, getLogId() + ">>> " + commandToSend); } } return tag; - } - catch (IOException ioe) - { + } catch (IOException ioe) { close(); throw ioe; - } - catch (ImapException ie) - { + } catch (ImapException ie) { close(); throw ie; - } - catch (MessagingException me) - { + } catch (MessagingException me) { close(); throw me; } } public List executeSimpleCommand(String command) throws IOException, - ImapException, MessagingException - { + ImapException, MessagingException { return executeSimpleCommand(command, false); } public List executeSimpleCommand(String command, boolean sensitive) throws IOException, - ImapException, MessagingException - { + ImapException, MessagingException { return executeSimpleCommand(command, sensitive, null); } public List executeSimpleCommand(String command, boolean sensitive, UntaggedHandler untaggedHandler) - throws IOException, ImapException, MessagingException - { + throws IOException, ImapException, MessagingException { String commandToLog = command; - if (sensitive && !K9.DEBUG_SENSITIVE) - { + if (sensitive && !K9.DEBUG_SENSITIVE) { commandToLog = "*sensitive*"; } @@ -2851,125 +2283,102 @@ public class ImapStore extends Store ArrayList responses = new ArrayList(); ImapResponse response; - do - { + do { response = mParser.readResponse(); if (K9.DEBUG && K9.DEBUG_PROTOCOL_IMAP) Log.v(K9.LOG_TAG, getLogId() + "<<<" + response); - if (response.mTag != null && !response.mTag.equalsIgnoreCase(tag)) - { + if (response.mTag != null && !response.mTag.equalsIgnoreCase(tag)) { Log.w(K9.LOG_TAG, "After sending tag " + tag + ", got tag response from previous command " + response + " for " + getLogId()); Iterator iter = responses.iterator(); - while (iter.hasNext()) - { + while (iter.hasNext()) { ImapResponse delResponse = iter.next(); if (delResponse.mTag != null || delResponse.size() < 2 - || (!ImapResponseParser.equalsIgnoreCase(delResponse.get(1), "EXISTS") && !ImapResponseParser.equalsIgnoreCase(delResponse.get(1), "EXPUNGE"))) - { + || (!ImapResponseParser.equalsIgnoreCase(delResponse.get(1), "EXISTS") && !ImapResponseParser.equalsIgnoreCase(delResponse.get(1), "EXPUNGE"))) { iter.remove(); } } response.mTag = null; continue; } - if (untaggedHandler != null) - { + if (untaggedHandler != null) { untaggedHandler.handleAsyncUntaggedResponse(response); } responses.add(response); - } - while (response.mTag == null); - if (response.size() < 1 || !ImapResponseParser.equalsIgnoreCase(response.get(0), "OK")) - { + } while (response.mTag == null); + if (response.size() < 1 || !ImapResponseParser.equalsIgnoreCase(response.get(0), "OK")) { throw new ImapException("Command: " + commandToLog + "; response: " + response.toString(), response.getAlertText()); } return responses; } } - static class ImapMessage extends MimeMessage - { - ImapMessage(String uid, Folder folder) - { + static class ImapMessage extends MimeMessage { + ImapMessage(String uid, Folder folder) { this.mUid = uid; this.mFolder = folder; } - public void setSize(int size) - { + public void setSize(int size) { this.mSize = size; } @Override - public void parse(InputStream in) throws IOException, MessagingException - { + public void parse(InputStream in) throws IOException, MessagingException { super.parse(in); } - public void setFlagInternal(Flag flag, boolean set) throws MessagingException - { + public void setFlagInternal(Flag flag, boolean set) throws MessagingException { super.setFlag(flag, set); } @Override - public void setFlag(Flag flag, boolean set) throws MessagingException - { + public void setFlag(Flag flag, boolean set) throws MessagingException { super.setFlag(flag, set); mFolder.setFlags(new Message[] { this }, new Flag[] { flag }, set); } @Override - public void delete(String trashFolderName) throws MessagingException - { + public void delete(String trashFolderName) throws MessagingException { getFolder().delete(new Message[] { this }, trashFolderName); } } - static class ImapBodyPart extends MimeBodyPart - { - public ImapBodyPart() throws MessagingException - { + static class ImapBodyPart extends MimeBodyPart { + public ImapBodyPart() throws MessagingException { super(); } - public void setSize(int size) - { + public void setSize(int size) { this.mSize = size; } } - static class ImapException extends MessagingException - { + static class ImapException extends MessagingException { private static final long serialVersionUID = 3725007182205882394L; String mAlertText; - public ImapException(String message, String alertText, Throwable throwable) - { + public ImapException(String message, String alertText, Throwable throwable) { super(message, throwable); this.mAlertText = alertText; } - public ImapException(String message, String alertText) - { + public ImapException(String message, String alertText) { super(message); this.mAlertText = alertText; } - public String getAlertText() - { + public String getAlertText() { return mAlertText; } - public void setAlertText(String alertText) - { + public void setAlertText(String alertText) { mAlertText = alertText; } } - public class ImapFolderPusher extends ImapFolder implements UntaggedHandler - { + public class ImapFolderPusher extends ImapFolder implements UntaggedHandler { final PushReceiver receiver; Thread listeningThread = null; final AtomicBoolean stop = new AtomicBoolean(false); @@ -2981,8 +2390,7 @@ public class ImapStore extends Store List storedUntaggedResponses = new ArrayList(); TracingWakeLock wakeLock = null; - public ImapFolderPusher(ImapStore store, String name, PushReceiver nReceiver) - { + public ImapFolderPusher(ImapStore store, String name, PushReceiver nReceiver) { super(store, name); receiver = nReceiver; TracingPowerManager pm = TracingPowerManager.getPowerManager(receiver.getContext()); @@ -2990,22 +2398,17 @@ public class ImapStore extends Store wakeLock.setReferenceCounted(false); } - public void refresh() throws IOException, MessagingException - { - if (idling.get()) - { + public void refresh() throws IOException, MessagingException { + if (idling.get()) { wakeLock.acquire(K9.PUSH_WAKE_LOCK_TIMEOUT); sendDone(); } } - private void sendDone() throws IOException, MessagingException - { - if (doneSent.compareAndSet(false, true)) - { + private void sendDone() throws IOException, MessagingException { + if (doneSent.compareAndSet(false, true)) { ImapConnection conn = mConnection; - if (conn != null) - { + if (conn != null) { conn.setReadTimeout(Store.SOCKET_READ_TIMEOUT); sendContinuation("DONE"); } @@ -3014,86 +2417,68 @@ public class ImapStore extends Store } private void sendContinuation(String continuation) - throws IOException - { + throws IOException { ImapConnection conn = mConnection; - if (conn != null) - { + if (conn != null) { conn.sendContinuation(continuation); } } - public void start() - { - Runnable runner = new Runnable() - { - public void run() - { + public void start() { + Runnable runner = new Runnable() { + public void run() { wakeLock.acquire(K9.PUSH_WAKE_LOCK_TIMEOUT); if (K9.DEBUG) Log.i(K9.LOG_TAG, "Pusher starting for " + getLogId()); - while (!stop.get()) - { - try - { + while (!stop.get()) { + try { int oldUidNext = -1; - try - { + try { String pushStateS = receiver.getPushState(getName()); ImapPushState pushState = ImapPushState.parse(pushStateS); oldUidNext = pushState.uidNext; if (K9.DEBUG) Log.i(K9.LOG_TAG, "Got oldUidNext " + oldUidNext + " for " + getLogId()); - } - catch (Exception e) - { + } catch (Exception e) { Log.e(K9.LOG_TAG, "Unable to get oldUidNext for " + getLogId(), e); } ImapConnection oldConnection = mConnection; internalOpen(OpenMode.READ_ONLY); ImapConnection conn = mConnection; - if (conn == null) - { + if (conn == null) { receiver.pushError("Could not establish connection for IDLE", null); throw new MessagingException("Could not establish connection for IDLE"); } - if (!conn.isIdleCapable()) - { + if (!conn.isIdleCapable()) { stop.set(true); receiver.pushError("IMAP server is not IDLE capable: " + conn.toString(), null); throw new MessagingException("IMAP server is not IDLE capable:" + conn.toString()); } - if (!stop.get() && mAccount.isPushPollOnConnect() && (conn != oldConnection || needsPoll.getAndSet(false))) - { + if (!stop.get() && mAccount.isPushPollOnConnect() && (conn != oldConnection || needsPoll.getAndSet(false))) { List untaggedResponses = new ArrayList(storedUntaggedResponses); storedUntaggedResponses.clear(); processUntaggedResponses(untaggedResponses); - if (mMessageCount == -1) - { + if (mMessageCount == -1) { throw new MessagingException("Message count = -1 for idling"); } receiver.syncFolder(ImapFolderPusher.this); } - if (stop.get()) - { + if (stop.get()) { continue; } int startUid = oldUidNext; int newUidNext = uidNext; - if (newUidNext == -1) - { - if (K9.DEBUG) - { + if (newUidNext == -1) { + if (K9.DEBUG) { Log.d(K9.LOG_TAG, "uidNext is -1, using search to find highest UID"); } int highestUid = getHighestUid(); - if (highestUid != -1) - { + if (highestUid != -1) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "highest UID = " + highestUid); newUidNext = highestUid + 1; @@ -3103,36 +2488,28 @@ public class ImapStore extends Store } } - if (startUid < newUidNext - mAccount.getDisplayCount()) - { + if (startUid < newUidNext - mAccount.getDisplayCount()) { startUid = newUidNext - mAccount.getDisplayCount(); } - if (startUid < 1) - { + if (startUid < 1) { startUid = 1; } - if (newUidNext > startUid) - { + if (newUidNext > startUid) { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Needs sync from uid " + startUid + " to " + newUidNext + " for " + getLogId()); List messages = new ArrayList(); - for (int uid = startUid; uid < newUidNext; uid++) - { + for (int uid = startUid; uid < newUidNext; uid++) { ImapMessage message = new ImapMessage("" + uid, ImapFolderPusher.this); messages.add(message); } - if (messages.size() > 0) - { + if (messages.size() > 0) { pushMessages(messages, true); } - } - else - { + } else { List untaggedResponses = null; - while (storedUntaggedResponses.size() > 0) - { + while (storedUntaggedResponses.size() > 0) { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Processing " + storedUntaggedResponses.size() + " untagged responses from previous commands for " + getLogId()); untaggedResponses = new ArrayList(storedUntaggedResponses); @@ -3153,39 +2530,29 @@ public class ImapStore extends Store delayTime.set(NORMAL_DELAY_TIME); idleFailureCount.set(0); } - } - catch (Exception e) - { + } catch (Exception e) { wakeLock.acquire(K9.PUSH_WAKE_LOCK_TIMEOUT); storedUntaggedResponses.clear(); idling.set(false); receiver.setPushActive(getName(), false); - try - { + try { close(); - } - catch (Exception me) - { + } catch (Exception me) { Log.e(K9.LOG_TAG, "Got exception while closing for exception for " + getLogId(), me); } - if (stop.get()) - { + if (stop.get()) { Log.i(K9.LOG_TAG, "Got exception while idling, but stop is set for " + getLogId()); - } - else - { + } else { receiver.pushError("Push error for " + getName(), e); Log.e(K9.LOG_TAG, "Got exception while idling for " + getLogId(), e); int delayTimeInt = delayTime.get(); receiver.sleep(wakeLock, delayTimeInt); delayTimeInt *= 2; - if (delayTimeInt > MAX_DELAY_TIME) - { + if (delayTimeInt > MAX_DELAY_TIME) { delayTimeInt = MAX_DELAY_TIME; } delayTime.set(delayTimeInt); - if (idleFailureCount.incrementAndGet() > IDLE_FAILURE_COUNT_LIMIT) - { + if (idleFailureCount.incrementAndGet() > IDLE_FAILURE_COUNT_LIMIT) { Log.e(K9.LOG_TAG, "Disabling pusher for " + getLogId() + " after " + idleFailureCount.get() + " consecutive errors"); receiver.pushError("Push disabled for " + getName() + " after " + idleFailureCount.get() + " consecutive errors", e); stop.set(true); @@ -3195,18 +2562,13 @@ public class ImapStore extends Store } } receiver.setPushActive(getName(), false); - try - { + try { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Pusher for " + getLogId() + " is exiting"); close(); - } - catch (Exception me) - { + } catch (Exception me) { Log.e(K9.LOG_TAG, "Got exception while closing for " + getLogId(), me); - } - finally - { + } finally { wakeLock.release(); } } @@ -3216,15 +2578,12 @@ public class ImapStore extends Store } @Override - protected void handleUntaggedResponse(ImapResponse response) - { - if (response.mTag == null && response.size() > 1) - { + protected void handleUntaggedResponse(ImapResponse response) { + if (response.mTag == null && response.size() > 1) { Object responseType = response.get(1); if (ImapResponseParser.equalsIgnoreCase(responseType, "FETCH") || ImapResponseParser.equalsIgnoreCase(responseType, "EXPUNGE") - || ImapResponseParser.equalsIgnoreCase(responseType, "EXISTS")) - { + || ImapResponseParser.equalsIgnoreCase(responseType, "EXISTS")) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "Storing response " + response + " for later processing"); @@ -3234,99 +2593,79 @@ public class ImapStore extends Store } } - protected void processUntaggedResponses(List responses) throws MessagingException - { + protected void processUntaggedResponses(List responses) throws MessagingException { boolean skipSync = false; int oldMessageCount = mMessageCount; - if (oldMessageCount == -1) - { + if (oldMessageCount == -1) { skipSync = true; } List flagSyncMsgSeqs = new ArrayList(); List removeMsgUids = new LinkedList(); - for (ImapResponse response : responses) - { + for (ImapResponse response : responses) { oldMessageCount += processUntaggedResponse(oldMessageCount, response, flagSyncMsgSeqs, removeMsgUids); } - if (!skipSync) - { - if (oldMessageCount < 0) - { + if (!skipSync) { + if (oldMessageCount < 0) { oldMessageCount = 0; } - if (mMessageCount > oldMessageCount) - { + if (mMessageCount > oldMessageCount) { syncMessages(mMessageCount, true); } } if (K9.DEBUG) Log.d(K9.LOG_TAG, "UIDs for messages needing flag sync are " + flagSyncMsgSeqs + " for " + getLogId()); - if (flagSyncMsgSeqs.size() > 0) - { + if (flagSyncMsgSeqs.size() > 0) { syncMessages(flagSyncMsgSeqs); } - if (removeMsgUids.size() > 0) - { + if (removeMsgUids.size() > 0) { removeMessages(removeMsgUids); } } - private void syncMessages(int end, boolean newArrivals) throws MessagingException - { + private void syncMessages(int end, boolean newArrivals) throws MessagingException { int oldUidNext = -1; - try - { + try { String pushStateS = receiver.getPushState(getName()); ImapPushState pushState = ImapPushState.parse(pushStateS); oldUidNext = pushState.uidNext; if (K9.DEBUG) Log.i(K9.LOG_TAG, "Got oldUidNext " + oldUidNext + " for " + getLogId()); - } - catch (Exception e) - { + } catch (Exception e) { Log.e(K9.LOG_TAG, "Unable to get oldUidNext for " + getLogId(), e); } Message[] messageArray = getMessages(end, end, null, true, null); - if (messageArray != null && messageArray.length > 0) - { + if (messageArray != null && messageArray.length > 0) { int newUid = Integer.parseInt(messageArray[0].getUid()); if (K9.DEBUG) Log.i(K9.LOG_TAG, "Got newUid " + newUid + " for message " + end + " on " + getLogId()); int startUid = oldUidNext; - if (startUid < newUid - 10) - { + if (startUid < newUid - 10) { startUid = newUid - 10; } - if (startUid < 1) - { + if (startUid < 1) { startUid = 1; } - if (newUid >= startUid) - { + if (newUid >= startUid) { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Needs sync from uid " + startUid + " to " + newUid + " for " + getLogId()); List messages = new ArrayList(); - for (int uid = startUid; uid <= newUid; uid++) - { + for (int uid = startUid; uid <= newUid; uid++) { ImapMessage message = new ImapMessage("" + uid, ImapFolderPusher.this); messages.add(message); } - if (messages.size() > 0) - { + if (messages.size() > 0) { pushMessages(messages, true); } } } } - private void syncMessages(List flagSyncMsgSeqs) - { - try - { + private void syncMessages(List flagSyncMsgSeqs) { + try { Message[] messageArray = null; messageArray = getMessages(flagSyncMsgSeqs, true, null); @@ -3335,77 +2674,59 @@ public class ImapStore extends Store messages.addAll(Arrays.asList(messageArray)); pushMessages(messages, false); - } - catch (Exception e) - { + } catch (Exception e) { receiver.pushError("Exception while processing Push untagged responses", e); } } - private void removeMessages(List removeUids) - { + private void removeMessages(List removeUids) { List messages = new ArrayList(removeUids.size()); - try - { + try { Message[] existingMessages = getMessagesFromUids(removeUids, true, null); - for (Message existingMessage : existingMessages) - { + for (Message existingMessage : existingMessages) { needsPoll.set(true); msgSeqUidMap.clear(); String existingUid = existingMessage.getUid(); Log.w(K9.LOG_TAG, "Message with UID " + existingUid + " still exists on server, not expunging"); removeUids.remove(existingUid); } - for (String uid : removeUids) - { + for (String uid : removeUids) { ImapMessage message = new ImapMessage(uid, this); - try - { + try { message.setFlagInternal(Flag.DELETED, true); - } - catch (MessagingException me) - { + } catch (MessagingException me) { Log.e(K9.LOG_TAG, "Unable to set DELETED flag on message " + message.getUid()); } messages.add(message); } receiver.messagesRemoved(this, messages); - } - catch (Exception e) - { + } catch (Exception e) { Log.e(K9.LOG_TAG, "Cannot remove EXPUNGEd messages", e); } } - protected int processUntaggedResponse(int oldMessageCount, ImapResponse response, List flagSyncMsgSeqs, List removeMsgUids) - { + protected int processUntaggedResponse(int oldMessageCount, ImapResponse response, List flagSyncMsgSeqs, List removeMsgUids) { super.handleUntaggedResponse(response); int messageCountDelta = 0; - if (response.mTag == null && response.size() > 1) - { - try - { + if (response.mTag == null && response.size() > 1) { + try { Object responseType = response.get(1); - if (ImapResponseParser.equalsIgnoreCase(responseType, "FETCH")) - { + if (ImapResponseParser.equalsIgnoreCase(responseType, "FETCH")) { Log.i(K9.LOG_TAG, "Got FETCH " + response); int msgSeq = response.getNumber(0); if (K9.DEBUG) Log.d(K9.LOG_TAG, "Got untagged FETCH for msgseq " + msgSeq + " for " + getLogId()); - if (!flagSyncMsgSeqs.contains(msgSeq)) - { + if (!flagSyncMsgSeqs.contains(msgSeq)) { flagSyncMsgSeqs.add(msgSeq); } } - if (ImapResponseParser.equalsIgnoreCase(responseType, "EXPUNGE")) - { + if (ImapResponseParser.equalsIgnoreCase(responseType, "EXPUNGE")) { int msgSeq = response.getNumber(0); - if (msgSeq <= oldMessageCount) - { + if (msgSeq <= oldMessageCount) { messageCountDelta = -1; } if (K9.DEBUG) @@ -3413,14 +2734,11 @@ public class ImapStore extends Store List newSeqs = new ArrayList(); Iterator flagIter = flagSyncMsgSeqs.iterator(); - while (flagIter.hasNext()) - { + while (flagIter.hasNext()) { Integer flagMsg = flagIter.next(); - if (flagMsg >= msgSeq) - { + if (flagMsg >= msgSeq) { flagIter.remove(); - if (flagMsg > msgSeq) - { + if (flagMsg > msgSeq) { newSeqs.add(flagMsg--); } } @@ -3431,38 +2749,29 @@ public class ImapStore extends Store List msgSeqs = new ArrayList(msgSeqUidMap.keySet()); Collections.sort(msgSeqs); // Have to do comparisons in order because of msgSeq reductions - for (Integer msgSeqNumI : msgSeqs) - { - if (K9.DEBUG) - { + for (Integer msgSeqNumI : msgSeqs) { + if (K9.DEBUG) { Log.v(K9.LOG_TAG, "Comparing EXPUNGEd msgSeq " + msgSeq + " to " + msgSeqNumI); } int msgSeqNum = msgSeqNumI; - if (msgSeqNum == msgSeq) - { + if (msgSeqNum == msgSeq) { String uid = msgSeqUidMap.get(msgSeqNum); - if (K9.DEBUG) - { + if (K9.DEBUG) { Log.d(K9.LOG_TAG, "Scheduling removal of UID " + uid + " because msgSeq " + msgSeqNum + " was expunged"); } removeMsgUids.add(uid); msgSeqUidMap.remove(msgSeqNum); - } - else if (msgSeqNum > msgSeq) - { + } else if (msgSeqNum > msgSeq) { String uid = msgSeqUidMap.get(msgSeqNum); - if (K9.DEBUG) - { + if (K9.DEBUG) { Log.d(K9.LOG_TAG, "Reducing msgSeq for UID " + uid + " from " + msgSeqNum + " to " + (msgSeqNum - 1)); } msgSeqUidMap.remove(msgSeqNum); - msgSeqUidMap.put(msgSeqNum-1, uid); + msgSeqUidMap.put(msgSeqNum - 1, uid); } } } - } - catch (Exception e) - { + } catch (Exception e) { Log.e(K9.LOG_TAG, "Could not handle untagged FETCH for " + getLogId(), e); } } @@ -3470,83 +2779,59 @@ public class ImapStore extends Store } - private void pushMessages(List messages, boolean newArrivals) - { + private void pushMessages(List messages, boolean newArrivals) { RuntimeException holdException = null; - try - { - if (newArrivals) - { + try { + if (newArrivals) { receiver.messagesArrived(this, messages); - } - else - { + } else { receiver.messagesFlagsChanged(this, messages); } - } - catch (RuntimeException e) - { + } catch (RuntimeException e) { holdException = e; } - if (holdException != null) - { + if (holdException != null) { throw holdException; } } - public void stop() - { + public void stop() { stop.set(true); - if (listeningThread != null) - { + if (listeningThread != null) { listeningThread.interrupt(); } ImapConnection conn = mConnection; - if (conn != null) - { + if (conn != null) { if (K9.DEBUG) Log.v(K9.LOG_TAG, "Closing mConnection to stop pushing for " + getLogId()); conn.close(); - } - else - { + } else { Log.w(K9.LOG_TAG, "Attempt to interrupt null mConnection to stop pushing on folderPusher for " + getLogId()); } } - public void handleAsyncUntaggedResponse(ImapResponse response) - { + public void handleAsyncUntaggedResponse(ImapResponse response) { if (K9.DEBUG) Log.v(K9.LOG_TAG, "Got async response: " + response); - if (stop.get()) - { + if (stop.get()) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "Got async untagged response: " + response + ", but stop is set for " + getLogId()); - try - { + try { sendDone(); - } - catch (Exception e) - { + } catch (Exception e) { Log.e(K9.LOG_TAG, "Exception while sending DONE for " + getLogId(), e); } - } - else - { - if (response.mTag == null) - { - if (response.size() > 1) - { + } else { + if (response.mTag == null) { + if (response.size() > 1) { boolean started = false; Object responseType = response.get(1); if (ImapResponseParser.equalsIgnoreCase(responseType, "EXISTS") || ImapResponseParser.equalsIgnoreCase(responseType, "EXPUNGE") || - ImapResponseParser.equalsIgnoreCase(responseType,"FETCH")) - { - if (!started) - { + ImapResponseParser.equalsIgnoreCase(responseType, "FETCH")) { + if (!started) { wakeLock.acquire(K9.PUSH_WAKE_LOCK_TIMEOUT); started = true; } @@ -3554,18 +2839,13 @@ public class ImapStore extends Store if (K9.DEBUG) Log.d(K9.LOG_TAG, "Got useful async untagged response: " + response + " for " + getLogId()); - try - { + try { sendDone(); - } - catch (Exception e) - { + } catch (Exception e) { Log.e(K9.LOG_TAG, "Exception while sending DONE for " + getLogId(), e); } } - } - else if (response.mCommandContinuationRequested) - { + } else if (response.mCommandContinuationRequested) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "Idling " + getLogId()); @@ -3576,36 +2856,29 @@ public class ImapStore extends Store } } @Override - public Pusher getPusher(PushReceiver receiver) - { + public Pusher getPusher(PushReceiver receiver) { return new ImapPusher(this, receiver); } - public class ImapPusher implements Pusher - { + public class ImapPusher implements Pusher { final ImapStore mStore; final PushReceiver mReceiver; private long lastRefresh = -1; HashMap folderPushers = new HashMap(); - public ImapPusher(ImapStore store, PushReceiver receiver) - { + public ImapPusher(ImapStore store, PushReceiver receiver) { mStore = store; mReceiver = receiver; } - public void start(List folderNames) - { + public void start(List folderNames) { stop(); - synchronized (folderPushers) - { + synchronized (folderPushers) { setLastRefresh(System.currentTimeMillis()); - for (String folderName : folderNames) - { + for (String folderName : folderNames) { ImapFolderPusher pusher = folderPushers.get(folderName); - if (pusher == null) - { + if (pusher == null) { pusher = new ImapFolderPusher(mStore, folderName, mReceiver); folderPushers.put(folderName, pusher); pusher.start(); @@ -3614,41 +2887,29 @@ public class ImapStore extends Store } } - public void refresh() - { - synchronized (folderPushers) - { - for (ImapFolderPusher folderPusher : folderPushers.values()) - { - try - { + public void refresh() { + synchronized (folderPushers) { + for (ImapFolderPusher folderPusher : folderPushers.values()) { + try { folderPusher.refresh(); - } - catch (Exception e) - { + } catch (Exception e) { Log.e(K9.LOG_TAG, "Got exception while refreshing for " + folderPusher.getName(), e); } } } } - public void stop() - { + public void stop() { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Requested stop of IMAP pusher"); - synchronized (folderPushers) - { - for (ImapFolderPusher folderPusher : folderPushers.values()) - { - try - { + synchronized (folderPushers) { + for (ImapFolderPusher folderPusher : folderPushers.values()) { + try { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Requesting stop of IMAP folderPusher " + folderPusher.getName()); folderPusher.stop(); - } - catch (Exception e) - { + } catch (Exception e) { Log.e(K9.LOG_TAG, "Got exception while stopping " + folderPusher.getName(), e); } } @@ -3656,56 +2917,42 @@ public class ImapStore extends Store } } - public int getRefreshInterval() - { + public int getRefreshInterval() { return (getAccount().getIdleRefreshMinutes() * 60 * 1000); } - public long getLastRefresh() - { + public long getLastRefresh() { return lastRefresh; } - public void setLastRefresh(long lastRefresh) - { + public void setLastRefresh(long lastRefresh) { this.lastRefresh = lastRefresh; } } - private interface UntaggedHandler - { + private interface UntaggedHandler { void handleAsyncUntaggedResponse(ImapResponse respose); } - protected static class ImapPushState - { + protected static class ImapPushState { protected int uidNext; - protected ImapPushState(int nUidNext) - { + protected ImapPushState(int nUidNext) { uidNext = nUidNext; } - protected static ImapPushState parse(String pushState) - { + protected static ImapPushState parse(String pushState) { int newUidNext = -1; - if (pushState != null) - { + if (pushState != null) { StringTokenizer tokenizer = new StringTokenizer(pushState, ";"); - while (tokenizer.hasMoreTokens()) - { + while (tokenizer.hasMoreTokens()) { StringTokenizer thisState = new StringTokenizer(tokenizer.nextToken(), "="); - if (thisState.hasMoreTokens()) - { + if (thisState.hasMoreTokens()) { String key = thisState.nextToken(); - if ("uidNext".equalsIgnoreCase(key) && thisState.hasMoreTokens()) - { + if ("uidNext".equalsIgnoreCase(key) && thisState.hasMoreTokens()) { String value = thisState.nextToken(); - try - { + try { newUidNext = Integer.parseInt(value); - } - catch (Exception e) - { + } catch (Exception e) { Log.e(K9.LOG_TAG, "Unable to part uidNext value " + value, e); } @@ -3716,33 +2963,27 @@ public class ImapStore extends Store return new ImapPushState(newUidNext); } @Override - public String toString() - { + public String toString() { return "uidNext=" + uidNext; } } - private interface ImapSearcher - { + private interface ImapSearcher { List search() throws IOException, MessagingException; } - private static class FetchBodyCallback implements ImapResponseParser.IImapResponseCallback - { + private static class FetchBodyCallback implements ImapResponseParser.IImapResponseCallback { private HashMap mMessageMap; - FetchBodyCallback(HashMap mesageMap) - { + FetchBodyCallback(HashMap mesageMap) { mMessageMap = mesageMap; } @Override public Object foundLiteral(ImapResponse response, - FixedLengthInputStream literal) throws IOException, Exception - { + FixedLengthInputStream literal) throws IOException, Exception { if (response.mTag == null && - ImapResponseParser.equalsIgnoreCase(response.get(1), "FETCH")) - { + ImapResponseParser.equalsIgnoreCase(response.get(1), "FETCH")) { ImapList fetchList = (ImapList)response.getKeyedValue("FETCH"); String uid = fetchList.getKeyedString("UID"); @@ -3756,22 +2997,18 @@ public class ImapStore extends Store } } - private static class FetchPartCallback implements ImapResponseParser.IImapResponseCallback - { + private static class FetchPartCallback implements ImapResponseParser.IImapResponseCallback { private Part mPart; - FetchPartCallback(Part part) - { + FetchPartCallback(Part part) { mPart = part; } @Override public Object foundLiteral(ImapResponse response, - FixedLengthInputStream literal) throws IOException, Exception - { + FixedLengthInputStream literal) throws IOException, Exception { if (response.mTag == null && - ImapResponseParser.equalsIgnoreCase(response.get(1), "FETCH")) - { + ImapResponseParser.equalsIgnoreCase(response.get(1), "FETCH")) { //TODO: check for correct UID String contentTransferEncoding = mPart.getHeader( diff --git a/src/com/fsck/k9/mail/store/LocalStore.java b/src/com/fsck/k9/mail/store/LocalStore.java index a83d1fbd0..d2af53b6c 100644 --- a/src/com/fsck/k9/mail/store/LocalStore.java +++ b/src/com/fsck/k9/mail/store/LocalStore.java @@ -62,8 +62,7 @@ import com.fsck.k9.provider.AttachmentProvider; * Implements a SQLite database backed local store for Messages. * */ -public class LocalStore extends Store implements Serializable -{ +public class LocalStore extends Store implements Serializable { private static final long serialVersionUID = -5142141896809423072L; @@ -77,8 +76,7 @@ public class LocalStore extends Store implements Serializable private static final Flag[] PERMANENT_FLAGS = { Flag.DELETED, Flag.X_DESTROYED, Flag.SEEN, Flag.FLAGGED }; private static Set HEADERS_TO_SAVE = new HashSet(); - static - { + static { HEADERS_TO_SAVE.add(K9.IDENTITY_HEADER); HEADERS_TO_SAVE.add("To"); HEADERS_TO_SAVE.add("Cc"); @@ -116,8 +114,7 @@ public class LocalStore extends Store implements Serializable * @param application * @throws UnavailableStorageException if not {@link StorageProvider#isReady(Context)} */ - public LocalStore(final Account account, final Application application) throws MessagingException - { + public LocalStore(final Account account, final Application application) throws MessagingException { super(account); database = new LockableDatabase(application, account.getUuid(), new StoreSchemaDefinition()); @@ -128,46 +125,39 @@ public class LocalStore extends Store implements Serializable database.open(); } - public void switchLocalStorage(final String newStorageProviderId) throws MessagingException - { + public void switchLocalStorage(final String newStorageProviderId) throws MessagingException { database.switchProvider(newStorageProviderId); } - protected SharedPreferences getPreferences() - { + protected SharedPreferences getPreferences() { return Preferences.getPreferences(mApplication).getPreferences(); } - private class StoreSchemaDefinition implements LockableDatabase.SchemaDefinition - { + private class StoreSchemaDefinition implements LockableDatabase.SchemaDefinition { @Override - public int getVersion() - { + public int getVersion() { return DB_VERSION; } @Override - public void doDbUpgrade(final SQLiteDatabase db) - { + public void doDbUpgrade(final SQLiteDatabase db) { Log.i(K9.LOG_TAG, String.format("Upgrading database from version %d to version %d", db.getVersion(), DB_VERSION)); AttachmentProvider.clear(mApplication); - try - { + try { // schema version 29 was when we moved to incremental updates // in the case of a new db or a < v29 db, we blow away and start from scratch - if (db.getVersion() < 29) - { + if (db.getVersion() < 29) { db.execSQL("DROP TABLE IF EXISTS folders"); db.execSQL("CREATE TABLE folders (id INTEGER PRIMARY KEY, name TEXT, " + "last_updated INTEGER, unread_count INTEGER, visible_limit INTEGER, status TEXT, " + "push_state TEXT, last_pushed INTEGER, flagged_count INTEGER default 0, " + "integrate INTEGER, top_group INTEGER, poll_class TEXT, push_class TEXT, display_class TEXT" - +")"); + + ")"); db.execSQL("CREATE INDEX IF NOT EXISTS folder_name ON folders (name)"); db.execSQL("DROP TABLE IF EXISTS messages"); @@ -199,189 +189,132 @@ public class LocalStore extends Store implements Serializable db.execSQL("DROP TRIGGER IF EXISTS delete_message"); db.execSQL("CREATE TRIGGER delete_message BEFORE DELETE ON messages BEGIN DELETE FROM attachments WHERE old.id = message_id; " + "DELETE FROM headers where old.id = message_id; END;"); - } - else - { + } else { // in the case that we're starting out at 29 or newer, run all the needed updates - if (db.getVersion() < 30) - { - try - { + if (db.getVersion() < 30) { + try { db.execSQL("ALTER TABLE messages ADD deleted INTEGER default 0"); - } - catch (SQLiteException e) - { - if (! e.toString().startsWith("duplicate column name: deleted")) - { + } catch (SQLiteException e) { + if (! e.toString().startsWith("duplicate column name: deleted")) { throw e; } } } - if (db.getVersion() < 31) - { + if (db.getVersion() < 31) { db.execSQL("DROP INDEX IF EXISTS msg_folder_id_date"); db.execSQL("CREATE INDEX IF NOT EXISTS msg_folder_id_deleted_date ON messages (folder_id,deleted,internal_date)"); } - if (db.getVersion() < 32) - { + if (db.getVersion() < 32) { db.execSQL("UPDATE messages SET deleted = 1 WHERE flags LIKE '%DELETED%'"); } - if (db.getVersion() < 33) - { + if (db.getVersion() < 33) { - try - { + try { db.execSQL("ALTER TABLE messages ADD preview TEXT"); - } - catch (SQLiteException e) - { - if (! e.toString().startsWith("duplicate column name: preview")) - { + } catch (SQLiteException e) { + if (! e.toString().startsWith("duplicate column name: preview")) { throw e; } } } - if (db.getVersion() < 34) - { - try - { + if (db.getVersion() < 34) { + try { db.execSQL("ALTER TABLE folders ADD flagged_count INTEGER default 0"); - } - catch (SQLiteException e) - { - if (! e.getMessage().startsWith("duplicate column name: flagged_count")) - { + } catch (SQLiteException e) { + if (! e.getMessage().startsWith("duplicate column name: flagged_count")) { throw e; } } } - if (db.getVersion() < 35) - { - try - { + if (db.getVersion() < 35) { + try { db.execSQL("update messages set flags = replace(flags, 'X_NO_SEEN_INFO', 'X_BAD_FLAG')"); - } - catch (SQLiteException e) - { + } catch (SQLiteException e) { Log.e(K9.LOG_TAG, "Unable to get rid of obsolete flag X_NO_SEEN_INFO", e); } } - if (db.getVersion() < 36) - { - try - { + if (db.getVersion() < 36) { + try { db.execSQL("ALTER TABLE attachments ADD content_id TEXT"); - } - catch (SQLiteException e) - { + } catch (SQLiteException e) { Log.e(K9.LOG_TAG, "Unable to add content_id column to attachments"); } } - if (db.getVersion() < 37) - { - try - { + if (db.getVersion() < 37) { + try { db.execSQL("ALTER TABLE attachments ADD content_disposition TEXT"); - } - catch (SQLiteException e) - { + } catch (SQLiteException e) { Log.e(K9.LOG_TAG, "Unable to add content_disposition column to attachments"); } } // Database version 38 is solely to prune cached attachments now that we clear them better - if (db.getVersion() < 39) - { - try - { + if (db.getVersion() < 39) { + try { db.execSQL("DELETE FROM headers WHERE id in (SELECT headers.id FROM headers LEFT JOIN messages ON headers.message_id = messages.id WHERE messages.id IS NULL)"); - } - catch (SQLiteException e) - { + } catch (SQLiteException e) { Log.e(K9.LOG_TAG, "Unable to remove extra header data from the database"); } } // V40: Store the MIME type for a message. - if (db.getVersion() < 40) - { - try - { + if (db.getVersion() < 40) { + try { db.execSQL("ALTER TABLE messages ADD mime_type TEXT"); - } - catch (SQLiteException e) - { + } catch (SQLiteException e) { Log.e(K9.LOG_TAG, "Unable to add mime_type column to messages"); } } - if (db.getVersion() < 41) - { - try - { + if (db.getVersion() < 41) { + try { db.execSQL("ALTER TABLE folders ADD integrate INTEGER"); db.execSQL("ALTER TABLE folders ADD top_group INTEGER"); db.execSQL("ALTER TABLE folders ADD poll_class TEXT"); db.execSQL("ALTER TABLE folders ADD push_class TEXT"); db.execSQL("ALTER TABLE folders ADD display_class TEXT"); - } - catch (SQLiteException e) - { - if (! e.getMessage().startsWith("duplicate column name:")) - { + } catch (SQLiteException e) { + if (! e.getMessage().startsWith("duplicate column name:")) { throw e; } } Cursor cursor = null; - try - { + try { SharedPreferences prefs = getPreferences(); cursor = db.rawQuery("SELECT id, name FROM folders", null); - while (cursor.moveToNext()) - { - try - { + while (cursor.moveToNext()) { + try { int id = cursor.getInt(0); String name = cursor.getString(1); update41Metadata(db, prefs, id, name); - } - catch (Exception e) - { - Log.e(K9.LOG_TAG," error trying to ugpgrade a folder class: " +e); + } catch (Exception e) { + Log.e(K9.LOG_TAG, " error trying to ugpgrade a folder class: " + e); } } } - catch (SQLiteException e) - { - Log.e(K9.LOG_TAG, "Exception while upgrading database to v41. folder classes may have vanished "+e); + catch (SQLiteException e) { + Log.e(K9.LOG_TAG, "Exception while upgrading database to v41. folder classes may have vanished " + e); - } - finally - { - if (cursor != null) - { + } finally { + if (cursor != null) { cursor.close(); } } } - if (db.getVersion() == 41) - { - try - { + if (db.getVersion() == 41) { + try { long startTime = System.currentTimeMillis(); SharedPreferences.Editor editor = getPreferences().edit(); - List folders = getPersonalNamespaces(true); - for (Folder folder : folders) - { - if (folder instanceof LocalFolder) - { + List folders = getPersonalNamespaces(true); + for (Folder folder : folders) { + if (folder instanceof LocalFolder) { LocalFolder lFolder = (LocalFolder)folder; lFolder.save(editor); } @@ -390,17 +323,14 @@ public class LocalStore extends Store implements Serializable editor.commit(); long endTime = System.currentTimeMillis(); Log.i(K9.LOG_TAG, "Putting folder preferences for " + folders.size() + " folders back into Preferences took " + (endTime - startTime) + " ms"); - } - catch (Exception e) - { + } catch (Exception e) { Log.e(K9.LOG_TAG, "Could not replace Preferences in upgrade from DB_VERSION 41", e); } } } } - catch (SQLiteException e) - { + catch (SQLiteException e) { Log.e(K9.LOG_TAG, "Exception while upgrading database. Resetting the DB to v0"); db.setVersion(0); throw new Error("Database upgrade failed! Resetting your DB version to 0 to force a full schema recreation."); @@ -410,8 +340,7 @@ public class LocalStore extends Store implements Serializable db.setVersion(DB_VERSION); - if (db.getVersion() != DB_VERSION) - { + if (db.getVersion() != DB_VERSION) { throw new Error("Database upgrade failed!"); } @@ -427,8 +356,7 @@ public class LocalStore extends Store implements Serializable //} } - private void update41Metadata(final SQLiteDatabase db, SharedPreferences prefs, int id, String name) - { + private void update41Metadata(final SQLiteDatabase db, SharedPreferences prefs, int id, String name) { Folder.FolderClass displayClass = Folder.FolderClass.NO_CLASS; @@ -436,8 +364,7 @@ public class LocalStore extends Store implements Serializable Folder.FolderClass pushClass = Folder.FolderClass.SECOND_CLASS; boolean inTopGroup = false; boolean integrate = false; - if (K9.INBOX.equals(name)) - { + if (K9.INBOX.equals(name)) { displayClass = Folder.FolderClass.FIRST_CLASS; syncClass = Folder.FolderClass.FIRST_CLASS; pushClass = Folder.FolderClass.FIRST_CLASS; @@ -445,58 +372,47 @@ public class LocalStore extends Store implements Serializable integrate = true; } - try - { - displayClass = Folder.FolderClass.valueOf(prefs.getString(uUid + "."+ name + ".displayMode", displayClass.name())); - syncClass = Folder.FolderClass.valueOf(prefs.getString(uUid + "."+ name + ".syncMode", syncClass.name())); - pushClass = Folder.FolderClass.valueOf(prefs.getString(uUid + "."+ name + ".pushMode", pushClass.name())); - inTopGroup = prefs.getBoolean(uUid + "."+ name + ".inTopGroup",inTopGroup); - integrate = prefs.getBoolean(uUid + "."+ name + ".integrate", integrate); - } - catch (Exception e) - { - Log.e(K9.LOG_TAG," Throwing away an error while trying to upgrade folder metadata: "+e); + try { + displayClass = Folder.FolderClass.valueOf(prefs.getString(uUid + "." + name + ".displayMode", displayClass.name())); + syncClass = Folder.FolderClass.valueOf(prefs.getString(uUid + "." + name + ".syncMode", syncClass.name())); + pushClass = Folder.FolderClass.valueOf(prefs.getString(uUid + "." + name + ".pushMode", pushClass.name())); + inTopGroup = prefs.getBoolean(uUid + "." + name + ".inTopGroup", inTopGroup); + integrate = prefs.getBoolean(uUid + "." + name + ".integrate", integrate); + } catch (Exception e) { + Log.e(K9.LOG_TAG, " Throwing away an error while trying to upgrade folder metadata: " + e); } - if (displayClass == Folder.FolderClass.NONE) - { + if (displayClass == Folder.FolderClass.NONE) { displayClass = Folder.FolderClass.NO_CLASS; } - if (syncClass == Folder.FolderClass.NONE) - { + if (syncClass == Folder.FolderClass.NONE) { syncClass = Folder.FolderClass.INHERITED; } - if (pushClass == Folder.FolderClass.NONE) - { + if (pushClass == Folder.FolderClass.NONE) { pushClass = Folder.FolderClass.INHERITED; } db.execSQL("UPDATE folders SET integrate = ?, top_group = ?, poll_class=?, push_class =?, display_class = ? WHERE id = ?", - new Object[] { integrate, inTopGroup,syncClass,pushClass,displayClass, id }); + new Object[] { integrate, inTopGroup, syncClass, pushClass, displayClass, id }); } } - public long getSize() throws UnavailableStorageException - { + public long getSize() throws UnavailableStorageException { final StorageManager storageManager = StorageManager.getInstance(mApplication); final File attachmentDirectory = storageManager.getAttachmentDirectory(uUid, database.getStorageProviderId()); - return database.execute(false, new DbCallback() - { + return database.execute(false, new DbCallback() { @Override - public Long doDbWork(final SQLiteDatabase db) - { + public Long doDbWork(final SQLiteDatabase db) { final File[] files = attachmentDirectory.listFiles(); long attachmentLength = 0; - for (File file : files) - { - if (file.exists()) - { + for (File file : files) { + if (file.exists()) { attachmentLength += file.length(); } } @@ -507,16 +423,13 @@ public class LocalStore extends Store implements Serializable }); } - public void compact() throws MessagingException - { + public void compact() throws MessagingException { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Before compaction size = " + getSize()); - database.execute(false, new DbCallback() - { + database.execute(false, new DbCallback() { @Override - public Void doDbWork(final SQLiteDatabase db) throws WrappedException - { + public Void doDbWork(final SQLiteDatabase db) throws WrappedException { db.execSQL("VACUUM"); return null; } @@ -526,14 +439,12 @@ public class LocalStore extends Store implements Serializable } - public void clear() throws MessagingException - { + public void clear() throws MessagingException { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Before prune size = " + getSize()); pruneCachedAttachments(true); - if (K9.DEBUG) - { + if (K9.DEBUG) { Log.i(K9.LOG_TAG, "After prune / before compaction size = " + getSize()); Log.i(K9.LOG_TAG, "Before clear folder count = " + getFolderCount()); @@ -544,11 +455,9 @@ public class LocalStore extends Store implements Serializable // don't delete messages that are Local, since there is no copy on the server. // Don't delete deleted messages. They are essentially placeholders for UIDs of messages that have // been deleted locally. They take up insignificant space - database.execute(false, new DbCallback() - { + database.execute(false, new DbCallback() { @Override - public Void doDbWork(final SQLiteDatabase db) - { + public Void doDbWork(final SQLiteDatabase db) { db.execSQL("DELETE FROM messages WHERE deleted = 0 and uid not like 'Local%'"); db.execSQL("update folders set flagged_count = 0, unread_count = 0"); return null; @@ -557,35 +466,27 @@ public class LocalStore extends Store implements Serializable compact(); - if (K9.DEBUG) - { + if (K9.DEBUG) { Log.i(K9.LOG_TAG, "After clear message count = " + getMessageCount()); Log.i(K9.LOG_TAG, "After clear size = " + getSize()); } } - public int getMessageCount() throws MessagingException - { - return database.execute(false, new DbCallback() - { + public int getMessageCount() throws MessagingException { + return database.execute(false, new DbCallback() { @Override - public Integer doDbWork(final SQLiteDatabase db) - { + public Integer doDbWork(final SQLiteDatabase db) { Cursor cursor = null; - try - { + try { cursor = db.rawQuery("SELECT COUNT(*) FROM messages", null); cursor.moveToFirst(); return cursor.getInt(0); // message count - } - finally - { - if (cursor != null) - { + } finally { + if (cursor != null) { cursor.close(); } } @@ -595,87 +496,67 @@ public class LocalStore extends Store implements Serializable - public void getMessageCounts(final AccountStats stats) throws MessagingException - { + public void getMessageCounts(final AccountStats stats) throws MessagingException { final Account.FolderMode displayMode = mAccount.getFolderDisplayMode(); - database.execute(false, new DbCallback() - { + database.execute(false, new DbCallback() { @Override - public Integer doDbWork(final SQLiteDatabase db) - { + public Integer doDbWork(final SQLiteDatabase db) { Cursor cursor = null; - try - { + try { String baseQuery = "SELECT SUM(unread_count), SUM(flagged_count) FROM folders WHERE ( name != ? AND name != ? AND name != ? AND name != ? AND name != ? ) "; - if (displayMode == Account.FolderMode.NONE) - { - cursor = db.rawQuery(baseQuery+ "AND (name = ? )", new String[] - { + if (displayMode == Account.FolderMode.NONE) { + cursor = db.rawQuery(baseQuery + "AND (name = ? )", new String[] { mAccount.getTrashFolderName() != null ? mAccount.getTrashFolderName() : "" , mAccount.getDraftsFolderName() != null ? mAccount.getDraftsFolderName() : "", mAccount.getSpamFolderName() != null ? mAccount.getSpamFolderName() : "", - mAccount.getOutboxFolderName() != null? mAccount.getOutboxFolderName() : "", + mAccount.getOutboxFolderName() != null ? mAccount.getOutboxFolderName() : "", mAccount.getSentFolderName() != null ? mAccount.getSentFolderName() : "", K9.INBOX } ); - } - else if (displayMode == Account.FolderMode.FIRST_CLASS ) - { - cursor = db.rawQuery(baseQuery + " AND ( name = ? OR display_class = ?)", new String[] - { + } else if (displayMode == Account.FolderMode.FIRST_CLASS) { + cursor = db.rawQuery(baseQuery + " AND ( name = ? OR display_class = ?)", new String[] { mAccount.getTrashFolderName() != null ? mAccount.getTrashFolderName() : "" , mAccount.getDraftsFolderName() != null ? mAccount.getDraftsFolderName() : "", mAccount.getSpamFolderName() != null ? mAccount.getSpamFolderName() : "", - mAccount.getOutboxFolderName() != null? mAccount.getOutboxFolderName() : "", + mAccount.getOutboxFolderName() != null ? mAccount.getOutboxFolderName() : "", mAccount.getSentFolderName() != null ? mAccount.getSentFolderName() : "", K9.INBOX, Folder.FolderClass.FIRST_CLASS.name() }); - } - else if (displayMode == Account.FolderMode.FIRST_AND_SECOND_CLASS) - { - cursor = db.rawQuery(baseQuery + " AND ( name = ? OR display_class = ? OR display_class = ? )", new String[] - { + } else if (displayMode == Account.FolderMode.FIRST_AND_SECOND_CLASS) { + cursor = db.rawQuery(baseQuery + " AND ( name = ? OR display_class = ? OR display_class = ? )", new String[] { mAccount.getTrashFolderName() != null ? mAccount.getTrashFolderName() : "" , mAccount.getDraftsFolderName() != null ? mAccount.getDraftsFolderName() : "", mAccount.getSpamFolderName() != null ? mAccount.getSpamFolderName() : "", - mAccount.getOutboxFolderName() != null? mAccount.getOutboxFolderName() : "", + mAccount.getOutboxFolderName() != null ? mAccount.getOutboxFolderName() : "", mAccount.getSentFolderName() != null ? mAccount.getSentFolderName() : "", K9.INBOX, Folder.FolderClass.FIRST_CLASS.name(), Folder.FolderClass.SECOND_CLASS.name() }); - } - else if (displayMode == Account.FolderMode.NOT_SECOND_CLASS) - { - cursor = db.rawQuery(baseQuery + " AND ( name = ? OR display_class != ?)", new String[] - { + } else if (displayMode == Account.FolderMode.NOT_SECOND_CLASS) { + cursor = db.rawQuery(baseQuery + " AND ( name = ? OR display_class != ?)", new String[] { mAccount.getTrashFolderName() != null ? mAccount.getTrashFolderName() : "" , mAccount.getDraftsFolderName() != null ? mAccount.getDraftsFolderName() : "", mAccount.getSpamFolderName() != null ? mAccount.getSpamFolderName() : "", - mAccount.getOutboxFolderName() != null? mAccount.getOutboxFolderName() : "", + mAccount.getOutboxFolderName() != null ? mAccount.getOutboxFolderName() : "", mAccount.getSentFolderName() != null ? mAccount.getSentFolderName() : "", K9.INBOX, Folder.FolderClass.SECOND_CLASS.name() }); - } - else if (displayMode == Account.FolderMode.ALL) - { - cursor = db.rawQuery(baseQuery, new String[] - { + } else if (displayMode == Account.FolderMode.ALL) { + cursor = db.rawQuery(baseQuery, new String[] { mAccount.getTrashFolderName() != null ? mAccount.getTrashFolderName() : "" , mAccount.getDraftsFolderName() != null ? mAccount.getDraftsFolderName() : "", mAccount.getSpamFolderName() != null ? mAccount.getSpamFolderName() : "", - mAccount.getOutboxFolderName() != null? mAccount.getOutboxFolderName() : "", + mAccount.getOutboxFolderName() != null ? mAccount.getOutboxFolderName() : "", mAccount.getSentFolderName() != null ? mAccount.getSentFolderName() : "", }); - } - else - { + } else { Log.e(K9.LOG_TAG, "asked to compute account statistics for an impossible folder mode " + displayMode); stats.unreadMessageCount = 0; stats.flaggedMessageCount = 0; @@ -686,11 +567,8 @@ public class LocalStore extends Store implements Serializable stats.unreadMessageCount = cursor.getInt(0); stats.flaggedMessageCount = cursor.getInt(1); return null; - } - finally - { - if (cursor != null) - { + } finally { + if (cursor != null) { cursor.close(); } } @@ -699,24 +577,17 @@ public class LocalStore extends Store implements Serializable } - public int getFolderCount() throws MessagingException - { - return database.execute(false, new DbCallback() - { + public int getFolderCount() throws MessagingException { + return database.execute(false, new DbCallback() { @Override - public Integer doDbWork(final SQLiteDatabase db) - { + public Integer doDbWork(final SQLiteDatabase db) { Cursor cursor = null; - try - { + try { cursor = db.rawQuery("SELECT COUNT(*) FROM folders", null); cursor.moveToFirst(); return cursor.getInt(0); // folder count - } - finally - { - if (cursor != null) - { + } finally { + if (cursor != null) { cursor.close(); } } @@ -725,75 +596,57 @@ public class LocalStore extends Store implements Serializable } @Override - public LocalFolder getFolder(String name) - { + public LocalFolder getFolder(String name) { return new LocalFolder(name); } // TODO this takes about 260-300ms, seems slow. @Override - public List getPersonalNamespaces(boolean forceListAll) throws MessagingException - { + public List getPersonalNamespaces(boolean forceListAll) throws MessagingException { final List folders = new LinkedList(); - try - { - database.execute(false, new DbCallback>() - { + try { + database.execute(false, new DbCallback < List > () { @Override - public List doDbWork(final SQLiteDatabase db) throws WrappedException - { + public List doDbWork(final SQLiteDatabase db) throws WrappedException { Cursor cursor = null; - try - { - cursor = db.rawQuery("SELECT " +GET_FOLDER_COLS + " FROM folders ORDER BY name ASC", null); - while (cursor.moveToNext()) - { + try { + cursor = db.rawQuery("SELECT " + GET_FOLDER_COLS + " FROM folders ORDER BY name ASC", null); + while (cursor.moveToNext()) { LocalFolder folder = new LocalFolder(cursor.getString(1)); folder.open(cursor.getInt(0), cursor.getString(1), cursor.getInt(2), cursor.getInt(3), cursor.getLong(4), cursor.getString(5), cursor.getString(6), cursor.getLong(7), cursor.getInt(8), cursor.getInt(9), cursor.getInt(10), cursor.getString(11), cursor.getString(12), cursor.getString(13)); folders.add(folder); } return folders; - } - catch (MessagingException e) - { + } catch (MessagingException e) { throw new WrappedException(e); - } - finally - { - if (cursor != null) - { + } finally { + if (cursor != null) { cursor.close(); } } } }); - } - catch (WrappedException e) - { - throw (MessagingException) e.getCause(); + } catch (WrappedException e) { + throw(MessagingException) e.getCause(); } return folders; } @Override - public void checkSettings() throws MessagingException - { + public void checkSettings() throws MessagingException { } - public void delete() throws UnavailableStorageException - { + public void delete() throws UnavailableStorageException { database.delete(); } - public void recreate() throws UnavailableStorageException - { + public void recreate() throws UnavailableStorageException { database.recreate(); } - public void pruneCachedAttachments() throws MessagingException - { + public void pruneCachedAttachments() throws MessagingException { pruneCachedAttachments(false); } @@ -802,30 +655,22 @@ public class LocalStore extends Store implements Serializable * @param force * @throws com.fsck.k9.mail.MessagingException */ - private void pruneCachedAttachments(final boolean force) throws MessagingException - { - database.execute(false, new DbCallback() - { + private void pruneCachedAttachments(final boolean force) throws MessagingException { + database.execute(false, new DbCallback() { @Override - public Void doDbWork(final SQLiteDatabase db) throws WrappedException - { - if (force) - { + public Void doDbWork(final SQLiteDatabase db) throws WrappedException { + if (force) { ContentValues cv = new ContentValues(); cv.putNull("content_uri"); db.update("attachments", cv, null, null); } final StorageManager storageManager = StorageManager.getInstance(mApplication); File[] files = storageManager.getAttachmentDirectory(uUid, database.getStorageProviderId()).listFiles(); - for (File file : files) - { - if (file.exists()) - { - if (!force) - { + for (File file : files) { + if (file.exists()) { + if (!force) { Cursor cursor = null; - try - { + try { cursor = db.query( "attachments", new String[] { "store_data" }, @@ -834,10 +679,8 @@ public class LocalStore extends Store implements Serializable null, null, null); - if (cursor.moveToNext()) - { - if (cursor.getString(0) == null) - { + if (cursor.moveToNext()) { + if (cursor.getString(0) == null) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "Attachment " + file.getAbsolutePath() + " has no store data, not deleting"); /* @@ -847,33 +690,25 @@ public class LocalStore extends Store implements Serializable continue; } } - } - finally - { - if (cursor != null) - { + } finally { + if (cursor != null) { cursor.close(); } } } - if (!force) - { - try - { + if (!force) { + try { ContentValues cv = new ContentValues(); cv.putNull("content_uri"); db.update("attachments", cv, "id = ?", new String[] { file.getName() }); - } - catch (Exception e) - { + } catch (Exception e) { /* * If the row has gone away before we got to mark it not-downloaded that's * okay. */ } } - if (!file.delete()) - { + if (!file.delete()) { file.deleteOnExit(); } } @@ -883,36 +718,28 @@ public class LocalStore extends Store implements Serializable }); } - public void resetVisibleLimits() throws UnavailableStorageException - { + public void resetVisibleLimits() throws UnavailableStorageException { resetVisibleLimits(mAccount.getDisplayCount()); } - public void resetVisibleLimits(int visibleLimit) throws UnavailableStorageException - { + public void resetVisibleLimits(int visibleLimit) throws UnavailableStorageException { final ContentValues cv = new ContentValues(); cv.put("visible_limit", Integer.toString(visibleLimit)); - database.execute(false, new DbCallback() - { + database.execute(false, new DbCallback() { @Override - public Void doDbWork(final SQLiteDatabase db) throws WrappedException - { + public Void doDbWork(final SQLiteDatabase db) throws WrappedException { db.update("folders", cv, null, null); return null; } }); } - public ArrayList getPendingCommands() throws UnavailableStorageException - { - return database.execute(false, new DbCallback>() - { + public ArrayList getPendingCommands() throws UnavailableStorageException { + return database.execute(false, new DbCallback>() { @Override - public ArrayList doDbWork(final SQLiteDatabase db) throws WrappedException - { + public ArrayList doDbWork(final SQLiteDatabase db) throws WrappedException { Cursor cursor = null; - try - { + try { cursor = db.query("pending_commands", new String[] { "id", "command", "arguments" }, null, @@ -921,25 +748,20 @@ public class LocalStore extends Store implements Serializable null, "id ASC"); ArrayList commands = new ArrayList(); - while (cursor.moveToNext()) - { + while (cursor.moveToNext()) { PendingCommand command = new PendingCommand(); command.mId = cursor.getLong(0); command.command = cursor.getString(1); String arguments = cursor.getString(2); command.arguments = arguments.split(","); - for (int i = 0; i < command.arguments.length; i++) - { + for (int i = 0; i < command.arguments.length; i++) { command.arguments[i] = Utility.fastUrlDecode(command.arguments[i]); } commands.add(command); } return commands; - } - finally - { - if (cursor != null) - { + } finally { + if (cursor != null) { cursor.close(); } } @@ -947,73 +769,57 @@ public class LocalStore extends Store implements Serializable }); } - public void addPendingCommand(PendingCommand command) throws UnavailableStorageException - { - try - { - for (int i = 0; i < command.arguments.length; i++) - { + public void addPendingCommand(PendingCommand command) throws UnavailableStorageException { + try { + for (int i = 0; i < command.arguments.length; i++) { command.arguments[i] = URLEncoder.encode(command.arguments[i], "UTF-8"); } final ContentValues cv = new ContentValues(); cv.put("command", command.command); cv.put("arguments", Utility.combine(command.arguments, ',')); - database.execute(false, new DbCallback() - { + database.execute(false, new DbCallback() { @Override - public Void doDbWork(final SQLiteDatabase db) throws WrappedException - { + public Void doDbWork(final SQLiteDatabase db) throws WrappedException { db.insert("pending_commands", "command", cv); return null; } }); - } - catch (UnsupportedEncodingException usee) - { + } catch (UnsupportedEncodingException usee) { throw new Error("Aparently UTF-8 has been lost to the annals of history."); } } - public void removePendingCommand(final PendingCommand command) throws UnavailableStorageException - { - database.execute(false, new DbCallback() - { + public void removePendingCommand(final PendingCommand command) throws UnavailableStorageException { + database.execute(false, new DbCallback() { @Override - public Void doDbWork(final SQLiteDatabase db) throws WrappedException - { + public Void doDbWork(final SQLiteDatabase db) throws WrappedException { db.delete("pending_commands", "id = ?", new String[] { Long.toString(command.mId) }); return null; } }); } - public void removePendingCommands() throws UnavailableStorageException - { - database.execute(false, new DbCallback() - { + public void removePendingCommands() throws UnavailableStorageException { + database.execute(false, new DbCallback() { @Override - public Void doDbWork(final SQLiteDatabase db) throws WrappedException - { + public Void doDbWork(final SQLiteDatabase db) throws WrappedException { db.delete("pending_commands", null, null); return null; } }); } - public static class PendingCommand - { + public static class PendingCommand { private long mId; public String command; public String[] arguments; @Override - public String toString() - { + public String toString() { StringBuffer sb = new StringBuffer(); sb.append(command); sb.append(": "); - for (String argument : arguments) - { + for (String argument : arguments) { sb.append(", "); sb.append(argument); //sb.append("\n"); @@ -1023,33 +829,27 @@ public class LocalStore extends Store implements Serializable } @Override - public boolean isMoveCapable() - { + public boolean isMoveCapable() { return true; } @Override - public boolean isCopyCapable() - { + public boolean isCopyCapable() { return true; } public Message[] searchForMessages(MessageRetrievalListener listener, String[] queryFields, String queryString, - List folders, Message[] messages, final Flag[] requiredFlags, final Flag[] forbiddenFlags) throws MessagingException - { + List folders, Message[] messages, final Flag[] requiredFlags, final Flag[] forbiddenFlags) throws MessagingException { List args = new LinkedList(); StringBuilder whereClause = new StringBuilder(); - if (queryString != null && queryString.length() > 0) - { + if (queryString != null && queryString.length() > 0) { boolean anyAdded = false; - String likeString = "%"+queryString+"%"; + String likeString = "%" + queryString + "%"; whereClause.append(" AND ("); - for (String queryField : queryFields) - { + for (String queryField : queryFields) { - if (anyAdded) - { + if (anyAdded) { whereClause.append(" OR "); } whereClause.append(queryField).append(" LIKE ? "); @@ -1060,14 +860,11 @@ public class LocalStore extends Store implements Serializable whereClause.append(" )"); } - if (folders != null && folders.size() > 0) - { + if (folders != null && folders.size() > 0) { whereClause.append(" AND folder_id in ("); boolean anyAdded = false; - for (LocalFolder folder : folders) - { - if (anyAdded) - { + for (LocalFolder folder : folders) { + if (anyAdded) { whereClause.append(","); } anyAdded = true; @@ -1076,14 +873,11 @@ public class LocalStore extends Store implements Serializable } whereClause.append(" )"); } - if (messages != null && messages.length > 0) - { + if (messages != null && messages.length > 0) { whereClause.append(" AND ( "); boolean anyAdded = false; - for (Message message : messages) - { - if (anyAdded) - { + for (Message message : messages) { + if (anyAdded) { whereClause.append(" OR "); } anyAdded = true; @@ -1093,14 +887,11 @@ public class LocalStore extends Store implements Serializable } whereClause.append(" )"); } - if (forbiddenFlags != null && forbiddenFlags.length > 0) - { + if (forbiddenFlags != null && forbiddenFlags.length > 0) { whereClause.append(" AND ("); boolean anyAdded = false; - for (Flag flag : forbiddenFlags) - { - if (anyAdded) - { + for (Flag flag : forbiddenFlags) { + if (anyAdded) { whereClause.append(" AND "); } anyAdded = true; @@ -1110,14 +901,11 @@ public class LocalStore extends Store implements Serializable } whereClause.append(" )"); } - if (requiredFlags != null && requiredFlags.length > 0) - { + if (requiredFlags != null && requiredFlags.length > 0) { whereClause.append(" AND ("); boolean anyAdded = false; - for (Flag flag : requiredFlags) - { - if (anyAdded) - { + for (Flag flag : requiredFlags) { + if (anyAdded) { whereClause.append(" OR "); } anyAdded = true; @@ -1128,8 +916,7 @@ public class LocalStore extends Store implements Serializable whereClause.append(" )"); } - if (K9.DEBUG) - { + if (K9.DEBUG) { Log.v(K9.LOG_TAG, "whereClause = " + whereClause.toString()); Log.v(K9.LOG_TAG, "args = " + args); } @@ -1150,28 +937,22 @@ public class LocalStore extends Store implements Serializable final MessageRetrievalListener listener, final LocalFolder folder, final String queryString, final String[] placeHolders - ) throws MessagingException - { + ) throws MessagingException { final ArrayList messages = new ArrayList(); - final int j = database.execute(false, new DbCallback() - { + final int j = database.execute(false, new DbCallback() { @Override - public Integer doDbWork(final SQLiteDatabase db) throws WrappedException - { + public Integer doDbWork(final SQLiteDatabase db) throws WrappedException { Cursor cursor = null; int i = 0; - try - { + try { cursor = db.rawQuery(queryString + " LIMIT 10", placeHolders); - while (cursor.moveToNext()) - { + while (cursor.moveToNext()) { LocalMessage message = new LocalMessage(null, folder); message.populateFromGetMessageCursor(cursor); messages.add(message); - if (listener != null) - { + if (listener != null) { listener.messageFinished(message, i, -1); } i++; @@ -1179,35 +960,27 @@ public class LocalStore extends Store implements Serializable cursor.close(); cursor = db.rawQuery(queryString + " LIMIT -1 OFFSET 10", placeHolders); - while (cursor.moveToNext()) - { + while (cursor.moveToNext()) { LocalMessage message = new LocalMessage(null, folder); message.populateFromGetMessageCursor(cursor); messages.add(message); - if (listener != null) - { + if (listener != null) { listener.messageFinished(message, i, -1); } i++; } - } - catch (Exception e) - { - Log.d(K9.LOG_TAG,"Got an exception "+e); - } - finally - { - if (cursor != null) - { + } catch (Exception e) { + Log.d(K9.LOG_TAG, "Got an exception " + e); + } finally { + if (cursor != null) { cursor.close(); } } return i; } }); - if (listener != null) - { + if (listener != null) { listener.messagesFinished(j); } @@ -1215,16 +988,12 @@ public class LocalStore extends Store implements Serializable } - public String getAttachmentType(final String attachmentId) throws UnavailableStorageException - { - return database.execute(false, new DbCallback() - { + public String getAttachmentType(final String attachmentId) throws UnavailableStorageException { + return database.execute(false, new DbCallback() { @Override - public String doDbWork(final SQLiteDatabase db) throws WrappedException - { + public String doDbWork(final SQLiteDatabase db) throws WrappedException { Cursor cursor = null; - try - { + try { cursor = db.query( "attachments", new String[] { "mime_type", "name" }, @@ -1238,16 +1007,12 @@ public class LocalStore extends Store implements Serializable String name = cursor.getString(1); cursor.close(); - if (MimeUtility.DEFAULT_ATTACHMENT_MIME_TYPE.equals(type)) - { + if (MimeUtility.DEFAULT_ATTACHMENT_MIME_TYPE.equals(type)) { type = MimeUtility.getMimeTypeByExtension(name); } return type; - } - finally - { - if (cursor != null) - { + } finally { + if (cursor != null) { cursor.close(); } } @@ -1255,18 +1020,14 @@ public class LocalStore extends Store implements Serializable }); } - public AttachmentInfo getAttachmentInfo(final String attachmentId) throws UnavailableStorageException - { - return database.execute(false, new DbCallback() - { + public AttachmentInfo getAttachmentInfo(final String attachmentId) throws UnavailableStorageException { + return database.execute(false, new DbCallback() { @Override - public AttachmentInfo doDbWork(final SQLiteDatabase db) throws WrappedException - { + public AttachmentInfo doDbWork(final SQLiteDatabase db) throws WrappedException { String name; int size; Cursor cursor = null; - try - { + try { cursor = db.query( "attachments", new String[] { "name", "size" }, @@ -1275,8 +1036,7 @@ public class LocalStore extends Store implements Serializable null, null, null); - if (!cursor.moveToFirst()) - { + if (!cursor.moveToFirst()) { return null; } name = cursor.getString(0); @@ -1285,11 +1045,8 @@ public class LocalStore extends Store implements Serializable attachmentInfo.name = name; attachmentInfo.size = size; return attachmentInfo; - } - finally - { - if (cursor != null) - { + } finally { + if (cursor != null) { cursor.close(); } } @@ -1297,56 +1054,43 @@ public class LocalStore extends Store implements Serializable }); } - public static class AttachmentInfo - { + public static class AttachmentInfo { public String name; public int size; } - public void createFolders(final List foldersToCreate, final int visibleLimit) throws UnavailableStorageException - { - database.execute(true, new DbCallback() - { + public void createFolders(final List foldersToCreate, final int visibleLimit) throws UnavailableStorageException { + database.execute(true, new DbCallback() { @Override - public Void doDbWork(final SQLiteDatabase db) throws WrappedException - { - for (LocalFolder folder : foldersToCreate) - { + public Void doDbWork(final SQLiteDatabase db) throws WrappedException { + for (LocalFolder folder : foldersToCreate) { String name = folder.getName(); final LocalFolder.PreferencesHolder prefHolder = folder.new PreferencesHolder(); // When created, special folders should always be displayed // inbox should be integrated // and the inbox and drafts folders should be syncced by default - if (mAccount.isSpecialFolder(name)) - { + if (mAccount.isSpecialFolder(name)) { prefHolder.inTopGroup = true; prefHolder.displayClass = LocalFolder.FolderClass.FIRST_CLASS; - if (name.equalsIgnoreCase(K9.INBOX)) - { + if (name.equalsIgnoreCase(K9.INBOX)) { prefHolder.integrate = true; prefHolder.pushClass = LocalFolder.FolderClass.FIRST_CLASS; - } - else - { + } else { prefHolder.pushClass = LocalFolder.FolderClass.INHERITED; } - if ( name.equalsIgnoreCase(K9.INBOX) || - name.equalsIgnoreCase(mAccount.getDraftsFolderName()) ) - { + if (name.equalsIgnoreCase(K9.INBOX) || + name.equalsIgnoreCase(mAccount.getDraftsFolderName())) { prefHolder.syncClass = LocalFolder.FolderClass.FIRST_CLASS; - } - else - { + } else { prefHolder.syncClass = LocalFolder.FolderClass.NO_CLASS; } } folder.refresh(name, prefHolder); // Recover settings from Preferences - db.execSQL("INSERT INTO folders (name, visible_limit, top_group, display_class, poll_class, push_class, integrate) VALUES (?, ?, ?, ?, ?, ?, ?)", new Object[] - { - name, + db.execSQL("INSERT INTO folders (name, visible_limit, top_group, display_class, poll_class, push_class, integrate) VALUES (?, ?, ?, ?, ?, ?, ?)", new Object[] { + name, visibleLimit, prefHolder.inTopGroup ? 1 : 0, prefHolder.displayClass.name(), @@ -1361,8 +1105,7 @@ public class LocalStore extends Store implements Serializable }); } - public class LocalFolder extends Folder implements Serializable - { + public class LocalFolder extends Folder implements Serializable { /** * */ @@ -1383,13 +1126,11 @@ public class LocalStore extends Store implements Serializable // know whether or not an unread message added to the local folder is actually "new" or not. private Integer mLastUid = null; - public LocalFolder(String name) - { + public LocalFolder(String name) { super(LocalStore.this.mAccount); this.mName = name; - if (K9.INBOX.equals(getName())) - { + if (K9.INBOX.equals(getName())) { mSyncClass = FolderClass.FIRST_CLASS; mPushClass = FolderClass.FIRST_CLASS; mInTopGroup = true; @@ -1398,83 +1139,60 @@ public class LocalStore extends Store implements Serializable } - public LocalFolder(long id) - { + public LocalFolder(long id) { super(LocalStore.this.mAccount); this.mFolderId = id; } - public long getId() - { + public long getId() { return mFolderId; } @Override - public void open(final OpenMode mode) throws MessagingException - { - if (isOpen()) - { + public void open(final OpenMode mode) throws MessagingException { + if (isOpen()) { return; } - try - { - database.execute(false, new DbCallback() - { + try { + database.execute(false, new DbCallback() { @Override - public Void doDbWork(final SQLiteDatabase db) throws WrappedException - { + public Void doDbWork(final SQLiteDatabase db) throws WrappedException { Cursor cursor = null; - try - { + try { String baseQuery = "SELECT " + GET_FOLDER_COLS + " FROM folders "; - if (mName != null) - { + if (mName != null) { cursor = db.rawQuery(baseQuery + "where folders.name = ?", new String[] { mName }); - } - else - { + } else { cursor = db.rawQuery(baseQuery + "where folders.id = ?", new String[] { Long.toString(mFolderId) }); } - if (cursor.moveToFirst()) - { + if (cursor.moveToFirst()) { int folderId = cursor.getInt(0); - if (folderId > 0) - { + if (folderId > 0) { open(folderId, cursor.getString(1), cursor.getInt(2), cursor.getInt(3), cursor.getLong(4), cursor.getString(5), cursor.getString(6), cursor.getLong(7), cursor.getInt(8), cursor.getInt(9), cursor.getInt(10), cursor.getString(11), cursor.getString(12), cursor.getString(13)); } - } - else - { + } else { Log.w(K9.LOG_TAG, "Creating folder " + getName() + " with existing id " + getId()); create(FolderType.HOLDS_MESSAGES); open(mode); } - } - catch (MessagingException e) - { + } catch (MessagingException e) { throw new WrappedException(e); - } - finally - { - if (cursor != null) - { + } finally { + if (cursor != null) { cursor.close(); } } return null; } }); - } - catch (WrappedException e) - { - throw (MessagingException) e.getCause(); + } catch (WrappedException e) { + throw(MessagingException) e.getCause(); } } - private void open(int id, String name, int unreadCount, int visibleLimit, long lastChecked, String status, String pushState, long lastPushed, int flaggedCount, int integrate, int topGroup, String syncClass, String pushClass, String displayClass) throws MessagingException - { + private void open(int id, String name, int unreadCount, int visibleLimit, long lastChecked, String status, String pushState, long lastPushed, int flaggedCount, int integrate, int topGroup, String syncClass, String pushClass, String displayClass) throws MessagingException { mFolderId = id; mName = name; mUnreadMessageCount = unreadCount; @@ -1486,7 +1204,7 @@ public class LocalStore extends Store implements Serializable // does a DB update on setLastChecked super.setLastChecked(lastChecked); super.setLastPush(lastPushed); - mInTopGroup = topGroup ==1 ? true : false; + mInTopGroup = topGroup == 1 ? true : false; mIntegrate = integrate == 1 ? true : false; String noClass = FolderClass.NO_CLASS.toString(); mDisplayClass = Folder.FolderClass.valueOf((displayClass == null) ? noClass : displayClass); @@ -1496,52 +1214,39 @@ public class LocalStore extends Store implements Serializable } @Override - public boolean isOpen() - { + public boolean isOpen() { return (mFolderId != -1 && mName != null); } @Override - public OpenMode getMode() - { + public OpenMode getMode() { return OpenMode.READ_WRITE; } @Override - public String getName() - { + public String getName() { return mName; } @Override - public boolean exists() throws MessagingException - { - return database.execute(false, new DbCallback() - { + public boolean exists() throws MessagingException { + return database.execute(false, new DbCallback() { @Override - public Boolean doDbWork(final SQLiteDatabase db) throws WrappedException - { + public Boolean doDbWork(final SQLiteDatabase db) throws WrappedException { Cursor cursor = null; - try - { + try { cursor = db.rawQuery("SELECT id FROM folders " + "where folders.name = ?", new String[] { LocalFolder.this .getName() }); - if (cursor.moveToFirst()) - { + if (cursor.moveToFirst()) { int folderId = cursor.getInt(0); return (folderId > 0); - } - else - { + } else { return false; } - } - finally - { - if (cursor != null) - { + } finally { + if (cursor != null) { cursor.close(); } } @@ -1550,16 +1255,13 @@ public class LocalStore extends Store implements Serializable } @Override - public boolean create(FolderType type) throws MessagingException - { + public boolean create(FolderType type) throws MessagingException { return create(type, mAccount.getDisplayCount()); } @Override - public boolean create(FolderType type, final int visibleLimit) throws MessagingException - { - if (exists()) - { + public boolean create(FolderType type, final int visibleLimit) throws MessagingException { + if (exists()) { throw new MessagingException("Folder " + mName + " already exists."); } List foldersToCreate = new ArrayList(1); @@ -1569,8 +1271,7 @@ public class LocalStore extends Store implements Serializable return true; } - private class PreferencesHolder - { + private class PreferencesHolder { FolderClass displayClass = mDisplayClass; FolderClass syncClass = mSyncClass; FolderClass pushClass = mPushClass; @@ -1579,130 +1280,98 @@ public class LocalStore extends Store implements Serializable } @Override - public void close() - { + public void close() { mFolderId = -1; } @Override - public int getMessageCount() throws MessagingException - { - try - { - return database.execute(false, new DbCallback() - { + public int getMessageCount() throws MessagingException { + try { + return database.execute(false, new DbCallback() { @Override - public Integer doDbWork(final SQLiteDatabase db) throws WrappedException - { - try - { + public Integer doDbWork(final SQLiteDatabase db) throws WrappedException { + try { open(OpenMode.READ_WRITE); - } - catch (MessagingException e) - { + } catch (MessagingException e) { throw new WrappedException(e); } Cursor cursor = null; - try - { + try { cursor = db.rawQuery("SELECT COUNT(*) FROM messages WHERE folder_id = ?", - new String[] - { + new String[] { Long.toString(mFolderId) }); cursor.moveToFirst(); return cursor.getInt(0); //messagecount - } - finally - { - if (cursor != null) - { + } finally { + if (cursor != null) { cursor.close(); } } } }); - } - catch (WrappedException e) - { - throw (MessagingException) e.getCause(); + } catch (WrappedException e) { + throw(MessagingException) e.getCause(); } } @Override - public int getUnreadMessageCount() throws MessagingException - { + public int getUnreadMessageCount() throws MessagingException { open(OpenMode.READ_WRITE); return mUnreadMessageCount; } @Override - public int getFlaggedMessageCount() throws MessagingException - { + public int getFlaggedMessageCount() throws MessagingException { open(OpenMode.READ_WRITE); return mFlaggedMessageCount; } - public void setUnreadMessageCount(final int unreadMessageCount) throws MessagingException - { + public void setUnreadMessageCount(final int unreadMessageCount) throws MessagingException { mUnreadMessageCount = Math.max(0, unreadMessageCount); - updateFolderColumn( "unread_count", mUnreadMessageCount); + updateFolderColumn("unread_count", mUnreadMessageCount); } - public void setFlaggedMessageCount(final int flaggedMessageCount) throws MessagingException - { + public void setFlaggedMessageCount(final int flaggedMessageCount) throws MessagingException { mFlaggedMessageCount = Math.max(0, flaggedMessageCount); - updateFolderColumn( "flagged_count", mFlaggedMessageCount); + updateFolderColumn("flagged_count", mFlaggedMessageCount); } @Override - public void setLastChecked(final long lastChecked) throws MessagingException - { - try - { + public void setLastChecked(final long lastChecked) throws MessagingException { + try { open(OpenMode.READ_WRITE); LocalFolder.super.setLastChecked(lastChecked); - } - catch (MessagingException e) - { + } catch (MessagingException e) { throw new WrappedException(e); } - updateFolderColumn( "last_updated", lastChecked); + updateFolderColumn("last_updated", lastChecked); } @Override - public void setLastPush(final long lastChecked) throws MessagingException - { - try - { + public void setLastPush(final long lastChecked) throws MessagingException { + try { open(OpenMode.READ_WRITE); LocalFolder.super.setLastPush(lastChecked); - } - catch (MessagingException e) - { + } catch (MessagingException e) { throw new WrappedException(e); } - updateFolderColumn( "last_pushed", lastChecked); + updateFolderColumn("last_pushed", lastChecked); } - public int getVisibleLimit() throws MessagingException - { + public int getVisibleLimit() throws MessagingException { open(OpenMode.READ_WRITE); return mVisibleLimit; } - public void purgeToVisibleLimit(MessageRemovalListener listener) throws MessagingException - { - if ( mVisibleLimit == 0) - { + public void purgeToVisibleLimit(MessageRemovalListener listener) throws MessagingException { + if (mVisibleLimit == 0) { return ; } open(OpenMode.READ_WRITE); Message[] messages = getMessages(null, false); - for (int i = mVisibleLimit; i < messages.length; i++) - { - if (listener != null) - { + for (int i = mVisibleLimit; i < messages.length; i++) { + if (listener != null) { listener.messageRemoved(messages[i]); } messages[i].destroy(); @@ -1711,146 +1380,113 @@ public class LocalStore extends Store implements Serializable } - public void setVisibleLimit(final int visibleLimit) throws MessagingException - { + public void setVisibleLimit(final int visibleLimit) throws MessagingException { mVisibleLimit = visibleLimit; - updateFolderColumn( "visible_limit", mVisibleLimit); + updateFolderColumn("visible_limit", mVisibleLimit); } @Override - public void setStatus(final String status) throws MessagingException - { - updateFolderColumn( "status", status); + public void setStatus(final String status) throws MessagingException { + updateFolderColumn("status", status); } - public void setPushState(final String pushState) throws MessagingException - { + public void setPushState(final String pushState) throws MessagingException { mPushState = pushState; updateFolderColumn("push_state", pushState); } - private void updateFolderColumn(final String column, final Object value) throws MessagingException - { - try - { - database.execute(false, new DbCallback() - { + private void updateFolderColumn(final String column, final Object value) throws MessagingException { + try { + database.execute(false, new DbCallback() { @Override - public Void doDbWork(final SQLiteDatabase db) throws WrappedException - { - try - { + public Void doDbWork(final SQLiteDatabase db) throws WrappedException { + try { open(OpenMode.READ_WRITE); - } - catch (MessagingException e) - { + } catch (MessagingException e) { throw new WrappedException(e); } - db.execSQL("UPDATE folders SET "+column+" = ? WHERE id = ?", new Object[] { value, mFolderId }); + db.execSQL("UPDATE folders SET " + column + " = ? WHERE id = ?", new Object[] { value, mFolderId }); return null; } }); - } - catch (WrappedException e) - { - throw (MessagingException) e.getCause(); + } catch (WrappedException e) { + throw(MessagingException) e.getCause(); } } - public String getPushState() - { + public String getPushState() { return mPushState; } @Override - public FolderClass getDisplayClass() - { + public FolderClass getDisplayClass() { return mDisplayClass; } @Override - public FolderClass getSyncClass() - { - if (FolderClass.INHERITED == mSyncClass) - { + public FolderClass getSyncClass() { + if (FolderClass.INHERITED == mSyncClass) { return getDisplayClass(); - } - else - { + } else { return mSyncClass; } } - public FolderClass getRawSyncClass() - { + public FolderClass getRawSyncClass() { return mSyncClass; } @Override - public FolderClass getPushClass() - { - if (FolderClass.INHERITED == mPushClass) - { + public FolderClass getPushClass() { + if (FolderClass.INHERITED == mPushClass) { return getSyncClass(); - } - else - { + } else { return mPushClass; } } - public FolderClass getRawPushClass() - { + public FolderClass getRawPushClass() { return mPushClass; } - public void setDisplayClass(FolderClass displayClass) throws MessagingException - { + public void setDisplayClass(FolderClass displayClass) throws MessagingException { mDisplayClass = displayClass; - updateFolderColumn( "display_class", mDisplayClass.name()); + updateFolderColumn("display_class", mDisplayClass.name()); } - public void setSyncClass(FolderClass syncClass) throws MessagingException - { + public void setSyncClass(FolderClass syncClass) throws MessagingException { mSyncClass = syncClass; - updateFolderColumn( "poll_class", mSyncClass.name()); + updateFolderColumn("poll_class", mSyncClass.name()); } - public void setPushClass(FolderClass pushClass) throws MessagingException - { + public void setPushClass(FolderClass pushClass) throws MessagingException { mPushClass = pushClass; - updateFolderColumn( "push_class", mPushClass.name()); + updateFolderColumn("push_class", mPushClass.name()); } - public boolean isIntegrate() - { + public boolean isIntegrate() { return mIntegrate; } - public void setIntegrate(boolean integrate) throws MessagingException - { + public void setIntegrate(boolean integrate) throws MessagingException { mIntegrate = integrate; - updateFolderColumn( "integrate", mIntegrate ? 1 : 0 ); + updateFolderColumn("integrate", mIntegrate ? 1 : 0); } - private String getPrefId(String name) - { - if (prefId == null) - { + private String getPrefId(String name) { + if (prefId == null) { prefId = uUid + "." + name; } return prefId; } - private String getPrefId() throws MessagingException - { + private String getPrefId() throws MessagingException { open(OpenMode.READ_WRITE); return getPrefId(mName); } - public void delete() throws MessagingException - { + public void delete() throws MessagingException { String id = getPrefId(); SharedPreferences.Editor editor = LocalStore.this.getPreferences().edit(); @@ -1864,42 +1500,31 @@ public class LocalStore extends Store implements Serializable editor.commit(); } - public void save() throws MessagingException - { + public void save() throws MessagingException { SharedPreferences.Editor editor = LocalStore.this.getPreferences().edit(); save(editor); editor.commit(); } - public void save(SharedPreferences.Editor editor) throws MessagingException - { + public void save(SharedPreferences.Editor editor) throws MessagingException { String id = getPrefId(); // there can be a lot of folders. For the defaults, let's not save prefs, saving space, except for INBOX - if (mDisplayClass == FolderClass.NO_CLASS && !K9.INBOX.equals(getName())) - { + if (mDisplayClass == FolderClass.NO_CLASS && !K9.INBOX.equals(getName())) { editor.remove(id + ".displayMode"); - } - else - { + } else { editor.putString(id + ".displayMode", mDisplayClass.name()); } - if (mSyncClass == FolderClass.INHERITED && !K9.INBOX.equals(getName())) - { + if (mSyncClass == FolderClass.INHERITED && !K9.INBOX.equals(getName())) { editor.remove(id + ".syncMode"); - } - else - { + } else { editor.putString(id + ".syncMode", mSyncClass.name()); } - if (mPushClass == FolderClass.SECOND_CLASS && !K9.INBOX.equals(getName())) - { + if (mPushClass == FolderClass.SECOND_CLASS && !K9.INBOX.equals(getName())) { editor.remove(id + ".pushMode"); - } - else - { + } else { editor.putString(id + ".pushMode", mPushClass.name()); } editor.putBoolean(id + ".inTopGroup", mInTopGroup); @@ -1908,52 +1533,39 @@ public class LocalStore extends Store implements Serializable } - public void refresh(String name, PreferencesHolder prefHolder) - { + public void refresh(String name, PreferencesHolder prefHolder) { String id = getPrefId(name); SharedPreferences preferences = LocalStore.this.getPreferences(); - try - { + try { prefHolder.displayClass = FolderClass.valueOf(preferences.getString(id + ".displayMode", - prefHolder.displayClass.name())); - } - catch (Exception e) - { + prefHolder.displayClass.name())); + } catch (Exception e) { Log.e(K9.LOG_TAG, "Unable to load displayMode for " + getName(), e); } - if (prefHolder.displayClass == FolderClass.NONE) - { + if (prefHolder.displayClass == FolderClass.NONE) { prefHolder.displayClass = FolderClass.NO_CLASS; } - try - { + try { prefHolder.syncClass = FolderClass.valueOf(preferences.getString(id + ".syncMode", - prefHolder.syncClass.name())); - } - catch (Exception e) - { + prefHolder.syncClass.name())); + } catch (Exception e) { Log.e(K9.LOG_TAG, "Unable to load syncMode for " + getName(), e); } - if (prefHolder.syncClass == FolderClass.NONE) - { + if (prefHolder.syncClass == FolderClass.NONE) { prefHolder.syncClass = FolderClass.INHERITED; } - try - { + try { prefHolder.pushClass = FolderClass.valueOf(preferences.getString(id + ".pushMode", - prefHolder.pushClass.name())); - } - catch (Exception e) - { + prefHolder.pushClass.name())); + } catch (Exception e) { Log.e(K9.LOG_TAG, "Unable to load pushMode for " + getName(), e); } - if (prefHolder.pushClass == FolderClass.NONE) - { + if (prefHolder.pushClass == FolderClass.NONE) { prefHolder.pushClass = FolderClass.INHERITED; } prefHolder.inTopGroup = preferences.getBoolean(id + ".inTopGroup", prefHolder.inTopGroup); @@ -1963,28 +1575,20 @@ public class LocalStore extends Store implements Serializable @Override public void fetch(final Message[] messages, final FetchProfile fp, final MessageRetrievalListener listener) - throws MessagingException - { - try - { - database.execute(false, new DbCallback() - { + throws MessagingException { + try { + database.execute(false, new DbCallback() { @Override - public Void doDbWork(final SQLiteDatabase db) throws WrappedException - { - try - { + public Void doDbWork(final SQLiteDatabase db) throws WrappedException { + try { open(OpenMode.READ_WRITE); - if (fp.contains(FetchProfile.Item.BODY)) - { - for (Message message : messages) - { + if (fp.contains(FetchProfile.Item.BODY)) { + for (Message message : messages) { LocalMessage localMessage = (LocalMessage)message; Cursor cursor = null; MimeMultipart mp = new MimeMultipart(); mp.setSubType("mixed"); - try - { + try { cursor = db.rawQuery("SELECT html_content, text_content, mime_type FROM messages " + "WHERE id = ?", new String[] { Long.toString(localMessage.mId) }); @@ -1992,19 +1596,16 @@ public class LocalStore extends Store implements Serializable String htmlContent = cursor.getString(0); String textContent = cursor.getString(1); String mimeType = cursor.getString(2); - if (mimeType != null && mimeType.toLowerCase().startsWith("multipart/")) - { + if (mimeType != null && mimeType.toLowerCase().startsWith("multipart/")) { // If this is a multipart message, preserve both text // and html parts, as well as the subtype. mp.setSubType(mimeType.toLowerCase().replaceFirst("^multipart/", "")); - if (textContent != null) - { + if (textContent != null) { LocalTextBody body = new LocalTextBody(textContent, htmlContent); MimeBodyPart bp = new MimeBodyPart(body, "text/plain"); mp.addBodyPart(bp); } - if (htmlContent != null) - { + if (htmlContent != null) { TextBody body = new TextBody(htmlContent); MimeBodyPart bp = new MimeBodyPart(body, "text/html"); mp.addBodyPart(bp); @@ -2016,74 +1617,55 @@ public class LocalStore extends Store implements Serializable // If it turns out that this is the only part in the parent // MimeMultipart, it'll get fixed below before we attach to // the message. - if (textContent != null && htmlContent != null && !mimeType.equalsIgnoreCase("multipart/alternative")) - { + if (textContent != null && htmlContent != null && !mimeType.equalsIgnoreCase("multipart/alternative")) { MimeMultipart alternativeParts = mp; alternativeParts.setSubType("alternative"); mp = new MimeMultipart(); mp.addBodyPart(new MimeBodyPart(alternativeParts)); } - } - else if (mimeType != null && mimeType.equalsIgnoreCase("text/plain")) - { + } else if (mimeType != null && mimeType.equalsIgnoreCase("text/plain")) { // If it's text, add only the plain part. The MIME // container will drop away below. - if (textContent != null) - { + if (textContent != null) { LocalTextBody body = new LocalTextBody(textContent, htmlContent); MimeBodyPart bp = new MimeBodyPart(body, "text/plain"); mp.addBodyPart(bp); } - } - else if (mimeType != null && mimeType.equalsIgnoreCase("text/html")) - { + } else if (mimeType != null && mimeType.equalsIgnoreCase("text/html")) { // If it's html, add only the html part. The MIME // container will drop away below. - if (htmlContent != null) - { + if (htmlContent != null) { TextBody body = new TextBody(htmlContent); MimeBodyPart bp = new MimeBodyPart(body, "text/html"); mp.addBodyPart(bp); } - } - else - { + } else { // MIME type not set. Grab whatever part we can get, // with Text taking precedence. This preserves pre-HTML // composition behaviour. - if (textContent != null) - { + if (textContent != null) { LocalTextBody body = new LocalTextBody(textContent, htmlContent); MimeBodyPart bp = new MimeBodyPart(body, "text/plain"); mp.addBodyPart(bp); - } - else if (htmlContent != null) - { + } else if (htmlContent != null) { TextBody body = new TextBody(htmlContent); MimeBodyPart bp = new MimeBodyPart(body, "text/html"); mp.addBodyPart(bp); } } - } - catch (Exception e) - { + } catch (Exception e) { Log.e(K9.LOG_TAG, "Exception fetching message:", e); - } - finally - { - if (cursor != null) - { + } finally { + if (cursor != null) { cursor.close(); } } - try - { + try { cursor = db.query( "attachments", - new String[] - { + new String[] { "id", "size", "name", @@ -2099,8 +1681,7 @@ public class LocalStore extends Store implements Serializable null, null); - while (cursor.moveToNext()) - { + while (cursor.moveToNext()) { long id = cursor.getLong(0); int size = cursor.getInt(1); String name = cursor.getString(2); @@ -2111,13 +1692,11 @@ public class LocalStore extends Store implements Serializable String contentDisposition = cursor.getString(7); Body body = null; - if (contentDisposition == null) - { + if (contentDisposition == null) { contentDisposition = "attachment"; } - if (contentUri != null) - { + if (contentUri != null) { body = new LocalAttachmentBody(Uri.parse(contentUri), mApplication); } MimeBodyPart bp = new LocalAttachmentBodyPart(body, id); @@ -2141,58 +1720,46 @@ public class LocalStore extends Store implements Serializable mp.addBodyPart(bp); } - } - finally - { - if (cursor != null) - { + } finally { + if (cursor != null) { cursor.close(); } } - if (mp.getCount() == 0) - { + if (mp.getCount() == 0) { // If we have no body, remove the container and create a // dummy plain text body. This check helps prevents us from // triggering T_MIME_NO_TEXT and T_TVD_MIME_NO_HEADERS // SpamAssassin rules. localMessage.setHeader(MimeHeader.HEADER_CONTENT_TYPE, "text/plain"); localMessage.setBody(new TextBody("")); - } - else if (mp.getCount() == 1 && (mp.getBodyPart(0) instanceof LocalAttachmentBodyPart) == false ) + } else if (mp.getCount() == 1 && (mp.getBodyPart(0) instanceof LocalAttachmentBodyPart) == false) { // If we have only one part, drop the MimeMultipart container. BodyPart part = mp.getBodyPart(0); localMessage.setHeader(MimeHeader.HEADER_CONTENT_TYPE, part.getContentType()); localMessage.setBody(part.getBody()); - } - else - { + } else { // Otherwise, attach the MimeMultipart to the message. localMessage.setBody(mp); } } } - } - catch (MessagingException e) - { + } catch (MessagingException e) { throw new WrappedException(e); } return null; } }); - } - catch (WrappedException e) - { - throw (MessagingException) e.getCause(); + } catch (WrappedException e) { + throw(MessagingException) e.getCause(); } } @Override public Message[] getMessages(int start, int end, Date earliestDate, MessageRetrievalListener listener) - throws MessagingException - { + throws MessagingException { open(OpenMode.READ_WRITE); throw new MessagingException( "LocalStore.getMessages(int, int, MessageRetrievalListener) not yet implemented"); @@ -2206,28 +1773,21 @@ public class LocalStore extends Store implements Serializable * The messages whose headers should be loaded. * @throws UnavailableStorageException */ - private void populateHeaders(final List messages) throws UnavailableStorageException - { - database.execute(false, new DbCallback() - { + private void populateHeaders(final List messages) throws UnavailableStorageException { + database.execute(false, new DbCallback() { @Override - public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException - { + public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException { Cursor cursor = null; - if (messages.size() == 0) - { + if (messages.size() == 0) { return null; } - try - { + try { Map popMessages = new HashMap(); List ids = new ArrayList(); StringBuffer questions = new StringBuffer(); - for (int i = 0; i < messages.size(); i++) - { - if (i != 0) - { + for (int i = 0; i < messages.size(); i++) { + if (i != 0) { questions.append(", "); } questions.append("?"); @@ -2243,19 +1803,15 @@ public class LocalStore extends Store implements Serializable ids.toArray(EMPTY_STRING_ARRAY)); - while (cursor.moveToNext()) - { + while (cursor.moveToNext()) { Long id = cursor.getLong(0); String name = cursor.getString(1); String value = cursor.getString(2); //Log.i(K9.LOG_TAG, "Retrieved header name= " + name + ", value = " + value + " for message " + id); popMessages.get(id).addHeader(name, value); } - } - finally - { - if (cursor != null) - { + } finally { + if (cursor != null) { cursor.close(); } } @@ -2265,77 +1821,56 @@ public class LocalStore extends Store implements Serializable } @Override - public Message getMessage(final String uid) throws MessagingException - { - try - { - return database.execute(false, new DbCallback() - { + public Message getMessage(final String uid) throws MessagingException { + try { + return database.execute(false, new DbCallback() { @Override - public Message doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException - { - try - { + public Message doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException { + try { open(OpenMode.READ_WRITE); LocalMessage message = new LocalMessage(uid, LocalFolder.this); Cursor cursor = null; - try - { + try { cursor = db.rawQuery( "SELECT " + GET_MESSAGES_COLS + "FROM messages WHERE uid = ? AND folder_id = ?", - new String[] - { + new String[] { message.getUid(), Long.toString(mFolderId) }); - if (!cursor.moveToNext()) - { + if (!cursor.moveToNext()) { return null; } message.populateFromGetMessageCursor(cursor); - } - finally - { - if (cursor != null) - { + } finally { + if (cursor != null) { cursor.close(); } } return message; - } - catch (MessagingException e) - { + } catch (MessagingException e) { throw new WrappedException(e); } } }); - } - catch (WrappedException e) - { - throw (MessagingException) e.getCause(); + } catch (WrappedException e) { + throw(MessagingException) e.getCause(); } } @Override - public Message[] getMessages(MessageRetrievalListener listener) throws MessagingException - { + public Message[] getMessages(MessageRetrievalListener listener) throws MessagingException { return getMessages(listener, true); } @Override - public Message[] getMessages(final MessageRetrievalListener listener, final boolean includeDeleted) throws MessagingException - { - try - { - return database.execute(false, new DbCallback() - { + public Message[] getMessages(final MessageRetrievalListener listener, final boolean includeDeleted) throws MessagingException { + try { + return database.execute(false, new DbCallback() { @Override - public Message[] doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException - { - try - { + public Message[] doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException { + try { open(OpenMode.READ_WRITE); return LocalStore.this.getMessages( listener, @@ -2344,41 +1879,32 @@ public class LocalStore extends Store implements Serializable + "FROM messages WHERE " + (includeDeleted ? "" : "deleted = 0 AND ") + " folder_id = ? ORDER BY date DESC" - , new String[] - { + , new String[] { Long.toString(mFolderId) } ); - } - catch (MessagingException e) - { + } catch (MessagingException e) { throw new WrappedException(e); } } }); - } - catch (WrappedException e) - { - throw (MessagingException) e.getCause(); + } catch (WrappedException e) { + throw(MessagingException) e.getCause(); } } @Override public Message[] getMessages(String[] uids, MessageRetrievalListener listener) - throws MessagingException - { + throws MessagingException { open(OpenMode.READ_WRITE); - if (uids == null) - { + if (uids == null) { return getMessages(listener); } ArrayList messages = new ArrayList(); - for (String uid : uids) - { + for (String uid : uids) { Message message = getMessage(uid); - if (message != null) - { + if (message != null) { messages.add(message); } } @@ -2386,47 +1912,36 @@ public class LocalStore extends Store implements Serializable } @Override - public void copyMessages(Message[] msgs, Folder folder) throws MessagingException - { - if (!(folder instanceof LocalFolder)) - { + public void copyMessages(Message[] msgs, Folder folder) throws MessagingException { + if (!(folder instanceof LocalFolder)) { throw new MessagingException("copyMessages called with incorrect Folder"); } ((LocalFolder) folder).appendMessages(msgs, true); } @Override - public void moveMessages(final Message[] msgs, final Folder destFolder) throws MessagingException - { - if (!(destFolder instanceof LocalFolder)) - { + public void moveMessages(final Message[] msgs, final Folder destFolder) throws MessagingException { + if (!(destFolder instanceof LocalFolder)) { throw new MessagingException("moveMessages called with non-LocalFolder"); } final LocalFolder lDestFolder = (LocalFolder)destFolder; - try - { - database.execute(false, new DbCallback() - { + try { + database.execute(false, new DbCallback() { @Override - public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException - { - try - { + public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException { + try { lDestFolder.open(OpenMode.READ_WRITE); - for (Message message : msgs) - { + for (Message message : msgs) { LocalMessage lMessage = (LocalMessage)message; - if (!message.isSet(Flag.SEEN)) - { + if (!message.isSet(Flag.SEEN)) { setUnreadMessageCount(getUnreadMessageCount() - 1); lDestFolder.setUnreadMessageCount(lDestFolder.getUnreadMessageCount() + 1); } - if (message.isSet(Flag.FLAGGED)) - { + if (message.isSet(Flag.FLAGGED)) { setFlaggedMessageCount(getFlaggedMessageCount() - 1); lDestFolder.setFlaggedMessageCount(lDestFolder.getFlaggedMessageCount() + 1); } @@ -2439,8 +1954,7 @@ public class LocalStore extends Store implements Serializable message.setUid(K9.LOCAL_UID_PREFIX + UUID.randomUUID().toString()); - db.execSQL("UPDATE messages " + "SET folder_id = ?, uid = ? " + "WHERE id = ?", new Object[] - { + db.execSQL("UPDATE messages " + "SET folder_id = ?, uid = ? " + "WHERE id = ?", new Object[] { lDestFolder.getId(), message.getUid(), lMessage.getId() @@ -2451,18 +1965,14 @@ public class LocalStore extends Store implements Serializable placeHolder.setFlagInternal(Flag.SEEN, true); appendMessages(new Message[] { placeHolder }); } - } - catch (MessagingException e) - { + } catch (MessagingException e) { throw new WrappedException(e); } return null; } }); - } - catch (WrappedException e) - { - throw (MessagingException) e.getCause(); + } catch (WrappedException e) { + throw(MessagingException) e.getCause(); } } @@ -2475,15 +1985,11 @@ public class LocalStore extends Store implements Serializable * @return The local version of the message. Never null. * @throws MessagingException */ - public Message storeSmallMessage(final Message message, final Runnable runnable) throws MessagingException - { - return database.execute(true, new DbCallback() - { + public Message storeSmallMessage(final Message message, final Runnable runnable) throws MessagingException { + return database.execute(true, new DbCallback() { @Override - public Message doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException - { - try - { + public Message doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException { + try { appendMessages(new Message[] { message }); final String uid = message.getUid(); final Message result = getMessage(uid); @@ -2491,9 +1997,7 @@ public class LocalStore extends Store implements Serializable // Set a flag indicating this message has now be fully downloaded result.setFlag(Flag.X_DOWNLOADED_FULL, true); return result; - } - catch (MessagingException e) - { + } catch (MessagingException e) { throw new WrappedException(e); } } @@ -2512,8 +2016,7 @@ public class LocalStore extends Store implements Serializable * message, retrieve the appropriate local message instance first (if it already exists). */ @Override - public void appendMessages(Message[] messages) throws MessagingException - { + public void appendMessages(Message[] messages) throws MessagingException { appendMessages(messages, false); } @@ -2530,43 +2033,30 @@ public class LocalStore extends Store implements Serializable * @param messages * @param copy */ - private void appendMessages(final Message[] messages, final boolean copy) throws MessagingException - { + private void appendMessages(final Message[] messages, final boolean copy) throws MessagingException { open(OpenMode.READ_WRITE); - try - { - database.execute(true, new DbCallback() - { + try { + database.execute(true, new DbCallback() { @Override - public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException - { - try - { - for (Message message : messages) - { - if (!(message instanceof MimeMessage)) - { + public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException { + try { + for (Message message : messages) { + if (!(message instanceof MimeMessage)) { throw new Error("LocalStore can only store Messages that extend MimeMessage"); } String uid = message.getUid(); - if (uid == null || copy) - { + if (uid == null || copy) { uid = K9.LOCAL_UID_PREFIX + UUID.randomUUID().toString(); - if (!copy) - { + if (!copy) { message.setUid(uid); } - } - else - { + } else { Message oldMessage = getMessage(uid); - if (oldMessage != null && !oldMessage.isSet(Flag.SEEN)) - { + if (oldMessage != null && !oldMessage.isSet(Flag.SEEN)) { setUnreadMessageCount(getUnreadMessageCount() - 1); } - if (oldMessage != null && oldMessage.isSet(Flag.FLAGGED)) - { + if (oldMessage != null && oldMessage.isSet(Flag.FLAGGED)) { setFlaggedMessageCount(getFlaggedMessageCount() - 1); } /* @@ -2584,26 +2074,19 @@ public class LocalStore extends Store implements Serializable StringBuffer sbHtml = new StringBuffer(); StringBuffer sbText = new StringBuffer(); - for (Part viewable : viewables) - { - try - { + for (Part viewable : viewables) { + try { String text = MimeUtility.getTextFromPart(viewable); /* * Anything with MIME type text/html will be stored as such. Anything * else will be stored as text/plain. */ - if (viewable.getMimeType().equalsIgnoreCase("text/html")) - { + if (viewable.getMimeType().equalsIgnoreCase("text/html")) { sbHtml.append(text); - } - else - { + } else { sbText.append(text); } - } - catch (Exception e) - { + } catch (Exception e) { throw new MessagingException("Unable to get text for message part", e); } } @@ -2612,13 +2095,11 @@ public class LocalStore extends Store implements Serializable String html = markupContent(text, sbHtml.toString()); String preview = calculateContentPreview(text); // If we couldn't generate a reasonable preview from the text part, try doing it with the HTML part. - if (preview == null || preview.length() == 0) - { + if (preview == null || preview.length() == 0) { preview = calculateContentPreview(HtmlConverter.htmlToText(html)); } - try - { + try { ContentValues cv = new ContentValues(); cv.put("uid", uid); cv.put("subject", message.getSubject()); @@ -2641,43 +2122,33 @@ public class LocalStore extends Store implements Serializable cv.put("mime_type", message.getMimeType()); String messageId = message.getMessageId(); - if (messageId != null) - { + if (messageId != null) { cv.put("message_id", messageId); } long messageUid; messageUid = db.insert("messages", "uid", cv); - for (Part attachment : attachments) - { + for (Part attachment : attachments) { saveAttachment(messageUid, attachment, copy); } saveHeaders(messageUid, (MimeMessage)message); - if (!message.isSet(Flag.SEEN)) - { + if (!message.isSet(Flag.SEEN)) { setUnreadMessageCount(getUnreadMessageCount() + 1); } - if (message.isSet(Flag.FLAGGED)) - { + if (message.isSet(Flag.FLAGGED)) { setFlaggedMessageCount(getFlaggedMessageCount() + 1); } - } - catch (Exception e) - { + } catch (Exception e) { throw new MessagingException("Error appending message", e); } } - } - catch (MessagingException e) - { + } catch (MessagingException e) { throw new WrappedException(e); } return null; } }); - } - catch (WrappedException e) - { - throw (MessagingException) e.getCause(); + } catch (WrappedException e) { + throw(MessagingException) e.getCause(); } } @@ -2691,18 +2162,13 @@ public class LocalStore extends Store implements Serializable * @param message * @throws MessagingException */ - public void updateMessage(final LocalMessage message) throws MessagingException - { + public void updateMessage(final LocalMessage message) throws MessagingException { open(OpenMode.READ_WRITE); - try - { - database.execute(false, new DbCallback() - { + try { + database.execute(false, new DbCallback() { @Override - public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException - { - try - { + public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException { + try { ArrayList viewables = new ArrayList(); ArrayList attachments = new ArrayList(); @@ -2712,27 +2178,20 @@ public class LocalStore extends Store implements Serializable StringBuffer sbHtml = new StringBuffer(); StringBuffer sbText = new StringBuffer(); - for (int i = 0, count = viewables.size(); i < count; i++) - { + for (int i = 0, count = viewables.size(); i < count; i++) { Part viewable = viewables.get(i); - try - { + try { String text = MimeUtility.getTextFromPart(viewable); /* * Anything with MIME type text/html will be stored as such. Anything * else will be stored as text/plain. */ - if (viewable.getMimeType().equalsIgnoreCase("text/html")) - { + if (viewable.getMimeType().equalsIgnoreCase("text/html")) { sbHtml.append(text); - } - else - { + } else { sbText.append(text); } - } - catch (Exception e) - { + } catch (Exception e) { throw new MessagingException("Unable to get text for message part", e); } } @@ -2741,19 +2200,16 @@ public class LocalStore extends Store implements Serializable String html = markupContent(text, sbHtml.toString()); String preview = calculateContentPreview(text); // If we couldn't generate a reasonable preview from the text part, try doing it with the HTML part. - if (preview == null || preview.length() == 0) - { + if (preview == null || preview.length() == 0) { preview = calculateContentPreview(HtmlConverter.htmlToText(html)); } - try - { + try { db.execSQL("UPDATE messages SET " + "uid = ?, subject = ?, sender_list = ?, date = ?, flags = ?, " + "folder_id = ?, to_list = ?, cc_list = ?, bcc_list = ?, " + "html_content = ?, text_content = ?, preview = ?, reply_to_list = ?, " + "attachment_count = ? WHERE id = ?", - new Object[] - { + new Object[] { message.getUid(), message.getSubject(), Address.pack(message.getFrom()), @@ -2776,29 +2232,22 @@ public class LocalStore extends Store implements Serializable message.mId }); - for (int i = 0, count = attachments.size(); i < count; i++) - { + for (int i = 0, count = attachments.size(); i < count; i++) { Part attachment = attachments.get(i); saveAttachment(message.mId, attachment, false); } saveHeaders(message.getId(), message); - } - catch (Exception e) - { + } catch (Exception e) { throw new MessagingException("Error appending message", e); } - } - catch (MessagingException e) - { + } catch (MessagingException e) { throw new WrappedException(e); } return null; } }); - } - catch (WrappedException e) - { - throw (MessagingException) e.getCause(); + } catch (WrappedException e) { + throw(MessagingException) e.getCause(); } } @@ -2809,39 +2258,30 @@ public class LocalStore extends Store implements Serializable * @param message * @throws com.fsck.k9.mail.MessagingException */ - private void saveHeaders(final long id, final MimeMessage message) throws MessagingException - { - database.execute(true, new DbCallback() - { + private void saveHeaders(final long id, final MimeMessage message) throws MessagingException { + database.execute(true, new DbCallback() { @Override - public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException - { + public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException { boolean saveAllHeaders = mAccount.saveAllHeaders(); boolean gotAdditionalHeaders = false; deleteHeaders(id); - for (String name : message.getHeaderNames()) - { - if (saveAllHeaders || HEADERS_TO_SAVE.contains(name)) - { + for (String name : message.getHeaderNames()) { + if (saveAllHeaders || HEADERS_TO_SAVE.contains(name)) { String[] values = message.getHeader(name); - for (String value : values) - { + for (String value : values) { ContentValues cv = new ContentValues(); cv.put("message_id", id); cv.put("name", name); cv.put("value", value); db.insert("headers", "name", cv); } - } - else - { + } else { gotAdditionalHeaders = true; } } - if (!gotAdditionalHeaders) - { + if (!gotAdditionalHeaders) { // Remember that all headers for this message have been saved, so it is // not necessary to download them again in case the user wants to see all headers. List appendedFlags = new ArrayList(); @@ -2857,13 +2297,10 @@ public class LocalStore extends Store implements Serializable }); } - private void deleteHeaders(final long id) throws UnavailableStorageException - { - database.execute(false, new DbCallback() - { + private void deleteHeaders(final long id) throws UnavailableStorageException { + database.execute(false, new DbCallback() { @Override - public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException - { + public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException { db.execSQL("DELETE FROM headers WHERE message_id = ?", new Object[] { id }); return null; @@ -2879,37 +2316,27 @@ public class LocalStore extends Store implements Serializable * @throws MessagingException */ private void saveAttachment(final long messageId, final Part attachment, final boolean saveAsNew) - throws IOException, MessagingException - { - try - { - database.execute(true, new DbCallback() - { + throws IOException, MessagingException { + try { + database.execute(true, new DbCallback() { @Override - public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException - { - try - { + public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException { + try { long attachmentId = -1; Uri contentUri = null; int size = -1; File tempAttachmentFile = null; - if ((!saveAsNew) && (attachment instanceof LocalAttachmentBodyPart)) - { + if ((!saveAsNew) && (attachment instanceof LocalAttachmentBodyPart)) { attachmentId = ((LocalAttachmentBodyPart) attachment).getAttachmentId(); } final File attachmentDirectory = StorageManager.getInstance(mApplication).getAttachmentDirectory(uUid, database.getStorageProviderId()); - if (attachment.getBody() != null) - { + if (attachment.getBody() != null) { Body body = attachment.getBody(); - if (body instanceof LocalAttachmentBody) - { + if (body instanceof LocalAttachmentBody) { contentUri = ((LocalAttachmentBody) body).getContentUri(); - } - else - { + } else { /* * If the attachment has a body we're expected to save it into the local store * so we copy the data into a cached attachment file. @@ -2923,24 +2350,20 @@ public class LocalStore extends Store implements Serializable } } - if (size == -1) - { + if (size == -1) { /* * If the attachment is not yet downloaded see if we can pull a size * off the Content-Disposition. */ String disposition = attachment.getDisposition(); - if (disposition != null) - { + if (disposition != null) { String s = MimeUtility.getHeaderParameter(disposition, "size"); - if (s != null) - { + if (s != null) { size = Integer.parseInt(s); } } } - if (size == -1) - { + if (size == -1) { size = 0; } @@ -2952,12 +2375,10 @@ public class LocalStore extends Store implements Serializable String contentId = MimeUtility.getHeaderParameter(attachment.getContentId(), null); String contentDisposition = MimeUtility.unfoldAndDecode(attachment.getDisposition()); - if (name == null && contentDisposition != null) - { + if (name == null && contentDisposition != null) { name = MimeUtility.getHeaderParameter(contentDisposition, "filename"); } - if (attachmentId == -1) - { + if (attachmentId == -1) { ContentValues cv = new ContentValues(); cv.put("message_id", messageId); cv.put("content_uri", contentUri != null ? contentUri.toString() : null); @@ -2969,9 +2390,7 @@ public class LocalStore extends Store implements Serializable cv.put("content_disposition", contentDisposition); attachmentId = db.insert("attachments", "message_id", cv); - } - else - { + } else { ContentValues cv = new ContentValues(); cv.put("content_uri", contentUri != null ? contentUri.toString() : null); cv.put("size", size); @@ -2979,8 +2398,7 @@ public class LocalStore extends Store implements Serializable { Long.toString(attachmentId) }); } - if (attachmentId != -1 && tempAttachmentFile != null) - { + if (attachmentId != -1 && tempAttachmentFile != null) { File attachmentFile = new File(attachmentDirectory, Long.toString(attachmentId)); tempAttachmentFile.renameTo(attachmentFile); contentUri = AttachmentProvider.getAttachmentUri( @@ -2994,15 +2412,12 @@ public class LocalStore extends Store implements Serializable } /* The message has attachment with Content-ID */ - if (contentId != null && contentUri != null) - { + if (contentId != null && contentUri != null) { Cursor cursor = db.query("messages", new String[] { "html_content" }, "id = ?", new String[] { Long.toString(messageId) }, null, null, null); - try - { - if (cursor.moveToNext()) - { + try { + if (cursor.moveToNext()) { String new_html; new_html = cursor.getString(0); @@ -3014,43 +2429,30 @@ public class LocalStore extends Store implements Serializable db.update("messages", cv, "id = ?", new String[] { Long.toString(messageId) }); } - } - finally - { - if (cursor != null) - { + } finally { + if (cursor != null) { cursor.close(); } } } - if (attachmentId != -1 && attachment instanceof LocalAttachmentBodyPart) - { + if (attachmentId != -1 && attachment instanceof LocalAttachmentBodyPart) { ((LocalAttachmentBodyPart) attachment).setAttachmentId(attachmentId); } return null; - } - catch (MessagingException e) - { + } catch (MessagingException e) { throw new WrappedException(e); - } - catch (IOException e) - { + } catch (IOException e) { throw new WrappedException(e); } } }); - } - catch (WrappedException e) - { + } catch (WrappedException e) { final Throwable cause = e.getCause(); - if (cause instanceof IOException) - { - throw (IOException) cause; - } - else - { - throw (MessagingException) cause; + if (cause instanceof IOException) { + throw(IOException) cause; + } else { + throw(MessagingException) cause; } } } @@ -3061,16 +2463,13 @@ public class LocalStore extends Store implements Serializable * @param message * @throws com.fsck.k9.mail.MessagingException */ - public void changeUid(final LocalMessage message) throws MessagingException - { + public void changeUid(final LocalMessage message) throws MessagingException { open(OpenMode.READ_WRITE); final ContentValues cv = new ContentValues(); cv.put("uid", message.getUid()); - database.execute(false, new DbCallback() - { + database.execute(false, new DbCallback() { @Override - public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException - { + public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException { db.update("messages", cv, "id = ?", new String[] { Long.toString(message.mId) }); return null; @@ -3080,34 +2479,28 @@ public class LocalStore extends Store implements Serializable @Override public void setFlags(Message[] messages, Flag[] flags, boolean value) - throws MessagingException - { + throws MessagingException { open(OpenMode.READ_WRITE); - for (Message message : messages) - { + for (Message message : messages) { message.setFlags(flags, value); } } @Override public void setFlags(Flag[] flags, boolean value) - throws MessagingException - { + throws MessagingException { open(OpenMode.READ_WRITE); - for (Message message : getMessages(null)) - { + for (Message message : getMessages(null)) { message.setFlags(flags, value); } } @Override - public String getUidFromMessageId(Message message) throws MessagingException - { + public String getUidFromMessageId(Message message) throws MessagingException { throw new MessagingException("Cannot call getUidFromMessageId on LocalFolder"); } - private void clearMessagesWhere(final String whereClause, final String[] params) throws MessagingException - { + private void clearMessagesWhere(final String whereClause, final String[] params) throws MessagingException { open(OpenMode.READ_ONLY); Message[] messages = LocalStore.this.getMessages( null, @@ -3115,15 +2508,12 @@ public class LocalStore extends Store implements Serializable "SELECT " + GET_MESSAGES_COLS + "FROM messages WHERE " + whereClause, params); - for (Message message : messages) - { + for (Message message : messages) { deleteAttachments(message.getUid()); } - database.execute(false, new DbCallback() - { + database.execute(false, new DbCallback() { @Override - public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException - { + public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException { db.execSQL("DELETE FROM messages WHERE " + whereClause, params); return null; } @@ -3131,11 +2521,9 @@ public class LocalStore extends Store implements Serializable resetUnreadAndFlaggedCounts(); } - public void clearMessagesOlderThan(long cutoff) throws MessagingException - { + public void clearMessagesOlderThan(long cutoff) throws MessagingException { final String where = "folder_id = ? and date < ?"; - final String[] params = new String[] - { + final String[] params = new String[] { Long.toString(mFolderId), Long.toString(cutoff) }; @@ -3144,11 +2532,9 @@ public class LocalStore extends Store implements Serializable - public void clearAllMessages() throws MessagingException - { + public void clearAllMessages() throws MessagingException { final String where = "folder_id = ?"; - final String[] params = new String[] - { + final String[] params = new String[] { Long.toString(mFolderId) }; @@ -3159,56 +2545,41 @@ public class LocalStore extends Store implements Serializable setLastChecked(0); } - private void resetUnreadAndFlaggedCounts() - { - try - { + private void resetUnreadAndFlaggedCounts() { + try { int newUnread = 0; int newFlagged = 0; Message[] messages = getMessages(null); - for (Message message : messages) - { - if (!message.isSet(Flag.SEEN)) - { + for (Message message : messages) { + if (!message.isSet(Flag.SEEN)) { newUnread++; } - if (message.isSet(Flag.FLAGGED)) - { + if (message.isSet(Flag.FLAGGED)) { newFlagged++; } } setUnreadMessageCount(newUnread); setFlaggedMessageCount(newFlagged); - } - catch (Exception e) - { + } catch (Exception e) { Log.e(K9.LOG_TAG, "Unable to fetch all messages from LocalStore", e); } } @Override - public void delete(final boolean recurse) throws MessagingException - { - try - { - database.execute(false, new DbCallback() - { + public void delete(final boolean recurse) throws MessagingException { + try { + database.execute(false, new DbCallback() { @Override - public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException - { - try - { + public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException { + try { // We need to open the folder first to make sure we've got it's id open(OpenMode.READ_ONLY); Message[] messages = getMessages(null); - for (Message message : messages) - { + for (Message message : messages) { deleteAttachments(message.getUid()); } - } - catch (MessagingException e) - { + } catch (MessagingException e) { throw new WrappedException(e); } db.execSQL("DELETE FROM folders WHERE id = ?", new Object[] @@ -3216,73 +2587,55 @@ public class LocalStore extends Store implements Serializable return null; } }); - } - catch (WrappedException e) - { - throw (MessagingException) e.getCause(); + } catch (WrappedException e) { + throw(MessagingException) e.getCause(); } } @Override - public boolean equals(Object o) - { - if (o instanceof LocalFolder) - { + public boolean equals(Object o) { + if (o instanceof LocalFolder) { return ((LocalFolder)o).mName.equals(mName); } return super.equals(o); } @Override - public int hashCode() - { + public int hashCode() { return mName.hashCode(); } @Override - public Flag[] getPermanentFlags() - { + public Flag[] getPermanentFlags() { return PERMANENT_FLAGS; } - private void deleteAttachments(final long messageId) throws MessagingException - { + private void deleteAttachments(final long messageId) throws MessagingException { open(OpenMode.READ_WRITE); - database.execute(false, new DbCallback() - { + database.execute(false, new DbCallback() { @Override - public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException - { + public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException { Cursor attachmentsCursor = null; - try - { + try { attachmentsCursor = db.query("attachments", new String[] { "id" }, "message_id = ?", new String[] { Long.toString(messageId) }, null, null, null); final File attachmentDirectory = StorageManager.getInstance(mApplication) .getAttachmentDirectory(uUid, database.getStorageProviderId()); - while (attachmentsCursor.moveToNext()) - { + while (attachmentsCursor.moveToNext()) { long attachmentId = attachmentsCursor.getLong(0); - try - { + try { File file = new File(attachmentDirectory, Long.toString(attachmentId)); - if (file.exists()) - { + if (file.exists()) { file.delete(); } - } - catch (Exception e) - { + } catch (Exception e) { } } - } - finally - { - if (attachmentsCursor != null) - { + } finally { + if (attachmentsCursor != null) { attachmentsCursor.close(); } } @@ -3291,47 +2644,34 @@ public class LocalStore extends Store implements Serializable }); } - private void deleteAttachments(final String uid) throws MessagingException - { + private void deleteAttachments(final String uid) throws MessagingException { open(OpenMode.READ_WRITE); - try - { - database.execute(false, new DbCallback() - { + try { + database.execute(false, new DbCallback() { @Override - public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException - { + public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException { Cursor messagesCursor = null; - try - { + try { messagesCursor = db.query("messages", new String[] { "id" }, "folder_id = ? AND uid = ?", new String[] { Long.toString(mFolderId), uid }, null, null, null); - while (messagesCursor.moveToNext()) - { + while (messagesCursor.moveToNext()) { long messageId = messagesCursor.getLong(0); deleteAttachments(messageId); } - } - catch (MessagingException e) - { + } catch (MessagingException e) { throw new WrappedException(e); - } - finally - { - if (messagesCursor != null) - { + } finally { + if (messagesCursor != null) { messagesCursor.close(); } } return null; } }); - } - catch (WrappedException e) - { - throw (MessagingException) e.getCause(); + } catch (WrappedException e) { + throw(MessagingException) e.getCause(); } } @@ -3346,45 +2686,37 @@ public class LocalStore extends Store implements Serializable * All newlines and whitespace will be compressed. * */ - public String calculateContentPreview(String text) - { - if (text == null) - { + public String calculateContentPreview(String text) { + if (text == null) { return null; } // Only look at the first 8k of a message when calculating // the preview. This should avoid unnecessary // memory usage on large messages - if (text.length() > 8192) - { - text = text.substring(0,8192); + if (text.length() > 8192) { + text = text.substring(0, 8192); } - text = text.replaceAll("(?m)^----.*?$",""); - text = text.replaceAll("(?m)^[#>].*$",""); - text = text.replaceAll("(?m)^On .*wrote.?$",""); - text = text.replaceAll("(?m)^.*\\w+:$",""); - text = text.replaceAll("https?://\\S+","..."); - text = text.replaceAll("(\\r|\\n)+"," "); - text = text.replaceAll("\\s+"," "); - if (text.length() <= 512) - { + text = text.replaceAll("(?m)^----.*?$", ""); + text = text.replaceAll("(?m)^[#>].*$", ""); + text = text.replaceAll("(?m)^On .*wrote.?$", ""); + text = text.replaceAll("(?m)^.*\\w+:$", ""); + text = text.replaceAll("https?://\\S+", "..."); + text = text.replaceAll("(\\r|\\n)+", " "); + text = text.replaceAll("\\s+", " "); + if (text.length() <= 512) { return text; - } - else - { - text = text.substring(0,512); + } else { + text = text.substring(0, 512); return text; } } - public String markupContent(String text, String html) - { - if (text.length() > 0 && html.length() == 0) - { + public String markupContent(String text, String html) { + if (text.length() > 0 && html.length() == 0) { html = HtmlConverter.textToHtml(text); } @@ -3395,19 +2727,16 @@ public class LocalStore extends Store implements Serializable @Override - public boolean isInTopGroup() - { + public boolean isInTopGroup() { return mInTopGroup; } - public void setInTopGroup(boolean inTopGroup) throws MessagingException - { + public void setInTopGroup(boolean inTopGroup) throws MessagingException { mInTopGroup = inTopGroup; - updateFolderColumn( "top_group", mInTopGroup ? 1 : 0 ); + updateFolderColumn("top_group", mInTopGroup ? 1 : 0); } - public Integer getLastUid() - { + public Integer getLastUid() { return mLastUid; } @@ -3427,69 +2756,49 @@ public class LocalStore extends Store implements Serializable * framework to examine send date in lieu of internal date.

    * @throws MessagingException */ - public void updateLastUid() throws MessagingException - { - Integer lastUid = database.execute(false, new DbCallback() - { + public void updateLastUid() throws MessagingException { + Integer lastUid = database.execute(false, new DbCallback() { @Override - public Integer doDbWork(final SQLiteDatabase db) - { + public Integer doDbWork(final SQLiteDatabase db) { Cursor cursor = null; - try - { + try { open(OpenMode.READ_ONLY); cursor = db.rawQuery("SELECT MAX(uid) FROM messages WHERE folder_id=?", new String[] { Long.toString(mFolderId) }); - if (cursor.getCount() > 0) - { + if (cursor.getCount() > 0) { cursor.moveToFirst(); return cursor.getInt(0); } - } - catch (Exception e) - { + } catch (Exception e) { Log.e(K9.LOG_TAG, "Unable to updateLastUid: ", e); - } - finally - { - if (cursor != null) - { + } finally { + if (cursor != null) { cursor.close(); } } return null; } }); - if(K9.DEBUG) + if (K9.DEBUG) Log.d(K9.LOG_TAG, "Updated last UID for folder " + mName + " to " + lastUid); mLastUid = lastUid; } - public long getOldestMessageDate() throws MessagingException - { - return database.execute(false, new DbCallback() - { + public long getOldestMessageDate() throws MessagingException { + return database.execute(false, new DbCallback() { @Override - public Long doDbWork(final SQLiteDatabase db) - { + public Long doDbWork(final SQLiteDatabase db) { Cursor cursor = null; - try - { + try { open(OpenMode.READ_ONLY); cursor = db.rawQuery("SELECT MIN(date) FROM messages WHERE folder_id=?", new String[] { Long.toString(mFolderId) }); - if (cursor.getCount() > 0) - { + if (cursor.getCount() > 0) { cursor.moveToFirst(); return cursor.getLong(0); } - } - catch (Exception e) - { + } catch (Exception e) { Log.e(K9.LOG_TAG, "Unable to fetch oldest message date: ", e); - } - finally - { - if (cursor != null) - { + } finally { + if (cursor != null) { cursor.close(); } } @@ -3500,38 +2809,32 @@ public class LocalStore extends Store implements Serializable } - public static class LocalTextBody extends TextBody - { + public static class LocalTextBody extends TextBody { /** * This is an HTML-ified version of the message for display purposes. */ private String mBodyForDisplay; - public LocalTextBody(String body) - { + public LocalTextBody(String body) { super(body); } - public LocalTextBody(String body, String bodyForDisplay) - { + public LocalTextBody(String body, String bodyForDisplay) { super(body); this.mBodyForDisplay = bodyForDisplay; } - public String getBodyForDisplay() - { + public String getBodyForDisplay() { return mBodyForDisplay; } - public void setBodyForDisplay(String mBodyForDisplay) - { + public void setBodyForDisplay(String mBodyForDisplay) { this.mBodyForDisplay = mBodyForDisplay; } }//LocalTextBody - public class LocalMessage extends MimeMessage - { + public class LocalMessage extends MimeMessage { private long mId; private int mAttachmentCount; private String mSubject; @@ -3546,45 +2849,36 @@ public class LocalStore extends Store implements Serializable private boolean mHeadersLoaded = false; private boolean mMessageDirty = false; - public LocalMessage() - { + public LocalMessage() { } - LocalMessage(String uid, Folder folder) - { + LocalMessage(String uid, Folder folder) { this.mUid = uid; this.mFolder = folder; } private void populateFromGetMessageCursor(Cursor cursor) - throws MessagingException - { + throws MessagingException { final String subject = cursor.getString(0); this.setSubject(subject == null ? "" : subject); Address[] from = Address.unpack(cursor.getString(1)); - if (from.length > 0) - { + if (from.length > 0) { this.setFrom(from[0]); } this.setInternalSentDate(new Date(cursor.getLong(2))); this.setUid(cursor.getString(3)); String flagList = cursor.getString(4); - if (flagList != null && flagList.length() > 0) - { + if (flagList != null && flagList.length() > 0) { String[] flags = flagList.split(","); - for (String flag : flags) - { - try - { + for (String flag : flags) { + try { this.setFlagInternal(Flag.valueOf(flag), true); } - catch (Exception e) - { - if (!"X_BAD_FLAG".equals(flag)) - { + catch (Exception e) { + if (!"X_BAD_FLAG".equals(flag)) { Log.w(K9.LOG_TAG, "Unable to parse flag " + flag); } } @@ -3603,8 +2897,7 @@ public class LocalStore extends Store implements Serializable final String preview = cursor.getString(14); mPreview = (preview == null ? "" : preview); - if (this.mFolder == null) - { + if (this.mFolder == null) { LocalFolder f = new LocalFolder(cursor.getInt(13)); f.open(LocalFolder.OpenMode.READ_WRITE); this.mFolder = f; @@ -3617,33 +2910,23 @@ public class LocalStore extends Store implements Serializable * @return HTML version of message for display purposes. * @throws MessagingException */ - public String getTextForDisplay() throws MessagingException - { + public String getTextForDisplay() throws MessagingException { String text; // First try and fetch an HTML part. Part part = MimeUtility.findFirstPartByMimeType(this, "text/html"); - if (part == null) - { + if (part == null) { // If that fails, try and get a text part. part = MimeUtility.findFirstPartByMimeType(this, "text/plain"); - if (part == null) - { + if (part == null) { text = null; - } - else - { + } else { LocalStore.LocalTextBody body = (LocalStore.LocalTextBody) part.getBody(); - if (body == null) - { + if (body == null) { text = null; - } - else - { + } else { text = body.getBodyForDisplay(); } } - } - else - { + } else { // We successfully found an HTML part; do the necessary character set decoding. text = MimeUtility.getTextFromPart(part); } @@ -3656,22 +2939,18 @@ public class LocalStore extends Store implements Serializable */ @Override - public void writeTo(OutputStream out) throws IOException, MessagingException - { + public void writeTo(OutputStream out) throws IOException, MessagingException { if (mMessageDirty) buildMimeRepresentation(); super.writeTo(out); } - private void buildMimeRepresentation() throws MessagingException - { - if (!mMessageDirty) - { + private void buildMimeRepresentation() throws MessagingException { + if (!mMessageDirty) { return; } super.setSubject(mSubject); - if (this.mFrom != null && this.mFrom.length > 0) - { + if (this.mFrom != null && this.mFrom.length > 0) { super.setFrom(this.mFrom[0]); } @@ -3685,68 +2964,54 @@ public class LocalStore extends Store implements Serializable mMessageDirty = false; } - public String getPreview() - { + public String getPreview() { return mPreview; } @Override - public String getSubject() - { + public String getSubject() { return mSubject; } @Override - public void setSubject(String subject) throws MessagingException - { + public void setSubject(String subject) throws MessagingException { mSubject = subject; mMessageDirty = true; } @Override - public void setMessageId(String messageId) - { + public void setMessageId(String messageId) { mMessageId = messageId; mMessageDirty = true; } - public boolean hasAttachments() - { - if (mAttachmentCount > 0) - { + public boolean hasAttachments() { + if (mAttachmentCount > 0) { return true; - } - else - { + } else { return false; } } - public int getAttachmentCount() - { + public int getAttachmentCount() { return mAttachmentCount; } @Override - public void setFrom(Address from) throws MessagingException - { + public void setFrom(Address from) throws MessagingException { this.mFrom = new Address[] { from }; mMessageDirty = true; } @Override - public void setReplyTo(Address[] replyTo) throws MessagingException - { - if (replyTo == null || replyTo.length == 0) - { + public void setReplyTo(Address[] replyTo) throws MessagingException { + if (replyTo == null || replyTo.length == 0) { mReplyTo = null; - } - else - { + } else { mReplyTo = replyTo; } mMessageDirty = true; @@ -3758,43 +3023,26 @@ public class LocalStore extends Store implements Serializable * which removes (expensive) them before adding them */ @Override - public void setRecipients(RecipientType type, Address[] addresses) throws MessagingException - { - if (type == RecipientType.TO) - { - if (addresses == null || addresses.length == 0) - { + public void setRecipients(RecipientType type, Address[] addresses) throws MessagingException { + if (type == RecipientType.TO) { + if (addresses == null || addresses.length == 0) { this.mTo = null; - } - else - { + } else { this.mTo = addresses; } - } - else if (type == RecipientType.CC) - { - if (addresses == null || addresses.length == 0) - { + } else if (type == RecipientType.CC) { + if (addresses == null || addresses.length == 0) { this.mCc = null; - } - else - { + } else { this.mCc = addresses; } - } - else if (type == RecipientType.BCC) - { - if (addresses == null || addresses.length == 0) - { + } else if (type == RecipientType.BCC) { + if (addresses == null || addresses.length == 0) { this.mBcc = null; - } - else - { + } else { this.mBcc = addresses; } - } - else - { + } else { throw new MessagingException("Unrecognized recipient type."); } mMessageDirty = true; @@ -3802,24 +3050,17 @@ public class LocalStore extends Store implements Serializable - public boolean toMe() - { - try - { - if (!mToMeCalculated) - { - for (Address address : getRecipients(RecipientType.TO)) - { - if (mAccount.isAnIdentity(address)) - { + public boolean toMe() { + try { + if (!mToMeCalculated) { + for (Address address : getRecipients(RecipientType.TO)) { + if (mAccount.isAnIdentity(address)) { mToMe = true; mToMeCalculated = true; } } } - } - catch (MessagingException e) - { + } catch (MessagingException e) { // do something better than ignore this // getRecipients can throw a messagingexception } @@ -3830,26 +3071,19 @@ public class LocalStore extends Store implements Serializable - public boolean ccMe() - { - try - { + public boolean ccMe() { + try { - if (!mCcMeCalculated) - { - for(Address address : getRecipients(RecipientType.CC)) - { - if (mAccount.isAnIdentity(address)) - { + if (!mCcMeCalculated) { + for (Address address : getRecipients(RecipientType.CC)) { + if (mAccount.isAnIdentity(address)) { mCcMe = true; mCcMeCalculated = true; } } } - } - catch (MessagingException e) - { + } catch (MessagingException e) { // do something better than ignore this // getRecipients can throw a messagingexception } @@ -3862,31 +3096,23 @@ public class LocalStore extends Store implements Serializable - public void setFlagInternal(Flag flag, boolean set) throws MessagingException - { + public void setFlagInternal(Flag flag, boolean set) throws MessagingException { super.setFlag(flag, set); } - public long getId() - { + public long getId() { return mId; } @Override - public void setFlag(final Flag flag, final boolean set) throws MessagingException - { + public void setFlag(final Flag flag, final boolean set) throws MessagingException { - try - { - database.execute(true, new DbCallback() - { + try { + database.execute(true, new DbCallback() { @Override - public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException - { - try - { - if (flag == Flag.DELETED && set) - { + public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException { + try { + if (flag == Flag.DELETED && set) { delete(); } @@ -3894,9 +3120,7 @@ public class LocalStore extends Store implements Serializable LocalMessage.super.setFlag(flag, set); - } - catch (MessagingException e) - { + } catch (MessagingException e) { throw new WrappedException(e); } /* @@ -3907,10 +3131,8 @@ public class LocalStore extends Store implements Serializable return null; } }); - } - catch (WrappedException e) - { - throw (MessagingException) e.getCause(); + } catch (WrappedException e) { + throw(MessagingException) e.getCause(); } @@ -3927,13 +3149,10 @@ public class LocalStore extends Store implements Serializable /* * Delete all of the message's content to save space. */ - try - { - database.execute(true, new DbCallback() - { + try { + database.execute(true, new DbCallback() { @Override - public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException - { + public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException { db.execSQL("UPDATE messages SET " + "deleted = 1," + "subject = NULL, " + "sender_list = NULL, " + "date = NULL, " + "to_list = NULL, " + "cc_list = NULL, " + "bcc_list = NULL, " + "preview = NULL, " @@ -3945,12 +3164,9 @@ public class LocalStore extends Store implements Serializable * We do this explicit deletion here because we're not deleting the record * in messages, which means our ON DELETE trigger for messages won't cascade */ - try - { + try { ((LocalFolder) mFolder).deleteAttachments(mId); - } - catch (MessagingException e) - { + } catch (MessagingException e) { throw new WrappedException(e); } db.execSQL("DELETE FROM attachments WHERE message_id = ?", new Object[] @@ -3958,10 +3174,8 @@ public class LocalStore extends Store implements Serializable return null; } }); - } - catch (WrappedException e) - { - throw (MessagingException) e.getCause(); + } catch (WrappedException e) { + throw(MessagingException) e.getCause(); } ((LocalFolder)mFolder).deleteHeaders(mId); @@ -3972,84 +3186,63 @@ public class LocalStore extends Store implements Serializable * Completely remove a message from the local database */ @Override - public void destroy() throws MessagingException - { - try - { - database.execute(true, new DbCallback() - { + public void destroy() throws MessagingException { + try { + database.execute(true, new DbCallback() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException, - UnavailableStorageException - { - try - { + UnavailableStorageException { + try { updateFolderCountsOnFlag(Flag.X_DESTROYED, true); ((LocalFolder) mFolder).deleteAttachments(mId); db.execSQL("DELETE FROM messages WHERE id = ?", new Object[] { mId }); - } - catch (MessagingException e) - { + } catch (MessagingException e) { throw new WrappedException(e); } return null; } }); - } - catch (WrappedException e) - { - throw (MessagingException) e.getCause(); + } catch (WrappedException e) { + throw(MessagingException) e.getCause(); } } - private void updateFolderCountsOnFlag(Flag flag, boolean set) - { + private void updateFolderCountsOnFlag(Flag flag, boolean set) { /* * Update the unread count on the folder. */ - try - { + try { LocalFolder folder = (LocalFolder)mFolder; - if (flag == Flag.DELETED || flag == Flag.X_DESTROYED) - { - if (!isSet(Flag.SEEN)) - { - folder.setUnreadMessageCount(folder.getUnreadMessageCount() + ( set ? -1:1) ); + if (flag == Flag.DELETED || flag == Flag.X_DESTROYED) { + if (!isSet(Flag.SEEN)) { + folder.setUnreadMessageCount(folder.getUnreadMessageCount() + (set ? -1 : 1)); } - if (isSet(Flag.FLAGGED)) - { + if (isSet(Flag.FLAGGED)) { folder.setFlaggedMessageCount(folder.getFlaggedMessageCount() + (set ? -1 : 1)); } } - if ( !isSet(Flag.DELETED) ) - { + if (!isSet(Flag.DELETED)) { - if ( flag == Flag.SEEN ) - { - if (set != isSet(Flag.SEEN)) - { - folder.setUnreadMessageCount(folder.getUnreadMessageCount() + ( set ? -1: 1) ); + if (flag == Flag.SEEN) { + if (set != isSet(Flag.SEEN)) { + folder.setUnreadMessageCount(folder.getUnreadMessageCount() + (set ? -1 : 1)); } } - if ( flag == Flag.FLAGGED ) - { + if (flag == Flag.FLAGGED) { folder.setFlaggedMessageCount(folder.getFlaggedMessageCount() + (set ? 1 : -1)); } } - } - catch (MessagingException me) - { + } catch (MessagingException me) { Log.e(K9.LOG_TAG, "Unable to update LocalStore unread message count", me); throw new RuntimeException(me); } } - private void loadHeaders() throws UnavailableStorageException - { + private void loadHeaders() throws UnavailableStorageException { ArrayList messages = new ArrayList(); messages.add(this); mHeadersLoaded = true; // set true before calling populate headers to stop recursion @@ -4058,52 +3251,45 @@ public class LocalStore extends Store implements Serializable } @Override - public void addHeader(String name, String value) throws UnavailableStorageException - { + public void addHeader(String name, String value) throws UnavailableStorageException { if (!mHeadersLoaded) loadHeaders(); super.addHeader(name, value); } @Override - public void setHeader(String name, String value) throws UnavailableStorageException - { + public void setHeader(String name, String value) throws UnavailableStorageException { if (!mHeadersLoaded) loadHeaders(); super.setHeader(name, value); } @Override - public String[] getHeader(String name) throws UnavailableStorageException - { + public String[] getHeader(String name) throws UnavailableStorageException { if (!mHeadersLoaded) loadHeaders(); return super.getHeader(name); } @Override - public void removeHeader(String name) throws UnavailableStorageException - { + public void removeHeader(String name) throws UnavailableStorageException { if (!mHeadersLoaded) loadHeaders(); super.removeHeader(name); } @Override - public Set getHeaderNames() throws UnavailableStorageException - { + public Set getHeaderNames() throws UnavailableStorageException { if (!mHeadersLoaded) loadHeaders(); return super.getHeaderNames(); } } - public static class LocalAttachmentBodyPart extends MimeBodyPart - { + public static class LocalAttachmentBodyPart extends MimeBodyPart { private long mAttachmentId = -1; - public LocalAttachmentBodyPart(Body body, long attachmentId) throws MessagingException - { + public LocalAttachmentBodyPart(Body body, long attachmentId) throws MessagingException { super(body); mAttachmentId = attachmentId; } @@ -4112,43 +3298,34 @@ public class LocalStore extends Store implements Serializable * Returns the local attachment id of this body, or -1 if it is not stored. * @return */ - public long getAttachmentId() - { + public long getAttachmentId() { return mAttachmentId; } - public void setAttachmentId(long attachmentId) - { + public void setAttachmentId(long attachmentId) { mAttachmentId = attachmentId; } @Override - public String toString() - { + public String toString() { return "" + mAttachmentId; } } - public static class LocalAttachmentBody implements Body - { + public static class LocalAttachmentBody implements Body { private static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; private Application mApplication; private Uri mUri; - public LocalAttachmentBody(Uri uri, Application application) - { + public LocalAttachmentBody(Uri uri, Application application) { mApplication = application; mUri = uri; } - public InputStream getInputStream() throws MessagingException - { - try - { + public InputStream getInputStream() throws MessagingException { + try { return mApplication.getContentResolver().openInputStream(mUri); - } - catch (FileNotFoundException fnfe) - { + } catch (FileNotFoundException fnfe) { /* * Since it's completely normal for us to try to serve up attachments that * have been blown away, we just return an empty stream. @@ -4157,16 +3334,14 @@ public class LocalStore extends Store implements Serializable } } - public void writeTo(OutputStream out) throws IOException, MessagingException - { + public void writeTo(OutputStream out) throws IOException, MessagingException { InputStream in = getInputStream(); Base64OutputStream base64Out = new Base64OutputStream(out); IOUtils.copy(in, base64Out); base64Out.close(); } - public Uri getContentUri() - { + public Uri getContentUri() { return mUri; } } diff --git a/src/com/fsck/k9/mail/store/LockableDatabase.java b/src/com/fsck/k9/mail/store/LockableDatabase.java index 5a35d6dc4..4662dc708 100644 --- a/src/com/fsck/k9/mail/store/LockableDatabase.java +++ b/src/com/fsck/k9/mail/store/LockableDatabase.java @@ -14,8 +14,7 @@ import com.fsck.k9.K9; import com.fsck.k9.helper.Utility; import com.fsck.k9.mail.MessagingException; -public class LockableDatabase -{ +public class LockableDatabase { /** * Callback interface for DB operations. Concept is similar to Spring @@ -24,8 +23,7 @@ public class LockableDatabase * @param * Return value type for {@link #doDbWork(SQLiteDatabase)} */ - public static interface DbCallback - { + public static interface DbCallback { /** * @param db * The locked database on which the work should occur. Never @@ -37,8 +35,7 @@ public class LockableDatabase T doDbWork(SQLiteDatabase db) throws WrappedException, UnavailableStorageException; } - public static interface SchemaDefinition - { + public static interface SchemaDefinition { int getVersion(); /** @@ -51,15 +48,13 @@ public class LockableDatabase * Workaround exception wrapper used to keep the inner exception generated * in a {@link DbCallback}. */ - protected static class WrappedException extends RuntimeException - { + protected static class WrappedException extends RuntimeException { /** * */ private static final long serialVersionUID = 8184421232587399369L; - public WrappedException(final Exception cause) - { + public WrappedException(final Exception cause) { super(cause); } } @@ -67,58 +62,42 @@ public class LockableDatabase /** * Open the DB on mount and close the DB on unmount */ - private class StorageListener implements StorageManager.StorageListener - { + private class StorageListener implements StorageManager.StorageListener { @Override - public void onUnmount(final String providerId) - { - if (!providerId.equals(mStorageProviderId)) - { + public void onUnmount(final String providerId) { + if (!providerId.equals(mStorageProviderId)) { return; } - if (K9.DEBUG) - { + if (K9.DEBUG) { Log.d(K9.LOG_TAG, "LockableDatabase: Closing DB " + uUid + " due to unmount event on StorageProvider: " + providerId); } - try - { + try { lockWrite(); - try - { + try { mDb.close(); - } - finally - { + } finally { unlockWrite(); } - } - catch (UnavailableStorageException e) - { + } catch (UnavailableStorageException e) { Log.w(K9.LOG_TAG, "Unable to writelock on unmount", e); } } @Override - public void onMount(final String providerId) - { - if (!providerId.equals(mStorageProviderId)) - { + public void onMount(final String providerId) { + if (!providerId.equals(mStorageProviderId)) { return; } - if (K9.DEBUG) - { + if (K9.DEBUG) { Log.d(K9.LOG_TAG, "LockableDatabase: Opening DB " + uUid + " due to mount event on StorageProvider: " + providerId); } - try - { + try { openOrCreateDataspace(mApplication); - } - catch (UnavailableStorageException e) - { + } catch (UnavailableStorageException e) { Log.e(K9.LOG_TAG, "Unable to open DB on mount", e); } } @@ -167,25 +146,21 @@ public class LockableDatabase * @param schemaDefinition * Never null T execute(final boolean transactional, final DbCallback callback) throws UnavailableStorageException - { + public T execute(final boolean transactional, final DbCallback callback) throws UnavailableStorageException { lockRead(); final boolean doTransaction = transactional && inTransaction.get() == null; - try - { + try { final boolean debug = K9.DEBUG; - if (doTransaction) - { + if (doTransaction) { inTransaction.set(Boolean.TRUE); mDb.beginTransaction(); } - try - { + try { final T result = callback.doDbWork(mDb); - if (doTransaction) - { + if (doTransaction) { mDb.setTransactionSuccessful(); } return result; - } - finally - { - if (doTransaction) - { + } finally { + if (doTransaction) { final long begin; - if (debug) - { + if (debug) { begin = System.currentTimeMillis(); - } - else - { + } else { begin = 0l; } // not doing endTransaction in the same 'finally' block of unlockRead() because endTransaction() may throw an exception mDb.endTransaction(); - if (debug) - { + if (debug) { Log.v(K9.LOG_TAG, "LockableDatabase: Transaction ended, took " + Long.toString(System.currentTimeMillis() - begin) + "ms / " + new Exception().getStackTrace()[1].toString()); } } } - } - finally - { - if (doTransaction) - { + } finally { + if (doTransaction) { inTransaction.set(null); } unlockRead(); @@ -366,27 +310,20 @@ public class LockableDatabase * Never null. * @throws MessagingException */ - public void switchProvider(final String newProviderId) throws MessagingException - { - if (newProviderId.equals(mStorageProviderId)) - { + public void switchProvider(final String newProviderId) throws MessagingException { + if (newProviderId.equals(mStorageProviderId)) { Log.v(K9.LOG_TAG, "LockableDatabase: Ignoring provider switch request as they are equal: " + newProviderId); return; } final String oldProviderId = mStorageProviderId; lockWrite(oldProviderId); - try - { + try { lockWrite(newProviderId); - try - { - try - { + try { + try { mDb.close(); - } - catch (Exception e) - { + } catch (Exception e) { Log.i(K9.LOG_TAG, "Unable to close DB on local store migration", e); } @@ -404,27 +341,19 @@ public class LockableDatabase // re-initialize this class with the new Uri openOrCreateDataspace(mApplication); - } - finally - { + } finally { unlockWrite(newProviderId); } - } - finally - { + } finally { unlockWrite(oldProviderId); } } - public void open() throws UnavailableStorageException - { + public void open() throws UnavailableStorageException { lockWrite(); - try - { + try { openOrCreateDataspace(mApplication); - } - finally - { + } finally { unlockWrite(); } StorageManager.getInstance(mApplication).addListener(mStorageListener); @@ -435,31 +364,23 @@ public class LockableDatabase * @param application * @throws UnavailableStorageException */ - protected void openOrCreateDataspace(final Application application) throws UnavailableStorageException - { + protected void openOrCreateDataspace(final Application application) throws UnavailableStorageException { lockWrite(); - try - { + try { final File databaseFile = prepareStorage(mStorageProviderId); - try - { + try { mDb = SQLiteDatabase.openOrCreateDatabase(databaseFile, null); - } - catch (SQLiteException e) - { + } catch (SQLiteException e) { // try to gracefully handle DB corruption - see issue 2537 Log.w(K9.LOG_TAG, "Unable to open DB " + databaseFile + " - removing file and retrying", e); databaseFile.delete(); mDb = SQLiteDatabase.openOrCreateDatabase(databaseFile, null); } - if (mDb.getVersion() != mSchemaDefinition.getVersion()) - { + if (mDb.getVersion() != mSchemaDefinition.getVersion()) { mSchemaDefinition.doDbUpgrade(mDb); } - } - finally - { + } finally { unlockWrite(); } } @@ -470,23 +391,19 @@ public class LockableDatabase * @return DB file. * @throws UnavailableStorageException */ - protected File prepareStorage(final String providerId) throws UnavailableStorageException - { + protected File prepareStorage(final String providerId) throws UnavailableStorageException { final StorageManager storageManager = getStorageManager(); final File databaseFile; final File databaseParentDir; databaseFile = storageManager.getDatabase(uUid, providerId); databaseParentDir = databaseFile.getParentFile(); - if (databaseParentDir.isFile()) - { + if (databaseParentDir.isFile()) { // should be safe to inconditionally delete clashing file: user is not supposed to mess with our directory databaseParentDir.delete(); } - if (!databaseParentDir.exists()) - { - if (!databaseParentDir.mkdirs()) - { + if (!databaseParentDir.exists()) { + if (!databaseParentDir.mkdirs()) { // Android seems to be unmounting the storage... throw new UnavailableStorageException("Unable to access: " + databaseParentDir); } @@ -498,13 +415,11 @@ public class LockableDatabase attachmentDir = storageManager .getAttachmentDirectory(uUid, providerId); attachmentParentDir = attachmentDir.getParentFile(); - if (!attachmentParentDir.exists()) - { + if (!attachmentParentDir.exists()) { attachmentParentDir.mkdirs(); Utility.touchFile(attachmentParentDir, ".nomedia"); } - if (!attachmentDir.exists()) - { + if (!attachmentDir.exists()) { attachmentDir.mkdirs(); } return databaseFile; @@ -515,13 +430,11 @@ public class LockableDatabase * * @throws UnavailableStorageException */ - public void delete() throws UnavailableStorageException - { + public void delete() throws UnavailableStorageException { delete(false); } - public void recreate() throws UnavailableStorageException - { + public void recreate() throws UnavailableStorageException { delete(true); } @@ -530,60 +443,41 @@ public class LockableDatabase * true if the DB should be recreated after delete * @throws UnavailableStorageException */ - private void delete(final boolean recreate) throws UnavailableStorageException - { + private void delete(final boolean recreate) throws UnavailableStorageException { lockWrite(); - try - { - try - { + try { + try { mDb.close(); - } - catch (Exception e) - { + } catch (Exception e) { } final StorageManager storageManager = getStorageManager(); - try - { + try { final File attachmentDirectory = storageManager.getAttachmentDirectory(uUid, mStorageProviderId); final File[] attachments = attachmentDirectory.listFiles(); - for (File attachment : attachments) - { - if (attachment.exists()) - { + for (File attachment : attachments) { + if (attachment.exists()) { attachment.delete(); } } - if (attachmentDirectory.exists()) - { + if (attachmentDirectory.exists()) { attachmentDirectory.delete(); } + } catch (Exception e) { } - catch (Exception e) - { - } - try - { + try { storageManager.getDatabase(uUid, mStorageProviderId).delete(); - } - catch (Exception e) - { + } catch (Exception e) { Log.i(K9.LOG_TAG, "LockableDatabase: delete(): Unable to delete backing DB file", e); } - if (recreate) - { + if (recreate) { openOrCreateDataspace(mApplication); - } - else - { + } else { // stop waiting for mount/unmount events getStorageManager().removeListener(mStorageListener); } - } - finally - { + } finally { unlockWrite(); } } diff --git a/src/com/fsck/k9/mail/store/Pop3Store.java b/src/com/fsck/k9/mail/store/Pop3Store.java index 46492e23a..64f5709f2 100644 --- a/src/com/fsck/k9/mail/store/Pop3Store.java +++ b/src/com/fsck/k9/mail/store/Pop3Store.java @@ -25,8 +25,7 @@ import java.util.HashMap; import java.util.HashSet; import java.util.List; -public class Pop3Store extends Store -{ +public class Pop3Store extends Store { public static final int CONNECTION_SECURITY_NONE = 0; public static final int CONNECTION_SECURITY_TLS_OPTIONAL = 1; public static final int CONNECTION_SECURITY_TLS_REQUIRED = 2; @@ -50,71 +49,50 @@ public class Pop3Store extends Store * pop3+ssl+://user:password@server:port CONNECTION_SECURITY_SSL_REQUIRED * pop3+ssl://user:password@server:port CONNECTION_SECURITY_SSL_OPTIONAL */ - public Pop3Store(Account account) throws MessagingException - { + public Pop3Store(Account account) throws MessagingException { super(account); URI uri; - try - { + try { uri = new URI(mAccount.getStoreUri()); - } - catch (URISyntaxException use) - { + } catch (URISyntaxException use) { throw new MessagingException("Invalid Pop3Store URI", use); } String scheme = uri.getScheme(); - if (scheme.equals("pop3")) - { + if (scheme.equals("pop3")) { mConnectionSecurity = CONNECTION_SECURITY_NONE; mPort = 110; - } - else if (scheme.equals("pop3+tls")) - { + } else if (scheme.equals("pop3+tls")) { mConnectionSecurity = CONNECTION_SECURITY_TLS_OPTIONAL; mPort = 110; - } - else if (scheme.equals("pop3+tls+")) - { + } else if (scheme.equals("pop3+tls+")) { mConnectionSecurity = CONNECTION_SECURITY_TLS_REQUIRED; mPort = 110; - } - else if (scheme.equals("pop3+ssl+")) - { + } else if (scheme.equals("pop3+ssl+")) { mConnectionSecurity = CONNECTION_SECURITY_SSL_REQUIRED; mPort = 995; - } - else if (scheme.equals("pop3+ssl")) - { + } else if (scheme.equals("pop3+ssl")) { mConnectionSecurity = CONNECTION_SECURITY_SSL_OPTIONAL; mPort = 995; - } - else - { + } else { throw new MessagingException("Unsupported protocol"); } mHost = uri.getHost(); - if (uri.getPort() != -1) - { + if (uri.getPort() != -1) { mPort = uri.getPort(); } - if (uri.getUserInfo() != null) - { - try - { + if (uri.getUserInfo() != null) { + try { String[] userInfoParts = uri.getUserInfo().split(":"); mUsername = URLDecoder.decode(userInfoParts[0], "UTF-8"); - if (userInfoParts.length > 1) - { + if (userInfoParts.length > 1) { mPassword = URLDecoder.decode(userInfoParts[1], "UTF-8"); } - } - catch (UnsupportedEncodingException enc) - { + } catch (UnsupportedEncodingException enc) { // This shouldn't happen since the encoding is hardcoded to UTF-8 Log.e(K9.LOG_TAG, "Couldn't urldecode username or password.", enc); } @@ -122,11 +100,9 @@ public class Pop3Store extends Store } @Override - public Folder getFolder(String name) - { + public Folder getFolder(String name) { Folder folder = mFolders.get(name); - if (folder == null) - { + if (folder == null) { folder = new Pop3Folder(name); mFolders.put(folder.getName(), folder); } @@ -134,20 +110,17 @@ public class Pop3Store extends Store } @Override - public List getPersonalNamespaces(boolean forceListAll) throws MessagingException - { + public List getPersonalNamespaces(boolean forceListAll) throws MessagingException { List folders = new LinkedList(); folders.add(getFolder("INBOX")); return folders; } @Override - public void checkSettings() throws MessagingException - { + public void checkSettings() throws MessagingException { Pop3Folder folder = new Pop3Folder("INBOX"); folder.open(OpenMode.READ_WRITE); - if (!mCapabilities.uidl) - { + if (!mCapabilities.uidl) { /* * Run an additional test to see if UIDL is supported on the server. If it's not we * can't service this account. @@ -163,8 +136,7 @@ public class Pop3Store extends Store folder.close(); } - class Pop3Folder extends Folder - { + class Pop3Folder extends Folder { private Socket mSocket; private InputStream mIn; private OutputStream mOut; @@ -174,45 +146,35 @@ public class Pop3Store extends Store private String mName; private int mMessageCount; - public Pop3Folder(String name) - { + public Pop3Folder(String name) { super(Pop3Store.this.mAccount); this.mName = name; - if (mName.equalsIgnoreCase("INBOX")) - { + if (mName.equalsIgnoreCase("INBOX")) { mName = "INBOX"; } } @Override - public synchronized void open(OpenMode mode) throws MessagingException - { - if (isOpen()) - { + public synchronized void open(OpenMode mode) throws MessagingException { + if (isOpen()) { return; } - if (!mName.equalsIgnoreCase("INBOX")) - { + if (!mName.equalsIgnoreCase("INBOX")) { throw new MessagingException("Folder does not exist"); } - try - { + try { SocketAddress socketAddress = new InetSocketAddress(mHost, mPort); if (mConnectionSecurity == CONNECTION_SECURITY_SSL_REQUIRED || - mConnectionSecurity == CONNECTION_SECURITY_SSL_OPTIONAL) - { + mConnectionSecurity == CONNECTION_SECURITY_SSL_OPTIONAL) { SSLContext sslContext = SSLContext.getInstance("TLS"); final boolean secure = mConnectionSecurity == CONNECTION_SECURITY_SSL_REQUIRED; - sslContext.init(null, new TrustManager[] - { + sslContext.init(null, new TrustManager[] { TrustManagerFactory.get(mHost, secure) }, new SecureRandom()); mSocket = sslContext.getSocketFactory().createSocket(); - } - else - { + } else { mSocket = new Socket(); } @@ -221,8 +183,7 @@ public class Pop3Store extends Store mOut = new BufferedOutputStream(mSocket.getOutputStream(), 512); mSocket.setSoTimeout(Store.SOCKET_READ_TIMEOUT); - if (!isOpen()) - { + if (!isOpen()) { throw new MessagingException("Unable to connect socket"); } @@ -230,18 +191,15 @@ public class Pop3Store extends Store executeSimpleCommand(null); if (mConnectionSecurity == CONNECTION_SECURITY_TLS_OPTIONAL - || mConnectionSecurity == CONNECTION_SECURITY_TLS_REQUIRED) - { + || mConnectionSecurity == CONNECTION_SECURITY_TLS_REQUIRED) { mCapabilities = getCapabilities(); - if (mCapabilities.stls) - { + if (mCapabilities.stls) { writeLine("STLS"); SSLContext sslContext = SSLContext.getInstance("TLS"); boolean secure = mConnectionSecurity == CONNECTION_SECURITY_TLS_REQUIRED; - sslContext.init(null, new TrustManager[] - { + sslContext.init(null, new TrustManager[] { TrustManagerFactory.get(mHost, secure) }, new SecureRandom()); mSocket = sslContext.getSocketFactory().createSocket(mSocket, mHost, mPort, @@ -249,40 +207,28 @@ public class Pop3Store extends Store mSocket.setSoTimeout(Store.SOCKET_READ_TIMEOUT); mIn = new BufferedInputStream(mSocket.getInputStream(), 1024); mOut = new BufferedOutputStream(mSocket.getOutputStream(), 512); - if (!isOpen()) - { + if (!isOpen()) { throw new MessagingException("Unable to connect socket"); } - } - else if (mConnectionSecurity == CONNECTION_SECURITY_TLS_REQUIRED) - { + } else if (mConnectionSecurity == CONNECTION_SECURITY_TLS_REQUIRED) { throw new MessagingException("TLS not supported but required"); } } - try - { + try { executeSimpleCommand("USER " + mUsername); executeSimpleCommand("PASS " + mPassword, true); - } - catch (MessagingException me) - { + } catch (MessagingException me) { throw new AuthenticationFailedException(null, me); } mCapabilities = getCapabilities(); - } - catch (SSLException e) - { + } catch (SSLException e) { throw new CertificateValidationException(e.getMessage(), e); - } - catch (GeneralSecurityException gse) - { + } catch (GeneralSecurityException gse) { throw new MessagingException( "Unable to open connection to POP server due to security error.", gse); - } - catch (IOException ioe) - { + } catch (IOException ioe) { throw new MessagingException("Unable to open connection to POP server.", ioe); } @@ -296,27 +242,21 @@ public class Pop3Store extends Store } @Override - public boolean isOpen() - { + public boolean isOpen() { return (mIn != null && mOut != null && mSocket != null && mSocket.isConnected() && !mSocket.isClosed()); } @Override - public OpenMode getMode() - { + public OpenMode getMode() { return OpenMode.READ_WRITE; } @Override - public void close() - { - try - { + public void close() { + try { executeSimpleCommand("QUIT"); - } - catch (Exception e) - { + } catch (Exception e) { /* * QUIT may fail if the connection is already closed. We don't care. It's just * being friendly. @@ -326,34 +266,24 @@ public class Pop3Store extends Store closeIO(); } - private void closeIO() - { - try - { + private void closeIO() { + try { mIn.close(); - } - catch (Exception e) - { + } catch (Exception e) { /* * May fail if the connection is already closed. */ } - try - { + try { mOut.close(); - } - catch (Exception e) - { + } catch (Exception e) { /* * May fail if the connection is already closed. */ } - try - { + try { mSocket.close(); - } - catch (Exception e) - { + } catch (Exception e) { /* * May fail if the connection is already closed. */ @@ -364,46 +294,38 @@ public class Pop3Store extends Store } @Override - public String getName() - { + public String getName() { return mName; } @Override - public boolean create(FolderType type) throws MessagingException - { + public boolean create(FolderType type) throws MessagingException { return false; } @Override - public boolean exists() throws MessagingException - { + public boolean exists() throws MessagingException { return mName.equalsIgnoreCase("INBOX"); } @Override - public int getMessageCount() - { + public int getMessageCount() { return mMessageCount; } @Override - public int getUnreadMessageCount() throws MessagingException - { + public int getUnreadMessageCount() throws MessagingException { return -1; } @Override - public int getFlaggedMessageCount() throws MessagingException - { + public int getFlaggedMessageCount() throws MessagingException { return -1; } @Override - public Message getMessage(String uid) throws MessagingException - { + public Message getMessage(String uid) throws MessagingException { Pop3Message message = mUidToMsgMap.get(uid); - if (message == null) - { + if (message == null) { message = new Pop3Message(uid, this); } return message; @@ -411,28 +333,21 @@ public class Pop3Store extends Store @Override public Message[] getMessages(int start, int end, Date earliestDate, MessageRetrievalListener listener) - throws MessagingException - { - if (start < 1 || end < 1 || end < start) - { + throws MessagingException { + if (start < 1 || end < 1 || end < start) { throw new MessagingException(String.format("Invalid message set %d %d", start, end)); } - try - { + try { indexMsgNums(start, end); - } - catch (IOException ioe) - { + } catch (IOException ioe) { throw new MessagingException("getMessages", ioe); } ArrayList messages = new ArrayList(); int i = 0; - for (int msgNum = start; msgNum <= end; msgNum++) - { + for (int msgNum = start; msgNum <= end; msgNum++) { Pop3Message message = mMsgNumToMsgMap.get(msgNum); - if (message == null) - { + if (message == null) { /* * There could be gaps in the message numbers or malformed * responses which lead to "gaps" in mMsgNumToMsgMap. @@ -442,13 +357,11 @@ public class Pop3Store extends Store continue; } - if (listener != null) - { + if (listener != null) { listener.messageStarted(message.getUid(), i++, (end - start) + 1); } messages.add(message); - if (listener != null) - { + if (listener != null) { listener.messageFinished(message, i++, (end - start) + 1); } } @@ -464,31 +377,24 @@ public class Pop3Store extends Store * @throws IOException */ private void indexMsgNums(int start, int end) - throws MessagingException, IOException - { + throws MessagingException, IOException { int unindexedMessageCount = 0; - for (int msgNum = start; msgNum <= end; msgNum++) - { - if (mMsgNumToMsgMap.get(msgNum) == null) - { + for (int msgNum = start; msgNum <= end; msgNum++) { + if (mMsgNumToMsgMap.get(msgNum) == null) { unindexedMessageCount++; } } - if (unindexedMessageCount == 0) - { + if (unindexedMessageCount == 0) { return; } - if (unindexedMessageCount < 50 && mMessageCount > 5000) - { + if (unindexedMessageCount < 50 && mMessageCount > 5000) { /* * In extreme cases we'll do a UIDL command per message instead of a bulk * download. */ - for (int msgNum = start; msgNum <= end; msgNum++) - { + for (int msgNum = start; msgNum <= end; msgNum++) { Pop3Message message = mMsgNumToMsgMap.get(msgNum); - if (message == null) - { + if (message == null) { String response = executeSimpleCommand("UIDL " + msgNum); int uidIndex = response.lastIndexOf(' '); String msgUid = response.substring(uidIndex + 1); @@ -496,19 +402,14 @@ public class Pop3Store extends Store indexMessage(msgNum, message); } } - } - else - { + } else { String response = executeSimpleCommand("UIDL"); - while ((response = readLine()) != null) - { - if (response.equals(".")) - { + while ((response = readLine()) != null) { + if (response.equals(".")) { break; } String[] uidParts = response.split(" "); - if ((uidParts.length >= 3) && "+OK".equals(uidParts[0])) - { + if ((uidParts.length >= 3) && "+OK".equals(uidParts[0])) { /* * At least one server software places a "+OK" in * front of every line in the unique-id listing. @@ -519,15 +420,12 @@ public class Pop3Store extends Store uidParts[0] = uidParts[1]; uidParts[1] = uidParts[2]; } - if (uidParts.length >= 2) - { + if (uidParts.length >= 2) { Integer msgNum = Integer.valueOf(uidParts[0]); String msgUid = uidParts[1]; - if (msgNum >= start && msgNum <= end) - { + if (msgNum >= start && msgNum <= end) { Pop3Message message = mMsgNumToMsgMap.get(msgNum); - if (message == null) - { + if (message == null) { message = new Pop3Message(msgUid, this); indexMessage(msgNum, message); } @@ -538,22 +436,17 @@ public class Pop3Store extends Store } private void indexUids(ArrayList uids) - throws MessagingException, IOException - { + throws MessagingException, IOException { HashSet unindexedUids = new HashSet(); - for (String uid : uids) - { - if (mUidToMsgMap.get(uid) == null) - { - if (K9.DEBUG && K9.DEBUG_PROTOCOL_POP3) - { + for (String uid : uids) { + if (mUidToMsgMap.get(uid) == null) { + if (K9.DEBUG && K9.DEBUG_PROTOCOL_POP3) { Log.d(K9.LOG_TAG, "Need to index UID " + uid); } unindexedUids.add(uid); } } - if (unindexedUids.size() == 0) - { + if (unindexedUids.size() == 0) { return; } /* @@ -562,29 +455,23 @@ public class Pop3Store extends Store * would be trying UIDL for the latest X messages and praying. */ String response = executeSimpleCommand("UIDL"); - while ((response = readLine()) != null) - { - if (response.equals(".")) - { + while ((response = readLine()) != null) { + if (response.equals(".")) { break; } String[] uidParts = response.split(" "); // Ignore messages without a unique-id - if (uidParts.length >= 2) - { + if (uidParts.length >= 2) { Integer msgNum = Integer.valueOf(uidParts[0]); String msgUid = uidParts[1]; - if (unindexedUids.contains(msgUid)) - { - if (K9.DEBUG && K9.DEBUG_PROTOCOL_POP3) - { + if (unindexedUids.contains(msgUid)) { + if (K9.DEBUG && K9.DEBUG_PROTOCOL_POP3) { Log.d(K9.LOG_TAG, "Got msgNum " + msgNum + " for UID " + msgUid); } Pop3Message message = mUidToMsgMap.get(msgUid); - if (message == null) - { + if (message == null) { message = new Pop3Message(msgUid, this); } indexMessage(msgNum, message); @@ -593,10 +480,8 @@ public class Pop3Store extends Store } } - private void indexMessage(int msgNum, Pop3Message message) - { - if (K9.DEBUG && K9.DEBUG_PROTOCOL_POP3) - { + private void indexMessage(int msgNum, Pop3Message message) { + if (K9.DEBUG && K9.DEBUG_PROTOCOL_POP3) { Log.d(K9.LOG_TAG, "Adding index for UID " + message.getUid() + " to msgNum " + msgNum); } mMsgNumToMsgMap.put(msgNum, message); @@ -605,15 +490,13 @@ public class Pop3Store extends Store } @Override - public Message[] getMessages(MessageRetrievalListener listener) throws MessagingException - { + public Message[] getMessages(MessageRetrievalListener listener) throws MessagingException { throw new UnsupportedOperationException("Pop3: No getMessages"); } @Override public Message[] getMessages(String[] uids, MessageRetrievalListener listener) - throws MessagingException - { + throws MessagingException { throw new UnsupportedOperationException("Pop3: No getMessages by uids"); } @@ -626,29 +509,21 @@ public class Pop3Store extends Store */ @Override public void fetch(Message[] messages, FetchProfile fp, MessageRetrievalListener listener) - throws MessagingException - { - if (messages == null || messages.length == 0) - { + throws MessagingException { + if (messages == null || messages.length == 0) { return; } ArrayList uids = new ArrayList(); - for (Message message : messages) - { + for (Message message : messages) { uids.add(message.getUid()); } - try - { + try { indexUids(uids); - } - catch (IOException ioe) - { + } catch (IOException ioe) { throw new MessagingException("fetch", ioe); } - try - { - if (fp.contains(FetchProfile.Item.ENVELOPE)) - { + try { + if (fp.contains(FetchProfile.Item.ENVELOPE)) { /* * We pass the listener only if there are other things to do in the * FetchProfile. Since fetchEnvelop works in bulk and eveything else @@ -657,89 +532,67 @@ public class Pop3Store extends Store */ fetchEnvelope(messages, fp.size() == 1 ? listener : null); } - } - catch (IOException ioe) - { + } catch (IOException ioe) { throw new MessagingException("fetch", ioe); } - for (int i = 0, count = messages.length; i < count; i++) - { + for (int i = 0, count = messages.length; i < count; i++) { Message message = messages[i]; - if (!(message instanceof Pop3Message)) - { + if (!(message instanceof Pop3Message)) { throw new MessagingException("Pop3Store.fetch called with non-Pop3 Message"); } Pop3Message pop3Message = (Pop3Message)message; - try - { - if (listener != null && !fp.contains(FetchProfile.Item.ENVELOPE)) - { + try { + if (listener != null && !fp.contains(FetchProfile.Item.ENVELOPE)) { listener.messageStarted(pop3Message.getUid(), i, count); } - if (fp.contains(FetchProfile.Item.BODY)) - { + if (fp.contains(FetchProfile.Item.BODY)) { fetchBody(pop3Message, -1); - } - else if (fp.contains(FetchProfile.Item.BODY_SANE)) - { + } else if (fp.contains(FetchProfile.Item.BODY_SANE)) { /* * To convert the suggested download size we take the size * divided by the maximum line size (76). */ fetchBody(pop3Message, (mAccount.getMaximumAutoDownloadMessageSize() / 76)); - } - else if (fp.contains(FetchProfile.Item.STRUCTURE)) - { + } else if (fp.contains(FetchProfile.Item.STRUCTURE)) { /* * If the user is requesting STRUCTURE we are required to set the body * to null since we do not support the function. */ pop3Message.setBody(null); } - if (listener != null && !(fp.contains(FetchProfile.Item.ENVELOPE) && fp.size() == 1)) - { + if (listener != null && !(fp.contains(FetchProfile.Item.ENVELOPE) && fp.size() == 1)) { listener.messageFinished(message, i, count); } - } - catch (IOException ioe) - { + } catch (IOException ioe) { throw new MessagingException("Unable to fetch message", ioe); } } } private void fetchEnvelope(Message[] messages, - MessageRetrievalListener listener) throws IOException, MessagingException - { + MessageRetrievalListener listener) throws IOException, MessagingException { int unsizedMessages = 0; - for (Message message : messages) - { - if (message.getSize() == -1) - { + for (Message message : messages) { + if (message.getSize() == -1) { unsizedMessages++; } } - if (unsizedMessages == 0) - { + if (unsizedMessages == 0) { return; } - if (unsizedMessages < 50 && mMessageCount > 5000) - { + if (unsizedMessages < 50 && mMessageCount > 5000) { /* * In extreme cases we'll do a command per message instead of a bulk request * to hopefully save some time and bandwidth. */ - for (int i = 0, count = messages.length; i < count; i++) - { + for (int i = 0, count = messages.length; i < count; i++) { Message message = messages[i]; - if (!(message instanceof Pop3Message)) - { + if (!(message instanceof Pop3Message)) { throw new MessagingException("Pop3Store.fetch called with non-Pop3 Message"); } Pop3Message pop3Message = (Pop3Message)message; - if (listener != null) - { + if (listener != null) { listener.messageStarted(pop3Message.getUid(), i, count); } String response = executeSimpleCommand(String.format("LIST %d", @@ -748,40 +601,31 @@ public class Pop3Store extends Store //int msgNum = Integer.parseInt(listParts[1]); int msgSize = Integer.parseInt(listParts[2]); pop3Message.setSize(msgSize); - if (listener != null) - { + if (listener != null) { listener.messageFinished(pop3Message, i, count); } } - } - else - { + } else { HashSet msgUidIndex = new HashSet(); - for (Message message : messages) - { + for (Message message : messages) { msgUidIndex.add(message.getUid()); } int i = 0, count = messages.length; String response = executeSimpleCommand("LIST"); - while ((response = readLine()) != null) - { - if (response.equals(".")) - { + while ((response = readLine()) != null) { + if (response.equals(".")) { break; } String[] listParts = response.split(" "); int msgNum = Integer.parseInt(listParts[0]); int msgSize = Integer.parseInt(listParts[1]); Pop3Message pop3Message = mMsgNumToMsgMap.get(msgNum); - if (pop3Message != null && msgUidIndex.contains(pop3Message.getUid())) - { - if (listener != null) - { + if (pop3Message != null && msgUidIndex.contains(pop3Message.getUid())) { + if (listener != null) { listener.messageStarted(pop3Message.getUid(), i, count); } pop3Message.setSize(msgSize); - if (listener != null) - { + if (listener != null) { listener.messageFinished(pop3Message, i, count); } i++; @@ -800,40 +644,30 @@ public class Pop3Store extends Store * @param lines */ private void fetchBody(Pop3Message message, int lines) - throws IOException, MessagingException - { + throws IOException, MessagingException { String response = null; - if (lines == -1 || !mCapabilities.top) - { + if (lines == -1 || !mCapabilities.top) { response = executeSimpleCommand(String.format("RETR %d", mUidToMsgNumMap.get(message.getUid()))); - } - else - { + } else { response = executeSimpleCommand(String.format("TOP %d %d", mUidToMsgNumMap.get(message.getUid()), lines)); } - if (response != null) - { - try - { + if (response != null) { + try { message.parse(new Pop3ResponseInputStream(mIn)); - if (lines == -1 || !mCapabilities.top) - { + if (lines == -1 || !mCapabilities.top) { message.setFlag(Flag.X_DOWNLOADED_FULL, true); } - } - catch (MessagingException me) - { + } catch (MessagingException me) { /* * If we're only downloading headers it's possible * we'll get a broken MIME message which we're not * real worried about. If we've downloaded the body * and can't parse it we need to let the user know. */ - if (lines == -1) - { + if (lines == -1) { throw me; } } @@ -841,72 +675,58 @@ public class Pop3Store extends Store } @Override - public Flag[] getPermanentFlags() - { + public Flag[] getPermanentFlags() { return PERMANENT_FLAGS; } @Override - public void appendMessages(Message[] messages) throws MessagingException - { + public void appendMessages(Message[] messages) throws MessagingException { } @Override - public void delete(boolean recurse) throws MessagingException - { + public void delete(boolean recurse) throws MessagingException { } @Override - public void delete(Message[] msgs, String trashFolderName) throws MessagingException - { + public void delete(Message[] msgs, String trashFolderName) throws MessagingException { setFlags(msgs, new Flag[] { Flag.DELETED }, true); } @Override - public String getUidFromMessageId(Message message) throws MessagingException - { + public String getUidFromMessageId(Message message) throws MessagingException { return null; } @Override public void setFlags(Flag[] flags, boolean value) - throws MessagingException - { + throws MessagingException { Message[] messages = getMessages(null); setFlags(messages, flags, value); } @Override public void setFlags(Message[] messages, Flag[] flags, boolean value) - throws MessagingException - { - if (!value || !Utility.arrayContains(flags, Flag.DELETED)) - { + throws MessagingException { + if (!value || !Utility.arrayContains(flags, Flag.DELETED)) { /* * The only flagging we support is setting the Deleted flag. */ return; } ArrayList uids = new ArrayList(); - try - { - for (Message message : messages) - { + try { + for (Message message : messages) { uids.add(message.getUid()); } indexUids(uids); - } - catch (IOException ioe) - { + } catch (IOException ioe) { throw new MessagingException("Could not get message number for uid " + uids, ioe); } - for (Message message : messages) - { + for (Message message : messages) { Integer msgNum = mUidToMsgNumMap.get(message.getUid()); - if (msgNum == null) - { + if (msgNum == null) { MessagingException me = new MessagingException("Could not delete message " + message.getUid() + " because no msgNum found; permanent error"); me.setPermanentFailure(true); @@ -916,82 +736,56 @@ public class Pop3Store extends Store } } - private String readLine() throws IOException - { + private String readLine() throws IOException { StringBuffer sb = new StringBuffer(); int d = mIn.read(); - if (d == -1) - { + if (d == -1) { throw new IOException("End of stream reached while trying to read line."); } - do - { - if (((char)d) == '\r') - { + do { + if (((char)d) == '\r') { continue; - } - else if (((char)d) == '\n') - { + } else if (((char)d) == '\n') { break; - } - else - { + } else { sb.append((char)d); } - } - while ((d = mIn.read()) != -1); + } while ((d = mIn.read()) != -1); String ret = sb.toString(); - if (K9.DEBUG && K9.DEBUG_PROTOCOL_POP3) - { + if (K9.DEBUG && K9.DEBUG_PROTOCOL_POP3) { Log.d(K9.LOG_TAG, "<<< " + ret); } return ret; } - private void writeLine(String s) throws IOException - { + private void writeLine(String s) throws IOException { mOut.write(s.getBytes()); mOut.write('\r'); mOut.write('\n'); mOut.flush(); } - private Pop3Capabilities getCapabilities() throws IOException - { + private Pop3Capabilities getCapabilities() throws IOException { Pop3Capabilities capabilities = new Pop3Capabilities(); - try - { + try { String response = executeSimpleCommand("CAPA"); - while ((response = readLine()) != null) - { - if (response.equals(".")) - { + while ((response = readLine()) != null) { + if (response.equals(".")) { break; } - if (response.equalsIgnoreCase("STLS")) - { + if (response.equalsIgnoreCase("STLS")) { capabilities.stls = true; - } - else if (response.equalsIgnoreCase("UIDL")) - { + } else if (response.equalsIgnoreCase("UIDL")) { capabilities.uidl = true; - } - else if (response.equalsIgnoreCase("PIPELINING")) - { + } else if (response.equalsIgnoreCase("PIPELINING")) { capabilities.pipelining = true; - } - else if (response.equalsIgnoreCase("USER")) - { + } else if (response.equalsIgnoreCase("USER")) { capabilities.user = true; - } - else if (response.equalsIgnoreCase("TOP")) - { + } else if (response.equalsIgnoreCase("TOP")) { capabilities.top = true; } } - } - catch (MessagingException me) - { + } catch (MessagingException me) { /* * The server may not support the CAPA command, so we just eat this Exception * and allow the empty capabilities object to be returned. @@ -1000,28 +794,20 @@ public class Pop3Store extends Store return capabilities; } - private String executeSimpleCommand(String command) throws MessagingException - { + private String executeSimpleCommand(String command) throws MessagingException { return executeSimpleCommand(command, false); } - private String executeSimpleCommand(String command, boolean sensitive) throws MessagingException - { - try - { + private String executeSimpleCommand(String command, boolean sensitive) throws MessagingException { + try { open(OpenMode.READ_WRITE); - if (command != null) - { - if (K9.DEBUG && K9.DEBUG_PROTOCOL_POP3) - { - if (sensitive && !K9.DEBUG_SENSITIVE) - { + if (command != null) { + if (K9.DEBUG && K9.DEBUG_PROTOCOL_POP3) { + if (sensitive && !K9.DEBUG_SENSITIVE) { Log.d(K9.LOG_TAG, ">>> " + "[Command Hidden, Enable Sensitive Debug Logging To Show]"); - } - else - { + } else { Log.d(K9.LOG_TAG, ">>> " + command); } } @@ -1030,78 +816,63 @@ public class Pop3Store extends Store } String response = readLine(); - if (response.length() > 1 && response.charAt(0) == '-') - { + if (response.length() > 1 && response.charAt(0) == '-') { throw new MessagingException(response); } return response; - } - catch (MessagingException me) - { + } catch (MessagingException me) { throw me; - } - catch (Exception e) - { + } catch (Exception e) { closeIO(); throw new MessagingException("Unable to execute POP3 command", e); } } @Override - public boolean supportsFetchingFlags() - { + public boolean supportsFetchingFlags() { return false; } @Override - public boolean equals(Object o) - { - if (o instanceof Pop3Folder) - { + public boolean equals(Object o) { + if (o instanceof Pop3Folder) { return ((Pop3Folder) o).mName.equals(mName); } return super.equals(o); } @Override - public int hashCode() - { + public int hashCode() { return mName.hashCode(); } }//Pop3Folder - static class Pop3Message extends MimeMessage - { - public Pop3Message(String uid, Pop3Folder folder) - { + static class Pop3Message extends MimeMessage { + public Pop3Message(String uid, Pop3Folder folder) { mUid = uid; mFolder = folder; mSize = -1; } - public void setSize(int size) - { + public void setSize(int size) { mSize = size; } @Override - protected void parse(InputStream in) throws IOException, MessagingException - { + protected void parse(InputStream in) throws IOException, MessagingException { super.parse(in); } @Override - public void setFlag(Flag flag, boolean set) throws MessagingException - { + public void setFlag(Flag flag, boolean set) throws MessagingException { super.setFlag(flag, set); mFolder.setFlags(new Message[] { this }, new Flag[] { flag }, set); } @Override - public void delete(String trashFolderName) throws MessagingException - { + public void delete(String trashFolderName) throws MessagingException { // try // { // Poor POP3 users, we can't copy the message to the Trash folder, but they still want a delete @@ -1114,8 +885,7 @@ public class Pop3Store extends Store } } - static class Pop3Capabilities - { + static class Pop3Capabilities { public boolean stls; public boolean top; public boolean user; @@ -1123,8 +893,7 @@ public class Pop3Store extends Store public boolean pipelining; @Override - public String toString() - { + public String toString() { return String.format("STLS %b, TOP %b, USER %b, UIDL %b, PIPELINING %b", stls, top, @@ -1134,30 +903,24 @@ public class Pop3Store extends Store } } - static class Pop3ResponseInputStream extends InputStream - { + static class Pop3ResponseInputStream extends InputStream { InputStream mIn; boolean mStartOfLine = true; boolean mFinished; - public Pop3ResponseInputStream(InputStream in) - { + public Pop3ResponseInputStream(InputStream in) { mIn = in; } @Override - public int read() throws IOException - { - if (mFinished) - { + public int read() throws IOException { + if (mFinished) { return -1; } int d = mIn.read(); - if (mStartOfLine && d == '.') - { + if (mStartOfLine && d == '.') { d = mIn.read(); - if (d == '\r') - { + if (d == '\r') { mFinished = true; mIn.read(); return -1; diff --git a/src/com/fsck/k9/mail/store/StorageManager.java b/src/com/fsck/k9/mail/store/StorageManager.java index 83eb6b74b..9c52b7114 100644 --- a/src/com/fsck/k9/mail/store/StorageManager.java +++ b/src/com/fsck/k9/mail/store/StorageManager.java @@ -26,8 +26,7 @@ import com.fsck.k9.service.MailService; * Manager for different {@link StorageProvider} -classes that abstract access * to sd-cards, additional internal memory and other storage-locations. */ -public class StorageManager -{ +public class StorageManager { /** * Provides entry points (File objects) to an underlying storage, @@ -39,8 +38,7 @@ public class StorageManager * online later). *

    */ - public static interface StorageProvider - { + public static interface StorageProvider { /** * Retrieve the uniquely identifier for the current implementation. @@ -139,8 +137,7 @@ public class StorageManager * Interface for components wanting to be notified of storage availability * events. */ - public static interface StorageListener - { + public static interface StorageListener { /** * Invoked on storage mount (with read/write access). * @@ -176,8 +173,7 @@ public class StorageManager * points using {@link StorageManager#isMountPoint(File)}. *

    */ - public abstract static class FixedStorageProviderBase implements StorageProvider - { + public abstract static class FixedStorageProviderBase implements StorageProvider { /** * The root of the denoted storage. Used for mount points checking. */ @@ -189,8 +185,7 @@ public class StorageManager protected File mApplicationDir; @Override - public void init(final Context context) - { + public void init(final Context context) { mRoot = computeRoot(context); // use /k9 mApplicationDir = new File(mRoot, "k9"); @@ -205,42 +200,34 @@ public class StorageManager protected abstract boolean supportsVendor(); @Override - public boolean isReady(Context context) - { - try - { + public boolean isReady(Context context) { + try { final File root = mRoot.getCanonicalFile(); return isMountPoint(root) && Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()); - } - catch (IOException e) - { + } catch (IOException e) { Log.w(K9.LOG_TAG, "Specified root isn't ready: " + mRoot, e); return false; } } @Override - public final boolean isSupported(Context context) - { + public final boolean isSupported(Context context) { return mRoot.isDirectory() && supportsVendor(); } @Override - public File getDatabase(Context context, String id) - { + public File getDatabase(Context context, String id) { return new File(mApplicationDir, id + ".db"); } @Override - public File getAttachmentDirectory(Context context, String id) - { + public File getAttachmentDirectory(Context context, String id) { return new File(mApplicationDir, id + ".db_att"); } @Override - public final File getRoot(Context context) - { + public final File getRoot(Context context) { return mRoot; } @@ -268,60 +255,51 @@ public class StorageManager * The underlying storage has always been used by K-9. *

    */ - public static class InternalStorageProvider implements StorageProvider - { + public static class InternalStorageProvider implements StorageProvider { public static final String ID = "InternalStorage"; protected File mRoot; @Override - public String getId() - { + public String getId() { return ID; } @Override - public void init(Context context) - { + public void init(Context context) { // XXX mRoot = new File("/"); } @Override - public String getName(Context context) - { + public String getName(Context context) { return context.getString(R.string.local_storage_provider_internal_label); } @Override - public boolean isSupported(Context context) - { + public boolean isSupported(Context context) { return true; } @Override - public File getDatabase(Context context, String id) - { + public File getDatabase(Context context, String id) { return context.getDatabasePath(id + ".db"); } @Override - public File getAttachmentDirectory(Context context, String id) - { + public File getAttachmentDirectory(Context context, String id) { // we store attachments in the database directory return context.getDatabasePath(id + ".db_att"); } @Override - public boolean isReady(Context context) - { + public boolean isReady(Context context) { return true; } @Override - public File getRoot(Context context) - { + public File getRoot(Context context) { return mRoot; } } @@ -344,8 +322,7 @@ public class StorageManager * mount/unmount/USB share events. *

    */ - public static class ExternalStorageProvider implements StorageProvider - { + public static class ExternalStorageProvider implements StorageProvider { public static final String ID = "ExternalStorage"; @@ -359,52 +336,44 @@ public class StorageManager */ protected File mApplicationDirectory; - public String getId() - { + public String getId() { return ID; } @Override - public void init(Context context) - { + public void init(Context context) { mRoot = Environment.getExternalStorageDirectory(); mApplicationDirectory = new File(new File(new File(new File(mRoot, "Android"), "data"), context.getPackageName()), "files"); } @Override - public String getName(Context context) - { + public String getName(Context context) { return context.getString(R.string.local_storage_provider_external_label); } @Override - public boolean isSupported(Context context) - { + public boolean isSupported(Context context) { return true; } @Override - public File getDatabase(Context context, String id) - { + public File getDatabase(Context context, String id) { return new File(mApplicationDirectory, id + ".db"); } @Override - public File getAttachmentDirectory(Context context, String id) - { + public File getAttachmentDirectory(Context context, String id) { return new File(mApplicationDirectory, id + ".db_att"); } @Override - public boolean isReady(Context context) - { + public boolean isReady(Context context) { return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()); } @Override - public File getRoot(Context context) - { + public File getRoot(Context context) { return mRoot; } } @@ -420,32 +389,27 @@ public class StorageManager * * @see FixedStorageProviderBase */ - public static class HtcIncredibleStorageProvider extends FixedStorageProviderBase - { + public static class HtcIncredibleStorageProvider extends FixedStorageProviderBase { public static final String ID = "HtcIncredibleStorage"; - public String getId() - { + public String getId() { return ID; } @Override - public String getName(Context context) - { + public String getName(Context context) { return context.getString(R.string.local_storage_provider_samsunggalaxy_label, Build.MODEL); } @Override - protected boolean supportsVendor() - { + protected boolean supportsVendor() { return "inc".equals(Build.DEVICE); } @Override - protected File computeRoot(Context context) - { + protected File computeRoot(Context context) { return new File("/emmc"); } } @@ -461,34 +425,29 @@ public class StorageManager * * @see FixedStorageProviderBase */ - public static class SamsungGalaxySStorageProvider extends FixedStorageProviderBase - { + public static class SamsungGalaxySStorageProvider extends FixedStorageProviderBase { public static final String ID = "SamsungGalaxySStorage"; - public String getId() - { + public String getId() { return ID; } @Override - public String getName(Context context) - { + public String getName(Context context) { return context.getString(R.string.local_storage_provider_samsunggalaxy_label, Build.MODEL); } @Override - protected boolean supportsVendor() - { + protected boolean supportsVendor() { // FIXME return "GT-I5800".equals(Build.DEVICE) || "GT-I9000".equals(Build.DEVICE) || "SGH-T959".equals(Build.DEVICE) || "SGH-I897".equals(Build.DEVICE); } @Override - protected File computeRoot(Context context) - { + protected File computeRoot(Context context) { return Environment.getExternalStorageDirectory(); // was: new // File("/sdcard") } @@ -497,8 +456,7 @@ public class StorageManager /** * Stores storage provider locking informations */ - public static class SynchronizationAid - { + public static class SynchronizationAid { /** * {@link Lock} has a thread semantic so it can't be released from * another thread - this flags act as a holder for the unmount state @@ -535,10 +493,8 @@ public class StorageManager private static transient StorageManager instance; - public static synchronized StorageManager getInstance(final Application application) - { - if (instance == null) - { + public static synchronized StorageManager getInstance(final Application application) { + if (instance == null) { instance = new StorageManager(application); } return instance; @@ -550,12 +506,9 @@ public class StorageManager * @return Whether the specified file matches a filesystem root. * @throws IOException */ - public static boolean isMountPoint(final File file) - { - for (final File root : File.listRoots()) - { - if (root.equals(file)) - { + public static boolean isMountPoint(final File file) { + for (final File root : File.listRoots()) { + if (root.equals(file)) { return true; } } @@ -568,10 +521,8 @@ public class StorageManager * @throws NullPointerException * If application is null. */ - protected StorageManager(final Application application) throws NullPointerException - { - if (application == null) - { + protected StorageManager(final Application application) throws NullPointerException { + if (application == null) { throw new NullPointerException("No application instance given"); } @@ -592,11 +543,9 @@ public class StorageManager */ final List allProviders = Arrays.asList(new InternalStorageProvider(), new ExternalStorageProvider()); - for (final StorageProvider provider : allProviders) - { + for (final StorageProvider provider : allProviders) { // check for provider compatibility - if (provider.isSupported(mApplication)) - { + if (provider.isSupported(mApplication)) { // provider is compatible! proceeding provider.init(application); @@ -610,8 +559,7 @@ public class StorageManager /** * @return Never null. */ - public String getDefaultProviderId() - { + public String getDefaultProviderId() { // assume there is at least 1 provider defined return mProviders.entrySet().iterator().next().getKey(); } @@ -621,8 +569,7 @@ public class StorageManager * Never null. * @return null if not found. */ - protected StorageProvider getProvider(final String providerId) - { + protected StorageProvider getProvider(final String providerId) { return mProviders.get(providerId); } @@ -633,8 +580,7 @@ public class StorageManager * Never null. * @return The resolved database file for the given provider ID. */ - public File getDatabase(final String dbName, final String providerId) - { + public File getDatabase(final String dbName, final String providerId) { StorageProvider provider = getProvider(providerId); // TODO fallback to internal storage if no provider return provider.getDatabase(mApplication, dbName); @@ -647,8 +593,7 @@ public class StorageManager * Never null. * @return The resolved attachement directory for the given provider ID. */ - public File getAttachmentDirectory(final String dbName, final String providerId) - { + public File getAttachmentDirectory(final String dbName, final String providerId) { StorageProvider provider = getProvider(providerId); // TODO fallback to internal storage if no provider return provider.getAttachmentDirectory(mApplication, dbName); @@ -659,11 +604,9 @@ public class StorageManager * Never null. * @return Whether the specified provider is ready for read/write operations */ - public boolean isReady(final String providerId) - { + public boolean isReady(final String providerId) { StorageProvider provider = getProvider(providerId); - if (provider == null) - { + if (provider == null) { Log.w(K9.LOG_TAG, "Storage-Provider \"" + providerId + "\" does not exist"); return false; } @@ -676,11 +619,9 @@ public class StorageManager * @see StorageManager * @see StorageProvider#isSupported(Context) */ - public Map getAvailableProviders() - { + public Map getAvailableProviders() { final Map result = new LinkedHashMap(); - for (final Map.Entry entry : mProviders.entrySet()) - { + for (final Map.Entry entry : mProviders.entrySet()) { result.put(entry.getKey(), entry.getValue().getName(mApplication)); } return result; @@ -689,22 +630,16 @@ public class StorageManager /** * @param path */ - public void onBeforeUnmount(final String path) - { + public void onBeforeUnmount(final String path) { Log.i(K9.LOG_TAG, "storage path \"" + path + "\" unmounting"); final StorageProvider provider = resolveProvider(path); - if (provider == null) - { + if (provider == null) { return; } - for (final StorageListener listener : mListeners) - { - try - { + for (final StorageListener listener : mListeners) { + try { listener.onUnmount(provider.getId()); - } - catch (Exception e) - { + } catch (Exception e) { Log.w(K9.LOG_TAG, "Error while notifying StorageListener", e); } } @@ -714,12 +649,10 @@ public class StorageManager sync.writeLock.unlock(); } - public void onAfterUnmount(final String path) - { + public void onAfterUnmount(final String path) { Log.i(K9.LOG_TAG, "storage path \"" + path + "\" unmounted"); final StorageProvider provider = resolveProvider(path); - if (provider == null) - { + if (provider == null) { return; } final SynchronizationAid sync = mProviderLocks.get(resolveProvider(path)); @@ -732,27 +665,20 @@ public class StorageManager * @param path * @param readOnly */ - public void onMount(final String path, final boolean readOnly) - { + public void onMount(final String path, final boolean readOnly) { Log.i(K9.LOG_TAG, "storage path \"" + path + "\" mounted readOnly=" + readOnly); - if (readOnly) - { + if (readOnly) { return; } final StorageProvider provider = resolveProvider(path); - if (provider == null) - { + if (provider == null) { return; } - for (final StorageListener listener : mListeners) - { - try - { + for (final StorageListener listener : mListeners) { + try { listener.onMount(provider.getId()); - } - catch (Exception e) - { + } catch (Exception e) { Log.w(K9.LOG_TAG, "Error while notifying StorageListener", e); } } @@ -766,25 +692,20 @@ public class StorageManager * Never null. * @return The corresponding provider. null if no match. */ - protected StorageProvider resolveProvider(final String path) - { - for (final StorageProvider provider : mProviders.values()) - { - if (path.equals(provider.getRoot(mApplication).getAbsolutePath())) - { + protected StorageProvider resolveProvider(final String path) { + for (final StorageProvider provider : mProviders.values()) { + if (path.equals(provider.getRoot(mApplication).getAbsolutePath())) { return provider; } } return null; } - public void addListener(final StorageListener listener) - { + public void addListener(final StorageListener listener) { mListeners.add(listener); } - public void removeListener(final StorageListener listener) - { + public void removeListener(final StorageListener listener) { mListeners.remove(listener); } @@ -800,33 +721,26 @@ public class StorageManager * @throws UnavailableStorageException * If the storage can't be locked. */ - public void lockProvider(final String providerId) throws UnavailableStorageException - { + public void lockProvider(final String providerId) throws UnavailableStorageException { final StorageProvider provider = getProvider(providerId); - if (provider == null) - { + if (provider == null) { throw new UnavailableStorageException("StorageProvider not found: " + providerId); } // lock provider final SynchronizationAid sync = mProviderLocks.get(provider); final boolean locked = sync.readLock.tryLock(); - if (!locked || (locked && sync.unmounting)) - { - if (locked) - { + if (!locked || (locked && sync.unmounting)) { + if (locked) { sync.readLock.unlock(); } throw new UnavailableStorageException("StorageProvider is unmounting"); - } - else if (locked && !provider.isReady(mApplication)) - { + } else if (locked && !provider.isReady(mApplication)) { sync.readLock.unlock(); throw new UnavailableStorageException("StorageProvider not ready"); } } - public void unlockProvider(final String providerId) - { + public void unlockProvider(final String providerId) { final StorageProvider provider = getProvider(providerId); final SynchronizationAid sync = mProviderLocks.get(provider); sync.readLock.unlock(); diff --git a/src/com/fsck/k9/mail/store/TrustManagerFactory.java b/src/com/fsck/k9/mail/store/TrustManagerFactory.java index f10b8990b..b6ead8d9d 100644 --- a/src/com/fsck/k9/mail/store/TrustManagerFactory.java +++ b/src/com/fsck/k9/mail/store/TrustManagerFactory.java @@ -20,8 +20,7 @@ import java.security.cert.X509Certificate; import java.util.HashMap; import java.util.Map; -public final class TrustManagerFactory -{ +public final class TrustManagerFactory { private static final String LOG_TAG = "TrustManagerFactory"; private static X509TrustManager defaultTrustManager; @@ -34,45 +33,35 @@ public final class TrustManagerFactory private static KeyStore keyStore; - private static class SimpleX509TrustManager implements X509TrustManager - { + private static class SimpleX509TrustManager implements X509TrustManager { public void checkClientTrusted(X509Certificate[] chain, String authType) - throws CertificateException - { + throws CertificateException { } public void checkServerTrusted(X509Certificate[] chain, String authType) - throws CertificateException - { + throws CertificateException { } - public X509Certificate[] getAcceptedIssuers() - { + public X509Certificate[] getAcceptedIssuers() { return null; } } - private static class SecureX509TrustManager implements X509TrustManager - { + private static class SecureX509TrustManager implements X509TrustManager { private static final Map mTrustManager = new HashMap(); private final String mHost; - private SecureX509TrustManager(String host) - { + private SecureX509TrustManager(String host) { mHost = host; } - public synchronized static X509TrustManager getInstance(String host) - { + public synchronized static X509TrustManager getInstance(String host) { SecureX509TrustManager trustManager; - if (mTrustManager.containsKey(host)) - { + if (mTrustManager.containsKey(host)) { trustManager = mTrustManager.get(host); - } - else - { + } else { trustManager = new SecureX509TrustManager(host); mTrustManager.put(host, trustManager); } @@ -81,35 +70,25 @@ public final class TrustManagerFactory } public void checkClientTrusted(X509Certificate[] chain, String authType) - throws CertificateException - { + throws CertificateException { defaultTrustManager.checkClientTrusted(chain, authType); } public void checkServerTrusted(X509Certificate[] chain, String authType) - throws CertificateException - { + throws CertificateException { TrustManagerFactory.setLastCertChain(chain); - try - { + try { defaultTrustManager.checkServerTrusted(chain, authType); - } - catch (CertificateException e) - { + } catch (CertificateException e) { localTrustManager.checkServerTrusted(new X509Certificate[] {chain[0]}, authType); } - if (!DomainNameChecker.match(chain[0], mHost)) - { - try - { + if (!DomainNameChecker.match(chain[0], mHost)) { + try { String dn = chain[0].getSubjectDN().toString(); - if ((dn != null) && (dn.equalsIgnoreCase(keyStore.getCertificateAlias(chain[0])))) - { + if ((dn != null) && (dn.equalsIgnoreCase(keyStore.getCertificateAlias(chain[0])))) { return; } - } - catch (KeyStoreException e) - { + } catch (KeyStoreException e) { throw new CertificateException("Certificate cannot be verified; KeyStore Exception: " + e); } throw new CertificateException("Certificate domain name does not match " @@ -117,55 +96,41 @@ public final class TrustManagerFactory } } - public X509Certificate[] getAcceptedIssuers() - { + public X509Certificate[] getAcceptedIssuers() { return defaultTrustManager.getAcceptedIssuers(); } } - static - { - try - { + static { + try { javax.net.ssl.TrustManagerFactory tmf = javax.net.ssl.TrustManagerFactory.getInstance("X509"); Application app = K9.app; keyStoreFile = new File(app.getDir("KeyStore", Context.MODE_PRIVATE) + File.separator + "KeyStore.bks"); keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); java.io.FileInputStream fis; - try - { + try { fis = new java.io.FileInputStream(keyStoreFile); - } - catch (FileNotFoundException e1) - { + } catch (FileNotFoundException e1) { fis = null; } - try - { + try { keyStore.load(fis, "".toCharArray()); //if (fis != null) { // fis.close(); //} - } - catch (IOException e) - { + } catch (IOException e) { Log.e(LOG_TAG, "KeyStore IOException while initializing TrustManagerFactory ", e); keyStore = null; - } - catch (CertificateException e) - { + } catch (CertificateException e) { Log.e(LOG_TAG, "KeyStore CertificateException while initializing TrustManagerFactory ", e); keyStore = null; } tmf.init(keyStore); TrustManager[] tms = tmf.getTrustManagers(); - if (tms != null) - { - for (TrustManager tm : tms) - { - if (tm instanceof X509TrustManager) - { + if (tms != null) { + for (TrustManager tm : tms) { + if (tm instanceof X509TrustManager) { localTrustManager = (X509TrustManager)tm; break; } @@ -174,105 +139,76 @@ public final class TrustManagerFactory tmf = javax.net.ssl.TrustManagerFactory.getInstance("X509"); tmf.init((KeyStore)null); tms = tmf.getTrustManagers(); - if (tms != null) - { - for (TrustManager tm : tms) - { - if (tm instanceof X509TrustManager) - { + if (tms != null) { + for (TrustManager tm : tms) { + if (tm instanceof X509TrustManager) { defaultTrustManager = (X509TrustManager) tm; break; } } } - } - catch (NoSuchAlgorithmException e) - { + } catch (NoSuchAlgorithmException e) { Log.e(LOG_TAG, "Unable to get X509 Trust Manager ", e); - } - catch (KeyStoreException e) - { + } catch (KeyStoreException e) { Log.e(LOG_TAG, "Key Store exception while initializing TrustManagerFactory ", e); } unsecureTrustManager = new SimpleX509TrustManager(); } - private TrustManagerFactory() - { + private TrustManagerFactory() { } - public static X509TrustManager get(String host, boolean secure) - { + public static X509TrustManager get(String host, boolean secure) { return secure ? SecureX509TrustManager.getInstance(host) : unsecureTrustManager; } - public static KeyStore getKeyStore() - { + public static KeyStore getKeyStore() { return keyStore; } - public static void setLastCertChain(X509Certificate[] chain) - { + public static void setLastCertChain(X509Certificate[] chain) { lastCertChain = chain; } - public static X509Certificate[] getLastCertChain() - { + public static X509Certificate[] getLastCertChain() { return lastCertChain; } - public static void addCertificateChain(String alias, X509Certificate[] chain) throws CertificateException - { - try - { + public static void addCertificateChain(String alias, X509Certificate[] chain) throws CertificateException { + try { javax.net.ssl.TrustManagerFactory tmf = javax.net.ssl.TrustManagerFactory.getInstance("X509"); - for (X509Certificate element : chain) - { + for (X509Certificate element : chain) { keyStore.setCertificateEntry (element.getSubjectDN().toString(), element); } tmf.init(keyStore); TrustManager[] tms = tmf.getTrustManagers(); - if (tms != null) - { - for (TrustManager tm : tms) - { - if (tm instanceof X509TrustManager) - { + if (tms != null) { + for (TrustManager tm : tms) { + if (tm instanceof X509TrustManager) { localTrustManager = (X509TrustManager) tm; break; } } } java.io.FileOutputStream keyStoreStream; - try - { + try { keyStoreStream = new java.io.FileOutputStream(keyStoreFile); keyStore.store(keyStoreStream, "".toCharArray()); keyStoreStream.close(); - } - catch (FileNotFoundException e) - { + } catch (FileNotFoundException e) { throw new CertificateException("Unable to write KeyStore: " + e.getMessage()); - } - catch (CertificateException e) - { + } catch (CertificateException e) { throw new CertificateException("Unable to write KeyStore: " + e.getMessage()); - } - catch (IOException e) - { + } catch (IOException e) { throw new CertificateException("Unable to write KeyStore: " + e.getMessage()); } - } - catch (NoSuchAlgorithmException e) - { + } catch (NoSuchAlgorithmException e) { Log.e(LOG_TAG, "Unable to get X509 Trust Manager ", e); - } - catch (KeyStoreException e) - { + } catch (KeyStoreException e) { Log.e(LOG_TAG, "Key Store exception while initializing TrustManagerFactory ", e); } } diff --git a/src/com/fsck/k9/mail/store/UnavailableAccountException.java b/src/com/fsck/k9/mail/store/UnavailableAccountException.java index 64c336ee6..26e66b1be 100644 --- a/src/com/fsck/k9/mail/store/UnavailableAccountException.java +++ b/src/com/fsck/k9/mail/store/UnavailableAccountException.java @@ -7,16 +7,14 @@ import com.fsck.k9.Account; * {@link Account#isAvailable(android.content.Context)}.
    * The operation may be retried later. */ -public class UnavailableAccountException extends RuntimeException -{ +public class UnavailableAccountException extends RuntimeException { /** * */ private static final long serialVersionUID = -1827283277120501465L; - public UnavailableAccountException() - { + public UnavailableAccountException() { super("please try again later"); } @@ -24,24 +22,21 @@ public class UnavailableAccountException extends RuntimeException * @param detailMessage * @param throwable */ - public UnavailableAccountException(String detailMessage, Throwable throwable) - { + public UnavailableAccountException(String detailMessage, Throwable throwable) { super(detailMessage, throwable); } /** * @param detailMessage */ - public UnavailableAccountException(String detailMessage) - { + public UnavailableAccountException(String detailMessage) { super(detailMessage); } /** * @param throwable */ - public UnavailableAccountException(Throwable throwable) - { + public UnavailableAccountException(Throwable throwable) { super(throwable); } } diff --git a/src/com/fsck/k9/mail/store/UnavailableStorageException.java b/src/com/fsck/k9/mail/store/UnavailableStorageException.java index 7a22a49f7..90974161b 100644 --- a/src/com/fsck/k9/mail/store/UnavailableStorageException.java +++ b/src/com/fsck/k9/mail/store/UnavailableStorageException.java @@ -2,30 +2,25 @@ package com.fsck.k9.mail.store; import com.fsck.k9.mail.MessagingException; -public class UnavailableStorageException extends MessagingException -{ +public class UnavailableStorageException extends MessagingException { private static final long serialVersionUID = 1348267375054620792L; - public UnavailableStorageException(String message) - { + public UnavailableStorageException(String message) { // consider this exception as a permanent failure by default this(message, true); } - public UnavailableStorageException(String message, boolean perm) - { + public UnavailableStorageException(String message, boolean perm) { super(message, perm); } - public UnavailableStorageException(String message, Throwable throwable) - { + public UnavailableStorageException(String message, Throwable throwable) { // consider this exception as permanent failure by default this(message, true, throwable); } - public UnavailableStorageException(String message, boolean perm, Throwable throwable) - { + public UnavailableStorageException(String message, boolean perm, Throwable throwable) { super(message, perm, throwable); } diff --git a/src/com/fsck/k9/mail/store/WebDavStore.java b/src/com/fsck/k9/mail/store/WebDavStore.java index f3a9a63ca..8ef9c25cf 100644 --- a/src/com/fsck/k9/mail/store/WebDavStore.java +++ b/src/com/fsck/k9/mail/store/WebDavStore.java @@ -59,8 +59,7 @@ import java.util.zip.GZIPInputStream; * and email information. * */ -public class WebDavStore extends Store -{ +public class WebDavStore extends Store { // Security options private static final short CONNECTION_SECURITY_NONE = 0; private static final short CONNECTION_SECURITY_TLS_OPTIONAL = 1; @@ -110,78 +109,53 @@ public class WebDavStore extends Store * webdav+ssl+://user:password@server:port CONNECTION_SECURITY_SSL_REQUIRED * webdav+ssl://user:password@server:port CONNECTION_SECURITY_SSL_OPTIONAL */ - public WebDavStore(Account account) throws MessagingException - { + public WebDavStore(Account account) throws MessagingException { super(account); - try - { + try { mUri = new URI(mAccount.getStoreUri()); - } - catch (URISyntaxException use) - { + } catch (URISyntaxException use) { throw new MessagingException("Invalid WebDavStore URI", use); } String scheme = mUri.getScheme(); - if (scheme.equals("webdav")) - { + if (scheme.equals("webdav")) { mConnectionSecurity = CONNECTION_SECURITY_NONE; - } - else if (scheme.equals("webdav+ssl")) - { + } else if (scheme.equals("webdav+ssl")) { mConnectionSecurity = CONNECTION_SECURITY_SSL_OPTIONAL; - } - else if (scheme.equals("webdav+ssl+")) - { + } else if (scheme.equals("webdav+ssl+")) { mConnectionSecurity = CONNECTION_SECURITY_SSL_REQUIRED; - } - else if (scheme.equals("webdav+tls")) - { + } else if (scheme.equals("webdav+tls")) { mConnectionSecurity = CONNECTION_SECURITY_TLS_OPTIONAL; - } - else if (scheme.equals("webdav+tls+")) - { + } else if (scheme.equals("webdav+tls+")) { mConnectionSecurity = CONNECTION_SECURITY_TLS_REQUIRED; - } - else - { + } else { throw new MessagingException("Unsupported protocol"); } mHost = mUri.getHost(); - if (mHost.startsWith("http")) - { + if (mHost.startsWith("http")) { String[] hostParts = mHost.split("://", 2); - if (hostParts.length > 1) - { + if (hostParts.length > 1) { mHost = hostParts[1]; } } - if (mUri.getUserInfo() != null) - { - try - { + if (mUri.getUserInfo() != null) { + try { String[] userInfoParts = mUri.getUserInfo().split(":"); mUsername = URLDecoder.decode(userInfoParts[0], "UTF-8"); String userParts[] = mUsername.split("\\\\", 2); - if (userParts.length > 1) - { + if (userParts.length > 1) { mAlias = userParts[1]; - } - else - { + } else { mAlias = mUsername; } - if (userInfoParts.length > 1) - { + if (userInfoParts.length > 1) { mPassword = URLDecoder.decode(userInfoParts[1], "UTF-8"); } - } - catch (UnsupportedEncodingException enc) - { + } catch (UnsupportedEncodingException enc) { // This shouldn't happen since the encoding is hardcoded to UTF-8 Log.e(K9.LOG_TAG, "Couldn't urldecode username or password.", enc); } @@ -189,56 +163,40 @@ public class WebDavStore extends Store String[] pathParts = mUri.getPath().split("\\|"); - for (int i = 0, count = pathParts.length; i < count; i++) - { - if (i == 0) - { + for (int i = 0, count = pathParts.length; i < count; i++) { + if (i == 0) { if (pathParts[0] != null && - pathParts[0].length() > 1) - { + pathParts[0].length() > 1) { mPath = pathParts[0]; } - } - else if (i == 1) - { + } else if (i == 1) { if (pathParts[1] != null && - pathParts[1].length() > 1) - { + pathParts[1].length() > 1) { mAuthPath = pathParts[1]; } - } - else if (i == 2) - { + } else if (i == 2) { if (pathParts[2] != null && - pathParts[2].length() > 1) - { + pathParts[2].length() > 1) { mMailboxPath = pathParts[2]; } } } - if (mPath == null || mPath.equals("")) - { + if (mPath == null || mPath.equals("")) { mPath = "/Exchange"; - } - else if (!mPath.startsWith("/")) - { + } else if (!mPath.startsWith("/")) { mPath = "/" + mPath; } - if (mMailboxPath == null || mMailboxPath.equals("")) - { + if (mMailboxPath == null || mMailboxPath.equals("")) { mMailboxPath = "/" + mAlias; - } - else if (!mMailboxPath.startsWith("/")) - { + } else if (!mMailboxPath.startsWith("/")) { mMailboxPath = "/" + mMailboxPath; } if (mAuthPath != null && !mAuthPath.equals("") && - !mAuthPath.startsWith("/")) - { + !mAuthPath.startsWith("/")) { mAuthPath = "/" + mAuthPath; } @@ -250,18 +208,14 @@ public class WebDavStore extends Store mAuthString = "Basic " + Utility.base64Encode(mUsername + ":" + mPassword); } - private String getRoot() - { + private String getRoot() { String root; if (mConnectionSecurity == CONNECTION_SECURITY_TLS_REQUIRED || mConnectionSecurity == CONNECTION_SECURITY_SSL_REQUIRED || mConnectionSecurity == CONNECTION_SECURITY_TLS_OPTIONAL || - mConnectionSecurity == CONNECTION_SECURITY_SSL_OPTIONAL) - { + mConnectionSecurity == CONNECTION_SECURITY_SSL_OPTIONAL) { root = "https"; - } - else - { + } else { root = "http"; } root += "://" + mHost + ":" + mUri.getPort(); @@ -269,14 +223,12 @@ public class WebDavStore extends Store } @Override - public void checkSettings() throws MessagingException - { + public void checkSettings() throws MessagingException { authenticate(); } @Override - public List getPersonalNamespaces(boolean forceListAll) throws MessagingException - { + public List getPersonalNamespaces(boolean forceListAll) throws MessagingException { LinkedList folderList = new LinkedList(); HashMap headers = new HashMap(); DataSet dataset = new DataSet(); @@ -295,36 +247,25 @@ public class WebDavStore extends Store folderUrls = dataset.getHrefs(); urlLength = folderUrls.length; - for (int i = 0; i < urlLength; i++) - { + for (int i = 0; i < urlLength; i++) { String[] urlParts = folderUrls[i].split("/"); String folderName = urlParts[urlParts.length - 1]; String fullPathName = ""; WebDavFolder wdFolder; - if (folderName.equalsIgnoreCase(K9.INBOX)) - { + if (folderName.equalsIgnoreCase(K9.INBOX)) { folderName = "INBOX"; - } - else - { - for (int j = 5, count = urlParts.length; j < count; j++) - { - if (j != 5) - { + } else { + for (int j = 5, count = urlParts.length; j < count; j++) { + if (j != 5) { fullPathName = fullPathName + "/" + urlParts[j]; - } - else - { + } else { fullPathName = urlParts[j]; } } - try - { + try { folderName = java.net.URLDecoder.decode(fullPathName, "UTF-8"); - } - catch (UnsupportedEncodingException uee) - { + } catch (UnsupportedEncodingException uee) { /** If we don't support UTF-8 there's a problem, don't decode it then */ folderName = fullPathName; } @@ -340,40 +281,34 @@ public class WebDavStore extends Store } @Override - public Folder getFolder(String name) - { + public Folder getFolder(String name) { WebDavFolder folder; - if ((folder = this.mFolderList.get(name)) == null) - { + if ((folder = this.mFolderList.get(name)) == null) { folder = new WebDavFolder(this, name); } return folder; } - public Folder getSendSpoolFolder() throws MessagingException - { + public Folder getSendSpoolFolder() throws MessagingException { return getFolder(DAV_MAIL_SEND_FOLDER); } @Override - public boolean isMoveCapable() - { + public boolean isMoveCapable() { return true; } @Override - public boolean isCopyCapable() - { + public boolean isCopyCapable() { return true; } /*************************************************************** * WebDAV XML Request body retrieval functions */ - private String getFolderListXml() - { + private String getFolderListXml() { StringBuffer buffer = new StringBuffer(200); buffer.append(""); buffer.append("\r\n"); @@ -384,8 +319,7 @@ public class WebDavStore extends Store return buffer.toString(); } - private String getMessageCountXml(String messageState) - { + private String getMessageCountXml(String messageState) { StringBuffer buffer = new StringBuffer(200); buffer.append(""); buffer.append("\r\n"); @@ -398,8 +332,7 @@ public class WebDavStore extends Store return buffer.toString(); } - private String getMessageEnvelopeXml(String[] uids) - { + private String getMessageEnvelopeXml(String[] uids) { StringBuffer buffer = new StringBuffer(200); buffer.append(""); buffer.append("\r\n"); @@ -418,10 +351,8 @@ public class WebDavStore extends Store buffer.append(" \r\n"); buffer.append(" FROM \"\"\r\n"); buffer.append(" WHERE \"DAV:ishidden\"=False AND \"DAV:isfolder\"=False AND "); - for (int i = 0, count = uids.length; i < count; i++) - { - if (i != 0) - { + for (int i = 0, count = uids.length; i < count; i++) { + if (i != 0) { buffer.append(" OR "); } buffer.append(" \"DAV:uid\"='").append(uids[i]).append("' "); @@ -431,8 +362,7 @@ public class WebDavStore extends Store return buffer.toString(); } - private String getMessagesXml() - { + private String getMessagesXml() { StringBuffer buffer = new StringBuffer(200); buffer.append(""); buffer.append("\r\n"); @@ -443,18 +373,15 @@ public class WebDavStore extends Store return buffer.toString(); } - private String getMessageUrlsXml(String[] uids) - { + private String getMessageUrlsXml(String[] uids) { StringBuffer buffer = new StringBuffer(600); buffer.append(""); buffer.append("\r\n"); buffer.append("SELECT \"urn:schemas:httpmail:read\", \"DAV:uid\"\r\n"); buffer.append(" FROM \"\"\r\n"); buffer.append(" WHERE \"DAV:ishidden\"=False AND \"DAV:isfolder\"=False AND "); - for (int i = 0, count = uids.length; i < count; i++) - { - if (i != 0) - { + for (int i = 0, count = uids.length; i < count; i++) { + if (i != 0) { buffer.append(" OR "); } @@ -466,10 +393,8 @@ public class WebDavStore extends Store return buffer.toString(); } - private String getMessageFlagsXml(String[] uids) throws MessagingException - { - if (uids.length == 0) - { + private String getMessageFlagsXml(String[] uids) throws MessagingException { + if (uids.length == 0) { throw new MessagingException("Attempt to get flags on 0 length array for uids"); } @@ -480,10 +405,8 @@ public class WebDavStore extends Store buffer.append(" FROM \"\"\r\n"); buffer.append(" WHERE \"DAV:ishidden\"=False AND \"DAV:isfolder\"=False AND "); - for (int i = 0, count = uids.length; i < count; i++) - { - if (i != 0) - { + for (int i = 0, count = uids.length; i < count; i++) { + if (i != 0) { buffer.append(" OR "); } buffer.append(" \"DAV:uid\"='").append(uids[i]).append("' "); @@ -493,14 +416,12 @@ public class WebDavStore extends Store return buffer.toString(); } - private String getMarkMessagesReadXml(String[] urls, boolean read) - { + private String getMarkMessagesReadXml(String[] urls, boolean read) { StringBuffer buffer = new StringBuffer(600); buffer.append("\r\n"); buffer.append("\r\n"); buffer.append("\r\n"); - for (String url : urls) - { + for (String url : urls) { buffer.append(" ").append(url).append("\r\n"); } buffer.append("\r\n"); @@ -517,16 +438,14 @@ public class WebDavStore extends Store // http://www.devnewsgroups.net/group/microsoft.public.exchange.development/topic27175.aspx // "1" & _ - private String getMoveOrCopyMessagesReadXml(String[] urls, boolean isMove) - { + private String getMoveOrCopyMessagesReadXml(String[] urls, boolean isMove) { String action = (isMove ? "move" : "copy"); StringBuffer buffer = new StringBuffer(600); buffer.append("\r\n"); buffer.append("\r\n"); buffer.append("\r\n"); - for (String url : urls) - { + for (String url : urls) { buffer.append(" ").append(url).append("\r\n"); } buffer.append("\r\n"); @@ -545,16 +464,12 @@ public class WebDavStore extends Store * @throws MessagingException */ public boolean authenticate() - throws MessagingException - { - try - { - if (mAuthentication == AUTH_TYPE_NONE) - { + throws MessagingException { + try { + if (mAuthentication == AUTH_TYPE_NONE) { ConnectionInfo info = doInitialConnection(); - if (info.requiredAuthType == AUTH_TYPE_BASIC) - { + if (info.requiredAuthType == AUTH_TYPE_BASIC) { HttpGeneric request = new HttpGeneric(mUrl); request.setMethod("GET"); request.setHeader("Authorization", mAuthString); @@ -563,38 +478,25 @@ public class WebDavStore extends Store HttpResponse response = httpClient.executeOverride(request, mContext); int statusCode = response.getStatusLine().getStatusCode(); - if (statusCode >= 200 && statusCode < 300) - { + if (statusCode >= 200 && statusCode < 300) { mAuthentication = AUTH_TYPE_BASIC; - } - else if (statusCode == 401) - { + } else if (statusCode == 401) { throw new MessagingException("Invalid username or password for authentication."); - } - else - { + } else { throw new MessagingException("Error with code " + response.getStatusLine().getStatusCode() + " during request processing: " + response.getStatusLine().toString()); } - } - else if (info.requiredAuthType == AUTH_TYPE_FORM_BASED) - { + } else if (info.requiredAuthType == AUTH_TYPE_FORM_BASED) { doFBA(info); } - } - else if (mAuthentication == AUTH_TYPE_BASIC) - { + } else if (mAuthentication == AUTH_TYPE_BASIC) { // Nothing to do, we authenticate with every request when // using basic authentication. - } - else if (mAuthentication == AUTH_TYPE_FORM_BASED) - { + } else if (mAuthentication == AUTH_TYPE_FORM_BASED) { // Our cookie expired, re-authenticate. doFBA(null); } - } - catch (IOException ioe) - { + } catch (IOException ioe) { Log.e(K9.LOG_TAG, "Error during authentication: " + ioe + "\nStack: " + processException(ioe)); throw new MessagingException("Error during authentication", ioe); } @@ -609,8 +511,7 @@ public class WebDavStore extends Store * @throws MessagingException */ private ConnectionInfo doInitialConnection() - throws MessagingException - { + throws MessagingException { // For our initial connection we are sending an empty GET request to // the configured URL, which should be in the following form: // https://mail.server.com/Exchange/alias @@ -628,20 +529,17 @@ public class WebDavStore extends Store HttpGeneric request = new HttpGeneric(mUrl); request.setMethod("GET"); - try - { + try { HttpResponse response = httpClient.executeOverride(request, mContext); info.statusCode = response.getStatusLine().getStatusCode(); - if (info.statusCode == 401) - { + if (info.statusCode == 401) { // 401 is the "Unauthorized" status code, meaning the server wants // an authentication header for basic authentication. info.requiredAuthType = AUTH_TYPE_BASIC; - } - else if ((info.statusCode >= 200 && info.statusCode < 300) || // Success - (info.statusCode >= 300 && info.statusCode < 400) || // Redirect - (info.statusCode == 440)) // Unauthorized + } else if ((info.statusCode >= 200 && info.statusCode < 300) || // Success + (info.statusCode >= 300 && info.statusCode < 400) || // Redirect + (info.statusCode == 440)) // Unauthorized { // We will handle all 3 situations the same. First we take an educated @@ -651,36 +549,26 @@ public class WebDavStore extends Store // authorization URL. info.requiredAuthType = AUTH_TYPE_FORM_BASED; - if (mAuthPath != null && !mAuthPath.equals("")) - { + if (mAuthPath != null && !mAuthPath.equals("")) { // The user specified their own authentication path, use that. info.guessedAuthUrl = getRoot() + mAuthPath; - } - else - { + } else { // Use the default path to the authentication dll. info.guessedAuthUrl = getRoot() + "/exchweb/bin/auth/owaauth.dll"; } // Determine where the server is trying to redirect us. Header location = response.getFirstHeader("Location"); - if (location != null) - { + if (location != null) { info.redirectUrl = location.getValue(); } - } - else - { + } else { throw new IOException("Error with code " + info.statusCode + " during request processing: " + response.getStatusLine().toString()); } - } - catch (SSLException e) - { + } catch (SSLException e) { throw new CertificateValidationException(e.getMessage(), e); - } - catch (IOException ioe) - { + } catch (IOException ioe) { Log.e(K9.LOG_TAG, "IOException: " + ioe + "\nTrace: " + processException(ioe)); throw new MessagingException("IOException", ioe); } @@ -694,24 +582,18 @@ public class WebDavStore extends Store * @throws MessagingException */ public void doFBA(ConnectionInfo info) - throws IOException, MessagingException - { + throws IOException, MessagingException { // Clear out cookies from any previous authentication. mAuthCookies.clear(); WebDavHttpClient httpClient = getHttpClient(); String loginUrl = ""; - if (info != null) - { + if (info != null) { loginUrl = info.guessedAuthUrl; - } - else if (mCachedLoginUrl != null && !mCachedLoginUrl.equals("")) - { + } else if (mCachedLoginUrl != null && !mCachedLoginUrl.equals("")) { loginUrl = mCachedLoginUrl; - } - else - { + } else { throw new MessagingException("No valid login URL available for form-based authentication."); } @@ -735,19 +617,14 @@ public class WebDavStore extends Store int statusCode = response.getStatusLine().getStatusCode(); if (statusCode >= 200 && statusCode < 300 && - mAuthCookies != null && !mAuthCookies.getCookies().isEmpty()) - { + mAuthCookies != null && !mAuthCookies.getCookies().isEmpty()) { // Success, we're authenticated and cookies have been added to mAuthCookies for us. - } - else - { + } else { // Check our response from the authentication URL above for a form action. String formAction = findFormAction(WebDavHttpClient.getUngzippedContent(response.getEntity())); - if (formAction == null) - { + if (formAction == null) { // If there is no form action, try using our redirect URL from the initial connection. - if (info != null && info.redirectUrl != null && !info.redirectUrl.equals("")) - { + if (info != null && info.redirectUrl != null && !info.redirectUrl.equals("")) { loginUrl = info.redirectUrl; request = new HttpGeneric(loginUrl); @@ -757,25 +634,19 @@ public class WebDavStore extends Store formAction = findFormAction(WebDavHttpClient.getUngzippedContent(response.getEntity())); } } - if (formAction != null) - { - try - { + if (formAction != null) { + try { URI formActionUri = new URI(formAction); URI loginUri = new URI(loginUrl); - if (formActionUri.isAbsolute()) - { + if (formActionUri.isAbsolute()) { // The form action is an absolute URL, just use it. loginUrl = formAction; - } - else - { + } else { // Append the form action to our current URL, minus the file name. String urlPath = loginUri.getPath(); int lastPathPos = urlPath.lastIndexOf('/'); - if (lastPathPos > -1) - { + if (lastPathPos > -1) { urlPath = urlPath.substring(0, lastPathPos + 1); urlPath = urlPath.concat(formAction); } @@ -796,21 +667,16 @@ public class WebDavStore extends Store request.setMethod("POST"); request.setEntity(formEntity); httpClient.executeOverride(request, mContext); - } - catch (URISyntaxException e) - { + } catch (URISyntaxException e) { Log.e(K9.LOG_TAG, "URISyntaxException caught " + e + "\nTrace: " + processException(e)); throw new MessagingException("URISyntaxException caught", e); } - } - else - { + } else { throw new MessagingException("A valid URL for Exchange authentication could not be found."); } } - if (mAuthCookies != null && !mAuthCookies.getCookies().isEmpty()) - { + if (mAuthCookies != null && !mAuthCookies.getCookies().isEmpty()) { mAuthentication = AUTH_TYPE_FORM_BASED; mCachedLoginUrl = loginUrl; } @@ -822,8 +688,7 @@ public class WebDavStore extends Store * @throws IOException */ private String findFormAction(InputStream istream) - throws IOException - { + throws IOException { String formAction = null; BufferedReader reader = new BufferedReader(new InputStreamReader(istream), 4096); @@ -831,22 +696,17 @@ public class WebDavStore extends Store // Read line by line until we find something like:
    . while ((tempText = reader.readLine()) != null && - formAction == null) - { - if (tempText.indexOf(" action=") > -1) - { + formAction == null) { + if (tempText.indexOf(" action=") > -1) { String[] actionParts = tempText.split(" action="); - if (actionParts.length > 1 && actionParts[1].length() > 1) - { + if (actionParts.length > 1 && actionParts[1].length() > 1) { char openQuote = actionParts[1].charAt(0); int closePos = actionParts[1].indexOf(openQuote, 1); - if (closePos > 1) - { + if (closePos > 1) { formAction = actionParts[1].substring(1, closePos); // Remove any GET parameters. int quesPos = formAction.indexOf('?'); - if (quesPos != -1) - { + if (quesPos != -1) { formAction = formAction.substring(0, quesPos); } } @@ -857,25 +717,20 @@ public class WebDavStore extends Store return formAction; } - public CookieStore getAuthCookies() - { + public CookieStore getAuthCookies() { return mAuthCookies; } - public String getAlias() - { + public String getAlias() { return mAlias; } - public String getUrl() - { + public String getUrl() { return mUrl; } - public WebDavHttpClient getHttpClient() throws MessagingException - { - if (mHttpClient == null) - { + public WebDavHttpClient getHttpClient() throws MessagingException { + if (mHttpClient == null) { mHttpClient = new WebDavHttpClient(); // Disable automatic redirects on the http client. mHttpClient.getParams().setBooleanParameter("http.protocol.handle-redirects", false); @@ -886,18 +741,13 @@ public class WebDavStore extends Store mContext.setAttribute(ClientContext.COOKIE_STORE, mAuthCookies); SchemeRegistry reg = mHttpClient.getConnectionManager().getSchemeRegistry(); - try - { + try { Scheme s = new Scheme("https", new TrustedSocketFactory(mHost, mSecure), 443); reg.register(s); - } - catch (NoSuchAlgorithmException nsa) - { + } catch (NoSuchAlgorithmException nsa) { Log.e(K9.LOG_TAG, "NoSuchAlgorithmException in getHttpClient: " + nsa); throw new MessagingException("NoSuchAlgorithmException in getHttpClient: " + nsa); - } - catch (KeyManagementException kme) - { + } catch (KeyManagementException kme) { Log.e(K9.LOG_TAG, "KeyManagementException in getHttpClient: " + kme); throw new MessagingException("KeyManagementException in getHttpClient: " + kme); } @@ -907,46 +757,36 @@ public class WebDavStore extends Store private InputStream sendRequest(String url, String method, StringEntity messageBody, HashMap headers, boolean tryAuth) - throws MessagingException - { + throws MessagingException { InputStream istream = null; - if (url == null || method == null) - { + if (url == null || method == null) { return istream; } WebDavHttpClient httpclient = getHttpClient(); - try - { + try { int statusCode = -1; HttpGeneric httpmethod = new HttpGeneric(url); HttpResponse response; HttpEntity entity; - if (messageBody != null) - { + if (messageBody != null) { httpmethod.setEntity(messageBody); } - if (headers != null) - { - for (String headerName : headers.keySet()) - { + if (headers != null) { + for (String headerName : headers.keySet()) { httpmethod.setHeader(headerName, headers.get(headerName)); } } - if (mAuthentication == AUTH_TYPE_NONE) - { - if (!tryAuth || !authenticate()) - { + if (mAuthentication == AUTH_TYPE_NONE) { + if (!tryAuth || !authenticate()) { throw new MessagingException("Unable to authenticate in sendRequest()."); } - } - else if (mAuthentication == AUTH_TYPE_BASIC) - { + } else if (mAuthentication == AUTH_TYPE_BASIC) { httpmethod.setHeader("Authorization", mAuthString); } @@ -956,41 +796,28 @@ public class WebDavStore extends Store entity = response.getEntity(); - if (statusCode == 401) - { + if (statusCode == 401) { throw new MessagingException("Invalid username or password for Basic authentication."); - } - else if (statusCode == 440) - { - if (tryAuth && mAuthentication == AUTH_TYPE_FORM_BASED) - { + } else if (statusCode == 440) { + if (tryAuth && mAuthentication == AUTH_TYPE_FORM_BASED) { // Our cookie expired, re-authenticate. doFBA(null); sendRequest(url, method, messageBody, headers, false); - } - else - { + } else { throw new MessagingException("Authentication failure in sendRequest()."); } - } - else if (statusCode < 200 || statusCode >= 300) - { + } else if (statusCode < 200 || statusCode >= 300) { throw new IOException("Error with code " + statusCode + " during request processing: " + response.getStatusLine().toString()); } - if (entity != null) - { + if (entity != null) { istream = WebDavHttpClient.getUngzippedContent(entity); } - } - catch (UnsupportedEncodingException uee) - { + } catch (UnsupportedEncodingException uee) { Log.e(K9.LOG_TAG, "UnsupportedEncodingException: " + uee + "\nTrace: " + processException(uee)); throw new MessagingException("UnsupportedEncodingException", uee); - } - catch (IOException ioe) - { + } catch (IOException ioe) { Log.e(K9.LOG_TAG, "IOException: " + ioe + "\nTrace: " + processException(ioe)); throw new MessagingException("IOException", ioe); } @@ -998,8 +825,7 @@ public class WebDavStore extends Store return istream; } - public String getAuthString() - { + public String getAuthString() { return mAuthString; } @@ -1009,44 +835,36 @@ public class WebDavStore extends Store * response. */ private DataSet processRequest(String url, String method, String messageBody, HashMap headers) - throws MessagingException - { + throws MessagingException { return processRequest(url, method, messageBody, headers, true); } private DataSet processRequest(String url, String method, String messageBody, HashMap headers, boolean needsParsing) - throws MessagingException - { + throws MessagingException { DataSet dataset = new DataSet(); - if (K9.DEBUG && K9.DEBUG_PROTOCOL_WEBDAV) - { + if (K9.DEBUG && K9.DEBUG_PROTOCOL_WEBDAV) { Log.v(K9.LOG_TAG, "processRequest url = '" + url + "', method = '" + method + "', messageBody = '" + messageBody + "'"); } if (url == null || - method == null) - { + method == null) { return dataset; } getHttpClient(); - try - { + try { StringEntity messageEntity = null; - if (messageBody != null) - { + if (messageBody != null) { messageEntity = new StringEntity(messageBody); messageEntity.setContentType("text/xml"); } InputStream istream = sendRequest(url, method, messageEntity, headers, true); if (istream != null && - needsParsing) - { - try - { + needsParsing) { + try { SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); @@ -1057,14 +875,10 @@ public class WebDavStore extends Store xr.parse(new InputSource(istream)); dataset = myHandler.getDataSet(); - } - catch (SAXException se) - { + } catch (SAXException se) { Log.e(K9.LOG_TAG, "SAXException in processRequest() " + se + "\nTrace: " + processException(se)); throw new MessagingException("SAXException in processRequest() ", se); - } - catch (ParserConfigurationException pce) - { + } catch (ParserConfigurationException pce) { Log.e(K9.LOG_TAG, "ParserConfigurationException in processRequest() " + pce + "\nTrace: " + processException(pce)); throw new MessagingException("ParserConfigurationException in processRequest() ", pce); @@ -1072,14 +886,10 @@ public class WebDavStore extends Store istream.close(); } - } - catch (UnsupportedEncodingException uee) - { + } catch (UnsupportedEncodingException uee) { Log.e(K9.LOG_TAG, "UnsupportedEncodingException: " + uee + "\nTrace: " + processException(uee)); throw new MessagingException("UnsupportedEncodingException in processRequest() ", uee); - } - catch (IOException ioe) - { + } catch (IOException ioe) { Log.e(K9.LOG_TAG, "IOException: " + ioe + "\nTrace: " + processException(ioe)); throw new MessagingException("IOException in processRequest() ", ioe); } @@ -1090,8 +900,7 @@ public class WebDavStore extends Store /** * Returns a string of the stacktrace for a Throwable to allow for easy inline printing of errors. */ - private String processException(Throwable t) - { + private String processException(Throwable t) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); @@ -1102,26 +911,20 @@ public class WebDavStore extends Store } @Override - public boolean isSendCapable() - { + public boolean isSendCapable() { return true; } @Override - public void sendMessages(Message[] messages) throws MessagingException - { + public void sendMessages(Message[] messages) throws MessagingException { WebDavFolder tmpFolder = (WebDavStore.WebDavFolder) getFolder(DAV_MAIL_TMP_FOLDER); - try - { + try { tmpFolder.open(OpenMode.READ_WRITE); Message[] retMessages = tmpFolder.appendWebDavMessages(messages); tmpFolder.moveMessages(retMessages, getSendSpoolFolder()); - } - finally - { - if (tmpFolder != null) - { + } finally { + if (tmpFolder != null) { tmpFolder.close(); } } @@ -1134,8 +937,7 @@ public class WebDavStore extends Store /** * A WebDav Folder */ - class WebDavFolder extends Folder - { + class WebDavFolder extends Folder { private String mName; private String mFolderUrl; private boolean mIsOpen = false; @@ -1143,43 +945,31 @@ public class WebDavStore extends Store private int mUnreadMessageCount = 0; private WebDavStore store; - protected WebDavStore getStore() - { + protected WebDavStore getStore() { return store; } - public WebDavFolder(WebDavStore nStore, String name) - { + public WebDavFolder(WebDavStore nStore, String name) { super(nStore.getAccount()); store = nStore; this.mName = name; - if (DAV_MAIL_SEND_FOLDER.equals(name)) - { + if (DAV_MAIL_SEND_FOLDER.equals(name)) { this.mFolderUrl = getUrl() + "/" + name + "/"; - } - else - { + } else { String encodedName = ""; - try - { + try { String[] urlParts = name.split("/"); String url = ""; - for (int i = 0, count = urlParts.length; i < count; i++) - { - if (i != 0) - { + for (int i = 0, count = urlParts.length; i < count; i++) { + if (i != 0) { url = url + "/" + java.net.URLEncoder.encode(urlParts[i], "UTF-8"); - } - else - { + } else { url = java.net.URLEncoder.encode(urlParts[i], "UTF-8"); } } encodedName = url; - } - catch (UnsupportedEncodingException uee) - { + } catch (UnsupportedEncodingException uee) { Log.e(K9.LOG_TAG, "UnsupportedEncodingException URLEncoding folder name, skipping encoded"); encodedName = name; } @@ -1194,60 +984,50 @@ public class WebDavStore extends Store // TODO: danapple0 - huh? // getHttpClient(); - if (encodedName.equals("INBOX")) - { + if (encodedName.equals("INBOX")) { encodedName = "Inbox"; } this.mFolderUrl = WebDavStore.this.mUrl; - if (!WebDavStore.this.mUrl.endsWith("/")) - { + if (!WebDavStore.this.mUrl.endsWith("/")) { this.mFolderUrl += "/"; } this.mFolderUrl += encodedName; } } - public void setUrl(String url) - { - if (url != null) - { + public void setUrl(String url) { + if (url != null) { this.mFolderUrl = url; } } @Override - public void open(OpenMode mode) throws MessagingException - { + public void open(OpenMode mode) throws MessagingException { getHttpClient(); this.mIsOpen = true; } @Override - public void copyMessages(Message[] messages, Folder folder) throws MessagingException - { + public void copyMessages(Message[] messages, Folder folder) throws MessagingException { moveOrCopyMessages(messages, folder.getName(), false); } @Override - public void moveMessages(Message[] messages, Folder folder) throws MessagingException - { + public void moveMessages(Message[] messages, Folder folder) throws MessagingException { moveOrCopyMessages(messages, folder.getName(), true); } @Override - public void delete(Message[] msgs, String trashFolderName) throws MessagingException - { + public void delete(Message[] msgs, String trashFolderName) throws MessagingException { moveOrCopyMessages(msgs, trashFolderName, true); } private void moveOrCopyMessages(Message[] messages, String folderName, boolean isMove) - throws MessagingException - { + throws MessagingException { String[] uids = new String[messages.length]; - for (int i = 0, count = messages.length; i < count; i++) - { + for (int i = 0, count = messages.length; i < count; i++) { uids[i] = messages[i].getUid(); } String messageBody = ""; @@ -1255,11 +1035,9 @@ public class WebDavStore extends Store HashMap uidToUrl = getMessageUrls(uids); String[] urls = new String[uids.length]; - for (int i = 0, count = uids.length; i < count; i++) - { + for (int i = 0, count = uids.length; i < count; i++) { urls[i] = uidToUrl.get(uids[i]); - if (urls[i] == null && messages[i] instanceof WebDavMessage) - { + if (urls[i] == null && messages[i] instanceof WebDavMessage) { WebDavMessage wdMessage = (WebDavMessage) messages[i]; urls[i] = wdMessage.getUrl(); } @@ -1276,28 +1054,23 @@ public class WebDavStore extends Store processRequest(mFolderUrl, action, messageBody, headers, false); } - private int getMessageCount(boolean read) throws MessagingException - { + private int getMessageCount(boolean read) throws MessagingException { String isRead; int messageCount = 0; DataSet dataset = new DataSet(); HashMap headers = new HashMap(); String messageBody; - if (read) - { + if (read) { isRead = "True"; - } - else - { + } else { isRead = "False"; } messageBody = getMessageCountXml(isRead); headers.put("Brief", "t"); dataset = processRequest(this.mFolderUrl, "SEARCH", messageBody, headers); - if (dataset != null) - { + if (dataset != null) { messageCount = dataset.getMessageCount(); } @@ -1305,81 +1078,69 @@ public class WebDavStore extends Store } @Override - public int getMessageCount() throws MessagingException - { + public int getMessageCount() throws MessagingException { open(OpenMode.READ_WRITE); this.mMessageCount = getMessageCount(true); return this.mMessageCount; } @Override - public int getUnreadMessageCount() throws MessagingException - { + public int getUnreadMessageCount() throws MessagingException { open(OpenMode.READ_WRITE); this.mUnreadMessageCount = getMessageCount(false); return this.mUnreadMessageCount; } @Override - public int getFlaggedMessageCount() throws MessagingException - { + public int getFlaggedMessageCount() throws MessagingException { return -1; } @Override - public boolean isOpen() - { + public boolean isOpen() { return this.mIsOpen; } @Override - public OpenMode getMode() - { + public OpenMode getMode() { return OpenMode.READ_WRITE; } @Override - public String getName() - { + public String getName() { return this.mName; } @Override - public boolean exists() - { + public boolean exists() { return true; } @Override - public void close() - { + public void close() { this.mMessageCount = 0; this.mUnreadMessageCount = 0; this.mIsOpen = false; } @Override - public boolean create(FolderType type) throws MessagingException - { + public boolean create(FolderType type) throws MessagingException { return true; } @Override - public void delete(boolean recursive) throws MessagingException - { + public void delete(boolean recursive) throws MessagingException { throw new Error("WebDavFolder.delete() not implemeneted"); } @Override - public Message getMessage(String uid) throws MessagingException - { + public Message getMessage(String uid) throws MessagingException { return new WebDavMessage(uid, this); } @Override public Message[] getMessages(int start, int end, Date earliestDate, MessageRetrievalListener listener) - throws MessagingException - { + throws MessagingException { ArrayList messages = new ArrayList(); String[] uids; DataSet dataset = new DataSet(); @@ -1393,13 +1154,11 @@ public class WebDavStore extends Store start = this.mMessageCount - end; end = start + (end - prevStart); - if (start < 0 || end < 0 || end < start) - { + if (start < 0 || end < 0 || end < start) { throw new MessagingException(String.format("Invalid message set %d %d", start, end)); } - if (start == 0 && end < 10) - { + if (start == 0 && end < 10) { end = 10; } @@ -1414,18 +1173,15 @@ public class WebDavStore extends Store HashMap uidToUrl = dataset.getUidToUrl(); uidsLength = uids.length; - for (int i = 0; i < uidsLength; i++) - { - if (listener != null) - { + for (int i = 0; i < uidsLength; i++) { + if (listener != null) { listener.messageStarted(uids[i], i, uidsLength); } WebDavMessage message = new WebDavMessage(uids[i], this); message.setUrl(uidToUrl.get(uids[i])); messages.add(message); - if (listener != null) - { + if (listener != null) { listener.messageFinished(message, i, uidsLength); } } @@ -1434,35 +1190,29 @@ public class WebDavStore extends Store } @Override - public Message[] getMessages(MessageRetrievalListener listener) throws MessagingException - { + public Message[] getMessages(MessageRetrievalListener listener) throws MessagingException { return getMessages(null, listener); } @Override - public Message[] getMessages(String[] uids, MessageRetrievalListener listener) throws MessagingException - { + public Message[] getMessages(String[] uids, MessageRetrievalListener listener) throws MessagingException { ArrayList messageList = new ArrayList(); Message[] messages; if (uids == null || - uids.length == 0) - { + uids.length == 0) { return messageList.toArray(EMPTY_MESSAGE_ARRAY); } - for (int i = 0, count = uids.length; i < count; i++) - { - if (listener != null) - { + for (int i = 0, count = uids.length; i < count; i++) { + if (listener != null) { listener.messageStarted(uids[i], i, count); } WebDavMessage message = new WebDavMessage(uids[i], this); messageList.add(message); - if (listener != null) - { + if (listener != null) { listener.messageFinished(message, i, count); } } @@ -1471,8 +1221,7 @@ public class WebDavStore extends Store return messages; } - private HashMap getMessageUrls(String[] uids) throws MessagingException - { + private HashMap getMessageUrls(String[] uids) throws MessagingException { HashMap uidToUrl = new HashMap(); HashMap headers = new HashMap(); DataSet dataset = new DataSet(); @@ -1490,35 +1239,29 @@ public class WebDavStore extends Store @Override public void fetch(Message[] messages, FetchProfile fp, MessageRetrievalListener listener) - throws MessagingException - { + throws MessagingException { if (messages == null || - messages.length == 0) - { + messages.length == 0) { return; } /** * Fetch message envelope information for the array */ - if (fp.contains(FetchProfile.Item.ENVELOPE)) - { + if (fp.contains(FetchProfile.Item.ENVELOPE)) { fetchEnvelope(messages, listener); } /** * Fetch message flag info for the array */ - if (fp.contains(FetchProfile.Item.FLAGS)) - { + if (fp.contains(FetchProfile.Item.FLAGS)) { fetchFlags(messages, listener); } - if (fp.contains(FetchProfile.Item.BODY_SANE)) - { + if (fp.contains(FetchProfile.Item.BODY_SANE)) { fetchMessages(messages, listener, (mAccount.getMaximumAutoDownloadMessageSize() / 76)); } - if (fp.contains(FetchProfile.Item.BODY)) - { + if (fp.contains(FetchProfile.Item.BODY)) { fetchMessages(messages, listener, -1); } } @@ -1527,28 +1270,24 @@ public class WebDavStore extends Store * Fetches the full messages or up to lines lines and passes them to the message parser. */ private void fetchMessages(Message[] messages, MessageRetrievalListener listener, int lines) - throws MessagingException - { + throws MessagingException { WebDavHttpClient httpclient; httpclient = getHttpClient(); /** * We can't hand off to processRequest() since we need the stream to parse. */ - for (int i = 0, count = messages.length; i < count; i++) - { + for (int i = 0, count = messages.length; i < count; i++) { WebDavMessage wdMessage; int statusCode = 0; - if (!(messages[i] instanceof WebDavMessage)) - { + if (!(messages[i] instanceof WebDavMessage)) { throw new MessagingException("WebDavStore fetch called with non-WebDavMessage"); } wdMessage = (WebDavMessage) messages[i]; - if (listener != null) - { + if (listener != null) { listener.messageStarted(wdMessage.getUid(), i, count); } @@ -1556,19 +1295,16 @@ public class WebDavStore extends Store * If fetch is called outside of the initial list (ie, a locally stored message), it may not have a URL * associated. Verify and fix that */ - if (wdMessage.getUrl().equals("")) - { + if (wdMessage.getUrl().equals("")) { wdMessage.setUrl(getMessageUrls(new String[] { wdMessage.getUid() }).get(wdMessage.getUid())); Log.i(K9.LOG_TAG, "Fetching messages with UID = '" + wdMessage.getUid() + "', URL = '" + wdMessage.getUrl() + "'"); - if (wdMessage.getUrl().equals("")) - { + if (wdMessage.getUrl().equals("")) { throw new MessagingException("Unable to get URL for message"); } } - try - { + try { Log.i(K9.LOG_TAG, "Fetching message with UID = '" + wdMessage.getUid() + "', URL = '" + wdMessage.getUrl() + "'"); HttpGet httpget = new HttpGet(new URI(wdMessage.getUrl())); @@ -1576,8 +1312,7 @@ public class WebDavStore extends Store HttpEntity entity; httpget.setHeader("translate", "f"); - if (mAuthentication == AUTH_TYPE_BASIC) - { + if (mAuthentication == AUTH_TYPE_BASIC) { httpget.setHeader("Authorization", mAuthString); } response = httpclient.executeOverride(httpget, mContext); @@ -1587,14 +1322,12 @@ public class WebDavStore extends Store entity = response.getEntity(); if (statusCode < 200 || - statusCode > 300) - { + statusCode > 300) { throw new IOException("Error during with code " + statusCode + " during fetch: " + response.getStatusLine().toString()); } - if (entity != null) - { + if (entity != null) { InputStream istream = null; StringBuffer buffer = new StringBuffer(); String tempText = ""; @@ -1604,13 +1337,11 @@ public class WebDavStore extends Store istream = WebDavHttpClient.getUngzippedContent(entity); - if (lines != -1) - { + if (lines != -1) { reader = new BufferedReader(new InputStreamReader(istream), 8192); while ((tempText = reader.readLine()) != null && - (currentLines < lines)) - { + (currentLines < lines)) { buffer.append(tempText).append("\r\n"); currentLines++; } @@ -1623,27 +1354,20 @@ public class WebDavStore extends Store wdMessage.parse(istream); } - } - catch (IllegalArgumentException iae) - { + } catch (IllegalArgumentException iae) { Log.e(K9.LOG_TAG, "IllegalArgumentException caught " + iae + "\nTrace: " + processException(iae)); throw new MessagingException("IllegalArgumentException caught", iae); - } - catch (URISyntaxException use) - { + } catch (URISyntaxException use) { Log.e(K9.LOG_TAG, "URISyntaxException caught " + use + "\nTrace: " + processException(use)); throw new MessagingException("URISyntaxException caught", use); - } - catch (IOException ioe) - { + } catch (IOException ioe) { Log.e(K9.LOG_TAG, "Non-success response code loading message, response code was " + statusCode + "\nURL: " + wdMessage.getUrl() + "\nError: " + ioe.getMessage() + "\nTrace: " + processException(ioe)); throw new MessagingException("Failure code " + statusCode, ioe); } - if (listener != null) - { + if (listener != null) { listener.messageFinished(wdMessage, i, count); } } @@ -1653,8 +1377,7 @@ public class WebDavStore extends Store * Fetches and sets the message flags for the supplied messages. The idea is to have this be recursive so that * we do a series of medium calls instead of one large massive call or a large number of smaller calls. */ - private void fetchFlags(Message[] startMessages, MessageRetrievalListener listener) throws MessagingException - { + private void fetchFlags(Message[] startMessages, MessageRetrievalListener listener) throws MessagingException { HashMap uidToReadStatus = new HashMap(); HashMap headers = new HashMap(); DataSet dataset = new DataSet(); @@ -1663,37 +1386,28 @@ public class WebDavStore extends Store String[] uids; if (startMessages == null || - startMessages.length == 0) - { + startMessages.length == 0) { return; } - if (startMessages.length > 20) - { + if (startMessages.length > 20) { Message[] newMessages = new Message[startMessages.length - 20]; - for (int i = 0, count = startMessages.length; i < count; i++) - { - if (i < 20) - { + for (int i = 0, count = startMessages.length; i < count; i++) { + if (i < 20) { messages[i] = startMessages[i]; - } - else - { + } else { newMessages[i - 20] = startMessages[i]; } } fetchFlags(newMessages, listener); - } - else - { + } else { messages = startMessages; } uids = new String[messages.length]; - for (int i = 0, count = messages.length; i < count; i++) - { + for (int i = 0, count = messages.length; i < count; i++) { uids[i] = messages[i].getUid(); } @@ -1701,30 +1415,25 @@ public class WebDavStore extends Store headers.put("Brief", "t"); dataset = processRequest(this.mFolderUrl, "SEARCH", messageBody, headers); - if (dataset == null) - { + if (dataset == null) { throw new MessagingException("Data Set from request was null"); } uidToReadStatus = dataset.getUidToRead(); - for (int i = 0, count = messages.length; i < count; i++) - { - if (!(messages[i] instanceof WebDavMessage)) - { + for (int i = 0, count = messages.length; i < count; i++) { + if (!(messages[i] instanceof WebDavMessage)) { throw new MessagingException("WebDavStore fetch called with non-WebDavMessage"); } WebDavMessage wdMessage = (WebDavMessage) messages[i]; - if (listener != null) - { + if (listener != null) { listener.messageStarted(messages[i].getUid(), i, count); } wdMessage.setFlagInternal(Flag.SEEN, uidToReadStatus.get(wdMessage.getUid())); - if (listener != null) - { + if (listener != null) { listener.messageFinished(messages[i], i, count); } } @@ -1736,8 +1445,7 @@ public class WebDavStore extends Store * Call it a happy balance */ private void fetchEnvelope(Message[] startMessages, MessageRetrievalListener listener) - throws MessagingException - { + throws MessagingException { HashMap envelopes = new HashMap(); HashMap headers = new HashMap(); DataSet dataset = new DataSet(); @@ -1746,37 +1454,28 @@ public class WebDavStore extends Store Message[] messages = new Message[10]; if (startMessages == null || - startMessages.length == 0) - { + startMessages.length == 0) { return; } - if (startMessages.length > 10) - { + if (startMessages.length > 10) { Message[] newMessages = new Message[startMessages.length - 10]; - for (int i = 0, count = startMessages.length; i < count; i++) - { - if (i < 10) - { + for (int i = 0, count = startMessages.length; i < count; i++) { + if (i < 10) { messages[i] = startMessages[i]; - } - else - { + } else { newMessages[i - 10] = startMessages[i]; } } fetchEnvelope(newMessages, listener); - } - else - { + } else { messages = startMessages; } uids = new String[messages.length]; - for (int i = 0, count = messages.length; i < count; i++) - { + for (int i = 0, count = messages.length; i < count; i++) { uids[i] = messages[i].getUid(); } @@ -1787,68 +1486,55 @@ public class WebDavStore extends Store envelopes = dataset.getMessageEnvelopes(); int count = messages.length; - for (int i = messages.length - 1; i >= 0; i--) - { - if (!(messages[i] instanceof WebDavMessage)) - { + for (int i = messages.length - 1; i >= 0; i--) { + if (!(messages[i] instanceof WebDavMessage)) { throw new MessagingException("WebDavStore fetch called with non-WebDavMessage"); } WebDavMessage wdMessage = (WebDavMessage) messages[i]; - if (listener != null) - { + if (listener != null) { listener.messageStarted(messages[i].getUid(), i, count); } wdMessage.setNewHeaders(envelopes.get(wdMessage.getUid())); wdMessage.setFlagInternal(Flag.SEEN, envelopes.get(wdMessage.getUid()).getReadStatus()); - if (listener != null) - { + if (listener != null) { listener.messageFinished(messages[i], i, count); } } } @Override - public Flag[] getPermanentFlags() - { + public Flag[] getPermanentFlags() { return PERMANENT_FLAGS; } @Override public void setFlags(Message[] messages, Flag[] flags, boolean value) - throws MessagingException - { + throws MessagingException { String[] uids = new String[messages.length]; - for (int i = 0, count = messages.length; i < count; i++) - { + for (int i = 0, count = messages.length; i < count; i++) { uids[i] = messages[i].getUid(); } - for (Flag flag : flags) - { - if (flag == Flag.SEEN) - { + for (Flag flag : flags) { + if (flag == Flag.SEEN) { markServerMessagesRead(uids, value); - } - else if (flag == Flag.DELETED) - { + } else if (flag == Flag.DELETED) { deleteServerMessages(uids); } } } - private void markServerMessagesRead(String[] uids, boolean read) throws MessagingException - { + private void markServerMessagesRead(String[] uids, boolean read) throws MessagingException { String messageBody = ""; HashMap headers = new HashMap(); HashMap uidToUrl = getMessageUrls(uids); String[] urls = new String[uids.length]; - for (int i = 0, count = uids.length; i < count; i++) - { + for (int i = 0, count = uids.length; i < count; i++) { urls[i] = uidToUrl.get(uids[i]); } @@ -1859,12 +1545,10 @@ public class WebDavStore extends Store processRequest(this.mFolderUrl, "BPROPPATCH", messageBody, headers, false); } - private void deleteServerMessages(String[] uids) throws MessagingException - { + private void deleteServerMessages(String[] uids) throws MessagingException { HashMap uidToUrl = getMessageUrls(uids); - for (String uid : uids) - { + for (String uid : uids) { HashMap headers = new HashMap(); String url = uidToUrl.get(uid); String destinationUrl = generateDeleteUrl(url); @@ -1872,13 +1556,10 @@ public class WebDavStore extends Store /** * If the destination is the same as the origin, assume delete forever */ - if (destinationUrl.equals(url)) - { + if (destinationUrl.equals(url)) { headers.put("Brief", "t"); processRequest(url, "DELETE", null, headers, false); - } - else - { + } else { headers.put("Destination", generateDeleteUrl(url)); headers.put("Brief", "t"); processRequest(url, "MOVE", null, headers, false); @@ -1886,8 +1567,7 @@ public class WebDavStore extends Store } } - private String generateDeleteUrl(String startUrl) - { + private String generateDeleteUrl(String startUrl) { String[] urlParts = startUrl.split("/"); String filename = urlParts[urlParts.length - 1]; String finalUrl = WebDavStore.this.mUrl + "Deleted%20Items/" + filename; @@ -1896,27 +1576,23 @@ public class WebDavStore extends Store } @Override - public void appendMessages(Message[] messages) throws MessagingException - { + public void appendMessages(Message[] messages) throws MessagingException { appendWebDavMessages(messages); } - public Message[] appendWebDavMessages(Message[] messages) throws MessagingException - { + public Message[] appendWebDavMessages(Message[] messages) throws MessagingException { Message[] retMessages = new Message[messages.length]; int ind = 0; WebDavHttpClient httpclient = getHttpClient(); - for (Message message : messages) - { + for (Message message : messages) { HttpGeneric httpmethod; HttpResponse response; StringEntity bodyEntity; int statusCode; - try - { + try { ByteArrayOutputStream out; out = new ByteArrayOutputStream(message.getSize()); @@ -1931,8 +1607,7 @@ public class WebDavStore extends Store bodyEntity.setContentType("message/rfc822"); String messageURL = mFolderUrl; - if (!messageURL.endsWith("/")) - { + if (!messageURL.endsWith("/")) { messageURL += "/"; } messageURL += URLEncoder.encode(message.getUid() + ":" + System.currentTimeMillis() + ".eml"); @@ -1945,8 +1620,7 @@ public class WebDavStore extends Store String mAuthString = getAuthString(); - if (mAuthString != null) - { + if (mAuthString != null) { httpmethod.setHeader("Authorization", mAuthString); } @@ -1954,8 +1628,7 @@ public class WebDavStore extends Store statusCode = response.getStatusLine().getStatusCode(); if (statusCode < 200 || - statusCode > 300) - { + statusCode > 300) { throw new IOException("Error with status code " + statusCode + " while sending/appending message. Response = " + response.getStatusLine().toString() + " for message " + messageURL); @@ -1964,9 +1637,7 @@ public class WebDavStore extends Store retMessage.setUrl(messageURL); retMessages[ind++] = retMessage; - } - catch (Exception e) - { + } catch (Exception e) { throw new MessagingException("Unable to append", e); } } @@ -1974,20 +1645,17 @@ public class WebDavStore extends Store } @Override - public boolean equals(Object o) - { + public boolean equals(Object o) { return false; } @Override - public int hashCode() - { + public int hashCode() { return super.hashCode(); } @Override - public String getUidFromMessageId(Message message) throws MessagingException - { + public String getUidFromMessageId(Message message) throws MessagingException { Log.e(K9.LOG_TAG, "Unimplemented method getUidFromMessageId in WebDavStore.WebDavFolder could lead to duplicate messages " + " being uploaded to the Sent folder"); @@ -1995,8 +1663,7 @@ public class WebDavStore extends Store } @Override - public void setFlags(Flag[] flags, boolean value) throws MessagingException - { + public void setFlags(Flag[] flags, boolean value) throws MessagingException { Log.e(K9.LOG_TAG, "Unimplemented method setFlags(Flag[], boolean) breaks markAllMessagesAsRead and EmptyTrash"); // Try to make this efficient by not retrieving all of the messages @@ -2006,24 +1673,19 @@ public class WebDavStore extends Store /** * A WebDav Message */ - class WebDavMessage extends MimeMessage - { + class WebDavMessage extends MimeMessage { private String mUrl = ""; - WebDavMessage(String uid, Folder folder) - { + WebDavMessage(String uid, Folder folder) { this.mUid = uid; this.mFolder = folder; } - public void setUrl(String url) - { + public void setUrl(String url) { // TODO: This is a not as ugly hack (ie, it will actually work) // XXX: prevent URLs from getting to us that are broken - if (!(url.toLowerCase().contains("http"))) - { - if (!(url.startsWith("/"))) - { + if (!(url.toLowerCase().contains("http"))) { + if (!(url.startsWith("/"))) { url = "/" + url; } url = WebDavStore.this.mUrl + this.mFolder + url; @@ -2039,31 +1701,22 @@ public class WebDavStore extends Store /** * We have to decode, then encode the URL because Exchange likes to not properly encode all characters */ - try - { + try { end = java.net.URLDecoder.decode(end, "UTF-8"); end = java.net.URLEncoder.encode(end, "UTF-8"); end = end.replaceAll("\\+", "%20"); - } - catch (UnsupportedEncodingException uee) - { + } catch (UnsupportedEncodingException uee) { Log.e(K9.LOG_TAG, "UnsupportedEncodingException caught in setUrl: " + uee + "\nTrace: " + processException(uee)); - } - catch (IllegalArgumentException iae) - { + } catch (IllegalArgumentException iae) { Log.e(K9.LOG_TAG, "IllegalArgumentException caught in setUrl: " + iae + "\nTrace: " + processException(iae)); } - for (int i = 0; i < length - 1; i++) - { - if (i != 0) - { + for (int i = 0; i < length - 1; i++) { + if (i != 0) { url = url + "/" + urlParts[i]; - } - else - { + } else { url = urlParts[i]; } } @@ -2073,60 +1726,50 @@ public class WebDavStore extends Store this.mUrl = url; } - public String getUrl() - { + public String getUrl() { return this.mUrl; } - public void setSize(int size) - { + public void setSize(int size) { this.mSize = size; } @Override - public void parse(InputStream in) throws IOException, MessagingException - { + public void parse(InputStream in) throws IOException, MessagingException { super.parse(in); } - public void setFlagInternal(Flag flag, boolean set) throws MessagingException - { + public void setFlagInternal(Flag flag, boolean set) throws MessagingException { super.setFlag(flag, set); } - public void setNewHeaders(ParsedMessageEnvelope envelope) throws MessagingException - { + public void setNewHeaders(ParsedMessageEnvelope envelope) throws MessagingException { String[] headers = envelope.getHeaderList(); HashMap messageHeaders = envelope.getMessageHeaders(); - for (String header : headers) - { + for (String header : headers) { String headerValue = messageHeaders.get(header); - if (header.equals("Content-Length")) - { + if (header.equals("Content-Length")) { int size = Integer.parseInt(messageHeaders.get(header)); this.setSize(size); } if (headerValue != null && - !headerValue.equals("")) - { + !headerValue.equals("")) { this.addHeader(header, headerValue); } } } @Override - public void delete(String trashFolderName) throws MessagingException - { + public void delete(String trashFolderName) throws MessagingException { WebDavFolder wdFolder = (WebDavFolder) getFolder(); Log.i(K9.LOG_TAG, "Deleting message by moving to " + trashFolderName); wdFolder.moveMessages(new Message[] { this }, wdFolder.getStore().getFolder(trashFolderName)); } @Override - public void setFlag(Flag flag, boolean set) throws MessagingException - { + public void setFlag(Flag flag, boolean set) throws MessagingException { super.setFlag(flag, set); mFolder.setFlags(new Message[] { this }, new Flag[] { flag }, set); } @@ -2135,50 +1778,42 @@ public class WebDavStore extends Store /** * XML Parsing Handler Can handle all XML handling needs */ - public class WebDavHandler extends DefaultHandler - { + public class WebDavHandler extends DefaultHandler { private DataSet mDataSet = new DataSet(); private Stack mOpenTags = new Stack(); - public DataSet getDataSet() - { + public DataSet getDataSet() { return this.mDataSet; } @Override - public void startDocument() throws SAXException - { + public void startDocument() throws SAXException { this.mDataSet = new DataSet(); } @Override - public void endDocument() throws SAXException - { + public void endDocument() throws SAXException { /* Do nothing */ } @Override public void startElement(String namespaceURI, String localName, - String qName, Attributes atts) throws SAXException - { + String qName, Attributes atts) throws SAXException { mOpenTags.push(localName); } @Override - public void endElement(String namespaceURI, String localName, String qName) - { + public void endElement(String namespaceURI, String localName, String qName) { mOpenTags.pop(); /** Reset the hash temp variables */ - if (localName.equals("response")) - { + if (localName.equals("response")) { this.mDataSet.finish(); } } @Override - public void characters(char ch[], int start, int length) - { + public void characters(char ch[], int start, int length) { String value = new String(ch, start, length); mDataSet.addValue(value, mOpenTags.peek()); } @@ -2189,13 +1824,11 @@ public class WebDavStore extends Store * stored data. All processing should be done elsewhere. This is done rather than having multiple hashmaps * associating UIDs to values */ - public static class ParsedMessageEnvelope - { + public static class ParsedMessageEnvelope { /** * Holds the mappings from the name returned from Exchange to the MIME format header name */ - private final HashMap mHeaderMappings = new HashMap() - { + private final HashMap mHeaderMappings = new HashMap() { { put("mime-version", "MIME-Version"); put("content-type", "Content-Type"); @@ -2216,47 +1849,38 @@ public class WebDavStore extends Store private HashMap mMessageHeaders = new HashMap(); private ArrayList mHeaders = new ArrayList(); - public void addHeader(String field, String value) - { + public void addHeader(String field, String value) { String headerName = mHeaderMappings.get(field); - if (headerName != null) - { + if (headerName != null) { this.mMessageHeaders.put(mHeaderMappings.get(field), value); this.mHeaders.add(mHeaderMappings.get(field)); } } - public HashMap getMessageHeaders() - { + public HashMap getMessageHeaders() { return this.mMessageHeaders; } - public String[] getHeaderList() - { + public String[] getHeaderList() { return this.mHeaders.toArray(EMPTY_STRING_ARRAY); } - public void setReadStatus(boolean status) - { + public void setReadStatus(boolean status) { this.mReadStatus = status; } - public boolean getReadStatus() - { + public boolean getReadStatus() { return this.mReadStatus; } - public void setUid(String uid) - { - if (uid != null) - { + public void setUid(String uid) { + if (uid != null) { this.mUid = uid; } } - public String getUid() - { + public String getUid() { return this.mUid; } } @@ -2265,39 +1889,29 @@ public class WebDavStore extends Store * Dataset for all XML parses. Data is stored in a single format inside the class and is formatted appropriately * depending on the accessor calls made. */ - public class DataSet - { + public class DataSet { private HashMap> mData = new HashMap>(); // private HashMap mLostData = new HashMap(); private String mUid = ""; private HashMap mTempData = new HashMap(); - public void addValue(String value, String tagName) - { - if (tagName.equals("uid")) - { + public void addValue(String value, String tagName) { + if (tagName.equals("uid")) { mUid = value; } - if (mTempData.containsKey(tagName)) - { + if (mTempData.containsKey(tagName)) { mTempData.put(tagName, mTempData.get(tagName) + value); - } - else - { + } else { mTempData.put(tagName, value); } } - public void finish() - { + public void finish() { if (mUid != null && - mTempData != null) - { + mTempData != null) { mData.put(mUid, mTempData); - } - else if (mTempData != null) - { + } else if (mTempData != null) { /* * Lost Data are for requests that don't include a message UID. These requests should only have a depth * of one for the response so it will never get stomped over. @@ -2311,17 +1925,14 @@ public class WebDavStore extends Store /** * Returns a hashmap of Message UID => Message Url */ - public HashMap getUidToUrl() - { + public HashMap getUidToUrl() { HashMap uidToUrl = new HashMap(); - for (String uid : mData.keySet()) - { + for (String uid : mData.keySet()) { HashMap data = mData.get(uid); String value = data.get("href"); if (value != null && - !value.equals("")) - { + !value.equals("")) { uidToUrl.put(uid, value); } } @@ -2332,17 +1943,14 @@ public class WebDavStore extends Store /** * Returns a hashmap of Message UID => Read Status */ - public HashMap getUidToRead() - { + public HashMap getUidToRead() { HashMap uidToRead = new HashMap(); - for (String uid : mData.keySet()) - { + for (String uid : mData.keySet()) { HashMap data = mData.get(uid); String readStatus = data.get("read"); if (readStatus != null && - !readStatus.equals("")) - { + !readStatus.equals("")) { Boolean value = !readStatus.equals("0"); uidToRead.put(uid, value); } @@ -2354,12 +1962,10 @@ public class WebDavStore extends Store /** * Returns an array of all hrefs (urls) that were received */ - public String[] getHrefs() - { + public String[] getHrefs() { ArrayList hrefs = new ArrayList(); - for (String uid : mData.keySet()) - { + for (String uid : mData.keySet()) { HashMap data = mData.get(uid); String href = data.get("href"); hrefs.add(href); @@ -2371,12 +1977,10 @@ public class WebDavStore extends Store /** * Return an array of all Message UIDs that were received */ - public String[] getUids() - { + public String[] getUids() { ArrayList uids = new ArrayList(); - for (String uid : mData.keySet()) - { + for (String uid : mData.keySet()) { uids.add(uid); } @@ -2386,18 +1990,15 @@ public class WebDavStore extends Store /** * Returns the message count as it was retrieved */ - public int getMessageCount() - { + public int getMessageCount() { int messageCount = -1; - for (String uid : mData.keySet()) - { + for (String uid : mData.keySet()) { HashMap data = mData.get(uid); String count = data.get("visiblecount"); if (count != null && - !count.equals("")) - { + !count.equals("")) { messageCount = Integer.parseInt(count); } @@ -2409,28 +2010,21 @@ public class WebDavStore extends Store /** * Returns a HashMap of message UID => ParsedMessageEnvelope */ - public HashMap getMessageEnvelopes() - { + public HashMap getMessageEnvelopes() { HashMap envelopes = new HashMap(); - for (String uid : mData.keySet()) - { + for (String uid : mData.keySet()) { ParsedMessageEnvelope envelope = new ParsedMessageEnvelope(); HashMap data = mData.get(uid); - if (data != null) - { - for (String header : data.keySet()) - { - if (header.equals("read")) - { + if (data != null) { + for (String header : data.keySet()) { + if (header.equals("read")) { String read = data.get(header); Boolean readStatus = !read.equals("0"); envelope.setReadStatus(readStatus); - } - else if (header.equals("date")) - { + } else if (header.equals("date")) { /** * Exchange doesn't give us rfc822 dates like it claims. The date is in the format: * yyyy-MM-dd'T'HH:mm:ss.SSS 3) - { + try { + if (length > 3) { end = java.net.URLDecoder.decode(end, "UTF-8"); end = java.net.URLEncoder.encode(end, "UTF-8"); end = end.replaceAll("\\+", "%20"); } - } - catch (UnsupportedEncodingException uee) - { + } catch (UnsupportedEncodingException uee) { Log.e(K9.LOG_TAG, "UnsupportedEncodingException caught in HttpGeneric(String uri): " + uee + "\nTrace: " + processException(uee)); - } - catch (IllegalArgumentException iae) - { + } catch (IllegalArgumentException iae) { Log.e(K9.LOG_TAG, "IllegalArgumentException caught in HttpGeneric(String uri): " + iae + "\nTrace: " + processException(iae)); } - for (int i = 0; i < length - 1; i++) - { - if (i != 0) - { + for (int i = 0; i < length - 1; i++) { + if (i != 0) { url = url + "/" + urlParts[i]; - } - else - { + } else { url = urlParts[i]; } } - if (K9.DEBUG && K9.DEBUG_PROTOCOL_WEBDAV) - { + if (K9.DEBUG && K9.DEBUG_PROTOCOL_WEBDAV) { Log.v(K9.LOG_TAG, "url = '" + url + "' length = " + url.length() + ", end = '" + end + "' length = " + end.length()); } @@ -2551,22 +2124,18 @@ public class WebDavStore extends Store } @Override - public String getMethod() - { + public String getMethod() { return METHOD_NAME; } - public void setMethod(String method) - { - if (method != null) - { + public void setMethod(String method) { + if (method != null) { METHOD_NAME = method; } } } - public static class WebDavHttpClient extends DefaultHttpClient - { + public static class WebDavHttpClient extends DefaultHttpClient { /* * Copyright (C) 2007 The Android Open Source Project * @@ -2579,15 +2148,13 @@ public class WebDavStore extends Store * 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. */ - public static void modifyRequestToAcceptGzipResponse(HttpRequest request) - { + public static void modifyRequestToAcceptGzipResponse(HttpRequest request) { Log.i(K9.LOG_TAG, "Requesting gzipped data"); request.addHeader("Accept-Encoding", "gzip"); } public static InputStream getUngzippedContent(HttpEntity entity) - throws IOException - { + throws IOException { InputStream responseStream = entity.getContent(); if (responseStream == null) return responseStream; @@ -2597,8 +2164,7 @@ public class WebDavStore extends Store String contentEncoding = header.getValue(); if (contentEncoding == null) return responseStream; - if (contentEncoding.contains("gzip")) - { + if (contentEncoding.contains("gzip")) { Log.i(K9.LOG_TAG, "Response is gzipped"); responseStream = new GZIPInputStream(responseStream); } @@ -2606,8 +2172,7 @@ public class WebDavStore extends Store } public HttpResponse executeOverride(HttpUriRequest request, HttpContext context) - throws IOException - { + throws IOException { modifyRequestToAcceptGzipResponse(request); return super.execute(request, context); } @@ -2616,8 +2181,7 @@ public class WebDavStore extends Store /** * Simple data container for passing connection information. */ - private static class ConnectionInfo - { + private static class ConnectionInfo { public int statusCode; public short requiredAuthType; public String guessedAuthUrl; diff --git a/src/com/fsck/k9/mail/transport/SmtpTransport.java b/src/com/fsck/k9/mail/transport/SmtpTransport.java index 678e99ca1..b541b4da6 100644 --- a/src/com/fsck/k9/mail/transport/SmtpTransport.java +++ b/src/com/fsck/k9/mail/transport/SmtpTransport.java @@ -32,8 +32,7 @@ import java.util.Arrays; import java.util.HashMap; import java.util.List; -public class SmtpTransport extends Transport -{ +public class SmtpTransport extends Transport { public static final int CONNECTION_SECURITY_NONE = 0; public static final int CONNECTION_SECURITY_TLS_OPTIONAL = 1; @@ -74,73 +73,51 @@ public class SmtpTransport extends Transport * * @param _uri */ - public SmtpTransport(String _uri) throws MessagingException - { + public SmtpTransport(String _uri) throws MessagingException { URI uri; - try - { + try { uri = new URI(_uri); - } - catch (URISyntaxException use) - { + } catch (URISyntaxException use) { throw new MessagingException("Invalid SmtpTransport URI", use); } String scheme = uri.getScheme(); - if (scheme.equals("smtp")) - { + if (scheme.equals("smtp")) { mConnectionSecurity = CONNECTION_SECURITY_NONE; mPort = 25; - } - else if (scheme.equals("smtp+tls")) - { + } else if (scheme.equals("smtp+tls")) { mConnectionSecurity = CONNECTION_SECURITY_TLS_OPTIONAL; mPort = 25; - } - else if (scheme.equals("smtp+tls+")) - { + } else if (scheme.equals("smtp+tls+")) { mConnectionSecurity = CONNECTION_SECURITY_TLS_REQUIRED; mPort = 25; - } - else if (scheme.equals("smtp+ssl+")) - { + } else if (scheme.equals("smtp+ssl+")) { mConnectionSecurity = CONNECTION_SECURITY_SSL_REQUIRED; mPort = 465; - } - else if (scheme.equals("smtp+ssl")) - { + } else if (scheme.equals("smtp+ssl")) { mConnectionSecurity = CONNECTION_SECURITY_SSL_OPTIONAL; mPort = 465; - } - else - { + } else { throw new MessagingException("Unsupported protocol"); } mHost = uri.getHost(); - if (uri.getPort() != -1) - { + if (uri.getPort() != -1) { mPort = uri.getPort(); } - if (uri.getUserInfo() != null) - { - try - { + if (uri.getUserInfo() != null) { + try { String[] userInfoParts = uri.getUserInfo().split(":"); mUsername = URLDecoder.decode(userInfoParts[0], "UTF-8"); - if (userInfoParts.length > 1) - { + if (userInfoParts.length > 1) { mPassword = URLDecoder.decode(userInfoParts[1], "UTF-8"); } - if (userInfoParts.length > 2) - { + if (userInfoParts.length > 2) { mAuthType = userInfoParts[2]; } - } - catch (UnsupportedEncodingException enc) - { + } catch (UnsupportedEncodingException enc) { // This shouldn't happen since the encoding is hardcoded to UTF-8 Log.e(K9.LOG_TAG, "Couldn't urldecode username or password.", enc); } @@ -148,39 +125,28 @@ public class SmtpTransport extends Transport } @Override - public void open() throws MessagingException - { - try - { + public void open() throws MessagingException { + try { InetAddress[] addresses = InetAddress.getAllByName(mHost); - for (int i = 0; i < addresses.length; i++) - { - try - { + for (int i = 0; i < addresses.length; i++) { + try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], mPort); if (mConnectionSecurity == CONNECTION_SECURITY_SSL_REQUIRED || - mConnectionSecurity == CONNECTION_SECURITY_SSL_OPTIONAL) - { + mConnectionSecurity == CONNECTION_SECURITY_SSL_OPTIONAL) { SSLContext sslContext = SSLContext.getInstance("TLS"); boolean secure = mConnectionSecurity == CONNECTION_SECURITY_SSL_REQUIRED; - sslContext.init(null, new TrustManager[] - { + sslContext.init(null, new TrustManager[] { TrustManagerFactory.get(mHost, secure) }, new SecureRandom()); mSocket = sslContext.getSocketFactory().createSocket(); mSocket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); mSecure = true; - } - else - { + } else { mSocket = new Socket(); mSocket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } - } - catch (ConnectException e) - { - if (i < (addresses.length - 1)) - { + } catch (ConnectException e) { + if (i < (addresses.length - 1)) { // there are still other addresses for that host to try continue; } @@ -202,23 +168,16 @@ public class SmtpTransport extends Transport String localHost = localAddress.getHostName(); String ipAddr = localAddress.getHostAddress(); - if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) - { + if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { // We don't have a FQDN or the hostname contains invalid // characters (see issue 2143), so use IP address. - if (!ipAddr.equals("")) - { - if (localAddress instanceof Inet6Address) - { + if (!ipAddr.equals("")) { + if (localAddress instanceof Inet6Address) { localHost = "[IPV6:" + ipAddr + "]"; - } - else - { + } else { localHost = "[" + ipAddr + "]"; } - } - else - { + } else { // If the IP address is no good, set a sane default (see issue 2750). localHost = "android"; } @@ -237,16 +196,13 @@ public class SmtpTransport extends Transport * if not. */ if (mConnectionSecurity == CONNECTION_SECURITY_TLS_OPTIONAL - || mConnectionSecurity == CONNECTION_SECURITY_TLS_REQUIRED) - { - if (results.contains("STARTTLS")) - { + || mConnectionSecurity == CONNECTION_SECURITY_TLS_REQUIRED) { + if (results.contains("STARTTLS")) { executeSimpleCommand("STARTTLS"); SSLContext sslContext = SSLContext.getInstance("TLS"); boolean secure = mConnectionSecurity == CONNECTION_SECURITY_TLS_REQUIRED; - sslContext.init(null, new TrustManager[] - { + sslContext.init(null, new TrustManager[] { TrustManagerFactory.get(mHost, secure) }, new SecureRandom()); mSocket = sslContext.getSocketFactory().createSocket(mSocket, mHost, mPort, @@ -260,9 +216,7 @@ public class SmtpTransport extends Transport * Exim. */ results = executeSimpleCommand("EHLO " + localHost); - } - else if (mConnectionSecurity == CONNECTION_SECURITY_TLS_REQUIRED) - { + } else if (mConnectionSecurity == CONNECTION_SECURITY_TLS_REQUIRED) { throw new MessagingException("TLS not supported but required"); } } @@ -273,61 +227,42 @@ public class SmtpTransport extends Transport boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; - for (String result : results) - { - if (result.matches(".*AUTH.*LOGIN.*$")) - { + for (String result : results) { + if (result.matches(".*AUTH.*LOGIN.*$")) { authLoginSupported = true; } - if (result.matches(".*AUTH.*PLAIN.*$")) - { + if (result.matches(".*AUTH.*PLAIN.*$")) { authPlainSupported = true; } - if (result.matches(".*AUTH.*CRAM-MD5.*$") && mAuthType != null && mAuthType.equals("CRAM_MD5")) - { + if (result.matches(".*AUTH.*CRAM-MD5.*$") && mAuthType != null && mAuthType.equals("CRAM_MD5")) { authCramMD5Supported = true; } } if (mUsername != null && mUsername.length() > 0 && mPassword != null - && mPassword.length() > 0) - { - if (authCramMD5Supported) - { + && mPassword.length() > 0) { + if (authCramMD5Supported) { saslAuthCramMD5(mUsername, mPassword); - } - else if (authPlainSupported) - { + } else if (authPlainSupported) { saslAuthPlain(mUsername, mPassword); - } - else if (authLoginSupported) - { + } else if (authLoginSupported) { saslAuthLogin(mUsername, mPassword); - } - else - { + } else { throw new MessagingException("No valid authentication mechanism found."); } } - } - catch (SSLException e) - { + } catch (SSLException e) { throw new CertificateValidationException(e.getMessage(), e); - } - catch (GeneralSecurityException gse) - { + } catch (GeneralSecurityException gse) { throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); - } - catch (IOException ioe) - { + } catch (IOException ioe) { throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } @Override - public void sendMessage(Message message) throws MessagingException - { + public void sendMessage(Message message) throws MessagingException { ArrayList
    addresses = new ArrayList
    (); { addresses.addAll(Arrays.asList(message.getRecipients(RecipientType.TO))); @@ -338,13 +273,11 @@ public class SmtpTransport extends Transport HashMap> charsetAddressesMap = new HashMap>(); - for (Address address : addresses) - { + for (Address address : addresses) { String addressString = address.getAddress(); String charset = MimeUtility.getCharsetFromAddress(addressString); ArrayList addressesOfCharset = charsetAddressesMap.get(charset); - if (addressesOfCharset == null) - { + if (addressesOfCharset == null) { addressesOfCharset = new ArrayList(); charsetAddressesMap.put(charset, addressesOfCharset); } @@ -352,8 +285,7 @@ public class SmtpTransport extends Transport } for (HashMap.Entry> charsetAddressesMapEntry : - charsetAddressesMap.entrySet()) - { + charsetAddressesMap.entrySet()) { String charset = charsetAddressesMapEntry.getKey(); ArrayList addressesOfCharset = charsetAddressesMapEntry.getValue(); message.setCharset(charset); @@ -362,8 +294,7 @@ public class SmtpTransport extends Transport } private void sendMessageTo(ArrayList addresses, Message message) - throws MessagingException - { + throws MessagingException { close(); open(); @@ -371,12 +302,10 @@ public class SmtpTransport extends Transport Address[] from = message.getFrom(); boolean possibleSend = false; - try - { + try { //TODO: Add BODY=8BITMIME parameter if appropriate? executeSimpleCommand("MAIL FROM: " + "<" + from[0].getAddress() + ">"); - for (String address : addresses) - { + for (String address : addresses) { executeSimpleCommand("RCPT TO: " + "<" + address + ">"); } executeSimpleCommand("DATA"); @@ -394,15 +323,11 @@ public class SmtpTransport extends Transport possibleSend = true; // After the "\r\n." is attempted, we may have sent the message executeSimpleCommand("\r\n."); - } - catch (Exception e) - { + } catch (Exception e) { MessagingException me = new MessagingException("Unable to send message", e); me.setPermanentFailure(possibleSend); throw me; - } - finally - { + } finally { close(); } @@ -411,38 +336,25 @@ public class SmtpTransport extends Transport } @Override - public void close() - { - try - { + public void close() { + try { executeSimpleCommand("QUIT"); - } - catch (Exception e) - { + } catch (Exception e) { } - try - { + try { mIn.close(); - } - catch (Exception e) - { + } catch (Exception e) { } - try - { + try { mOut.close(); - } - catch (Exception e) - { + } catch (Exception e) { } - try - { + try { mSocket.close(); - } - catch (Exception e) - { + } catch (Exception e) { } mIn = null; @@ -450,22 +362,15 @@ public class SmtpTransport extends Transport mSocket = null; } - private String readLine() throws IOException - { + private String readLine() throws IOException { StringBuffer sb = new StringBuffer(); int d; - while ((d = mIn.read()) != -1) - { - if (((char)d) == '\r') - { + while ((d = mIn.read()) != -1) { + if (((char)d) == '\r') { continue; - } - else if (((char)d) == '\n') - { + } else if (((char)d) == '\n') { break; - } - else - { + } else { sb.append((char)d); } } @@ -476,17 +381,12 @@ public class SmtpTransport extends Transport return ret; } - private void writeLine(String s, boolean sensitive) throws IOException - { - if (K9.DEBUG && K9.DEBUG_PROTOCOL_SMTP) - { + private void writeLine(String s, boolean sensitive) throws IOException { + if (K9.DEBUG && K9.DEBUG_PROTOCOL_SMTP) { final String commandToLog; - if (sensitive && !K9.DEBUG_SENSITIVE) - { + if (sensitive && !K9.DEBUG_SENSITIVE) { commandToLog = "SMTP >>> *sensitive*"; - } - else - { + } else { commandToLog = "SMTP >>> " + s; } Log.d(K9.LOG_TAG, commandToLog); @@ -513,30 +413,24 @@ public class SmtpTransport extends Transport mOut.flush(); } - private void checkLine(String line) throws MessagingException - { - if (line.length() < 1) - { + private void checkLine(String line) throws MessagingException { + if (line.length() < 1) { throw new MessagingException("SMTP response is 0 length"); } char c = line.charAt(0); - if ((c == '4') || (c == '5')) - { + if ((c == '4') || (c == '5')) { throw new MessagingException(line); } } - private List executeSimpleCommand(String command) throws IOException, MessagingException - { + private List executeSimpleCommand(String command) throws IOException, MessagingException { return executeSimpleCommand(command, false); } private List executeSimpleCommand(String command, boolean sensitive) - throws IOException, MessagingException - { + throws IOException, MessagingException { List results = new ArrayList(); - if (command != null) - { + if (command != null) { writeLine(command, sensitive); } @@ -546,16 +440,13 @@ public class SmtpTransport extends Transport * be handled by checkLine() below. */ String line = readLine(); - while (line.length() >= 4) - { - if (line.length() > 4) - { + while (line.length() >= 4) { + if (line.length() > 4) { // Everything after the first four characters goes into the results array. results.add(line.substring(4)); } - if (line.charAt(3) != '-') - { + if (line.charAt(3) != '-') { // If the fourth character isn't "-" this is the last line of the response. break; } @@ -587,18 +478,13 @@ public class SmtpTransport extends Transport // S: 235 2.0.0 OK Authenticated private void saslAuthLogin(String username, String password) throws MessagingException, - AuthenticationFailedException, IOException - { - try - { + AuthenticationFailedException, IOException { + try { executeSimpleCommand("AUTH LOGIN"); executeSimpleCommand(new String(Base64.encodeBase64(username.getBytes())), true); executeSimpleCommand(new String(Base64.encodeBase64(password.getBytes())), true); - } - catch (MessagingException me) - { - if (me.getMessage().length() > 1 && me.getMessage().charAt(1) == '3') - { + } catch (MessagingException me) { + if (me.getMessage().length() > 1 && me.getMessage().charAt(1) == '3') { throw new AuthenticationFailedException("AUTH LOGIN failed (" + me.getMessage() + ")"); } @@ -607,18 +493,13 @@ public class SmtpTransport extends Transport } private void saslAuthPlain(String username, String password) throws MessagingException, - AuthenticationFailedException, IOException - { + AuthenticationFailedException, IOException { byte[] data = ("\000" + username + "\000" + password).getBytes(); data = new Base64().encode(data); - try - { + try { executeSimpleCommand("AUTH PLAIN " + new String(data), true); - } - catch (MessagingException me) - { - if (me.getMessage().length() > 1 && me.getMessage().charAt(1) == '3') - { + } catch (MessagingException me) { + if (me.getMessage().length() > 1 && me.getMessage().charAt(1) == '3') { throw new AuthenticationFailedException("AUTH PLAIN failed (" + me.getMessage() + ")"); } @@ -627,8 +508,7 @@ public class SmtpTransport extends Transport } private void saslAuthCramMD5(String username, String password) throws MessagingException, - AuthenticationFailedException, IOException - { + AuthenticationFailedException, IOException { List respList = executeSimpleCommand("AUTH CRAM-MD5"); if (respList.size() != 1) throw new AuthenticationFailedException("Unable to negotiate CRAM-MD5"); String b64Nonce = respList.get(0); @@ -637,16 +517,12 @@ public class SmtpTransport extends Transport byte[] opad = new byte[64]; byte[] secretBytes = password.getBytes("US-ASCII"); MessageDigest md; - try - { + try { md = MessageDigest.getInstance("MD5"); - } - catch (NoSuchAlgorithmException nsae) - { + } catch (NoSuchAlgorithmException nsae) { throw new AuthenticationFailedException("MD5 Not Available."); } - if (secretBytes.length > 64) - { + if (secretBytes.length > 64) { secretBytes = md.digest(secretBytes); } System.arraycopy(secretBytes, 0, ipad, 0, secretBytes.length); @@ -660,12 +536,9 @@ public class SmtpTransport extends Transport String plainCRAM = username + " " + new String(Hex.encodeHex(result)); byte[] b64CRAM = Base64.encodeBase64(plainCRAM.getBytes("US-ASCII")); String b64CRAMString = new String(b64CRAM, "US-ASCII"); - try - { + try { executeSimpleCommand(b64CRAMString, true); - } - catch (MessagingException me) - { + } catch (MessagingException me) { throw new AuthenticationFailedException("Unable to negotiate MD5 CRAM"); } } diff --git a/src/com/fsck/k9/mail/transport/TrustedSocketFactory.java b/src/com/fsck/k9/mail/transport/TrustedSocketFactory.java index d4c179601..fa23f079b 100644 --- a/src/com/fsck/k9/mail/transport/TrustedSocketFactory.java +++ b/src/com/fsck/k9/mail/transport/TrustedSocketFactory.java @@ -17,16 +17,13 @@ import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; -public class TrustedSocketFactory implements LayeredSocketFactory -{ +public class TrustedSocketFactory implements LayeredSocketFactory { private SSLSocketFactory mSocketFactory; private org.apache.http.conn.ssl.SSLSocketFactory mSchemeSocketFactory; - public TrustedSocketFactory(String host, boolean secure) throws NoSuchAlgorithmException, KeyManagementException - { + public TrustedSocketFactory(String host, boolean secure) throws NoSuchAlgorithmException, KeyManagementException { SSLContext sslContext = SSLContext.getInstance("TLS"); - sslContext.init(null, new TrustManager[] - { + sslContext.init(null, new TrustManager[] { TrustManagerFactory.get(host, secure) }, new SecureRandom()); mSocketFactory = sslContext.getSocketFactory(); @@ -37,18 +34,15 @@ public class TrustedSocketFactory implements LayeredSocketFactory public Socket connectSocket(Socket sock, String host, int port, InetAddress localAddress, int localPort, HttpParams params) - throws IOException, UnknownHostException, ConnectTimeoutException - { + throws IOException, UnknownHostException, ConnectTimeoutException { return mSchemeSocketFactory.connectSocket(sock, host, port, localAddress, localPort, params); } - public Socket createSocket() throws IOException - { + public Socket createSocket() throws IOException { return mSocketFactory.createSocket(); } - public boolean isSecure(Socket sock) throws IllegalArgumentException - { + public boolean isSecure(Socket sock) throws IllegalArgumentException { return mSchemeSocketFactory.isSecure(sock); } public Socket createSocket( @@ -56,8 +50,7 @@ public class TrustedSocketFactory implements LayeredSocketFactory final String host, final int port, final boolean autoClose - ) throws IOException, UnknownHostException - { + ) throws IOException, UnknownHostException { SSLSocket sslSocket = (SSLSocket) mSocketFactory.createSocket( socket, host, diff --git a/src/com/fsck/k9/mail/transport/WebDavTransport.java b/src/com/fsck/k9/mail/transport/WebDavTransport.java index 0790cc2a6..72159a5e6 100644 --- a/src/com/fsck/k9/mail/transport/WebDavTransport.java +++ b/src/com/fsck/k9/mail/transport/WebDavTransport.java @@ -10,18 +10,13 @@ import com.fsck.k9.mail.MessagingException; import com.fsck.k9.mail.Transport; import com.fsck.k9.mail.store.WebDavStore; -public class WebDavTransport extends Transport -{ +public class WebDavTransport extends Transport { private WebDavStore store; - public WebDavTransport(Account account) throws MessagingException - { - if (account.getRemoteStore() instanceof WebDavStore) - { + public WebDavTransport(Account account) throws MessagingException { + if (account.getRemoteStore() instanceof WebDavStore) { store = (WebDavStore) account.getRemoteStore(); - } - else - { + } else { store = new WebDavStore(account); } @@ -30,8 +25,7 @@ public class WebDavTransport extends Transport } @Override - public void open() throws MessagingException - { + public void open() throws MessagingException { if (K9.DEBUG) Log.d(K9.LOG_TAG, ">>> open called on WebDavTransport "); @@ -39,13 +33,11 @@ public class WebDavTransport extends Transport } @Override - public void close() - { + public void close() { } @Override - public void sendMessage(Message message) throws MessagingException - { + public void sendMessage(Message message) throws MessagingException { store.sendMessages(new Message[] { message }); } } diff --git a/src/com/fsck/k9/mail/transport/imap/ImapSettings.java b/src/com/fsck/k9/mail/transport/imap/ImapSettings.java index d16eb0273..769763015 100644 --- a/src/com/fsck/k9/mail/transport/imap/ImapSettings.java +++ b/src/com/fsck/k9/mail/transport/imap/ImapSettings.java @@ -7,8 +7,7 @@ import com.fsck.k9.mail.store.ImapStore.ImapConnection; /** * Settings source for IMAP. Implemented in order to remove coupling between {@link ImapStore} and {@link ImapConnection}. */ -public interface ImapSettings -{ +public interface ImapSettings { String getHost(); int getPort(); diff --git a/src/com/fsck/k9/preferences/CheckBoxListPreference.java b/src/com/fsck/k9/preferences/CheckBoxListPreference.java index f67788c11..1a6ec2980 100644 --- a/src/com/fsck/k9/preferences/CheckBoxListPreference.java +++ b/src/com/fsck/k9/preferences/CheckBoxListPreference.java @@ -6,8 +6,7 @@ import android.content.DialogInterface; import android.preference.DialogPreference; import android.util.AttributeSet; -public class CheckBoxListPreference extends DialogPreference -{ +public class CheckBoxListPreference extends DialogPreference { private CharSequence[] mItems; @@ -23,8 +22,7 @@ public class CheckBoxListPreference extends DialogPreference * @param attrs * @param defStyle */ - public CheckBoxListPreference(Context context, AttributeSet attrs, int defStyle) - { + public CheckBoxListPreference(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @@ -32,52 +30,43 @@ public class CheckBoxListPreference extends DialogPreference * @param context * @param attrs */ - public CheckBoxListPreference(Context context, AttributeSet attrs) - { + public CheckBoxListPreference(Context context, AttributeSet attrs) { super(context, attrs); } @Override - protected void onPrepareDialogBuilder(final Builder builder) - { + protected void onPrepareDialogBuilder(final Builder builder) { mPendingItems = new boolean[mItems.length]; System.arraycopy(mCheckedItems, 0, mPendingItems, 0, mCheckedItems.length); builder.setMultiChoiceItems(mItems, mPendingItems, - new DialogInterface.OnMultiChoiceClickListener() - { + new DialogInterface.OnMultiChoiceClickListener() { @Override public void onClick(final DialogInterface dialog, final int which, - final boolean isChecked) - { + final boolean isChecked) { mPendingItems[which] = isChecked; } }); } @Override - protected void onDialogClosed(boolean positiveResult) - { - if (positiveResult) - { + protected void onDialogClosed(boolean positiveResult) { + if (positiveResult) { System.arraycopy(mPendingItems, 0, mCheckedItems, 0, mPendingItems.length); } mPendingItems = null; } - public void setItems(final CharSequence[] items) - { + public void setItems(final CharSequence[] items) { mItems = items; } - public void setCheckedItems(final boolean[] items) - { + public void setCheckedItems(final boolean[] items) { mCheckedItems = items; } - public boolean[] getCheckedItems() - { + public boolean[] getCheckedItems() { return mCheckedItems; } diff --git a/src/com/fsck/k9/preferences/Editor.java b/src/com/fsck/k9/preferences/Editor.java index bdbedf39b..412d14ff8 100644 --- a/src/com/fsck/k9/preferences/Editor.java +++ b/src/com/fsck/k9/preferences/Editor.java @@ -8,8 +8,7 @@ import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; -public class Editor implements android.content.SharedPreferences.Editor -{ +public class Editor implements android.content.SharedPreferences.Editor { private Storage storage; private HashMap changes = new HashMap(); private ArrayList removals = new ArrayList(); @@ -18,31 +17,23 @@ public class Editor implements android.content.SharedPreferences.Editor Map snapshot = new HashMap(); - protected Editor(Storage storage) - { + protected Editor(Storage storage) { this.storage = storage; snapshot.putAll(storage.getAll()); } - public void copy(android.content.SharedPreferences input) - { - Map oldVals = input.getAll(); - for (Entry entry : oldVals.entrySet()) - { + public void copy(android.content.SharedPreferences input) { + Map < String, ? > oldVals = input.getAll(); + for (Entry < String, ? > entry : oldVals.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); - if (key != null && value != null) - { - if (K9.DEBUG) - { + if (key != null && value != null) { + if (K9.DEBUG) { Log.d(K9.LOG_TAG, "Copying key '" + key + "', value '" + value + "'"); } changes.put(key, "" + value); - } - else - { - if (K9.DEBUG) - { + } else { + if (K9.DEBUG) { Log.d(K9.LOG_TAG, "Skipping copying key '" + key + "', value '" + value + "'"); } } @@ -50,16 +41,14 @@ public class Editor implements android.content.SharedPreferences.Editor } //@Override - public android.content.SharedPreferences.Editor clear() - { + public android.content.SharedPreferences.Editor clear() { removeAll = true; return this; } // TODO Android 2.3 provides a sexy new "apply" method we need to implement - public void apply() - { + public void apply() { commit(); } @@ -67,44 +56,33 @@ public class Editor implements android.content.SharedPreferences.Editor /* This method is poorly defined. It should throw an Exception on failure */ //@Override - public boolean commit() - { - try - { + public boolean commit() { + try { commitChanges(); return true; - } - catch (Exception e) - { + } catch (Exception e) { Log.e(K9.LOG_TAG, "Failed to save preferences", e); return false; } } - public void commitChanges() - { + public void commitChanges() { long startTime = System.currentTimeMillis(); Log.i(K9.LOG_TAG, "Committing preference changes"); - Runnable committer = new Runnable() - { - public void run() - { - if (removeAll) - { + Runnable committer = new Runnable() { + public void run() { + if (removeAll) { storage.removeAll(); } - for (String removeKey : removals) - { + for (String removeKey : removals) { storage.remove(removeKey); } Map insertables = new HashMap(); - for (Entry entry : changes.entrySet()) - { + for (Entry entry : changes.entrySet()) { String key = entry.getKey(); String newValue = entry.getValue(); String oldValue = snapshot.get(key); - if (removeAll || removals.contains(key) || !newValue.equals(oldValue)) - { + if (removeAll || removals.contains(key) || !newValue.equals(oldValue)) { insertables.put(key, newValue); } } @@ -119,52 +97,43 @@ public class Editor implements android.content.SharedPreferences.Editor //@Override public android.content.SharedPreferences.Editor putBoolean(String key, - boolean value) - { + boolean value) { changes.put(key, "" + value); return this; } //@Override public android.content.SharedPreferences.Editor putFloat(String key, - float value) - { + float value) { changes.put(key, "" + value); return this; } //@Override - public android.content.SharedPreferences.Editor putInt(String key, int value) - { + public android.content.SharedPreferences.Editor putInt(String key, int value) { changes.put(key, "" + value); return this; } //@Override - public android.content.SharedPreferences.Editor putLong(String key, long value) - { + public android.content.SharedPreferences.Editor putLong(String key, long value) { changes.put(key, "" + value); return this; } //@Override public android.content.SharedPreferences.Editor putString(String key, - String value) - { - if (value == null) - { + String value) { + if (value == null) { remove(key); - } - else - { + } else { changes.put(key, value); } return this; } //@Override - public android.content.SharedPreferences.Editor remove(String key) - { + public android.content.SharedPreferences.Editor remove(String key) { removals.add(key); return this; } diff --git a/src/com/fsck/k9/preferences/Storage.java b/src/com/fsck/k9/preferences/Storage.java index 13183444f..fd05d812b 100644 --- a/src/com/fsck/k9/preferences/Storage.java +++ b/src/com/fsck/k9/preferences/Storage.java @@ -18,8 +18,7 @@ import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; -public class Storage implements SharedPreferences -{ +public class Storage implements SharedPreferences { private static ConcurrentHashMap storages = new ConcurrentHashMap(); @@ -40,48 +39,39 @@ public class Storage implements SharedPreferences private Context context = null; - private SQLiteDatabase openDB() - { + private SQLiteDatabase openDB() { SQLiteDatabase mDb = context.openOrCreateDatabase(DB_NAME, Context.MODE_PRIVATE, null); - if (mDb.getVersion() == 1) - { + if (mDb.getVersion() == 1) { Log.i(K9.LOG_TAG, "Updating preferences to urlencoded username/password"); String accountUuids = readValue(mDb, "accountUuids"); - if (accountUuids != null && accountUuids.length() != 0) - { + if (accountUuids != null && accountUuids.length() != 0) { String[] uuids = accountUuids.split(","); - for (String uuid : uuids) - { - try - { + for (String uuid : uuids) { + try { String storeUriStr = Utility.base64Decode(readValue(mDb, uuid + ".storeUri")); String transportUriStr = Utility.base64Decode(readValue(mDb, uuid + ".transportUri")); URI uri = new URI(transportUriStr); String newUserInfo = null; - if (transportUriStr != null) - { + if (transportUriStr != null) { String[] userInfoParts = uri.getUserInfo().split(":"); String usernameEnc = URLEncoder.encode(userInfoParts[0], "UTF-8"); String passwordEnc = ""; String authType = ""; - if (userInfoParts.length > 1) - { + if (userInfoParts.length > 1) { passwordEnc = ":" + URLEncoder.encode(userInfoParts[1], "UTF-8"); } - if (userInfoParts.length > 2) - { + if (userInfoParts.length > 2) { authType = ":" + userInfoParts[2]; } newUserInfo = usernameEnc + passwordEnc + authType; } - if (newUserInfo != null) - { + if (newUserInfo != null) { URI newUri = new URI(uri.getScheme(), newUserInfo, uri.getHost(), uri.getPort(), uri.getPath(), uri.getQuery(), uri.getFragment()); String newTransportUriStr = Utility.base64Encode(newUri.toString()); writeValue(mDb, uuid + ".transportUri", newTransportUriStr); @@ -89,61 +79,48 @@ public class Storage implements SharedPreferences uri = new URI(storeUriStr); newUserInfo = null; - if (storeUriStr.startsWith("imap")) - { + if (storeUriStr.startsWith("imap")) { String[] userInfoParts = uri.getUserInfo().split(":"); - if (userInfoParts.length == 2) - { + if (userInfoParts.length == 2) { String usernameEnc = URLEncoder.encode(userInfoParts[0], "UTF-8"); String passwordEnc = URLEncoder.encode(userInfoParts[1], "UTF-8"); newUserInfo = usernameEnc + ":" + passwordEnc; - } - else - { + } else { String authType = userInfoParts[0]; String usernameEnc = URLEncoder.encode(userInfoParts[1], "UTF-8"); String passwordEnc = URLEncoder.encode(userInfoParts[2], "UTF-8"); newUserInfo = authType + ":" + usernameEnc + ":" + passwordEnc; } - } - else if (storeUriStr.startsWith("pop3")) - { + } else if (storeUriStr.startsWith("pop3")) { String[] userInfoParts = uri.getUserInfo().split(":", 2); String usernameEnc = URLEncoder.encode(userInfoParts[0], "UTF-8"); String passwordEnc = ""; - if (userInfoParts.length > 1) - { + if (userInfoParts.length > 1) { passwordEnc = ":" + URLEncoder.encode(userInfoParts[1], "UTF-8"); } newUserInfo = usernameEnc + passwordEnc; - } - else if (storeUriStr.startsWith("webdav")) - { + } else if (storeUriStr.startsWith("webdav")) { String[] userInfoParts = uri.getUserInfo().split(":", 2); String usernameEnc = URLEncoder.encode(userInfoParts[0], "UTF-8"); String passwordEnc = ""; - if (userInfoParts.length > 1) - { + if (userInfoParts.length > 1) { passwordEnc = ":" + URLEncoder.encode(userInfoParts[1], "UTF-8"); } newUserInfo = usernameEnc + passwordEnc; } - if (newUserInfo != null) - { + if (newUserInfo != null) { URI newUri = new URI(uri.getScheme(), newUserInfo, uri.getHost(), uri.getPort(), uri.getPath(), uri.getQuery(), uri.getFragment()); String newStoreUriStr = Utility.base64Encode(newUri.toString()); writeValue(mDb, uuid + ".storeUri", newStoreUriStr); } - } - catch (Exception e) - { + } catch (Exception e) { Log.e(K9.LOG_TAG, "ooops", e); } } @@ -152,8 +129,7 @@ public class Storage implements SharedPreferences mDb.setVersion(DB_VERSION); } - if (mDb.getVersion() != DB_VERSION) - { + if (mDb.getVersion() != DB_VERSION) { Log.i(K9.LOG_TAG, "Creating Storage database"); mDb.execSQL("DROP TABLE IF EXISTS preferences_storage"); mDb.execSQL("CREATE TABLE preferences_storage " + @@ -164,37 +140,26 @@ public class Storage implements SharedPreferences } - public static Storage getStorage(Context context) - { + public static Storage getStorage(Context context) { Storage tmpStorage = storages.get(context); - if (tmpStorage != null) - { - if (K9.DEBUG) - { + if (tmpStorage != null) { + if (K9.DEBUG) { Log.d(K9.LOG_TAG, "Returning already existing Storage"); } return tmpStorage; - } - else - { - if (K9.DEBUG) - { + } else { + if (K9.DEBUG) { Log.d(K9.LOG_TAG, "Creating provisional storage"); } tmpStorage = new Storage(context); Storage oldStorage = storages.putIfAbsent(context, tmpStorage); - if (oldStorage != null) - { - if (K9.DEBUG) - { + if (oldStorage != null) { + if (K9.DEBUG) { Log.d(K9.LOG_TAG, "Another thread beat us to creating the Storage, returning that one"); } return oldStorage; - } - else - { - if (K9.DEBUG) - { + } else { + if (K9.DEBUG) { Log.d(K9.LOG_TAG, "Returning the Storage we created"); } return tmpStorage; @@ -202,36 +167,28 @@ public class Storage implements SharedPreferences } } - private void loadValues() - { + private void loadValues() { long startTime = System.currentTimeMillis(); Log.i(K9.LOG_TAG, "Loading preferences from DB into Storage"); Cursor cursor = null; SQLiteDatabase mDb = null; - try - { + try { mDb = openDB(); cursor = mDb.rawQuery("SELECT primkey, value FROM preferences_storage", null); - while (cursor.moveToNext()) - { + while (cursor.moveToNext()) { String key = cursor.getString(0); String value = cursor.getString(1); - if (K9.DEBUG) - { + if (K9.DEBUG) { Log.d(K9.LOG_TAG, "Loading key '" + key + "', value = '" + value + "'"); } storage.put(key, value); } - } - finally - { - if (cursor != null) - { + } finally { + if (cursor != null) { cursor.close(); } - if (mDb != null) - { + if (mDb != null) { mDb.close(); } long endTime = System.currentTimeMillis(); @@ -239,35 +196,29 @@ public class Storage implements SharedPreferences } } - private Storage(Context context) - { + private Storage(Context context) { this.context = context; loadValues(); } - private void keyChange(String key) - { + private void keyChange(String key) { ArrayList changedKeys = workingChangedKeys.get(); - if (!changedKeys.contains(key)) - { + if (!changedKeys.contains(key)) { changedKeys.add(key); } } - protected void put(String key, String value) - { + protected void put(String key, String value) { ContentValues cv = generateCV(key, value); workingDB.get().insert("preferences_storage", "primkey", cv); liveUpdate(key, value); } - protected void put(Map insertables) - { + protected void put(Map insertables) { String sql = "insert into preferences_storage (primkey, value) VALUES (?, ?)"; SQLiteStatement stmt = workingDB.get().compileStatement(sql); - for (Map.Entry entry : insertables.entrySet()) - { + for (Map.Entry entry : insertables.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); stmt.bindString(1, key); @@ -279,41 +230,35 @@ public class Storage implements SharedPreferences stmt.close(); } - private ContentValues generateCV(String key, String value) - { + private ContentValues generateCV(String key, String value) { ContentValues cv = new ContentValues(); cv.put("primkey", key); cv.put("value", value); return cv; } - private void liveUpdate(String key, String value) - { + private void liveUpdate(String key, String value) { workingStorage.get().put(key, value); keyChange(key); } - protected void remove(String key) - { + protected void remove(String key) { workingDB.get().delete("preferences_storage", "primkey = ?", new String[] { key }); workingStorage.get().remove(key); keyChange(key); } - protected void removeAll() - { - for (String key : workingStorage.get().keySet()) - { + protected void removeAll() { + for (String key : workingStorage.get().keySet()) { keyChange(key); } workingDB.get().execSQL("DELETE FROM preferences_storage"); workingStorage.get().clear(); } - protected void doInTransaction(Runnable dbWork) - { + protected void doInTransaction(Runnable dbWork) { ConcurrentHashMap newStorage = new ConcurrentHashMap(); newStorage.putAll(storage); workingStorage.set(newStorage); @@ -325,21 +270,16 @@ public class Storage implements SharedPreferences workingChangedKeys.set(changedKeys); mDb.beginTransaction(); - try - { + try { dbWork.run(); mDb.setTransactionSuccessful(); storage = newStorage; - for (String changedKey : changedKeys) - { - for (OnSharedPreferenceChangeListener listener : listeners) - { + for (String changedKey : changedKeys) { + for (OnSharedPreferenceChangeListener listener : listeners) { listener.onSharedPreferenceChanged(this, changedKey); } } - } - finally - { + } finally { workingDB.remove(); workingStorage.remove(); workingChangedKeys.remove(); @@ -348,79 +288,65 @@ public class Storage implements SharedPreferences } } - public long size() - { + public long size() { return storage.size(); } //@Override - public boolean contains(String key) - { + public boolean contains(String key) { return storage.contains(key); } //@Override - public com.fsck.k9.preferences.Editor edit() - { + public com.fsck.k9.preferences.Editor edit() { return new com.fsck.k9.preferences.Editor(this); } //@Override - public Map getAll() - { + public Map getAll() { return storage; } //@Override - public boolean getBoolean(String key, boolean defValue) - { + public boolean getBoolean(String key, boolean defValue) { String val = storage.get(key); - if (val == null) - { + if (val == null) { return defValue; } return Boolean.parseBoolean(val); } //@Override - public float getFloat(String key, float defValue) - { + public float getFloat(String key, float defValue) { String val = storage.get(key); - if (val == null) - { + if (val == null) { return defValue; } return Float.parseFloat(val); } //@Override - public int getInt(String key, int defValue) - { + public int getInt(String key, int defValue) { String val = storage.get(key); - if (val == null) - { + if (val == null) { return defValue; } return Integer.parseInt(val); } //@Override - public long getLong(String key, long defValue) - { + public long getLong(String key, long defValue) { String val = storage.get(key); - if (val == null) - { + if (val == null) { return defValue; } return Long.parseLong(val); } //@Override - public String getString(String key, String defValue) - { + public String getString(String key, String defValue) { String val = storage.get(key); - if (val == null) - { + if (val == null) { return defValue; } return val; @@ -428,24 +354,20 @@ public class Storage implements SharedPreferences //@Override public void registerOnSharedPreferenceChangeListener( - OnSharedPreferenceChangeListener listener) - { + OnSharedPreferenceChangeListener listener) { listeners.addIfAbsent(listener); } //@Override public void unregisterOnSharedPreferenceChangeListener( - OnSharedPreferenceChangeListener listener) - { + OnSharedPreferenceChangeListener listener) { listeners.remove(listener); } - private String readValue(SQLiteDatabase mDb, String key) - { + private String readValue(SQLiteDatabase mDb, String key) { Cursor cursor = null; String value = null; - try - { + try { cursor = mDb.query( "preferences_storage", new String[] {"value"}, @@ -455,19 +377,14 @@ public class Storage implements SharedPreferences null, null); - if (cursor.moveToNext()) - { + if (cursor.moveToNext()) { value = cursor.getString(0); - if (K9.DEBUG) - { + if (K9.DEBUG) { Log.d(K9.LOG_TAG, "Loading key '" + key + "', value = '" + value + "'"); } } - } - finally - { - if (cursor != null) - { + } finally { + if (cursor != null) { cursor.close(); } } @@ -475,16 +392,14 @@ public class Storage implements SharedPreferences return value; } - private void writeValue(SQLiteDatabase mDb, String key, String value) - { + private void writeValue(SQLiteDatabase mDb, String key, String value) { ContentValues cv = new ContentValues(); cv.put("primkey", key); cv.put("value", value); long result = mDb.insert("preferences_storage", "primkey", cv); - if (result == -1) - { + if (result == -1) { Log.e(K9.LOG_TAG, "Error writing key '" + key + "', value = '" + value + "'"); } } diff --git a/src/com/fsck/k9/preferences/TimePickerPreference.java b/src/com/fsck/k9/preferences/TimePickerPreference.java index 36ff47744..b8824bac1 100644 --- a/src/com/fsck/k9/preferences/TimePickerPreference.java +++ b/src/com/fsck/k9/preferences/TimePickerPreference.java @@ -14,8 +14,7 @@ import android.widget.TimePicker; * A preference type that allows a user to choose a time */ public class TimePickerPreference extends DialogPreference implements - TimePicker.OnTimeChangedListener -{ + TimePicker.OnTimeChangedListener { /** * The validation expression for this preference @@ -31,8 +30,7 @@ public class TimePickerPreference extends DialogPreference implements * @param context * @param attrs */ - public TimePickerPreference(Context context, AttributeSet attrs) - { + public TimePickerPreference(Context context, AttributeSet attrs) { super(context, attrs); initialize(); } @@ -43,8 +41,7 @@ public class TimePickerPreference extends DialogPreference implements * @param defStyle */ public TimePickerPreference(Context context, AttributeSet attrs, - int defStyle) - { + int defStyle) { super(context, attrs, defStyle); initialize(); } @@ -52,8 +49,7 @@ public class TimePickerPreference extends DialogPreference implements /** * Initialize this preference */ - private void initialize() - { + private void initialize() { setPersistent(true); } @@ -63,16 +59,14 @@ public class TimePickerPreference extends DialogPreference implements * @see android.preference.DialogPreference#onCreateDialogView() */ @Override - protected View onCreateDialogView() - { + protected View onCreateDialogView() { TimePicker tp = new TimePicker(getContext()); tp.setOnTimeChangedListener(this); int h = getHour(); int m = getMinute(); - if (h >= 0 && m >= 0) - { + if (h >= 0 && m >= 0) { tp.setCurrentHour(h); tp.setCurrentMinute(m); } @@ -88,11 +82,10 @@ public class TimePickerPreference extends DialogPreference implements * .widget.TimePicker, int, int) */ @Override - public void onTimeChanged(TimePicker view, int hour, int minute) - { + public void onTimeChanged(TimePicker view, int hour, int minute) { - persistString(String.format("%02d:%02d",hour,minute)); - callChangeListener(String.format("%02d:%02d",hour,minute)); + persistString(String.format("%02d:%02d", hour, minute)); + callChangeListener(String.format("%02d:%02d", hour, minute)); } /* @@ -101,19 +94,16 @@ public class TimePickerPreference extends DialogPreference implements * @see android.preference.Preference#setDefaultValue(java.lang.Object) */ @Override - public void setDefaultValue(Object defaultValue) - { + public void setDefaultValue(Object defaultValue) { // BUG this method is never called if you use the 'android:defaultValue' attribute in your XML preference file, not sure why it isn't super.setDefaultValue(defaultValue); - if (!(defaultValue instanceof String)) - { + if (!(defaultValue instanceof String)) { return; } - if (!((String) defaultValue).matches(VALIDATION_EXPRESSION)) - { + if (!((String) defaultValue).matches(VALIDATION_EXPRESSION)) { return; } @@ -125,11 +115,9 @@ public class TimePickerPreference extends DialogPreference implements * * @return The hour value, will be 0 to 23 (inclusive) */ - private int getHour() - { + private int getHour() { String time = getPersistedString(this.defaultValue); - if (time == null || !time.matches(VALIDATION_EXPRESSION)) - { + if (time == null || !time.matches(VALIDATION_EXPRESSION)) { return -1; } @@ -141,19 +129,16 @@ public class TimePickerPreference extends DialogPreference implements * * @return the minute value, will be 0 to 59 (inclusive) */ - private int getMinute() - { + private int getMinute() { String time = getPersistedString(this.defaultValue); - if (time == null || !time.matches(VALIDATION_EXPRESSION)) - { + if (time == null || !time.matches(VALIDATION_EXPRESSION)) { return -1; } return Integer.valueOf(time.split(":")[1]); } - public String getTime() - { + public String getTime() { return getPersistedString(this.defaultValue); } diff --git a/src/com/fsck/k9/provider/AttachmentProvider.java b/src/com/fsck/k9/provider/AttachmentProvider.java index abdfac6c9..fc9c8c4f6 100644 --- a/src/com/fsck/k9/provider/AttachmentProvider.java +++ b/src/com/fsck/k9/provider/AttachmentProvider.java @@ -26,28 +26,24 @@ import java.util.List; * A simple ContentProvider that allows file access to Email's attachments.
    * Warning! We make heavy assumptions about the Uris used by the {@link LocalStore} for an {@link Account} here. */ -public class AttachmentProvider extends ContentProvider -{ +public class AttachmentProvider extends ContentProvider { public static final Uri CONTENT_URI = Uri.parse("content://com.fsck.k9.attachmentprovider"); private static final String FORMAT_RAW = "RAW"; private static final String FORMAT_THUMBNAIL = "THUMBNAIL"; - public static class AttachmentProviderColumns - { + public static class AttachmentProviderColumns { public static final String _ID = "_id"; public static final String DATA = "_data"; public static final String DISPLAY_NAME = "_display_name"; public static final String SIZE = "_size"; } - public static Uri getAttachmentUri(Account account, long id) - { + public static Uri getAttachmentUri(Account account, long id) { return getAttachmentUri(account.getUuid(), id); } - public static Uri getAttachmentThumbnailUri(Account account, long id, int width, int height) - { + public static Uri getAttachmentThumbnailUri(Account account, long id, int width, int height) { return CONTENT_URI.buildUpon() .appendPath(account.getUuid()) .appendPath(Long.toString(id)) @@ -57,8 +53,7 @@ public class AttachmentProvider extends ContentProvider .build(); } - private static Uri getAttachmentUri(String db, long id) - { + private static Uri getAttachmentUri(String db, long id) { return CONTENT_URI.buildUpon() .appendPath(db) .appendPath(Long.toString(id)) @@ -67,17 +62,14 @@ public class AttachmentProvider extends ContentProvider } @Override - public boolean onCreate() - { + public boolean onCreate() { /* * We use the cache dir as a temporary directory (since Android doesn't give us one) so * on startup we'll clean up any .tmp files from the last run. */ File[] files = getContext().getCacheDir().listFiles(); - for (File file : files) - { - if (file.getName().endsWith(".tmp")) - { + for (File file : files) { + if (file.getName().endsWith(".tmp")) { file.delete(); } } @@ -85,47 +77,36 @@ public class AttachmentProvider extends ContentProvider return true; } - public static void clear(Context lContext) - { + public static void clear(Context lContext) { /* * We use the cache dir as a temporary directory (since Android doesn't give us one) so * on startup we'll clean up any .tmp files from the last run. */ File[] files = lContext.getCacheDir().listFiles(); - for (File file : files) - { - try - { + for (File file : files) { + try { if (K9.DEBUG) Log.d(K9.LOG_TAG, "Deleting file " + file.getCanonicalPath()); - } - catch (IOException ioe) {} // No need to log failure to log + } catch (IOException ioe) {} // No need to log failure to log file.delete(); } } @Override - public String getType(Uri uri) - { + public String getType(Uri uri) { List segments = uri.getPathSegments(); String dbName = segments.get(0); String id = segments.get(1); String format = segments.get(2); - if (FORMAT_THUMBNAIL.equals(format)) - { + if (FORMAT_THUMBNAIL.equals(format)) { return "image/png"; - } - else - { + } else { final Account account = Preferences.getPreferences(getContext()).getAccount(dbName); - try - { + try { final LocalStore localStore = LocalStore.getLocalInstance(account, K9.app); return localStore.getAttachmentType(id); - } - catch (MessagingException e) - { + } catch (MessagingException e) { Log.e(K9.LOG_TAG, "Unable to retrieve LocalStore for " + account, e); return null; } @@ -133,79 +114,61 @@ public class AttachmentProvider extends ContentProvider } private File getFile(String dbName, String id) - throws FileNotFoundException - { - try - { + throws FileNotFoundException { + try { final Account account = Preferences.getPreferences(getContext()).getAccount(dbName); final File attachmentsDir; attachmentsDir = StorageManager.getInstance(K9.app).getAttachmentDirectory(dbName, account.getLocalStorageProviderId()); final File file = new File(attachmentsDir, id); - if (!file.exists()) - { + if (!file.exists()) { throw new FileNotFoundException(file.getAbsolutePath()); } return file; - } - catch (IOException e) - { + } catch (IOException e) { Log.w(K9.LOG_TAG, null, e); throw new FileNotFoundException(e.getMessage()); } } @Override - public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException - { + public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException { List segments = uri.getPathSegments(); String dbName = segments.get(0); // "/sdcard/..." is URL-encoded and makes up only 1 segment String id = segments.get(1); String format = segments.get(2); - if (FORMAT_THUMBNAIL.equals(format)) - { + if (FORMAT_THUMBNAIL.equals(format)) { int width = Integer.parseInt(segments.get(3)); int height = Integer.parseInt(segments.get(4)); String filename = "thmb_" + dbName + "_" + id + ".tmp"; int index = dbName.lastIndexOf('/'); - if (index >= 0) - { + if (index >= 0) { filename = /*dbName.substring(0, index + 1) + */"thmb_" + dbName.substring(index + 1) + "_" + id + ".tmp"; } File dir = getContext().getCacheDir(); File file = new File(dir, filename); - if (!file.exists()) - { + if (!file.exists()) { Uri attachmentUri = getAttachmentUri(dbName, Long.parseLong(id)); String type = getType(attachmentUri); - try - { + try { FileInputStream in = new FileInputStream(getFile(dbName, id)); - try - { + try { Bitmap thumbnail = createThumbnail(type, in); - if (thumbnail != null) - { + if (thumbnail != null) { thumbnail = Bitmap.createScaledBitmap(thumbnail, width, height, true); FileOutputStream out = new FileOutputStream(file); thumbnail.compress(Bitmap.CompressFormat.PNG, 100, out); out.close(); } - } - finally - { + } finally { in.close(); } - } - catch (IOException ioe) - { + } catch (IOException ioe) { return null; } } return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY); - } - else - { + } else { return ParcelFileDescriptor.open( getFile(dbName, id), ParcelFileDescriptor.MODE_READ_ONLY); @@ -213,26 +176,21 @@ public class AttachmentProvider extends ContentProvider } @Override - public int delete(Uri uri, String arg1, String[] arg2) - { + public int delete(Uri uri, String arg1, String[] arg2) { return 0; } @Override - public Uri insert(Uri uri, ContentValues values) - { + public Uri insert(Uri uri, ContentValues values) { return null; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, - String sortOrder) - { - if (projection == null) - { + String sortOrder) { + if (projection == null) { projection = - new String[] - { + new String[] { AttachmentProviderColumns._ID, AttachmentProviderColumns.DATA, }; @@ -244,43 +202,31 @@ public class AttachmentProvider extends ContentProvider // Versions of K-9 before 3.400 had a database name here, not an // account UID, so implement a bit of backcompat - if (dbName.endsWith(".db")) - { - dbName = dbName.substring(0, dbName.length()-3); + if (dbName.endsWith(".db")) { + dbName = dbName.substring(0, dbName.length() - 3); } //String format = segments.get(2); final AttachmentInfo attachmentInfo; - try - { + try { final Account account = Preferences.getPreferences(getContext()).getAccount(dbName); attachmentInfo = LocalStore.getLocalInstance(account, K9.app).getAttachmentInfo(id); - } - catch (MessagingException e) - { + } catch (MessagingException e) { Log.e(K9.LOG_TAG, "Uname to retrieve attachment info from local store for ID: " + id, e); return null; } MatrixCursor ret = new MatrixCursor(projection); Object[] values = new Object[projection.length]; - for (int i = 0, count = projection.length; i < count; i++) - { + for (int i = 0, count = projection.length; i < count; i++) { String column = projection[i]; - if (AttachmentProviderColumns._ID.equals(column)) - { + if (AttachmentProviderColumns._ID.equals(column)) { values[i] = id; - } - else if (AttachmentProviderColumns.DATA.equals(column)) - { + } else if (AttachmentProviderColumns.DATA.equals(column)) { values[i] = uri.toString(); - } - else if (AttachmentProviderColumns.DISPLAY_NAME.equals(column)) - { + } else if (AttachmentProviderColumns.DISPLAY_NAME.equals(column)) { values[i] = attachmentInfo.name; - } - else if (AttachmentProviderColumns.SIZE.equals(column)) - { + } else if (AttachmentProviderColumns.SIZE.equals(column)) { values[i] = attachmentInfo.size; } } @@ -289,29 +235,22 @@ public class AttachmentProvider extends ContentProvider } @Override - public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) - { + public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { return 0; } - private Bitmap createThumbnail(String type, InputStream data) - { - if (MimeUtility.mimeTypeMatches(type, "image/*")) - { + private Bitmap createThumbnail(String type, InputStream data) { + if (MimeUtility.mimeTypeMatches(type, "image/*")) { return createImageThumbnail(data); } return null; } - private Bitmap createImageThumbnail(InputStream data) - { - try - { + private Bitmap createImageThumbnail(InputStream data) { + try { Bitmap bitmap = BitmapFactory.decodeStream(data); return bitmap; - } - catch (OutOfMemoryError oome) - { + } catch (OutOfMemoryError oome) { /* * Improperly downloaded images, corrupt bitmaps and the like can commonly * cause OOME due to invalid allocation sizes. We're happy with a null bitmap in @@ -319,9 +258,7 @@ public class AttachmentProvider extends ContentProvider * enough. */ return null; - } - catch (Exception e) - { + } catch (Exception e) { return null; } } diff --git a/src/com/fsck/k9/provider/MessageProvider.java b/src/com/fsck/k9/provider/MessageProvider.java index dea58d60e..f2615023e 100644 --- a/src/com/fsck/k9/provider/MessageProvider.java +++ b/src/com/fsck/k9/provider/MessageProvider.java @@ -46,11 +46,9 @@ import com.fsck.k9.mail.Message; import com.fsck.k9.mail.MessagingException; import com.fsck.k9.mail.store.LocalStore; -public class MessageProvider extends ContentProvider -{ +public class MessageProvider extends ContentProvider { - public static interface MessageColumns extends BaseColumns - { + public static interface MessageColumns extends BaseColumns { /** * The number of milliseconds since Jan. 1, 1970, midnight GMT. * @@ -84,8 +82,7 @@ public class MessageProvider extends ContentProvider String INCREMENT = "id"; } - protected static interface QueryHandler - { + protected static interface QueryHandler { /** * The path this instance is able to respond to. * @@ -113,8 +110,7 @@ public class MessageProvider extends ContentProvider * @param * @param */ - public static interface FieldExtractor - { + public static interface FieldExtractor { K getField(T source); } @@ -123,83 +119,64 @@ public class MessageProvider extends ContentProvider * {@link MessageInfoHolder}. The underlying {@link Message} is expected to * be a {@link LocalStore.LocalMessage}. */ - public static class IdExtractor implements FieldExtractor - { + public static class IdExtractor implements FieldExtractor { @Override - public Long getField(final MessageInfoHolder source) - { + public Long getField(final MessageInfoHolder source) { return source.message.getId(); } } - public static class CountExtractor implements FieldExtractor - { + public static class CountExtractor implements FieldExtractor { private Integer mCount; - public CountExtractor(final int count) - { + public CountExtractor(final int count) { mCount = count; } @Override - public Integer getField(final T source) - { + public Integer getField(final T source) { return mCount; } } - public static class SubjectExtractor implements FieldExtractor - { + public static class SubjectExtractor implements FieldExtractor { @Override - public String getField(final MessageInfoHolder source) - { + public String getField(final MessageInfoHolder source) { return source.message.getSubject(); } } - public static class SendDateExtractor implements FieldExtractor - { + public static class SendDateExtractor implements FieldExtractor { @Override - public Long getField(final MessageInfoHolder source) - { + public Long getField(final MessageInfoHolder source) { return source.message.getSentDate().getTime(); } } - public static class PreviewExtractor implements FieldExtractor - { + public static class PreviewExtractor implements FieldExtractor { @Override - public String getField(final MessageInfoHolder source) - { + public String getField(final MessageInfoHolder source) { return source.message.getPreview(); } } - public static class UriExtractor implements FieldExtractor - { + public static class UriExtractor implements FieldExtractor { @Override - public String getField(final MessageInfoHolder source) - { + public String getField(final MessageInfoHolder source) { return source.uri; } } - public static class DeleteUriExtractor implements FieldExtractor - { + public static class DeleteUriExtractor implements FieldExtractor { @Override - public String getField(final MessageInfoHolder source) - { + public String getField(final MessageInfoHolder source) { final Message message = source.message; return CONTENT_URI + "/delete_message/" + message.getFolder().getAccount().getAccountNumber() + "/" + message.getFolder().getName() + "/" + message.getUid(); } } - public static class SenderExtractor implements FieldExtractor - { + public static class SenderExtractor implements FieldExtractor { @Override - public CharSequence getField(final MessageInfoHolder source) - { + public CharSequence getField(final MessageInfoHolder source) { return source.sender; } } - public static class AccountExtractor implements FieldExtractor - { + public static class AccountExtractor implements FieldExtractor { @Override - public String getField(final MessageInfoHolder source) - { + public String getField(final MessageInfoHolder source) { return source.message.getFolder().getAccount().getDescription(); } } @@ -210,12 +187,10 @@ public class MessageProvider extends ContentProvider */ @Deprecated // TODO remove - public static class IncrementExtractor implements FieldExtractor - { + public static class IncrementExtractor implements FieldExtractor { private int count = 0; @Override - public Integer getField(final MessageInfoHolder source) - { + public Integer getField(final MessageInfoHolder source) { return count++; } } @@ -223,19 +198,16 @@ public class MessageProvider extends ContentProvider /** * Retrieve messages from the integrated inbox. */ - protected class MessagesQueryHandler implements QueryHandler - { + protected class MessagesQueryHandler implements QueryHandler { @Override - public String getPath() - { + public String getPath() { return "inbox_messages/"; } @Override public Cursor query(final Uri uri, final String[] projection, final String selection, - final String[] selectionArgs, final String sortOrder) throws Exception - { + final String[] selectionArgs, final String sortOrder) throws Exception { return getMessages(projection); } @@ -246,8 +218,7 @@ public class MessageProvider extends ContentProvider * @return Never null. * @throws InterruptedException */ - protected MatrixCursor getMessages(final String[] projection) throws InterruptedException - { + protected MatrixCursor getMessages(final String[] projection) throws InterruptedException { final BlockingQueue> queue = new SynchronousQueue>(); // new code for integrated inbox, only execute this once as it will be processed afterwards via the listener @@ -264,28 +235,23 @@ public class MessageProvider extends ContentProvider new MessageList.DateComparator())); final String[] projectionToUse; - if (projection == null) - { + if (projection == null) { projectionToUse = DEFAULT_MESSAGE_PROJECTION; - } - else - { + } else { projectionToUse = projection; } - final LinkedHashMap> extractors = resolveMessageExtractors(projectionToUse, holders.size()); + final LinkedHashMap < String, FieldExtractor < MessageInfoHolder, ? >> extractors = resolveMessageExtractors(projectionToUse, holders.size()); final int fieldCount = extractors.size(); final String[] actualProjection = extractors.keySet().toArray(new String[fieldCount]); final MatrixCursor cursor = new MatrixCursor(actualProjection); - for (final MessageInfoHolder holder : holders) - { + for (final MessageInfoHolder holder : holders) { final Object[] o = new Object[fieldCount]; int i = 0; - for (final FieldExtractor extractor : extractors.values()) - { + for (final FieldExtractor < MessageInfoHolder, ? > extractor : extractors.values()) { o[i] = extractor.getField(holder); i += 1; } @@ -297,54 +263,32 @@ public class MessageProvider extends ContentProvider } // returns LinkedHashMap (rather than Map) to emphasize the inner element ordering - protected LinkedHashMap> resolveMessageExtractors(final String[] projection, int count) - { - final LinkedHashMap> extractors = new LinkedHashMap>(); + protected LinkedHashMap < String, FieldExtractor < MessageInfoHolder, ? >> resolveMessageExtractors(final String[] projection, int count) { + final LinkedHashMap < String, FieldExtractor < MessageInfoHolder, ? >> extractors = new LinkedHashMap < String, FieldExtractor < MessageInfoHolder, ? >> (); - for (final String field : projection) - { - if (extractors.containsKey(field)) - { + for (final String field : projection) { + if (extractors.containsKey(field)) { continue; } - if (MessageColumns._ID.equals(field)) - { + if (MessageColumns._ID.equals(field)) { extractors.put(field, new IdExtractor()); - } - else if (MessageColumns._COUNT.equals(field)) - { + } else if (MessageColumns._COUNT.equals(field)) { extractors.put(field, new CountExtractor(count)); - } - else if (MessageColumns.SUBJECT.equals(field)) - { + } else if (MessageColumns.SUBJECT.equals(field)) { extractors.put(field, new SubjectExtractor()); - } - else if (MessageColumns.SENDER.equals(field)) - { + } else if (MessageColumns.SENDER.equals(field)) { extractors.put(field, new SenderExtractor()); - } - else if (MessageColumns.SEND_DATE.equals(field)) - { + } else if (MessageColumns.SEND_DATE.equals(field)) { extractors.put(field, new SendDateExtractor()); - } - else if (MessageColumns.PREVIEW.equals(field)) - { + } else if (MessageColumns.PREVIEW.equals(field)) { extractors.put(field, new PreviewExtractor()); - } - else if (MessageColumns.URI.equals(field)) - { + } else if (MessageColumns.URI.equals(field)) { extractors.put(field, new UriExtractor()); - } - else if (MessageColumns.DELETE_URI.equals(field)) - { + } else if (MessageColumns.DELETE_URI.equals(field)) { extractors.put(field, new DeleteUriExtractor()); - } - else if (MessageColumns.ACCOUNT.equals(field)) - { + } else if (MessageColumns.ACCOUNT.equals(field)) { extractors.put(field, new AccountExtractor()); - } - else if (MessageColumns.INCREMENT.equals(field)) - { + } else if (MessageColumns.INCREMENT.equals(field)) { extractors.put(field, new IncrementExtractor()); } } @@ -356,30 +300,25 @@ public class MessageProvider extends ContentProvider /** * Retrieve the account list. */ - protected class AccountsQueryHandler implements QueryHandler - { + protected class AccountsQueryHandler implements QueryHandler { @Override - public String getPath() - { + public String getPath() { return "accounts"; } @Override public Cursor query(final Uri uri, String[] projection, String selection, - String[] selectionArgs, String sortOrder) throws Exception - { + String[] selectionArgs, String sortOrder) throws Exception { return getAllAccounts(); } - public Cursor getAllAccounts() - { + public Cursor getAllAccounts() { String[] projection = new String[] { "accountNumber", "accountName" }; MatrixCursor ret = new MatrixCursor(projection); - for (Account account : Preferences.getPreferences(getContext()).getAccounts()) - { + for (Account account : Preferences.getPreferences(getContext()).getAccounts()) { Object[] values = new Object[2]; values[0] = account.getAccountNumber(); values[1] = account.getDescription(); @@ -395,19 +334,16 @@ public class MessageProvider extends ContentProvider * Retrieve the unread message count for a given account specified by its * {@link Account#getAccountNumber() number}. */ - protected class UnreadQueryHandler implements QueryHandler - { + protected class UnreadQueryHandler implements QueryHandler { @Override - public String getPath() - { + public String getPath() { return "account_unread/#"; } @Override public Cursor query(final Uri uri, String[] projection, String selection, - String[] selectionArgs, String sortOrder) throws Exception - { + String[] selectionArgs, String sortOrder) throws Exception { List segments = null; int accountId = -1; segments = uri.getPathSegments(); @@ -415,8 +351,7 @@ public class MessageProvider extends ContentProvider return getAccountUnread(accountId); } - public Cursor getAccountUnread(int accountNumber) - { + public Cursor getAccountUnread(int accountNumber) { String[] projection = new String[] { "accountName", "unread" }; MatrixCursor ret = new MatrixCursor(projection); @@ -426,28 +361,20 @@ public class MessageProvider extends ContentProvider Object[] values = new Object[2]; - for (Account account : Preferences.getPreferences(getContext()).getAvailableAccounts()) - { - if (account.getAccountNumber()==accountNumber) - { + for (Account account : Preferences.getPreferences(getContext()).getAvailableAccounts()) { + if (account.getAccountNumber() == accountNumber) { myAccount = account; - try - { + try { myAccountStats = account.getStats(getContext()); values[0] = myAccount.getDescription(); - if (myAccountStats == null) - { + if (myAccountStats == null) { values[1] = 0; - } - else - { + } else { values[1] = myAccountStats.unreadMessageCount; } ret.addRow(values); - } - catch (MessagingException e) - { + } catch (MessagingException e) { Log.e(K9.LOG_TAG, e.getMessage()); values[0] = "Unknown"; values[1] = 0; @@ -463,8 +390,7 @@ public class MessageProvider extends ContentProvider * Cursor wrapper that release a semaphore on close. Close is also triggered * on {@link #finalize()}. */ - protected static class MonitoredCursor implements CrossProcessCursor - { + protected static class MonitoredCursor implements CrossProcessCursor { /** * The underlying cursor implementation that handles regular * requests @@ -485,8 +411,7 @@ public class MessageProvider extends ContentProvider * The semaphore to release on close. Never * null. */ - protected MonitoredCursor(final CrossProcessCursor cursor, final Semaphore semaphore) - { + protected MonitoredCursor(final CrossProcessCursor cursor, final Semaphore semaphore) { this.mCursor = cursor; this.mSemaphore = semaphore; } @@ -498,10 +423,8 @@ public class MessageProvider extends ContentProvider * @see android.database.Cursor#close() */ @Override - public void close() - { - if (mClosed.compareAndSet(false, true)) - { + public void close() { + if (mClosed.compareAndSet(false, true)) { mCursor.close(); Log.d(K9.LOG_TAG, "Cursor closed, null'ing & releasing semaphore"); mCursor = null; @@ -510,8 +433,7 @@ public class MessageProvider extends ContentProvider } @Override - public boolean isClosed() - { + public boolean isClosed() { return mClosed.get() || mCursor.isClosed(); } @@ -522,321 +444,274 @@ public class MessageProvider extends ContentProvider * @see java.lang.Object#finalize() */ @Override - protected void finalize() throws Throwable - { + protected void finalize() throws Throwable { close(); super.finalize(); } - protected void checkClosed() throws IllegalStateException - { - if (mClosed.get()) - { + protected void checkClosed() throws IllegalStateException { + if (mClosed.get()) { throw new IllegalStateException("Cursor was closed"); } } @Override - public void fillWindow(int pos, CursorWindow winow) - { + public void fillWindow(int pos, CursorWindow winow) { checkClosed(); mCursor.fillWindow(pos, winow); } @Override - public CursorWindow getWindow() - { + public CursorWindow getWindow() { checkClosed(); return mCursor.getWindow(); } @Override - public boolean onMove(int oldPosition, int newPosition) - { + public boolean onMove(int oldPosition, int newPosition) { checkClosed(); return mCursor.onMove(oldPosition, newPosition); } @Override - public void copyStringToBuffer(int columnIndex, CharArrayBuffer buffer) - { + public void copyStringToBuffer(int columnIndex, CharArrayBuffer buffer) { checkClosed(); mCursor.copyStringToBuffer(columnIndex, buffer); } @Override - public void deactivate() - { + public void deactivate() { checkClosed(); mCursor.deactivate(); } @Override - public byte[] getBlob(int columnIndex) - { + public byte[] getBlob(int columnIndex) { checkClosed(); return mCursor.getBlob(columnIndex); } @Override - public int getColumnCount() - { + public int getColumnCount() { checkClosed(); return mCursor.getColumnCount(); } @Override - public int getColumnIndex(String columnName) - { + public int getColumnIndex(String columnName) { checkClosed(); return mCursor.getColumnIndex(columnName); } @Override - public int getColumnIndexOrThrow(String columnName) throws IllegalArgumentException - { + public int getColumnIndexOrThrow(String columnName) throws IllegalArgumentException { checkClosed(); return mCursor.getColumnIndexOrThrow(columnName); } @Override - public String getColumnName(int columnIndex) - { + public String getColumnName(int columnIndex) { checkClosed(); return mCursor.getColumnName(columnIndex); } @Override - public String[] getColumnNames() - { + public String[] getColumnNames() { checkClosed(); return mCursor.getColumnNames(); } @Override - public int getCount() - { + public int getCount() { checkClosed(); return mCursor.getCount(); } @Override - public double getDouble(int columnIndex) - { + public double getDouble(int columnIndex) { checkClosed(); return mCursor.getDouble(columnIndex); } @Override - public Bundle getExtras() - { + public Bundle getExtras() { checkClosed(); return mCursor.getExtras(); } @Override - public float getFloat(int columnIndex) - { + public float getFloat(int columnIndex) { checkClosed(); return mCursor.getFloat(columnIndex); } @Override - public int getInt(int columnIndex) - { + public int getInt(int columnIndex) { checkClosed(); return mCursor.getInt(columnIndex); } @Override - public long getLong(int columnIndex) - { + public long getLong(int columnIndex) { checkClosed(); return mCursor.getLong(columnIndex); } @Override - public int getPosition() - { + public int getPosition() { checkClosed(); return mCursor.getPosition(); } @Override - public short getShort(int columnIndex) - { + public short getShort(int columnIndex) { checkClosed(); return mCursor.getShort(columnIndex); } @Override - public String getString(int columnIndex) - { + public String getString(int columnIndex) { checkClosed(); return mCursor.getString(columnIndex); } @Override - public boolean getWantsAllOnMoveCalls() - { + public boolean getWantsAllOnMoveCalls() { checkClosed(); return mCursor.getWantsAllOnMoveCalls(); } @Override - public boolean isAfterLast() - { + public boolean isAfterLast() { checkClosed(); return mCursor.isAfterLast(); } @Override - public boolean isBeforeFirst() - { + public boolean isBeforeFirst() { checkClosed(); return mCursor.isBeforeFirst(); } @Override - public boolean isFirst() - { + public boolean isFirst() { checkClosed(); return mCursor.isFirst(); } - public boolean isLast() - { + public boolean isLast() { checkClosed(); return mCursor.isLast(); } @Override - public boolean isNull(int columnIndex) - { + public boolean isNull(int columnIndex) { checkClosed(); return mCursor.isNull(columnIndex); } @Override - public boolean move(int offset) - { + public boolean move(int offset) { checkClosed(); return mCursor.move(offset); } @Override - public boolean moveToFirst() - { + public boolean moveToFirst() { checkClosed(); return mCursor.moveToFirst(); } @Override - public boolean moveToLast() - { + public boolean moveToLast() { checkClosed(); return mCursor.moveToLast(); } @Override - public boolean moveToNext() - { + public boolean moveToNext() { checkClosed(); return mCursor.moveToNext(); } @Override - public boolean moveToPosition(int position) - { + public boolean moveToPosition(int position) { checkClosed(); return mCursor.moveToPosition(position); } @Override - public boolean moveToPrevious() - { + public boolean moveToPrevious() { checkClosed(); return mCursor.moveToPrevious(); } @Override - public void registerContentObserver(ContentObserver observer) - { + public void registerContentObserver(ContentObserver observer) { checkClosed(); mCursor.registerContentObserver(observer); } @Override - public void registerDataSetObserver(DataSetObserver observer) - { + public void registerDataSetObserver(DataSetObserver observer) { checkClosed(); mCursor.registerDataSetObserver(observer); } @Override - public boolean requery() - { + public boolean requery() { checkClosed(); return mCursor.requery(); } @Override - public Bundle respond(Bundle extras) - { + public Bundle respond(Bundle extras) { checkClosed(); return mCursor.respond(extras); } @Override - public void setNotificationUri(ContentResolver cr, Uri uri) - { + public void setNotificationUri(ContentResolver cr, Uri uri) { checkClosed(); mCursor.setNotificationUri(cr, uri); } @Override - public void unregisterContentObserver(ContentObserver observer) - { + public void unregisterContentObserver(ContentObserver observer) { checkClosed(); mCursor.unregisterContentObserver(observer); } @Override - public void unregisterDataSetObserver(DataSetObserver observer) - { + public void unregisterDataSetObserver(DataSetObserver observer) { checkClosed(); mCursor.unregisterDataSetObserver(observer); } } - protected class ThrottlingQueryHandler implements QueryHandler - { + protected class ThrottlingQueryHandler implements QueryHandler { private QueryHandler mDelegate; - public ThrottlingQueryHandler(final QueryHandler delegate) - { + public ThrottlingQueryHandler(final QueryHandler delegate) { mDelegate = delegate; } @Override - public String getPath() - { + public String getPath() { return mDelegate.getPath(); } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, - String sortOrder) throws Exception - { + String sortOrder) throws Exception { mSemaphore.acquire(); final Cursor cursor; cursor = mDelegate.query(uri, projection, selection, selectionArgs, sortOrder); /* Android content resolvers can only process CrossProcessCursor instances */ - if (!(cursor instanceof CrossProcessCursor)) - { + if (!(cursor instanceof CrossProcessCursor)) { Log.w(K9.LOG_TAG, "Unsupported cursor, returning null: " + cursor); return null; } @@ -847,22 +722,16 @@ public class MessageProvider extends ContentProvider final WeakReference weakReference = new WeakReference(wrapped); /* make sure the cursor is closed after 30 seconds */ - mScheduledPool.schedule(new Runnable() - { + mScheduledPool.schedule(new Runnable() { @Override - public void run() - { + public void run() { final MonitoredCursor monitored = weakReference.get(); - if (monitored != null && !monitored.isClosed()) - { + if (monitored != null && !monitored.isClosed()) { Log.w(K9.LOG_TAG, "Forcibly closing remotely exposed cursor"); - try - { + try { monitored.close(); - } - catch (Exception e) - { + } catch (Exception e) { Log.w(K9.LOG_TAG, "Exception while forcibly closing cursor", e); } } @@ -878,8 +747,7 @@ public class MessageProvider extends ContentProvider * Synchronized listener used to retrieve {@link MessageInfoHolder}s using a * given {@link BlockingQueue}. */ - protected class MesssageInfoHolderRetrieverListener extends MessagingListener - { + protected class MesssageInfoHolderRetrieverListener extends MessagingListener { private final BlockingQueue> queue; private List mHolders = new ArrayList(); @@ -889,23 +757,20 @@ public class MessageProvider extends ContentProvider * Never null. The synchronized channel to use * to retrieve {@link MessageInfoHolder}s. */ - public MesssageInfoHolderRetrieverListener(final BlockingQueue> queue) - { + public MesssageInfoHolderRetrieverListener(final BlockingQueue> queue) { this.queue = queue; } @Override public void listLocalMessagesAddMessages(final Account account, - final String folderName, final List messages) - { + final String folderName, final List messages) { // cache fields into local variables for faster access on JVM without JIT final MessageHelper helper = mMessageHelper; final List holders = mHolders; final Context context = getContext(); - for (final Message message : messages) - { + for (final Message message : messages) { final MessageInfoHolder messageInfoHolder = new MessageInfoHolder(); final Folder messageFolder = message.getFolder(); final Account messageAccount = messageFolder.getAccount(); @@ -918,14 +783,10 @@ public class MessageProvider extends ContentProvider } @Override - public void searchStats(AccountStats stats) - { - try - { + public void searchStats(AccountStats stats) { + try { queue.put(mHolders); - } - catch (InterruptedException e) - { + } catch (InterruptedException e) { Log.e(K9.LOG_TAG, "Unable to return message list back to caller", e); } } @@ -935,8 +796,7 @@ public class MessageProvider extends ContentProvider public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY); - private static final String[] DEFAULT_MESSAGE_PROJECTION = new String[] - { + private static final String[] DEFAULT_MESSAGE_PROJECTION = new String[] { MessageColumns._ID, MessageColumns.SEND_DATE, MessageColumns.SENDER, @@ -971,26 +831,21 @@ public class MessageProvider extends ContentProvider ScheduledExecutorService mScheduledPool = Executors.newScheduledThreadPool(1); @Override - public boolean onCreate() - { + public boolean onCreate() { mMessageHelper = MessageHelper.getInstance(getContext()); registerQueryHandler(new ThrottlingQueryHandler(new AccountsQueryHandler())); registerQueryHandler(new ThrottlingQueryHandler(new MessagesQueryHandler())); registerQueryHandler(new ThrottlingQueryHandler(new UnreadQueryHandler())); - K9.registerApplicationAware(new K9.ApplicationAware() - { + K9.registerApplicationAware(new K9.ApplicationAware() { @Override - public void initializeComponent(final K9 application) - { + public void initializeComponent(final K9 application) { Log.v(K9.LOG_TAG, "Registering content resolver notifier"); - MessagingController.getInstance(application).addListener(new MessagingListener() - { + MessagingController.getInstance(application).addListener(new MessagingListener() { @Override - public void searchStats(final AccountStats stats) - { + public void searchStats(final AccountStats stats) { application.getContentResolver().notifyChange(CONTENT_URI, null); } }); @@ -1001,15 +856,12 @@ public class MessageProvider extends ContentProvider } @Override - public int delete(Uri uri, String selection, String[] selectionArgs) - { - if (K9.app == null) - { + public int delete(Uri uri, String selection, String[] selectionArgs) { + if (K9.app == null) { return 0; } - if (K9.DEBUG) - { + if (K9.DEBUG) { Log.v(K9.LOG_TAG, "MessageProvider/delete: " + uri); } @@ -1027,13 +879,10 @@ public class MessageProvider extends ContentProvider // get account Account myAccount = null; - for (Account account : Preferences.getPreferences(getContext()).getAccounts()) - { - if (account.getAccountNumber() == accountId) - { + for (Account account : Preferences.getPreferences(getContext()).getAccounts()) { + if (account.getAccountNumber() == accountId) { myAccount = account; - if (!account.isAvailable(getContext())) - { + if (!account.isAvailable(getContext())) { Log.w(K9.LOG_TAG, "not deleting messages because account is unavailable at the moment"); return 0; } @@ -1042,24 +891,19 @@ public class MessageProvider extends ContentProvider // get localstore parameter Message msg = null; - try - { + try { Folder lf = LocalStore.getLocalInstance(myAccount, K9.app).getFolder(folderName); int msgCount = lf.getMessageCount(); - if (K9.DEBUG) - { + if (K9.DEBUG) { Log.d(K9.LOG_TAG, "folder msg count = " + msgCount); } msg = lf.getMessage(msgUid); - } - catch (MessagingException e) - { + } catch (MessagingException e) { Log.e(K9.LOG_TAG, "Unable to retrieve message", e); } // launch command to delete the message - if ((myAccount != null) && (msg != null)) - { + if ((myAccount != null) && (msg != null)) { MessagingController.getInstance(K9.app).deleteMessages(new Message[] { msg }, null); } @@ -1068,15 +912,12 @@ public class MessageProvider extends ContentProvider } @Override - public String getType(Uri uri) - { - if (K9.app == null) - { + public String getType(Uri uri) { + if (K9.app == null) { return null; } - if (K9.DEBUG) - { + if (K9.DEBUG) { Log.v(K9.LOG_TAG, "MessageProvider/getType: " + uri); } @@ -1084,15 +925,12 @@ public class MessageProvider extends ContentProvider } @Override - public Uri insert(Uri uri, ContentValues values) - { - if (K9.app == null) - { + public Uri insert(Uri uri, ContentValues values) { + if (K9.app == null) { return null; } - if (K9.DEBUG) - { + if (K9.DEBUG) { Log.v(K9.LOG_TAG, "MessageProvider/insert: " + uri); } @@ -1101,15 +939,12 @@ public class MessageProvider extends ContentProvider @Override public Cursor query(final Uri uri, final String[] projection, final String selection, - final String[] selectionArgs, final String sortOrder) - { - if (K9.app == null) - { + final String[] selectionArgs, final String sortOrder) { + if (K9.app == null) { return null; } - if (K9.DEBUG) - { + if (K9.DEBUG) { Log.v(K9.LOG_TAG, "MessageProvider/query: " + uri); } @@ -1117,20 +952,16 @@ public class MessageProvider extends ContentProvider final int code = mUriMatcher.match(uri); - if (code == -1) - { + if (code == -1) { throw new IllegalStateException("Unrecognized URI: " + uri); } - try - { + try { // since we used the list index as the UriMatcher code, using it // back to retrieve the handler from the list final QueryHandler handler = mQueryHandlers.get(code); cursor = handler.query(uri, projection, selection, selectionArgs, sortOrder); - } - catch (Exception e) - { + } catch (Exception e) { Log.e(K9.LOG_TAG, "Unable to execute query for URI: " + uri, e); return null; } @@ -1139,15 +970,12 @@ public class MessageProvider extends ContentProvider } @Override - public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) - { - if (K9.app == null) - { + public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { + if (K9.app == null) { return 0; } - if (K9.DEBUG) - { + if (K9.DEBUG) { Log.v(K9.LOG_TAG, "MessageProvider/update: " + uri); } @@ -1163,10 +991,8 @@ public class MessageProvider extends ContentProvider * @param handler * Never null. */ - protected void registerQueryHandler(final QueryHandler handler) - { - if (mQueryHandlers.contains(handler)) - { + protected void registerQueryHandler(final QueryHandler handler) { + if (mQueryHandlers.contains(handler)) { return; } mQueryHandlers.add(handler); diff --git a/src/com/fsck/k9/remotecontrol/AccountReceiver.java b/src/com/fsck/k9/remotecontrol/AccountReceiver.java index af0675181..309dadbe0 100644 --- a/src/com/fsck/k9/remotecontrol/AccountReceiver.java +++ b/src/com/fsck/k9/remotecontrol/AccountReceiver.java @@ -6,23 +6,18 @@ import android.content.Intent; import android.os.Bundle; import android.util.Log; -class AccountReceiver extends BroadcastReceiver -{ +class AccountReceiver extends BroadcastReceiver { K9AccountReceptor receptor = null; - protected AccountReceiver(K9AccountReceptor nReceptor) - { + protected AccountReceiver(K9AccountReceptor nReceptor) { receptor = nReceptor; } @Override - public void onReceive(Context context, Intent intent) - { - if (K9RemoteControl.K9_REQUEST_ACCOUNTS.equals(intent.getAction())) - { + public void onReceive(Context context, Intent intent) { + if (K9RemoteControl.K9_REQUEST_ACCOUNTS.equals(intent.getAction())) { Bundle bundle = getResultExtras(false); - if (bundle == null) - { + if (bundle == null) { Log.w(K9RemoteControl.LOG_TAG, "Response bundle is empty"); return; } diff --git a/src/com/fsck/k9/remotecontrol/K9AccountReceptor.java b/src/com/fsck/k9/remotecontrol/K9AccountReceptor.java index 7cdf6f534..8732b83ac 100644 --- a/src/com/fsck/k9/remotecontrol/K9AccountReceptor.java +++ b/src/com/fsck/k9/remotecontrol/K9AccountReceptor.java @@ -5,7 +5,6 @@ package com.fsck.k9.remotecontrol; * The interface to implement in order to accept the arrays containing the UUIDs and descriptions of * the accounts configured in K-9 Mail. Should be passed to fetchAccounts(Context, K9AccountReceptor) */ -public interface K9AccountReceptor -{ +public interface K9AccountReceptor { public void accounts(String[] uuids, String[] descriptions); } \ No newline at end of file diff --git a/src/com/fsck/k9/remotecontrol/K9RemoteControl.java b/src/com/fsck/k9/remotecontrol/K9RemoteControl.java index 5255821f6..21122e3f0 100644 --- a/src/com/fsck/k9/remotecontrol/K9RemoteControl.java +++ b/src/com/fsck/k9/remotecontrol/K9RemoteControl.java @@ -19,8 +19,7 @@ import android.content.Intent; * @author Daniel I. Applebaum * */ -public class K9RemoteControl -{ +public class K9RemoteControl { /** * Permission that every application sending a broadcast to K-9 for Remote Control purposes should send on every broadcast. * Prevent other applications from intercepting the broadcasts. @@ -119,14 +118,12 @@ public class K9RemoteControl protected static String LOG_TAG = "K9RemoteControl"; - public static void set(Context context, Intent broadcastIntent) - { + public static void set(Context context, Intent broadcastIntent) { broadcastIntent.setAction(K9RemoteControl.K9_SET); context.sendBroadcast(broadcastIntent, K9RemoteControl.K9_REMOTE_CONTROL_PERMISSION); } - public static void fetchAccounts(Context context, K9AccountReceptor receptor) - { + public static void fetchAccounts(Context context, K9AccountReceptor receptor) { Intent accountFetchIntent = new Intent(); accountFetchIntent.setAction(K9RemoteControl.K9_REQUEST_ACCOUNTS); AccountReceiver receiver = new AccountReceiver(receptor); diff --git a/src/com/fsck/k9/service/BootReceiver.java b/src/com/fsck/k9/service/BootReceiver.java index aa216d6e4..bbe8ea734 100644 --- a/src/com/fsck/k9/service/BootReceiver.java +++ b/src/com/fsck/k9/service/BootReceiver.java @@ -14,8 +14,7 @@ import android.util.Log; import com.fsck.k9.K9; import com.fsck.k9.helper.AutoSyncHelper; -public class BootReceiver extends CoreReceiver -{ +public class BootReceiver extends CoreReceiver { public static String FIRE_INTENT = "com.fsck.k9.service.BroadcastReceiver.fireIntent"; public static String SCHEDULE_INTENT = "com.fsck.k9.service.BroadcastReceiver.scheduleIntent"; @@ -25,52 +24,36 @@ public class BootReceiver extends CoreReceiver public static String AT_TIME = "com.fsck.k9.service.BroadcastReceiver.atTime"; @Override - public Integer receive(Context context, Intent intent, Integer tmpWakeLockId) - { + public Integer receive(Context context, Intent intent, Integer tmpWakeLockId) { if (K9.DEBUG) Log.i(K9.LOG_TAG, "BootReceiver.onReceive" + intent); final String action = intent.getAction(); - if (Intent.ACTION_BOOT_COMPLETED.equals(action)) - { + if (Intent.ACTION_BOOT_COMPLETED.equals(action)) { //K9.setServicesEnabled(context, tmpWakeLockId); //tmpWakeLockId = null; - } - else if (Intent.ACTION_DEVICE_STORAGE_LOW.equals(action)) - { + } else if (Intent.ACTION_DEVICE_STORAGE_LOW.equals(action)) { MailService.actionCancel(context, tmpWakeLockId); tmpWakeLockId = null; - } - else if (Intent.ACTION_DEVICE_STORAGE_OK.equals(action)) - { + } else if (Intent.ACTION_DEVICE_STORAGE_OK.equals(action)) { MailService.actionReset(context, tmpWakeLockId); tmpWakeLockId = null; - } - else if (ConnectivityManager.CONNECTIVITY_ACTION.equals(action)) - { + } else if (ConnectivityManager.CONNECTIVITY_ACTION.equals(action)) { MailService.connectivityChange(context, tmpWakeLockId); tmpWakeLockId = null; - } - else if (AutoSyncHelper.SYNC_CONN_STATUS_CHANGE.equals(action)) - { + } else if (AutoSyncHelper.SYNC_CONN_STATUS_CHANGE.equals(action)) { K9.BACKGROUND_OPS bOps = K9.getBackgroundOps(); - if (bOps == K9.BACKGROUND_OPS.WHEN_CHECKED_AUTO_SYNC) - { + if (bOps == K9.BACKGROUND_OPS.WHEN_CHECKED_AUTO_SYNC) { MailService.actionReset(context, tmpWakeLockId); tmpWakeLockId = null; } - } - else if (ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED.equals(action)) - { + } else if (ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED.equals(action)) { K9.BACKGROUND_OPS bOps = K9.getBackgroundOps(); - if (bOps == K9.BACKGROUND_OPS.WHEN_CHECKED || bOps == K9.BACKGROUND_OPS.WHEN_CHECKED_AUTO_SYNC) - { + if (bOps == K9.BACKGROUND_OPS.WHEN_CHECKED || bOps == K9.BACKGROUND_OPS.WHEN_CHECKED_AUTO_SYNC) { MailService.actionReset(context, tmpWakeLockId); tmpWakeLockId = null; } - } - else if (FIRE_INTENT.equals(action)) - { + } else if (FIRE_INTENT.equals(action)) { Intent alarmedIntent = intent.getParcelableExtra(ALARMED_INTENT); String alarmedAction = alarmedIntent.getAction(); if (K9.DEBUG) @@ -78,21 +61,17 @@ public class BootReceiver extends CoreReceiver alarmedIntent.putExtra(WAKE_LOCK_ID, tmpWakeLockId); tmpWakeLockId = null; context.startService(alarmedIntent); - } - else if (SCHEDULE_INTENT.equals(action)) - { + } else if (SCHEDULE_INTENT.equals(action)) { long atTime = intent.getLongExtra(AT_TIME, -1); Intent alarmedIntent = intent.getParcelableExtra(ALARMED_INTENT); if (K9.DEBUG) - Log.i(K9.LOG_TAG,"BootReceiver Scheduling intent " + alarmedIntent + " for " + new Date(atTime)); + Log.i(K9.LOG_TAG, "BootReceiver Scheduling intent " + alarmedIntent + " for " + new Date(atTime)); PendingIntent pi = buildPendingIntent(context, intent); AlarmManager alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE); alarmMgr.set(AlarmManager.RTC_WAKEUP, atTime, pi); - } - else if (CANCEL_INTENT.equals(action)) - { + } else if (CANCEL_INTENT.equals(action)) { Intent alarmedIntent = intent.getParcelableExtra(ALARMED_INTENT); if (K9.DEBUG) Log.i(K9.LOG_TAG, "BootReceiver Canceling alarmedIntent " + alarmedIntent); @@ -107,8 +86,7 @@ public class BootReceiver extends CoreReceiver return tmpWakeLockId; } - private PendingIntent buildPendingIntent(Context context, Intent intent) - { + private PendingIntent buildPendingIntent(Context context, Intent intent) { Intent alarmedIntent = intent.getParcelableExtra(ALARMED_INTENT); String alarmedAction = alarmedIntent.getAction(); @@ -121,8 +99,7 @@ public class BootReceiver extends CoreReceiver return pi; } - public static void scheduleIntent(Context context, long atTime, Intent alarmedIntent) - { + public static void scheduleIntent(Context context, long atTime, Intent alarmedIntent) { if (K9.DEBUG) Log.i(K9.LOG_TAG, "BootReceiver Got request to schedule alarmedIntent " + alarmedIntent.getAction()); Intent i = new Intent(); @@ -133,8 +110,7 @@ public class BootReceiver extends CoreReceiver context.sendBroadcast(i); } - public static void cancelIntent(Context context, Intent alarmedIntent) - { + public static void cancelIntent(Context context, Intent alarmedIntent) { if (K9.DEBUG) Log.i(K9.LOG_TAG, "BootReceiver Got request to cancel alarmedIntent " + alarmedIntent.getAction()); Intent i = new Intent(); @@ -149,15 +125,12 @@ public class BootReceiver extends CoreReceiver * * @param context */ - public static void purgeSchedule(final Context context) - { + public static void purgeSchedule(final Context context) { final AlarmManager alarmService = (AlarmManager) context .getSystemService(Context.ALARM_SERVICE); - alarmService.cancel(PendingIntent.getBroadcast(context, 0, new Intent() - { + alarmService.cancel(PendingIntent.getBroadcast(context, 0, new Intent() { @Override - public boolean filterEquals(final Intent other) - { + public boolean filterEquals(final Intent other) { // we want to match all intents return true; } diff --git a/src/com/fsck/k9/service/CoreReceiver.java b/src/com/fsck/k9/service/CoreReceiver.java index ef2fc998e..9d4b4bbdc 100644 --- a/src/com/fsck/k9/service/CoreReceiver.java +++ b/src/com/fsck/k9/service/CoreReceiver.java @@ -14,8 +14,7 @@ import com.fsck.k9.K9; import com.fsck.k9.helper.power.TracingPowerManager; import com.fsck.k9.helper.power.TracingPowerManager.TracingWakeLock; -public class CoreReceiver extends BroadcastReceiver -{ +public class CoreReceiver extends BroadcastReceiver { public static String WAKE_LOCK_RELEASE = "com.fsck.k9.service.CoreReceiver.wakeLockRelease"; @@ -24,8 +23,7 @@ public class CoreReceiver extends BroadcastReceiver private static ConcurrentHashMap wakeLocks = new ConcurrentHashMap(); private static AtomicInteger wakeLockSeq = new AtomicInteger(0); - private static Integer getWakeLock(Context context) - { + private static Integer getWakeLock(Context context) { TracingPowerManager pm = TracingPowerManager.getPowerManager(context); TracingWakeLock wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "CoreReceiver getWakeLock"); wakeLock.setReferenceCounted(false); @@ -37,60 +35,45 @@ public class CoreReceiver extends BroadcastReceiver return tmpWakeLockId; } - private static void releaseWakeLock(Integer wakeLockId) - { - if (wakeLockId != null) - { + private static void releaseWakeLock(Integer wakeLockId) { + if (wakeLockId != null) { TracingWakeLock wl = wakeLocks.remove(wakeLockId); - if (wl != null) - { + if (wl != null) { if (K9.DEBUG) Log.v(K9.LOG_TAG, "CoreReceiver Releasing wakeLock " + wakeLockId); wl.release(); - } - else - { + } else { Log.w(K9.LOG_TAG, "BootReceiver WakeLock " + wakeLockId + " doesn't exist"); } } } @Override - public void onReceive(Context context, Intent intent) - { + public void onReceive(Context context, Intent intent) { Integer tmpWakeLockId = CoreReceiver.getWakeLock(context); - try - { + try { if (K9.DEBUG) Log.i(K9.LOG_TAG, "CoreReceiver.onReceive" + intent); - if (CoreReceiver.WAKE_LOCK_RELEASE.equals(intent.getAction())) - { + if (CoreReceiver.WAKE_LOCK_RELEASE.equals(intent.getAction())) { Integer wakeLockId = intent.getIntExtra(WAKE_LOCK_ID, -1); - if (wakeLockId != -1) - { + if (wakeLockId != -1) { if (K9.DEBUG) Log.v(K9.LOG_TAG, "CoreReceiver Release wakeLock " + wakeLockId); CoreReceiver.releaseWakeLock(wakeLockId); } - } - else - { + } else { tmpWakeLockId = receive(context, intent, tmpWakeLockId); } - } - finally - { + } finally { CoreReceiver.releaseWakeLock(tmpWakeLockId); } } - public Integer receive(Context context, Intent intent, Integer wakeLockId) - { + public Integer receive(Context context, Intent intent, Integer wakeLockId) { return wakeLockId; } - public static void releaseWakeLock(Context context, int wakeLockId) - { + public static void releaseWakeLock(Context context, int wakeLockId) { if (K9.DEBUG) Log.v(K9.LOG_TAG, "CoreReceiver Got request to release wakeLock " + wakeLockId); Intent i = new Intent(); diff --git a/src/com/fsck/k9/service/CoreService.java b/src/com/fsck/k9/service/CoreService.java index e1bcc3161..8e70e8ed1 100644 --- a/src/com/fsck/k9/service/CoreService.java +++ b/src/com/fsck/k9/service/CoreService.java @@ -17,8 +17,7 @@ import com.fsck.k9.controller.MessagingController; import com.fsck.k9.helper.power.TracingPowerManager; import com.fsck.k9.helper.power.TracingPowerManager.TracingWakeLock; -public abstract class CoreService extends Service -{ +public abstract class CoreService extends Service { public static String WAKE_LOCK_ID = "com.fsck.k9.service.CoreService.wakeLockId"; private static ConcurrentHashMap wakeLocks = new ConcurrentHashMap(); @@ -28,8 +27,7 @@ public abstract class CoreService extends Service private volatile boolean mShutdown = false; @Override - public void onCreate() - { + public void onCreate() { if (K9.DEBUG) Log.i(K9.LOG_TAG, "CoreService: " + className + ".onCreate()"); threadPool = Executors.newFixedThreadPool(1); // Must be single threaded @@ -37,16 +35,13 @@ public abstract class CoreService extends Service } - protected static void addWakeLockId(Intent i, Integer wakeLockId) - { - if (wakeLockId != null) - { + protected static void addWakeLockId(Intent i, Integer wakeLockId) { + if (wakeLockId != null) { i.putExtra(BootReceiver.WAKE_LOCK_ID, wakeLockId); } } - protected static void addWakeLock(Context context, Intent i) - { + protected static void addWakeLock(Context context, Intent i) { TracingPowerManager pm = TracingPowerManager.getPowerManager(context); TracingWakeLock wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "CoreService addWakeLock"); wakeLock.setReferenceCounted(false); @@ -61,8 +56,7 @@ public abstract class CoreService extends Service @Override - public void onStart(Intent intent, int startId) - { + public void onStart(Intent intent, int startId) { TracingPowerManager pm = TracingPowerManager.getPowerManager(this); TracingWakeLock wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "CoreService onStart"); wakeLock.setReferenceCounted(false); @@ -72,91 +66,69 @@ public abstract class CoreService extends Service Log.i(K9.LOG_TAG, "CoreService: " + className + ".onStart(" + intent + ", " + startId); int wakeLockId = intent.getIntExtra(BootReceiver.WAKE_LOCK_ID, -1); - if (wakeLockId != -1) - { + if (wakeLockId != -1) { BootReceiver.releaseWakeLock(this, wakeLockId); } Integer coreWakeLockId = intent.getIntExtra(WAKE_LOCK_ID, -1); - if (coreWakeLockId != null && coreWakeLockId != -1) - { + if (coreWakeLockId != null && coreWakeLockId != -1) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "Got core wake lock id " + coreWakeLockId); TracingWakeLock coreWakeLock = wakeLocks.remove(coreWakeLockId); - if (coreWakeLock != null) - { + if (coreWakeLock != null) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "Found core wake lock with id " + coreWakeLockId + ", releasing"); coreWakeLock.release(); } } - try - { + try { super.onStart(intent, startId); startService(intent, startId); - } - finally - { + } finally { wakeLock.release(); } } - public void execute(Context context, final Runnable runner, int wakeLockTime, final Integer startId) - { + public void execute(Context context, final Runnable runner, int wakeLockTime, final Integer startId) { TracingPowerManager pm = TracingPowerManager.getPowerManager(context); final TracingWakeLock wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "CoreService execute"); wakeLock.setReferenceCounted(false); wakeLock.acquire(wakeLockTime); - Runnable myRunner = new Runnable() - { - public void run() - { - try - { + Runnable myRunner = new Runnable() { + public void run() { + try { boolean oldIsSyncDisabled = MailService.isSyncDisabled(); if (K9.DEBUG) Log.d(K9.LOG_TAG, "CoreService (" + className + ") running Runnable " + runner.hashCode() + " with startId " + startId); runner.run(); - if (MailService.isSyncDisabled() != oldIsSyncDisabled) - { + if (MailService.isSyncDisabled() != oldIsSyncDisabled) { MessagingController.getInstance(getApplication()).systemStatusChanged(); } - } - finally - { + } finally { if (K9.DEBUG) Log.d(K9.LOG_TAG, "CoreService (" + className + ") completed Runnable " + runner.hashCode() + " with startId " + startId); wakeLock.release(); - if (startId != null) - { + if (startId != null) { stopSelf(startId); } } } }; - if (threadPool == null) - { + if (threadPool == null) { Log.e(K9.LOG_TAG, "CoreService.execute (" + className + ") called with no threadPool available; running Runnable " + runner.hashCode() + " in calling thread", new Throwable()); - synchronized (this) - { + synchronized (this) { myRunner.run(); } - } - else - { + } else { if (K9.DEBUG) Log.d(K9.LOG_TAG, "CoreService (" + className + ") queueing Runnable " + runner.hashCode() + " with startId " + startId); - try - { + try { threadPool.execute(myRunner); - } - catch (RejectedExecutionException e) - { - if (!mShutdown) - { + } catch (RejectedExecutionException e) { + if (!mShutdown) { throw e; } Log.i(K9.LOG_TAG, "CoreService: " + className + " is shutting down, ignoring rejected execution exception: " + e.getMessage()); @@ -167,21 +139,18 @@ public abstract class CoreService extends Service public abstract void startService(Intent intent, int startId); @Override - public IBinder onBind(Intent arg0) - { + public IBinder onBind(Intent arg0) { // TODO Auto-generated method stub return null; } @Override - public void onLowMemory() - { + public void onLowMemory() { Log.w(K9.LOG_TAG, "CoreService: " + className + ".onLowMemory() - Running low on memory"); } @Override - public void onDestroy() - { + public void onDestroy() { if (K9.DEBUG) Log.i(K9.LOG_TAG, "CoreService: " + className + ".onDestroy()"); mShutdown = true; diff --git a/src/com/fsck/k9/service/MailService.java b/src/com/fsck/k9/service/MailService.java index f84775aec..06f2f193c 100644 --- a/src/com/fsck/k9/service/MailService.java +++ b/src/com/fsck/k9/service/MailService.java @@ -23,8 +23,7 @@ import com.fsck.k9.mail.Pusher; /** */ -public class MailService extends CoreService -{ +public class MailService extends CoreService { private static final String ACTION_CHECK_MAIL = "com.fsck.k9.intent.action.MAIL_SERVICE_WAKEUP"; private static final String ACTION_RESET = "com.fsck.k9.intent.action.MAIL_SERVICE_RESET"; private static final String ACTION_RESCHEDULE_POLL = "com.fsck.k9.intent.action.MAIL_SERVICE_RESCHEDULE_POLL"; @@ -39,47 +38,40 @@ public class MailService extends CoreService private static boolean pollingRequested = false; private static boolean syncBlocked = false; - public static void actionReset(Context context, Integer wakeLockId) - { + public static void actionReset(Context context, Integer wakeLockId) { Intent i = new Intent(); i.setClass(context, MailService.class); i.setAction(MailService.ACTION_RESET); addWakeLockId(i, wakeLockId); - if (wakeLockId == null) - { + if (wakeLockId == null) { addWakeLock(context, i); } context.startService(i); } - public static void actionRestartPushers(Context context, Integer wakeLockId) - { + public static void actionRestartPushers(Context context, Integer wakeLockId) { Intent i = new Intent(); i.setClass(context, MailService.class); i.setAction(MailService.ACTION_RESTART_PUSHERS); addWakeLockId(i, wakeLockId); - if (wakeLockId == null) - { + if (wakeLockId == null) { addWakeLock(context, i); } context.startService(i); } - public static void actionReschedulePoll(Context context, Integer wakeLockId) - { + public static void actionReschedulePoll(Context context, Integer wakeLockId) { Intent i = new Intent(); i.setClass(context, MailService.class); i.setAction(MailService.ACTION_RESCHEDULE_POLL); addWakeLockId(i, wakeLockId); - if (wakeLockId == null) - { + if (wakeLockId == null) { addWakeLock(context, i); } context.startService(i); } - public static void actionCancel(Context context, Integer wakeLockId) - { + public static void actionCancel(Context context, Integer wakeLockId) { Intent i = new Intent(); i.setClass(context, MailService.class); i.setAction(MailService.ACTION_CANCEL); @@ -87,8 +79,7 @@ public class MailService extends CoreService context.startService(i); } - public static void connectivityChange(Context context, Integer wakeLockId) - { + public static void connectivityChange(Context context, Integer wakeLockId) { Intent i = new Intent(); i.setClass(context, MailService.class); i.setAction(MailService.CONNECTIVITY_CHANGE); @@ -97,37 +88,31 @@ public class MailService extends CoreService } @Override - public void onCreate() - { + public void onCreate() { super.onCreate(); if (K9.DEBUG) Log.v(K9.LOG_TAG, "***** MailService *****: onCreate"); } @Override - public void startService(Intent intent, int startId) - { + public void startService(Intent intent, int startId) { Integer startIdObj = startId; long startTime = System.currentTimeMillis(); - try - { + try { boolean oldIsSyncDisabled = isSyncDisabled(); ConnectivityManager connectivityManager = (ConnectivityManager)getApplication().getSystemService(Context.CONNECTIVITY_SERVICE); boolean doBackground = true; boolean hasConnectivity = false; - if (connectivityManager != null) - { + if (connectivityManager != null) { NetworkInfo netInfo = connectivityManager.getActiveNetworkInfo(); - if (netInfo != null) - { + if (netInfo != null) { State state = netInfo.getState(); hasConnectivity = state == State.CONNECTED; } boolean backgroundData = connectivityManager.getBackgroundDataSetting(); boolean autoSync = true; - if (AutoSyncHelper.isAvailable()) - { + if (AutoSyncHelper.isAvailable()) { autoSync = AutoSyncHelper.getMasterSyncAutomatically(); Log.i(K9.LOG_TAG, "AutoSync help is available, autoSync = " + autoSync); @@ -135,20 +120,19 @@ public class MailService extends CoreService K9.BACKGROUND_OPS bOps = K9.getBackgroundOps(); - switch (bOps) - { - case NEVER: - doBackground = false; - break; - case ALWAYS: - doBackground = true; - break; - case WHEN_CHECKED: - doBackground = backgroundData; - break; - case WHEN_CHECKED_AUTO_SYNC: - doBackground = backgroundData & autoSync; - break; + switch (bOps) { + case NEVER: + doBackground = false; + break; + case ALWAYS: + doBackground = true; + break; + case WHEN_CHECKED: + doBackground = backgroundData; + break; + case WHEN_CHECKED_AUTO_SYNC: + doBackground = backgroundData & autoSync; + break; } } @@ -160,78 +144,57 @@ public class MailService extends CoreService + "), hasConnectivity = " + hasConnectivity + ", doBackground = " + doBackground); // MessagingController.getInstance(getApplication()).addListener(mListener); - if (ACTION_CHECK_MAIL.equals(intent.getAction())) - { + if (ACTION_CHECK_MAIL.equals(intent.getAction())) { if (K9.DEBUG) Log.i(K9.LOG_TAG, "***** MailService *****: checking mail"); - if (hasConnectivity && doBackground) - { + if (hasConnectivity && doBackground) { PollService.startService(this); } reschedulePoll(hasConnectivity, doBackground, startIdObj, false); startIdObj = null; - } - else if (ACTION_CANCEL.equals(intent.getAction())) - { + } else if (ACTION_CANCEL.equals(intent.getAction())) { if (K9.DEBUG) Log.v(K9.LOG_TAG, "***** MailService *****: cancel"); cancel(); - } - else if (ACTION_RESET.equals(intent.getAction())) - { + } else if (ACTION_RESET.equals(intent.getAction())) { if (K9.DEBUG) Log.v(K9.LOG_TAG, "***** MailService *****: reschedule"); rescheduleAll(hasConnectivity, doBackground, startIdObj); startIdObj = null; - } - else if (ACTION_RESTART_PUSHERS.equals(intent.getAction())) - { + } else if (ACTION_RESTART_PUSHERS.equals(intent.getAction())) { if (K9.DEBUG) Log.v(K9.LOG_TAG, "***** MailService *****: restarting pushers"); reschedulePushers(hasConnectivity, doBackground, startIdObj); startIdObj = null; - } - else if (ACTION_RESCHEDULE_POLL.equals(intent.getAction())) - { + } else if (ACTION_RESCHEDULE_POLL.equals(intent.getAction())) { if (K9.DEBUG) Log.v(K9.LOG_TAG, "***** MailService *****: rescheduling poll"); reschedulePoll(hasConnectivity, doBackground, startIdObj, true); startIdObj = null; - } - else if (ACTION_REFRESH_PUSHERS.equals(intent.getAction())) - { - if (hasConnectivity && doBackground) - { + } else if (ACTION_REFRESH_PUSHERS.equals(intent.getAction())) { + if (hasConnectivity && doBackground) { refreshPushers(null); schedulePushers(startIdObj); startIdObj = null; } - } - else if (CONNECTIVITY_CHANGE.equals(intent.getAction())) - { + } else if (CONNECTIVITY_CHANGE.equals(intent.getAction())) { rescheduleAll(hasConnectivity, doBackground, startIdObj); startIdObj = null; if (K9.DEBUG) Log.i(K9.LOG_TAG, "Got connectivity action with hasConnectivity = " + hasConnectivity + ", doBackground = " + doBackground); + } else if (CANCEL_CONNECTIVITY_NOTICE.equals(intent.getAction())) { } - else if (CANCEL_CONNECTIVITY_NOTICE.equals(intent.getAction())) - { - } - if (isSyncDisabled() != oldIsSyncDisabled) - { + if (isSyncDisabled() != oldIsSyncDisabled) { MessagingController.getInstance(getApplication()).systemStatusChanged(); } - } - finally - { - if (startIdObj != null) - { + } finally { + if (startIdObj != null) { stopSelf(startId); } } @@ -239,8 +202,7 @@ public class MailService extends CoreService Log.i(K9.LOG_TAG, "MailService.onStart took " + (System.currentTimeMillis() - startTime) + "ms"); } - private void rescheduleAll(final boolean hasConnectivity, final boolean doBackground, final Integer startId) - { + private void rescheduleAll(final boolean hasConnectivity, final boolean doBackground, final Integer startId) { reschedulePoll(hasConnectivity, doBackground, null, true); reschedulePushers(hasConnectivity, doBackground, startId); @@ -248,16 +210,14 @@ public class MailService extends CoreService @Override - public void onDestroy() - { + public void onDestroy() { if (K9.DEBUG) Log.v(K9.LOG_TAG, "***** MailService *****: onDestroy()"); super.onDestroy(); // MessagingController.getInstance(getApplication()).removeListener(mListener); } - private void cancel() - { + private void cancel() { Intent i = new Intent(); i.setClassName(getApplication().getPackageName(), "com.fsck.k9.service.MailService"); i.setAction(ACTION_CHECK_MAIL); @@ -267,8 +227,7 @@ public class MailService extends CoreService private final static String PREVIOUS_INTERVAL = "MailService.previousInterval"; private final static String LAST_CHECK_END = "MailService.lastCheckEnd"; - public static void saveLastCheckEnd(Context context) - { + public static void saveLastCheckEnd(Context context) { long lastCheckEnd = System.currentTimeMillis(); if (K9.DEBUG) @@ -280,26 +239,20 @@ public class MailService extends CoreService editor.commit(); } - private void reschedulePoll(final boolean hasConnectivity, final boolean doBackground, Integer startId, final boolean considerLastCheckEnd) - { - if (hasConnectivity && doBackground) - { - execute(getApplication(), new Runnable() - { - public void run() - { + private void reschedulePoll(final boolean hasConnectivity, final boolean doBackground, Integer startId, final boolean considerLastCheckEnd) { + if (hasConnectivity && doBackground) { + execute(getApplication(), new Runnable() { + public void run() { int shortestInterval = -1; Preferences prefs = Preferences.getPreferences(MailService.this); SharedPreferences sPrefs = prefs.getPreferences(); int previousInterval = sPrefs.getInt(PREVIOUS_INTERVAL, -1); long lastCheckEnd = sPrefs.getLong(LAST_CHECK_END, -1); - for (Account account : prefs.getAccounts()) - { + for (Account account : prefs.getAccounts()) { if (account.getAutomaticCheckIntervalMinutes() != -1 && account.getFolderSyncMode() != FolderMode.NONE - && (account.getAutomaticCheckIntervalMinutes() < shortestInterval || shortestInterval == -1)) - { + && (account.getAutomaticCheckIntervalMinutes() < shortestInterval || shortestInterval == -1)) { shortestInterval = account.getAutomaticCheckIntervalMinutes(); } } @@ -307,16 +260,13 @@ public class MailService extends CoreService editor.putInt(PREVIOUS_INTERVAL, shortestInterval); editor.commit(); - if (shortestInterval == -1) - { + if (shortestInterval == -1) { nextCheck = -1; pollingRequested = false; if (K9.DEBUG) Log.i(K9.LOG_TAG, "No next check scheduled for package " + getApplication().getPackageName()); cancel(); - } - else - { + } else { long delay = (shortestInterval * (60 * 1000)); long base = (previousInterval == -1 || lastCheckEnd == -1 || !considerLastCheckEnd ? System.currentTimeMillis() : lastCheckEnd); long nextTime = base + delay; @@ -328,13 +278,10 @@ public class MailService extends CoreService + ", considerLastCheckEnd = " + considerLastCheckEnd); nextCheck = nextTime; pollingRequested = true; - try - { + try { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Next check for package " + getApplication().getPackageName() + " scheduled for " + new Date(nextTime)); - } - catch (Exception e) - { + } catch (Exception e) { // I once got a NullPointerException deep in new Date(); Log.e(K9.LOG_TAG, "Exception while logging", e); } @@ -348,9 +295,7 @@ public class MailService extends CoreService } } , K9.MAIL_SERVICE_WAKE_LOCK_TIMEOUT, startId); - } - else - { + } else { nextCheck = -1; if (K9.DEBUG) Log.i(K9.LOG_TAG, "No connectivity, canceling check for " + getApplication().getPackageName()); @@ -358,17 +303,13 @@ public class MailService extends CoreService } } - public static boolean isSyncDisabled() - { + public static boolean isSyncDisabled() { return syncBlocked || (!pollingRequested && !pushingRequested); } - private void stopPushers(final Integer startId) - { - execute(getApplication(), new Runnable() - { - public void run() - { + private void stopPushers(final Integer startId) { + execute(getApplication(), new Runnable() { + public void run() { MessagingController.getInstance(getApplication()).stopAllPushing(); PushService.stopService(MailService.this); } @@ -376,26 +317,19 @@ public class MailService extends CoreService , K9.MAIL_SERVICE_WAKE_LOCK_TIMEOUT, startId); } - private void reschedulePushers(final boolean hasConnectivity, final boolean doBackground, final Integer startId) - { - execute(getApplication(), new Runnable() - { - public void run() - { + private void reschedulePushers(final boolean hasConnectivity, final boolean doBackground, final Integer startId) { + execute(getApplication(), new Runnable() { + public void run() { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Rescheduling pushers"); stopPushers(null); - if (hasConnectivity && doBackground) - { + if (hasConnectivity && doBackground) { setupPushers(null); schedulePushers(startId); - } - else - { - if (K9.DEBUG) - { - Log.i(K9.LOG_TAG, "Not scheduling pushers: connectivity? "+hasConnectivity + " -- doBackground? "+doBackground); + } else { + if (K9.DEBUG) { + Log.i(K9.LOG_TAG, "Not scheduling pushers: connectivity? " + hasConnectivity + " -- doBackground? " + doBackground); } } @@ -405,28 +339,20 @@ public class MailService extends CoreService , K9.MAIL_SERVICE_WAKE_LOCK_TIMEOUT, null); } - private void setupPushers(final Integer startId) - { - execute(getApplication(), new Runnable() - { - public void run() - { + private void setupPushers(final Integer startId) { + execute(getApplication(), new Runnable() { + public void run() { boolean pushing = false; - for (Account account : Preferences.getPreferences(MailService.this).getAccounts()) - { + for (Account account : Preferences.getPreferences(MailService.this).getAccounts()) { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Setting up pushers for account " + account.getDescription()); - if (account.isAvailable(getApplicationContext())) - { + if (account.isAvailable(getApplicationContext())) { pushing |= MessagingController.getInstance(getApplication()).setupPushing(account); - } - else - { + } else { //TODO: setupPushing of unavailable accounts when they become available (sd-card inserted) } } - if (pushing) - { + if (pushing) { PushService.startService(MailService.this); } pushingRequested = pushing; @@ -435,53 +361,40 @@ public class MailService extends CoreService , K9.MAIL_SERVICE_WAKE_LOCK_TIMEOUT, startId); } - private void refreshPushers(final Integer startId) - { - execute(getApplication(), new Runnable() - { - public void run() - { - try - { + private void refreshPushers(final Integer startId) { + execute(getApplication(), new Runnable() { + public void run() { + try { long nowTime = System.currentTimeMillis(); if (K9.DEBUG) Log.i(K9.LOG_TAG, "Refreshing pushers"); Collection pushers = MessagingController.getInstance(getApplication()).getPushers(); - for (Pusher pusher : pushers) - { + for (Pusher pusher : pushers) { long lastRefresh = pusher.getLastRefresh(); int refreshInterval = pusher.getRefreshInterval(); long sinceLast = nowTime - lastRefresh; - if (sinceLast + 10000 > refreshInterval) // Add 10 seconds to keep pushers in sync, avoid drift - { - if (K9.DEBUG) - { + if (sinceLast + 10000 > refreshInterval) { // Add 10 seconds to keep pushers in sync, avoid drift + if (K9.DEBUG) { Log.d(K9.LOG_TAG, "PUSHREFRESH: refreshing lastRefresh = " + lastRefresh + ", interval = " + refreshInterval + ", nowTime = " + nowTime + ", sinceLast = " + sinceLast); } pusher.refresh(); pusher.setLastRefresh(nowTime); - } - else - { - if (K9.DEBUG) - { + } else { + if (K9.DEBUG) { Log.d(K9.LOG_TAG, "PUSHREFRESH: NOT refreshing lastRefresh = " + lastRefresh + ", interval = " + refreshInterval + ", nowTime = " + nowTime + ", sinceLast = " + sinceLast); } } } // Whenever we refresh our pushers, send any unsent messages - if (K9.DEBUG) - { + if (K9.DEBUG) { Log.d(K9.LOG_TAG, "PUSHREFRESH: trying to send mail in all folders!"); } MessagingController.getInstance(getApplication()).sendPendingMessages(null); - } - catch (Exception e) - { + } catch (Exception e) { Log.e(K9.LOG_TAG, "Exception while refreshing pushers", e); } } @@ -489,29 +402,22 @@ public class MailService extends CoreService , K9.MAIL_SERVICE_WAKE_LOCK_TIMEOUT, startId); } - private void schedulePushers(final Integer startId) - { - execute(getApplication(), new Runnable() - { - public void run() - { + private void schedulePushers(final Integer startId) { + execute(getApplication(), new Runnable() { + public void run() { int minInterval = -1; Collection pushers = MessagingController.getInstance(getApplication()).getPushers(); - for (Pusher pusher : pushers) - { + for (Pusher pusher : pushers) { int interval = pusher.getRefreshInterval(); - if (interval > 0 && (interval < minInterval || minInterval == -1)) - { + if (interval > 0 && (interval < minInterval || minInterval == -1)) { minInterval = interval; } } - if (K9.DEBUG) - { + if (K9.DEBUG) { Log.v(K9.LOG_TAG, "Pusher refresh interval = " + minInterval); } - if (minInterval > 0) - { + if (minInterval > 0) { long nextTime = System.currentTimeMillis() + minInterval; if (K9.DEBUG) Log.d(K9.LOG_TAG, "Next pusher refresh scheduled for " + new Date(nextTime)); @@ -527,13 +433,11 @@ public class MailService extends CoreService @Override - public IBinder onBind(Intent intent) - { + public IBinder onBind(Intent intent) { return null; } - public static long getNextPollTime() - { + public static long getNextPollTime() { return nextCheck; } diff --git a/src/com/fsck/k9/service/PollService.java b/src/com/fsck/k9/service/PollService.java index 45eb13d10..b8d1b60e4 100644 --- a/src/com/fsck/k9/service/PollService.java +++ b/src/com/fsck/k9/service/PollService.java @@ -13,15 +13,13 @@ import com.fsck.k9.helper.power.TracingPowerManager.TracingWakeLock; import java.util.HashMap; -public class PollService extends CoreService -{ +public class PollService extends CoreService { private static String START_SERVICE = "com.fsck.k9.service.PollService.startService"; private static String STOP_SERVICE = "com.fsck.k9.service.PollService.stopService"; private Listener mListener = new Listener(); - public static void startService(Context context) - { + public static void startService(Context context) { Intent i = new Intent(); i.setClass(context, PollService.class); i.setAction(PollService.START_SERVICE); @@ -29,8 +27,7 @@ public class PollService extends CoreService context.startService(i); } - public static void stopService(Context context) - { + public static void stopService(Context context) { Intent i = new Intent(); i.setClass(context, PollService.class); i.setAction(PollService.STOP_SERVICE); @@ -39,34 +36,27 @@ public class PollService extends CoreService } @Override - public void startService(Intent intent, int startId) - { - if (START_SERVICE.equals(intent.getAction())) - { + public void startService(Intent intent, int startId) { + if (START_SERVICE.equals(intent.getAction())) { if (K9.DEBUG) Log.i(K9.LOG_TAG, "PollService started with startId = " + startId); MessagingController controller = MessagingController.getInstance(getApplication()); Listener listener = (Listener)controller.getCheckMailListener(); - if (listener == null) - { + if (listener == null) { if (K9.DEBUG) Log.i(K9.LOG_TAG, "***** PollService *****: starting new check"); mListener.setStartId(startId); mListener.wakeLockAcquire(); controller.setCheckMailListener(mListener); controller.checkMail(this, null, false, false, mListener); - } - else - { + } else { if (K9.DEBUG) - Log.i(K9.LOG_TAG,"***** PollService *****: renewing WakeLock"); + Log.i(K9.LOG_TAG, "***** PollService *****: renewing WakeLock"); listener.setStartId(startId); listener.wakeLockAcquire(); } - } - else if (STOP_SERVICE.equals(intent.getAction())) - { + } else if (STOP_SERVICE.equals(intent.getAction())) { if (K9.DEBUG) Log.i(K9.LOG_TAG, "PollService stopping"); stopSelf(); @@ -75,21 +65,18 @@ public class PollService extends CoreService } @Override - public IBinder onBind(Intent arg0) - { + public IBinder onBind(Intent arg0) { return null; } - class Listener extends MessagingListener - { + class Listener extends MessagingListener { HashMap accountsChecked = new HashMap(); private TracingWakeLock wakeLock = null; private int startId = -1; // wakelock strategy is to be very conservative. If there is any reason to release, then release // don't want to take the chance of running wild - public synchronized void wakeLockAcquire() - { + public synchronized void wakeLockAcquire() { TracingWakeLock oldWakeLock = wakeLock; TracingPowerManager pm = TracingPowerManager.getPowerManager(PollService.this); @@ -97,29 +84,24 @@ public class PollService extends CoreService wakeLock.setReferenceCounted(false); wakeLock.acquire(K9.WAKE_LOCK_TIMEOUT); - if (oldWakeLock != null) - { + if (oldWakeLock != null) { oldWakeLock.release(); } } - public synchronized void wakeLockRelease() - { - if (wakeLock != null) - { + public synchronized void wakeLockRelease() { + if (wakeLock != null) { wakeLock.release(); wakeLock = null; } } @Override - public void checkMailStarted(Context context, Account account) - { + public void checkMailStarted(Context context, Account account) { accountsChecked.clear(); } @Override - public void checkMailFailed(Context context, Account account, String reason) - { + public void checkMailFailed(Context context, Account account, String reason) { release(); } @@ -128,21 +110,17 @@ public class PollService extends CoreService Account account, String folder, int totalMessagesInMailbox, - int numNewMessages) - { - if (account.isNotifyNewMail()) - { + int numNewMessages) { + if (account.isNotifyNewMail()) { Integer existingNewMessages = accountsChecked.get(account.getUuid()); - if (existingNewMessages == null) - { + if (existingNewMessages == null) { existingNewMessages = 0; } accountsChecked.put(account.getUuid(), existingNewMessages + numNewMessages); } } - private void release() - { + private void release() { MessagingController controller = MessagingController.getInstance(getApplication()); controller.setCheckMailListener(null); @@ -157,19 +135,16 @@ public class PollService extends CoreService } @Override - public void checkMailFinished(Context context, Account account) - { + public void checkMailFinished(Context context, Account account) { if (K9.DEBUG) Log.v(K9.LOG_TAG, "***** PollService *****: checkMailFinished"); release(); } - public int getStartId() - { + public int getStartId() { return startId; } - public void setStartId(int startId) - { + public void setStartId(int startId) { this.startId = startId; } } diff --git a/src/com/fsck/k9/service/PushService.java b/src/com/fsck/k9/service/PushService.java index 5d3c3e1ac..e773b042b 100644 --- a/src/com/fsck/k9/service/PushService.java +++ b/src/com/fsck/k9/service/PushService.java @@ -6,13 +6,11 @@ import android.os.IBinder; import android.util.Log; import com.fsck.k9.K9; -public class PushService extends CoreService -{ +public class PushService extends CoreService { private static String START_SERVICE = "com.fsck.k9.service.PushService.startService"; private static String STOP_SERVICE = "com.fsck.k9.service.PushService.stopService"; - public static void startService(Context context) - { + public static void startService(Context context) { Intent i = new Intent(); i.setClass(context, PushService.class); i.setAction(PushService.START_SERVICE); @@ -20,8 +18,7 @@ public class PushService extends CoreService context.startService(i); } - public static void stopService(Context context) - { + public static void stopService(Context context) { Intent i = new Intent(); i.setClass(context, PushService.class); i.setAction(PushService.STOP_SERVICE); @@ -30,15 +27,11 @@ public class PushService extends CoreService } @Override - public void startService(Intent intent, int startId) - { - if (START_SERVICE.equals(intent.getAction())) - { + public void startService(Intent intent, int startId) { + if (START_SERVICE.equals(intent.getAction())) { if (K9.DEBUG) Log.i(K9.LOG_TAG, "PushService started with startId = " + startId); - } - else if (STOP_SERVICE.equals(intent.getAction())) - { + } else if (STOP_SERVICE.equals(intent.getAction())) { if (K9.DEBUG) Log.i(K9.LOG_TAG, "PushService stopping with startId = " + startId); stopSelf(startId); @@ -47,8 +40,7 @@ public class PushService extends CoreService } @Override - public IBinder onBind(Intent arg0) - { + public IBinder onBind(Intent arg0) { // TODO Auto-generated method stub return null; } diff --git a/src/com/fsck/k9/service/RemoteControlReceiver.java b/src/com/fsck/k9/service/RemoteControlReceiver.java index 1ea3293ef..7843a1ac5 100644 --- a/src/com/fsck/k9/service/RemoteControlReceiver.java +++ b/src/com/fsck/k9/service/RemoteControlReceiver.java @@ -13,29 +13,22 @@ import com.fsck.k9.Preferences; import static com.fsck.k9.remotecontrol.K9RemoteControl.*; -public class RemoteControlReceiver extends CoreReceiver -{ +public class RemoteControlReceiver extends CoreReceiver { @Override - public Integer receive(Context context, Intent intent, Integer tmpWakeLockId) - { + public Integer receive(Context context, Intent intent, Integer tmpWakeLockId) { if (K9.DEBUG) Log.i(K9.LOG_TAG, "RemoteControlReceiver.onReceive" + intent); - if (K9RemoteControl.K9_SET.equals(intent.getAction())) - { + if (K9RemoteControl.K9_SET.equals(intent.getAction())) { RemoteControlService.set(context, intent, tmpWakeLockId); tmpWakeLockId = null; - } - else if (K9RemoteControl.K9_REQUEST_ACCOUNTS.equals(intent.getAction())) - { - try - { + } else if (K9RemoteControl.K9_REQUEST_ACCOUNTS.equals(intent.getAction())) { + try { Preferences preferences = Preferences.getPreferences(context); Account[] accounts = preferences.getAccounts(); String[] uuids = new String[accounts.length]; String[] descriptions = new String[accounts.length]; - for (int i = 0; i < accounts.length; i++) - { + for (int i = 0; i < accounts.length; i++) { //warning: account may not be isAvailable() Account account = accounts[i]; @@ -45,9 +38,7 @@ public class RemoteControlReceiver extends CoreReceiver Bundle bundle = getResultExtras(true); bundle.putStringArray(K9_ACCOUNT_UUIDS, uuids); bundle.putStringArray(K9_ACCOUNT_DESCRIPTIONS, descriptions); - } - catch (Exception e) - { + } catch (Exception e) { Log.e(K9.LOG_TAG, "Could not handle K9_RESPONSE_INTENT", e); } diff --git a/src/com/fsck/k9/service/RemoteControlService.java b/src/com/fsck/k9/service/RemoteControlService.java index 2c43d92b7..fd088e462 100644 --- a/src/com/fsck/k9/service/RemoteControlService.java +++ b/src/com/fsck/k9/service/RemoteControlService.java @@ -17,21 +17,18 @@ import android.content.SharedPreferences.Editor; import android.util.Log; import android.widget.Toast; -public class RemoteControlService extends CoreService -{ +public class RemoteControlService extends CoreService { private final static String RESCHEDULE_ACTION = "com.fsck.k9.service.RemoteControlService.RESCHEDULE_ACTION"; private final static String PUSH_RESTART_ACTION = "com.fsck.k9.service.RemoteControlService.PUSH_RESTART_ACTION"; private final static String SET_ACTION = "com.fsck.k9.service.RemoteControlService.SET_ACTION"; - public static void set(Context context, Intent i, Integer wakeLockId) - { + public static void set(Context context, Intent i, Integer wakeLockId) { // Intent i = new Intent(); i.setClass(context, RemoteControlService.class); i.setAction(RemoteControlService.SET_ACTION); addWakeLockId(i, wakeLockId); - if (wakeLockId == null) - { + if (wakeLockId == null) { addWakeLock(context, i); } context.startService(i); @@ -40,55 +37,41 @@ public class RemoteControlService extends CoreService public static final int REMOTE_CONTROL_SERVICE_WAKE_LOCK_TIMEOUT = 20000; @Override - public void startService(final Intent intent, final int startId) - { + public void startService(final Intent intent, final int startId) { if (K9.DEBUG) Log.i(K9.LOG_TAG, "RemoteControlService started with startId = " + startId); final Preferences preferences = Preferences.getPreferences(this); - if (RESCHEDULE_ACTION.equals(intent.getAction())) - { + if (RESCHEDULE_ACTION.equals(intent.getAction())) { if (K9.DEBUG) Log.i(K9.LOG_TAG, "RemoteControlService requesting MailService poll reschedule"); MailService.actionReschedulePoll(this, null); } - if (PUSH_RESTART_ACTION.equals(intent.getAction())) - { + if (PUSH_RESTART_ACTION.equals(intent.getAction())) { if (K9.DEBUG) Log.i(K9.LOG_TAG, "RemoteControlService requesting MailService push restart"); MailService.actionRestartPushers(this, null); - } - else if (RemoteControlService.SET_ACTION.equals(intent.getAction())) - { + } else if (RemoteControlService.SET_ACTION.equals(intent.getAction())) { if (K9.DEBUG) Log.i(K9.LOG_TAG, "RemoteControlService got request to change settings"); - execute(getApplication(), new Runnable() - { - public void run() - { - try - { + execute(getApplication(), new Runnable() { + public void run() { + try { boolean needsReschedule = false; boolean needsPushRestart = false; String uuid = intent.getStringExtra(K9_ACCOUNT_UUID); boolean allAccounts = intent.getBooleanExtra(K9_ALL_ACCOUNTS, false); - if (K9.DEBUG) - { - if (allAccounts) - { + if (K9.DEBUG) { + if (allAccounts) { Log.i(K9.LOG_TAG, "RemoteControlService changing settings for all accounts"); - } - else - { + } else { Log.i(K9.LOG_TAG, "RemoteControlService changing settings for account with UUID " + uuid); } } Account[] accounts = preferences.getAccounts(); - for (Account account : accounts) - { + for (Account account : accounts) { //warning: account may not be isAvailable() - if (allAccounts || account.getUuid().equals(uuid)) - { + if (allAccounts || account.getUuid().equals(uuid)) { if (K9.DEBUG) Log.i(K9.LOG_TAG, "RemoteControlService changing settings for account " + account.getDescription()); @@ -100,33 +83,25 @@ public class RemoteControlService extends CoreService String pollClasses = intent.getStringExtra(K9_POLL_CLASSES); String pollFrequency = intent.getStringExtra(K9_POLL_FREQUENCY); - if (notificationEnabled != null) - { + if (notificationEnabled != null) { account.setNotifyNewMail(Boolean.parseBoolean(notificationEnabled)); } - if (ringEnabled != null) - { + if (ringEnabled != null) { account.getNotificationSetting().setRing(Boolean.parseBoolean(ringEnabled)); } - if (vibrateEnabled != null) - { + if (vibrateEnabled != null) { account.getNotificationSetting().setVibrate(Boolean.parseBoolean(vibrateEnabled)); } - if (pushClasses != null) - { + if (pushClasses != null) { needsPushRestart |= account.setFolderPushMode(FolderMode.valueOf(pushClasses)); } - if (pollClasses != null) - { + if (pollClasses != null) { needsReschedule |= account.setFolderSyncMode(FolderMode.valueOf(pollClasses)); } - if (pollFrequency != null) - { + if (pollFrequency != null) { String[] allowedFrequencies = getResources().getStringArray(R.array.account_settings_check_frequency_values); - for (String allowedFrequency : allowedFrequencies) - { - if (allowedFrequency.equals(pollFrequency)) - { + for (String allowedFrequency : allowedFrequencies) { + if (allowedFrequency.equals(pollFrequency)) { Integer newInterval = Integer.parseInt(allowedFrequency); needsReschedule |= account.setAutomaticCheckIntervalMinutes(newInterval); } @@ -142,8 +117,7 @@ public class RemoteControlService extends CoreService if (K9RemoteControl.K9_BACKGROUND_OPERATIONS_ALWAYS.equals(backgroundOps) || K9RemoteControl.K9_BACKGROUND_OPERATIONS_NEVER.equals(backgroundOps) || K9RemoteControl.K9_BACKGROUND_OPERATIONS_WHEN_CHECKED.equals(backgroundOps) - || K9RemoteControl.K9_BACKGROUND_OPERATIONS_WHEN_CHECKED_AUTO_SYNC.equals(backgroundOps)) - { + || K9RemoteControl.K9_BACKGROUND_OPERATIONS_WHEN_CHECKED_AUTO_SYNC.equals(backgroundOps)) { BACKGROUND_OPS newBackgroundOps = BACKGROUND_OPS.valueOf(backgroundOps); boolean needsReset = K9.setBackgroundOps(newBackgroundOps); needsPushRestart |= needsReset; @@ -151,8 +125,7 @@ public class RemoteControlService extends CoreService } String theme = intent.getStringExtra(K9_THEME); - if (theme != null) - { + if (theme != null) { K9.setK9Theme(K9RemoteControl.K9_THEME_DARK.equals(theme) ? android.R.style.Theme : android.R.style.Theme_Light); } @@ -162,25 +135,21 @@ public class RemoteControlService extends CoreService K9.save(editor); editor.commit(); - if (needsReschedule) - { + if (needsReschedule) { Intent i = new Intent(); i.setClassName(getApplication().getPackageName(), "com.fsck.k9.service.RemoteControlService"); i.setAction(RESCHEDULE_ACTION); long nextTime = System.currentTimeMillis() + 10000; BootReceiver.scheduleIntent(RemoteControlService.this, nextTime, i); } - if (needsPushRestart) - { + if (needsPushRestart) { Intent i = new Intent(); i.setClassName(getApplication().getPackageName(), "com.fsck.k9.service.RemoteControlService"); i.setAction(PUSH_RESTART_ACTION); long nextTime = System.currentTimeMillis() + 10000; BootReceiver.scheduleIntent(RemoteControlService.this, nextTime, i); } - } - catch (Exception e) - { + } catch (Exception e) { Log.e(K9.LOG_TAG, "Could not handle K9_SET", e); Toast toast = Toast.makeText(RemoteControlService.this, e.getMessage(), Toast.LENGTH_LONG); toast.show(); diff --git a/src/com/fsck/k9/service/ShutdownReceiver.java b/src/com/fsck/k9/service/ShutdownReceiver.java index d82d7b5a3..d97745143 100644 --- a/src/com/fsck/k9/service/ShutdownReceiver.java +++ b/src/com/fsck/k9/service/ShutdownReceiver.java @@ -19,14 +19,11 @@ import com.fsck.k9.K9; * {@link Context#registerReceiver(BroadcastReceiver, android.content.IntentFilter)} *

    */ -public class ShutdownReceiver extends BroadcastReceiver -{ +public class ShutdownReceiver extends BroadcastReceiver { @Override - public void onReceive(final Context context, final Intent intent) - { - if (Intent.ACTION_SHUTDOWN.equals(intent.getAction())) - { + public void onReceive(final Context context, final Intent intent) { + if (Intent.ACTION_SHUTDOWN.equals(intent.getAction())) { Log.i(K9.LOG_TAG, "System is shutting down, releasing resources"); // prevent any scheduled intent from waking up K-9 diff --git a/src/com/fsck/k9/service/SleepService.java b/src/com/fsck/k9/service/SleepService.java index 2d90c59a6..425ee70d6 100644 --- a/src/com/fsck/k9/service/SleepService.java +++ b/src/com/fsck/k9/service/SleepService.java @@ -11,8 +11,7 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; -public class SleepService extends CoreService -{ +public class SleepService extends CoreService { private static String ALARM_FIRED = "com.fsck.k9.service.SleepService.ALARM_FIRED"; private static String LATCH_ID = "com.fsck.k9.service.SleepService.LATCH_ID_EXTRA"; @@ -22,8 +21,7 @@ public class SleepService extends CoreService private static AtomicInteger latchId = new AtomicInteger(); - public static void sleep(Context context, long sleepTime, TracingWakeLock wakeLock, long wakeLockTimeout) - { + public static void sleep(Context context, long sleepTime, TracingWakeLock wakeLock, long wakeLockTimeout) { Integer id = latchId.getAndIncrement(); if (K9.DEBUG) Log.d(K9.LOG_TAG, "SleepService Preparing CountDownLatch with id = " + id + ", thread " + Thread.currentThread().getName()); @@ -40,99 +38,72 @@ public class SleepService extends CoreService long startTime = System.currentTimeMillis(); long nextTime = startTime + sleepTime; BootReceiver.scheduleIntent(context, nextTime, i); - if (wakeLock != null) - { + if (wakeLock != null) { sleepDatum.wakeLock = wakeLock; sleepDatum.timeout = wakeLockTimeout; wakeLock.release(); } - try - { + try { boolean countedDown = latch.await(sleepTime, TimeUnit.MILLISECONDS); - if (!countedDown) - { + if (!countedDown) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "SleepService latch timed out for id = " + id + ", thread " + Thread.currentThread().getName()); } - } - catch (InterruptedException ie) - { + } catch (InterruptedException ie) { Log.e(K9.LOG_TAG, "SleepService Interrupted while awaiting latch", ie); } SleepDatum releaseDatum = sleepData.remove(id); - if (releaseDatum == null) - { - try - { + if (releaseDatum == null) { + try { if (K9.DEBUG) Log.d(K9.LOG_TAG, "SleepService waiting for reacquireLatch for id = " + id + ", thread " + Thread.currentThread().getName()); - if (!sleepDatum.reacquireLatch.await(5000, TimeUnit.MILLISECONDS)) - { + if (!sleepDatum.reacquireLatch.await(5000, TimeUnit.MILLISECONDS)) { Log.w(K9.LOG_TAG, "SleepService reacquireLatch timed out for id = " + id + ", thread " + Thread.currentThread().getName()); - } - else if (K9.DEBUG) + } else if (K9.DEBUG) Log.d(K9.LOG_TAG, "SleepService reacquireLatch finished for id = " + id + ", thread " + Thread.currentThread().getName()); - } - catch (InterruptedException ie) - { + } catch (InterruptedException ie) { Log.e(K9.LOG_TAG, "SleepService Interrupted while awaiting reacquireLatch", ie); } - } - else - { + } else { reacquireWakeLock(releaseDatum); } long endTime = System.currentTimeMillis(); long actualSleep = endTime - startTime; - if (actualSleep < sleepTime) - { + if (actualSleep < sleepTime) { Log.w(K9.LOG_TAG, "SleepService sleep time too short: requested was " + sleepTime + ", actual was " + actualSleep); - } - else - { + } else { if (K9.DEBUG) Log.d(K9.LOG_TAG, "SleepService requested sleep time was " + sleepTime + ", actual was " + actualSleep); } } - private static void endSleep(Integer id) - { - if (id != -1) - { + private static void endSleep(Integer id) { + if (id != -1) { SleepDatum sleepDatum = sleepData.remove(id); - if (sleepDatum != null) - { + if (sleepDatum != null) { CountDownLatch latch = sleepDatum.latch; - if (latch == null) - { + if (latch == null) { Log.e(K9.LOG_TAG, "SleepService No CountDownLatch available with id = " + id); - } - else - { + } else { if (K9.DEBUG) Log.d(K9.LOG_TAG, "SleepService Counting down CountDownLatch with id = " + id); latch.countDown(); } reacquireWakeLock(sleepDatum); sleepDatum.reacquireLatch.countDown(); - } - else - { + } else { if (K9.DEBUG) Log.d(K9.LOG_TAG, "SleepService Sleep for id " + id + " already finished"); } } } - private static void reacquireWakeLock(SleepDatum sleepDatum) - { + private static void reacquireWakeLock(SleepDatum sleepDatum) { TracingWakeLock wakeLock = sleepDatum.wakeLock; - if (wakeLock != null) - { - synchronized (wakeLock) - { + if (wakeLock != null) { + synchronized (wakeLock) { long timeout = sleepDatum.timeout; if (K9.DEBUG) Log.d(K9.LOG_TAG, "SleepService Acquiring wakeLock for " + timeout + "ms"); @@ -142,18 +113,15 @@ public class SleepService extends CoreService } @Override - public void startService(Intent intent, int startId) - { - if (intent.getAction().startsWith(ALARM_FIRED)) - { + public void startService(Intent intent, int startId) { + if (intent.getAction().startsWith(ALARM_FIRED)) { Integer id = intent.getIntExtra(LATCH_ID, -1); endSleep(id); } stopSelf(startId); } - private static class SleepDatum - { + private static class SleepDatum { CountDownLatch latch; TracingWakeLock wakeLock; long timeout; diff --git a/src/com/fsck/k9/service/StorageGoneReceiver.java b/src/com/fsck/k9/service/StorageGoneReceiver.java index ab7021e29..43f9e49d7 100644 --- a/src/com/fsck/k9/service/StorageGoneReceiver.java +++ b/src/com/fsck/k9/service/StorageGoneReceiver.java @@ -17,33 +17,26 @@ import com.fsck.k9.mail.store.StorageManager; * receiver to be statically defined in manifest. *

    */ -public class StorageGoneReceiver extends BroadcastReceiver -{ +public class StorageGoneReceiver extends BroadcastReceiver { @Override - public void onReceive(final Context context, final Intent intent) - { + public void onReceive(final Context context, final Intent intent) { final String action = intent.getAction(); final Uri uri = intent.getData(); - if (uri == null || uri.getPath() == null) - { + if (uri == null || uri.getPath() == null) { return; } - if (K9.DEBUG) - { + if (K9.DEBUG) { Log.v(K9.LOG_TAG, "StorageGoneReceiver: " + intent.toString()); } final String path = uri.getPath(); - if (Intent.ACTION_MEDIA_EJECT.equals(action)) - { + if (Intent.ACTION_MEDIA_EJECT.equals(action)) { StorageManager.getInstance(K9.app).onBeforeUnmount(path); - } - else if (Intent.ACTION_MEDIA_UNMOUNTED.equals(action)) - { + } else if (Intent.ACTION_MEDIA_UNMOUNTED.equals(action)) { StorageManager.getInstance(K9.app).onAfterUnmount(path); } } diff --git a/src/com/fsck/k9/service/StorageReceiver.java b/src/com/fsck/k9/service/StorageReceiver.java index 10676cf46..515750be4 100644 --- a/src/com/fsck/k9/service/StorageReceiver.java +++ b/src/com/fsck/k9/service/StorageReceiver.java @@ -12,29 +12,24 @@ import com.fsck.k9.mail.store.StorageManager; /** * That BroadcastReceiver is only interested in MOUNT events. */ -public class StorageReceiver extends BroadcastReceiver -{ +public class StorageReceiver extends BroadcastReceiver { @Override - public void onReceive(final Context context, final Intent intent) - { + public void onReceive(final Context context, final Intent intent) { final String action = intent.getAction(); final Uri uri = intent.getData(); - if (uri == null || uri.getPath() == null) - { + if (uri == null || uri.getPath() == null) { return; } - if (K9.DEBUG) - { + if (K9.DEBUG) { Log.v(K9.LOG_TAG, "StorageReceiver: " + intent.toString()); } final String path = uri.getPath(); - if (Intent.ACTION_MEDIA_MOUNTED.equals(action)) - { + if (Intent.ACTION_MEDIA_MOUNTED.equals(action)) { StorageManager.getInstance(K9.app).onMount(path, intent.getBooleanExtra("read-only", true)); } diff --git a/src/com/fsck/k9/view/AccessibleWebView.java b/src/com/fsck/k9/view/AccessibleWebView.java index ac2f92a14..7112e6dab 100644 --- a/src/com/fsck/k9/view/AccessibleWebView.java +++ b/src/com/fsck/k9/view/AccessibleWebView.java @@ -27,80 +27,66 @@ import android.widget.TextView; import com.fsck.k9.activity.AccessibleEmailContentActivity; -public class AccessibleWebView extends TextView -{ +public class AccessibleWebView extends TextView { private Context mContext; private String mHtmlSource; private WebView mDummyWebView; - public AccessibleWebView(Context context) - { + public AccessibleWebView(Context context) { super(context); init(context); } - public AccessibleWebView(Context context, AttributeSet attributes) - { + public AccessibleWebView(Context context, AttributeSet attributes) { super(context, attributes); init(context); } - private void init(Context context) - { + private void init(Context context) { mContext = context; mDummyWebView = new WebView(context); setFocusable(true); setFocusableInTouchMode(true); - setOnClickListener(new OnClickListener() - { + setOnClickListener(new OnClickListener() { @Override - public void onClick(View arg0) - { + public void onClick(View arg0) { diveIn(); } }); } - public void loadData(String data, String mimeType, String encoding) - { + public void loadData(String data, String mimeType, String encoding) { mHtmlSource = data; this.setText(Html.fromHtml(mHtmlSource, null, null)); } - public WebSettings getSettings() - { + public WebSettings getSettings() { return mDummyWebView.getSettings(); } public void loadDataWithBaseURL(String baseUrl, String data, String mimeType, String encoding, - String historyUrl) - { + String historyUrl) { mHtmlSource = data; this.setText(Html.fromHtml(mHtmlSource, null, null)); } - public boolean zoomIn() - { - if (getTextSize() < 100) - { + public boolean zoomIn() { + if (getTextSize() < 100) { setTextSize(getTextSize() + 5); return true; } return false; } - public boolean zoomOut() - { - if (getTextSize() > 5) - { + public boolean zoomOut() { + if (getTextSize() > 5) { setTextSize(getTextSize() - 5); return true; } return false; } - private void diveIn() - { + private void diveIn() { Intent i = new Intent(); i.setClass(mContext, AccessibleEmailContentActivity.class); i.putExtra("content", mHtmlSource); diff --git a/src/com/fsck/k9/view/AttachmentView.java b/src/com/fsck/k9/view/AttachmentView.java index 6400c5663..36de6172d 100644 --- a/src/com/fsck/k9/view/AttachmentView.java +++ b/src/com/fsck/k9/view/AttachmentView.java @@ -27,8 +27,7 @@ import org.apache.commons.io.IOUtils; import java.io.*; -public class AttachmentView extends FrameLayout -{ +public class AttachmentView extends FrameLayout { private Context mContext; public Button viewButton; @@ -43,40 +42,33 @@ public class AttachmentView extends FrameLayout public long size; public ImageView iconView; - public AttachmentView(Context context, AttributeSet attrs, int defStyle) - { + public AttachmentView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); mContext = context; } - public AttachmentView(Context context, AttributeSet attrs) - { + public AttachmentView(Context context, AttributeSet attrs) { super(context, attrs); mContext = context; } - public AttachmentView(Context context) - { + public AttachmentView(Context context) { super(context); mContext = context; } - public boolean populateFromPart(Part inputPart, Message message, Account account, MessagingController controller, MessagingListener listener ) - { - try - { + public boolean populateFromPart(Part inputPart, Message message, Account account, MessagingController controller, MessagingListener listener) { + try { part = (LocalAttachmentBodyPart) inputPart; contentType = MimeUtility.unfoldAndDecode(part.getContentType()); String contentDisposition = MimeUtility.unfoldAndDecode(part.getDisposition()); name = MimeUtility.getHeaderParameter(contentType, "name"); - if (name == null) - { + if (name == null) { name = MimeUtility.getHeaderParameter(contentDisposition, "filename"); } - if (name == null) - { + if (name == null) { return false; } @@ -87,8 +79,7 @@ public class AttachmentView extends FrameLayout size = Integer.parseInt(MimeUtility.getHeaderParameter(contentDisposition, "size")); contentType = part.getMimeType(); - if (MimeUtility.DEFAULT_ATTACHMENT_MIME_TYPE.equals(contentType)) - { + if (MimeUtility.DEFAULT_ATTACHMENT_MIME_TYPE.equals(contentType)) { contentType = MimeUtility.getMimeTypeByExtension(name); } TextView attachmentName = (TextView) findViewById(R.id.attachment_name); @@ -97,37 +88,30 @@ public class AttachmentView extends FrameLayout viewButton = (Button) findViewById(R.id.view); downloadButton = (Button) findViewById(R.id.download); if ((!MimeUtility.mimeTypeMatches(contentType, K9.ACCEPTABLE_ATTACHMENT_VIEW_TYPES)) - || (MimeUtility.mimeTypeMatches(contentType, K9.UNACCEPTABLE_ATTACHMENT_VIEW_TYPES))) - { + || (MimeUtility.mimeTypeMatches(contentType, K9.UNACCEPTABLE_ATTACHMENT_VIEW_TYPES))) { viewButton.setVisibility(View.GONE); } if ((!MimeUtility.mimeTypeMatches(contentType, K9.ACCEPTABLE_ATTACHMENT_DOWNLOAD_TYPES)) - || (MimeUtility.mimeTypeMatches(contentType, K9.UNACCEPTABLE_ATTACHMENT_DOWNLOAD_TYPES))) - { + || (MimeUtility.mimeTypeMatches(contentType, K9.UNACCEPTABLE_ATTACHMENT_DOWNLOAD_TYPES))) { downloadButton.setVisibility(View.GONE); } - if (size > K9.MAX_ATTACHMENT_DOWNLOAD_SIZE) - { + if (size > K9.MAX_ATTACHMENT_DOWNLOAD_SIZE) { viewButton.setVisibility(View.GONE); downloadButton.setVisibility(View.GONE); } - viewButton.setOnClickListener(new OnClickListener() - { + viewButton.setOnClickListener(new OnClickListener() { @Override - public void onClick(View v) - { + public void onClick(View v) { onViewButtonClicked(); return; } }); - downloadButton.setOnClickListener(new OnClickListener() - { + downloadButton.setOnClickListener(new OnClickListener() { @Override - public void onClick(View v) - { + public void onClick(View v) { onSaveButtonClicked(); return; } @@ -136,37 +120,29 @@ public class AttachmentView extends FrameLayout attachmentName.setText(name); attachmentInfo.setText(SizeFormatter.formatSize(mContext, size)); Bitmap previewIcon = getPreviewIcon(); - if (previewIcon != null) - { + if (previewIcon != null) { attachmentIcon.setImageBitmap(previewIcon); - } - else - { + } else { attachmentIcon.setImageResource(R.drawable.attached_image_placeholder); } } - catch (Exception e) - { - Log.e(K9.LOG_TAG, "error ",e); + catch (Exception e) { + Log.e(K9.LOG_TAG, "error ", e); } return true; } - private Bitmap getPreviewIcon() - { - try - { + private Bitmap getPreviewIcon() { + try { return BitmapFactory.decodeStream( mContext.getContentResolver().openInputStream( AttachmentProvider.getAttachmentThumbnailUri(mAccount, part.getAttachmentId(), 62, 62))); - } - catch (Exception e) - { + } catch (Exception e) { /* * We don't care what happened, we just return null for the preview icon. */ @@ -174,26 +150,21 @@ public class AttachmentView extends FrameLayout } } - private void onViewButtonClicked() - { - if (mMessage != null) - { - mController.loadAttachment( mAccount, mMessage, part, new Object[] { false, this }, mListener); + private void onViewButtonClicked() { + if (mMessage != null) { + mController.loadAttachment(mAccount, mMessage, part, new Object[] { false, this }, mListener); } } - private void onSaveButtonClicked() - { + private void onSaveButtonClicked() { saveFile(); } - public void writeFile () - { - try - { + public void writeFile() { + try { File file = Utility.createUniqueFile(Environment.getExternalStorageDirectory(), name); - Uri uri = AttachmentProvider.getAttachmentUri( mAccount, part.getAttachmentId()); + Uri uri = AttachmentProvider.getAttachmentUri(mAccount, part.getAttachmentId()); InputStream in = mContext.getContentResolver().openInputStream(uri); OutputStream out = new FileOutputStream(file); IOUtils.copy(in, out); @@ -202,17 +173,13 @@ public class AttachmentView extends FrameLayout in.close(); attachmentSaved(file.getName()); new MediaScannerNotifier(mContext, file); - } - catch (IOException ioe) - { + } catch (IOException ioe) { attachmentNotSaved(); } } - public void saveFile() - { - if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) - { + public void saveFile() { + if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { /* * Abort early if there's no place to save the attachment. We don't want to spend * the time downloading it and then abort. @@ -222,25 +189,20 @@ public class AttachmentView extends FrameLayout Toast.LENGTH_SHORT).show(); return; } - if (mMessage != null) - { - mController.loadAttachment( mAccount, mMessage, part, new Object[] {true, this}, mListener); + if (mMessage != null) { + mController.loadAttachment(mAccount, mMessage, part, new Object[] {true, this}, mListener); } } - public void showFile() - { - Uri uri = AttachmentProvider.getAttachmentUri( mAccount, part.getAttachmentId()); + public void showFile() { + Uri uri = AttachmentProvider.getAttachmentUri(mAccount, part.getAttachmentId()); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(uri); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); - try - { + try { mContext.startActivity(intent); - } - catch (Exception e) - { + } catch (Exception e) { Log.e(K9.LOG_TAG, "Could not display attachment of type " + contentType, e); Toast toast = Toast.makeText(mContext, mContext.getString(R.string.message_view_no_viewer, contentType), Toast.LENGTH_LONG); toast.show(); @@ -255,45 +217,36 @@ public class AttachmentView extends FrameLayout * attachment.viewButton.setEnabled(enabled); is called. * This method is safe to be called from the UI-thread. */ - public void checkViewable() - { - if (viewButton.getVisibility() == View.GONE) - { + public void checkViewable() { + if (viewButton.getVisibility() == View.GONE) { // nothing to do return; } - if (!viewButton.isEnabled()) - { + if (!viewButton.isEnabled()) { // nothing to do return; } - try - { - Uri uri = AttachmentProvider.getAttachmentUri( mAccount, part.getAttachmentId()); + try { + Uri uri = AttachmentProvider.getAttachmentUri(mAccount, part.getAttachmentId()); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(uri); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); - if (intent.resolveActivity(mContext.getPackageManager()) == null) - { + if (intent.resolveActivity(mContext.getPackageManager()) == null) { viewButton.setEnabled(false); } // currently we do not cache re result. - } - catch (Exception e) - { + } catch (Exception e) { Log.e(K9.LOG_TAG, "Cannot resolve activity to determine if we shall show the 'view'-button for an attachment", e); } } - public void attachmentSaved(final String filename) - { + public void attachmentSaved(final String filename) { Toast.makeText(mContext, String.format( mContext.getString(R.string.message_view_status_attachment_saved), filename), Toast.LENGTH_LONG).show(); } - public void attachmentNotSaved() - { + public void attachmentNotSaved() { Toast.makeText(mContext, mContext.getString(R.string.message_view_status_attachment_not_saved), Toast.LENGTH_LONG).show(); diff --git a/src/com/fsck/k9/view/ColorChip.java b/src/com/fsck/k9/view/ColorChip.java index a71f394ea..4bdc9e356 100644 --- a/src/com/fsck/k9/view/ColorChip.java +++ b/src/com/fsck/k9/view/ColorChip.java @@ -4,27 +4,24 @@ import android.graphics.Path; import android.graphics.drawable.ShapeDrawable; import android.graphics.drawable.shapes.PathShape; -public class ColorChip -{ +public class ColorChip { private static final Path CHIP_PATH = new Path(); - static - { + static { - CHIP_PATH.lineTo(6,0); + CHIP_PATH.lineTo(6, 0); - CHIP_PATH.cubicTo( 8f, 0f, 10f, 0f, 10f, 2f ); + CHIP_PATH.cubicTo(8f, 0f, 10f, 0f, 10f, 2f); CHIP_PATH.lineTo(10, 8); - CHIP_PATH.cubicTo( 10f, 9f, 10f, 10f, 6f, 10f ); - CHIP_PATH.lineTo(0,10); + CHIP_PATH.cubicTo(10f, 9f, 10f, 10f, 6f, 10f); + CHIP_PATH.lineTo(0, 10); CHIP_PATH.close(); } private ShapeDrawable mDrawable; - public ColorChip(int color) - { + public ColorChip(int color) { mDrawable = new ShapeDrawable(new PathShape(CHIP_PATH, 10, 10)); mDrawable.getPaint().setColor(color); @@ -32,8 +29,7 @@ public class ColorChip } - public ShapeDrawable drawable () - { + public ShapeDrawable drawable() { return mDrawable; } diff --git a/src/com/fsck/k9/view/ColorPickerBox.java b/src/com/fsck/k9/view/ColorPickerBox.java index 81f605a3b..1f6af83be 100644 --- a/src/com/fsck/k9/view/ColorPickerBox.java +++ b/src/com/fsck/k9/view/ColorPickerBox.java @@ -16,8 +16,7 @@ import android.graphics.Shader.*; import android.util.*; import android.view.*; -public class ColorPickerBox extends View -{ +public class ColorPickerBox extends View { Paint paint; Shader dalam; @@ -28,18 +27,15 @@ public class ColorPickerBox extends View float sizeUiPx; // diset di constructor float[] tmp00 = new float[3]; - public ColorPickerBox(Context context) - { + public ColorPickerBox(Context context) { this(context, null); } - public ColorPickerBox(Context context, AttributeSet attrs) - { + public ColorPickerBox(Context context, AttributeSet attrs) { this(context, attrs, 0); } - public ColorPickerBox(Context context, AttributeSet attrs, int defStyle) - { + public ColorPickerBox(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); onedp = context.getResources().getDimension(R.dimen.colorpicker_onedp); @@ -47,12 +43,10 @@ public class ColorPickerBox extends View } @Override - protected void onDraw(Canvas canvas) - { + protected void onDraw(Canvas canvas) { super.onDraw(canvas); - if (paint == null) - { + if (paint == null) { paint = new Paint(); luar = new LinearGradient(0.f, 0.f, 0.f, sizeUiPx, 0xffffffff, 0xff000000, TileMode.CLAMP); } @@ -69,8 +63,7 @@ public class ColorPickerBox extends View canvas.drawRect(0.f, 0.f, sizeUiPx, sizeUiPx, paint); } - public void setHue(float hue) - { + public void setHue(float hue) { this.hue = hue; invalidate(); } diff --git a/src/com/fsck/k9/view/MessageHeader.java b/src/com/fsck/k9/view/MessageHeader.java index abb59f0d9..462d25bf7 100644 --- a/src/com/fsck/k9/view/MessageHeader.java +++ b/src/com/fsck/k9/view/MessageHeader.java @@ -32,8 +32,7 @@ import java.util.List; import java.util.Set; import java.text.DateFormat; -public class MessageHeader extends LinearLayout -{ +public class MessageHeader extends LinearLayout { private Context mContext; private TextView mFromView; private TextView mDateView; @@ -61,20 +60,17 @@ public class MessageHeader extends LinearLayout * Pair class is only available since API Level 5, so we need * this helper class unfortunately */ - private static class HeaderEntry - { + private static class HeaderEntry { public String label; public String value; - public HeaderEntry(String label, String value) - { + public HeaderEntry(String label, String value) { this.label = label; this.value = value; } } - public MessageHeader(Context context, AttributeSet attrs) - { + public MessageHeader(Context context, AttributeSet attrs) { super(context, attrs); mContext = context; mDateFormat = DateFormatter.getDateFormat(mContext); @@ -82,8 +78,7 @@ public class MessageHeader extends LinearLayout mContacts = Contacts.getInstance(mContext); } - private void initializeLayout() - { + private void initializeLayout() { mAttachmentIcon = findViewById(R.id.attachment); mAnsweredIcon = findViewById(R.id.answered); mFromView = (TextView) findViewById(R.id.from); @@ -112,30 +107,22 @@ public class MessageHeader extends LinearLayout ((TextView) findViewById(R.id.to_label)).setTextSize(TypedValue.COMPLEX_UNIT_DIP, mFontSizes.getMessageViewTo()); ((TextView) findViewById(R.id.cc_label)).setTextSize(TypedValue.COMPLEX_UNIT_DIP, mFontSizes.getMessageViewCC()); - setOnClickListener(new OnClickListener() - { + setOnClickListener(new OnClickListener() { @Override - public void onClick(View v) - { + public void onClick(View v) { onShowAdditionalHeaders(); return; } }); - mFromView.setOnClickListener( new OnClickListener() - { + mFromView.setOnClickListener(new OnClickListener() { @Override - public void onClick(View v) - { - if (mMessage != null) - { - try - { + public void onClick(View v) { + if (mMessage != null) { + try { final Address senderEmail = mMessage.getFrom()[0]; mContacts.createContact(senderEmail); - } - catch (Exception e) - { + } catch (Exception e) { Log.e(K9.LOG_TAG, "Couldn't create contact", e); } } @@ -143,20 +130,15 @@ public class MessageHeader extends LinearLayout }); } - public void setOnFlagListener (OnClickListener listener) - { + public void setOnFlagListener(OnClickListener listener) { mFlagged.setOnClickListener(listener); } - public boolean additionalHeadersVisible() - { - if ( mAdditionalHeadersView != null && mAdditionalHeadersView.getVisibility() == View.VISIBLE ) - { + public boolean additionalHeadersVisible() { + if (mAdditionalHeadersView != null && mAdditionalHeadersView.getVisibility() == View.VISIBLE) { return true; - } - else - { + } else { return false; } } @@ -165,8 +147,7 @@ public class MessageHeader extends LinearLayout * Clear the text field for the additional headers display if they are * not shown, to save UI resources. */ - private void hideAdditionalHeaders() - { + private void hideAdditionalHeaders() { mAdditionalHeadersView.setVisibility(View.GONE); mAdditionalHeadersView.setText(""); @@ -178,22 +159,18 @@ public class MessageHeader extends LinearLayout * {@link #onShowAdditionalHeaders()} * (when switching between messages). */ - private void showAdditionalHeaders() - { + private void showAdditionalHeaders() { Integer messageToShow = null; - try - { + try { // Retrieve additional headers boolean allHeadersDownloaded = mMessage.isSet(Flag.X_GOT_ALL_HEADERS); List additionalHeaders = getAdditionalHeaders(mMessage); - if (!additionalHeaders.isEmpty()) - { + if (!additionalHeaders.isEmpty()) { // Show the additional headers that we have got. populateAdditionalHeadersView(additionalHeaders); mAdditionalHeadersView.setVisibility(View.VISIBLE); } - if (!allHeadersDownloaded) - { + if (!allHeadersDownloaded) { /* * Tell the user about the "save all headers" setting * @@ -202,20 +179,15 @@ public class MessageHeader extends LinearLayout * have not been saved in their entirety initially. */ messageToShow = R.string.message_additional_headers_not_downloaded; - } - else if (additionalHeaders.isEmpty()) - { + } else if (additionalHeaders.isEmpty()) { // All headers have been downloaded, but there are no additional headers. messageToShow = R.string.message_no_additional_headers_available; } - } - catch (MessagingException e) - { + } catch (MessagingException e) { messageToShow = R.string.message_additional_headers_retrieval_failed; } // Show a message to the user, if any - if (messageToShow != null) - { + if (messageToShow != null) { Toast toast = Toast.makeText(mContext, messageToShow, Toast.LENGTH_LONG); toast.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL, 0, 0); toast.show(); @@ -223,8 +195,7 @@ public class MessageHeader extends LinearLayout } - public void populate( final Message message, final Account account) throws MessagingException - { + public void populate(final Message message, final Account account) throws MessagingException { final Contacts contacts = K9.showContactName() ? mContacts : null; final CharSequence from = Address.toFriendly(message.getFrom(), contacts); final String date = mDateFormat.format(message.getSentDate()); @@ -237,25 +208,19 @@ public class MessageHeader extends LinearLayout initializeLayout(); String subject = message.getSubject(); - if (subject == null || subject.equals("")) - { + if (subject == null || subject.equals("")) { mSubjectView.setText(mContext.getText(R.string.general_no_subject)); - } - else - { + } else { mSubjectView.setText(subject); } mSubjectView.setTextColor(0xff000000 | defaultSubjectColor); mFromView.setText(from); - if (date != null) - { + if (date != null) { mDateView.setText(date); mDateView.setVisibility(View.VISIBLE); - } - else - { + } else { mDateView.setVisibility(View.GONE); } mTimeView.setText(time); @@ -269,28 +234,22 @@ public class MessageHeader extends LinearLayout mChip.setBackgroundDrawable(mAccount.generateColorChip().drawable()); mChip.getBackground().setAlpha(!message.isSet(Flag.SEEN) ? 255 : 127); setVisibility(View.VISIBLE); - if (mAdditionalHeadersView.getVisibility() == View.VISIBLE) - { + if (mAdditionalHeadersView.getVisibility() == View.VISIBLE) { showAdditionalHeaders(); } } - public void onShowAdditionalHeaders() - { + public void onShowAdditionalHeaders() { int currentVisibility = mAdditionalHeadersView.getVisibility(); - if (currentVisibility == View.VISIBLE) - { + if (currentVisibility == View.VISIBLE) { hideAdditionalHeaders(); - } - else - { + } else { showAdditionalHeaders(); } } private List getAdditionalHeaders(final Message message) - throws MessagingException - { + throws MessagingException { List additionalHeaders = new LinkedList(); /* * Remove "Subject" header as it is already shown in the standard @@ -299,11 +258,9 @@ public class MessageHeader extends LinearLayout */ Set headerNames = new HashSet(message.getHeaderNames()); headerNames.remove("Subject"); - for (String headerName : headerNames) - { + for (String headerName : headerNames) { String[] headerValues = message.getHeader(headerName); - for (String headerValue : headerValues) - { + for (String headerValue : headerValues) { additionalHeaders.add(new HeaderEntry(headerName, headerValue)); } } @@ -320,18 +277,13 @@ public class MessageHeader extends LinearLayout * This method is always called from within the UI thread by * {@link #showAdditionalHeaders()}. */ - private void populateAdditionalHeadersView(final List additionalHeaders) - { + private void populateAdditionalHeadersView(final List additionalHeaders) { SpannableStringBuilder sb = new SpannableStringBuilder(); boolean first = true; - for (HeaderEntry additionalHeader : additionalHeaders) - { - if (!first) - { + for (HeaderEntry additionalHeader : additionalHeaders) { + if (!first) { sb.append("\n"); - } - else - { + } else { first = false; } StyleSpan boldSpan = new StyleSpan(Typeface.BOLD); diff --git a/src/com/fsck/k9/view/MessageWebView.java b/src/com/fsck/k9/view/MessageWebView.java index 4c8f9c256..d5a45a247 100644 --- a/src/com/fsck/k9/view/MessageWebView.java +++ b/src/com/fsck/k9/view/MessageWebView.java @@ -13,8 +13,7 @@ import com.fsck.k9.R; import java.lang.reflect.Method; -public class MessageWebView extends WebView -{ +public class MessageWebView extends WebView { /** * We use WebSettings.getBlockNetworkLoads() to prevent the WebView that displays email @@ -24,18 +23,15 @@ public class MessageWebView extends WebView */ public static final Method mGetBlockNetworkLoads = K9.getMethod(WebSettings.class, "setBlockNetworkLoads"); - public MessageWebView(Context context) - { + public MessageWebView(Context context) { super(context); } - public MessageWebView(Context context, AttributeSet attrs) - { + public MessageWebView(Context context, AttributeSet attrs) { super(context, attrs); } - public MessageWebView(Context context, AttributeSet attrs, int defStyle) - { + public MessageWebView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @@ -44,23 +40,17 @@ public class MessageWebView extends WebView * network data will be blocked. * @param shouldBlockNetworkData True if network data should be blocked, false to allow network data. */ - public void blockNetworkData(final boolean shouldBlockNetworkData) - { + public void blockNetworkData(final boolean shouldBlockNetworkData) { // Sanity check to make sure we don't blow up. - if (getSettings() == null) - { + if (getSettings() == null) { return; } // Block network loads. - if (mGetBlockNetworkLoads != null) - { - try - { + if (mGetBlockNetworkLoads != null) { + try { mGetBlockNetworkLoads.invoke(getSettings(), shouldBlockNetworkData); - } - catch (Exception e) - { + } catch (Exception e) { Log.e(K9.LOG_TAG, "Error on invoking WebSettings.setBlockNetworkLoads()", e); } } @@ -75,8 +65,7 @@ public class MessageWebView extends WebView * preferences when configuring the view. This message is used to view a message and to display a message being * replied to. */ - public void configure() - { + public void configure() { this.setVerticalScrollBarEnabled(true); this.setVerticalScrollbarOverlay(true); this.setScrollBarStyle(SCROLLBARS_INSIDE_OVERLAY); @@ -90,21 +79,17 @@ public class MessageWebView extends WebView webSettings.setLoadsImagesAutomatically(true); webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH); - if (K9.zoomControlsEnabled()) - { + if (K9.zoomControlsEnabled()) { webSettings.setBuiltInZoomControls(true); } // SINGLE_COLUMN layout was broken on Android < 2.2, so we // administratively disable it if ( - ( Integer.parseInt(Build.VERSION.SDK) > 7) - && K9.mobileOptimizedLayout()) - { + (Integer.parseInt(Build.VERSION.SDK) > 7) + && K9.mobileOptimizedLayout()) { webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN); - } - else - { + } else { webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS); } @@ -119,18 +104,14 @@ public class MessageWebView extends WebView * of a WebView. */ @Override - public void emulateShiftHeld() - { - try - { + public void emulateShiftHeld() { + try { KeyEvent shiftPressEvent = new KeyEvent(0, 0, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_SHIFT_LEFT, 0, 0); shiftPressEvent.dispatch(this); Toast.makeText(getContext() , R.string.select_text_now, Toast.LENGTH_SHORT).show(); - } - catch (Exception e) - { + } catch (Exception e) { Log.e(K9.LOG_TAG, "Exception in emulateShiftHeld()", e); } } diff --git a/src/com/fsck/k9/view/ToggleScrollView.java b/src/com/fsck/k9/view/ToggleScrollView.java index 54757684b..16ee41ab1 100644 --- a/src/com/fsck/k9/view/ToggleScrollView.java +++ b/src/com/fsck/k9/view/ToggleScrollView.java @@ -6,33 +6,27 @@ import android.view.GestureDetector; import android.view.MotionEvent; import android.widget.ScrollView; -public class ToggleScrollView extends ScrollView -{ +public class ToggleScrollView extends ScrollView { private GestureDetector mDetector; private boolean mScrolling = true; - public ToggleScrollView(Context context, AttributeSet attrs) - { + public ToggleScrollView(Context context, AttributeSet attrs) { super(context, attrs); mDetector = new GestureDetector(new YScrollDetector()); } - public void setScrolling(boolean enable) - { + public void setScrolling(boolean enable) { mScrolling = enable; } @Override - public boolean onTouchEvent(MotionEvent ev) - { + public boolean onTouchEvent(MotionEvent ev) { return (mScrolling) ? super.onTouchEvent(ev) : true; } @Override - public boolean onInterceptTouchEvent(MotionEvent ev) - { - if(!mScrolling) - { + public boolean onInterceptTouchEvent(MotionEvent ev) { + if (!mScrolling) { return false; } @@ -41,8 +35,7 @@ public class ToggleScrollView extends ScrollView // http://stackoverflow.com/questions/2646028/android-horizontalscrollview-within-scrollview-touch-handling boolean result = super.onInterceptTouchEvent(ev); // Let the original ScrollView handle ACTION_DOWN so we can stop the scroll when someone touches the screen. - if (ev.getAction() == MotionEvent.ACTION_DOWN || mDetector.onTouchEvent(ev)) - { + if (ev.getAction() == MotionEvent.ACTION_DOWN || mDetector.onTouchEvent(ev)) { return result; } @@ -51,24 +44,16 @@ public class ToggleScrollView extends ScrollView // Return false if we're scrolling in the x direction. That is, decline to consume the event and // let the parent class take a stab at it. - class YScrollDetector extends GestureDetector.SimpleOnGestureListener - { + class YScrollDetector extends GestureDetector.SimpleOnGestureListener { @Override - public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) - { - try - { - if (Math.abs(distanceY) > Math.abs(distanceX)) - { + public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { + try { + if (Math.abs(distanceY) > Math.abs(distanceX)) { return true; - } - else - { + } else { return false; } - } - catch (Exception e) - { + } catch (Exception e) { // nothing } return false;