1
0
mirror of https://github.com/moparisthebest/k-9 synced 2024-11-27 11:42:16 -05:00
This commit is contained in:
danapple 2011-02-26 18:39:06 -06:00
parent 6dc94fb78e
commit ad3dd07a7a
170 changed files with 11554 additions and 21128 deletions

View File

@ -151,6 +151,11 @@
<arg path="${out-debug-package}" />
</exec>
</target>
<target name="astyle">
<exec executable="astyle" failonerror="true">
<arg line="--style=java --indent=spaces=4 --brackets=attach --convert-tabs --unpad-paren --pad-header --pad-oper --suffix=none --recursive 'src/com/fsck/k9/*.java'"/>
</exec>
</target>
<target name="help">
<!-- displays starts at col 13
@ -170,6 +175,7 @@
<echo> device.</echo>
<echo> bump-version: ant -Dversion-name=3.123</echo>
<echo> Bumps the project version to 3.123,tags and commits it</echo>
<echo> astyle: Make K-9's source look like it's supposed to</echo>
</target>
</project>

File diff suppressed because it is too large Load Diff

View File

@ -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;

View File

@ -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();

View File

@ -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);
}
}

View File

@ -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();
}
}

View File

@ -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";

View File

@ -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 <code>FontSizes</code> 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,165 +200,132 @@ 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)
{
public int getMessageViewContentAsInt() {
switch (messageViewContent) {
case SMALLEST:
return 1;
case SMALLER:
@ -377,10 +340,8 @@ public class FontSizes
}
}
public void setMessageViewContent(int size)
{
switch (size)
{
public void setMessageViewContent(int size) {
switch (size) {
case 1:
messageViewContent = TextSize.SMALLEST;
break;

View File

@ -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;
}
}

View File

@ -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<ApplicationAware> observers = new ArrayList<ApplicationAware>();
public enum BACKGROUND_OPS
{
public enum BACKGROUND_OPS {
WHEN_CHECKED, ALWAYS, NEVER, WHEN_CHECKED_AUTO_SYNC
}
@ -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<Handler> queue = new SynchronousQueue<Handler>();
// 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());
@ -460,18 +434,9 @@ public class K9 extends Application
fontSizes.save(editor);
}
@Override
public void onCreate()
{
maybeSetupStrictMode();
super.onCreate();
app = this;
galleryBuggy = checkForBuggyGallery();
Preferences prefs = Preferences.getPreferences(this);
public static void loadPrefs(Preferences prefs) {
SharedPreferences sprefs = prefs.getPreferences();
DEBUG = sprefs.getBoolean("enableDebugLogging", false);
DEBUG_SENSITIVE = sprefs.getBoolean("enableSensitiveLogging", false);
mAnimations = sprefs.getBoolean("animations", true);
@ -511,18 +476,26 @@ public class K9 extends Application
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);
}
K9.setK9Language(sprefs.getString("language", ""));
K9.setK9Theme(sprefs.getInt("theme", android.R.style.Theme_Light));
}
@Override
public void onCreate() {
maybeSetupStrictMode();
super.onCreate();
app = this;
galleryBuggy = checkForBuggyGallery();
loadPrefs(Preferences.getPreferences(this));
/*
* We have to give MimeMessage a temp directory because File.createTempFile(String, String)
* doesn't work in Android and MimeMessage does not have access to a Context.
@ -536,12 +509,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 +531,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 +541,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,20 +566,17 @@ 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);
}
@ -628,20 +589,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 +608,118 @@ public class K9 extends Application
* @param component
* Never <code>null</code>.
*/
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;
}
@ -809,29 +735,24 @@ public class K9 extends Application
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 +762,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 +938,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;
}
}

View File

@ -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
* <code>true</code> to allow ringtones, <code>false</code>
* otherwise.
*/
public synchronized void setRing(boolean ring)
{
public synchronized void setRing(boolean ring) {
mRing = ring;
}
@ -47,68 +45,55 @@ public class NotificationSetting
* @return <code>true</code> if ringtone is allowed to play,
* <code>false</code> 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,13 +107,11 @@ 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};
@ -139,8 +122,7 @@ public class NotificationSetting
long[] selectedPattern = pattern0; //default pattern
switch (pattern)
{
switch (pattern) {
case 1:
selectedPattern = pattern1;
break;
@ -159,8 +141,7 @@ public class NotificationSetting
}
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.

View File

@ -16,8 +16,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
@ -26,10 +25,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;
@ -42,12 +39,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));
@ -55,38 +50,30 @@ public class Preferences
}
}
private synchronized void loadAccounts()
{
private synchronized void loadAccounts() {
accounts = new HashMap<String, Account>();
refreshAccounts();
}
public synchronized void refreshAccounts()
{
public synchronized void refreshAccounts() {
Map<String, Account> newAccountMap = new HashMap<String, Account>();
accountsInOrder = new LinkedList<Account>();
String accountUuids = getPreferences().getString("accountUuids", null);
if ((accountUuids != null) && (accountUuids.length() != 0))
{
if ((accountUuids != null) && (accountUuids.length() != 0)) {
String[] uuids = accountUuids.split(",");
for (String uuid : uuids)
{
for (String uuid : uuids) {
Account account = accounts.get(uuid);
if (account != null)
{
if (account != null) {
newAccountMap.put(uuid, account);
accountsInOrder.add(account);
}
else
{
} else {
Account newAccount = new Account(this, uuid);
newAccountMap.put(uuid, newAccount);
accountsInOrder.add(newAccount);
}
}
}
if ((newAccount != null) && newAccount.getAccountNumber() != -1)
{
if ((newAccount != null) && newAccount.getAccountNumber() != -1) {
newAccountMap.put(newAccount.getUuid(), newAccount);
accountsInOrder.add(newAccount);
newAccount = null;
@ -100,10 +87,8 @@ 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();
}
@ -115,14 +100,11 @@ public class Preferences
* registered the method returns an empty array.
* @return all accounts with {@link Account#isAvailable(Context)}
*/
public synchronized Collection<Account> getAvailableAccounts()
{
public synchronized Collection<Account> getAvailableAccounts() {
Account[] allAccounts = getAccounts();
Collection<Account> retval = new ArrayList<Account>(accounts.size());
for (Account account : allAccounts)
{
if (account.isAvailable(mContext))
{
for (Account account : allAccounts) {
if (account.isAvailable(mContext)) {
retval.add(account);
}
}
@ -130,10 +112,8 @@ public class Preferences
return retval;
}
public synchronized Account getAccount(String uuid)
{
if (accounts == null)
{
public synchronized Account getAccount(String uuid) {
if (accounts == null) {
loadAccounts();
}
Account account = accounts.get(uuid);
@ -141,8 +121,7 @@ public class Preferences
return account;
}
public synchronized Account newAccount()
{
public synchronized Account newAccount() {
newAccount = new Account(K9.app);
accounts.put(newAccount.getUuid(), newAccount);
accountsInOrder.add(newAccount);
@ -150,14 +129,12 @@ public class Preferences
return newAccount;
}
public synchronized void deleteAccount(Account account)
{
public synchronized void deleteAccount(Account account) {
accounts.remove(account.getUuid());
accountsInOrder.remove(account);
account.delete(this);
if (newAccount == account)
{
if (newAccount == account) {
newAccount = null;
}
}
@ -167,16 +144,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<Account> accounts = getAvailableAccounts();
if (accounts.size() > 0)
{
if (accounts.size() > 0) {
defaultAccount = accounts.iterator().next();
setDefaultAccount(defaultAccount);
}
@ -185,24 +159,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;
}
}

View File

@ -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 )
{
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;
}
}

View File

@ -3,8 +3,7 @@ package com.fsck.k9;
import com.fsck.k9.mail.Flag;
public interface SearchSpecification
{
public interface SearchSpecification {
public Flag[] getRequiredFlags();

View File

@ -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<String> cleanedList = new ArrayList<String>();
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<String>(this, android.R.layout.simple_list_item_1, listItems));
}
private void addToCleanedList(ArrayList<String> cleanedList, String line)
{
if (line.length() < 80)
{
private void addToCleanedList(ArrayList<String> 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);
}
}

File diff suppressed because it is too large Load Diff

View File

@ -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;
}

View File

@ -19,34 +19,26 @@ import com.fsck.k9.preferences.StorageImporter;
* that can be moved here.
*
*/
public class AsyncUIProcessor
{
public class AsyncUIProcessor {
private final ExecutorService threadPool = Executors.newCachedThreadPool();
private Application mApplication;
private static AsyncUIProcessor inst = null;
private AsyncUIProcessor(Application application)
{
private AsyncUIProcessor(Application application) {
mApplication = application;
}
public synchronized static AsyncUIProcessor getInstance(Application application)
{
if (inst == null)
{
public synchronized static AsyncUIProcessor getInstance(Application application) {
if (inst == null) {
inst = new AsyncUIProcessor(application);
}
return inst;
}
public void exportSettings(final String uuid, final String encryptionKey, final ExportListener listener)
{
threadPool.execute(new Runnable()
{
public void exportSettings(final String uuid, final String encryptionKey, final ExportListener listener) {
threadPool.execute(new Runnable() {
@Override
public void run()
{
try
{
public void run() {
try {
// Do not store with application files. Settings exports should *not* be
// deleted when the application is uninstalled
File dir = new File(Environment.getExternalStorageDirectory() + File.separator
@ -55,13 +47,10 @@ public class AsyncUIProcessor
File file = Utility.createUniqueFile(dir, "settings.k9s");
String fileName = file.getAbsolutePath();
StorageExporter.exportPreferences(mApplication, uuid, fileName, encryptionKey);
if (listener != null)
{
if (listener != null) {
listener.exportSuccess(fileName);
}
}
catch (Exception e)
{
} catch (Exception e) {
listener.failure(e.getLocalizedMessage(), e);
}
}
@ -69,25 +58,18 @@ public class AsyncUIProcessor
);
}
public void importSettings(final String fileName, final String encryptionKey, final ImportListener listener)
{
threadPool.execute(new Runnable()
{
public void importSettings(final String fileName, final String encryptionKey, final ImportListener listener) {
threadPool.execute(new Runnable() {
@Override
public void run()
{
try
{
public void run() {
try {
int numAccounts = StorageImporter.importPreferences(mApplication, fileName, encryptionKey);
K9.setServicesEnabled(mApplication);
if (listener != null)
{
if (listener != null) {
listener.importSuccess(numAccounts);
}
}
catch (Exception e)
{
} catch (Exception e) {
listener.failure(e.getLocalizedMessage(), e);
}
}
@ -95,25 +77,18 @@ public class AsyncUIProcessor
);
}
public void importSettings(final InputStream inputStream, final String encryptionKey, final ImportListener listener)
{
threadPool.execute(new Runnable()
{
public void importSettings(final InputStream inputStream, final String encryptionKey, final ImportListener listener) {
threadPool.execute(new Runnable() {
@Override
public void run()
{
try
{
public void run() {
try {
int numAccounts = StorageImporter.importPreferences(mApplication, inputStream, encryptionKey);
K9.setServicesEnabled(mApplication);
if (listener != null)
{
if (listener != null) {
listener.importSuccess(numAccounts);
}
}
catch (Exception e)
{
} catch (Exception e) {
listener.failure(e.getLocalizedMessage(), e);
}
}

View File

@ -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<Identity> 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
* <li>Children represent {@link Identity identities} of the parent account</li>
* </ul>
*/
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();
}
}

View File

@ -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<String>(this, android.R.layout.simple_list_item_1)
{
mAdapter = new ArrayAdapter<String>(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<String>(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,10 +129,8 @@ 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)
{
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case MSG_PROGRESS:
setProgressBarIndeterminateVisibility(msg.arg1 != 0);
break;
@ -164,58 +150,48 @@ public class ChooseFolder extends K9ListActivity
}
}
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:
{
case R.id.display_1st_class: {
setDisplayMode(FolderMode.FIRST_CLASS);
return true;
}
case R.id.display_1st_and_2nd_class:
{
case R.id.display_1st_and_2nd_class: {
setDisplayMode(FolderMode.FIRST_AND_SECOND_CLASS);
return true;
}
case R.id.display_not_second_class:
{
case R.id.display_not_second_class: {
setDisplayMode(FolderMode.NOT_SECOND_CLASS);
return true;
}
case R.id.display_all:
{
case R.id.display_all: {
setDisplayMode(FolderMode.ALL);
return true;
}
@ -224,12 +200,10 @@ public class ChooseFolder extends K9ListActivity
}
}
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<String> localFolders = new ArrayList<String>();
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<String>()
{
public int compare(String aName, String bName)
{
if (K9.FOLDER_NONE.equalsIgnoreCase(aName))
{
Collections.sort(localFolders, new Comparator<String>() {
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);
}
}

View File

@ -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<String> adapter;
@ -27,8 +26,7 @@ public class ChooseIdentity extends K9ListActivity
protected List<Identity> 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();
}

View File

@ -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,8 +146,7 @@ public class ColorPickerDialog
}
@SuppressWarnings("deprecation")
protected void placeArrow()
{
protected void placeArrow() {
float y = sizeUiPx - (hue * sizeUiPx / 360.f);
if (y == sizeUiPx) y = 0.f;
@ -172,8 +156,7 @@ public class ColorPickerDialog
}
@SuppressWarnings("deprecation")
protected void placeSpyglass()
{
protected void placeSpyglass() {
float x = sat * sizeUiPx;
float y = (1.f - val) * sizeUiPx;
@ -184,16 +167,14 @@ public class ColorPickerDialog
}
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();
}
}

View File

@ -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<Identity> 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);
}

View File

@ -6,33 +6,24 @@ import android.widget.Toast;
import com.fsck.k9.Account;
import com.fsck.k9.R;
public class ExportHelper
{
public static void exportSettings(final Activity activity, final Progressable progressable, final Account account)
{
public class ExportHelper {
public static void exportSettings(final Activity activity, final Progressable progressable, final Account account) {
PasswordEntryDialog dialog = new PasswordEntryDialog(activity, activity.getString(R.string.settings_encryption_password_prompt),
new PasswordEntryDialog.PasswordEntryListener()
{
public void passwordChosen(String chosenPassword)
{
new PasswordEntryDialog.PasswordEntryListener() {
public void passwordChosen(String chosenPassword) {
String toastText = activity.getString(R.string.settings_exporting);
Toast toast = Toast.makeText(activity, toastText, Toast.LENGTH_SHORT);
toast.show();
progressable.setProgress(true);
String uuid = null;
if (account != null)
{
if (account != null) {
uuid = account.getUuid();
}
AsyncUIProcessor.getInstance(activity.getApplication()).exportSettings(uuid, chosenPassword,
new ExportListener()
{
public void failure(final String message, Exception e)
{
activity.runOnUiThread(new Runnable()
{
public void run()
{
new ExportListener() {
public void failure(final String message, Exception e) {
activity.runOnUiThread(new Runnable() {
public void run() {
progressable.setProgress(false);
String toastText = activity.getString(R.string.settings_export_failure, message);
Toast toast = Toast.makeText(activity.getApplication(), toastText, Toast.LENGTH_LONG);
@ -41,12 +32,9 @@ public class ExportHelper
});
}
public void exportSuccess(final String fileName)
{
activity.runOnUiThread(new Runnable()
{
public void run()
{
public void exportSuccess(final String fileName) {
activity.runOnUiThread(new Runnable() {
public void run() {
progressable.setProgress(false);
String toastText = activity.getString(R.string.settings_export_success, fileName);
Toast toast = Toast.makeText(activity.getApplication(), toastText, Toast.LENGTH_LONG);
@ -57,8 +45,7 @@ public class ExportHelper
});
}
public void cancel()
{
public void cancel() {
}
});
dialog.show();

View File

@ -1,7 +1,6 @@
package com.fsck.k9.activity;
public interface ExportListener
{
public interface ExportListener {
public void exportSuccess(String fileName);
public void failure(String message, Exception e);

View File

@ -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<FolderInfoHolder>
{
public class FolderInfoHolder implements Comparable<FolderInfoHolder> {
public String name;
public String displayName;
public long lastChecked;
@ -23,72 +22,56 @@ public class FolderInfoHolder implements Comparable<FolderInfoHolder>
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);
}
@ -96,12 +79,9 @@ public class FolderInfoHolder implements Comparable<FolderInfoHolder>
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<FolderInfoHolder>
}
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);
}
}

File diff suppressed because it is too large Load Diff

View File

@ -15,8 +15,7 @@ import com.fsck.k9.K9;
*
* @author Marcus@Wolschon.biz
*/
public class FolderListFilter<T> extends Filter
{
public class FolderListFilter<T> extends Filter {
/**
* ArrayAdapter that contains the list of folders displayed in the
* ListView.
@ -36,8 +35,7 @@ public class FolderListFilter<T> extends Filter
*
* @param folderNames
*/
public FolderListFilter(final ArrayAdapter<T> folderNames)
{
public FolderListFilter(final ArrayAdapter<T> folderNames) {
this.mFolders = folderNames;
}
@ -48,30 +46,24 @@ public class FolderListFilter<T> 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<T>(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<T> list = new ArrayList<T>(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<T> extends Filter
final ArrayList<T> newValues = new ArrayList<T>();
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<T> 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<T> folders = (List<T>) 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<T> extends Filter
mFolders.notifyDataSetChanged();
}
public void invalidate()
{
public void invalidate() {
mOriginalValues = null;
}
}

View File

@ -1,7 +1,6 @@
package com.fsck.k9.activity;
public interface ImportListener
{
public interface ImportListener {
public void importSuccess(int numAccounts);
public void failure(String message, Exception e);

View File

@ -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.</p>
* @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.</p>
* @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 +

View File

@ -21,23 +21,19 @@ import com.fsck.k9.K9;
import com.fsck.k9.helper.DateFormatter;
public class K9Activity extends Activity implements Progressable
{
public class K9Activity extends Activity implements Progressable {
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);
@ -48,20 +44,14 @@ public class K9Activity extends Activity implements Progressable
}
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();
@ -71,15 +61,13 @@ public class K9Activity extends Activity implements Progressable
}
@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();
}
@ -87,43 +75,35 @@ public class K9Activity extends Activity implements Progressable
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,
@ -135,27 +115,21 @@ public class K9Activity extends Activity implements Progressable
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);
}
@ -164,10 +138,8 @@ public class K9Activity extends Activity implements Progressable
}
@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);
@ -175,34 +147,26 @@ public class K9Activity extends Activity implements Progressable
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
}
}
return false;
}
}
public void setProgress(boolean progress)
{
public void setProgress(boolean progress) {
}
public void onExport(final Account account)
{
public void onExport(final Account account) {
ExportHelper.exportSettings(this, this, account);
}

View File

@ -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);
}

View File

@ -14,11 +14,9 @@ import com.fsck.k9.R;
import com.fsck.k9.controller.MessagingController;
import com.fsck.k9.helper.DateFormatter;
public class K9ListActivity extends ListActivity implements Progressable
{
public class K9ListActivity extends ListActivity implements Progressable {
@Override
public void onCreate(Bundle icicle)
{
public void onCreate(Bundle icicle) {
K9Activity.setLanguage(this, K9.getK9Language());
setTheme(K9.getK9Theme());
super.onCreate(icicle);
@ -26,8 +24,7 @@ public class K9ListActivity extends ListActivity implements Progressable
}
@Override
public void onResume()
{
public void onResume() {
super.onResume();
setupFormats();
}
@ -35,58 +32,45 @@ public class K9ListActivity extends ListActivity implements Progressable
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:
{
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_UP: {
final ListView listView = getListView();
if (K9.useVolumeKeysForListNavigationEnabled())
{
if (K9.useVolumeKeysForListNavigationEnabled()) {
int currentPosition = listView.getSelectedItemPosition();
if (currentPosition == AdapterView.INVALID_POSITION || listView.isInTouchMode())
{
if (currentPosition == AdapterView.INVALID_POSITION || listView.isInTouchMode()) {
currentPosition = listView.getFirstVisiblePosition();
}
if (currentPosition > 0)
{
if (currentPosition > 0) {
listView.setSelection(currentPosition - 1);
}
return true;
}
}
case KeyEvent.KEYCODE_VOLUME_DOWN:
{
case KeyEvent.KEYCODE_VOLUME_DOWN: {
final ListView listView = getListView();
if (K9.useVolumeKeysForListNavigationEnabled())
{
if (K9.useVolumeKeysForListNavigationEnabled()) {
int currentPosition = listView.getSelectedItemPosition();
if (currentPosition == AdapterView.INVALID_POSITION || listView.isInTouchMode())
{
if (currentPosition == AdapterView.INVALID_POSITION || listView.isInTouchMode()) {
currentPosition = listView.getFirstVisiblePosition();
}
if (currentPosition < listView.getCount())
{
if (currentPosition < listView.getCount()) {
listView.setSelection(currentPosition + 1);
}
return true;
@ -97,13 +81,10 @@ public class K9ListActivity extends ListActivity implements Progressable
}
@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;
@ -112,12 +93,10 @@ public class K9ListActivity extends ListActivity implements Progressable
return super.onKeyUp(keyCode, event);
}
public void setProgress(boolean progress)
{
public void setProgress(boolean progress) {
}
public void onExport(final Account account)
{
public void onExport(final Account account) {
ExportHelper.exportSettings(this, this, account);
}

View File

@ -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]);

View File

@ -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<Account>
{
public AccountsAdapter(Account[] accounts)
{
class AccountsAdapter extends ArrayAdapter<Account> {
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;

View File

@ -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,18 +38,15 @@ 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())
{
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());
@ -67,25 +59,21 @@ public class ManageIdentities extends ChooseIdentity
}
@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())
{
switch (item.getItemId()) {
case R.id.edit:
editItem(menuInfo.position);
break;
case R.id.up:
if (menuInfo.position > 0)
{
if (menuInfo.position > 0) {
Identity identity = identities.remove(menuInfo.position);
identities.add(menuInfo.position - 1, identity);
mIdentitiesChanged = true;
@ -94,8 +82,7 @@ public class ManageIdentities extends ChooseIdentity
break;
case R.id.down:
if (menuInfo.position < identities.size() - 1)
{
if (menuInfo.position < identities.size() - 1) {
Identity identity = identities.remove(menuInfo.position);
identities.add(menuInfo.position + 1, identity);
mIdentitiesChanged = true;
@ -109,14 +96,11 @@ public class ManageIdentities extends ChooseIdentity
refreshView();
break;
case R.id.remove:
if (identities.size() > 1)
{
if (identities.size() > 1) {
identities.remove(menuInfo.position);
mIdentitiesChanged = true;
refreshView();
}
else
{
} else {
Toast.makeText(this, getString(R.string.no_removable_identity),
Toast.LENGTH_LONG).show();
}
@ -127,8 +111,7 @@ public class ManageIdentities extends ChooseIdentity
@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()));
}

File diff suppressed because it is too large Load Diff

View File

@ -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;

File diff suppressed because it is too large Load Diff

View File

@ -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,8 +113,7 @@ public class MessageReference implements Serializable
}
@Override
public String toString()
{
public String toString() {
return "MessageReference{" +
"accountUuid='" + accountUuid + '\'' +
", folderName='" + folderName + '\'' +

File diff suppressed because it is too large Load Diff

View File

@ -13,50 +13,40 @@ import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class PasswordEntryDialog
{
public interface PasswordEntryListener
{
public class PasswordEntryDialog {
public interface PasswordEntryListener {
void passwordChosen(String chosenPassword);
void cancel();
}
PasswordEntryListener listener;
private EditText passwordView;
AlertDialog dialog;
public PasswordEntryDialog(Context context, String headerText, PasswordEntryListener listener )
{
public PasswordEntryDialog(Context context, String headerText, PasswordEntryListener listener) {
this.listener = listener;
View view = LayoutInflater.from(context).inflate(R.layout.password_entry_dialog, null);
Builder builder = new AlertDialog.Builder(context);
passwordView = (EditText)view.findViewById(R.id.password_text_box);
builder.setView(view);
builder.setPositiveButton(R.string.okay_action, new DialogInterface.OnClickListener()
{
builder.setPositiveButton(R.string.okay_action, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which)
{
if (PasswordEntryDialog.this.listener != null)
{
public void onClick(DialogInterface dialog, int which) {
if (PasswordEntryDialog.this.listener != null) {
String chosenPassword = passwordView.getText().toString();
PasswordEntryDialog.this.listener.passwordChosen(chosenPassword);
}
}
});
builder.setNegativeButton(R.string.cancel_action, new DialogInterface.OnClickListener()
{
builder.setNegativeButton(R.string.cancel_action, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which)
{
if (PasswordEntryDialog.this.listener != null)
{
public void onClick(DialogInterface dialog, int which) {
if (PasswordEntryDialog.this.listener != null) {
PasswordEntryDialog.this.listener.cancel();
}
}
});
dialog = builder.create();
passwordView.addTextChangedListener(new TextWatcher()
{
passwordView.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable arg0) { }
@ -66,8 +56,7 @@ public class PasswordEntryDialog
@Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3)
{
int arg3) {
Button okButton = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
String chosenPassword = passwordView.getText().toString();
@ -80,8 +69,7 @@ public class PasswordEntryDialog
}
public void show()
{
public void show() {
dialog.show();
Button okButton = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
okButton.setEnabled(false);

View File

@ -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

View File

@ -1,6 +1,5 @@
package com.fsck.k9.activity;
public interface Progressable
{
public interface Progressable {
public void setProgress(boolean progress);
}

View File

@ -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 {
}

View File

@ -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;

View File

@ -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<String, String> entry : providers.entrySet())
{
for (final Map.Entry<String, String> 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,28 +739,20 @@ 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)
{
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;
@ -859,63 +762,50 @@ public class AccountSettings 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);
}
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<Void, Void, Void>
{
private class PopulateFolderPrefsTask extends AsyncTask<Void, Void, Void> {
List <? extends Folder > folders = new LinkedList<LocalFolder>();
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];
@ -988,8 +864,7 @@ public class AccountSettings extends K9PreferenceActivity
int i = 2;
for (Folder folder : folders)
{
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,8 +892,7 @@ public class AccountSettings extends K9PreferenceActivity
}
@Override
protected void onPostExecute(Void res)
{
protected void onPostExecute(Void res) {
initListPreference(mAutoExpandFolder, mAccount.getAutoExpandFolderName(), allFolderLabels, allFolderValues);
initListPreference(mArchiveFolder, mAccount.getArchiveFolderName(), allFolderLabels, allFolderValues);
initListPreference(mDraftsFolder, mAccount.getDraftsFolderName(), allFolderLabels, allFolderValues);

View File

@ -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,61 +50,47 @@ 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())
{
public void onClick(View v) {
switch (v.getId()) {
case R.id.pop:
onPop();
break;
@ -119,8 +102,7 @@ public class AccountSetupAccountType extends K9Activity implements OnClickListen
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());

View File

@ -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,10 +310,8 @@ public class AccountSetupBasics extends K9Activity
finish();
}
public void onClick(View v)
{
switch (v.getId())
{
public void onClick(View v) {
switch (v.getId()) {
case R.id.next:
onNext();
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
} else if (xmlEventType == XmlResourceParser.START_TAG
&& "incoming".equals(xml.getName())
&& provider != null)
{
&& provider != null) {
provider.incomingUriTemplate = new URI(getXmlAttribute(xml, "uri"));
provider.incomingUsernameTemplate = getXmlAttribute(xml, "username");
}
else if (xmlEventType == XmlResourceParser.START_TAG
} else if (xmlEventType == XmlResourceParser.START_TAG
&& "outgoing".equals(xml.getName())
&& provider != null)
{
&& provider != null) {
provider.outgoingUriTemplate = new URI(getXmlAttribute(xml, "uri"));
provider.outgoingUsernameTemplate = getXmlAttribute(xml, "username");
}
else if (xmlEventType == XmlResourceParser.END_TAG
} else if (xmlEventType == XmlResourceParser.END_TAG
&& "provider".equals(xml.getName())
&& provider != null)
{
&& 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;

View File

@ -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,10 +194,8 @@ 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)
{
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
mCanceled = false;
setResult(RESULT_OK);
finish();
@ -239,10 +203,8 @@ public class AccountSetupCheckSettings extends K9Activity implements OnClickList
})
.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");
@ -303,25 +253,18 @@ public class AccountSetupCheckSettings extends K9Activity implements OnClickList
.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,23 +286,19 @@ 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())
{
public void onClick(View v) {
switch (v.getId()) {
case R.id.cancel:
onCancel();
break;

View File

@ -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();
}

View File

@ -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())
{
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());

View File

@ -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,10 +89,8 @@ public class AccountSetupNames extends K9Activity implements OnClickListener
finish();
}
public void onClick(View v)
{
switch (v.getId())
{
public void onClick(View v) {
switch (v.getId()) {
case R.id.done:
onNext();
break;

View File

@ -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,10 +153,8 @@ public class AccountSetupOptions extends K9Activity implements OnClickListener
finish();
}
public void onClick(View v)
{
switch (v.getId())
{
public void onClick(View v) {
switch (v.getId()) {
case R.id.next:
onDone();
break;

View File

@ -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())
{
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());

View File

@ -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,23 +145,17 @@ 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)
{
} catch (MessagingException e) {
Log.e(K9.LOG_TAG, "Saving folder settings failed " + e);
}
}

View File

@ -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);

View File

@ -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
@ -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<CharSequence> entryValueVector = new Vector<CharSequence>(Arrays.asList(mLanguage.getEntryValues()));
String supportedLanguages[] = getResources().getStringArray(R.array.supported_languages);
HashSet<String> supportedLanguageSet = new HashSet<String>(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;
@ -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);
}
},

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -4,25 +4,16 @@ package com.fsck.k9.controller;
import java.util.Comparator;
import com.fsck.k9.mail.Message;
public class MessageDateComparator implements Comparator<Message>
{
public int compare(Message o1, Message o2)
{
try
{
if (o1.getSentDate() == null)
{
public class MessageDateComparator implements Comparator<Message> {
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;
}
}

View File

@ -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);
}

View File

@ -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);

File diff suppressed because it is too large Load Diff

View File

@ -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<Message> messages)
{
List<Message> messages) {
controller.messagesArrived(account, folder, messages, true);
}
public void messagesArrived(Folder folder, List<Message> messages)
{
public void messagesArrived(Folder folder, List<Message> messages) {
controller.messagesArrived(account, folder, messages, false);
}
public void messagesRemoved(Folder folder, List<Message> messages)
{
public void messagesRemoved(Folder folder, List<Message> 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;
}

View File

@ -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<Message> messages)
{
public void listLocalMessagesAddMessages(Account account, String folder, List<Message> 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) {
}
}

View File

@ -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<Long> keyIds = new Vector<Long>();
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,13 +278,10 @@ public class Apg extends CryptoProvider
*/
@Override
public boolean onActivityResult(Activity activity, int requestCode, int resultCode,
android.content.Intent data, PgpData pgpData)
{
switch (requestCode)
{
android.content.Intent data, PgpData pgpData) {
switch (requestCode) {
case Apg.SELECT_SECRET_KEY:
if (resultCode != Activity.RESULT_OK || data == null)
{
if (resultCode != Activity.RESULT_OK || data == null) {
break;
}
pgpData.setSignatureKeyId(data.getLongExtra(Apg.EXTRA_KEY_ID, 0));
@ -337,8 +290,7 @@ public class Apg extends CryptoProvider
break;
case Apg.SELECT_PUBLIC_KEYS:
if (resultCode != Activity.RESULT_OK || data == null)
{
if (resultCode != Activity.RESULT_OK || data == null) {
pgpData.setEncryptionKeys(null);
((MessageCompose) activity).onEncryptionKeySelectionDone();
break;
@ -348,8 +300,7 @@ public class Apg extends CryptoProvider
break;
case Apg.ENCRYPT_MESSAGE:
if (resultCode != Activity.RESULT_OK || data == null)
{
if (resultCode != Activity.RESULT_OK || data == null) {
pgpData.setEncryptionKeys(null);
((MessageCompose) activity).onEncryptDone();
break;
@ -357,19 +308,16 @@ public class Apg extends CryptoProvider
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)
{
if (pgpData.getEncryptedData() == null) {
pgpData.setEncryptedData(data.getStringExtra(Apg.EXTRA_DECRYPTED_MESSAGE));
}
if (pgpData.getEncryptedData() != null)
{
if (pgpData.getEncryptedData() != null) {
((MessageCompose) activity).onEncryptDone();
}
break;
case Apg.DECRYPT_MESSAGE:
if (resultCode != Activity.RESULT_OK || data == null)
{
if (resultCode != Activity.RESULT_OK || data == null) {
break;
}
@ -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,

View File

@ -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();
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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,24 +47,18 @@ 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
{
try {
Class <? extends IAutoSync > clazz =
Class.forName(className).asSubclass(IAutoSync.class);
@ -74,23 +66,14 @@ public class AutoSyncHelper
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.");
}

View File

@ -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;
}
}

View File

@ -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;
}

View File

@ -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.

View File

@ -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
{
try {
Class <? extends Contacts > clazz =
Class.forName(className).asSubclass(Contacts.class);
Constructor <? extends Contacts > 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();
}

View File

@ -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 + " = ?";

View File

@ -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,

View File

@ -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

View File

@ -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<Map<String, DateFormat>> storedFormats = new ThreadLocal<Map<String, DateFormat>>()
{
private static ThreadLocal<Map<String, DateFormat>> storedFormats = new ThreadLocal<Map<String, DateFormat>>() {
@Override
public synchronized Map<String, DateFormat> initialValue()
{
public synchronized Map<String, DateFormat> initialValue() {
return new HashMap<String, DateFormat>();
}
};
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<String, DateFormat> 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);
}

View File

@ -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)
{
if (subjectAltNames != null) {
for (Object subjectAltName : subjectAltNames) {
List<?> altNameEntry = (List<?>)(subjectAltName);
if ((altNameEntry != null) && (2 <= altNameEntry.size()))
{
if ((altNameEntry != null) && (2 <= altNameEntry.size())) {
Integer altNameType = (Integer)(altNameEntry.get(0));
if (altNameType != null)
{
if (altNameType == ALT_IPA_NAME)
{
if (altNameType != null) {
if (altNameType == ALT_IPA_NAME) {
String altName = (String)(altNameEntry.get(1));
if (altName != null)
{
if (K9.DEBUG)
{
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);

View File

@ -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<String> TAGS_WITH_IGNORED_CONTENT = Collections.unmodifiableSet(new HashSet<String>()
{
private static final Set<String> TAGS_WITH_IGNORED_CONTENT = Collections.unmodifiableSet(new HashSet<String>() {
{
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 <hr>, 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 "<html><head/><body>" +
htmlifyMessageHeader() +
text +
@ -163,12 +145,9 @@ 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)
{
try {
while ((c = reader.read()) != -1) {
switch (c) {
case '&':
buff.append("&amp;");
break;
@ -184,9 +163,7 @@ public class HtmlConverter
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);
}
@ -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, "<a href=\"$0\">$0</a>");
}
else
{
} else {
m.appendReplacement(outputBuffer, "<a href=\"http://$0\">$0</a>");
}
}
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,12 +239,10 @@ 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)
{
switch (codePoint) {
case 0xFE000:
return "sun";
case 0xFE001:
@ -1109,26 +1072,18 @@ public class HtmlConverter
}
}
private static String htmlifyMessageHeader()
{
if (K9.messageViewFixedWidthFont())
{
private static String htmlifyMessageHeader() {
if (K9.messageViewFixedWidthFont()) {
return "<pre style=\"white-space: pre-wrap; word-wrap:break-word; \">";
}
else
{
} else {
return "<div style=\"white-space: pre-wrap; word-wrap:break-word; \">";
}
}
private static String htmlifyMessageFooter()
{
if (K9.messageViewFixedWidthFont())
{
private static String htmlifyMessageFooter() {
if (K9.messageViewFixedWidthFont()) {
return "</pre>";
}
else
{
} else {
return "</div>";
}
}
@ -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);

View File

@ -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.

View File

@ -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();
}
}

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -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);

View File

@ -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, <code>null</code> 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, <code>null</code> 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 <code>null</code>.
* @return Never <code>null</code>.
*/
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 <code>null</code>.
*/
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;

View File

@ -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)
{
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");
}
}

View File

@ -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 <james.bond@mi6.uk>
@ -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<Address> addresses = new ArrayList<Address>();
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<Address> addresses = new ArrayList<Address>();
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<Address> addresses = new ArrayList<Address>();
@ -364,22 +296,17 @@ 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);
}
@ -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("\"", "\\\"");
sb.append(personal);
}
if (i < count - 1)
{
if (i < count - 1) {
sb.append(",\u0000");
}
}

View File

@ -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);
}
}

View File

@ -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;
}

View File

@ -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;
}
}

View File

@ -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);
}
}

View File

@ -15,8 +15,7 @@ import java.util.ArrayList;
* any information it needs to download the content.
* </pre>
*/
public class FetchProfile extends ArrayList<FetchProfile.Item>
{
public class FetchProfile extends ArrayList<FetchProfile.Item> {
private static final long serialVersionUID = -5520076119120964166L;
/**
@ -24,8 +23,7 @@ public class FetchProfile extends ArrayList<FetchProfile.Item>
* 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.
*/

View File

@ -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,

View File

@ -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;
}
}

View File

@ -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);
}

View File

@ -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;
}

View File

@ -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<BodyPart> mParts = new ArrayList<BodyPart>();
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);
}

View File

@ -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;

Some files were not shown because too many files have changed in this diff Show More