From 108e6ebed08b617be7a9ebc68c8496052981971b Mon Sep 17 00:00:00 2001 From: Daniele Ricci Date: Wed, 9 Jul 2014 00:23:39 +0200 Subject: [PATCH] Convert all tabs to 4 spaces and remove CRLF line terminators Signed-off-by: Daniele Ricci --- src/org/kontalk/Kontalk.java | 16 +- .../kontalk/authenticator/Authenticator.java | 32 +- .../AndroidConnectionConfiguration.java | 10 +- .../kontalk/client/ClientHTTPConnection.java | 12 +- src/org/kontalk/client/KontalkConnection.java | 68 +- src/org/kontalk/client/NumberValidator.java | 34 +- src/org/kontalk/crypto/Coder.java | 20 +- src/org/kontalk/crypto/DecryptException.java | 70 +- src/org/kontalk/crypto/PGP.java | 48 +- src/org/kontalk/crypto/PGPCoder.java | 206 +- src/org/kontalk/crypto/PersonalKey.java | 66 +- src/org/kontalk/crypto/X509Bridge.java | 4 +- src/org/kontalk/data/Contact.java | 66 +- src/org/kontalk/data/Conversation.java | 8 +- src/org/kontalk/message/Attachment.java | 62 +- .../kontalk/message/AttachmentComponent.java | 14 +- src/org/kontalk/message/CompositeMessage.java | 156 +- src/org/kontalk/message/ImageComponent.java | 16 +- .../message/LegacyAbstractMessage.java | 4 +- .../message/LegacyPlainTextMessage.java | 10 +- src/org/kontalk/message/MessageComponent.java | 46 +- src/org/kontalk/message/RawComponent.java | 6 +- src/org/kontalk/message/TextComponent.java | 6 +- src/org/kontalk/message/VCardComponent.java | 16 +- .../kontalk/provider/MessagesProvider.java | 118 +- src/org/kontalk/provider/MyMessages.java | 2 +- src/org/kontalk/provider/UsersProvider.java | 48 +- src/org/kontalk/service/DownloadService.java | 22 +- .../kontalk/service/NetworkStateReceiver.java | 28 +- .../kontalk/service/XMPPConnectionHelper.java | 30 +- .../service/gcm/DefaultGcmListener.java | 20 +- .../service/gcm/GcmBroadcastReceiver.java | 8 +- .../kontalk/service/gcm/GcmIntentService.java | 62 +- src/org/kontalk/service/gcm/GcmUtils.java | 184 +- .../msgcenter/DiscoverInfoListener.java | 10 +- .../msgcenter/LastActivityListener.java | 8 +- .../MessageCenterPacketListener.java | 210 +- .../msgcenter/MessageCenterService.java | 238 +- .../service/msgcenter/MessageListener.java | 46 +- .../service/msgcenter/PingListener.java | 6 +- .../service/msgcenter/PresenceListener.java | 114 +- .../msgcenter/PushDiscoverItemsListener.java | 6 +- .../msgcenter/RegenerateKeyPairListener.java | 18 +- .../service/msgcenter/RosterListener.java | 6 +- .../UploadDiscoverItemsListener.java | 10 +- .../service/msgcenter/UploadInfoListener.java | 8 +- .../service/msgcenter/VCardListener.java | 84 +- src/org/kontalk/sync/Syncer.java | 30 +- src/org/kontalk/ui/AboutActivity.java | 50 +- src/org/kontalk/ui/AboutFragment.java | 106 +- src/org/kontalk/ui/AvatarListItem.java | 52 +- src/org/kontalk/ui/ComposeMessage.java | 20 +- .../kontalk/ui/ComposeMessageFragment.java | 2872 ++++++++--------- src/org/kontalk/ui/ContactsListActivity.java | 68 +- src/org/kontalk/ui/ConversationList.java | 118 +- .../kontalk/ui/ConversationListFragment.java | 4 +- src/org/kontalk/ui/ConversationListItem.java | 44 +- src/org/kontalk/ui/DonationFragment.java | 84 +- src/org/kontalk/ui/IconContextMenu.java | 526 +-- src/org/kontalk/ui/InputDialog.java | 70 +- src/org/kontalk/ui/MessageListAdapter.java | 2 +- src/org/kontalk/ui/MessageListItem.java | 76 +- src/org/kontalk/ui/MessagingNotification.java | 32 +- src/org/kontalk/ui/NumberValidation.java | 6 +- src/org/kontalk/ui/PopupWindows.java | 310 +- src/org/kontalk/ui/PreferencesActivity.java | 18 +- src/org/kontalk/ui/QuickAction.java | 362 +-- src/org/kontalk/util/MediaStorage.java | 10 +- src/org/kontalk/util/MessageUtils.java | 212 +- src/org/kontalk/util/Preferences.java | 24 +- src/org/kontalk/util/XMPPUtils.java | 64 +- 71 files changed, 3721 insertions(+), 3721 deletions(-) diff --git a/src/org/kontalk/Kontalk.java b/src/org/kontalk/Kontalk.java index 559c60e11..775024e99 100644 --- a/src/org/kontalk/Kontalk.java +++ b/src/org/kontalk/Kontalk.java @@ -190,10 +190,10 @@ public PersonalKey getPersonalKey() throws PGPException, IOException, Certificat } public void exportPersonalKey() - throws CertificateException, PGPException, IOException, - NoSuchProviderException, KeyStoreException, NoSuchAlgorithmException { + throws CertificateException, PGPException, IOException, + NoSuchProviderException, KeyStoreException, NoSuchAlgorithmException { - Authenticator.exportDefaultPersonalKey(this, getCachedPassphrase(), true); + Authenticator.exportDefaultPersonalKey(this, getCachedPassphrase(), true); } /** Invalidates the cached personal key. */ @@ -202,16 +202,16 @@ public void invalidatePersonalKey() { } private void ensureCachedPassphrase() { - if (mKeyPassphrase == null) { + if (mKeyPassphrase == null) { AccountManager am = AccountManager.get(this); Account account = Authenticator.getDefaultAccount(am); // cache passphrase from account mKeyPassphrase = am.getPassword(account); - } + } } public String getCachedPassphrase() { - ensureCachedPassphrase(); + ensureCachedPassphrase(); return mKeyPassphrase; } @@ -236,13 +236,13 @@ private static void enableService(Context context, PackageManager pm, Class k public static int getVersionCode(Context context) { try { PackageInfo pInfo = context.getPackageManager() - .getPackageInfo(context.getPackageName(), 0); + .getPackageInfo(context.getPackageName(), 0); return pInfo.versionCode; } catch (NameNotFoundException e) { // shouldn't happen - return 0; + return 0; } } diff --git a/src/org/kontalk/authenticator/Authenticator.java b/src/org/kontalk/authenticator/Authenticator.java index dc66c1521..a13150758 100644 --- a/src/org/kontalk/authenticator/Authenticator.java +++ b/src/org/kontalk/authenticator/Authenticator.java @@ -106,8 +106,8 @@ public static String getDefaultAccountName(Context ctx) { } public static boolean isSelfUserId(Context ctx, String userId) { - String name = getDefaultAccountName(ctx); - return (name != null && MessageUtils.sha1(name).equals(userId)); + String name = getDefaultAccountName(ctx); + return (name != null && MessageUtils.sha1(name).equals(userId)); } public static boolean hasPersonalKey(AccountManager am, Account account) { @@ -126,23 +126,23 @@ public static PersonalKey loadDefaultPersonalKey(Context ctx, String passphrase) String bridgeCertData = m.getUserData(acc, DATA_BRIDGECERT); if (privKeyData != null && pubKeyData != null && bridgeCertData != null) - return PersonalKey - .load(Base64.decode(privKeyData, Base64.DEFAULT), - Base64.decode(pubKeyData, Base64.DEFAULT), - passphrase, - Base64.decode(bridgeCertData, Base64.DEFAULT) - ); + return PersonalKey + .load(Base64.decode(privKeyData, Base64.DEFAULT), + Base64.decode(pubKeyData, Base64.DEFAULT), + passphrase, + Base64.decode(bridgeCertData, Base64.DEFAULT) + ); else - return null; + return null; } public static void exportDefaultPersonalKey(Context ctx, String passphrase, boolean bridgeCertificate) - throws CertificateException, NoSuchProviderException, PGPException, - IOException, KeyStoreException, NoSuchAlgorithmException { + throws CertificateException, NoSuchProviderException, PGPException, + IOException, KeyStoreException, NoSuchAlgorithmException { - AccountManager m = AccountManager.get(ctx); - Account acc = getDefaultAccount(m); + AccountManager m = AccountManager.get(ctx); + Account acc = getDefaultAccount(m); String privKeyData = m.getUserData(acc, DATA_PRIVATEKEY); String pubKeyData = m.getUserData(acc, DATA_PUBLICKEY); @@ -154,7 +154,7 @@ public static void exportDefaultPersonalKey(Context ctx, String passphrase, bool byte[] privateKey = Base64.decode(privKeyData, Base64.DEFAULT); if (bridgeCertificate) { - // bridge certificate is just plain data + // bridge certificate is just plain data String bridgeCertData = m.getUserData(acc, DATA_BRIDGECERT); byte[] bridgeCert = Base64.decode(bridgeCertData, Base64.DEFAULT); @@ -164,7 +164,7 @@ public static void exportDefaultPersonalKey(Context ctx, String passphrase, bool writer.close(); // export bridge private key - PrivateKey bridgeKey = PGP.convertPrivateKey(privateKey, passphrase); + PrivateKey bridgeKey = PGP.convertPrivateKey(privateKey, passphrase); writer = new PemWriter(new FileWriter(new File(path, BRIDGE_KEY_FILENAME))); writer.writeObject(new PemObject(X509Bridge.PEM_TYPE_PRIVATE_KEY, bridgeKey.getEncoded())); writer.close(); @@ -194,7 +194,7 @@ public static void setDefaultPersonalKey(Context ctx, byte[] publicKeyData, byte // private key data is optional when updating just the public key if (privateKeyData != null) - am.setUserData(acc, Authenticator.DATA_PRIVATEKEY, Base64.encodeToString(privateKeyData, Base64.NO_WRAP)); + am.setUserData(acc, Authenticator.DATA_PRIVATEKEY, Base64.encodeToString(privateKeyData, Base64.NO_WRAP)); am.setUserData(acc, Authenticator.DATA_PUBLICKEY, Base64.encodeToString(publicKeyData, Base64.NO_WRAP)); am.setUserData(acc, Authenticator.DATA_BRIDGECERT, Base64.encodeToString(bridgeCertData, Base64.NO_WRAP)); diff --git a/src/org/kontalk/client/AndroidConnectionConfiguration.java b/src/org/kontalk/client/AndroidConnectionConfiguration.java index b4a9b6180..dea364871 100644 --- a/src/org/kontalk/client/AndroidConnectionConfiguration.java +++ b/src/org/kontalk/client/AndroidConnectionConfiguration.java @@ -35,12 +35,12 @@ public AndroidConnectionConfiguration(String host, int port) { public AndroidConnectionConfiguration(String host, int port, String name) { super(host, port, name); - //AndroidInit(); + //AndroidInit(); } /* TODO move to custom SSL context private void AndroidInit() { - // API 14 is Ice Cream Sandwich + // API 14 is Ice Cream Sandwich if (Build.VERSION.SDK_INT >= 14) { setTruststoreType("AndroidCAStore"); setTruststorePassword(null); @@ -49,9 +49,9 @@ private void AndroidInit() { setTruststoreType("BKS"); String path = System.getProperty("javax.net.ssl.trustStore"); if (path == null) - path = System.getProperty("java.home") + File.separator + "etc" - + File.separator + "security" + File.separator - + "cacerts.bks"; + path = System.getProperty("java.home") + File.separator + "etc" + + File.separator + "security" + File.separator + + "cacerts.bks"; setTruststorePath(path); } } diff --git a/src/org/kontalk/client/ClientHTTPConnection.java b/src/org/kontalk/client/ClientHTTPConnection.java index 8fedd4348..31024eebb 100644 --- a/src/org/kontalk/client/ClientHTTPConnection.java +++ b/src/org/kontalk/client/ClientHTTPConnection.java @@ -125,11 +125,11 @@ public static SSLSocketFactory setupSSLSocketFactory(Context context, // load merged truststore (system + internal) KeyStore truststore = InternalTrustStore.getTrustStore(context); - if (acceptAnyCertificate) - return new BlackholeSSLSocketFactory(keystore, null, truststore); + if (acceptAnyCertificate) + return new BlackholeSSLSocketFactory(keystore, null, truststore); - else - return new SSLSocketFactory(keystore, null, truststore); + else + return new SSLSocketFactory(keystore, null, truststore); } /** @@ -148,7 +148,7 @@ private HttpResponse execute(HttpRequestBase request) throws IOException { boolean acceptAnyCertificate = Preferences.getAcceptAnyCertificate(mContext); registry.register(new Scheme("https", setupSSLSocketFactory(mContext, - mPrivateKey, mCertificate, acceptAnyCertificate), 443)); + mPrivateKey, mCertificate, acceptAnyCertificate), 443)); } catch (Exception e) { IOException ie = new IOException("unable to create keystore"); @@ -242,7 +242,7 @@ private static final class BlackholeSSLSocketFactory extends SSLSocketFactory { SSLContext sslContext = SSLContext.getInstance("TLS"); public BlackholeSSLSocketFactory(KeyStore keystore, String keystorePassword, KeyStore truststore) - throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { + throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { super(keystore, keystorePassword, truststore); TrustManager tm = new X509TrustManager() { diff --git a/src/org/kontalk/client/KontalkConnection.java b/src/org/kontalk/client/KontalkConnection.java index be0fe9c64..d2028d1a6 100644 --- a/src/org/kontalk/client/KontalkConnection.java +++ b/src/org/kontalk/client/KontalkConnection.java @@ -47,15 +47,15 @@ public class KontalkConnection extends XMPPTCPConnection { protected EndpointServer mServer; public KontalkConnection(EndpointServer server, - boolean acceptAnyCertificate, KeyStore trustStore) - throws XMPPException { + boolean acceptAnyCertificate, KeyStore trustStore) + throws XMPPException { this(server, null, null, acceptAnyCertificate, trustStore); } public KontalkConnection(EndpointServer server, - PrivateKey privateKey, X509Certificate bridgeCert, - boolean acceptAnyCertificate, KeyStore trustStore) throws XMPPException { + PrivateKey privateKey, X509Certificate bridgeCert, + boolean acceptAnyCertificate, KeyStore trustStore) throws XMPPException { super(new AndroidConnectionConfiguration (server.getHost(), @@ -83,49 +83,49 @@ private void setupSSL(PrivateKey privateKey, X509Certificate bridgeCert, boolean KeyManager[] km = null; if (privateKey != null && bridgeCert != null) { - // in-memory keystore - KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); - keystore.load(null, null); - keystore.setKeyEntry("private", privateKey, null, new Certificate[] { bridgeCert }); + // in-memory keystore + KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); + keystore.load(null, null); + keystore.setKeyEntry("private", privateKey, null, new Certificate[] { bridgeCert }); - // key managers - KeyManagerFactory kmFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); - kmFactory.init(keystore, null); + // key managers + KeyManagerFactory kmFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); + kmFactory.init(keystore, null); - km = kmFactory.getKeyManagers(); + km = kmFactory.getKeyManagers(); } // trust managers TrustManager[] tm; if (acceptAnyCertificate) { - tm = new TrustManager[] { - new X509TrustManager() { - @Override - public X509Certificate[] getAcceptedIssuers() { - return null; - } - - @Override - public void checkServerTrusted(X509Certificate[] chain, String authType) - throws CertificateException { - } - - @Override - public void checkClientTrusted(X509Certificate[] chain, String authType) - throws CertificateException { - } - } - }; + tm = new TrustManager[] { + new X509TrustManager() { + @Override + public X509Certificate[] getAcceptedIssuers() { + return null; + } + + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType) + throws CertificateException { + } + + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType) + throws CertificateException { + } + } + }; } else { // builtin keystore - TrustManagerFactory tmFactory = TrustManagerFactory - .getInstance(TrustManagerFactory.getDefaultAlgorithm()); - tmFactory.init(trustStore); + TrustManagerFactory tmFactory = TrustManagerFactory + .getInstance(TrustManagerFactory.getDefaultAlgorithm()); + tmFactory.init(trustStore); - tm = tmFactory.getTrustManagers(); + tm = tmFactory.getTrustManagers(); } ctx.init(km, tm, null); diff --git a/src/org/kontalk/client/NumberValidator.java b/src/org/kontalk/client/NumberValidator.java index 8146dff76..5fc227440 100644 --- a/src/org/kontalk/client/NumberValidator.java +++ b/src/org/kontalk/client/NumberValidator.java @@ -197,7 +197,7 @@ public void run() { XMPPConnection conn = mConnector.getConnection(); conn.addPacketListener(new PacketListener() { public void processPacket(Packet packet) { - int reason = 0; + int reason = 0; IQ iq = (IQ) packet; if (iq.getType() == IQ.Type.RESULT) { @@ -219,29 +219,29 @@ public void processPacket(Packet packet) { } else if (iq.getType() == IQ.Type.ERROR) { - XMPPError error = iq.getError(); + XMPPError error = iq.getError(); - if (XMPPError.Condition.service_unavailable.toString() - .equals(error.getCondition())) { + if (XMPPError.Condition.service_unavailable.toString() + .equals(error.getCondition())) { - if (error.getType() == XMPPError.Type.WAIT) { - reason = ERROR_THROTTLING; + if (error.getType() == XMPPError.Type.WAIT) { + reason = ERROR_THROTTLING; - } + } - else { - mListener.onServerCheckFailed(NumberValidator.this); - // onValidationFailed will not be called - reason = -1; + else { + mListener.onServerCheckFailed(NumberValidator.this); + // onValidationFailed will not be called + reason = -1; - } - } + } + } } // validation failed :( if (reason >= 0) - mListener.onValidationFailed(NumberValidator.this, reason); + mListener.onValidationFailed(NumberValidator.this, reason); mStep = STEP_INIT; return; @@ -364,8 +364,8 @@ public int getStep() { private void initConnection() throws XMPPException, SmackException, PGPException, KeyStoreException, NoSuchProviderException, - NoSuchAlgorithmException, CertificateException, - IOException { + NoSuchAlgorithmException, CertificateException, + IOException { if (!mConnector.isConnected()) { mConnector.setListener(this); @@ -574,7 +574,7 @@ public void authenticated(XMPPConnection conn) { @Override public void authenticationFailed() { - // not used + // not used } } diff --git a/src/org/kontalk/crypto/Coder.java b/src/org/kontalk/crypto/Coder.java index 131bf3aa5..28b3a4fc7 100644 --- a/src/org/kontalk/crypto/Coder.java +++ b/src/org/kontalk/crypto/Coder.java @@ -84,8 +84,8 @@ public abstract class Coder { /** Decrypts a byte array which should content text. */ public abstract void decryptText(byte[] encrypted, boolean verify, - StringBuilder out, StringBuilder mime, List errors) - throws GeneralSecurityException; + StringBuilder out, StringBuilder mime, List errors) + throws GeneralSecurityException; public abstract InputStream wrapInputStream(InputStream inputStream) throws GeneralSecurityException; @@ -97,14 +97,14 @@ public abstract void decryptText(byte[] encrypted, boolean verify, /** Returns true if the given security flags has some error bit on. */ public static boolean isError(int securityFlags) { - return (securityFlags & SECURITY_ERROR_INVALID_SIGNATURE) != 0 || - (securityFlags & SECURITY_ERROR_INVALID_SENDER) != 0 || - (securityFlags & SECURITY_ERROR_INVALID_RECIPIENT) != 0 || - (securityFlags & SECURITY_ERROR_INVALID_TIMESTAMP) != 0 || - (securityFlags & SECURITY_ERROR_INVALID_DATA) != 0 || - (securityFlags & SECURITY_ERROR_DECRYPT_FAILED) != 0 || - (securityFlags & SECURITY_ERROR_INTEGRITY_CHECK) != 0 || - (securityFlags & SECURITY_ERROR_PUBLIC_KEY_UNAVAILABLE) != 0; + return (securityFlags & SECURITY_ERROR_INVALID_SIGNATURE) != 0 || + (securityFlags & SECURITY_ERROR_INVALID_SENDER) != 0 || + (securityFlags & SECURITY_ERROR_INVALID_RECIPIENT) != 0 || + (securityFlags & SECURITY_ERROR_INVALID_TIMESTAMP) != 0 || + (securityFlags & SECURITY_ERROR_INVALID_DATA) != 0 || + (securityFlags & SECURITY_ERROR_DECRYPT_FAILED) != 0 || + (securityFlags & SECURITY_ERROR_INTEGRITY_CHECK) != 0 || + (securityFlags & SECURITY_ERROR_PUBLIC_KEY_UNAVAILABLE) != 0; } } diff --git a/src/org/kontalk/crypto/DecryptException.java b/src/org/kontalk/crypto/DecryptException.java index 92786a519..fbfd1de4e 100644 --- a/src/org/kontalk/crypto/DecryptException.java +++ b/src/org/kontalk/crypto/DecryptException.java @@ -26,47 +26,47 @@ */ public class DecryptException extends GeneralSecurityException { - private static final long serialVersionUID = -3210114563479741397L; + private static final long serialVersionUID = -3210114563479741397L; - /** Signature verification failed. */ - public static final int DECRYPT_EXCEPTION_VERIFICATION_FAILED = 1; - /** Generic (unknown) decryption failure. */ - public static final int DECRYPT_EXCEPTION_DECRYPT_FAILED = 2; - /** Private key needed for decryption was not found. */ - public static final int DECRYPT_EXCEPTION_PRIVATE_KEY_NOT_FOUND = 3; - /** Message sender doesn't match signature. */ - public static final int DECRYPT_EXCEPTION_INVALID_SENDER = 4; - /** Message recipient doesn't match encryption key. */ - public static final int DECRYPT_EXCEPTION_INVALID_RECIPIENT = 5; - /** Invalid packet data. */ - public static final int DECRYPT_EXCEPTION_INVALID_DATA = 6; - /** Message integrity check failed. */ - public static final int DECRYPT_EXCEPTION_INTEGRITY_CHECK = 7; + /** Signature verification failed. */ + public static final int DECRYPT_EXCEPTION_VERIFICATION_FAILED = 1; + /** Generic (unknown) decryption failure. */ + public static final int DECRYPT_EXCEPTION_DECRYPT_FAILED = 2; + /** Private key needed for decryption was not found. */ + public static final int DECRYPT_EXCEPTION_PRIVATE_KEY_NOT_FOUND = 3; + /** Message sender doesn't match signature. */ + public static final int DECRYPT_EXCEPTION_INVALID_SENDER = 4; + /** Message recipient doesn't match encryption key. */ + public static final int DECRYPT_EXCEPTION_INVALID_RECIPIENT = 5; + /** Invalid packet data. */ + public static final int DECRYPT_EXCEPTION_INVALID_DATA = 6; + /** Message integrity check failed. */ + public static final int DECRYPT_EXCEPTION_INTEGRITY_CHECK = 7; - private final int mCode; + private final int mCode; - public DecryptException(int code) { - super(); - mCode = code; - } + public DecryptException(int code) { + super(); + mCode = code; + } - public DecryptException(int code, String message) { - super(message); - mCode = code; - } + public DecryptException(int code, String message) { + super(message); + mCode = code; + } - public DecryptException(int code, Throwable cause) { - super(cause); - mCode = code; - } + public DecryptException(int code, Throwable cause) { + super(cause); + mCode = code; + } - public DecryptException(int code, Throwable cause, String message) { - super(message, cause); - mCode = code; - } + public DecryptException(int code, Throwable cause, String message) { + super(message, cause); + mCode = code; + } - public int getCode() { - return mCode; - } + public int getCode() { + return mCode; + } } diff --git a/src/org/kontalk/crypto/PGP.java b/src/org/kontalk/crypto/PGP.java index 56c351b9a..e5c8a5565 100644 --- a/src/org/kontalk/crypto/PGP.java +++ b/src/org/kontalk/crypto/PGP.java @@ -172,7 +172,7 @@ public static PGPKeyPairRing store(PGPDecryptedKeyPairRing pair, public static PGPPublicKey signPublicKey(PGPKeyPair secret, PGPPublicKey keyToBeSigned, String id) throws PGPException, IOException, SignatureException { - return signPublicKey(secret, keyToBeSigned, id, PGPSignature.CASUAL_CERTIFICATION); + return signPublicKey(secret, keyToBeSigned, id, PGPSignature.CASUAL_CERTIFICATION); } /** Signs a public key with the given secret key. */ @@ -192,14 +192,14 @@ public static PGPPublicKey signPublicKey(PGPKeyPair secret, PGPPublicKey keyToBe /** Signs and add the given user attributes to the given public key. */ public static PGPPublicKey signUserAttributes(PGPKeyPair secret, PGPPublicKey keyToBeSigned, PGPUserAttributeSubpacketVector attributes) - throws PGPException, SignatureException { + throws PGPException, SignatureException { return signUserAttributes(secret, keyToBeSigned, attributes, PGPSignature.POSITIVE_CERTIFICATION); } /** Signs and add the given user attributes to the given public key. */ public static PGPPublicKey signUserAttributes(PGPKeyPair secret, PGPPublicKey keyToBeSigned, PGPUserAttributeSubpacketVector attributes, int certification) - throws PGPException, SignatureException { + throws PGPException, SignatureException { PGPPrivateKey pgpPrivKey = secret.getPrivateKey(); @@ -210,14 +210,14 @@ public static PGPPublicKey signUserAttributes(PGPKeyPair secret, PGPPublicKey ke sGen.init(certification, pgpPrivKey); return PGPPublicKey.addCertification(keyToBeSigned, attributes, - sGen.generateCertification(attributes, keyToBeSigned)); + sGen.generateCertification(attributes, keyToBeSigned)); } public static PGPPublicKey revokeUserAttributes(PGPKeyPair secret, PGPPublicKey keyToBeSigned, PGPUserAttributeSubpacketVector attributes) - throws SignatureException, PGPException { + throws SignatureException, PGPException { - return PGP.signUserAttributes(secret, keyToBeSigned, attributes, - PGPSignature.CERTIFICATION_REVOCATION); + return PGP.signUserAttributes(secret, keyToBeSigned, attributes, + PGPSignature.CERTIFICATION_REVOCATION); } /** Revokes the given key. */ @@ -237,7 +237,7 @@ public static PGPPublicKey revokeKey(PGPKeyPair secret) } public static PGPDecryptedKeyPairRing fromParcel(Parcel in) throws PGPException { - ensureKeyConverter(); + ensureKeyConverter(); // TODO read byte data PrivateKey privSign = (PrivateKey) in.readSerializable(); @@ -287,12 +287,12 @@ public static void toParcel(PGPDecryptedKeyPairRing pair, Parcel dest) } public static String getFingerprint(PGPPublicKey publicKey) { - return MessageUtils.bytesToHex(publicKey.getFingerprint()); + return MessageUtils.bytesToHex(publicKey.getFingerprint()); } public static String getFingerprint(byte[] publicKeyring) throws IOException, PGPException { - PGPPublicKey pk = getMasterKey(publicKeyring); - return MessageUtils.bytesToHex(pk.getFingerprint()); + PGPPublicKey pk = getMasterKey(publicKeyring); + return MessageUtils.bytesToHex(pk.getFingerprint()); } /** Returns the first user ID on the key that matches the given hostname. */ @@ -303,8 +303,8 @@ public static String getUserId(PGPPublicKey key, String host) { /** Returns the first user ID on the key that matches the given hostname. */ public static String getUserId(byte[] publicKeyring, String host) throws IOException, PGPException { - PGPPublicKey pk = getMasterKey(publicKeyring); - return getUserId(pk, host); + PGPPublicKey pk = getMasterKey(publicKeyring); + return getUserId(pk, host); } /** Returns the first master key found in the given public keyring. */ @@ -322,12 +322,12 @@ public static PGPPublicKey getMasterKey(PGPPublicKeyRing publicKeyring) { /** Returns the first master key found in the given public keyring. */ public static PGPPublicKey getMasterKey(byte[] publicKeyring) throws IOException, PGPException { - return getMasterKey(readPublicKeyring(publicKeyring)); + return getMasterKey(readPublicKeyring(publicKeyring)); } public static PGPPublicKey getEncryptionKey(PGPPublicKeyRing publicKeyring) { @SuppressWarnings("unchecked") - Iterator iter = publicKeyring.getPublicKeys(); + Iterator iter = publicKeyring.getPublicKeys(); while (iter.hasNext()) { PGPPublicKey pk = iter.next(); if (pk.isEncryptionKey()) @@ -342,7 +342,7 @@ public static PGPPublicKeyRing readPublicKeyring(byte[] publicKeyring) throws IO Object o = reader.nextObject(); while (o != null) { if (o instanceof PGPPublicKeyRing) - return (PGPPublicKeyRing) o; + return (PGPPublicKeyRing) o; o = reader.nextObject(); } @@ -351,18 +351,18 @@ public static PGPPublicKeyRing readPublicKeyring(byte[] publicKeyring) throws IO } private static void ensureKeyConverter() { - if (sKeyConverter == null) - sKeyConverter = new JcaPGPKeyConverter().setProvider(PGP.PROVIDER); + if (sKeyConverter == null) + sKeyConverter = new JcaPGPKeyConverter().setProvider(PGP.PROVIDER); } public static PrivateKey convertPrivateKey(PGPPrivateKey key) throws PGPException { - ensureKeyConverter(); - return sKeyConverter.getPrivateKey(key); + ensureKeyConverter(); + return sKeyConverter.getPrivateKey(key); } @SuppressWarnings("unchecked") - public static PrivateKey convertPrivateKey(byte[] privateKeyData, String passphrase) - throws PGPException, IOException { + public static PrivateKey convertPrivateKey(byte[] privateKeyData, String passphrase) + throws PGPException, IOException { PGPDigestCalculatorProvider sha1Calc = new JcaPGPDigestCalculatorProviderBuilder().build(); PBESecretKeyDecryptor decryptor = new JcePBESecretKeyDecryptorBuilder(sha1Calc) @@ -388,8 +388,8 @@ public static PrivateKey convertPrivateKey(byte[] privateKeyData, String passphr } public static PublicKey convertPublicKey(PGPPublicKey key) throws PGPException { - ensureKeyConverter(); - return sKeyConverter.getPublicKey(key); + ensureKeyConverter(); + return sKeyConverter.getPublicKey(key); } diff --git a/src/org/kontalk/crypto/PGPCoder.java b/src/org/kontalk/crypto/PGPCoder.java index 3a6524be4..268bd85c1 100644 --- a/src/org/kontalk/crypto/PGPCoder.java +++ b/src/org/kontalk/crypto/PGPCoder.java @@ -101,7 +101,7 @@ public PGPCoder(EndpointServer server, PersonalKey key, PGPPublicKey sender) { @Override public byte[] encryptText(CharSequence text) throws GeneralSecurityException { try { - // consider plain text + // consider plain text return encryptData("text/plain", text); } @@ -119,9 +119,9 @@ public byte[] encryptStanza(CharSequence xml) throws GeneralSecurityException { try { // prepare XML wrapper StringBuilder xmlWrapper = new StringBuilder( - "") - .append( xml ) - .append(""); + "") + .append( xml ) + .append(""); return encryptData(XMPPUtils.XML_XMPP_TYPE, xmlWrapper.toString()); } @@ -136,7 +136,7 @@ public byte[] encryptStanza(CharSequence xml) throws GeneralSecurityException { } private byte[] encryptData(String mime, CharSequence data) - throws PGPException, IOException, SignatureException { + throws PGPException, IOException, SignatureException { String from = mKey.getUserId(mServer.getNetwork()); StringBuilder to = new StringBuilder(); @@ -212,8 +212,8 @@ private byte[] encryptData(String mime, CharSequence data) @SuppressWarnings("unchecked") @Override public void decryptText(byte[] encrypted, boolean verify, - StringBuilder out, StringBuilder mime, List errors) - throws GeneralSecurityException { + StringBuilder out, StringBuilder mime, List errors) + throws GeneralSecurityException { try { PGPObjectFactory pgpF = new PGPObjectFactory(encrypted); @@ -246,8 +246,8 @@ public void decryptText(byte[] encrypted, boolean verify, if (sKey == null) throw new DecryptException( - DECRYPT_EXCEPTION_PRIVATE_KEY_NOT_FOUND, - "Secret key for message not found."); + DECRYPT_EXCEPTION_PRIVATE_KEY_NOT_FOUND, + "Secret key for message not found."); InputStream clear = pbe.getDataStream(new BcPublicKeyDataDecryptorFactory(sKey)); @@ -265,10 +265,10 @@ public void decryptText(byte[] encrypted, boolean verify, PGPOnePassSignature ops = null; if (message instanceof PGPOnePassSignatureList) { - if (verify) { - ops = ((PGPOnePassSignatureList) message).get(0); - ops.init(new BcPGPContentVerifierBuilderProvider(), mSender); - } + if (verify) { + ops = ((PGPOnePassSignatureList) message).get(0); + ops.init(new BcPGPContentVerifierBuilderProvider(), mSender); + } message = pgpFact.nextObject(); } @@ -285,134 +285,134 @@ public void decryptText(byte[] encrypted, boolean verify, bout.write(ch); if (ops != null) - ops.update((byte) ch); + ops.update((byte) ch); } if (verify) { - if (ops == null) { - if (errors != null) - errors.add(new DecryptException( - DECRYPT_EXCEPTION_VERIFICATION_FAILED, - "No signature list found")); - } - - message = pgpFact.nextObject(); - - if (ops != null) { - - if (message instanceof PGPSignatureList) { - PGPSignature signature = ((PGPSignatureList) message).get(0); - if (!ops.verify(signature)) { - if (errors != null) - errors.add(new DecryptException( - DECRYPT_EXCEPTION_VERIFICATION_FAILED, - "Signature verification failed")); - } - } - - else { - if (errors != null) - errors.add(new DecryptException( - DECRYPT_EXCEPTION_INVALID_DATA, - "Invalid signature packet")); - } - - } + if (ops == null) { + if (errors != null) + errors.add(new DecryptException( + DECRYPT_EXCEPTION_VERIFICATION_FAILED, + "No signature list found")); + } + + message = pgpFact.nextObject(); + + if (ops != null) { + + if (message instanceof PGPSignatureList) { + PGPSignature signature = ((PGPSignatureList) message).get(0); + if (!ops.verify(signature)) { + if (errors != null) + errors.add(new DecryptException( + DECRYPT_EXCEPTION_VERIFICATION_FAILED, + "Signature verification failed")); + } + } + + else { + if (errors != null) + errors.add(new DecryptException( + DECRYPT_EXCEPTION_INVALID_DATA, + "Invalid signature packet")); + } + + } } // verify message integrity if (pbe.isIntegrityProtected()) { - try { - if (!pbe.verify()) { - // unrecoverable situation - throw new DecryptException( - DECRYPT_EXCEPTION_INTEGRITY_CHECK, - "Message integrity check failed"); - } - } - catch (PGPException e) { - // unrecoverable situation + try { + if (!pbe.verify()) { + // unrecoverable situation + throw new DecryptException( + DECRYPT_EXCEPTION_INTEGRITY_CHECK, + "Message integrity check failed"); + } + } + catch (PGPException e) { + // unrecoverable situation throw new DecryptException( - DECRYPT_EXCEPTION_INTEGRITY_CHECK, - e); - } + DECRYPT_EXCEPTION_INTEGRITY_CHECK, + e); + } } String data = bout.toString(); try { - // parse and check Message/CPIM - CPIMMessage msg = CPIMMessage.parse(data); + // parse and check Message/CPIM + CPIMMessage msg = CPIMMessage.parse(data); - if (mime != null) - mime.append(msg.getMime()); + if (mime != null) + mime.append(msg.getMime()); - msgData = msg.getBody(); + msgData = msg.getBody(); - if (verify) { - // verify CPIM headers, including mime type must be either text or xml + if (verify) { + // verify CPIM headers, including mime type must be either text or xml - // check mime type - if (!TextComponent.MIME_TYPE.equalsIgnoreCase(msg.getMime()) && - !XMPPUtils.XML_XMPP_TYPE.equalsIgnoreCase(msg.getMime())) - throw new DecryptException( - DECRYPT_EXCEPTION_INTEGRITY_CHECK, - "MIME type mismatch"); + // check mime type + if (!TextComponent.MIME_TYPE.equalsIgnoreCase(msg.getMime()) && + !XMPPUtils.XML_XMPP_TYPE.equalsIgnoreCase(msg.getMime())) + throw new DecryptException( + DECRYPT_EXCEPTION_INTEGRITY_CHECK, + "MIME type mismatch"); - // check that the recipient matches the full uid of the personal key - String myUid = mKey.getUserId(mServer.getNetwork()); - if (!myUid.equals(msg.getTo())) - throw new DecryptException( - DECRYPT_EXCEPTION_INVALID_RECIPIENT, - "Destination does not match personal key"); + // check that the recipient matches the full uid of the personal key + String myUid = mKey.getUserId(mServer.getNetwork()); + if (!myUid.equals(msg.getTo())) + throw new DecryptException( + DECRYPT_EXCEPTION_INVALID_RECIPIENT, + "Destination does not match personal key"); - // check that the sender matches the full uid of the sender's key - String otherUid = PGP.getUserId(mSender, mServer.getNetwork()); - if (!otherUid.equals(msg.getFrom())) - throw new DecryptException( - DECRYPT_EXCEPTION_INVALID_SENDER, - "Sender does not match sender's key"); + // check that the sender matches the full uid of the sender's key + String otherUid = PGP.getUserId(mSender, mServer.getNetwork()); + if (!otherUid.equals(msg.getFrom())) + throw new DecryptException( + DECRYPT_EXCEPTION_INVALID_SENDER, + "Sender does not match sender's key"); - // TODO check DateTime (possibly compare it with ) - } + // TODO check DateTime (possibly compare it with ) + } } catch (ParseException pe) { - // return data as-is - msgData = data; - - if (verify && errors != null) - // verification requested: invalid CPIM data - errors.add(new DecryptException( - DECRYPT_EXCEPTION_INVALID_DATA, pe, - "Verification was requested but no CPIM valid data was found")); + // return data as-is + msgData = data; + + if (verify && errors != null) + // verification requested: invalid CPIM data + errors.add(new DecryptException( + DECRYPT_EXCEPTION_INVALID_DATA, pe, + "Verification was requested but no CPIM valid data was found")); } catch (DecryptException de) { - if (errors != null) - errors.add(de); + if (errors != null) + errors.add(de); } finally { - if (msgData != null) - out.append(msgData); + if (msgData != null) + out.append(msgData); } } else { - // invalid or unknown packet + // invalid or unknown packet throw new DecryptException( - DECRYPT_EXCEPTION_INVALID_DATA, - "Unknown packet type " + message.getClass().getName()); + DECRYPT_EXCEPTION_INVALID_DATA, + "Unknown packet type " + message.getClass().getName()); } } else { - throw new DecryptException(DecryptException - .DECRYPT_EXCEPTION_INVALID_DATA, - "Compressed data packet expected"); + throw new DecryptException(DecryptException + .DECRYPT_EXCEPTION_INVALID_DATA, + "Compressed data packet expected"); } } @@ -420,11 +420,11 @@ public void decryptText(byte[] encrypted, boolean verify, // unrecoverable situations catch (IOException ioe) { - throw new DecryptException(DECRYPT_EXCEPTION_INVALID_DATA, ioe); + throw new DecryptException(DECRYPT_EXCEPTION_INVALID_DATA, ioe); } catch (PGPException pe) { - throw new DecryptException(DECRYPT_EXCEPTION_INVALID_DATA, pe); + throw new DecryptException(DECRYPT_EXCEPTION_INVALID_DATA, pe); } } diff --git a/src/org/kontalk/crypto/PersonalKey.java b/src/org/kontalk/crypto/PersonalKey.java index fd05075cb..82a4a9e5e 100644 --- a/src/org/kontalk/crypto/PersonalKey.java +++ b/src/org/kontalk/crypto/PersonalKey.java @@ -94,18 +94,18 @@ public X509Certificate getBridgeCertificate() { } public PrivateKey getBridgePrivateKey() throws PGPException { - return PGP.convertPrivateKey(mPair.signKey.getPrivateKey()); + return PGP.convertPrivateKey(mPair.signKey.getPrivateKey()); } public PGPPublicKeyRing getPublicKeyRing() throws IOException { - return new PGPPublicKeyRing(getEncodedPublicKeyRing(), new BcKeyFingerprintCalculator()); + return new PGPPublicKeyRing(getEncodedPublicKeyRing(), new BcKeyFingerprintCalculator()); } public byte[] getEncodedPublicKeyRing() throws IOException { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - mPair.signKey.getPublicKey().encode(out); - mPair.encryptKey.getPublicKey().encode(out); - return out.toByteArray(); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + mPair.signKey.getPublicKey().encode(out); + mPair.encryptKey.getPublicKey().encode(out); + return out.toByteArray(); } /** Returns the first user ID on the key that matches the given network. */ @@ -114,11 +114,11 @@ public String getUserId(String network) { } public String getFingerprint() { - return MessageUtils.bytesToHex(mPair.signKey.getPublicKey().getFingerprint()); + return MessageUtils.bytesToHex(mPair.signKey.getPublicKey().getFingerprint()); } public PGPKeyPairRing storeNetwork(String userId, String network, String name, String passphrase) throws PGPException { - // FIXME dummy values + // FIXME dummy values return store(name, userId + '@' + network, "NO COMMENT", passphrase); @@ -275,40 +275,40 @@ public PGPPublicKey signPublicKey(PGPPublicKey keyToBeSigned, String id) * @param store true to store the key in this object * @return the revoked master public key */ - public PGPPublicKey revoke(boolean store) - throws PGPException, IOException, SignatureException { + public PGPPublicKey revoke(boolean store) + throws PGPException, IOException, SignatureException { - PGPPublicKey revoked = PGP.revokeKey(mPair.signKey); + PGPPublicKey revoked = PGP.revokeKey(mPair.signKey); - if (store) - mPair.signKey = new PGPKeyPair(revoked, mPair.signKey.getPrivateKey()); + if (store) + mPair.signKey = new PGPKeyPair(revoked, mPair.signKey.getPrivateKey()); - return revoked; - } + return revoked; + } - /** Stores the public keyring to the system {@link AccountManager}. */ - public void updateAccountManager(Context context) - throws IOException, CertificateEncodingException, InvalidKeyException, - IllegalStateException, NoSuchAlgorithmException, SignatureException, - CertificateException, NoSuchProviderException, PGPException { + /** Stores the public keyring to the system {@link AccountManager}. */ + public void updateAccountManager(Context context) + throws IOException, CertificateEncodingException, InvalidKeyException, + IllegalStateException, NoSuchAlgorithmException, SignatureException, + CertificateException, NoSuchProviderException, PGPException { - AccountManager am = (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE); - Account account = Authenticator.getDefaultAccount(am); + AccountManager am = (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE); + Account account = Authenticator.getDefaultAccount(am); - if (account != null) { - PGPPublicKeyRing pubRing = getPublicKeyRing(); + if (account != null) { + PGPPublicKeyRing pubRing = getPublicKeyRing(); - // regenerate bridge certificate + // regenerate bridge certificate byte[] bridgeCertData = X509Bridge.createCertificate(pubRing, mPair.signKey.getPrivateKey(), null).getEncoded(); - byte[] publicKeyData = pubRing.getEncoded(); - - am.setUserData(account, Authenticator.DATA_PUBLICKEY, - Base64.encodeToString(publicKeyData, Base64.NO_WRAP)); - am.setUserData(account, Authenticator.DATA_BRIDGECERT, - Base64.encodeToString(bridgeCertData, Base64.NO_WRAP)); - } - } + byte[] publicKeyData = pubRing.getEncoded(); + + am.setUserData(account, Authenticator.DATA_PUBLICKEY, + Base64.encodeToString(publicKeyData, Base64.NO_WRAP)); + am.setUserData(account, Authenticator.DATA_BRIDGECERT, + Base64.encodeToString(bridgeCertData, Base64.NO_WRAP)); + } + } @Override public int describeContents() { diff --git a/src/org/kontalk/crypto/X509Bridge.java b/src/org/kontalk/crypto/X509Bridge.java index be0abfe0d..4440ea095 100644 --- a/src/org/kontalk/crypto/X509Bridge.java +++ b/src/org/kontalk/crypto/X509Bridge.java @@ -351,7 +351,7 @@ public static X509Certificate fromParcel(Parcel in) throws PGPException { } public static X509Certificate load(byte[] certData) - throws CertificateException, NoSuchProviderException { + throws CertificateException, NoSuchProviderException { CertificateFactory certFactory = CertificateFactory.getInstance("X.509", PGP.PROVIDER); InputStream in = new ByteArrayInputStream(certData); @@ -359,7 +359,7 @@ public static X509Certificate load(byte[] certData) } public static KeyStore exportCertificate(X509Certificate certificate, PrivateKey privateKey) - throws KeyStoreException, NoSuchProviderException, NoSuchAlgorithmException, CertificateException, IOException { + throws KeyStoreException, NoSuchProviderException, NoSuchAlgorithmException, CertificateException, IOException { KeyStore store = KeyStore.getInstance("PKCS12", PGP.PROVIDER); diff --git a/src/org/kontalk/data/Contact.java b/src/org/kontalk/data/Contact.java index fdd7e29e3..71f675130 100644 --- a/src/org/kontalk/data/Contact.java +++ b/src/org/kontalk/data/Contact.java @@ -94,7 +94,7 @@ public class Contact { private PGPPublicKeyRing mKeyRing; public interface ContactCallback { - public void avatarLoaded(Contact contact, Drawable avatar); + public void avatarLoaded(Contact contact, Drawable avatar); } /** @@ -198,32 +198,32 @@ public String getStatus() { } public boolean isBlocked() { - return mBlocked; + return mBlocked; } public PGPPublicKeyRing getPublicKeyRing() { - return mKeyRing; + return mKeyRing; } public void getAvatarAsync(final Context context, final ContactCallback callback) { - if (mAvatar != null) { - callback.avatarLoaded(this, mAvatar); - } - else { - // start async load - new Thread(new Runnable() { - public void run() { - try { - Drawable avatar = getAvatar(context, null); - callback.avatarLoaded(Contact.this, avatar); - } - catch (Exception e) { - // do not throw any exception while loading - Log.w(TAG, "error while loading avatar", e); - } - } - }).start(); - } + if (mAvatar != null) { + callback.avatarLoaded(this, mAvatar); + } + else { + // start async load + new Thread(new Runnable() { + public void run() { + try { + Drawable avatar = getAvatar(context, null); + callback.avatarLoaded(Contact.this, avatar); + } + catch (Exception e) { + // do not throw any exception while loading + Log.w(TAG, "error while loading avatar", e); + } + } + }).start(); + } } public synchronized Drawable getAvatar(Context context, Drawable defaultValue) { @@ -267,13 +267,13 @@ public static Contact fromUsersCursor(Context context, Cursor cursor) { c.mRegistered = registered; c.mStatus = status; try { - if (keyring != null) - c.mKeyRing = PGP.readPublicKeyring(keyring); - } + if (keyring != null) + c.mKeyRing = PGP.readPublicKeyring(keyring); + } catch (Exception e) { - // ignored for now - Log.w(TAG, "unable to load public keyring", e); - } + // ignored for now + Log.w(TAG, "unable to load public keyring", e); + } cache.put(hash, c); } @@ -336,13 +336,13 @@ private static Contact _findByUserId(Context context, String userId) { contact.mRegistered = registered; contact.mStatus = status; try { - if (keyring != null) - contact.mKeyRing = PGP.readPublicKeyring(keyring); - } + if (keyring != null) + contact.mKeyRing = PGP.readPublicKeyring(keyring); + } catch (Exception e) { - // ignored for now - Log.w(TAG, "unable to load public keyring", e); - } + // ignored for now + Log.w(TAG, "unable to load public keyring", e); + } return contact; } diff --git a/src/org/kontalk/data/Conversation.java b/src/org/kontalk/data/Conversation.java index 40c8c6ac4..555aefc05 100644 --- a/src/org/kontalk/data/Conversation.java +++ b/src/org/kontalk/data/Conversation.java @@ -152,8 +152,8 @@ public void setDate(long mDate) { } public String getMime() { - return mMime; - } + return mMime; + } public String getSubject() { return mSubject; @@ -190,7 +190,7 @@ public int getStatus() { } public boolean isEncrypted() { - return mEncrypted; + return mEncrypted; } public String getDraft() { @@ -198,7 +198,7 @@ public String getDraft() { } public int getRequestStatus() { - return mRequestStatus; + return mRequestStatus; } public String getNumberHint() { diff --git a/src/org/kontalk/message/Attachment.java b/src/org/kontalk/message/Attachment.java index 7b080f1b3..7bdb07bb9 100644 --- a/src/org/kontalk/message/Attachment.java +++ b/src/org/kontalk/message/Attachment.java @@ -29,36 +29,36 @@ */ public class Attachment { - private String mMime; - private File mPreviewFile; - private Uri mLocalUri; - private String mFetchUrl; - - public Attachment(String mime, File previewFile, Uri localUri, String fetchUrl) { - mMime = mime; - mPreviewFile = previewFile; - mLocalUri = localUri; - mFetchUrl = fetchUrl; - } - - public Attachment(String mime, String previewFile, String localUri, String fetchUrl) { - this(mime, new File(previewFile), Uri.parse(localUri), fetchUrl); - } - - public String getMime() { - return mMime; - } - - public File getPreviewFile() { - return mPreviewFile; - } - - public Uri getLocalUri() { - return mLocalUri; - } - - public String getFetchUrl() { - return mFetchUrl; - } + private String mMime; + private File mPreviewFile; + private Uri mLocalUri; + private String mFetchUrl; + + public Attachment(String mime, File previewFile, Uri localUri, String fetchUrl) { + mMime = mime; + mPreviewFile = previewFile; + mLocalUri = localUri; + mFetchUrl = fetchUrl; + } + + public Attachment(String mime, String previewFile, String localUri, String fetchUrl) { + this(mime, new File(previewFile), Uri.parse(localUri), fetchUrl); + } + + public String getMime() { + return mMime; + } + + public File getPreviewFile() { + return mPreviewFile; + } + + public Uri getLocalUri() { + return mLocalUri; + } + + public String getFetchUrl() { + return mFetchUrl; + } } diff --git a/src/org/kontalk/message/AttachmentComponent.java b/src/org/kontalk/message/AttachmentComponent.java index da51c38a3..ee1b39429 100644 --- a/src/org/kontalk/message/AttachmentComponent.java +++ b/src/org/kontalk/message/AttachmentComponent.java @@ -31,24 +31,24 @@ */ public abstract class AttachmentComponent extends MessageComponent { - public AttachmentComponent(String mime, File previewFile, Uri localUri, String fetchUrl, long length, boolean encrypted, int securityFlags) { - super(new Attachment(mime, previewFile, localUri, fetchUrl), length, encrypted, securityFlags); - } + public AttachmentComponent(String mime, File previewFile, Uri localUri, String fetchUrl, long length, boolean encrypted, int securityFlags) { + super(new Attachment(mime, previewFile, localUri, fetchUrl), length, encrypted, securityFlags); + } public String getMime() { - return mContent.getMime(); + return mContent.getMime(); } public File getPreviewFile() { - return mContent.getPreviewFile(); + return mContent.getPreviewFile(); } public Uri getLocalUri() { - return mContent.getLocalUri(); + return mContent.getLocalUri(); } public String getFetchUrl() { - return mContent.getFetchUrl(); + return mContent.getFetchUrl(); } protected abstract void populateFromCursor(Context context, Cursor cursor); diff --git a/src/org/kontalk/message/CompositeMessage.java b/src/org/kontalk/message/CompositeMessage.java index c605b8204..7389d294f 100644 --- a/src/org/kontalk/message/CompositeMessage.java +++ b/src/org/kontalk/message/CompositeMessage.java @@ -45,11 +45,11 @@ public class CompositeMessage { public static final int USERID_LENGTH = 40; public static final int USERID_LENGTH_RESOURCE = 48; - @SuppressWarnings("unchecked") - private static final Class[] TRY_COMPONENTS = new Class[] { - ImageComponent.class, - VCardComponent.class, - }; + @SuppressWarnings("unchecked") + private static final Class[] TRY_COMPONENTS = new Class[] { + ImageComponent.class, + VCardComponent.class, + }; private static final String[] MESSAGE_LIST_PROJECTION = { Messages._ID, @@ -127,7 +127,7 @@ public class CompositeMessage { /** Creates a new composite message. */ public CompositeMessage(Context context, String id, long timestamp, String sender, boolean encrypted, int securityFlags) { - this(); + this(); mContext = context; @@ -144,7 +144,7 @@ public CompositeMessage(Context context, String id, long timestamp, String sende /** Empty constructor for local use. */ private CompositeMessage() { - mComponents = new ArrayList>(); + mComponents = new ArrayList>(); } public String getId() { @@ -198,7 +198,7 @@ public int getStatus() { @Override public String toString() { - // FIXME include components + // FIXME include components return getClass().getSimpleName() + ": id=" + mId; } @@ -232,11 +232,11 @@ public void setSecurityFlags(int flags) { } public void addComponent(MessageComponent c) { - mComponents.add(c); + mComponents.add(c); } public void clearComponents() { - mComponents.clear(); + mComponents.clear(); } /** Returns the first component of the given type. */ @@ -250,7 +250,7 @@ public MessageComponent getComponent(Class> typ } public List> getComponents() { - return mComponents; + return mComponents; } private void populateFromCursor(Cursor c) { @@ -281,65 +281,65 @@ private void populateFromCursor(Cursor c) { // encrypted message - single raw encrypted component if (mEncrypted) { - RawComponent raw = new RawComponent(body, true, mSecurityFlags); - addComponent(raw); + RawComponent raw = new RawComponent(body, true, mSecurityFlags); + addComponent(raw); } else { - String mime = c.getString(COLUMN_BODY_MIME); + String mime = c.getString(COLUMN_BODY_MIME); - if (body != null) { + if (body != null) { - // text data - if (TextComponent.supportsMimeType(mime)) { - TextComponent txt = new TextComponent(new String(body)); - addComponent(txt); - } + // text data + if (TextComponent.supportsMimeType(mime)) { + TextComponent txt = new TextComponent(new String(body)); + addComponent(txt); + } - // unknown data - else { - RawComponent raw = new RawComponent(body, false, mSecurityFlags); - addComponent(raw); - } - } + // unknown data + else { + RawComponent raw = new RawComponent(body, false, mSecurityFlags); + addComponent(raw); + } + } - // attachment - String attMime = c.getString(COLUMN_ATTACHMENT_MIME); - if (attMime != null) { + // attachment + String attMime = c.getString(COLUMN_ATTACHMENT_MIME); + if (attMime != null) { - String attPreview = c.getString(COLUMN_ATTACHMENT_PREVIEW_PATH); - String attLocal = c.getString(COLUMN_ATTACHMENT_LOCAL_URI); - String attFetch = c.getString(COLUMN_ATTACHMENT_FETCH_URL); - long attLength = c.getLong(COLUMN_ATTACHMENT_LENGTH); - boolean attEncrypted = c.getInt(COLUMN_ATTACHMENT_ENCRYPTED) > 0; - int attSecurityFlags = c.getInt(COLUMN_ATTACHMENT_SECURITY_FLAGS); + String attPreview = c.getString(COLUMN_ATTACHMENT_PREVIEW_PATH); + String attLocal = c.getString(COLUMN_ATTACHMENT_LOCAL_URI); + String attFetch = c.getString(COLUMN_ATTACHMENT_FETCH_URL); + long attLength = c.getLong(COLUMN_ATTACHMENT_LENGTH); + boolean attEncrypted = c.getInt(COLUMN_ATTACHMENT_ENCRYPTED) > 0; + int attSecurityFlags = c.getInt(COLUMN_ATTACHMENT_SECURITY_FLAGS); - AttachmentComponent att = null; - File previewFile = (attPreview != null) ? new File(attPreview) : null; - Uri localUri = (attLocal != null) ? Uri.parse(attLocal) : null; + AttachmentComponent att = null; + File previewFile = (attPreview != null) ? new File(attPreview) : null; + Uri localUri = (attLocal != null) ? Uri.parse(attLocal) : null; - if (ImageComponent.supportsMimeType(attMime)) { - att = new ImageComponent(attMime, previewFile, - localUri, attFetch, attLength, - attEncrypted, attSecurityFlags); - att.populateFromCursor(mContext, c); - } + if (ImageComponent.supportsMimeType(attMime)) { + att = new ImageComponent(attMime, previewFile, + localUri, attFetch, attLength, + attEncrypted, attSecurityFlags); + att.populateFromCursor(mContext, c); + } - else if (VCardComponent.supportsMimeType(attMime)) { - att = new VCardComponent(previewFile, - localUri, attFetch, attLength, - attEncrypted, attSecurityFlags); - att.populateFromCursor(mContext, c); - } + else if (VCardComponent.supportsMimeType(attMime)) { + att = new VCardComponent(previewFile, + localUri, attFetch, attLength, + attEncrypted, attSecurityFlags); + att.populateFromCursor(mContext, c); + } - // TODO other type of attachments + // TODO other type of attachments - if (att != null) - addComponent(att); + if (att != null) + addComponent(att); - } + } } } @@ -361,9 +361,9 @@ protected void clear() { /** Builds an instance from a {@link Cursor} row. */ public static CompositeMessage fromCursor(Context context, Cursor cursor) { - CompositeMessage msg = new CompositeMessage(); - msg.populateFromCursor(cursor); - // TODO + CompositeMessage msg = new CompositeMessage(); + msg.populateFromCursor(cursor); + // TODO return msg; } @@ -377,27 +377,27 @@ public static void startQuery(AsyncQueryHandler handler, int token, long threadI /** A sample text content from class name and mime type. */ public static String getSampleTextContent(String mime) { - // TODO i18n - // FIXME using reflection BAD BAD BAD !!! - for (Class klass : TRY_COMPONENTS) { - Boolean supported = null; - try { - Method m = klass.getMethod("supportsMimeType", new Class[] { String.class }); - supported = (Boolean) m.invoke(klass, mime); - } - catch (Exception e) { - // ignored - } - - if (supported != null && supported.booleanValue()) { - String cname = klass.getSimpleName(); - return cname.substring(0, cname.length() - SUFFIX_LENGTH) + - ": " + mime; - } - } - - // no supporting component - return mime - return "Unknown: " + mime; + // TODO i18n + // FIXME using reflection BAD BAD BAD !!! + for (Class klass : TRY_COMPONENTS) { + Boolean supported = null; + try { + Method m = klass.getMethod("supportsMimeType", new Class[] { String.class }); + supported = (Boolean) m.invoke(klass, mime); + } + catch (Exception e) { + // ignored + } + + if (supported != null && supported.booleanValue()) { + String cname = klass.getSimpleName(); + return cname.substring(0, cname.length() - SUFFIX_LENGTH) + + ": " + mime; + } + } + + // no supporting component - return mime + return "Unknown: " + mime; } /** Still unused. diff --git a/src/org/kontalk/message/ImageComponent.java b/src/org/kontalk/message/ImageComponent.java index eb25d1153..f75ce3f1e 100644 --- a/src/org/kontalk/message/ImageComponent.java +++ b/src/org/kontalk/message/ImageComponent.java @@ -50,9 +50,9 @@ public class ImageComponent extends AttachmentComponent { private Bitmap mBitmap; - public ImageComponent(String mime, File previewFile, Uri localUri, String fetchUrl, long length, boolean encrypted, int securityFlags) { - super(mime, previewFile, localUri, fetchUrl, length, encrypted, securityFlags); - } + public ImageComponent(String mime, File previewFile, Uri localUri, String fetchUrl, long length, boolean encrypted, int securityFlags) { + super(mime, previewFile, localUri, fetchUrl, length, encrypted, securityFlags); + } public static boolean supportsMimeType(String mime) { for (int i = 0; i < MIME_TYPES.length; i++) @@ -76,12 +76,12 @@ private void loadPreview(File previewFile) throws IOException { } public Bitmap getBitmap() { - return mBitmap; - } + return mBitmap; + } /** FIXME not used yet */ public boolean isValidMedia(Context context) { - Uri localUri = mContent.getLocalUri(); + Uri localUri = mContent.getLocalUri(); if (localUri != null) { try { return (MediaStorage.getLength(context, localUri) == mLength); @@ -104,8 +104,8 @@ protected void populateFromCursor(Context context, Cursor c) { * generated on the fly from local_uri - if possible. */ - File previewFile = mContent.getPreviewFile(); - Uri localUri = mContent.getLocalUri(); + File previewFile = mContent.getPreviewFile(); + Uri localUri = mContent.getLocalUri(); try { // preview path if (previewFile != null) { diff --git a/src/org/kontalk/message/LegacyAbstractMessage.java b/src/org/kontalk/message/LegacyAbstractMessage.java index 7b4ffaf3f..a9d804b2b 100644 --- a/src/org/kontalk/message/LegacyAbstractMessage.java +++ b/src/org/kontalk/message/LegacyAbstractMessage.java @@ -359,7 +359,7 @@ protected void clear() { public abstract void recycle(); public static LegacyAbstractMessage fromCursor(Context context, Cursor cursor) { - // TODO + // TODO return null; } @@ -372,7 +372,7 @@ public static void startQuery(AsyncQueryHandler handler, int token, long threadI } public static String buildMediaFilename(LegacyAbstractMessage msg) { - // TODO + // TODO return null; } diff --git a/src/org/kontalk/message/LegacyPlainTextMessage.java b/src/org/kontalk/message/LegacyPlainTextMessage.java index 07695b026..b9786ce36 100644 --- a/src/org/kontalk/message/LegacyPlainTextMessage.java +++ b/src/org/kontalk/message/LegacyPlainTextMessage.java @@ -84,11 +84,11 @@ public byte[] getBinaryContent() { @Override public void decrypt(Coder coder) throws GeneralSecurityException { - /* + /* if (isEncrypted()) { - // FIXME ehm :) - StringBuilder clearText = new StringBuilder(); - coder.decryptText(content, true, clearText, null, null); + // FIXME ehm :) + StringBuilder clearText = new StringBuilder(); + coder.decryptText(content, true, clearText, null, null); content = clearText.toString().getBytes(); length = content.length; encrypted = false; @@ -119,7 +119,7 @@ public void recycle() { public static LegacyPlainTextMessage obtain(Context context) { synchronized (sPoolSync) { if (sPool != null) { - LegacyPlainTextMessage m = sPool; + LegacyPlainTextMessage m = sPool; sPool = m.next; m.next = null; sPoolSize--; diff --git a/src/org/kontalk/message/MessageComponent.java b/src/org/kontalk/message/MessageComponent.java index 81e9d123f..9fc93cd96 100644 --- a/src/org/kontalk/message/MessageComponent.java +++ b/src/org/kontalk/message/MessageComponent.java @@ -25,36 +25,36 @@ */ public abstract class MessageComponent { - protected T mContent; + protected T mContent; protected long mLength; - protected boolean mEncrypted; - protected int mSecurityFlags; - - public MessageComponent(T content, long length, boolean encrypted, int securityFlags) { - mContent = content; - mLength = length; - mEncrypted = encrypted; - mSecurityFlags = securityFlags; - } + protected boolean mEncrypted; + protected int mSecurityFlags; + + public MessageComponent(T content, long length, boolean encrypted, int securityFlags) { + mContent = content; + mLength = length; + mEncrypted = encrypted; + mSecurityFlags = securityFlags; + } - public T getContent() { - return mContent; - } + public T getContent() { + return mContent; + } - public void setContent(T content) { - this.mContent = content; - } + public void setContent(T content) { + this.mContent = content; + } - public long getLength() { + public long getLength() { return mLength; } - public boolean isEncrypted() { - return mEncrypted; - } + public boolean isEncrypted() { + return mEncrypted; + } - public int getSecurityFlags() { - return mSecurityFlags; - } + public int getSecurityFlags() { + return mSecurityFlags; + } } diff --git a/src/org/kontalk/message/RawComponent.java b/src/org/kontalk/message/RawComponent.java index f12642d28..94e5f13d0 100644 --- a/src/org/kontalk/message/RawComponent.java +++ b/src/org/kontalk/message/RawComponent.java @@ -26,8 +26,8 @@ */ public class RawComponent extends MessageComponent { - public RawComponent(byte[] text, boolean encrypted, int securityFlags) { - super(text, text.length, encrypted, securityFlags); - } + public RawComponent(byte[] text, boolean encrypted, int securityFlags) { + super(text, text.length, encrypted, securityFlags); + } } diff --git a/src/org/kontalk/message/TextComponent.java b/src/org/kontalk/message/TextComponent.java index 6549cb80d..85ac2a2fe 100644 --- a/src/org/kontalk/message/TextComponent.java +++ b/src/org/kontalk/message/TextComponent.java @@ -29,9 +29,9 @@ public class TextComponent extends MessageComponent { public static final String MIME_TYPE = "text/plain"; - public TextComponent(String text) { - super(text, text.length(), false, Coder.SECURITY_CLEARTEXT); - } + public TextComponent(String text) { + super(text, text.length(), false, Coder.SECURITY_CLEARTEXT); + } public static boolean supportsMimeType(String mime) { return MIME_TYPE.equalsIgnoreCase(mime); diff --git a/src/org/kontalk/message/VCardComponent.java b/src/org/kontalk/message/VCardComponent.java index eb0896cf6..023a433de 100644 --- a/src/org/kontalk/message/VCardComponent.java +++ b/src/org/kontalk/message/VCardComponent.java @@ -31,18 +31,18 @@ */ public class VCardComponent extends AttachmentComponent { - // actually the second one is not standard... + // actually the second one is not standard... public static final String[] MIME_TYPES = { "text/x-vcard", "text/vcard" }; public static final String MIME_TYPE = MIME_TYPES[0]; - public VCardComponent(File previewFile, Uri localUri, String fetchUrl, long length, boolean encrypted, int securityFlags) { - super(MIME_TYPES[0], previewFile, localUri, fetchUrl, length, encrypted, securityFlags); - } + public VCardComponent(File previewFile, Uri localUri, String fetchUrl, long length, boolean encrypted, int securityFlags) { + super(MIME_TYPES[0], previewFile, localUri, fetchUrl, length, encrypted, securityFlags); + } - @Override - protected void populateFromCursor(Context context, Cursor cursor) { - // TODO - } + @Override + protected void populateFromCursor(Context context, Cursor cursor) { + // TODO + } public static boolean supportsMimeType(String mime) { for (int i = 0; i < MIME_TYPES.length; i++) diff --git a/src/org/kontalk/provider/MessagesProvider.java b/src/org/kontalk/provider/MessagesProvider.java index 6b6cfd92e..a62ce5b43 100644 --- a/src/org/kontalk/provider/MessagesProvider.java +++ b/src/org/kontalk/provider/MessagesProvider.java @@ -254,7 +254,7 @@ private static class DatabaseHelper extends SQLiteOpenHelper { // copy contents of threads table "INSERT INTO " + TABLE_THREADS + "_new SELECT " + "_id, msg_id, peer, direction, count, unread, 'text/plain', content, timestamp, status_changed, status, 0, draft, 0" + - " FROM " + TABLE_THREADS, + " FROM " + TABLE_THREADS, // drop table messages "DROP TABLE " + TABLE_MESSAGES, // drop table threads @@ -274,16 +274,16 @@ private static class DatabaseHelper extends SQLiteOpenHelper { }; private static final String[] SCHEMA_V5_TO_V6 = { - // new messages counter: notified vs. unread - "ALTER TABLE " + TABLE_MESSAGES + " ADD COLUMN new INTEGER NOT NULL DEFAULT 0", - "ALTER TABLE " + TABLE_THREADS + " ADD COLUMN new INTEGER NOT NULL DEFAULT 0", - // recreate triggers for the new messages count + // new messages counter: notified vs. unread + "ALTER TABLE " + TABLE_MESSAGES + " ADD COLUMN new INTEGER NOT NULL DEFAULT 0", + "ALTER TABLE " + TABLE_THREADS + " ADD COLUMN new INTEGER NOT NULL DEFAULT 0", + // recreate triggers for the new messages count "DROP TRIGGER update_thread_on_insert", - TRIGGER_THREADS_INSERT_COUNT, - "DROP TRIGGER update_thread_on_update", - TRIGGER_THREADS_UPDATE_COUNT, - "DROP TRIGGER update_thread_on_delete", - TRIGGER_THREADS_DELETE_COUNT, + TRIGGER_THREADS_INSERT_COUNT, + "DROP TRIGGER update_thread_on_update", + TRIGGER_THREADS_UPDATE_COUNT, + "DROP TRIGGER update_thread_on_delete", + TRIGGER_THREADS_DELETE_COUNT, }; protected DatabaseHelper(Context context) { @@ -396,7 +396,7 @@ public Cursor query(Uri uri, String[] projection, String selection, @Override public synchronized Uri insert(Uri uri, ContentValues initialValues) { // only messages and requests virtual table can be inserted - int match = sUriMatcher.match(uri); + int match = sUriMatcher.match(uri); if (match != MESSAGES && match != REQUESTS) { throw new IllegalArgumentException("Unknown URI " + uri); } if (initialValues == null) { throw new IllegalArgumentException("No data"); } @@ -425,11 +425,11 @@ public synchronized Uri insert(Uri uri, ContentValues initialValues) { // request only - return conversation if (match == REQUESTS) - return ContentUris.withAppendedId(Conversations.CONTENT_URI, threadId); + return ContentUris.withAppendedId(Conversations.CONTENT_URI, threadId); // draft only - no uri else - return null; + return null; } @@ -476,7 +476,7 @@ public synchronized Uri insert(Uri uri, ContentValues initialValues) { if (rowId > 0) { // update fulltext table - byte[] content = values.getAsByteArray(Messages.BODY_CONTENT); + byte[] content = values.getAsByteArray(Messages.BODY_CONTENT); Boolean encrypted = values.getAsBoolean(Messages.ENCRYPTED); if (content != null && content.length > 0 && (encrypted == null || !encrypted.booleanValue())) { updateFulltext(db, rowId, threadId, content); @@ -511,22 +511,22 @@ private void setThreadContent(byte[] bodyContent, String bodyMime, String attach // use the binary content converted to string if (bodyContent == null) { - // try the attachment mime - mime = attachmentMime; - // no content - content = null; + // try the attachment mime + mime = attachmentMime; + // no content + content = null; } else { - // use body data if there is indeed a mime - if (bodyMime != null) { - mime = bodyMime; - content = new String(bodyContent); - } - // no mime and no data, nothing to do - else { - mime = null; - content = null; - } + // use body data if there is indeed a mime + if (bodyMime != null) { + mime = bodyMime; + content = new String(bodyContent); + } + // no mime and no data, nothing to do + else { + mime = null; + content = null; + } } values.put(Threads.CONTENT, content); @@ -553,35 +553,35 @@ private long updateThreads(SQLiteDatabase db, ContentValues initialValues, List< if (requestOnly) { - values.put(Threads.MESSAGE_ID, ""); - values.put(Threads.DIRECTION, Messages.DIRECTION_IN); - values.put(Threads.ENCRYPTED, false); - values.put(Threads.REQUEST_STATUS, Threads.REQUEST_WAITING); + values.put(Threads.MESSAGE_ID, ""); + values.put(Threads.DIRECTION, Messages.DIRECTION_IN); + values.put(Threads.ENCRYPTED, false); + values.put(Threads.REQUEST_STATUS, Threads.REQUEST_WAITING); } else { - values.put(Threads.MESSAGE_ID, initialValues.getAsString(Messages.MESSAGE_ID)); - values.put(Threads.DIRECTION, initialValues.getAsInteger(Messages.DIRECTION)); - values.put(Threads.ENCRYPTED, initialValues.getAsBoolean(Messages.ENCRYPTED)); - - if (initialValues.containsKey(Messages.STATUS)) - values.put(Threads.STATUS, initialValues.getAsInteger(Messages.STATUS)); - if (initialValues.containsKey(Messages.STATUS_CHANGED)) - values.put(Threads.STATUS_CHANGED, initialValues.getAsInteger(Messages.STATUS_CHANGED)); - // this column is an exception - if (initialValues.containsKey(Threads.DRAFT)) - values.put(Threads.DRAFT, initialValues.getAsString(Threads.DRAFT)); - - // unread column will be calculated by the trigger - - // thread content has a special behaviour - setThreadContent( - initialValues.getAsByteArray(Messages.BODY_CONTENT), - initialValues.getAsString(Messages.BODY_MIME), - initialValues.getAsString(Messages.ATTACHMENT_MIME), - values); + values.put(Threads.MESSAGE_ID, initialValues.getAsString(Messages.MESSAGE_ID)); + values.put(Threads.DIRECTION, initialValues.getAsInteger(Messages.DIRECTION)); + values.put(Threads.ENCRYPTED, initialValues.getAsBoolean(Messages.ENCRYPTED)); + + if (initialValues.containsKey(Messages.STATUS)) + values.put(Threads.STATUS, initialValues.getAsInteger(Messages.STATUS)); + if (initialValues.containsKey(Messages.STATUS_CHANGED)) + values.put(Threads.STATUS_CHANGED, initialValues.getAsInteger(Messages.STATUS_CHANGED)); + // this column is an exception + if (initialValues.containsKey(Threads.DRAFT)) + values.put(Threads.DRAFT, initialValues.getAsString(Threads.DRAFT)); + + // unread column will be calculated by the trigger + + // thread content has a special behaviour + setThreadContent( + initialValues.getAsByteArray(Messages.BODY_CONTENT), + initialValues.getAsString(Messages.BODY_MIME), + initialValues.getAsString(Messages.ATTACHMENT_MIME), + values); } // insert new thread @@ -597,9 +597,9 @@ private long updateThreads(SQLiteDatabase db, ContentValues initialValues, List< values.putNull(Threads.DRAFT); // remove other stuff coming from subscription request entry if (requestOnly) { - values.remove(Threads.MESSAGE_ID); - values.remove(Threads.ENCRYPTED); - values.remove(Threads.DIRECTION); + values.remove(Threads.MESSAGE_ID); + values.remove(Threads.ENCRYPTED); + values.remove(Threads.DIRECTION); } db.update(TABLE_THREADS, values, "peer = ?", new String[] { peer }); @@ -708,8 +708,8 @@ public synchronized int update(Uri uri, ContentValues values, String selection, // notify change only if rows are actually affected if (rows > 0) { - if (requestOnly) - uri = Threads.CONTENT_URI; + if (requestOnly) + uri = Threads.CONTENT_URI; notifications.add(uri); @@ -757,14 +757,14 @@ public synchronized int update(Uri uri, ContentValues values, String selection, } } - // delete thread if no messages are found + // delete thread if no messages are found else if (requestOnly) { Cursor th = db.query(TABLE_THREADS, new String[] { Threads.COUNT }, where, args, null, null, null); if (th.moveToFirst() && th.getInt(0) == 0) - db.delete(TABLE_THREADS, where, args); + db.delete(TABLE_THREADS, where, args); th.close(); diff --git a/src/org/kontalk/provider/MyMessages.java b/src/org/kontalk/provider/MyMessages.java index 0ea19e588..acdb7e46b 100644 --- a/src/org/kontalk/provider/MyMessages.java +++ b/src/org/kontalk/provider/MyMessages.java @@ -128,7 +128,7 @@ public static final class Conversations implements BaseColumns { /** Request represents a presence subscription request. */ public static final class Requests implements BaseColumns { public static final Uri CONTENT_URI = Uri - .parse("content://" + MessagesProvider.AUTHORITY + "/requests"); + .parse("content://" + MessagesProvider.AUTHORITY + "/requests"); } /** diff --git a/src/org/kontalk/provider/UsersProvider.java b/src/org/kontalk/provider/UsersProvider.java index 46cac2db7..7477dc5a5 100644 --- a/src/org/kontalk/provider/UsersProvider.java +++ b/src/org/kontalk/provider/UsersProvider.java @@ -342,14 +342,14 @@ public int update(Uri uri, ContentValues values, String selection, String[] sele int rc = db.update(offline ? TABLE_USERS_OFFLINE : TABLE_USERS, values, selection, selectionArgs); if (rc == 0) { - // insert new record - values.put(Users.HASH, selectionArgs[0]); - values.put(Users.NUMBER, selectionArgs[0]); - values.put(Users.DISPLAY_NAME, getContext().getString(R.string.peer_unknown)); - values.put(Users.REGISTERED, true); - - db.insert(offline ? TABLE_USERS_OFFLINE : TABLE_USERS, null, values); - return 1; + // insert new record + values.put(Users.HASH, selectionArgs[0]); + values.put(Users.NUMBER, selectionArgs[0]); + values.put(Users.DISPLAY_NAME, getContext().getString(R.string.peer_unknown)); + values.put(Users.REGISTERED, true); + + db.insert(offline ? TABLE_USERS_OFFLINE : TABLE_USERS, null, values); + return 1; } return rc; @@ -406,7 +406,7 @@ private int resync(boolean commit) { try { // query for phone numbers - // FIXME this might return null on some devices + // FIXME this might return null on some devices phones = cr.query(Phone.CONTENT_URI, new String[] { Phone.NUMBER, Phone.DISPLAY_NAME, Phone.LOOKUP_KEY, Phone.CONTACT_ID, RawContacts.ACCOUNT_TYPE }, // this will filter out RawContacts from Kontalk @@ -550,19 +550,19 @@ public Uri insert(Uri uri, ContentValues values) { long id = 0; try { - id = db.insertOrThrow(table, null, values); + id = db.insertOrThrow(table, null, values); } catch (SQLException e) { - String hash = values.getAsString(Users.HASH); - if (hash != null) { - // discard display_name if requested - boolean discardName = Boolean.parseBoolean(uri - .getQueryParameter(Users.DISCARD_NAME)); - if (discardName) - values.remove(Users.DISPLAY_NAME); - - db.update(table, values, Users.HASH + "=?", new String[] { hash }); - } + String hash = values.getAsString(Users.HASH); + if (hash != null) { + // discard display_name if requested + boolean discardName = Boolean.parseBoolean(uri + .getQueryParameter(Users.DISCARD_NAME)); + if (discardName) + values.remove(Users.DISPLAY_NAME); + + db.update(table, values, Users.HASH + "=?", new String[] { hash }); + } } if (id >= 0) @@ -600,8 +600,8 @@ public static Coder getEncryptCoder(Context context, EndpointServer server, Pers if (ring == null) throw new IllegalArgumentException("public key not found for user " + rcpt); - keys[i] = PGP.getEncryptionKey(ring); - if (keys[i] == null) + keys[i] = PGP.getEncryptionKey(ring); + if (keys[i] == null) throw new IllegalArgumentException("public key not found for user " + rcpt); } @@ -616,8 +616,8 @@ public static Coder getDecryptCoder(Context context, EndpointServer server, Pers if (ring == null) throw new IllegalArgumentException("public key not found for user " + rcpt); - PGPPublicKey senderKey = PGP.getMasterKey(ring); - if (senderKey == null) + PGPPublicKey senderKey = PGP.getMasterKey(ring); + if (senderKey == null) throw new IllegalArgumentException("public key not found for user " + rcpt); return new PGPCoder(server, key, senderKey); diff --git a/src/org/kontalk/service/DownloadService.java b/src/org/kontalk/service/DownloadService.java index fb953b29a..3b84b4956 100644 --- a/src/org/kontalk/service/DownloadService.java +++ b/src/org/kontalk/service/DownloadService.java @@ -123,20 +123,20 @@ protected void onHandleIntent(Intent intent) { mCanceled = false; if (mDownloadClient == null) { - PersonalKey key; - PrivateKey privateKey; - try { - key = ((Kontalk) getApplication()).getPersonalKey(); - privateKey = key.getBridgePrivateKey(); - } - catch (Exception e) { - // TODO i18n :) + PersonalKey key; + PrivateKey privateKey; + try { + key = ((Kontalk) getApplication()).getPersonalKey(); + privateKey = key.getBridgePrivateKey(); + } + catch (Exception e) { + // TODO i18n :) errorNotification("ERROR", "NAUGHTY BOY/GIRL!"); - return; - } + return; + } mDownloadClient = new ClientHTTPConnection(this, - privateKey, key.getBridgeCertificate()); + privateKey, key.getBridgeCertificate()); } try { diff --git a/src/org/kontalk/service/NetworkStateReceiver.java b/src/org/kontalk/service/NetworkStateReceiver.java index 4daa04305..ca9a588eb 100644 --- a/src/org/kontalk/service/NetworkStateReceiver.java +++ b/src/org/kontalk/service/NetworkStateReceiver.java @@ -72,9 +72,9 @@ else if (ConnectivityManager.CONNECTIVITY_ACTION.equals(action)) { Log.w(TAG, "network state changed!"); if (info.getType() == ConnectivityManager.TYPE_MOBILE && - !shouldReconnect(context)) { - Log.w(TAG, "throttling on mobile network"); - return; + !shouldReconnect(context)) { + Log.w(TAG, "throttling on mobile network"); + return; } switch (info.getState()) { @@ -102,23 +102,23 @@ else if (serviceAction == ACTION_STOP) private boolean shouldReconnect(Context context) { // check if some activity is holding to the message center - // or there is a pending push notification + // or there is a pending push notification if (((Kontalk) context.getApplicationContext()).hasReference() || - Preferences.getLastPushNotification(context) < 0) + Preferences.getLastPushNotification(context) < 0) return true; - long lastConnect = Preferences.getLastConnection(context); + long lastConnect = Preferences.getLastConnection(context); - // no last connection registered - if (lastConnect < 0) - return true; + // no last connection registered + if (lastConnect < 0) + return true; - long now = System.currentTimeMillis(); - long diff = Preferences.getWakeupTimeMillis(context, - MessageCenterService.MIN_WAKEUP_TIME, - MessageCenterService.DEFAULT_WAKEUP_TIME); + long now = System.currentTimeMillis(); + long diff = Preferences.getWakeupTimeMillis(context, + MessageCenterService.MIN_WAKEUP_TIME, + MessageCenterService.DEFAULT_WAKEUP_TIME); - return (now - lastConnect) >= diff; + return (now - lastConnect) >= diff; } } diff --git a/src/org/kontalk/service/XMPPConnectionHelper.java b/src/org/kontalk/service/XMPPConnectionHelper.java index 4d042e0bf..bd66a4464 100644 --- a/src/org/kontalk/service/XMPPConnectionHelper.java +++ b/src/org/kontalk/service/XMPPConnectionHelper.java @@ -114,15 +114,15 @@ public void run() { } public void connectOnce(PersonalKey key) throws XMPPException, SmackException, - PGPException, KeyStoreException, NoSuchProviderException, - NoSuchAlgorithmException, CertificateException, IOException { + PGPException, KeyStoreException, NoSuchProviderException, + NoSuchAlgorithmException, CertificateException, IOException { connectOnce(key, null); } private void connectOnce(PersonalKey key, String token) throws XMPPException, SmackException, PGPException, IOException, KeyStoreException, - NoSuchProviderException, NoSuchAlgorithmException, CertificateException { + NoSuchProviderException, NoSuchAlgorithmException, CertificateException { Log.d(TAG, "using server " + mServer.toString()); @@ -146,14 +146,14 @@ private void connectOnce(PersonalKey key, String token) throws XMPPException, // recreate connection if closed if (mConn == null || !mConn.isConnected()) { - KeyStore trustStore = null; - boolean acceptAnyCertificate = Preferences.getAcceptAnyCertificate(mContext); - if (!acceptAnyCertificate) - trustStore = InternalTrustStore.getTrustStore(mContext); + KeyStore trustStore = null; + boolean acceptAnyCertificate = Preferences.getAcceptAnyCertificate(mContext); + if (!acceptAnyCertificate) + trustStore = InternalTrustStore.getTrustStore(mContext); if (key == null) { mConn = new KontalkConnection(mServer, - acceptAnyCertificate, trustStore); + acceptAnyCertificate, trustStore); } else { @@ -231,15 +231,15 @@ public void connect() { // SASL: not-authorized if (ie instanceof SASLErrorException && ((SASLErrorException) ie) - .getSASLFailure().getSASLError() == SASLError.not_authorized && - mRetryCount >= MAX_AUTH_ERRORS) { + .getSASLFailure().getSASLError() == SASLError.not_authorized && + mRetryCount >= MAX_AUTH_ERRORS) { - if (mListener != null) { - mListener.authenticationFailed(); + if (mListener != null) { + mListener.authenticationFailed(); - // this ends here. - break; - } + // this ends here. + break; + } } if (mRetryEnabled) { diff --git a/src/org/kontalk/service/gcm/DefaultGcmListener.java b/src/org/kontalk/service/gcm/DefaultGcmListener.java index 87aca570a..d2312bde6 100644 --- a/src/org/kontalk/service/gcm/DefaultGcmListener.java +++ b/src/org/kontalk/service/gcm/DefaultGcmListener.java @@ -13,25 +13,25 @@ */ public class DefaultGcmListener implements GcmListener { - @Override - public void onRegistered(Context context, String registrationId) { + @Override + public void onRegistered(Context context, String registrationId) { Log.d(Kontalk.TAG, "registered to GCM - " + registrationId); MessageCenterService.registerPushNotifications(context, registrationId); - } + } - @Override - public void onUnregistered(Context context) { + @Override + public void onUnregistered(Context context) { Log.d(Kontalk.TAG, "unregistered from GCM"); MessageCenterService.registerPushNotifications(context, null); - } + } - @Override - public void onError(Context context, String errorId) { + @Override + public void onError(Context context, String errorId) { Log.w(Kontalk.TAG, "error registering to GCM service: " + errorId); - } + } @Override - public String getSenderId(Context context) { + public String getSenderId(Context context) { return MessageCenterService.getPushSenderId(); } diff --git a/src/org/kontalk/service/gcm/GcmBroadcastReceiver.java b/src/org/kontalk/service/gcm/GcmBroadcastReceiver.java index f9cb5bc32..84ea8c744 100644 --- a/src/org/kontalk/service/gcm/GcmBroadcastReceiver.java +++ b/src/org/kontalk/service/gcm/GcmBroadcastReceiver.java @@ -13,14 +13,14 @@ */ public class GcmBroadcastReceiver extends WakefulBroadcastReceiver { - @Override - public void onReceive(Context context, Intent intent) { - // Explicitly specify that GcmIntentService will handle the intent. + @Override + public void onReceive(Context context, Intent intent) { + // Explicitly specify that GcmIntentService will handle the intent. ComponentName comp = new ComponentName(context.getPackageName(), GcmIntentService.class.getName()); // Start the service, keeping the device awake while it is launching. startWakefulService(context, (intent.setComponent(comp))); setResultCode(Activity.RESULT_OK); - } + } } diff --git a/src/org/kontalk/service/gcm/GcmIntentService.java b/src/org/kontalk/service/gcm/GcmIntentService.java index d376d9620..c1009cd1b 100644 --- a/src/org/kontalk/service/gcm/GcmIntentService.java +++ b/src/org/kontalk/service/gcm/GcmIntentService.java @@ -22,7 +22,7 @@ */ public class GcmIntentService extends IntentService { - /** GCM message received from server. */ + /** GCM message received from server. */ private static final String ACTION_CHECK_MESSAGES = "org.kontalk.CHECK_MESSAGES"; /** Internal action for handling back-off. */ @@ -40,7 +40,7 @@ public GcmIntentService() { @Override protected void onHandleIntent(Intent intent) { - if (ACTION_RETRY.equals(intent.getAction())) { + if (ACTION_RETRY.equals(intent.getAction())) { String token = intent.getStringExtra(EXTRA_TOKEN); if (!TOKEN.equals(token)) { @@ -51,49 +51,49 @@ protected void onHandleIntent(Intent intent) { } GcmUtils.retry(this); - } + } - else { - Bundle extras = intent.getExtras(); - GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this); - // The getMessageType() intent parameter must be the intent you received - // in your BroadcastReceiver. - String messageType = gcm.getMessageType(intent); + else { + Bundle extras = intent.getExtras(); + GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this); + // The getMessageType() intent parameter must be the intent you received + // in your BroadcastReceiver. + String messageType = gcm.getMessageType(intent); - if (!extras.isEmpty()) { // has effect of unparcelling Bundle + if (!extras.isEmpty()) { // has effect of unparcelling Bundle - if (GoogleCloudMessaging. - MESSAGE_TYPE_MESSAGE.equals(messageType)) { + if (GoogleCloudMessaging. + MESSAGE_TYPE_MESSAGE.equals(messageType)) { - String dataAction = intent.getStringExtra("action"); - Log.v(Kontalk.TAG, "cloud message received: " + dataAction); + String dataAction = intent.getStringExtra("action"); + Log.v(Kontalk.TAG, "cloud message received: " + dataAction); - // new messages - start message center - if (ACTION_CHECK_MESSAGES.equals(dataAction)) { - // remember we just received a push notifications - // this means that there are really messages waiting for us - Preferences.setLastPushNotification(this, - System.currentTimeMillis()); + // new messages - start message center + if (ACTION_CHECK_MESSAGES.equals(dataAction)) { + // remember we just received a push notifications + // this means that there are really messages waiting for us + Preferences.setLastPushNotification(this, + System.currentTimeMillis()); - // start message center - MessageCenterService.start(getApplicationContext()); - } + // start message center + MessageCenterService.start(getApplicationContext()); + } - } - } - } + } + } + } // Release the wake lock provided by the WakefulBroadcastReceiver GcmBroadcastReceiver.completeWakefulIntent(intent); } static PendingIntent getRetryIntent(Context context) { - Intent retryIntent = new Intent(context.getApplicationContext(), GcmIntentService.class); - retryIntent.setAction(ACTION_RETRY); - retryIntent.putExtra(EXTRA_TOKEN, TOKEN); + Intent retryIntent = new Intent(context.getApplicationContext(), GcmIntentService.class); + retryIntent.setAction(ACTION_RETRY); + retryIntent.putExtra(EXTRA_TOKEN, TOKEN); - return PendingIntent.getService(context, - 0, retryIntent, 0); + return PendingIntent.getService(context, + 0, retryIntent, 0); } diff --git a/src/org/kontalk/service/gcm/GcmUtils.java b/src/org/kontalk/service/gcm/GcmUtils.java index f59b20aab..3959d4067 100644 --- a/src/org/kontalk/service/gcm/GcmUtils.java +++ b/src/org/kontalk/service/gcm/GcmUtils.java @@ -56,42 +56,42 @@ public class GcmUtils { /** The last used listener. */ private static GcmListener sListener; - private GcmUtils() { - } + private GcmUtils() { + } private static void ensureGcmInstance(Context context) { - if (sGcm == null) - sGcm = GoogleCloudMessaging.getInstance(context); + if (sGcm == null) + sGcm = GoogleCloudMessaging.getInstance(context); + } + + public static String getRegistrationId(Context context) { + final SharedPreferences prefs = getGCMPreferences(context); + String registrationId = prefs.getString(PROPERTY_REG_ID, ""); + if (registrationId == null || registrationId.length() == 0) { + Log.i(Kontalk.TAG, "Registration not found."); + return ""; + } + + // Check if app was updated; if so, it must clear the registration ID + // since the existing regID is not guaranteed to work with the new + // app version. + int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE); + int currentVersion = Kontalk.getVersionCode(context); + if (registeredVersion != currentVersion) { + Log.i(Kontalk.TAG, "App version changed."); + return ""; + } + return registrationId; } - public static String getRegistrationId(Context context) { - final SharedPreferences prefs = getGCMPreferences(context); - String registrationId = prefs.getString(PROPERTY_REG_ID, ""); - if (registrationId == null || registrationId.length() == 0) { - Log.i(Kontalk.TAG, "Registration not found."); - return ""; - } - - // Check if app was updated; if so, it must clear the registration ID - // since the existing regID is not guaranteed to work with the new - // app version. - int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE); - int currentVersion = Kontalk.getVersionCode(context); - if (registeredVersion != currentVersion) { - Log.i(Kontalk.TAG, "App version changed."); - return ""; - } - return registrationId; - } - - private static void storeRegistrationId(Context context, String regId) { - final SharedPreferences prefs = getGCMPreferences(context); - int appVersion = Kontalk.getVersionCode(context); - prefs.edit() - .putString(PROPERTY_REG_ID, regId) - .putInt(PROPERTY_APP_VERSION, appVersion) - .commit(); - } + private static void storeRegistrationId(Context context, String regId) { + final SharedPreferences prefs = getGCMPreferences(context); + int appVersion = Kontalk.getVersionCode(context); + prefs.edit() + .putString(PROPERTY_REG_ID, regId) + .putInt(PROPERTY_APP_VERSION, appVersion) + .commit(); + } /** * Sets whether the device was successfully registered in the server side. @@ -199,59 +199,59 @@ static void setBackoff(Context context, int backoff) { editor.commit(); } - public static void register(final GcmListener listener, final Context context, final String senderId) { - sListener = listener; - resetBackoff(context); + public static void register(final GcmListener listener, final Context context, final String senderId) { + sListener = listener; + resetBackoff(context); - new Thread(new Runnable() { - public void run() { + new Thread(new Runnable() { + public void run() { ensureGcmInstance(context); - try { - String regId = sGcm.register(senderId); + try { + String regId = sGcm.register(senderId); - // persist the regID - no need to register again. - storeRegistrationId(context, regId); + // persist the regID - no need to register again. + storeRegistrationId(context, regId); - // call the listener - listener.onRegistered(context, regId); + // call the listener + listener.onRegistered(context, regId); - } - catch (IOException e) { - listener.onError(context, e.toString()); - } - } - }).start(); - } + } + catch (IOException e) { + listener.onError(context, e.toString()); + } + } + }).start(); + } - public static void unregister(final GcmListener listener, final Context context) { - sListener = listener; - resetBackoff(context); + public static void unregister(final GcmListener listener, final Context context) { + sListener = listener; + resetBackoff(context); - new Thread(new Runnable() { - public void run() { + new Thread(new Runnable() { + public void run() { ensureGcmInstance(context); - try { - sGcm.unregister(); + try { + sGcm.unregister(); - // persist the regID - no need to register again. - storeRegistrationId(context, ""); + // persist the regID - no need to register again. + storeRegistrationId(context, ""); - // call the listener - listener.onUnregistered(context); + // call the listener + listener.onUnregistered(context); - } - catch (IOException e) { - listener.onError(context, e.toString()); + } + catch (IOException e) { + listener.onError(context, e.toString()); - retryOnError(context); - } - } - }).start(); - } + retryOnError(context); + } + } + }).start(); + } - static void retry(Context context) { + static void retry(Context context) { // retry last call if (isRegistered(context)) { unregister(sListener, context); @@ -259,7 +259,7 @@ static void retry(Context context) { register(sListener, context, sListener.getSenderId(context)); } - } + } public static boolean isRegistered(Context context) { return getRegistrationId(context).length() > 0; @@ -271,29 +271,29 @@ public static boolean isGcmAvailable(Context context) { } private static void retryOnError(Context context) { - int backoffTimeMs = getBackoff(context); - int nextAttempt = backoffTimeMs / 2 + sRandom.nextInt(backoffTimeMs); - Log.d(Kontalk.TAG, "Scheduling registration retry, backoff = " - + nextAttempt + " (" + backoffTimeMs + ")"); - - PendingIntent retryPendingIntent = GcmIntentService.getRetryIntent(context); - AlarmManager am = (AlarmManager) context - .getSystemService(Context.ALARM_SERVICE); - am.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() - + nextAttempt, retryPendingIntent); - - // Next retry should wait longer. - if (backoffTimeMs < MAX_BACKOFF_MS) { - setBackoff(context, backoffTimeMs * 2); - } + int backoffTimeMs = getBackoff(context); + int nextAttempt = backoffTimeMs / 2 + sRandom.nextInt(backoffTimeMs); + Log.d(Kontalk.TAG, "Scheduling registration retry, backoff = " + + nextAttempt + " (" + backoffTimeMs + ")"); + + PendingIntent retryPendingIntent = GcmIntentService.getRetryIntent(context); + AlarmManager am = (AlarmManager) context + .getSystemService(Context.ALARM_SERVICE); + am.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + + nextAttempt, retryPendingIntent); + + // Next retry should wait longer. + if (backoffTimeMs < MAX_BACKOFF_MS) { + setBackoff(context, backoffTimeMs * 2); + } } - private static SharedPreferences getGCMPreferences(Context context) { - // This sample app persists the registration ID in shared preferences, but - // how you store the regID in your app is up to you. - return context.getSharedPreferences(context.getPackageName() + ".gcm", - Context.MODE_PRIVATE); - } + private static SharedPreferences getGCMPreferences(Context context) { + // This sample app persists the registration ID in shared preferences, but + // how you store the regID in your app is up to you. + return context.getSharedPreferences(context.getPackageName() + ".gcm", + Context.MODE_PRIVATE); + } } diff --git a/src/org/kontalk/service/msgcenter/DiscoverInfoListener.java b/src/org/kontalk/service/msgcenter/DiscoverInfoListener.java index 56275535c..3bbb9046e 100644 --- a/src/org/kontalk/service/msgcenter/DiscoverInfoListener.java +++ b/src/org/kontalk/service/msgcenter/DiscoverInfoListener.java @@ -36,14 +36,14 @@ */ class DiscoverInfoListener extends MessageCenterPacketListener { - public DiscoverInfoListener(MessageCenterService instance) { - super(instance); - } + public DiscoverInfoListener(MessageCenterService instance) { + super(instance); + } @Override public void processPacket(Packet packet) { - XMPPConnection conn = getConnection(); - EndpointServer server = getServer(); + XMPPConnection conn = getConnection(); + EndpointServer server = getServer(); // we don't need this listener anymore conn.removePacketListener(this); diff --git a/src/org/kontalk/service/msgcenter/LastActivityListener.java b/src/org/kontalk/service/msgcenter/LastActivityListener.java index b18783933..6e5ba326e 100644 --- a/src/org/kontalk/service/msgcenter/LastActivityListener.java +++ b/src/org/kontalk/service/msgcenter/LastActivityListener.java @@ -42,11 +42,11 @@ */ class LastActivityListener extends MessageCenterPacketListener { - public LastActivityListener(MessageCenterService instance) { - super(instance); - } + public LastActivityListener(MessageCenterService instance) { + super(instance); + } - @Override + @Override public void processPacket(Packet packet) { LastActivity p = (LastActivity) packet; Intent i = new Intent(ACTION_LAST_ACTIVITY); diff --git a/src/org/kontalk/service/msgcenter/MessageCenterPacketListener.java b/src/org/kontalk/service/msgcenter/MessageCenterPacketListener.java index 51d1a4674..06d9dd001 100644 --- a/src/org/kontalk/service/msgcenter/MessageCenterPacketListener.java +++ b/src/org/kontalk/service/msgcenter/MessageCenterPacketListener.java @@ -43,144 +43,144 @@ */ abstract class MessageCenterPacketListener implements PacketListener { - private WeakReference mInstance; - - MessageCenterPacketListener(MessageCenterService instance) { - mInstance = new WeakReference(instance); - } - - protected MessageCenterService getInstance() { - return mInstance.get(); - } - - protected Context getContext() { - return mInstance.get(); - } - - protected Kontalk getApplication() { - return (Kontalk) mInstance.get().getApplicationContext(); - } - - protected KontalkConnection getConnection() { - MessageCenterService instance = mInstance.get(); - return (instance != null) ? instance.mConnection : null; - } - - protected EndpointServer getServer() { - MessageCenterService instance = mInstance.get(); - return (instance != null) ? instance.mServer : null; - } - - protected String getMyUsername() { - MessageCenterService instance = mInstance.get(); - return (instance != null) ? instance.mMyUsername : null; - } - - protected void sendBroadcast(Intent intent) { - MessageCenterService instance = mInstance.get(); - if (instance != null) - instance.mLocalBroadcastManager.sendBroadcast(intent); - } - - protected void registerReceiver(BroadcastReceiver receiver, IntentFilter filter) { - MessageCenterService instance = mInstance.get(); - if (instance != null) - instance.mLocalBroadcastManager.registerReceiver(receiver, filter); - } - - protected void unregisterReceiver(BroadcastReceiver receiver) { - MessageCenterService instance = mInstance.get(); - if (instance != null) - instance.mLocalBroadcastManager.unregisterReceiver(receiver); - } - - protected void sendPacket(Packet packet) { - MessageCenterService instance = mInstance.get(); - if (instance != null) - instance.sendPacket(packet); - } - - protected void sendPacket(Packet packet, boolean bumpIdle) { - MessageCenterService instance = mInstance.get(); - if (instance != null) - instance.sendPacket(packet, bumpIdle); - } - - protected void initUploadServices() { - MessageCenterService instance = mInstance.get(); - if (instance != null) { - if (instance.mUploadServices == null) - instance.mUploadServices = new HashMap(); - else - instance.mUploadServices.clear(); - } - } - - protected void setUploadService(String name, String url) { - MessageCenterService instance = mInstance.get(); - if (instance != null) - instance.mUploadServices.put(name, url); - } + private WeakReference mInstance; + + MessageCenterPacketListener(MessageCenterService instance) { + mInstance = new WeakReference(instance); + } + + protected MessageCenterService getInstance() { + return mInstance.get(); + } + + protected Context getContext() { + return mInstance.get(); + } + + protected Kontalk getApplication() { + return (Kontalk) mInstance.get().getApplicationContext(); + } + + protected KontalkConnection getConnection() { + MessageCenterService instance = mInstance.get(); + return (instance != null) ? instance.mConnection : null; + } + + protected EndpointServer getServer() { + MessageCenterService instance = mInstance.get(); + return (instance != null) ? instance.mServer : null; + } + + protected String getMyUsername() { + MessageCenterService instance = mInstance.get(); + return (instance != null) ? instance.mMyUsername : null; + } + + protected void sendBroadcast(Intent intent) { + MessageCenterService instance = mInstance.get(); + if (instance != null) + instance.mLocalBroadcastManager.sendBroadcast(intent); + } + + protected void registerReceiver(BroadcastReceiver receiver, IntentFilter filter) { + MessageCenterService instance = mInstance.get(); + if (instance != null) + instance.mLocalBroadcastManager.registerReceiver(receiver, filter); + } + + protected void unregisterReceiver(BroadcastReceiver receiver) { + MessageCenterService instance = mInstance.get(); + if (instance != null) + instance.mLocalBroadcastManager.unregisterReceiver(receiver); + } + + protected void sendPacket(Packet packet) { + MessageCenterService instance = mInstance.get(); + if (instance != null) + instance.sendPacket(packet); + } + + protected void sendPacket(Packet packet, boolean bumpIdle) { + MessageCenterService instance = mInstance.get(); + if (instance != null) + instance.sendPacket(packet, bumpIdle); + } + + protected void initUploadServices() { + MessageCenterService instance = mInstance.get(); + if (instance != null) { + if (instance.mUploadServices == null) + instance.mUploadServices = new HashMap(); + else + instance.mUploadServices.clear(); + } + } + + protected void setUploadService(String name, String url) { + MessageCenterService instance = mInstance.get(); + if (instance != null) + instance.mUploadServices.put(name, url); + } protected void resendPendingMessages(boolean retrying) { - MessageCenterService instance = mInstance.get(); - if (instance != null) - instance.resendPendingMessages(retrying); + MessageCenterService instance = mInstance.get(); + if (instance != null) + instance.resendPendingMessages(retrying); } protected boolean isPushNotificationsEnabled() { - MessageCenterService instance = mInstance.get(); - return (instance != null) ? instance.mPushNotifications : false; + MessageCenterService instance = mInstance.get(); + return (instance != null) ? instance.mPushNotifications : false; } protected void setPushSenderId(String senderId) { - MessageCenterService.mPushSenderId = senderId; + MessageCenterService.mPushSenderId = senderId; } protected GcmListener getGcmListener() { - return MessageCenterService.sGcmListener; + return MessageCenterService.sGcmListener; } protected void startPushRegistrationCycle() { - MessageCenterService instance = mInstance.get(); - if (instance != null) - instance.mPushRegistrationCycle = true; + MessageCenterService instance = mInstance.get(); + if (instance != null) + instance.mPushRegistrationCycle = true; } protected void gcmRegister() { - MessageCenterService instance = mInstance.get(); - if (instance != null) - instance.gcmRegister(); + MessageCenterService instance = mInstance.get(); + if (instance != null) + instance.gcmRegister(); } protected Map getWaitingReceiptList() { - MessageCenterService instance = mInstance.get(); - return (instance != null) ? instance.mWaitingReceipt : null; + MessageCenterService instance = mInstance.get(); + return (instance != null) ? instance.mWaitingReceipt : null; } protected Uri incoming(CompositeMessage msg) { - MessageCenterService instance = mInstance.get(); - if (instance != null) - return instance.incoming(msg); + MessageCenterService instance = mInstance.get(); + if (instance != null) + return instance.incoming(msg); - return null; + return null; } protected IdleConnectionHandler getIdleHandler() { - MessageCenterService instance = mInstance.get(); - return (instance != null) ? instance.mIdleHandler: null; + MessageCenterService instance = mInstance.get(); + return (instance != null) ? instance.mIdleHandler: null; } protected void runOnUiThread(Runnable action) { - MessageCenterService instance = mInstance.get(); - if (instance != null) - instance.mHandler.post(action); + MessageCenterService instance = mInstance.get(); + if (instance != null) + instance.mHandler.post(action); } protected void endKeyPairRegeneration() { - MessageCenterService instance = mInstance.get(); - if (instance != null) - instance.endKeyPairRegeneration(); + MessageCenterService instance = mInstance.get(); + if (instance != null) + instance.endKeyPairRegeneration(); } } diff --git a/src/org/kontalk/service/msgcenter/MessageCenterService.java b/src/org/kontalk/service/msgcenter/MessageCenterService.java index be6a7b75e..b689e2940 100644 --- a/src/org/kontalk/service/msgcenter/MessageCenterService.java +++ b/src/org/kontalk/service/msgcenter/MessageCenterService.java @@ -267,7 +267,7 @@ public class MessageCenterService extends Service implements ConnectionHelperLis /** Flag marking a currently ongoing GCM registration cycle (unregister/register) */ boolean mPushRegistrationCycle; - private WakeLock mWakeLock; // created in onCreate + private WakeLock mWakeLock; // created in onCreate LocalBroadcastManager mLocalBroadcastManager; // created in onCreate /** Cached last used server. */ @@ -333,9 +333,9 @@ public void handleMessage(Message msg) { private boolean handleMessage(MessageCenterService service, Message msg) { if (msg.what == MSG_IDLE) { - // push notifications unavailable: set up an alarm for next time + // push notifications unavailable: set up an alarm for next time if (service.mPushRegistrationId == null) { - setWakeupAlarm(service); + setWakeupAlarm(service); } Log.d(TAG, "shutting down message center due to inactivity"); @@ -361,7 +361,7 @@ public void reset() { // zero means no idle (keep-alive forever) if (time > 0) - sendMessageDelayed(obtainMessage(MSG_IDLE), time); + sendMessageDelayed(obtainMessage(MSG_IDLE), time); } } @@ -698,9 +698,9 @@ else if (ACTION_LAST_ACTIVITY.equals(action)) { } else if (ACTION_SUBSCRIBED.equals(action)) { - if (canConnect && isConnected) { + if (canConnect && isConnected) { - String to; + String to; String toUserid = intent.getStringExtra(EXTRA_TO_USERID); if (toUserid != null) to = MessageUtils.toJID(toUserid, mServer.getNetwork()); @@ -709,16 +709,16 @@ else if (ACTION_SUBSCRIBED.equals(action)) { // FIXME taking toUserid for granted sendSubscriptionReply(toUserid, - intent.getStringExtra(EXTRA_PACKET_ID), - intent.getIntExtra(EXTRA_PRIVACY, PRIVACY_ACCEPT)); - } + intent.getStringExtra(EXTRA_PACKET_ID), + intent.getIntExtra(EXTRA_PRIVACY, PRIVACY_ACCEPT)); + } } else if (ACTION_RETRY.equals(action)) { - Uri msgUri = intent.getParcelableExtra(EXTRA_MESSAGE); + Uri msgUri = intent.getParcelableExtra(EXTRA_MESSAGE); - boolean encrypted = Preferences.getEncryptionEnabled(this); + boolean encrypted = Preferences.getEncryptionEnabled(this); ContentValues values = new ContentValues(2); values.put(Messages.STATUS, Messages.STATUS_SENDING); @@ -727,14 +727,14 @@ else if (ACTION_RETRY.equals(action)) { // FIXME shouldn't we resend just the above message? - // already connected: resend pending messages - if (isConnected) - resendPendingMessages(false); + // already connected: resend pending messages + if (isConnected) + resendPendingMessages(false); } else if (ACTION_BLOCKLIST.equals(action)) { - if (isConnected) - requestBlocklist(); + if (isConnected) + requestBlocklist(); } else { @@ -791,8 +791,8 @@ public void connectionClosedOnError(Exception error) { @Override public void authenticationFailed() { - // fire up a notification explaining the situation - MessagingNotification.authenticationError(this); + // fire up a notification explaining the situation + MessagingNotification.authenticationError(this); } @Override @@ -883,7 +883,7 @@ private void broadcast(String action) { private void broadcast(String action, String extraName, String extraValue) { Intent i = new Intent(action); if (extraName != null) - i.putExtra(extraName, extraValue); + i.putExtra(extraName, extraValue); mLocalBroadcastManager.sendBroadcast(i); } @@ -1080,35 +1080,35 @@ private void sendPendingSubscriptionReplies() { private void sendSubscriptionReply(String userId, String packetId, int action) { - if (action == PRIVACY_ACCEPT) { + if (action == PRIVACY_ACCEPT) { String to = MessageUtils.toJID(userId, mServer.getNetwork()); - // standard response: subscribed - Presence p = new Presence(Presence.Type.subscribed); + // standard response: subscribed + Presence p = new Presence(Presence.Type.subscribed); - p.setPacketID(packetId); - p.setTo(to); + p.setPacketID(packetId); + p.setTo(to); - // send the subscribed response - sendPacket(p); + // send the subscribed response + sendPacket(p); - // send a subscription request anyway - p = new Presence(Presence.Type.subscribe); - p.setTo(to); + // send a subscription request anyway + p = new Presence(Presence.Type.subscribe); + p.setTo(to); - sendPacket(p); - } + sendPacket(p); + } - else if (action == PRIVACY_BLOCK || action == PRIVACY_UNBLOCK) { - sendPrivacyListCommand(userId, action); - } + else if (action == PRIVACY_BLOCK || action == PRIVACY_UNBLOCK) { + sendPrivacyListCommand(userId, action); + } - // clear the request status - ContentValues values = new ContentValues(1); - values.put(Threads.REQUEST_STATUS, Threads.REQUEST_NONE); + // clear the request status + ContentValues values = new ContentValues(1); + values.put(Threads.REQUEST_STATUS, Threads.REQUEST_NONE); - getContentResolver().update(Requests.CONTENT_URI, - values, CommonColumns.PEER + "=?", new String[] { userId }); + getContentResolver().update(Requests.CONTENT_URI, + values, CommonColumns.PEER + "=?", new String[] { userId }); } private void sendPrivacyListCommand(final String userId, final int action) { @@ -1144,8 +1144,8 @@ public void processPacket(Packet packet) { // broadcast result broadcast(action == PRIVACY_BLOCK ? - ACTION_BLOCKED : ACTION_UNBLOCKED, - EXTRA_FROM_USERID, userId); + ACTION_BLOCKED : ACTION_UNBLOCKED, + EXTRA_FROM_USERID, userId); } } @@ -1157,35 +1157,35 @@ public void processPacket(Packet packet) { } private void requestBlocklist() { - Packet p = BlockingCommand.blocklist(); - String packetId = p.getPacketID(); + Packet p = BlockingCommand.blocklist(); + String packetId = p.getPacketID(); - // listen for response (TODO cache the listener, it shouldn't change) - PacketFilter idFilter = new PacketIDFilter(packetId); - mConnection.addPacketListener(new PacketListener() { - public void processPacket(Packet packet) { - // we don't need this listener anymore - mConnection.removePacketListener(this); + // listen for response (TODO cache the listener, it shouldn't change) + PacketFilter idFilter = new PacketIDFilter(packetId); + mConnection.addPacketListener(new PacketListener() { + public void processPacket(Packet packet) { + // we don't need this listener anymore + mConnection.removePacketListener(this); - if (packet instanceof BlockingCommand) { - BlockingCommand blocklist = (BlockingCommand) packet; + if (packet instanceof BlockingCommand) { + BlockingCommand blocklist = (BlockingCommand) packet; - Intent i = new Intent(ACTION_BLOCKLIST); + Intent i = new Intent(ACTION_BLOCKLIST); - List _list = blocklist.getItems(); - if (_list != null) { - String[] list = new String[_list.size()]; - i.putExtra(EXTRA_BLOCKLIST, _list.toArray(list)); - } + List _list = blocklist.getItems(); + if (_list != null) { + String[] list = new String[_list.size()]; + i.putExtra(EXTRA_BLOCKLIST, _list.toArray(list)); + } - Log.v(TAG, "broadcasting blocklist: " + i); - mLocalBroadcastManager.sendBroadcast(i); - } + Log.v(TAG, "broadcasting blocklist: " + i); + mLocalBroadcastManager.sendBroadcast(i); + } - } - }, idFilter); + } + }, idFilter); - sendPacket(p); + sendPacket(p); } private void sendMessage(Bundle data) { @@ -1250,7 +1250,7 @@ private void sendMessage(Bundle data) { String body = data.getString("org.kontalk.message.body"); if (body != null) - m.setBody(body); + m.setBody(body); boolean encrypt = data.getBoolean("org.kontalk.message.encrypt"); String fetchUrl = data.getString("org.kontalk.message.fetch.url"); @@ -1295,24 +1295,24 @@ private void sendMessage(Bundle data) { Coder coder = UsersProvider.getEncryptCoder(this, mServer, key, new String[] { to }); if (coder != null) { - // no extensions, create a simple text version to save space - if (m.getExtensions().size() == 0) { + // no extensions, create a simple text version to save space + if (m.getExtensions().size() == 0) { toMessage = coder.encryptText(body); - } + } - // some extension, encrypt whole stanza just to be sure - else { - toMessage = coder.encryptStanza(m.toXML()); - } + // some extension, encrypt whole stanza just to be sure + else { + toMessage = coder.encryptStanza(m.toXML()); + } - org.jivesoftware.smack.packet.Message encMsg = - new org.jivesoftware.smack.packet.Message(m.getTo(), - m.getType()); + org.jivesoftware.smack.packet.Message encMsg = + new org.jivesoftware.smack.packet.Message(m.getTo(), + m.getType()); - encMsg.setPacketID(m.getPacketID()); - encMsg.addExtension(new E2EEncryption(toMessage)); + encMsg.setPacketID(m.getPacketID()); + encMsg.addExtension(new E2EEncryption(toMessage)); - m = encMsg; + m = encMsg; } } @@ -1320,43 +1320,43 @@ private void sendMessage(Bundle data) { // FIXME notify just once per session (store in Kontalk instance?) catch (PGPException pgpe) { - // warn user: message will be sent cleartext - if (to.equalsIgnoreCase(MessagingNotification.getPaused())) { - Toast.makeText(this, R.string.warn_no_personal_key, - Toast.LENGTH_LONG).show(); - } + // warn user: message will be sent cleartext + if (to.equalsIgnoreCase(MessagingNotification.getPaused())) { + Toast.makeText(this, R.string.warn_no_personal_key, + Toast.LENGTH_LONG).show(); + } } catch (IOException io) { - // warn user: message will be sent cleartext - if (to.equalsIgnoreCase(MessagingNotification.getPaused())) { - Toast.makeText(this, R.string.warn_no_personal_key, - Toast.LENGTH_LONG).show(); - } + // warn user: message will be sent cleartext + if (to.equalsIgnoreCase(MessagingNotification.getPaused())) { + Toast.makeText(this, R.string.warn_no_personal_key, + Toast.LENGTH_LONG).show(); + } } catch (IllegalArgumentException noPublicKey) { - // warn user: message will be sent cleartext - if (to.equalsIgnoreCase(MessagingNotification.getPaused())) { - Toast.makeText(this, R.string.warn_no_public_key, - Toast.LENGTH_LONG).show(); - } + // warn user: message will be sent cleartext + if (to.equalsIgnoreCase(MessagingNotification.getPaused())) { + Toast.makeText(this, R.string.warn_no_public_key, + Toast.LENGTH_LONG).show(); + } } catch (GeneralSecurityException e) { - // warn user: message will be sent cleartext - if (to.equalsIgnoreCase(MessagingNotification.getPaused())) { - Toast.makeText(this, R.string.warn_encryption_failed, - Toast.LENGTH_LONG).show(); - } + // warn user: message will be sent cleartext + if (to.equalsIgnoreCase(MessagingNotification.getPaused())) { + Toast.makeText(this, R.string.warn_encryption_failed, + Toast.LENGTH_LONG).show(); + } } if (toMessage == null) { - // message was not encrypted for some reason, mark it pending user review + // message was not encrypted for some reason, mark it pending user review ContentValues values = new ContentValues(1); values.put(Messages.STATUS, Messages.STATUS_PENDING); getContentResolver().update(ContentUris.withAppendedId - (Messages.CONTENT_URI, msgId), values, null, null); + (Messages.CONTENT_URI, msgId), values, null, null); // do not send the message return; @@ -1373,7 +1373,7 @@ private void sendMessage(Bundle data) { else { // add chat state if message is not a received receipt if (chatState != null) - m.addExtension(new ChatStateExtension(chatState)); + m.addExtension(new ChatStateExtension(chatState)); // standalone message: no receipt if (!data.getBoolean("org.kontalk.message.standalone", false)) @@ -1440,13 +1440,13 @@ private String getUploadService() { private void beginKeyPairRegeneration() { if (mKeyPairRegenerator == null) { - try { - mKeyPairRegenerator = new RegenerateKeyPairListener(this); - } - catch (Exception e) { - Log.e(TAG, "unable to initiate keypair regeneration", e); - // TODO warn user - } + try { + mKeyPairRegenerator = new RegenerateKeyPairListener(this); + } + catch (Exception e) { + Log.e(TAG, "unable to initiate keypair regeneration", e); + // TODO warn user + } } } @@ -1475,7 +1475,7 @@ private static boolean isOfflineMode(Context context) { } private static Intent getStartIntent(Context context) { - final Intent intent = new Intent(context, MessageCenterService.class); + final Intent intent = new Intent(context, MessageCenterService.class); EndpointServer server = Preferences.getEndpointServer(context); intent.putExtra(EndpointServer.class.getName(), server.toString()); return intent; @@ -1665,7 +1665,7 @@ public void setPushNotifications(boolean enabled) { void gcmRegister() { if (mPushSenderId != null) { - if (GcmUtils.isGcmAvailable(this)) { + if (GcmUtils.isGcmAvailable(this)) { // senderId will be given by serverinfo if any mPushRegistrationId = GcmUtils.getRegistrationId(this); if (TextUtils.isEmpty(mPushRegistrationId)) @@ -1700,19 +1700,19 @@ public static String getPushSenderId() { } public static void setWakeupAlarm(Context context) { - AlarmManager am = (AlarmManager) context - .getSystemService(Context.ALARM_SERVICE); + AlarmManager am = (AlarmManager) context + .getSystemService(Context.ALARM_SERVICE); - long delay = Preferences.getWakeupTimeMillis(context, - MIN_WAKEUP_TIME, DEFAULT_WAKEUP_TIME); + long delay = Preferences.getWakeupTimeMillis(context, + MIN_WAKEUP_TIME, DEFAULT_WAKEUP_TIME); - // start message center pending intent - PendingIntent pi = PendingIntent.getService(context - .getApplicationContext(), 0, getStartIntent(context), - PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT); + // start message center pending intent + PendingIntent pi = PendingIntent.getService(context + .getApplicationContext(), 0, getStartIntent(context), + PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT); - am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, - SystemClock.elapsedRealtime() + delay, pi); + am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, + SystemClock.elapsedRealtime() + delay, pi); } } diff --git a/src/org/kontalk/service/msgcenter/MessageListener.java b/src/org/kontalk/service/msgcenter/MessageListener.java index bd34e29c5..932156f9e 100644 --- a/src/org/kontalk/service/msgcenter/MessageListener.java +++ b/src/org/kontalk/service/msgcenter/MessageListener.java @@ -71,8 +71,8 @@ class MessageListener extends MessageCenterPacketListener { private static final String selectionIncoming = Messages.DIRECTION + "=" + Messages.DIRECTION_IN; public MessageListener(MessageCenterService instance) { - super(instance); - } + super(instance); + } @Override public void processPacket(Packet packet) { @@ -244,7 +244,7 @@ else if (ext instanceof AckServerReceipt) { PacketExtension _encrypted = m.getExtension(E2EEncryption.ELEMENT_NAME, E2EEncryption.NAMESPACE); if (_encrypted != null && _encrypted instanceof E2EEncryption) { - E2EEncryption mEnc = (E2EEncryption) _encrypted; + E2EEncryption mEnc = (E2EEncryption) _encrypted; byte[] encryptedData = mEnc.getData(); // encrypted message @@ -262,10 +262,10 @@ else if (ext instanceof AckServerReceipt) { catch (Exception exc) { Log.e(MessageCenterService.TAG, "decryption failed", exc); - // raw component for encrypted data - // reuse security flags + // raw component for encrypted data + // reuse security flags msg.clearComponents(); - msg.addComponent(new RawComponent(encryptedData, true, msg.getSecurityFlags())); + msg.addComponent(new RawComponent(encryptedData, true, msg.getSecurityFlags())); } } @@ -274,8 +274,8 @@ else if (ext instanceof AckServerReceipt) { else { // use message body - if (body != null) - msg.addComponent(new TextComponent(body)); + if (body != null) + msg.addComponent(new TextComponent(body)); } @@ -300,17 +300,17 @@ else if (ext instanceof AckServerReceipt) { String filename = null; if (ImageComponent.supportsMimeType(mime)) { - filename = ImageComponent.buildMediaFilename(msgId, previewMime); + filename = ImageComponent.buildMediaFilename(msgId, previewMime); } else if (VCardComponent.supportsMimeType(mime)) { - filename = VCardComponent.buildMediaFilename(msgId, previewMime); + filename = VCardComponent.buildMediaFilename(msgId, previewMime); } try { - if (filename != null) previewFile = - MediaStorage.writeInternalMedia(getContext(), - filename, preview.getContents()); + if (filename != null) previewFile = + MediaStorage.writeInternalMedia(getContext(), + filename, preview.getContents()); } catch (IOException e) { Log.w(MessageCenterService.TAG, "error storing thumbnail", e); @@ -321,27 +321,27 @@ else if (VCardComponent.supportsMimeType(mime)) { if (ImageComponent.supportsMimeType(mime)) { // cleartext only for now - attachment = new ImageComponent(mime, previewFile, null, fetchUrl, length, - false, Coder.SECURITY_CLEARTEXT); + attachment = new ImageComponent(mime, previewFile, null, fetchUrl, length, + false, Coder.SECURITY_CLEARTEXT); } else if (VCardComponent.supportsMimeType(mime)) { // cleartext only for now - attachment = new VCardComponent(previewFile, null, fetchUrl, length, - false, Coder.SECURITY_CLEARTEXT); + attachment = new VCardComponent(previewFile, null, fetchUrl, length, + false, Coder.SECURITY_CLEARTEXT); } // TODO other types if (attachment != null) - msg.addComponent(attachment); + msg.addComponent(attachment); // add a dummy body if none was found /* if (body == null) { - msg.addComponent(new TextComponent(CompositeMessage - .getSampleTextContent((Class>) - attachment.getClass(), mime))); + msg.addComponent(new TextComponent(CompositeMessage + .getSampleTextContent((Class>) + attachment.getClass(), mime))); } */ @@ -354,8 +354,8 @@ else if (VCardComponent.supportsMimeType(mime)) { // send ack :) ReceivedServerReceipt receipt = new ReceivedServerReceipt(msgId); org.jivesoftware.smack.packet.Message ack = - new org.jivesoftware.smack.packet.Message(from, - org.jivesoftware.smack.packet.Message.Type.chat); + new org.jivesoftware.smack.packet.Message(from, + org.jivesoftware.smack.packet.Message.Type.chat); ack.addExtension(receipt); if (msgUri != null) { diff --git a/src/org/kontalk/service/msgcenter/PingListener.java b/src/org/kontalk/service/msgcenter/PingListener.java index 92f169411..60de54283 100644 --- a/src/org/kontalk/service/msgcenter/PingListener.java +++ b/src/org/kontalk/service/msgcenter/PingListener.java @@ -28,10 +28,10 @@ class PingListener extends MessageCenterPacketListener { public PingListener(MessageCenterService instance) { - super(instance); - } + super(instance); + } - @Override + @Override public void processPacket(Packet packet) { sendPacket(IQ.createResultIQ((IQ) packet), false); } diff --git a/src/org/kontalk/service/msgcenter/PresenceListener.java b/src/org/kontalk/service/msgcenter/PresenceListener.java index d38f74968..8e95ab6c0 100644 --- a/src/org/kontalk/service/msgcenter/PresenceListener.java +++ b/src/org/kontalk/service/msgcenter/PresenceListener.java @@ -71,10 +71,10 @@ class PresenceListener extends MessageCenterPacketListener { public PresenceListener(MessageCenterService instance) { - super(instance); - } + super(instance); + } - private Packet createSubscribe(Presence p) { + private Packet createSubscribe(Presence p) { PacketExtension _pkey = p.getExtension(SubscribePublicKey.ELEMENT_NAME, SubscribePublicKey.NAMESPACE); try { @@ -89,7 +89,7 @@ private Packet createSubscribe(Presence p) { // store key to users table String userId = StringUtils.parseName(p.getFrom()); UsersProvider.setUserKey(getContext(), userId, - pkey.getKey(), fingerprint); + pkey.getKey(), fingerprint); } Presence p2 = new Presence(Presence.Type.subscribed); @@ -113,14 +113,14 @@ public void processPacket(Packet packet) { // presence subscription request if (p.getType() == Presence.Type.subscribe) { - handleSubscribe(p); + handleSubscribe(p); } // presence subscription response else if (p.getType() == Presence.Type.subscribed) { - handleSubscribed(p); + handleSubscribed(p); } @@ -132,7 +132,7 @@ else if (p.getType() == Presence.Type.unsubscribed) { else { - handlePresence(p); + handlePresence(p); } } @@ -142,34 +142,34 @@ else if (p.getType() == Presence.Type.unsubscribed) { } private void handleSubscribe(Presence p) - throws NotConnectedException, IOException, PGPException { + throws NotConnectedException, IOException, PGPException { - Context ctx = getContext(); + Context ctx = getContext(); - // auto-accept subscription - if (Preferences.getAutoAcceptSubscriptions(ctx)) { + // auto-accept subscription + if (Preferences.getAutoAcceptSubscriptions(ctx)) { Packet r = createSubscribe(p); if (r != null) getConnection().sendPacket(r); - } + } - // ask the user - else { + // ask the user + else { - /* - * Subscription procedure: - * 1. update (or insert) users table with the public key just received - * 2. update (or insert) threads table with a special subscription record - * 3. user will either accept or refuse - */ + /* + * Subscription procedure: + * 1. update (or insert) users table with the public key just received + * 2. update (or insert) threads table with a special subscription record + * 3. user will either accept or refuse + */ - String from = StringUtils.parseName(p.getFrom()); + String from = StringUtils.parseName(p.getFrom()); - // extract public key - String name = null, fingerprint = null; - byte[] publicKey = null; + // extract public key + String name = null, fingerprint = null; + byte[] publicKey = null; PacketExtension _pkey = p.getExtension(SubscribePublicKey.ELEMENT_NAME, SubscribePublicKey.NAMESPACE); if (_pkey instanceof SubscribePublicKey) { SubscribePublicKey pkey = (SubscribePublicKey) _pkey; @@ -177,55 +177,55 @@ private void handleSubscribe(Presence p) // extract the name from the uid PGPPublicKeyRing ring = PGP.readPublicKeyring(_publicKey); if (ring != null) { - PGPPublicKey pk = PGP.getMasterKey(ring); - if (pk != null) { - // set all parameters + PGPPublicKey pk = PGP.getMasterKey(ring); + if (pk != null) { + // set all parameters name = PGP.getUserId(pk, getServer().getNetwork()); fingerprint = PGP.getFingerprint(pk); publicKey = _publicKey; - } + } } } - ContentResolver cr = ctx.getContentResolver(); - ContentValues values = new ContentValues(4); - - // insert public key into the users table - values.put(Users.HASH, from); - values.put(Users.PUBLIC_KEY, publicKey); - values.put(Users.FINGERPRINT, fingerprint); - values.put(Users.DISPLAY_NAME, name); - cr.insert(Users.CONTENT_URI.buildUpon() - .appendQueryParameter(Users.DISCARD_NAME, "true") - .build(), values); - - // invalidate cache for this user - Contact.invalidate(from); - - // insert request into the database - values.clear(); - values.put(CommonColumns.PEER, from); - values.put(CommonColumns.TIMESTAMP, System.currentTimeMillis()); - cr.insert(Requests.CONTENT_URI, values); - - // fire up a notification - MessagingNotification.chatInvitation(ctx, from); - } + ContentResolver cr = ctx.getContentResolver(); + ContentValues values = new ContentValues(4); + + // insert public key into the users table + values.put(Users.HASH, from); + values.put(Users.PUBLIC_KEY, publicKey); + values.put(Users.FINGERPRINT, fingerprint); + values.put(Users.DISPLAY_NAME, name); + cr.insert(Users.CONTENT_URI.buildUpon() + .appendQueryParameter(Users.DISCARD_NAME, "true") + .build(), values); + + // invalidate cache for this user + Contact.invalidate(from); + + // insert request into the database + values.clear(); + values.put(CommonColumns.PEER, from); + values.put(CommonColumns.TIMESTAMP, System.currentTimeMillis()); + cr.insert(Requests.CONTENT_URI, values); + + // fire up a notification + MessagingNotification.chatInvitation(ctx, from); + } } private void handleSubscribed(Presence p) { - String from = StringUtils.parseName(p.getFrom()); + String from = StringUtils.parseName(p.getFrom()); - if (UsersProvider.getPublicKey(getContext(), from) == null) { - // public key not found - // assuming the user has allowed us, request it + if (UsersProvider.getPublicKey(getContext(), from) == null) { + // public key not found + // assuming the user has allowed us, request it VCard4 vcard = new VCard4(); vcard.setType(IQ.Type.GET); vcard.setTo(StringUtils.parseBareAddress(p.getFrom())); sendPacket(vcard); - } + } // send a broadcast Intent i = new Intent(ACTION_SUBSCRIBED); diff --git a/src/org/kontalk/service/msgcenter/PushDiscoverItemsListener.java b/src/org/kontalk/service/msgcenter/PushDiscoverItemsListener.java index fca1b7e0d..91d56b284 100644 --- a/src/org/kontalk/service/msgcenter/PushDiscoverItemsListener.java +++ b/src/org/kontalk/service/msgcenter/PushDiscoverItemsListener.java @@ -31,9 +31,9 @@ */ class PushDiscoverItemsListener extends MessageCenterPacketListener { - public PushDiscoverItemsListener(MessageCenterService instance) { - super(instance); - } + public PushDiscoverItemsListener(MessageCenterService instance) { + super(instance); + } @Override public void processPacket(Packet packet) { diff --git a/src/org/kontalk/service/msgcenter/RegenerateKeyPairListener.java b/src/org/kontalk/service/msgcenter/RegenerateKeyPairListener.java index 1b4318b0f..79307bc93 100644 --- a/src/org/kontalk/service/msgcenter/RegenerateKeyPairListener.java +++ b/src/org/kontalk/service/msgcenter/RegenerateKeyPairListener.java @@ -62,8 +62,8 @@ class RegenerateKeyPairListener extends MessageCenterPacketListener { private PGPPublicKey mRevoked; public RegenerateKeyPairListener(MessageCenterService instance) - throws CertificateException, SignatureException, PGPException, IOException { - super(instance); + throws CertificateException, SignatureException, PGPException, IOException { + super(instance); revokeCurrentKey(); setupKeyPairReceiver(); @@ -145,8 +145,8 @@ public void run(PersonalKey key) { // store the key try { - Context context = getContext(); - AccountManager am = (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE); + Context context = getContext(); + AccountManager am = (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE); Account acc = Authenticator.getDefaultAccount(am); String name = am.getUserData(acc, Authenticator.DATA_NAME); @@ -210,11 +210,11 @@ public void onReceive(Context context, Intent intent) { /** We do this here so if something goes wrong the old key is still valid. */ private void revokeCurrentKey() - throws CertificateException, PGPException, IOException, SignatureException { + throws CertificateException, PGPException, IOException, SignatureException { - PersonalKey oldKey = getApplication().getPersonalKey(); - if (oldKey != null) - mRevoked = oldKey.revoke(false); + PersonalKey oldKey = getApplication().getPersonalKey(); + if (oldKey != null) + mRevoked = oldKey.revoke(false); } @Override @@ -245,7 +245,7 @@ public void processPacket(Packet packet) { String passphrase = getApplication().getCachedPassphrase(); // TODO subjectAltName? bridgeCertData = X509Bridge.createCertificate(publicKeyData, - mKeyRing.secretKey.getSecretKey(), passphrase, null).getEncoded(); + mKeyRing.secretKey.getSecretKey(), passphrase, null).getEncoded(); } catch (Exception e) { Log.e(MessageCenterService.TAG, "error decoding key data", e); diff --git a/src/org/kontalk/service/msgcenter/RosterListener.java b/src/org/kontalk/service/msgcenter/RosterListener.java index 17ec80ca4..421a54b77 100644 --- a/src/org/kontalk/service/msgcenter/RosterListener.java +++ b/src/org/kontalk/service/msgcenter/RosterListener.java @@ -40,10 +40,10 @@ class RosterListener extends MessageCenterPacketListener { public RosterListener(MessageCenterService instance) { - super(instance); - } + super(instance); + } - @Override + @Override public void processPacket(Packet packet) { RosterPacket p = (RosterPacket) packet; Intent i = new Intent(ACTION_ROSTER); diff --git a/src/org/kontalk/service/msgcenter/UploadDiscoverItemsListener.java b/src/org/kontalk/service/msgcenter/UploadDiscoverItemsListener.java index 8e8ed6d1f..fd3b49cae 100644 --- a/src/org/kontalk/service/msgcenter/UploadDiscoverItemsListener.java +++ b/src/org/kontalk/service/msgcenter/UploadDiscoverItemsListener.java @@ -34,14 +34,14 @@ */ class UploadDiscoverItemsListener extends MessageCenterPacketListener { - public UploadDiscoverItemsListener(MessageCenterService instance) { - super(instance); - } + public UploadDiscoverItemsListener(MessageCenterService instance) { + super(instance); + } @Override public void processPacket(Packet packet) { - XMPPConnection conn = getConnection(); - EndpointServer server = getServer(); + XMPPConnection conn = getConnection(); + EndpointServer server = getServer(); // we don't need this listener anymore conn.removePacketListener(this); diff --git a/src/org/kontalk/service/msgcenter/UploadInfoListener.java b/src/org/kontalk/service/msgcenter/UploadInfoListener.java index efd2c7e85..6e664498a 100644 --- a/src/org/kontalk/service/msgcenter/UploadInfoListener.java +++ b/src/org/kontalk/service/msgcenter/UploadInfoListener.java @@ -29,9 +29,9 @@ */ class UploadInfoListener extends MessageCenterPacketListener { - public UploadInfoListener(MessageCenterService instance) { - super(instance); - } + public UploadInfoListener(MessageCenterService instance) { + super(instance); + } @Override public void processPacket(Packet packet) { @@ -42,7 +42,7 @@ public void processPacket(Packet packet) { String node = info.getNode(); setUploadService(node, info.getUri()); Log.v(MessageCenterService.TAG, "upload info received, node = " + - node + ", uri = " + info.getUri()); + node + ", uri = " + info.getUri()); // resend pending messages resendPendingMessages(true); diff --git a/src/org/kontalk/service/msgcenter/VCardListener.java b/src/org/kontalk/service/msgcenter/VCardListener.java index ac5612c7d..53f445a8e 100644 --- a/src/org/kontalk/service/msgcenter/VCardListener.java +++ b/src/org/kontalk/service/msgcenter/VCardListener.java @@ -47,10 +47,10 @@ class VCardListener extends MessageCenterPacketListener { public VCardListener(MessageCenterService instance) { - super(instance); - } + super(instance); + } - @Override + @Override public void processPacket(Packet packet) { VCard4 p = (VCard4) packet; @@ -64,44 +64,44 @@ public void processPacket(Packet packet) { if (_publicKey != null) { // FIXME always false LOL - if (myCard) { - byte[] bridgeCertData; - try { - PersonalKey key = getApplication().getPersonalKey(); - - // TODO subjectAltName? - bridgeCertData = X509Bridge.createCertificate(_publicKey, - key.getSignKeyPair().getPrivateKey(), null).getEncoded(); - } - catch (Exception e) { - Log.e(MessageCenterService.TAG, "error decoding key data", e); - bridgeCertData = null; - } - - if (bridgeCertData != null) { - // store key data in AccountManager - Authenticator.setDefaultPersonalKey(getContext(), - _publicKey, null, bridgeCertData); - // invalidate cached personal key - getApplication().invalidatePersonalKey(); - - Log.v(MessageCenterService.TAG, "personal key updated."); - } - } - - try { - String userId = StringUtils.parseName(p.getFrom()); - String fingerprint = PGP.getFingerprint(_publicKey); - UsersProvider.setUserKey(getContext(), userId, - _publicKey, fingerprint); - - // invalidate cache for this user - Contact.invalidate(userId); - } - catch (Exception e) { - // TODO warn user - Log.e(MessageCenterService.TAG, "unable to update user key", e); - } + if (myCard) { + byte[] bridgeCertData; + try { + PersonalKey key = getApplication().getPersonalKey(); + + // TODO subjectAltName? + bridgeCertData = X509Bridge.createCertificate(_publicKey, + key.getSignKeyPair().getPrivateKey(), null).getEncoded(); + } + catch (Exception e) { + Log.e(MessageCenterService.TAG, "error decoding key data", e); + bridgeCertData = null; + } + + if (bridgeCertData != null) { + // store key data in AccountManager + Authenticator.setDefaultPersonalKey(getContext(), + _publicKey, null, bridgeCertData); + // invalidate cached personal key + getApplication().invalidatePersonalKey(); + + Log.v(MessageCenterService.TAG, "personal key updated."); + } + } + + try { + String userId = StringUtils.parseName(p.getFrom()); + String fingerprint = PGP.getFingerprint(_publicKey); + UsersProvider.setUserKey(getContext(), userId, + _publicKey, fingerprint); + + // invalidate cache for this user + Contact.invalidate(userId); + } + catch (Exception e) { + // TODO warn user + Log.e(MessageCenterService.TAG, "unable to update user key", e); + } } } @@ -122,7 +122,7 @@ else if (p.getType() == IQ.Type.SET) { String userId = StringUtils.parseName(from); String hash = MessageUtils.sha1(getMyUsername()); if (userId.equalsIgnoreCase(hash)) - myCard = true; + myCard = true; b.append(userId); b.append(StringUtils.parseResource(from)); diff --git a/src/org/kontalk/sync/Syncer.java b/src/org/kontalk/sync/Syncer.java index 77cd4f1a8..52a1399a7 100644 --- a/src/org/kontalk/sync/Syncer.java +++ b/src/org/kontalk/sync/Syncer.java @@ -170,7 +170,7 @@ else if (MessageCenterService.ACTION_ROSTER.equals(action)) { // all presence data already received (WHATT???) if ((rosterCount == 0 || (presenceCount >= 0 && rosterCount >= presenceCount) || allPresenceReceived) - && blocklistReceived) + && blocklistReceived) finish(); } @@ -197,36 +197,36 @@ else if (MessageCenterService.ACTION_VCARD.equals(action)) { // done with presence data and blocklist if (rosterCount >= 0 && allPresenceReceived && - vCardCount >= presenceCount && blocklistReceived) - finish(); + vCardCount >= presenceCount && blocklistReceived) + finish(); } } else if (MessageCenterService.ACTION_BLOCKLIST.equals(action)) { - blocklistReceived = true; + blocklistReceived = true; - String[] list = intent.getStringArrayExtra(MessageCenterService.EXTRA_BLOCKLIST); - if (list != null) { + String[] list = intent.getStringArrayExtra(MessageCenterService.EXTRA_BLOCKLIST); + if (list != null) { - for (String jid : list) { + for (String jid : list) { // see if bare JID is present in roster response String compare = StringUtils.parseBareAddress(jid); for (PresenceItem item : response) { if (StringUtils.parseBareAddress(item.from).equalsIgnoreCase(compare)) { - item.blocked = true; + item.blocked = true; break; } } - } + } - } + } // done with presence data and blocklist if (rosterCount >= 0 && allPresenceReceived && - vCardCount >= presenceCount) + vCardCount >= presenceCount) finish(); } @@ -471,12 +471,12 @@ public void performSync(Context context, Account account, String authority, registeredValues.put(Users.PUBLIC_KEY, entry.publicKey); try { - byte[] fp = PGP.getMasterKey(entry.publicKey).getFingerprint(); - registeredValues.put(Users.FINGERPRINT, MessageUtils.bytesToHex(fp)); + byte[] fp = PGP.getMasterKey(entry.publicKey).getFingerprint(); + registeredValues.put(Users.FINGERPRINT, MessageUtils.bytesToHex(fp)); } catch (Exception e) { - Log.w(TAG, "unable to parse public key", e); - registeredValues.putNull(Users.FINGERPRINT); + Log.w(TAG, "unable to parse public key", e); + registeredValues.putNull(Users.FINGERPRINT); } } else diff --git a/src/org/kontalk/ui/AboutActivity.java b/src/org/kontalk/ui/AboutActivity.java index 66efb66ee..25667bbf0 100644 --- a/src/org/kontalk/ui/AboutActivity.java +++ b/src/org/kontalk/ui/AboutActivity.java @@ -56,17 +56,17 @@ public class AboutActivity extends ActionBarActivity { private AboutPagerAdapter mAdapter; private ViewPager mPager; - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.about_screen); + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.about_screen); - mAdapter = new AboutPagerAdapter(getSupportFragmentManager()); + mAdapter = new AboutPagerAdapter(getSupportFragmentManager()); - mPager = (ViewPager) findViewById(R.id.pager); - mPager.setAdapter(mAdapter); - mPager.setOnPageChangeListener( - new ViewPager.OnPageChangeListener() { + mPager = (ViewPager) findViewById(R.id.pager); + mPager.setAdapter(mAdapter); + mPager.setOnPageChangeListener( + new ViewPager.OnPageChangeListener() { @Override public void onPageSelected(int position) { @@ -82,7 +82,7 @@ public void onPageScrollStateChanged(int position) { } } - ); + ); setupActivity(); @@ -98,9 +98,9 @@ else if (ACTION_CREDITS.equals(action)) mPager.setCurrentItem(ABOUT_CREDITS, true); } } - } + } - private void setupActivity() { + private void setupActivity() { ActionBar bar = getSupportActionBar(); bar.setDisplayHomeAsUpEnabled(true); bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); @@ -133,7 +133,7 @@ public void onTabReselected(Tab tab, FragmentTransaction ft) { .setTabListener(listener)); } - @Override + @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: @@ -144,19 +144,19 @@ public boolean onOptionsItemSelected(MenuItem item) { return super.onOptionsItemSelected(item); } - @Override - protected void onActivityResult(int requestCode, int resultCode, Intent data) { - DonationFragment fragment = mAdapter.getDonationFragment(); - IabHelper iabHelper = fragment.getIabHelper(); + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + DonationFragment fragment = mAdapter.getDonationFragment(); + IabHelper iabHelper = fragment.getIabHelper(); if (iabHelper == null || !iabHelper.handleActivityResult(requestCode, resultCode, data)) super.onActivityResult(requestCode, resultCode, data); - } + } - private static class AboutPagerAdapter extends FragmentPagerAdapter { + private static class AboutPagerAdapter extends FragmentPagerAdapter { - // this is for IabHelper - private DonationFragment mDonationFragment; + // this is for IabHelper + private DonationFragment mDonationFragment; public AboutPagerAdapter(FragmentManager fm) { super(fm); @@ -174,7 +174,7 @@ public Fragment getItem(int position) { return new AboutFragment(); case ABOUT_DONATION: - mDonationFragment = new DonationFragment(); + mDonationFragment = new DonationFragment(); return mDonationFragment; case ABOUT_CREDITS: @@ -186,9 +186,9 @@ public Fragment getItem(int position) { } public DonationFragment getDonationFragment() { - return mDonationFragment; - } + return mDonationFragment; + } - } + } } diff --git a/src/org/kontalk/ui/AboutFragment.java b/src/org/kontalk/ui/AboutFragment.java index e859c9c3a..d39eef5bf 100644 --- a/src/org/kontalk/ui/AboutFragment.java +++ b/src/org/kontalk/ui/AboutFragment.java @@ -41,8 +41,8 @@ */ public class AboutFragment extends Fragment implements OnClickListener { - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.about_about, container, false); try { @@ -65,56 +65,56 @@ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle sa view.findViewById(R.id.button_identica).setOnClickListener(this); return view; - } - - @Override - public void onClick(View v) { - switch (v.getId()) { - case R.id.button_twitter: - socialTwitter(); - break; - - case R.id.button_googleplus: - socialGooglePlus(); - break; - - case R.id.button_facebook: - socialFacebook(); - break; - - case R.id.button_identica: - socialIdentica(); - break; - } - } - - private void socialFacebook() { - try { - // we try to first activate the Facebook app - getActivity().getPackageManager().getPackageInfo("com.facebook.katana", 0); - startUrl(getString(R.string.facebook_profile)); - } - catch (Exception e) { - // no facebook (or error) - start the profile page URL - startUrl(getString(R.string.facebook_link)); - } - } - - private void socialGooglePlus() { - startUrl(getString(R.string.googleplus_link)); - } - - private void socialIdentica() { - startUrl(getString(R.string.identica_link)); - } - - private void socialTwitter() { - startUrl(getString(R.string.twitter_link)); - } - - private void startUrl(String url) { - Intent link = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); - startActivity(link); - } + } + + @Override + public void onClick(View v) { + switch (v.getId()) { + case R.id.button_twitter: + socialTwitter(); + break; + + case R.id.button_googleplus: + socialGooglePlus(); + break; + + case R.id.button_facebook: + socialFacebook(); + break; + + case R.id.button_identica: + socialIdentica(); + break; + } + } + + private void socialFacebook() { + try { + // we try to first activate the Facebook app + getActivity().getPackageManager().getPackageInfo("com.facebook.katana", 0); + startUrl(getString(R.string.facebook_profile)); + } + catch (Exception e) { + // no facebook (or error) - start the profile page URL + startUrl(getString(R.string.facebook_link)); + } + } + + private void socialGooglePlus() { + startUrl(getString(R.string.googleplus_link)); + } + + private void socialIdentica() { + startUrl(getString(R.string.identica_link)); + } + + private void socialTwitter() { + startUrl(getString(R.string.twitter_link)); + } + + private void startUrl(String url) { + Intent link = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); + startActivity(link); + } } diff --git a/src/org/kontalk/ui/AvatarListItem.java b/src/org/kontalk/ui/AvatarListItem.java index 3e45e6023..0c723f976 100644 --- a/src/org/kontalk/ui/AvatarListItem.java +++ b/src/org/kontalk/ui/AvatarListItem.java @@ -30,11 +30,11 @@ public AvatarListItem(Context context, AttributeSet attrs) { } private void init(Context context) { - mHandler = new Handler(); + mHandler = new Handler(); if (sDefaultContactImage == null) sDefaultContactImage = context.getResources() - .getDrawable(R.drawable.ic_contact_picture); + .getDrawable(R.drawable.ic_contact_picture); } @Override @@ -65,33 +65,33 @@ protected void loadAvatar(Contact contact) { @Override public void avatarLoaded(final Contact contact, final Drawable avatar) { - if (avatar != null) { - if (mHandler.getLooper().getThread() != Thread.currentThread()) { - mHandler.post(new Runnable() { - public void run() { - updateAvatar(contact, avatar); - } - }); - } - else { - updateAvatar(contact, avatar); - } - } + if (avatar != null) { + if (mHandler.getLooper().getThread() != Thread.currentThread()) { + mHandler.post(new Runnable() { + public void run() { + updateAvatar(contact, avatar); + } + }); + } + else { + updateAvatar(contact, avatar); + } + } } private void updateAvatar(Contact contact, Drawable avatar) { - try { - // be sure the contact is still the same - // this is an insane workaround against race conditions - Integer contactTag = (Integer) mAvatarView.getTag(); - if (contactTag != null && contactTag.intValue() == contact.hashCode()) - mAvatarView.setImageDrawable(avatar); - } - catch (Exception e) { - // we are deliberately ignoring any exception here - // because an error here could happen only if something - // weird is happening, e.g. user leaving the activity - } + try { + // be sure the contact is still the same + // this is an insane workaround against race conditions + Integer contactTag = (Integer) mAvatarView.getTag(); + if (contactTag != null && contactTag.intValue() == contact.hashCode()) + mAvatarView.setImageDrawable(avatar); + } + catch (Exception e) { + // we are deliberately ignoring any exception here + // because an error here could happen only if something + // weird is happening, e.g. user leaving the activity + } } } diff --git a/src/org/kontalk/ui/ComposeMessage.java b/src/org/kontalk/ui/ComposeMessage.java index aa0017723..b4b0dc2e0 100644 --- a/src/org/kontalk/ui/ComposeMessage.java +++ b/src/org/kontalk/ui/ComposeMessage.java @@ -163,16 +163,16 @@ public void setTitle(CharSequence title, CharSequence subtitle, Contact contact) } public void setUpdatingSubtitle() { - CharSequence current = mSubtitleView.getText(); - // no need to set updating status if no text is displayed - if (current.length() > 0) { - // we call toString() to strip any existing span - SpannableString status = new SpannableString(current.toString()); - status.setSpan(new StyleSpan(Typeface.ITALIC), - 0, status.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); - - mSubtitleView.setText(status); - } + CharSequence current = mSubtitleView.getText(); + // no need to set updating status if no text is displayed + if (current.length() > 0) { + // we call toString() to strip any existing span + SpannableString status = new SpannableString(current.toString()); + status.setSpan(new StyleSpan(Typeface.ITALIC), + 0, status.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + + mSubtitleView.setText(status); + } } private void onAvatarClick() { diff --git a/src/org/kontalk/ui/ComposeMessageFragment.java b/src/org/kontalk/ui/ComposeMessageFragment.java index 7db486a67..5d155fa04 100644 --- a/src/org/kontalk/ui/ComposeMessageFragment.java +++ b/src/org/kontalk/ui/ComposeMessageFragment.java @@ -126,15 +126,15 @@ * @author Daniele Ricci */ public class ComposeMessageFragment extends ListFragment implements - View.OnLongClickListener, IconContextMenuOnClickListener { - private static final String TAG = ComposeMessageFragment.class - .getSimpleName(); + View.OnLongClickListener, IconContextMenuOnClickListener { + private static final String TAG = ComposeMessageFragment.class + .getSimpleName(); - private static final int MESSAGE_LIST_QUERY_TOKEN = 8720; - private static final int CONVERSATION_QUERY_TOKEN = 8721; + private static final int MESSAGE_LIST_QUERY_TOKEN = 8720; + private static final int CONVERSATION_QUERY_TOKEN = 8721; - private static final int SELECT_ATTACHMENT_OPENABLE = Activity.RESULT_FIRST_USER + 1; - private static final int SELECT_ATTACHMENT_CONTACT = Activity.RESULT_FIRST_USER + 2; + private static final int SELECT_ATTACHMENT_OPENABLE = Activity.RESULT_FIRST_USER + 1; + private static final int SELECT_ATTACHMENT_CONTACT = Activity.RESULT_FIRST_USER + 2; /** Context menu group ID for this fragment. */ private static final int CONTEXT_MENU_GROUP_ID = 2; @@ -145,38 +145,38 @@ public class ComposeMessageFragment extends ListFragment implements private static final int ATTACHMENT_ACTION_CONTACT = 2; private IconContextMenu attachmentMenu; - private MessageListQueryHandler mQueryHandler; - private MessageListAdapter mListAdapter; - private EditText mTextEntry; - private View mSendButton; - private ViewGroup mInvitationBar; + private MessageListQueryHandler mQueryHandler; + private MessageListAdapter mListAdapter; + private EditText mTextEntry; + private View mSendButton; + private ViewGroup mInvitationBar; private MenuItem mDeleteThreadMenu; private MenuItem mViewContactMenu; private MenuItem mCallMenu; private MenuItem mBlockMenu; private MenuItem mUnblockMenu; - /** The thread id. */ - private long threadId = -1; - private Conversation mConversation; - private Bundle mArguments; + /** The thread id. */ + private long threadId = -1; + private Conversation mConversation; + private Bundle mArguments; - /** The user we are talking to. */ - private String userId; - private String userName; - private String userPhone; + /** The user we are talking to. */ + private String userId; + private String userName; + private String userPhone; - /** Presence probe packet id. */ - private String mPresenceId; - /** Last most available stanza. */ - private PresenceData mMostAvailable; - /** Available resources. */ - private Set mAvailableResources = new HashSet(); + /** Presence probe packet id. */ + private String mPresenceId; + /** Last most available stanza. */ + private PresenceData mMostAvailable; + /** Available resources. */ + private Set mAvailableResources = new HashSet(); - private PeerObserver mPeerObserver; + private PeerObserver mPeerObserver; private File mCurrentPhoto; - private LocalBroadcastManager mLocalBroadcastManager; + private LocalBroadcastManager mLocalBroadcastManager; private BroadcastReceiver mPresenceReceiver; private BroadcastReceiver mPrivacyListener; @@ -194,86 +194,86 @@ private static final class PresenceData { public Date stamp; } - /** Returns a new fragment instance from a picked contact. */ - public static ComposeMessageFragment fromUserId(Context context, String userId) { - ComposeMessageFragment f = new ComposeMessageFragment(); - Conversation conv = Conversation.loadFromUserId(context, userId); - // not found - create new - if (conv == null) { - Bundle args = new Bundle(); - args.putString("action", ComposeMessage.ACTION_VIEW_USERID); - args.putParcelable("data", Threads.getUri(userId)); - f.setArguments(args); - return f; - } - - return fromConversation(context, conv); - } - - /** Returns a new fragment instance from a {@link Conversation} instance. */ - public static ComposeMessageFragment fromConversation(Context context, - Conversation conv) { - return fromConversation(context, conv.getThreadId()); - } - - /** Returns a new fragment instance from a thread ID. */ - public static ComposeMessageFragment fromConversation(Context context, - long threadId) { - ComposeMessageFragment f = new ComposeMessageFragment(); - Bundle args = new Bundle(); - args.putString("action", ComposeMessage.ACTION_VIEW_CONVERSATION); - args.putParcelable("data", - ContentUris.withAppendedId(Conversations.CONTENT_URI, threadId)); - f.setArguments(args); - return f; - } - - @Override - public void onActivityCreated(Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); - // setListAdapter() is post-poned + /** Returns a new fragment instance from a picked contact. */ + public static ComposeMessageFragment fromUserId(Context context, String userId) { + ComposeMessageFragment f = new ComposeMessageFragment(); + Conversation conv = Conversation.loadFromUserId(context, userId); + // not found - create new + if (conv == null) { + Bundle args = new Bundle(); + args.putString("action", ComposeMessage.ACTION_VIEW_USERID); + args.putParcelable("data", Threads.getUri(userId)); + f.setArguments(args); + return f; + } + + return fromConversation(context, conv); + } + + /** Returns a new fragment instance from a {@link Conversation} instance. */ + public static ComposeMessageFragment fromConversation(Context context, + Conversation conv) { + return fromConversation(context, conv.getThreadId()); + } + + /** Returns a new fragment instance from a thread ID. */ + public static ComposeMessageFragment fromConversation(Context context, + long threadId) { + ComposeMessageFragment f = new ComposeMessageFragment(); + Bundle args = new Bundle(); + args.putString("action", ComposeMessage.ACTION_VIEW_CONVERSATION); + args.putParcelable("data", + ContentUris.withAppendedId(Conversations.CONTENT_URI, threadId)); + f.setArguments(args); + return f; + } + + @Override + public void onActivityCreated(Bundle savedInstanceState) { + super.onActivityCreated(savedInstanceState); + // setListAdapter() is post-poned ListView list = getListView(); list.setFastScrollEnabled(true); - registerForContextMenu(list); + registerForContextMenu(list); - // set custom background (if any) - Drawable bg = Preferences.getConversationBackground(getActivity()); - if (bg != null) { - list.setCacheColorHint(Color.TRANSPARENT); - list.setBackgroundDrawable(bg); - } + // set custom background (if any) + Drawable bg = Preferences.getConversationBackground(getActivity()); + if (bg != null) { + list.setCacheColorHint(Color.TRANSPARENT); + list.setBackgroundDrawable(bg); + } - mTextEntry = (EditText) getView().findViewById(R.id.text_editor); + mTextEntry = (EditText) getView().findViewById(R.id.text_editor); - // enter key flag - int inputTypeFlags = Preferences.getEnterKeyEnabled(getActivity()) ? - InputType.TYPE_TEXT_VARIATION_LONG_MESSAGE : - InputType.TYPE_TEXT_VARIATION_SHORT_MESSAGE; + // enter key flag + int inputTypeFlags = Preferences.getEnterKeyEnabled(getActivity()) ? + InputType.TYPE_TEXT_VARIATION_LONG_MESSAGE : + InputType.TYPE_TEXT_VARIATION_SHORT_MESSAGE; - mTextEntry.setInputType(mTextEntry.getInputType() | inputTypeFlags); + mTextEntry.setInputType(mTextEntry.getInputType() | inputTypeFlags); - mTextEntry.addTextChangedListener(new TextWatcher() { - @Override - public void onTextChanged(CharSequence s, int start, int before, int count) { - } + mTextEntry.addTextChangedListener(new TextWatcher() { + @Override + public void onTextChanged(CharSequence s, int start, int before, int count) { + } - @Override - public void beforeTextChanged(CharSequence s, int start, int count, int after) { - } + @Override + public void beforeTextChanged(CharSequence s, int start, int count, int after) { + } - @Override - public void afterTextChanged(Editable s) { - // convert smiley codes - mTextEntry.removeTextChangedListener(this); + @Override + public void afterTextChanged(Editable s) { + // convert smiley codes + mTextEntry.removeTextChangedListener(this); MessageUtils.convertSmileys(getActivity(), s, SmileyImageSpan.SIZE_EDITABLE); mTextEntry.addTextChangedListener(this); // enable the send button if there is something to send mSendButton.setEnabled(s.length() > 0); - } - }); - mTextEntry.setOnEditorActionListener(new OnEditorActionListener() { + } + }); + mTextEntry.setOnEditorActionListener(new OnEditorActionListener() { public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_SEND) { InputMethodManager imm = (InputMethodManager) getActivity() @@ -285,7 +285,7 @@ public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { return false; } }); - mChatStateListener = new TextWatcher() { + mChatStateListener = new TextWatcher() { public void onTextChanged(CharSequence s, int start, int before, int count) { if (Preferences.getSendTyping(getActivity())) { // send typing notification if necessary @@ -304,14 +304,14 @@ public void afterTextChanged(Editable s) { } }; - mSendButton = getView().findViewById(R.id.send_button); - mSendButton.setEnabled(mTextEntry.length() > 0); - mSendButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - submitSend(); - } - }); + mSendButton = getView().findViewById(R.id.send_button); + mSendButton.setEnabled(mTextEntry.length() > 0); + mSendButton.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + submitSend(); + } + }); mSmileySelectListener = new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView parent, View view, int position, long id) { @@ -335,7 +335,7 @@ public void onItemClick(AdapterView parent, View view, int position, long id) } }; - ImageButton smileyButton = (ImageButton) getView().findViewById(R.id.smiley_button); + ImageButton smileyButton = (ImageButton) getView().findViewById(R.id.smiley_button); smileyButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { @@ -343,47 +343,47 @@ public void onClick(View v) { } }); - Configuration config = getResources().getConfiguration(); - onKeyboardStateChanged(config.keyboardHidden == KEYBOARDHIDDEN_NO); + Configuration config = getResources().getConfiguration(); + onKeyboardStateChanged(config.keyboardHidden == KEYBOARDHIDDEN_NO); - mLocalBroadcastManager = LocalBroadcastManager.getInstance(getActivity()); + mLocalBroadcastManager = LocalBroadcastManager.getInstance(getActivity()); - processArguments(savedInstanceState); - } + processArguments(savedInstanceState); + } - @Override - public void onConfigurationChanged(Configuration newConfig) { - super.onConfigurationChanged(newConfig); + @Override + public void onConfigurationChanged(Configuration newConfig) { + super.onConfigurationChanged(newConfig); - onKeyboardStateChanged(newConfig.keyboardHidden == KEYBOARDHIDDEN_NO); - } + onKeyboardStateChanged(newConfig.keyboardHidden == KEYBOARDHIDDEN_NO); + } - public void reload() { - processArguments(null); - } + public void reload() { + processArguments(null); + } - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - return inflater.inflate(R.layout.compose_message, container, false); - } + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, + Bundle savedInstanceState) { + return inflater.inflate(R.layout.compose_message, container, false); + } - private final MessageListAdapter.OnContentChangedListener mContentChangedListener = new MessageListAdapter.OnContentChangedListener() { - public void onContentChanged(MessageListAdapter adapter) { - if (isVisible()) - startQuery(true, false); - } - }; + private final MessageListAdapter.OnContentChangedListener mContentChangedListener = new MessageListAdapter.OnContentChangedListener() { + public void onContentChanged(MessageListAdapter adapter) { + if (isVisible()) + startQuery(true, false); + } + }; - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); - setHasOptionsMenu(true); - mQueryHandler = new MessageListQueryHandler(); + setHasOptionsMenu(true); + mQueryHandler = new MessageListQueryHandler(); - // list adapter creation is post-poned - } + // list adapter creation is post-poned + } private void submitSend() { mTextEntry.removeTextChangedListener(mChatStateListener); @@ -394,109 +394,109 @@ private void submitSend() { mTextEntry.addTextChangedListener(mChatStateListener); } - /** Sends out a binary message. */ - public void sendBinaryMessage(Uri uri, String mime, boolean media, - Class> klass) { - Log.v(TAG, "sending binary content: " + uri); - Uri newMsg = null; + /** Sends out a binary message. */ + public void sendBinaryMessage(Uri uri, String mime, boolean media, + Class> klass) { + Log.v(TAG, "sending binary content: " + uri); + Uri newMsg = null; File previewFile = null; long length = -1; - try { - // TODO convert to thread (?) + try { + // TODO convert to thread (?) - offlineModeWarning(); + offlineModeWarning(); - String msgId = "draft" + (new Random().nextInt()); + String msgId = "draft" + (new Random().nextInt()); - // generate thumbnail - // FIXME this is blocking!!!! - if (media) { - // FIXME hard-coded to ImageComponent - String filename = ImageComponent.buildMediaFilename(msgId, MediaStorage.THUMBNAIL_MIME); - previewFile = MediaStorage.cacheThumbnail(getActivity(), uri, - filename); - } + // generate thumbnail + // FIXME this is blocking!!!! + if (media) { + // FIXME hard-coded to ImageComponent + String filename = ImageComponent.buildMediaFilename(msgId, MediaStorage.THUMBNAIL_MIME); + previewFile = MediaStorage.cacheThumbnail(getActivity(), uri, + filename); + } - length = MediaStorage.getLength(getActivity(), uri); + length = MediaStorage.getLength(getActivity(), uri); - // save to database + // save to database ContentValues values = new ContentValues(); - // must supply a message ID... - values.put(Messages.MESSAGE_ID, msgId); - values.put(Messages.PEER, userId); - - /* TODO ask for a text to send with the image - values.put(Messages.BODY_MIME, TextComponent.MIME_TYPE); - values.put(Messages.BODY_CONTENT, content.getBytes()); - values.put(Messages.BODY_LENGTH, content.length()); - */ - - values.put(Messages.UNREAD, false); - values.put(Messages.ENCRYPTED, false); - values.put(Messages.DIRECTION, Messages.DIRECTION_OUT); - values.put(Messages.TIMESTAMP, System.currentTimeMillis()); - values.put(Messages.STATUS, Messages.STATUS_SENDING); - - if (previewFile != null) - values.put(Messages.ATTACHMENT_PREVIEW_PATH, previewFile.getAbsolutePath()); - - values.put(Messages.ATTACHMENT_MIME, mime); - values.put(Messages.ATTACHMENT_LOCAL_URI, uri.toString()); - values.put(Messages.ATTACHMENT_LENGTH, length); - - newMsg = getActivity().getContentResolver().insert( - Messages.CONTENT_URI, values); - } - catch (Exception e) { - Log.e(TAG, "unable to store media", e); - } - - if (newMsg != null) { - - // update thread id from the inserted message - if (threadId <= 0) { - Cursor c = getActivity().getContentResolver().query(newMsg, - new String[] { Messages.THREAD_ID }, null, null, null); - if (c.moveToFirst()) { - threadId = c.getLong(0); - mConversation = null; - startQuery(true, false); - } - else { - Log.v(TAG, "no data - cannot start query for this composer"); - } - c.close(); - } - - // send message! - // FIXME do not encrypt binary messages for now - String previewPath = (previewFile != null) ? previewFile.getAbsolutePath() : null; - MessageCenterService.sendBinaryMessage(getActivity(), - userId, mime, uri, length, previewPath, ContentUris.parseId(newMsg)); - } - else { - getActivity().runOnUiThread(new Runnable() { - public void run() { - Toast.makeText(getActivity(), - R.string.err_store_message_failed, - Toast.LENGTH_LONG).show(); - } - }); - } - } - - private final class TextMessageThread extends Thread { - private final String mText; - - TextMessageThread(String text) { - mText = text; - } - - @Override - public void run() { - try { - boolean encrypted = Preferences.getEncryptionEnabled(getActivity()); + // must supply a message ID... + values.put(Messages.MESSAGE_ID, msgId); + values.put(Messages.PEER, userId); + + /* TODO ask for a text to send with the image + values.put(Messages.BODY_MIME, TextComponent.MIME_TYPE); + values.put(Messages.BODY_CONTENT, content.getBytes()); + values.put(Messages.BODY_LENGTH, content.length()); + */ + + values.put(Messages.UNREAD, false); + values.put(Messages.ENCRYPTED, false); + values.put(Messages.DIRECTION, Messages.DIRECTION_OUT); + values.put(Messages.TIMESTAMP, System.currentTimeMillis()); + values.put(Messages.STATUS, Messages.STATUS_SENDING); + + if (previewFile != null) + values.put(Messages.ATTACHMENT_PREVIEW_PATH, previewFile.getAbsolutePath()); + + values.put(Messages.ATTACHMENT_MIME, mime); + values.put(Messages.ATTACHMENT_LOCAL_URI, uri.toString()); + values.put(Messages.ATTACHMENT_LENGTH, length); + + newMsg = getActivity().getContentResolver().insert( + Messages.CONTENT_URI, values); + } + catch (Exception e) { + Log.e(TAG, "unable to store media", e); + } + + if (newMsg != null) { + + // update thread id from the inserted message + if (threadId <= 0) { + Cursor c = getActivity().getContentResolver().query(newMsg, + new String[] { Messages.THREAD_ID }, null, null, null); + if (c.moveToFirst()) { + threadId = c.getLong(0); + mConversation = null; + startQuery(true, false); + } + else { + Log.v(TAG, "no data - cannot start query for this composer"); + } + c.close(); + } + + // send message! + // FIXME do not encrypt binary messages for now + String previewPath = (previewFile != null) ? previewFile.getAbsolutePath() : null; + MessageCenterService.sendBinaryMessage(getActivity(), + userId, mime, uri, length, previewPath, ContentUris.parseId(newMsg)); + } + else { + getActivity().runOnUiThread(new Runnable() { + public void run() { + Toast.makeText(getActivity(), + R.string.err_store_message_failed, + Toast.LENGTH_LONG).show(); + } + }); + } + } + + private final class TextMessageThread extends Thread { + private final String mText; + + TextMessageThread(String text) { + mText = text; + } + + @Override + public void run() { + try { + boolean encrypted = Preferences.getEncryptionEnabled(getActivity()); /* TODO maybe this hack could work...? MessageListItem v = (MessageListItem) LayoutInflater.from(getActivity()) @@ -556,32 +556,32 @@ public void run() { } }); } - } - catch (Exception e) { - // whatever - Log.d(TAG, "broken message thread", e); - } - } - } - - /** Sends out the text message in the composing entry. */ - public void sendTextMessage(String text, boolean fromTextEntry) { - if (fromTextEntry) - text = mTextEntry.getText().toString(); - - if (!TextUtils.isEmpty(text)) { - /* - * TODO show an animation to warn the user that the message - * is being sent (actually stored). - */ - - offlineModeWarning(); - - // start thread - new TextMessageThread(text).start(); - - if (fromTextEntry) { - // empty text + } + catch (Exception e) { + // whatever + Log.d(TAG, "broken message thread", e); + } + } + } + + /** Sends out the text message in the composing entry. */ + public void sendTextMessage(String text, boolean fromTextEntry) { + if (fromTextEntry) + text = mTextEntry.getText().toString(); + + if (!TextUtils.isEmpty(text)) { + /* + * TODO show an animation to warn the user that the message + * is being sent (actually stored). + */ + + offlineModeWarning(); + + // start thread + new TextMessageThread(text).start(); + + if (fromTextEntry) { + // empty text mTextEntry.setText(""); // hide softkeyboard @@ -589,42 +589,42 @@ public void sendTextMessage(String text, boolean fromTextEntry) { .getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(mTextEntry.getWindowToken(), InputMethodManager.HIDE_IMPLICIT_ONLY); - } - } - } - - @Override - public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { - inflater.inflate(R.menu.compose_message_menu, menu); - - mDeleteThreadMenu = menu.findItem(R.id.delete_thread); - mViewContactMenu = menu.findItem(R.id.view_contact); - mCallMenu = menu.findItem(R.id.call_contact); - mBlockMenu = menu.findItem(R.id.block_user); - mUnblockMenu = menu.findItem(R.id.unblock_user); - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - switch (item.getItemId()) { - case R.id.call_contact: - startActivity(new Intent(Intent.ACTION_CALL, Uri.parse("tel:" - + userPhone))); - return true; - - case R.id.view_contact: - viewContact(); - return true; - - case R.id.menu_attachment: - selectAttachment(); - return true; + } + } + } + + @Override + public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { + inflater.inflate(R.menu.compose_message_menu, menu); + + mDeleteThreadMenu = menu.findItem(R.id.delete_thread); + mViewContactMenu = menu.findItem(R.id.view_contact); + mCallMenu = menu.findItem(R.id.call_contact); + mBlockMenu = menu.findItem(R.id.block_user); + mUnblockMenu = menu.findItem(R.id.unblock_user); + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + case R.id.call_contact: + startActivity(new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + + userPhone))); + return true; + + case R.id.view_contact: + viewContact(); + return true; + + case R.id.menu_attachment: + selectAttachment(); + return true; case R.id.delete_thread: - if (threadId > 0) - deleteThread(); + if (threadId > 0) + deleteThread(); - return true; + return true; case R.id.block_user: blockUser(); @@ -634,31 +634,31 @@ public boolean onOptionsItemSelected(MenuItem item) { unblockUser(); return true; - } + } - return super.onOptionsItemSelected(item); - } + return super.onOptionsItemSelected(item); + } - @Override - public void onListItemClick(ListView listView, View view, int position, long id) { - MessageListItem item = (MessageListItem) view; - final CompositeMessage msg = item.getMessage(); + @Override + public void onListItemClick(ListView listView, View view, int position, long id) { + MessageListItem item = (MessageListItem) view; + final CompositeMessage msg = item.getMessage(); - AttachmentComponent attachment = (AttachmentComponent) msg - .getComponent(AttachmentComponent.class); + AttachmentComponent attachment = (AttachmentComponent) msg + .getComponent(AttachmentComponent.class); - if (attachment != null && (attachment.getFetchUrl() != null || attachment.getLocalUri() != null)) { + if (attachment != null && (attachment.getFetchUrl() != null || attachment.getLocalUri() != null)) { - // outgoing message or already fetched - if (attachment.getLocalUri() != null) { - // open file - openFile(msg); - } - else { - // info & download dialog - CharSequence message = MessageUtils - .getFileInfoMessage(getActivity(), msg, - userPhone != null ? userPhone : userId); + // outgoing message or already fetched + if (attachment.getLocalUri() != null) { + // open file + openFile(msg); + } + else { + // info & download dialog + CharSequence message = MessageUtils + .getFileInfoMessage(getActivity(), msg, + userPhone != null ? userPhone : userId); AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()) .setTitle(R.string.title_file_info) @@ -686,53 +686,53 @@ public void onClick(DialogInterface dialog, int which) { } builder.show(); - } - } - } + } + } + } - private void startDownload(CompositeMessage msg) { - AttachmentComponent attachment = (AttachmentComponent) msg - .getComponent(AttachmentComponent.class); + private void startDownload(CompositeMessage msg) { + AttachmentComponent attachment = (AttachmentComponent) msg + .getComponent(AttachmentComponent.class); - if (attachment != null && attachment.getFetchUrl() != null) { + if (attachment != null && attachment.getFetchUrl() != null) { Intent i = new Intent(getActivity(), DownloadService.class); i.setAction(DownloadService.ACTION_DOWNLOAD_URL); i.putExtra(CompositeMessage.MSG_ID, msg.getId()); i.putExtra(CompositeMessage.MSG_SENDER, msg.getSender()); i.setData(Uri.parse(attachment.getFetchUrl())); getActivity().startService(i); - } - else { - // corrupted message :( - Toast.makeText(getActivity(), R.string.err_attachment_corrupted, - Toast.LENGTH_LONG).show(); - } - } - - private void stopDownload(CompositeMessage msg) { - AttachmentComponent attachment = (AttachmentComponent) msg - .getComponent(AttachmentComponent.class); - - if (attachment != null && attachment.getFetchUrl() != null) { + } + else { + // corrupted message :( + Toast.makeText(getActivity(), R.string.err_attachment_corrupted, + Toast.LENGTH_LONG).show(); + } + } + + private void stopDownload(CompositeMessage msg) { + AttachmentComponent attachment = (AttachmentComponent) msg + .getComponent(AttachmentComponent.class); + + if (attachment != null && attachment.getFetchUrl() != null) { Intent i = new Intent(getActivity(), DownloadService.class); i.setAction(DownloadService.ACTION_DOWNLOAD_ABORT); i.setData(Uri.parse(attachment.getFetchUrl())); getActivity().startService(i); } - } + } - private void openFile(CompositeMessage msg) { - AttachmentComponent attachment = (AttachmentComponent) msg - .getComponent(AttachmentComponent.class); + private void openFile(CompositeMessage msg) { + AttachmentComponent attachment = (AttachmentComponent) msg + .getComponent(AttachmentComponent.class); - if (attachment != null) { - Intent i = new Intent(Intent.ACTION_VIEW); - i.setDataAndType(attachment.getLocalUri(), attachment.getMime()); - startActivity(i); - } - } + if (attachment != null) { + Intent i = new Intent(Intent.ACTION_VIEW); + i.setDataAndType(attachment.getLocalUri(), attachment.getMime()); + startActivity(i); + } + } - /** Listener for attachment type chooser. */ + /** Listener for attachment type chooser. */ @Override public void onClick(int id) { switch (id) { @@ -754,32 +754,32 @@ public void viewContact() { } } - /** Starts dialog for attachment selection. */ - public void selectAttachment() { - if (attachmentMenu == null) { - attachmentMenu = new IconContextMenu(getActivity(), CONTEXT_MENU_ATTACHMENT); - attachmentMenu.addItem(getResources(), R.string.attachment_picture, R.drawable.ic_launcher_gallery, ATTACHMENT_ACTION_PICTURE); - attachmentMenu.addItem(getResources(), R.string.attachment_contact, R.drawable.ic_launcher_contacts, ATTACHMENT_ACTION_CONTACT); - attachmentMenu.setOnClickListener(this); - } - attachmentMenu.createMenu(getString(R.string.menu_attachment)).show(); - } + /** Starts dialog for attachment selection. */ + public void selectAttachment() { + if (attachmentMenu == null) { + attachmentMenu = new IconContextMenu(getActivity(), CONTEXT_MENU_ATTACHMENT); + attachmentMenu.addItem(getResources(), R.string.attachment_picture, R.drawable.ic_launcher_gallery, ATTACHMENT_ACTION_PICTURE); + attachmentMenu.addItem(getResources(), R.string.attachment_contact, R.drawable.ic_launcher_contacts, ATTACHMENT_ACTION_CONTACT); + attachmentMenu.setOnClickListener(this); + } + attachmentMenu.createMenu(getString(R.string.menu_attachment)).show(); + } - /** Starts activity for an image attachment. */ - @TargetApi(Build.VERSION_CODES.KITKAT) - private void selectImageAttachment() { - Intent pictureIntent; + /** Starts activity for an image attachment. */ + @TargetApi(Build.VERSION_CODES.KITKAT) + private void selectImageAttachment() { + Intent pictureIntent; - if (!MediaStorage.isStorageAccessFrameworkAvailable()) { - pictureIntent = new Intent(Intent.ACTION_GET_CONTENT); - } - else { - pictureIntent = new Intent(Intent.ACTION_OPEN_DOCUMENT); - } + if (!MediaStorage.isStorageAccessFrameworkAvailable()) { + pictureIntent = new Intent(Intent.ACTION_GET_CONTENT); + } + else { + pictureIntent = new Intent(Intent.ACTION_OPEN_DOCUMENT); + } - pictureIntent - .addCategory(Intent.CATEGORY_OPENABLE) - .setType("image/*"); + pictureIntent + .addCategory(Intent.CATEGORY_OPENABLE) + .setType("image/*"); Intent chooser = null; try { @@ -791,9 +791,9 @@ private void selectImageAttachment() { if (list.size() <= 0) throw new UnsupportedOperationException(); mCurrentPhoto = MediaStorage.getTempImage(getActivity()); - Intent take = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); - take.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mCurrentPhoto)); - chooser = Intent.createChooser(pictureIntent, getString(R.string.chooser_send_picture)); + Intent take = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); + take.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mCurrentPhoto)); + chooser = Intent.createChooser(pictureIntent, getString(R.string.chooser_send_picture)); chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { take }); } catch (UnsupportedOperationException ue) { @@ -806,85 +806,85 @@ private void selectImageAttachment() { } if (chooser == null) chooser = pictureIntent; - startActivityForResult(chooser, SELECT_ATTACHMENT_OPENABLE); - } + startActivityForResult(chooser, SELECT_ATTACHMENT_OPENABLE); + } - /** Starts activity for a vCard attachment from a contact. */ - private void selectContactAttachment() { + /** Starts activity for a vCard attachment from a contact. */ + private void selectContactAttachment() { Intent i = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI); startActivityForResult(i, SELECT_ATTACHMENT_CONTACT); - } + } - private void showSmileysPopup(View anchor) { + private void showSmileysPopup(View anchor) { if (mSmileyPopup == null) mSmileyPopup = MessageUtils.smileysPopup(getActivity(), mSmileySelectListener); mSmileyPopup.show(anchor); - } - - private void deleteThread() { - AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); - builder.setTitle(R.string.confirm_delete_thread); - builder.setIcon(android.R.drawable.ic_dialog_alert); - builder.setMessage(R.string.confirm_will_delete_thread); - builder.setPositiveButton(android.R.string.ok, - new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - mTextEntry.setText(""); - MessagesProvider.deleteThread(getActivity(), threadId); - } - }); - builder.setNegativeButton(android.R.string.cancel, null); - builder.create().show(); - } - - private void deleteMessage(final long id) { - AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); - builder.setTitle(R.string.confirm_delete_message); - builder.setIcon(android.R.drawable.ic_dialog_alert); - builder.setMessage(R.string.confirm_will_delete_message); - builder.setPositiveButton(android.R.string.ok, - new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - getActivity().getContentResolver().delete( - ContentUris.withAppendedId( - Messages.CONTENT_URI, id), null, null); - } - }); - builder.setNegativeButton(android.R.string.cancel, null); - builder.create().show(); - } - - private void blockUser() { - new AlertDialog.Builder(getActivity()) - .setTitle(R.string.menu_block_user) - .setMessage(Html.fromHtml(getString(R.string.msg_block_user_warning))) - .setPositiveButton(R.string.menu_block_user, new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int which) { - setPrivacy(PRIVACY_BLOCK); - } - }) - .setNegativeButton(android.R.string.cancel, null) - .show(); - } + } + + private void deleteThread() { + AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); + builder.setTitle(R.string.confirm_delete_thread); + builder.setIcon(android.R.drawable.ic_dialog_alert); + builder.setMessage(R.string.confirm_will_delete_thread); + builder.setPositiveButton(android.R.string.ok, + new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + mTextEntry.setText(""); + MessagesProvider.deleteThread(getActivity(), threadId); + } + }); + builder.setNegativeButton(android.R.string.cancel, null); + builder.create().show(); + } + + private void deleteMessage(final long id) { + AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); + builder.setTitle(R.string.confirm_delete_message); + builder.setIcon(android.R.drawable.ic_dialog_alert); + builder.setMessage(R.string.confirm_will_delete_message); + builder.setPositiveButton(android.R.string.ok, + new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + getActivity().getContentResolver().delete( + ContentUris.withAppendedId( + Messages.CONTENT_URI, id), null, null); + } + }); + builder.setNegativeButton(android.R.string.cancel, null); + builder.create().show(); + } + + private void blockUser() { + new AlertDialog.Builder(getActivity()) + .setTitle(R.string.menu_block_user) + .setMessage(Html.fromHtml(getString(R.string.msg_block_user_warning))) + .setPositiveButton(R.string.menu_block_user, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + setPrivacy(PRIVACY_BLOCK); + } + }) + .setNegativeButton(android.R.string.cancel, null) + .show(); + } private void unblockUser() { - new AlertDialog.Builder(getActivity()) - .setTitle(R.string.menu_unblock_user) - .setMessage(Html.fromHtml(getString(R.string.msg_unblock_user_warning))) - .setPositiveButton(R.string.menu_unblock_user, new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int which) { - setPrivacy(PRIVACY_UNBLOCK); - } - }) - .setNegativeButton(android.R.string.cancel, null) - .show(); - } - - private void decryptMessage(CompositeMessage msg) { - try { - Context ctx = getActivity(); + new AlertDialog.Builder(getActivity()) + .setTitle(R.string.menu_unblock_user) + .setMessage(Html.fromHtml(getString(R.string.msg_unblock_user_warning))) + .setPositiveButton(R.string.menu_unblock_user, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + setPrivacy(PRIVACY_UNBLOCK); + } + }) + .setNegativeButton(android.R.string.cancel, null) + .show(); + } + + private void decryptMessage(CompositeMessage msg) { + try { + Context ctx = getActivity(); MessageUtils.decryptMessage(ctx, null, msg); @@ -893,7 +893,7 @@ private void decryptMessage(CompositeMessage msg) { MessageUtils.fillContentValues(values, msg); ctx.getContentResolver().update(Messages.getUri(msg.getId()), - values, null, null); + values, null, null); } catch (Exception e) { Log.e(TAG, "decryption failed", e); @@ -902,305 +902,305 @@ private void decryptMessage(CompositeMessage msg) { Toast.makeText(getActivity(), "Decryption failed!", Toast.LENGTH_LONG).show(); } - } + } - private void retryMessage(CompositeMessage msg) { + private void retryMessage(CompositeMessage msg) { Intent i = new Intent(getActivity(), MessageCenterService.class); i.setAction(MessageCenterService.ACTION_RETRY); i.putExtra(MessageCenterService.EXTRA_MESSAGE, ContentUris.withAppendedId - (Messages.CONTENT_URI, msg.getDatabaseId())); + (Messages.CONTENT_URI, msg.getDatabaseId())); getActivity().startService(i); - } - - private static final int MENU_RETRY = 1; - private static final int MENU_SHARE = 2; - private static final int MENU_COPY_TEXT = 3; - private static final int MENU_DECRYPT = 4; - private static final int MENU_OPEN = 5; - private static final int MENU_DOWNLOAD = 6; - private static final int MENU_CANCEL_DOWNLOAD = 7; - private static final int MENU_DETAILS = 8; - private static final int MENU_DELETE = 9; - - @Override - public void onCreateContextMenu(ContextMenu menu, View v, - ContextMenuInfo menuInfo) { - AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; - MessageListItem vitem = (MessageListItem) info.targetView; - CompositeMessage msg = vitem.getMessage(); - - menu.setHeaderTitle(R.string.title_message_options); - - // message waiting for user review - if (msg.getStatus() == Messages.STATUS_PENDING) { - menu.add(CONTEXT_MENU_GROUP_ID, MENU_RETRY, MENU_RETRY, R.string.resend); - } - - // some commands can be used only on unencrypted messages - if (!msg.isEncrypted()) { - - AttachmentComponent attachment = (AttachmentComponent) msg - .getComponent(AttachmentComponent.class); - TextComponent text = (TextComponent) msg - .getComponent(TextComponent.class); - - // sharing media messages has no purpose if media file hasn't been - // retrieved yet - if (text != null || (attachment != null ? attachment.getLocalUri() != null : true)) { - menu.add(CONTEXT_MENU_GROUP_ID, MENU_SHARE, MENU_SHARE, R.string.share); - } - - // non-empty text: copy text to clipboard - if (text != null && !TextUtils.isEmpty(text.getContent())) { - menu.add(CONTEXT_MENU_GROUP_ID, MENU_COPY_TEXT, MENU_COPY_TEXT, - R.string.copy_message_text); - } - - if (attachment != null) { - - // message has a local uri - add open file entry - if (attachment.getLocalUri() != null) { - int resId; - if (attachment instanceof ImageComponent) - resId = R.string.view_image; - else - resId = R.string.open_file; - - menu.add(CONTEXT_MENU_GROUP_ID, MENU_OPEN, MENU_OPEN, resId); - } - - // message has a fetch url - add download control entry - if (msg.getDirection() == Messages.DIRECTION_IN && attachment.getFetchUrl() != null) { - int id, string; - if (!DownloadService.isQueued(attachment.getFetchUrl())) { - // already fetched - if (attachment.getLocalUri() != null) - string = R.string.download_again; - else - string = R.string.download_file; - id = MENU_DOWNLOAD; - } - else { - string = R.string.download_cancel; - id = MENU_CANCEL_DOWNLOAD; - } - menu.add(CONTEXT_MENU_GROUP_ID, id, id, string); - } - - - } - - } - - else { - - menu.add(CONTEXT_MENU_GROUP_ID, MENU_DECRYPT, MENU_DECRYPT, - R.string.decrypt_message); - - } - - menu.add(CONTEXT_MENU_GROUP_ID, MENU_DETAILS, MENU_DETAILS, R.string.menu_message_details); - menu.add(CONTEXT_MENU_GROUP_ID, MENU_DELETE, MENU_DELETE, R.string.delete_message); - } - - @Override - public boolean onContextItemSelected(android.view.MenuItem item) { - // not our context - if (item.getGroupId() != CONTEXT_MENU_GROUP_ID) - return false; - - AdapterContextMenuInfo info = (AdapterContextMenuInfo) item - .getMenuInfo(); - MessageListItem v = (MessageListItem) info.targetView; - CompositeMessage msg = v.getMessage(); - - switch (item.getItemId()) { - case MENU_SHARE: { - Intent i = null; - AttachmentComponent attachment = (AttachmentComponent) msg - .getComponent(AttachmentComponent.class); - - if (attachment != null) { - i = ComposeMessage.sendMediaMessage(attachment.getLocalUri(), - attachment.getMime()); - } - - else { - TextComponent txt = (TextComponent) msg - .getComponent(TextComponent.class); - - if (txt != null) - i = ComposeMessage.sendTextMessage(txt.getContent()); - } - - if (i != null) - startActivity(i); - else - // TODO ehm... - Log.w(TAG, "error sharing message"); - - return true; - } - - case MENU_COPY_TEXT: { - TextComponent txt = (TextComponent) msg - .getComponent(TextComponent.class); - - String text = (txt != null) ? txt.getContent() : ""; - - ClipboardManager cpm = (ClipboardManager) getActivity() - .getSystemService(Context.CLIPBOARD_SERVICE); - cpm.setText(text); - - Toast.makeText(getActivity(), R.string.message_text_copied, - Toast.LENGTH_SHORT).show(); - return true; - } - - case MENU_DECRYPT: { - decryptMessage(msg); - return true; - } - - case MENU_RETRY: { - retryMessage(msg); - return true; - } - - case MENU_DOWNLOAD: { - startDownload(msg); - return true; - } + } + + private static final int MENU_RETRY = 1; + private static final int MENU_SHARE = 2; + private static final int MENU_COPY_TEXT = 3; + private static final int MENU_DECRYPT = 4; + private static final int MENU_OPEN = 5; + private static final int MENU_DOWNLOAD = 6; + private static final int MENU_CANCEL_DOWNLOAD = 7; + private static final int MENU_DETAILS = 8; + private static final int MENU_DELETE = 9; + + @Override + public void onCreateContextMenu(ContextMenu menu, View v, + ContextMenuInfo menuInfo) { + AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; + MessageListItem vitem = (MessageListItem) info.targetView; + CompositeMessage msg = vitem.getMessage(); + + menu.setHeaderTitle(R.string.title_message_options); + + // message waiting for user review + if (msg.getStatus() == Messages.STATUS_PENDING) { + menu.add(CONTEXT_MENU_GROUP_ID, MENU_RETRY, MENU_RETRY, R.string.resend); + } + + // some commands can be used only on unencrypted messages + if (!msg.isEncrypted()) { + + AttachmentComponent attachment = (AttachmentComponent) msg + .getComponent(AttachmentComponent.class); + TextComponent text = (TextComponent) msg + .getComponent(TextComponent.class); + + // sharing media messages has no purpose if media file hasn't been + // retrieved yet + if (text != null || (attachment != null ? attachment.getLocalUri() != null : true)) { + menu.add(CONTEXT_MENU_GROUP_ID, MENU_SHARE, MENU_SHARE, R.string.share); + } + + // non-empty text: copy text to clipboard + if (text != null && !TextUtils.isEmpty(text.getContent())) { + menu.add(CONTEXT_MENU_GROUP_ID, MENU_COPY_TEXT, MENU_COPY_TEXT, + R.string.copy_message_text); + } + + if (attachment != null) { + + // message has a local uri - add open file entry + if (attachment.getLocalUri() != null) { + int resId; + if (attachment instanceof ImageComponent) + resId = R.string.view_image; + else + resId = R.string.open_file; + + menu.add(CONTEXT_MENU_GROUP_ID, MENU_OPEN, MENU_OPEN, resId); + } + + // message has a fetch url - add download control entry + if (msg.getDirection() == Messages.DIRECTION_IN && attachment.getFetchUrl() != null) { + int id, string; + if (!DownloadService.isQueued(attachment.getFetchUrl())) { + // already fetched + if (attachment.getLocalUri() != null) + string = R.string.download_again; + else + string = R.string.download_file; + id = MENU_DOWNLOAD; + } + else { + string = R.string.download_cancel; + id = MENU_CANCEL_DOWNLOAD; + } + menu.add(CONTEXT_MENU_GROUP_ID, id, id, string); + } + + + } + + } + + else { + + menu.add(CONTEXT_MENU_GROUP_ID, MENU_DECRYPT, MENU_DECRYPT, + R.string.decrypt_message); + + } + + menu.add(CONTEXT_MENU_GROUP_ID, MENU_DETAILS, MENU_DETAILS, R.string.menu_message_details); + menu.add(CONTEXT_MENU_GROUP_ID, MENU_DELETE, MENU_DELETE, R.string.delete_message); + } + + @Override + public boolean onContextItemSelected(android.view.MenuItem item) { + // not our context + if (item.getGroupId() != CONTEXT_MENU_GROUP_ID) + return false; + + AdapterContextMenuInfo info = (AdapterContextMenuInfo) item + .getMenuInfo(); + MessageListItem v = (MessageListItem) info.targetView; + CompositeMessage msg = v.getMessage(); + + switch (item.getItemId()) { + case MENU_SHARE: { + Intent i = null; + AttachmentComponent attachment = (AttachmentComponent) msg + .getComponent(AttachmentComponent.class); + + if (attachment != null) { + i = ComposeMessage.sendMediaMessage(attachment.getLocalUri(), + attachment.getMime()); + } + + else { + TextComponent txt = (TextComponent) msg + .getComponent(TextComponent.class); + + if (txt != null) + i = ComposeMessage.sendTextMessage(txt.getContent()); + } + + if (i != null) + startActivity(i); + else + // TODO ehm... + Log.w(TAG, "error sharing message"); + + return true; + } + + case MENU_COPY_TEXT: { + TextComponent txt = (TextComponent) msg + .getComponent(TextComponent.class); + + String text = (txt != null) ? txt.getContent() : ""; + + ClipboardManager cpm = (ClipboardManager) getActivity() + .getSystemService(Context.CLIPBOARD_SERVICE); + cpm.setText(text); + + Toast.makeText(getActivity(), R.string.message_text_copied, + Toast.LENGTH_SHORT).show(); + return true; + } + + case MENU_DECRYPT: { + decryptMessage(msg); + return true; + } + + case MENU_RETRY: { + retryMessage(msg); + return true; + } + + case MENU_DOWNLOAD: { + startDownload(msg); + return true; + } case MENU_CANCEL_DOWNLOAD: { stopDownload(msg); return true; } - case MENU_DETAILS: { - CharSequence messageDetails = MessageUtils.getMessageDetails( - getActivity(), msg, userPhone != null ? userPhone : userId); - new AlertDialog.Builder(getActivity()) - .setTitle(R.string.title_message_details) - .setMessage(messageDetails) - .setPositiveButton(android.R.string.ok, null) - .setCancelable(true).show(); - return true; - } - - case MENU_DELETE: { - deleteMessage(msg.getDatabaseId()); - return true; - } - - case MENU_OPEN: { - openFile(msg); - return true; - } - } - - return super.onContextItemSelected(item); - } - - private void startQuery(boolean reloadConversation, boolean progress) { - try { - if (progress) - getActivity().setProgressBarIndeterminateVisibility(true); - - CompositeMessage.startQuery(mQueryHandler, MESSAGE_LIST_QUERY_TOKEN, - threadId); - - if (reloadConversation) - Conversation.startQuery(mQueryHandler, - CONVERSATION_QUERY_TOKEN, threadId); - - } catch (SQLiteException e) { - Log.e(TAG, "query error", e); - } - } - - private void loadConversationMetadata(Uri uri) { - threadId = ContentUris.parseId(uri); - mConversation = Conversation.loadFromId(getActivity(), threadId); - if (mConversation == null) { - Log.w(TAG, "conversation for thread " + threadId + " not found!"); - startActivity(new Intent(getActivity(), ConversationList.class)); - getActivity().finish(); - return; - } - - userId = mConversation.getRecipient(); - Contact contact = mConversation.getContact(); - if (contact != null) { - userName = contact.getName(); - userPhone = contact.getNumber(); - } - else { - userName = userId; - } - } - - private Bundle myArguments() { - return (mArguments != null) ? mArguments : getArguments(); - } - - public void setMyArguments(Bundle args) { - mArguments = args; - } - - @Override - public void onActivityResult(int requestCode, int resultCode, Intent data) { + case MENU_DETAILS: { + CharSequence messageDetails = MessageUtils.getMessageDetails( + getActivity(), msg, userPhone != null ? userPhone : userId); + new AlertDialog.Builder(getActivity()) + .setTitle(R.string.title_message_details) + .setMessage(messageDetails) + .setPositiveButton(android.R.string.ok, null) + .setCancelable(true).show(); + return true; + } + + case MENU_DELETE: { + deleteMessage(msg.getDatabaseId()); + return true; + } + + case MENU_OPEN: { + openFile(msg); + return true; + } + } + + return super.onContextItemSelected(item); + } + + private void startQuery(boolean reloadConversation, boolean progress) { + try { + if (progress) + getActivity().setProgressBarIndeterminateVisibility(true); + + CompositeMessage.startQuery(mQueryHandler, MESSAGE_LIST_QUERY_TOKEN, + threadId); + + if (reloadConversation) + Conversation.startQuery(mQueryHandler, + CONVERSATION_QUERY_TOKEN, threadId); + + } catch (SQLiteException e) { + Log.e(TAG, "query error", e); + } + } + + private void loadConversationMetadata(Uri uri) { + threadId = ContentUris.parseId(uri); + mConversation = Conversation.loadFromId(getActivity(), threadId); + if (mConversation == null) { + Log.w(TAG, "conversation for thread " + threadId + " not found!"); + startActivity(new Intent(getActivity(), ConversationList.class)); + getActivity().finish(); + return; + } + + userId = mConversation.getRecipient(); + Contact contact = mConversation.getContact(); + if (contact != null) { + userName = contact.getName(); + userPhone = contact.getNumber(); + } + else { + userName = userId; + } + } + + private Bundle myArguments() { + return (mArguments != null) ? mArguments : getArguments(); + } + + public void setMyArguments(Bundle args) { + mArguments = args; + } + + @Override + public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == SELECT_ATTACHMENT_OPENABLE) { if (resultCode == Activity.RESULT_OK) { - Uri uri = null; - String mime = null; - - // returning from camera - if (data == null) { - /* - * FIXME picture taking should be done differently. - * Use a MediaStore-based uri and use a requestCode just - * for taking pictures. - */ - if (mCurrentPhoto != null) { - uri = Uri.fromFile(mCurrentPhoto); - // notify media scanner - Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); - mediaScanIntent.setData(uri); - getActivity().sendBroadcast(mediaScanIntent); - mCurrentPhoto = null; - } - } - else { - if (mCurrentPhoto != null) { - mCurrentPhoto.delete(); - mCurrentPhoto = null; - } - uri = data.getData(); - mime = data.getType(); - - // SAF available, request persistable permissions - if (MediaStorage.isStorageAccessFrameworkAvailable()) { - MediaStorage.requestPersistablePermissions(getActivity(), data); - } - } - - if (uri != null) { - if (mime == null || mime.startsWith("*/") - || mime.endsWith("/*")) { - mime = MediaStorage.getType(getActivity(), uri); - Log.v(TAG, "using detected mime type " + mime); - } - - if (ImageComponent.supportsMimeType(mime)) - sendBinaryMessage(uri, mime, true, ImageComponent.class); - else if (VCardComponent.supportsMimeType(mime)) - sendBinaryMessage(uri, VCardComponent.MIME_TYPE, false, VCardComponent.class); - else - Toast.makeText(getActivity(), R.string.send_mime_not_supported, Toast.LENGTH_LONG) - .show(); - } - } + Uri uri = null; + String mime = null; + + // returning from camera + if (data == null) { + /* + * FIXME picture taking should be done differently. + * Use a MediaStore-based uri and use a requestCode just + * for taking pictures. + */ + if (mCurrentPhoto != null) { + uri = Uri.fromFile(mCurrentPhoto); + // notify media scanner + Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); + mediaScanIntent.setData(uri); + getActivity().sendBroadcast(mediaScanIntent); + mCurrentPhoto = null; + } + } + else { + if (mCurrentPhoto != null) { + mCurrentPhoto.delete(); + mCurrentPhoto = null; + } + uri = data.getData(); + mime = data.getType(); + + // SAF available, request persistable permissions + if (MediaStorage.isStorageAccessFrameworkAvailable()) { + MediaStorage.requestPersistablePermissions(getActivity(), data); + } + } + + if (uri != null) { + if (mime == null || mime.startsWith("*/") + || mime.endsWith("/*")) { + mime = MediaStorage.getType(getActivity(), uri); + Log.v(TAG, "using detected mime type " + mime); + } + + if (ImageComponent.supportsMimeType(mime)) + sendBinaryMessage(uri, mime, true, ImageComponent.class); + else if (VCardComponent.supportsMimeType(mime)) + sendBinaryMessage(uri, VCardComponent.MIME_TYPE, false, VCardComponent.class); + else + Toast.makeText(getActivity(), R.string.send_mime_not_supported, Toast.LENGTH_LONG) + .show(); + } + } // operation aborted else { // delete photo :) @@ -1210,321 +1210,321 @@ else if (VCardComponent.supportsMimeType(mime)) } } } - else if (requestCode == SELECT_ATTACHMENT_CONTACT) { - if (resultCode == Activity.RESULT_OK) { - Uri uri = data.getData(); - if (uri != null) { - // get lookup key - final Cursor c = getActivity().getContentResolver() - .query(uri, new String[] { Contacts.LOOKUP_KEY }, null, null, null); - if (c != null) { - try { - c.moveToFirst(); - String lookupKey = c.getString(0); - Uri vcardUri = Uri.withAppendedPath(Contacts.CONTENT_VCARD_URI, lookupKey); - sendBinaryMessage(vcardUri, VCardComponent.MIME_TYPE, false, VCardComponent.class); - } - finally { - c.close(); - } - } - } - } - } - } - - private void onKeyboardStateChanged(boolean isKeyboardOpen) { - if (isKeyboardOpen) { - mTextEntry.setFocusableInTouchMode(true); - mTextEntry.setHint(R.string.hint_type_to_compose); - } - else { - mTextEntry.setFocusableInTouchMode(false); - mTextEntry.setHint(R.string.hint_open_kbd_to_compose); - } - } - - @Override - public void onSaveInstanceState(Bundle out) { - super.onSaveInstanceState(out); - out.putParcelable(Uri.class.getName(), Threads.getUri(userId)); - } - - private void processArguments(Bundle savedInstanceState) { - Bundle args = null; - if (savedInstanceState != null) { - Uri uri = savedInstanceState.getParcelable(Uri.class.getName()); - // threadId = ContentUris.parseId(uri); - args = new Bundle(); - args.putString("action", ComposeMessage.ACTION_VIEW_USERID); - args.putParcelable("data", uri); - } - else { - args = myArguments(); - } - - if (args != null && args.size() > 0) { - final String action = args.getString("action"); - - // view intent - if (Intent.ACTION_VIEW.equals(action)) { - Uri uri = args.getParcelable("data"); - ContentResolver cres = getActivity().getContentResolver(); - - /* - * FIXME this will retrieve name directly from contacts, - * resulting in a possible discrepancy with users database - */ - Cursor c = cres.query(uri, new String[] { - Syncer.DATA_COLUMN_DISPLAY_NAME, - Syncer.DATA_COLUMN_PHONE }, null, null, null); - if (c.moveToFirst()) { - userName = c.getString(0); - userPhone = c.getString(1); - - // FIXME should it be retrieved from RawContacts.SYNC3 ?? - userId = MessageUtils.sha1(userPhone); - - Cursor cp = cres.query(Messages.CONTENT_URI, - new String[] { Messages.THREAD_ID }, Messages.PEER - + " = ?", new String[] { userId }, null); - if (cp.moveToFirst()) - threadId = cp.getLong(0); - cp.close(); - } - c.close(); - - if (threadId > 0) { - mConversation = Conversation.loadFromId(getActivity(), - threadId); - } - else { - mConversation = Conversation.createNew(getActivity()); - mConversation.setRecipient(userId); - } - } - - // view conversation - just threadId provided - else if (ComposeMessage.ACTION_VIEW_CONVERSATION.equals(action)) { - Uri uri = args.getParcelable("data"); - loadConversationMetadata(uri); - } - - // view conversation - just userId provided - else if (ComposeMessage.ACTION_VIEW_USERID.equals(action)) { - Uri uri = args.getParcelable("data"); - userId = uri.getPathSegments().get(1); - mConversation = Conversation.loadFromUserId(getActivity(), - userId); - - if (mConversation == null) { - mConversation = Conversation.createNew(getActivity()); + else if (requestCode == SELECT_ATTACHMENT_CONTACT) { + if (resultCode == Activity.RESULT_OK) { + Uri uri = data.getData(); + if (uri != null) { + // get lookup key + final Cursor c = getActivity().getContentResolver() + .query(uri, new String[] { Contacts.LOOKUP_KEY }, null, null, null); + if (c != null) { + try { + c.moveToFirst(); + String lookupKey = c.getString(0); + Uri vcardUri = Uri.withAppendedPath(Contacts.CONTENT_VCARD_URI, lookupKey); + sendBinaryMessage(vcardUri, VCardComponent.MIME_TYPE, false, VCardComponent.class); + } + finally { + c.close(); + } + } + } + } + } + } + + private void onKeyboardStateChanged(boolean isKeyboardOpen) { + if (isKeyboardOpen) { + mTextEntry.setFocusableInTouchMode(true); + mTextEntry.setHint(R.string.hint_type_to_compose); + } + else { + mTextEntry.setFocusableInTouchMode(false); + mTextEntry.setHint(R.string.hint_open_kbd_to_compose); + } + } + + @Override + public void onSaveInstanceState(Bundle out) { + super.onSaveInstanceState(out); + out.putParcelable(Uri.class.getName(), Threads.getUri(userId)); + } + + private void processArguments(Bundle savedInstanceState) { + Bundle args = null; + if (savedInstanceState != null) { + Uri uri = savedInstanceState.getParcelable(Uri.class.getName()); + // threadId = ContentUris.parseId(uri); + args = new Bundle(); + args.putString("action", ComposeMessage.ACTION_VIEW_USERID); + args.putParcelable("data", uri); + } + else { + args = myArguments(); + } + + if (args != null && args.size() > 0) { + final String action = args.getString("action"); + + // view intent + if (Intent.ACTION_VIEW.equals(action)) { + Uri uri = args.getParcelable("data"); + ContentResolver cres = getActivity().getContentResolver(); + + /* + * FIXME this will retrieve name directly from contacts, + * resulting in a possible discrepancy with users database + */ + Cursor c = cres.query(uri, new String[] { + Syncer.DATA_COLUMN_DISPLAY_NAME, + Syncer.DATA_COLUMN_PHONE }, null, null, null); + if (c.moveToFirst()) { + userName = c.getString(0); + userPhone = c.getString(1); + + // FIXME should it be retrieved from RawContacts.SYNC3 ?? + userId = MessageUtils.sha1(userPhone); + + Cursor cp = cres.query(Messages.CONTENT_URI, + new String[] { Messages.THREAD_ID }, Messages.PEER + + " = ?", new String[] { userId }, null); + if (cp.moveToFirst()) + threadId = cp.getLong(0); + cp.close(); + } + c.close(); + + if (threadId > 0) { + mConversation = Conversation.loadFromId(getActivity(), + threadId); + } + else { + mConversation = Conversation.createNew(getActivity()); + mConversation.setRecipient(userId); + } + } + + // view conversation - just threadId provided + else if (ComposeMessage.ACTION_VIEW_CONVERSATION.equals(action)) { + Uri uri = args.getParcelable("data"); + loadConversationMetadata(uri); + } + + // view conversation - just userId provided + else if (ComposeMessage.ACTION_VIEW_USERID.equals(action)) { + Uri uri = args.getParcelable("data"); + userId = uri.getPathSegments().get(1); + mConversation = Conversation.loadFromUserId(getActivity(), + userId); + + if (mConversation == null) { + mConversation = Conversation.createNew(getActivity()); mConversation.setNumberHint(args.getString("number")); - mConversation.setRecipient(userId); - } - // this way avoid doing the users database query twice - else { - if (mConversation.getContact() == null) { - mConversation.setNumberHint(args.getString("number")); - mConversation.setRecipient(userId); - } - } - - threadId = mConversation.getThreadId(); - Contact contact = mConversation.getContact(); - if (contact != null) { - userName = contact.getName(); - userPhone = contact.getNumber(); - } - else { - userName = userId; - } - } - } - - // set title if we are autonomous - if (mArguments != null) { - String title = userName; - //if (userPhone != null) title += " <" + userPhone + ">"; - setActivityTitle(title, "", null); - } - - // update conversation stuff - if (mConversation != null) - onConversationCreated(); - - // non existant thread - check for not synced contact - if (threadId <= 0 && mConversation != null) { - Contact contact = mConversation.getContact(); - if (userPhone != null && contact != null ? !contact.isRegistered() : true) { - // ask user to send invitation - DialogInterface.OnClickListener noListener = new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - // FIXME is this specific to sms app? - Intent i = new Intent(Intent.ACTION_SENDTO, - Uri.parse("smsto:" + userPhone)); - i.putExtra("sms_body", - getString(R.string.text_invite_message)); - startActivity(i); - getActivity().finish(); - } - }; - - AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); - builder. - setTitle(R.string.title_user_not_found) - .setMessage(R.string.message_user_not_found) - // nothing happens if user chooses to contact the user anyway - .setPositiveButton(R.string.yes_user_not_found, null) - .setNegativeButton(R.string.no_user_not_found, noListener) - .show(); - - } - } - } - - public void setActivityTitle(CharSequence title, CharSequence status, Contact contact) { - Activity parent = getActivity(); - if (parent instanceof ComposeMessage) - ((ComposeMessage) parent).setTitle(title, status, contact); - else if (title != null) - parent.setTitle(title); - } - - public void setActivityStatusUpdating() { - Activity parent = getActivity(); - if (parent instanceof ComposeMessage) - ((ComposeMessage) parent).setUpdatingSubtitle(); - } - - public ComposeMessage getParentActivity() { - Activity _activity = getActivity(); - return (_activity instanceof ComposeMessage) ? (ComposeMessage) _activity - : null; - } - - private void processStart(boolean resuming) { - ComposeMessage activity = getParentActivity(); - // opening for contact picker - do nothing - if (threadId < 0 && activity != null - && activity.getSendIntent() != null) - return; - - if (mListAdapter == null) { - Pattern highlight = null; - Bundle args = myArguments(); - if (args != null) { - String highlightString = args - .getString(ComposeMessage.EXTRA_HIGHLIGHT); - highlight = (highlightString == null) ? null : Pattern.compile( - "\\b" + Pattern.quote(highlightString), - Pattern.CASE_INSENSITIVE); - } - - mListAdapter = new MessageListAdapter(getActivity(), null, - highlight, getListView()); - mListAdapter.setOnContentChangedListener(mContentChangedListener); - setListAdapter(mListAdapter); - } - - if (threadId > 0) { - // always reload conversation - startQuery(true, resuming); - } - else { - // HACK this is for crappy honeycomb :) - getActivity().setProgressBarIndeterminateVisibility(false); - - mConversation = Conversation.createNew(getActivity()); - mConversation.setRecipient(userId); - onConversationCreated(); - } - } - - /** Called when the {@link Conversation} object has been created. */ - private void onConversationCreated() { + mConversation.setRecipient(userId); + } + // this way avoid doing the users database query twice + else { + if (mConversation.getContact() == null) { + mConversation.setNumberHint(args.getString("number")); + mConversation.setRecipient(userId); + } + } + + threadId = mConversation.getThreadId(); + Contact contact = mConversation.getContact(); + if (contact != null) { + userName = contact.getName(); + userPhone = contact.getNumber(); + } + else { + userName = userId; + } + } + } + + // set title if we are autonomous + if (mArguments != null) { + String title = userName; + //if (userPhone != null) title += " <" + userPhone + ">"; + setActivityTitle(title, "", null); + } + + // update conversation stuff + if (mConversation != null) + onConversationCreated(); + + // non existant thread - check for not synced contact + if (threadId <= 0 && mConversation != null) { + Contact contact = mConversation.getContact(); + if (userPhone != null && contact != null ? !contact.isRegistered() : true) { + // ask user to send invitation + DialogInterface.OnClickListener noListener = new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + // FIXME is this specific to sms app? + Intent i = new Intent(Intent.ACTION_SENDTO, + Uri.parse("smsto:" + userPhone)); + i.putExtra("sms_body", + getString(R.string.text_invite_message)); + startActivity(i); + getActivity().finish(); + } + }; + + AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); + builder. + setTitle(R.string.title_user_not_found) + .setMessage(R.string.message_user_not_found) + // nothing happens if user chooses to contact the user anyway + .setPositiveButton(R.string.yes_user_not_found, null) + .setNegativeButton(R.string.no_user_not_found, noListener) + .show(); + + } + } + } + + public void setActivityTitle(CharSequence title, CharSequence status, Contact contact) { + Activity parent = getActivity(); + if (parent instanceof ComposeMessage) + ((ComposeMessage) parent).setTitle(title, status, contact); + else if (title != null) + parent.setTitle(title); + } + + public void setActivityStatusUpdating() { + Activity parent = getActivity(); + if (parent instanceof ComposeMessage) + ((ComposeMessage) parent).setUpdatingSubtitle(); + } + + public ComposeMessage getParentActivity() { + Activity _activity = getActivity(); + return (_activity instanceof ComposeMessage) ? (ComposeMessage) _activity + : null; + } + + private void processStart(boolean resuming) { + ComposeMessage activity = getParentActivity(); + // opening for contact picker - do nothing + if (threadId < 0 && activity != null + && activity.getSendIntent() != null) + return; + + if (mListAdapter == null) { + Pattern highlight = null; + Bundle args = myArguments(); + if (args != null) { + String highlightString = args + .getString(ComposeMessage.EXTRA_HIGHLIGHT); + highlight = (highlightString == null) ? null : Pattern.compile( + "\\b" + Pattern.quote(highlightString), + Pattern.CASE_INSENSITIVE); + } + + mListAdapter = new MessageListAdapter(getActivity(), null, + highlight, getListView()); + mListAdapter.setOnContentChangedListener(mContentChangedListener); + setListAdapter(mListAdapter); + } + + if (threadId > 0) { + // always reload conversation + startQuery(true, resuming); + } + else { + // HACK this is for crappy honeycomb :) + getActivity().setProgressBarIndeterminateVisibility(false); + + mConversation = Conversation.createNew(getActivity()); + mConversation.setRecipient(userId); + onConversationCreated(); + } + } + + /** Called when the {@link Conversation} object has been created. */ + private void onConversationCreated() { // subscribe to presence notifications subscribePresence(); mTextEntry.removeTextChangedListener(mChatStateListener); - // restore draft (if any and only if user hasn't inserted text) - if (mTextEntry.getText().length() == 0) { - String draft = mConversation.getDraft(); - if (draft != null) { - mTextEntry.setText(draft); + // restore draft (if any and only if user hasn't inserted text) + if (mTextEntry.getText().length() == 0) { + String draft = mConversation.getDraft(); + if (draft != null) { + mTextEntry.setText(draft); - // move cursor to end - mTextEntry.setSelection(mTextEntry.getText().length()); - } - } + // move cursor to end + mTextEntry.setSelection(mTextEntry.getText().length()); + } + } mTextEntry.addTextChangedListener(mChatStateListener); - if (mConversation.getThreadId() > 0 && mConversation.getUnreadCount() > 0) { - /* - * FIXME this has the usual issue about resuming while screen is - * still locked, having focus and so on... - * See issue #28. - */ - mConversation.markAsRead(); - } - else { - // new conversation -- observe peer Uri - registerPeerObserver(); - } - - // update contact icon - setActivityTitle(null, null, mConversation.getContact()); - - // setup invitation bar - boolean visible = (mConversation.getRequestStatus() == Threads.REQUEST_WAITING); - - if (visible) { - - if (mInvitationBar == null) { - mInvitationBar = (ViewGroup) getView().findViewById(R.id.invitation_bar); - - // setup listeners and show button bar - View.OnClickListener listener = new View.OnClickListener() { - public void onClick(View v) { - mInvitationBar.setVisibility(View.GONE); - - int action; - if (v.getId() == R.id.button_accept) - action = PRIVACY_ACCEPT; - else - action = PRIVACY_BLOCK; - - setPrivacy(action); - } - }; - - mInvitationBar.findViewById(R.id.button_accept) - .setOnClickListener(listener); - mInvitationBar.findViewById(R.id.button_block) - .setOnClickListener(listener); - - // identity button has its own listener - mInvitationBar.findViewById(R.id.button_identity) - .setOnClickListener(new View.OnClickListener() { - public void onClick(View v) { - showIdentityDialog(); - } - } - ); - - } - } - - if (mInvitationBar != null) - mInvitationBar.setVisibility(visible ? View.VISIBLE : View.GONE); - - updateUI(); - } - - private void setPrivacy(int action) { + if (mConversation.getThreadId() > 0 && mConversation.getUnreadCount() > 0) { + /* + * FIXME this has the usual issue about resuming while screen is + * still locked, having focus and so on... + * See issue #28. + */ + mConversation.markAsRead(); + } + else { + // new conversation -- observe peer Uri + registerPeerObserver(); + } + + // update contact icon + setActivityTitle(null, null, mConversation.getContact()); + + // setup invitation bar + boolean visible = (mConversation.getRequestStatus() == Threads.REQUEST_WAITING); + + if (visible) { + + if (mInvitationBar == null) { + mInvitationBar = (ViewGroup) getView().findViewById(R.id.invitation_bar); + + // setup listeners and show button bar + View.OnClickListener listener = new View.OnClickListener() { + public void onClick(View v) { + mInvitationBar.setVisibility(View.GONE); + + int action; + if (v.getId() == R.id.button_accept) + action = PRIVACY_ACCEPT; + else + action = PRIVACY_BLOCK; + + setPrivacy(action); + } + }; + + mInvitationBar.findViewById(R.id.button_accept) + .setOnClickListener(listener); + mInvitationBar.findViewById(R.id.button_block) + .setOnClickListener(listener); + + // identity button has its own listener + mInvitationBar.findViewById(R.id.button_identity) + .setOnClickListener(new View.OnClickListener() { + public void onClick(View v) { + showIdentityDialog(); + } + } + ); + + } + } + + if (mInvitationBar != null) + mInvitationBar.setVisibility(visible ? View.VISIBLE : View.GONE); + + updateUI(); + } + + private void setPrivacy(int action) { int status; switch (action) { @@ -1558,47 +1558,47 @@ private void setPrivacy(int action) { // setup broadcast receiver for block/unblock reply if (action == PRIVACY_BLOCK || action == PRIVACY_UNBLOCK) { - if (mPrivacyListener == null) { - mPrivacyListener = new BroadcastReceiver() { - public void onReceive(Context context, Intent intent) { - String from = intent.getStringExtra(MessageCenterService.EXTRA_FROM_USERID); - - if (userId.equals(from)) { - // this will trigger a Contact reload - mConversation.setRecipient(userId); - // this will update block/unblock menu items - updateUI(); - // request presence subscription if unblocking - if (MessageCenterService.ACTION_UNBLOCKED.equals(intent.getAction())) { - Toast.makeText(getActivity(), - R.string.msg_user_unblocked, - Toast.LENGTH_LONG).show(); - - presenceSubscribe(); - } - else { - Toast.makeText(getActivity(), - R.string.msg_user_blocked, - Toast.LENGTH_LONG).show(); - } - - // we don't need this receiver anymore - mLocalBroadcastManager.unregisterReceiver(this); - } - } - }; - } - - IntentFilter filter = new IntentFilter(MessageCenterService.ACTION_BLOCKED); - filter.addAction(MessageCenterService.ACTION_UNBLOCKED); - mLocalBroadcastManager.registerReceiver(mPrivacyListener, filter); + if (mPrivacyListener == null) { + mPrivacyListener = new BroadcastReceiver() { + public void onReceive(Context context, Intent intent) { + String from = intent.getStringExtra(MessageCenterService.EXTRA_FROM_USERID); + + if (userId.equals(from)) { + // this will trigger a Contact reload + mConversation.setRecipient(userId); + // this will update block/unblock menu items + updateUI(); + // request presence subscription if unblocking + if (MessageCenterService.ACTION_UNBLOCKED.equals(intent.getAction())) { + Toast.makeText(getActivity(), + R.string.msg_user_unblocked, + Toast.LENGTH_LONG).show(); + + presenceSubscribe(); + } + else { + Toast.makeText(getActivity(), + R.string.msg_user_blocked, + Toast.LENGTH_LONG).show(); + } + + // we don't need this receiver anymore + mLocalBroadcastManager.unregisterReceiver(this); + } + } + }; + } + + IntentFilter filter = new IntentFilter(MessageCenterService.ACTION_BLOCKED); + filter.addAction(MessageCenterService.ACTION_UNBLOCKED); + mLocalBroadcastManager.registerReceiver(mPrivacyListener, filter); } // send command to message center MessageCenterService.replySubscription(ctx, userId, action); - } + } - private void showIdentityDialog() { + private void showIdentityDialog() { String fingerprint; String uid; @@ -1635,10 +1635,10 @@ private void showIdentityDialog() { .setMessage(text) .show(); - } + } /* - private final class UserPresenceBroadcastReceiver extends BroadcastReceiver { + private final class UserPresenceBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); @@ -1683,10 +1683,10 @@ else if (MessageCenterServiceLegacy.ACTION_CONNECTED.equals(action)) { Context.BIND_AUTO_CREATE); } } - } + } */ - private void subscribePresence() { + private void subscribePresence() { if (mPresenceReceiver == null) { mPresenceReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { @@ -1864,50 +1864,50 @@ else if (MessageCenterService.ACTION_MESSAGE.equals(action)) { } }; - // listen for user presence, connection and incoming messages - IntentFilter filter = new IntentFilter(); - filter.addAction(MessageCenterService.ACTION_PRESENCE); - filter.addAction(MessageCenterService.ACTION_CONNECTED); - filter.addAction(MessageCenterService.ACTION_MESSAGE); + // listen for user presence, connection and incoming messages + IntentFilter filter = new IntentFilter(); + filter.addAction(MessageCenterService.ACTION_PRESENCE); + filter.addAction(MessageCenterService.ACTION_CONNECTED); + filter.addAction(MessageCenterService.ACTION_MESSAGE); mLocalBroadcastManager.registerReceiver(mPresenceReceiver, filter); // request connection status MessageCenterService.requestConnectionStatus(getActivity()); - } - } - - /** Sends a subscription request for the current peer. */ - private void presenceSubscribe() { - // all of this shall be done only if there isn't a request from the other contact - if (mConversation.getRequestStatus() != Threads.REQUEST_WAITING) { - - Contact c = mConversation.getContact(); - - // pre-approve our presence if we don't have contact's key - if (c == null || c.getPublicKeyRing() == null) { - Intent i = new Intent(getActivity(), MessageCenterService.class); - i.setAction(MessageCenterService.ACTION_PRESENCE); - i.putExtra(MessageCenterService.EXTRA_TO_USERID, userId); - i.putExtra(MessageCenterService.EXTRA_TYPE, Presence.Type.subscribed.name()); - getActivity().startService(i); - } - - // send subscription request - Intent i = new Intent(getActivity(), MessageCenterService.class); - i.setAction(MessageCenterService.ACTION_PRESENCE); - i.putExtra(MessageCenterService.EXTRA_TO_USERID, userId); - i.putExtra(MessageCenterService.EXTRA_TYPE, Presence.Type.subscribe.name()); - getActivity().startService(i); - - } - } - - private void unsubcribePresence() { + } + } + + /** Sends a subscription request for the current peer. */ + private void presenceSubscribe() { + // all of this shall be done only if there isn't a request from the other contact + if (mConversation.getRequestStatus() != Threads.REQUEST_WAITING) { + + Contact c = mConversation.getContact(); + + // pre-approve our presence if we don't have contact's key + if (c == null || c.getPublicKeyRing() == null) { + Intent i = new Intent(getActivity(), MessageCenterService.class); + i.setAction(MessageCenterService.ACTION_PRESENCE); + i.putExtra(MessageCenterService.EXTRA_TO_USERID, userId); + i.putExtra(MessageCenterService.EXTRA_TYPE, Presence.Type.subscribed.name()); + getActivity().startService(i); + } + + // send subscription request + Intent i = new Intent(getActivity(), MessageCenterService.class); + i.setAction(MessageCenterService.ACTION_PRESENCE); + i.putExtra(MessageCenterService.EXTRA_TO_USERID, userId); + i.putExtra(MessageCenterService.EXTRA_TYPE, Presence.Type.subscribe.name()); + getActivity().startService(i); + + } + } + + private void unsubcribePresence() { if (mPresenceReceiver != null) { mLocalBroadcastManager.unregisterReceiver(mPresenceReceiver); - mPresenceReceiver = null; - } + mPresenceReceiver = null; + } // send unsubscription request Intent i = new Intent(getActivity(), MessageCenterService.class); @@ -1915,15 +1915,15 @@ private void unsubcribePresence() { i.putExtra(MessageCenterService.EXTRA_TO_USERID, userId); i.putExtra(MessageCenterService.EXTRA_TYPE, "unsubscribe"); getActivity().startService(i); - } - - /* - @Override - public boolean tx(ClientConnection connection, String txId, MessageLite pack) { - if (pack instanceof UserLookupResponse) { - UserLookupResponse _pack = (UserLookupResponse) pack; - if (_pack.getEntryCount() > 0) { - UserLookupResponse.Entry res = _pack.getEntry(0); + } + + /* + @Override + public boolean tx(ClientConnection connection, String txId, MessageLite pack) { + if (pack instanceof UserLookupResponse) { + UserLookupResponse _pack = (UserLookupResponse) pack; + if (_pack.getEntryCount() > 0) { + UserLookupResponse.Entry res = _pack.getEntry(0); CharSequence text = null; try { Activity context = getActivity(); @@ -1994,101 +1994,101 @@ public void run() { // what here? Log.e(TAG, "user lookup response error!", e); } - } - } + } + } - return false; - } - */ + return false; + } + */ - private void setStatusText(CharSequence text) { + private void setStatusText(CharSequence text) { setActivityTitle(null, text, null); - } - - private synchronized void registerPeerObserver() { - if (mPeerObserver == null) { - Uri uri = Threads.getUri(mConversation.getRecipient()); - mPeerObserver = new PeerObserver(getActivity(), mQueryHandler); - getActivity().getContentResolver().registerContentObserver(uri, - false, mPeerObserver); - } - } - - private synchronized void unregisterPeerObserver() { - if (mPeerObserver != null) { - getActivity().getContentResolver().unregisterContentObserver( - mPeerObserver); - mPeerObserver = null; - } - } - - private final class PeerObserver extends ContentObserver { - private final Context mContext; - - public PeerObserver(Context context, Handler handler) { - super(handler); - mContext = context; - } - - @Override - public void onChange(boolean selfChange) { - Conversation conv = Conversation.loadFromUserId(mContext, userId); - - if (conv != null) { - mConversation = conv; - threadId = mConversation.getThreadId(); - - // auto-unregister - unregisterPeerObserver(); - } - - // fire cursor update - processStart(false); - } - - @Override - public boolean deliverSelfNotifications() { - return false; - } - } - - @Override - public void onStart() { - super.onStart(); + } + + private synchronized void registerPeerObserver() { + if (mPeerObserver == null) { + Uri uri = Threads.getUri(mConversation.getRecipient()); + mPeerObserver = new PeerObserver(getActivity(), mQueryHandler); + getActivity().getContentResolver().registerContentObserver(uri, + false, mPeerObserver); + } + } + + private synchronized void unregisterPeerObserver() { + if (mPeerObserver != null) { + getActivity().getContentResolver().unregisterContentObserver( + mPeerObserver); + mPeerObserver = null; + } + } + + private final class PeerObserver extends ContentObserver { + private final Context mContext; + + public PeerObserver(Context context, Handler handler) { + super(handler); + mContext = context; + } + + @Override + public void onChange(boolean selfChange) { + Conversation conv = Conversation.loadFromUserId(mContext, userId); + + if (conv != null) { + mConversation = conv; + threadId = mConversation.getThreadId(); + + // auto-unregister + unregisterPeerObserver(); + } + + // fire cursor update + processStart(false); + } + + @Override + public boolean deliverSelfNotifications() { + return false; + } + } + + @Override + public void onStart() { + super.onStart(); // hold message center - MessageCenterService.hold(getActivity()); - } + MessageCenterService.hold(getActivity()); + } - @Override - public void onResume() { - super.onResume(); + @Override + public void onResume() { + super.onResume(); - if (Authenticator.getDefaultAccount(getActivity()) == null) { - NumberValidation.startValidation(getActivity()); - getActivity().finish(); - return; - } + if (Authenticator.getDefaultAccount(getActivity()) == null) { + NumberValidation.startValidation(getActivity()); + getActivity().finish(); + return; + } ComposeMessage activity = getParentActivity(); if (activity == null || !activity.hasLostFocus() || activity.hasWindowFocus()) { onFocus(); } - } + } - public void onFocus() { - // resume content watcher - resumeContentListener(); + public void onFocus() { + // resume content watcher + resumeContentListener(); - // we are updating the status now - setActivityStatusUpdating(); + // we are updating the status now + setActivityStatusUpdating(); - // cursor was previously destroyed -- reload everything - // mConversation = null; - processStart(true); - if (userId != null) { - // TODO use some method to generate the JID - EndpointServer server = Preferences.getEndpointServer(getActivity()); - String jid = userId + '@' + server.getNetwork(); + // cursor was previously destroyed -- reload everything + // mConversation = null; + processStart(true); + if (userId != null) { + // TODO use some method to generate the JID + EndpointServer server = Preferences.getEndpointServer(getActivity()); + String jid = userId + '@' + server.getNetwork(); // set notifications on pause MessagingNotification.setPaused(jid); @@ -2096,122 +2096,122 @@ public void onFocus() { // clear chat invitation (if any) // TODO use jid here MessagingNotification.clearChatInvitation(getActivity(), userId); - } - } + } + } - @Override - public void onPause() { - super.onPause(); + @Override + public void onPause() { + super.onPause(); - // pause content watcher - pauseContentListener(); + // pause content watcher + pauseContentListener(); - // notify parent of pausing - ComposeMessage parent = getParentActivity(); - if (parent != null) - parent.fragmentLostFocus(); + // notify parent of pausing + ComposeMessage parent = getParentActivity(); + if (parent != null) + parent.fragmentLostFocus(); - CharSequence text = mTextEntry.getText(); - int len = text.length(); + CharSequence text = mTextEntry.getText(); + int len = text.length(); // resume notifications MessagingNotification.setPaused(null); - // save last message as draft - if (threadId > 0) { - - // no draft and no messages - delete conversation - if (len == 0 && mConversation.getMessageCount() == 0 && - mConversation.getRequestStatus() != Threads.REQUEST_WAITING) { - - // FIXME shouldn't be faster to just delete the thread? - MessagesProvider.deleteThread(getActivity(), threadId); - } - - // update draft - else { - ContentValues values = new ContentValues(1); - values.put(Threads.DRAFT, (len > 0) ? text.toString() : null); - getActivity().getContentResolver().update( - ContentUris.withAppendedId(Threads.CONTENT_URI, threadId), - values, null, null); - } - } - - // new thread, create empty conversation - else { - if (len > 0) { - // save to local storage - ContentValues values = new ContentValues(); - // must supply a message ID... - values.put(Messages.MESSAGE_ID, - "draft" + (new Random().nextInt())); - values.put(Messages.PEER, userId); - values.put(Messages.BODY_CONTENT, new byte[0]); - values.put(Messages.BODY_LENGTH, 0); - values.put(Messages.BODY_MIME, TextComponent.MIME_TYPE); - values.put(Messages.DIRECTION, Messages.DIRECTION_OUT); - values.put(Messages.TIMESTAMP, System.currentTimeMillis()); - values.put(Messages.ENCRYPTED, false); - values.put(Threads.DRAFT, text.toString()); - getActivity().getContentResolver().insert(Messages.CONTENT_URI, - values); - } - } - - if (len > 0) { - Toast.makeText(getActivity(), R.string.msg_draft_saved, - Toast.LENGTH_LONG).show(); - } - - if (Preferences.getSendTyping(getActivity())) { - // send inactive state notification - if (mAvailableResources.size() > 0) - MessageCenterService.sendChatState(getActivity(), userId, ChatState.inactive); - mComposeSent = false; - } + // save last message as draft + if (threadId > 0) { + + // no draft and no messages - delete conversation + if (len == 0 && mConversation.getMessageCount() == 0 && + mConversation.getRequestStatus() != Threads.REQUEST_WAITING) { + + // FIXME shouldn't be faster to just delete the thread? + MessagesProvider.deleteThread(getActivity(), threadId); + } + + // update draft + else { + ContentValues values = new ContentValues(1); + values.put(Threads.DRAFT, (len > 0) ? text.toString() : null); + getActivity().getContentResolver().update( + ContentUris.withAppendedId(Threads.CONTENT_URI, threadId), + values, null, null); + } + } + + // new thread, create empty conversation + else { + if (len > 0) { + // save to local storage + ContentValues values = new ContentValues(); + // must supply a message ID... + values.put(Messages.MESSAGE_ID, + "draft" + (new Random().nextInt())); + values.put(Messages.PEER, userId); + values.put(Messages.BODY_CONTENT, new byte[0]); + values.put(Messages.BODY_LENGTH, 0); + values.put(Messages.BODY_MIME, TextComponent.MIME_TYPE); + values.put(Messages.DIRECTION, Messages.DIRECTION_OUT); + values.put(Messages.TIMESTAMP, System.currentTimeMillis()); + values.put(Messages.ENCRYPTED, false); + values.put(Threads.DRAFT, text.toString()); + getActivity().getContentResolver().insert(Messages.CONTENT_URI, + values); + } + } + + if (len > 0) { + Toast.makeText(getActivity(), R.string.msg_draft_saved, + Toast.LENGTH_LONG).show(); + } + + if (Preferences.getSendTyping(getActivity())) { + // send inactive state notification + if (mAvailableResources.size() > 0) + MessageCenterService.sendChatState(getActivity(), userId, ChatState.inactive); + mComposeSent = false; + } // unsubcribe presence notifications unsubcribePresence(); - } - - @Override - public void onStop() { - super.onStop(); - unregisterPeerObserver(); - if (mListAdapter != null) - mListAdapter.changeCursor(null); - - // be sure to cancel all queries - mQueryHandler.cancelOperation(MESSAGE_LIST_QUERY_TOKEN); - mQueryHandler.cancelOperation(CONVERSATION_QUERY_TOKEN); - - // release message center - MessageCenterService.release(getActivity()); - } - - @Override - public void onDestroy() { - super.onDestroy(); - if (mTextEntry != null) { - mTextEntry.removeTextChangedListener(mChatStateListener); - mTextEntry.setText(""); - } - } - - private void pauseContentListener() { - if (mListAdapter != null) - mListAdapter.setOnContentChangedListener(null); - } - - private void resumeContentListener() { - if (mListAdapter != null) - mListAdapter.setOnContentChangedListener(mContentChangedListener); - } - - public final boolean isFinishing() { - return (getActivity() == null || (getActivity() != null && getActivity() - .isFinishing())) || isRemoving(); - } + } + + @Override + public void onStop() { + super.onStop(); + unregisterPeerObserver(); + if (mListAdapter != null) + mListAdapter.changeCursor(null); + + // be sure to cancel all queries + mQueryHandler.cancelOperation(MESSAGE_LIST_QUERY_TOKEN); + mQueryHandler.cancelOperation(CONVERSATION_QUERY_TOKEN); + + // release message center + MessageCenterService.release(getActivity()); + } + + @Override + public void onDestroy() { + super.onDestroy(); + if (mTextEntry != null) { + mTextEntry.removeTextChangedListener(mChatStateListener); + mTextEntry.setText(""); + } + } + + private void pauseContentListener() { + if (mListAdapter != null) + mListAdapter.setOnContentChangedListener(null); + } + + private void resumeContentListener() { + if (mListAdapter != null) + mListAdapter.setOnContentChangedListener(mContentChangedListener); + } + + public final boolean isFinishing() { + return (getActivity() == null || (getActivity() != null && getActivity() + .isFinishing())) || isRemoving(); + } private void updateUI() { Contact contact = (mConversation != null) ? mConversation @@ -2235,140 +2235,140 @@ private void updateUI() { } if (mBlockMenu != null) { - if (Authenticator.isSelfUserId(getActivity(), userId)) { - mBlockMenu.setVisible(false).setEnabled(false); - mUnblockMenu.setVisible(false).setEnabled(false); - } - else if (contact != null) { - // block/unblock - boolean blocked = contact.isBlocked(); + if (Authenticator.isSelfUserId(getActivity(), userId)) { + mBlockMenu.setVisible(false).setEnabled(false); + mUnblockMenu.setVisible(false).setEnabled(false); + } + else if (contact != null) { + // block/unblock + boolean blocked = contact.isBlocked(); - mBlockMenu.setVisible(!blocked).setEnabled(!blocked); - mUnblockMenu.setVisible(blocked).setEnabled(blocked); - } - else { - mBlockMenu.setVisible(true).setEnabled(true); - mUnblockMenu.setVisible(true).setEnabled(true); - } + mBlockMenu.setVisible(!blocked).setEnabled(!blocked); + mUnblockMenu.setVisible(blocked).setEnabled(blocked); + } + else { + mBlockMenu.setVisible(true).setEnabled(true); + mUnblockMenu.setVisible(true).setEnabled(true); + } } } - /** The conversation list query handler. */ + /** The conversation list query handler. */ // TODO convert to static class and use a weak reference to the context - private final class MessageListQueryHandler extends AsyncQueryHandler { - public MessageListQueryHandler() { - super(getActivity().getApplicationContext().getContentResolver()); - } - - @Override - protected synchronized void onQueryComplete(int token, Object cookie, - Cursor cursor) { - if (cursor == null || isFinishing()) { - // close cursor - if any - if (cursor != null) - cursor.close(); - - Log.e(TAG, "query aborted or error!"); - unregisterPeerObserver(); - mListAdapter.changeCursor(null); - return; - } - - switch (token) { - case MESSAGE_LIST_QUERY_TOKEN: - - // no messages to show - exit - if (cursor.getCount() == 0 - && (mConversation == null || - // no draft - (mConversation.getDraft() == null && - // no subscription request - mConversation.getRequestStatus() != Threads.REQUEST_WAITING && - // no text in compose entry - mTextEntry.getText().length() == 0))) { - - Log.i(TAG, "no data to view - exit"); - - // close conversation - closeConversation(); - - } - else { - // see if we have to scroll to a specific message - int newSelectionPos = -1; - - Bundle args = myArguments(); - if (args != null) { - long msgId = args.getLong(ComposeMessage.EXTRA_MESSAGE, - -1); - if (msgId > 0) { - - cursor.moveToPosition(-1); - while (cursor.moveToNext()) { - long curId = cursor.getLong(CompositeMessage.COLUMN_ID); - if (curId == msgId) { - newSelectionPos = cursor.getPosition(); - break; - } - } - } - } - - mListAdapter.changeCursor(cursor); - if (newSelectionPos > 0) - getListView().setSelection(newSelectionPos); - - getActivity().setProgressBarIndeterminateVisibility(false); - updateUI(); - } - - break; - - case CONVERSATION_QUERY_TOKEN: - if (cursor.moveToFirst()) { - mConversation = Conversation.createFromCursor( - getActivity(), cursor); - onConversationCreated(); - } - - cursor.close(); - - break; - - default: - Log.e(TAG, "onQueryComplete called with unknown token " + token); - } - } - } - - public Conversation getConversation() { - return mConversation; - } - - public Contact getContact() { - return (mConversation != null) ? mConversation.getContact() : null; - } - - public long getThreadId() { - return threadId; - } - - public String getUserId() { - return userId; - } - - public void setTextEntry(CharSequence text) { - mTextEntry.setText(text); - } - - @Override - public boolean onLongClick(View v) { - // this seems to be necessary... - return false; - } - - public void closeConversation() { - // main activity + private final class MessageListQueryHandler extends AsyncQueryHandler { + public MessageListQueryHandler() { + super(getActivity().getApplicationContext().getContentResolver()); + } + + @Override + protected synchronized void onQueryComplete(int token, Object cookie, + Cursor cursor) { + if (cursor == null || isFinishing()) { + // close cursor - if any + if (cursor != null) + cursor.close(); + + Log.e(TAG, "query aborted or error!"); + unregisterPeerObserver(); + mListAdapter.changeCursor(null); + return; + } + + switch (token) { + case MESSAGE_LIST_QUERY_TOKEN: + + // no messages to show - exit + if (cursor.getCount() == 0 + && (mConversation == null || + // no draft + (mConversation.getDraft() == null && + // no subscription request + mConversation.getRequestStatus() != Threads.REQUEST_WAITING && + // no text in compose entry + mTextEntry.getText().length() == 0))) { + + Log.i(TAG, "no data to view - exit"); + + // close conversation + closeConversation(); + + } + else { + // see if we have to scroll to a specific message + int newSelectionPos = -1; + + Bundle args = myArguments(); + if (args != null) { + long msgId = args.getLong(ComposeMessage.EXTRA_MESSAGE, + -1); + if (msgId > 0) { + + cursor.moveToPosition(-1); + while (cursor.moveToNext()) { + long curId = cursor.getLong(CompositeMessage.COLUMN_ID); + if (curId == msgId) { + newSelectionPos = cursor.getPosition(); + break; + } + } + } + } + + mListAdapter.changeCursor(cursor); + if (newSelectionPos > 0) + getListView().setSelection(newSelectionPos); + + getActivity().setProgressBarIndeterminateVisibility(false); + updateUI(); + } + + break; + + case CONVERSATION_QUERY_TOKEN: + if (cursor.moveToFirst()) { + mConversation = Conversation.createFromCursor( + getActivity(), cursor); + onConversationCreated(); + } + + cursor.close(); + + break; + + default: + Log.e(TAG, "onQueryComplete called with unknown token " + token); + } + } + } + + public Conversation getConversation() { + return mConversation; + } + + public Contact getContact() { + return (mConversation != null) ? mConversation.getContact() : null; + } + + public long getThreadId() { + return threadId; + } + + public String getUserId() { + return userId; + } + + public void setTextEntry(CharSequence text) { + mTextEntry.setText(text); + } + + @Override + public boolean onLongClick(View v) { + // this seems to be necessary... + return false; + } + + public void closeConversation() { + // main activity if (getParentActivity() != null) { getActivity().finish(); } @@ -2377,14 +2377,14 @@ public void closeConversation() { ConversationList activity = (ConversationList) getActivity(); activity.getListFragment().endConversation(this); } - } + } - private void offlineModeWarning() { - if (Preferences.getOfflineMode(getActivity()) && !mOfflineModeWarned) { - mOfflineModeWarned = true; - Toast.makeText(getActivity(), R.string.warning_offline_mode, - Toast.LENGTH_LONG).show(); - } - } + private void offlineModeWarning() { + if (Preferences.getOfflineMode(getActivity()) && !mOfflineModeWarned) { + mOfflineModeWarned = true; + Toast.makeText(getActivity(), R.string.warning_offline_mode, + Toast.LENGTH_LONG).show(); + } + } } diff --git a/src/org/kontalk/ui/ContactsListActivity.java b/src/org/kontalk/ui/ContactsListActivity.java index d144087a7..7c1ed8fde 100644 --- a/src/org/kontalk/ui/ContactsListActivity.java +++ b/src/org/kontalk/ui/ContactsListActivity.java @@ -165,28 +165,28 @@ private void startInvite() { if (resInfo != null && resInfo.size() > 1) { List targets = new ArrayList(); - for (ResolveInfo resolveInfo : resInfo) { + for (ResolveInfo resolveInfo : resInfo) { String packageName = resolveInfo.activityInfo.packageName; if (!getPackageName().equals(packageName)) { - // copy intent and add resolved info - Intent targetShareIntent = new Intent(shareIntent); - targetShareIntent - .setPackage(packageName) - .setComponent(new ComponentName( - packageName, resolveInfo.activityInfo.name)) - .putExtra("org.kontalk.invite.label", resolveInfo.loadLabel(getPackageManager())); - - targets.add(targetShareIntent); + // copy intent and add resolved info + Intent targetShareIntent = new Intent(shareIntent); + targetShareIntent + .setPackage(packageName) + .setComponent(new ComponentName( + packageName, resolveInfo.activityInfo.name)) + .putExtra("org.kontalk.invite.label", resolveInfo.loadLabel(getPackageManager())); + + targets.add(targetShareIntent); } } - // initial intents are added before of the main intent, so we remove the last one here + // initial intents are added before of the main intent, so we remove the last one here Intent chooser = Intent.createChooser(targets.remove(targets.size() - 1), getString(R.string.menu_invite)); Collections.sort(targets, new DisplayNameComparator()); // remove custom extras for (Intent intent : targets) - intent.removeExtra("org.kontalk.invite.label"); + intent.removeExtra("org.kontalk.invite.label"); Parcelable[] extraIntents = new Parcelable[targets.size()]; targets.toArray(extraIntents); @@ -196,30 +196,30 @@ private void startInvite() { } else { - // no activity to handle invitation - Toast.makeText(this, R.string.warn_invite_no_app, - Toast.LENGTH_SHORT).show(); + // no activity to handle invitation + Toast.makeText(this, R.string.warn_invite_no_app, + Toast.LENGTH_SHORT).show(); } } - public static class DisplayNameComparator implements - Comparator { - public DisplayNameComparator() { - mCollator.setStrength(Collator.PRIMARY); - } - - public final int compare(Intent a, Intent b) { - CharSequence sa = a.getCharSequenceExtra("org.kontalk.invite.label"); - if (sa == null) - sa = a.getComponent().getClassName(); - CharSequence sb = b.getCharSequenceExtra("org.kontalk.invite.label"); - if (sb == null) - sb = b.getComponent().getClassName(); - - return mCollator.compare(sa.toString(), sb.toString()); - } - - private final Collator mCollator = Collator.getInstance(); - } + public static class DisplayNameComparator implements + Comparator { + public DisplayNameComparator() { + mCollator.setStrength(Collator.PRIMARY); + } + + public final int compare(Intent a, Intent b) { + CharSequence sa = a.getCharSequenceExtra("org.kontalk.invite.label"); + if (sa == null) + sa = a.getComponent().getClassName(); + CharSequence sb = b.getCharSequenceExtra("org.kontalk.invite.label"); + if (sb == null) + sb = b.getComponent().getClassName(); + + return mCollator.compare(sa.toString(), sb.toString()); + } + + private final Collator mCollator = Collator.getInstance(); + } } diff --git a/src/org/kontalk/ui/ConversationList.java b/src/org/kontalk/ui/ConversationList.java index 33e22162d..1ccc6eb9a 100644 --- a/src/org/kontalk/ui/ConversationList.java +++ b/src/org/kontalk/ui/ConversationList.java @@ -76,7 +76,7 @@ public void onCreate(Bundle savedInstanceState) { .findFragmentById(R.id.fragment_conversation_list); if (!xmppUpgrade()) - handleIntent(getIntent()); + handleIntent(getIntent()); } public void titleComposeMessage(View view) { @@ -92,26 +92,26 @@ private boolean xmppUpgrade() { AccountManager am = (AccountManager) getSystemService(Context.ACCOUNT_SERVICE); Account account = Authenticator.getDefaultAccount(am); if (account != null) { - // adjust manual server address if any - String manualServer = Preferences.getServerURI(this); - if (!TextUtils.isEmpty(manualServer) && manualServer.indexOf('|') < 0) { - ServerList list = ServerListUpdater.getCurrentList(this); - if (list != null) { - EndpointServer server = list.random(); - String newServer = server.getNetwork() + "|" + manualServer; - - Preferences.setServerURI(this, newServer); - } - } + // adjust manual server address if any + String manualServer = Preferences.getServerURI(this); + if (!TextUtils.isEmpty(manualServer) && manualServer.indexOf('|') < 0) { + ServerList list = ServerListUpdater.getCurrentList(this); + if (list != null) { + EndpointServer server = list.random(); + String newServer = server.getNetwork() + "|" + manualServer; + + Preferences.setServerURI(this, newServer); + } + } if (!Authenticator.hasPersonalKey(am, account)) { - // first of all, disable offline mode - Preferences.setOfflineMode(this, false); + // first of all, disable offline mode + Preferences.setOfflineMode(this, false); - // ask for user name - askForPersonalName(); + // ask for user name + askForPersonalName(); - return true; + return true; } } @@ -119,50 +119,50 @@ private boolean xmppUpgrade() { } private void askForPersonalName() { - DialogInterface.OnClickListener okListener = new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int which) { + DialogInterface.OnClickListener okListener = new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { // no key pair found, generate a new one Toast.makeText(ConversationList.this, - R.string.msg_generating_keypair, Toast.LENGTH_LONG).show(); + R.string.msg_generating_keypair, Toast.LENGTH_LONG).show(); String name = InputDialog - .getTextFromAlertDialog((AlertDialog) dialog) - .toString(); + .getTextFromAlertDialog((AlertDialog) dialog) + .toString(); // upgrade account LegacyAuthentication.doUpgrade(getApplicationContext(), name); - } - }; - - DialogInterface.OnCancelListener cancelListener = new DialogInterface.OnCancelListener() { - public void onCancel(DialogInterface dialog) { - new AlertDialog.Builder(ConversationList.this) - .setTitle(R.string.title_no_personal_key) - .setMessage(R.string.msg_no_personal_key) - .setPositiveButton(android.R.string.ok, null) - .show(); - } - }; - - new InputDialog.Builder(this, - InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PERSON_NAME) - .setTitle(R.string.title_no_name) - .setMessage(R.string.msg_no_name) - .setPositiveButton(android.R.string.ok, okListener) - .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int which) { - dialog.cancel(); - } - }) - .setOnCancelListener(cancelListener) - .show(); + } + }; + + DialogInterface.OnCancelListener cancelListener = new DialogInterface.OnCancelListener() { + public void onCancel(DialogInterface dialog) { + new AlertDialog.Builder(ConversationList.this) + .setTitle(R.string.title_no_personal_key) + .setMessage(R.string.msg_no_personal_key) + .setPositiveButton(android.R.string.ok, null) + .show(); + } + }; + + new InputDialog.Builder(this, + InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PERSON_NAME) + .setTitle(R.string.title_no_name) + .setMessage(R.string.msg_no_name) + .setPositiveButton(android.R.string.ok, okListener) + .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + dialog.cancel(); + } + }) + .setOnCancelListener(cancelListener) + .show(); } /** Called when a new intent is sent to the activity (if already started). */ @Override protected void onNewIntent(Intent intent) { - handleIntent(intent); + handleIntent(intent); ConversationListFragment fragment = getListFragment(); fragment.startQuery(); @@ -170,23 +170,23 @@ protected void onNewIntent(Intent intent) { @Override protected Dialog onCreateDialog(int id, Bundle args) { - if (id == DIALOG_AUTH_ERROR_WARNING) { + if (id == DIALOG_AUTH_ERROR_WARNING) { - return new AlertDialog.Builder(this) - .setTitle(R.string.title_auth_error) - .setMessage(Html.fromHtml(getString(R.string.msg_auth_error))) - .setPositiveButton(android.R.string.ok, null) - .create(); + return new AlertDialog.Builder(this) + .setTitle(R.string.title_auth_error) + .setMessage(Html.fromHtml(getString(R.string.msg_auth_error))) + .setPositiveButton(android.R.string.ok, null) + .create(); - } + } - return super.onCreateDialog(id, args); + return super.onCreateDialog(id, args); } private void handleIntent(Intent intent) { - if (intent != null && ACTION_AUTH_ERROR_WARNING.equals(intent.getAction())) { - showDialog(DIALOG_AUTH_ERROR_WARNING); - } + if (intent != null && ACTION_AUTH_ERROR_WARNING.equals(intent.getAction())) { + showDialog(DIALOG_AUTH_ERROR_WARNING); + } } @Override diff --git a/src/org/kontalk/ui/ConversationListFragment.java b/src/org/kontalk/ui/ConversationListFragment.java index 409fc77b2..e543bbd34 100644 --- a/src/org/kontalk/ui/ConversationListFragment.java +++ b/src/org/kontalk/ui/ConversationListFragment.java @@ -114,7 +114,7 @@ public void onActivityCreated(Bundle savedInstanceState) { else { // TODO restore state list.setChoiceMode(ListView.CHOICE_MODE_SINGLE); - list.setItemsCanFocus(true); + list.setItemsCanFocus(true); } // text for empty conversation list @@ -363,7 +363,7 @@ public void onListItemClick(ListView l, View v, int position, long id) { ConversationList parent = getParentActivity(); if (parent != null) - parent.openConversation(conv, position); + parent.openConversation(conv, position); } /** Used only in fragment contexts. */ diff --git a/src/org/kontalk/ui/ConversationListItem.java b/src/org/kontalk/ui/ConversationListItem.java index 97005f451..ed66c1ad4 100644 --- a/src/org/kontalk/ui/ConversationListItem.java +++ b/src/org/kontalk/ui/ConversationListItem.java @@ -129,27 +129,27 @@ public final void bind(Context context, final Conversation conv) { // last message or draft?? if (conv.getRequestStatus() == Threads.REQUEST_WAITING) { - // TODO i18n and italic (?) - text = "(chat invitation)"; + // TODO i18n and italic (?) + text = "(chat invitation)"; } else { - String source = (draft != null) ? draft : conv.getSubject(); - - if (source != null) { - text = new SpannableString(source); - MessageUtils.convertSmileys(context, (Spannable) text, SmileyImageSpan.SIZE_LISTITEM); - if (conv.getUnreadCount() > 0) - ((Spannable) text).setSpan(STYLE_BOLD, 0, text.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE); - } - - else if (conv.isEncrypted()) { - text = context.getString(R.string.text_encrypted); - } - - else { - // determine from mime type - text = CompositeMessage.getSampleTextContent(conv.getMime()); - } + String source = (draft != null) ? draft : conv.getSubject(); + + if (source != null) { + text = new SpannableString(source); + MessageUtils.convertSmileys(context, (Spannable) text, SmileyImageSpan.SIZE_LISTITEM); + if (conv.getUnreadCount() > 0) + ((Spannable) text).setSpan(STYLE_BOLD, 0, text.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE); + } + + else if (conv.isEncrypted()) { + text = context.getString(R.string.text_encrypted); + } + + else { + // determine from mime type + text = CompositeMessage.getSampleTextContent(conv.getMime()); + } } mSubjectView.setText(text); @@ -190,12 +190,12 @@ else if (conv.isEncrypted()) { int unread = mConversation.getUnreadCount(); if (unread > 0) { - mCounterView.setText(String.valueOf(unread)); - mCounterView.setVisibility(VISIBLE); + mCounterView.setText(String.valueOf(unread)); + mCounterView.setVisibility(VISIBLE); } } else { - mCounterView.setVisibility(GONE); + mCounterView.setVisibility(GONE); mErrorIndicator.setVisibility(VISIBLE); mErrorIndicator.setImageResource(resId); mErrorIndicator.setContentDescription(getResources().getString(statusId)); diff --git a/src/org/kontalk/ui/DonationFragment.java b/src/org/kontalk/ui/DonationFragment.java index 1eb840ee7..7b26d2fc6 100644 --- a/src/org/kontalk/ui/DonationFragment.java +++ b/src/org/kontalk/ui/DonationFragment.java @@ -71,8 +71,8 @@ public void onIabPurchaseFinished(IabResult result, Purchase purchase) { }; public IabHelper getIabHelper() { - return mIabHelper; - } + return mIabHelper; + } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { @@ -121,21 +121,21 @@ private void donateBitcoin() { startActivity(intent); else new AlertDialog - .Builder(getActivity()) - .setTitle(R.string.title_bitcoin_dialog) - .setMessage(getString(R.string.text_bitcoin_dialog, address)) - .setPositiveButton(android.R.string.ok, null) - .setNeutralButton(R.string.copy_clipboard, new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int which) { - ClipboardManager cpm = (ClipboardManager) getActivity() - .getSystemService(Context.CLIPBOARD_SERVICE); - cpm.setText(address); - - Toast.makeText(getActivity(), R.string.bitcoin_clipboard_copied, - Toast.LENGTH_LONG).show(); - } - }) - .show(); + .Builder(getActivity()) + .setTitle(R.string.title_bitcoin_dialog) + .setMessage(getString(R.string.text_bitcoin_dialog, address)) + .setPositiveButton(android.R.string.ok, null) + .setNeutralButton(R.string.copy_clipboard, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + ClipboardManager cpm = (ClipboardManager) getActivity() + .getSystemService(Context.CLIPBOARD_SERVICE); + cpm.setText(address); + + Toast.makeText(getActivity(), R.string.bitcoin_clipboard_copied, + Toast.LENGTH_LONG).show(); + } + }) + .show(); } private void donatePaypal() { @@ -144,28 +144,28 @@ private void donatePaypal() { } private void setupGoogle(final ProgressDialog progress) { - if (mIabHelper == null) { - mIabHelper = new IabHelper(getActivity()); - mIabHelper.enableDebugLogging(BuildConfig.DEBUG); - - mIabHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() { - public void onIabSetupFinished(IabResult result) { - - if (!result.isSuccess()) { - alert(R.string.title_error, getString(R.string.iab_error_setup, result.getResponse())); - mIabHelper = null; - progress.dismiss(); - return; - } - - queryInventory(progress); - } - }); - } - - else { - queryInventory(progress); - } + if (mIabHelper == null) { + mIabHelper = new IabHelper(getActivity()); + mIabHelper.enableDebugLogging(BuildConfig.DEBUG); + + mIabHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() { + public void onIabSetupFinished(IabResult result) { + + if (!result.isSuccess()) { + alert(R.string.title_error, getString(R.string.iab_error_setup, result.getResponse())); + mIabHelper = null; + progress.dismiss(); + return; + } + + queryInventory(progress); + } + }); + } + + else { + queryInventory(progress); + } } private void queryInventory(final ProgressDialog progress) { @@ -227,10 +227,10 @@ private void donateGoogle() { getString(R.string.msg_connecting_iab), true, true, new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { - // FIXME this doesn't seem to work in some cases + // FIXME this doesn't seem to work in some cases if (mIabHelper != null) { - mIabHelper.dispose(); - mIabHelper = null; + mIabHelper.dispose(); + mIabHelper = null; } } }); diff --git a/src/org/kontalk/ui/IconContextMenu.java b/src/org/kontalk/ui/IconContextMenu.java index f72dc5479..7350cb32f 100644 --- a/src/org/kontalk/ui/IconContextMenu.java +++ b/src/org/kontalk/ui/IconContextMenu.java @@ -1,263 +1,263 @@ -/* - * Copyright (C) 2010 Tani Group - * http://android-demo.blogspot.com/ - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.kontalk.ui; - -import java.util.ArrayList; - -import android.app.Activity; -import android.app.AlertDialog; -import android.app.Dialog; -import android.content.Context; -import android.content.DialogInterface; -import android.content.res.Resources; -import android.content.res.Resources.Theme; -import android.graphics.drawable.Drawable; -import android.util.TypedValue; -import android.view.View; -import android.view.ViewGroup; -import android.widget.AbsListView; -import android.widget.BaseAdapter; -import android.widget.TextView; - -/** - * @author nguyendt - * - */ -public class IconContextMenu implements DialogInterface.OnCancelListener, - DialogInterface.OnDismissListener{ - - private static final int LIST_PREFERED_HEIGHT = 65; - - private IconMenuAdapter menuAdapter = null; - private Activity parentActivity = null; - private int dialogId = 0; - - private IconContextMenuOnClickListener clickHandler = null; - - /** - * constructor - * @param parent - * @param id - */ - public IconContextMenu(Activity parent, int id) { - this.parentActivity = parent; - this.dialogId = id; - - menuAdapter = new IconMenuAdapter(parentActivity); - } - - /** - * Add menu item - * @param menuItem - */ - public void addItem(Resources res, CharSequence title, - int imageResourceId, int actionTag) { - menuAdapter.addItem(new IconContextMenuItem(res, title, imageResourceId, actionTag)); - } - - public void addItem(Resources res, int textResourceId, - int imageResourceId, int actionTag) { - menuAdapter.addItem(new IconContextMenuItem(res, textResourceId, imageResourceId, actionTag)); - } - - /** - * Set menu onclick listener - * @param listener - */ - public void setOnClickListener(IconContextMenuOnClickListener listener) { - clickHandler = listener; - } - - /** - * Create menu - * @return - */ - public Dialog createMenu(String menuItitle) { - final AlertDialog.Builder builder = new AlertDialog.Builder(parentActivity); - builder.setTitle(menuItitle); - builder.setAdapter(menuAdapter, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialoginterface, int i) { - IconContextMenuItem item = (IconContextMenuItem) menuAdapter.getItem(i); - - if (clickHandler != null) { - clickHandler.onClick(item.actionTag); - } - } - }); - - builder.setInverseBackgroundForced(true); - - AlertDialog dialog = builder.create(); - dialog.setOnCancelListener(this); - dialog.setOnDismissListener(this); - return dialog; - } - - public void onCancel(DialogInterface dialog) { - cleanup(); - } - - public void onDismiss(DialogInterface dialog) { - } - - private void cleanup() { - try { - parentActivity.dismissDialog(dialogId); - } - catch (IllegalArgumentException e) { - // ignore - } - } - - /** - * IconContextMenu On Click Listener interface - */ - public interface IconContextMenuOnClickListener { - public abstract void onClick(int menuId); - } - - /** - * Menu-like list adapter with icon - */ - protected class IconMenuAdapter extends BaseAdapter { - private Context context = null; - - private ArrayList mItems = new ArrayList(); - - public IconMenuAdapter(Context context) { - this.context = context; - } - - /** - * add item to adapter - * @param menuItem - */ - public void addItem(IconContextMenuItem menuItem) { - mItems.add(menuItem); - } - - @Override - public int getCount() { - return mItems.size(); - } - - @Override - public Object getItem(int position) { - return mItems.get(position); - } - - @Override - public long getItemId(int position) { - IconContextMenuItem item = (IconContextMenuItem) getItem(position); - return item.actionTag; - } - - @Override - public View getView(int position, View convertView, ViewGroup parent) { - IconContextMenuItem item = (IconContextMenuItem) getItem(position); - - Resources res = parentActivity.getResources(); - - if (convertView == null) { - TextView temp = new TextView(context); - AbsListView.LayoutParams param = new AbsListView.LayoutParams(AbsListView.LayoutParams.FILL_PARENT, - AbsListView.LayoutParams.WRAP_CONTENT); - temp.setLayoutParams(param); - temp.setPadding((int)toPixel(res, 15), 0, (int)toPixel(res, 15), 0); - temp.setGravity(android.view.Gravity.CENTER_VERTICAL); - - Theme th = context.getTheme(); - TypedValue tv = new TypedValue(); - - if (th.resolveAttribute(android.R.attr.textAppearanceLarge, tv, true)) { - temp.setTextAppearance(context, tv.resourceId); - } - - temp.setMinHeight((int)toPixel(res, LIST_PREFERED_HEIGHT)); - temp.setCompoundDrawablePadding((int)toPixel(res, 14)); - convertView = temp; - } - - TextView textView = (TextView) convertView; - textView.setTag(item); - textView.setText(item.text); - textView.setCompoundDrawablesWithIntrinsicBounds(item.image, null, null, null); - - return textView; - } - - private float toPixel(Resources res, int dip) { - float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip, res.getDisplayMetrics()); - return px; - } - } - - /** - * menu-like list item with icon - */ - protected class IconContextMenuItem { - public final CharSequence text; - public final Drawable image; - public final int actionTag; - - /** - * public constructor - * - * @param res - * resource handler - * @param textResourceId - * id of title in resource - * @param imageResourceId - * id of icon in resource - * @param actionTag - * indicate action of menu item - */ - public IconContextMenuItem(Resources res, int textResourceId, - int imageResourceId, int actionTag) { - text = res.getString(textResourceId); - if (imageResourceId != -1) { - image = res.getDrawable(imageResourceId); - } else { - image = null; - } - this.actionTag = actionTag; - } - - /** - * public constructor - * @param res - * resource handler - * @param title - * menu item title - * @param imageResourceId - * id of icon in resource - * @param actionTag - * indicate action of menu item - */ - public IconContextMenuItem(Resources res, CharSequence title, - int imageResourceId, int actionTag) { - text = title; - if (imageResourceId != -1) { - image = res.getDrawable(imageResourceId); - } else { - image = null; - } - this.actionTag = actionTag; - } - } -} +/* + * Copyright (C) 2010 Tani Group + * http://android-demo.blogspot.com/ + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.kontalk.ui; + +import java.util.ArrayList; + +import android.app.Activity; +import android.app.AlertDialog; +import android.app.Dialog; +import android.content.Context; +import android.content.DialogInterface; +import android.content.res.Resources; +import android.content.res.Resources.Theme; +import android.graphics.drawable.Drawable; +import android.util.TypedValue; +import android.view.View; +import android.view.ViewGroup; +import android.widget.AbsListView; +import android.widget.BaseAdapter; +import android.widget.TextView; + +/** + * @author nguyendt + * + */ +public class IconContextMenu implements DialogInterface.OnCancelListener, + DialogInterface.OnDismissListener{ + + private static final int LIST_PREFERED_HEIGHT = 65; + + private IconMenuAdapter menuAdapter = null; + private Activity parentActivity = null; + private int dialogId = 0; + + private IconContextMenuOnClickListener clickHandler = null; + + /** + * constructor + * @param parent + * @param id + */ + public IconContextMenu(Activity parent, int id) { + this.parentActivity = parent; + this.dialogId = id; + + menuAdapter = new IconMenuAdapter(parentActivity); + } + + /** + * Add menu item + * @param menuItem + */ + public void addItem(Resources res, CharSequence title, + int imageResourceId, int actionTag) { + menuAdapter.addItem(new IconContextMenuItem(res, title, imageResourceId, actionTag)); + } + + public void addItem(Resources res, int textResourceId, + int imageResourceId, int actionTag) { + menuAdapter.addItem(new IconContextMenuItem(res, textResourceId, imageResourceId, actionTag)); + } + + /** + * Set menu onclick listener + * @param listener + */ + public void setOnClickListener(IconContextMenuOnClickListener listener) { + clickHandler = listener; + } + + /** + * Create menu + * @return + */ + public Dialog createMenu(String menuItitle) { + final AlertDialog.Builder builder = new AlertDialog.Builder(parentActivity); + builder.setTitle(menuItitle); + builder.setAdapter(menuAdapter, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialoginterface, int i) { + IconContextMenuItem item = (IconContextMenuItem) menuAdapter.getItem(i); + + if (clickHandler != null) { + clickHandler.onClick(item.actionTag); + } + } + }); + + builder.setInverseBackgroundForced(true); + + AlertDialog dialog = builder.create(); + dialog.setOnCancelListener(this); + dialog.setOnDismissListener(this); + return dialog; + } + + public void onCancel(DialogInterface dialog) { + cleanup(); + } + + public void onDismiss(DialogInterface dialog) { + } + + private void cleanup() { + try { + parentActivity.dismissDialog(dialogId); + } + catch (IllegalArgumentException e) { + // ignore + } + } + + /** + * IconContextMenu On Click Listener interface + */ + public interface IconContextMenuOnClickListener { + public abstract void onClick(int menuId); + } + + /** + * Menu-like list adapter with icon + */ + protected class IconMenuAdapter extends BaseAdapter { + private Context context = null; + + private ArrayList mItems = new ArrayList(); + + public IconMenuAdapter(Context context) { + this.context = context; + } + + /** + * add item to adapter + * @param menuItem + */ + public void addItem(IconContextMenuItem menuItem) { + mItems.add(menuItem); + } + + @Override + public int getCount() { + return mItems.size(); + } + + @Override + public Object getItem(int position) { + return mItems.get(position); + } + + @Override + public long getItemId(int position) { + IconContextMenuItem item = (IconContextMenuItem) getItem(position); + return item.actionTag; + } + + @Override + public View getView(int position, View convertView, ViewGroup parent) { + IconContextMenuItem item = (IconContextMenuItem) getItem(position); + + Resources res = parentActivity.getResources(); + + if (convertView == null) { + TextView temp = new TextView(context); + AbsListView.LayoutParams param = new AbsListView.LayoutParams(AbsListView.LayoutParams.FILL_PARENT, + AbsListView.LayoutParams.WRAP_CONTENT); + temp.setLayoutParams(param); + temp.setPadding((int)toPixel(res, 15), 0, (int)toPixel(res, 15), 0); + temp.setGravity(android.view.Gravity.CENTER_VERTICAL); + + Theme th = context.getTheme(); + TypedValue tv = new TypedValue(); + + if (th.resolveAttribute(android.R.attr.textAppearanceLarge, tv, true)) { + temp.setTextAppearance(context, tv.resourceId); + } + + temp.setMinHeight((int)toPixel(res, LIST_PREFERED_HEIGHT)); + temp.setCompoundDrawablePadding((int)toPixel(res, 14)); + convertView = temp; + } + + TextView textView = (TextView) convertView; + textView.setTag(item); + textView.setText(item.text); + textView.setCompoundDrawablesWithIntrinsicBounds(item.image, null, null, null); + + return textView; + } + + private float toPixel(Resources res, int dip) { + float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip, res.getDisplayMetrics()); + return px; + } + } + + /** + * menu-like list item with icon + */ + protected class IconContextMenuItem { + public final CharSequence text; + public final Drawable image; + public final int actionTag; + + /** + * public constructor + * + * @param res + * resource handler + * @param textResourceId + * id of title in resource + * @param imageResourceId + * id of icon in resource + * @param actionTag + * indicate action of menu item + */ + public IconContextMenuItem(Resources res, int textResourceId, + int imageResourceId, int actionTag) { + text = res.getString(textResourceId); + if (imageResourceId != -1) { + image = res.getDrawable(imageResourceId); + } else { + image = null; + } + this.actionTag = actionTag; + } + + /** + * public constructor + * @param res + * resource handler + * @param title + * menu item title + * @param imageResourceId + * id of icon in resource + * @param actionTag + * indicate action of menu item + */ + public IconContextMenuItem(Resources res, CharSequence title, + int imageResourceId, int actionTag) { + text = title; + if (imageResourceId != -1) { + image = res.getDrawable(imageResourceId); + } else { + image = null; + } + this.actionTag = actionTag; + } + } +} diff --git a/src/org/kontalk/ui/InputDialog.java b/src/org/kontalk/ui/InputDialog.java index ee674d91b..4e800a87b 100644 --- a/src/org/kontalk/ui/InputDialog.java +++ b/src/org/kontalk/ui/InputDialog.java @@ -32,52 +32,52 @@ */ public class InputDialog extends AlertDialog { - private static final int TEXT_VIEW_ID = R.id.textinput; + private static final int TEXT_VIEW_ID = R.id.textinput; - public InputDialog(Context context) { - super(context); - } + public InputDialog(Context context) { + super(context); + } - public InputDialog(Context context, int theme) { - super(context, theme); - } + public InputDialog(Context context, int theme) { + super(context, theme); + } - public InputDialog(Context context, boolean cancelable, OnCancelListener cancelListener) { - super(context, cancelable, cancelListener); - } + public InputDialog(Context context, boolean cancelable, OnCancelListener cancelListener) { + super(context, cancelable, cancelListener); + } - public CharSequence getText() { - return getTextFromAlertDialog(this); - } + public CharSequence getText() { + return getTextFromAlertDialog(this); + } - public static CharSequence getTextFromAlertDialog(AlertDialog dialog) { - return ((EditText) dialog.findViewById(TEXT_VIEW_ID)).getText(); - } + public static CharSequence getTextFromAlertDialog(AlertDialog dialog) { + return ((EditText) dialog.findViewById(TEXT_VIEW_ID)).getText(); + } - public static class Builder extends AlertDialog.Builder { + public static class Builder extends AlertDialog.Builder { - public Builder(Context context, int inputType) { - super(context); + public Builder(Context context, int inputType) { + super(context); - setCustomView(context, inputType); - } + setCustomView(context, inputType); + } - private void setCustomView(Context context, int inputType) { - /* - EditText txt = new EditText(context); - txt.setInputType(inputType); - txt.setId(TEXT_VIEW_ID); - */ + private void setCustomView(Context context, int inputType) { + /* + EditText txt = new EditText(context); + txt.setInputType(inputType); + txt.setId(TEXT_VIEW_ID); + */ - setView(LayoutInflater.from(context) - .inflate(R.layout.edittext_dialog, null, false)); - } + setView(LayoutInflater.from(context) + .inflate(R.layout.edittext_dialog, null, false)); + } - @Override - public AlertDialog create() { - return super.create(); - } + @Override + public AlertDialog create() { + return super.create(); + } - } + } } diff --git a/src/org/kontalk/ui/MessageListAdapter.java b/src/org/kontalk/ui/MessageListAdapter.java index 6564f8747..49643c03c 100644 --- a/src/org/kontalk/ui/MessageListAdapter.java +++ b/src/org/kontalk/ui/MessageListAdapter.java @@ -69,7 +69,7 @@ public void bindView(View view, Context context, Cursor cursor) { MessageListItem headerView = (MessageListItem) view; CompositeMessage msg = CompositeMessage.fromCursor(context, cursor); if (msg.getDirection() == Messages.DIRECTION_IN && mContact == null) - mContact = Contact.findByUserId(context, msg.getSender()); + mContact = Contact.findByUserId(context, msg.getSender()); headerView.bind(context, msg, mContact, mHighlight); } diff --git a/src/org/kontalk/ui/MessageListItem.java b/src/org/kontalk/ui/MessageListItem.java index c7fef7871..df2e47a93 100644 --- a/src/org/kontalk/ui/MessageListItem.java +++ b/src/org/kontalk/ui/MessageListItem.java @@ -59,11 +59,11 @@ public class MessageListItem extends RelativeLayout { //private static final String TAG = MessageListItem.class.getSimpleName(); - /** - * Maximum affordable size of a text message to make complex stuff - * (e.g. emoji, linkify, etc.) - */ - private static final int MAX_AFFORDABLE_SIZE = 10240; // 10 KB + /** + * Maximum affordable size of a text message to make complex stuff + * (e.g. emoji, linkify, etc.) + */ + private static final int MAX_AFFORDABLE_SIZE = 10240; // 10 KB static private Drawable sDefaultContactImage; @@ -134,7 +134,7 @@ protected void onFinishInflate() { mDateView.setText("28 Nov"); */ - /* OUTGOING */ + /* OUTGOING */ if (mStatusIcon != null) { mStatusIcon.setImageResource(R.drawable.ic_msg_delivered); mStatusIcon.setVisibility(VISIBLE); @@ -173,7 +173,7 @@ else if (size.equals("large")) // linkify! boolean linksFound = false; if (mFormattedMessage.length() < MAX_AFFORDABLE_SIZE) - linksFound = Linkify.addLinks(mFormattedMessage, Linkify.ALL); + linksFound = Linkify.addLinks(mFormattedMessage, Linkify.ALL); /* * workaround for bugs: @@ -183,8 +183,8 @@ else if (size.equals("large")) */ if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB && android.os.Build.VERSION.SDK_INT <= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) - // from http://stackoverflow.com/a/12303155/1045199 - mFormattedMessage.append("\u200b"); // was: \u2060 + // from http://stackoverflow.com/a/12303155/1045199 + mFormattedMessage.append("\u200b"); // was: \u2060 if (linksFound) mTextView.setMovementMethod(LinkMovementMethod.getInstance()); @@ -199,18 +199,18 @@ else if (size.equals("large")) int securityFlags = mMessage.getSecurityFlags(); if (Coder.isError(securityFlags)) { - mWarningIcon.setImageResource(R.drawable.ic_msg_security); + mWarningIcon.setImageResource(R.drawable.ic_msg_security); mWarningIcon.setVisibility(VISIBLE); } else { - mWarningIcon.setImageResource(R.drawable.ic_msg_warning); - mWarningIcon.setVisibility((securityFlags != Coder.SECURITY_CLEARTEXT) ? GONE : VISIBLE); + mWarningIcon.setImageResource(R.drawable.ic_msg_warning); + mWarningIcon.setVisibility((securityFlags != Coder.SECURITY_CLEARTEXT) ? GONE : VISIBLE); } if (mMessage.getSender() != null) { if (mBalloonView != null) { - mBalloonView.setBackgroundResource(Preferences - .getBalloonResource(getContext(), Messages.DIRECTION_IN)); + mBalloonView.setBackgroundResource(Preferences + .getBalloonResource(getContext(), Messages.DIRECTION_IN)); } else { mParentView.setGravity(Gravity.LEFT); @@ -227,7 +227,7 @@ else if (size.equals("large")) } else { if (mBalloonView != null) { - mBalloonView.setBackgroundResource(Preferences + mBalloonView.setBackgroundResource(Preferences .getBalloonResource(getContext(), Messages.DIRECTION_OUT)); } else { @@ -316,50 +316,50 @@ private SpannableStringBuilder formatMessage(final Contact contact, final Patter String textContent = txt != null ? txt.getContent() : null; if (TextUtils.isEmpty(textContent)) { - buf = new SpannableStringBuilder(); - thumbnailOnly = true; + buf = new SpannableStringBuilder(); + thumbnailOnly = true; } else { - buf = new SpannableStringBuilder(textContent); - thumbnailOnly = false; + buf = new SpannableStringBuilder(textContent); + thumbnailOnly = false; } // convert smileys first int c = buf.length(); if (c > 0 && c < MAX_AFFORDABLE_SIZE) - MessageUtils.convertSmileys(getContext(), buf, SmileyImageSpan.SIZE_EDITABLE); + MessageUtils.convertSmileys(getContext(), buf, SmileyImageSpan.SIZE_EDITABLE); // image component: show image before text AttachmentComponent attachment = (AttachmentComponent) mMessage - .getComponent(AttachmentComponent.class); + .getComponent(AttachmentComponent.class); if (attachment != null) { - if (attachment instanceof ImageComponent) { - ImageComponent img = (ImageComponent) attachment; + if (attachment instanceof ImageComponent) { + ImageComponent img = (ImageComponent) attachment; - // prepend some text for the ImageSpan - String placeholder = CompositeMessage.getSampleTextContent(img.getContent().getMime()); - buf.insert(0, placeholder); + // prepend some text for the ImageSpan + String placeholder = CompositeMessage.getSampleTextContent(img.getContent().getMime()); + buf.insert(0, placeholder); - // add newline if there is some text after - if (!thumbnailOnly) - buf.insert(placeholder.length(), "\n"); + // add newline if there is some text after + if (!thumbnailOnly) + buf.insert(placeholder.length(), "\n"); - Bitmap bitmap = img.getBitmap(); - if (bitmap != null) { - ImageSpan imgSpan = new MaxSizeImageSpan(getContext(), bitmap); - buf.setSpan(imgSpan, 0, placeholder.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); - } + Bitmap bitmap = img.getBitmap(); + if (bitmap != null) { + ImageSpan imgSpan = new MaxSizeImageSpan(getContext(), bitmap); + buf.setSpan(imgSpan, 0, placeholder.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + } - } + } else { - // other component: show sample content if no body was found - if (txt == null) - buf.append(CompositeMessage.getSampleTextContent(attachment.getMime())); + // other component: show sample content if no body was found + if (txt == null) + buf.append(CompositeMessage.getSampleTextContent(attachment.getMime())); } diff --git a/src/org/kontalk/ui/MessagingNotification.java b/src/org/kontalk/ui/MessagingNotification.java index 9233166ad..943b63d2a 100644 --- a/src/org/kontalk/ui/MessagingNotification.java +++ b/src/org/kontalk/ui/MessagingNotification.java @@ -67,7 +67,7 @@ public class MessagingNotification { public static final int NOTIFICATION_ID_QUICK_REPLY = 107; public static final int NOTIFICATION_ID_KEYPAIR_GEN = 108; public static final int NOTIFICATION_ID_INVITATION = 109; - public static final int NOTIFICATION_ID_AUTH_ERROR = 110; + public static final int NOTIFICATION_ID_AUTH_ERROR = 110; private static final String[] MESSAGES_UNREAD_PROJECTION = { @@ -230,13 +230,13 @@ public static void updateMessagesNotification(Context context, boolean isNew) { boolean encrypted = c.getInt(4) != 0; if (encrypted) { - textContent = context.getString(R.string.text_encrypted); + textContent = context.getString(R.string.text_encrypted); } else if (content == null && attMime != null) { - textContent = CompositeMessage.getSampleTextContent(attMime); + textContent = CompositeMessage.getSampleTextContent(attMime); } else { - textContent = content != null ? new String(content) : ""; + textContent = content != null ? new String(content) : ""; } ((StringBuilder) b[0]).append(textContent); @@ -375,9 +375,9 @@ else if (content == null && attMime != null) { boolean encrypted = c.getInt(4) != 0; if (encrypted) - content = context.getString(R.string.text_encrypted); + content = context.getString(R.string.text_encrypted); else if (content == null) - content = CompositeMessage.getSampleTextContent(c.getString(2)); + content = CompositeMessage.getSampleTextContent(c.getString(2)); accumulator.accumulate( c.getLong(0), @@ -403,7 +403,7 @@ else if (content == null) } if (isNew) { - setDefaults(context, builder); + setDefaults(context, builder); } nm.notify(NOTIFICATION_ID_MESSAGES, builder.build()); @@ -440,9 +440,9 @@ private static void setDefaults(Context context, NotificationCompat.Builder buil /** Triggers a notification for a chat invitation. */ public static void chatInvitation(Context context, String userId) { - // open conversation, do not send notification - if (userId.equalsIgnoreCase(StringUtils.parseName(sPaused))) - return; + // open conversation, do not send notification + if (userId.equalsIgnoreCase(StringUtils.parseName(sPaused))) + return; // find the contact for the userId Contact contact = Contact.findByUserId(context, userId); @@ -453,12 +453,12 @@ public static void chatInvitation(Context context, String userId) { // notification will open the conversation Intent ni = ComposeMessage.fromUserId(context, userId); PendingIntent pi = PendingIntent.getActivity(context, - NOTIFICATION_ID_INVITATION, ni, 0); + NOTIFICATION_ID_INVITATION, ni, 0); // build the notification NotificationCompat.Builder builder = new NotificationCompat .Builder(context.getApplicationContext()) - .setAutoCancel(true) + .setAutoCancel(true) .setSmallIcon(R.drawable.stat_notify) .setTicker(context.getString(R.string.title_invitation)) .setContentTitle(title) @@ -488,12 +488,12 @@ public static void chatInvitation(Context context, String userId) { /** Cancel a chat invitation notification. */ public static void clearChatInvitation(Context context, String userId) { - if (userId.equalsIgnoreCase(sLastInvitation)) { + if (userId.equalsIgnoreCase(sLastInvitation)) { NotificationManager nm = (NotificationManager) context .getSystemService(Context.NOTIFICATION_SERVICE); nm.cancel(NOTIFICATION_ID_INVITATION); - } + } } /** Fires an authentication error notification. */ @@ -501,12 +501,12 @@ public static void authenticationError(Context context) { // notification will open the conversation Intent ni = ConversationList.authenticationErrorWarning(context); PendingIntent pi = PendingIntent.getActivity(context, - NOTIFICATION_ID_AUTH_ERROR, ni, 0); + NOTIFICATION_ID_AUTH_ERROR, ni, 0); // build the notification NotificationCompat.Builder builder = new NotificationCompat .Builder(context.getApplicationContext()) - .setAutoCancel(true) + .setAutoCancel(true) .setSmallIcon(R.drawable.stat_notify) .setTicker(context.getString(R.string.title_auth_error)) .setContentTitle(context.getString(R.string.title_auth_error)) diff --git a/src/org/kontalk/ui/NumberValidation.java b/src/org/kontalk/ui/NumberValidation.java index 33c8af2a2..02f524c4e 100644 --- a/src/org/kontalk/ui/NumberValidation.java +++ b/src/org/kontalk/ui/NumberValidation.java @@ -400,8 +400,8 @@ private boolean checkInput() { // check name first mName = mNameText.getText().toString().trim(); if (mName.length() == 0) { - error(R.string.title_no_name, R.string.msg_no_name); - return false; + error(R.string.title_no_name, R.string.msg_no_name); + return false; } PhoneNumberUtil util = PhoneNumberUtil.getInstance(); @@ -685,7 +685,7 @@ public void onValidationFailed(NumberValidator v, final int reason) { runOnUiThread(new Runnable() { @Override public void run() { - int msg; + int msg; if (reason == NumberValidator.ERROR_THROTTLING) msg = R.string.err_validation_retry_later; else diff --git a/src/org/kontalk/ui/PopupWindows.java b/src/org/kontalk/ui/PopupWindows.java index 440b847d4..4919df344 100644 --- a/src/org/kontalk/ui/PopupWindows.java +++ b/src/org/kontalk/ui/PopupWindows.java @@ -1,156 +1,156 @@ -/* - * Kontalk Android client - * Copyright (C) 2014 Kontalk Devteam - - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package org.kontalk.ui; - -import android.graphics.drawable.BitmapDrawable; -import android.graphics.drawable.Drawable; - -import android.view.LayoutInflater; -import android.view.MotionEvent; -import android.view.View; -import android.view.WindowManager; -import android.view.View.OnTouchListener; - -import android.widget.PopupWindow; -import android.content.Context; - -/** - * Custom popup window. - * - * @author Lorensius W. L. T - * - * @deprecated to be replaced by the bottom popup window - */ -@Deprecated -public class PopupWindows { - protected Context mContext; - protected PopupWindow mWindow; - protected View mRootView; - protected Drawable mBackground = null; - protected WindowManager mWindowManager; - - /** - * Constructor. - * - * @param context Context - */ - public PopupWindows(Context context) { - mContext = context; - mWindow = new PopupWindow(context); - - mWindow.setTouchInterceptor(new OnTouchListener() { - @Override - public boolean onTouch(View v, MotionEvent event) { - if (event.getAction() == MotionEvent.ACTION_OUTSIDE) { - mWindow.dismiss(); - - return true; - } - - return false; - } - }); - - mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); - } - - /** - * On dismiss - */ - protected void onDismiss() { - } - - /** - * On show - */ - protected void onShow() { - } - - /** - * On pre show - */ - protected void preShow() { - if (mRootView == null) - throw new IllegalStateException("setContentView was not called with a view to display."); - - onShow(); - - if (mBackground == null) - mWindow.setBackgroundDrawable(new BitmapDrawable()); - else - mWindow.setBackgroundDrawable(mBackground); - - mWindow.setWidth(WindowManager.LayoutParams.WRAP_CONTENT); - mWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT); - mWindow.setTouchable(true); - mWindow.setFocusable(true); - mWindow.setOutsideTouchable(true); - // FIXME workout some better solution - mWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED); - - mWindow.setContentView(mRootView); - } - - /** - * Set background drawable. - * - * @param background Background drawable - */ - public void setBackgroundDrawable(Drawable background) { - mBackground = background; - } - - /** - * Set content view. - * - * @param root Root view - */ - public void setContentView(View root) { - mRootView = root; - - mWindow.setContentView(root); - } - - /** - * Set content view. - * - * @param layoutResID Resource id - */ - public void setContentView(int layoutResID) { - LayoutInflater inflator = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); - - setContentView(inflator.inflate(layoutResID, null)); - } - - /** - * Set listener on window dismissed. - * - * @param listener - */ - public void setOnDismissListener(PopupWindow.OnDismissListener listener) { - mWindow.setOnDismissListener(listener); - } - - /** - * Dismiss the popup window. - */ - public void dismiss() { - mWindow.dismiss(); - } +/* + * Kontalk Android client + * Copyright (C) 2014 Kontalk Devteam + + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.kontalk.ui; + +import android.graphics.drawable.BitmapDrawable; +import android.graphics.drawable.Drawable; + +import android.view.LayoutInflater; +import android.view.MotionEvent; +import android.view.View; +import android.view.WindowManager; +import android.view.View.OnTouchListener; + +import android.widget.PopupWindow; +import android.content.Context; + +/** + * Custom popup window. + * + * @author Lorensius W. L. T + * + * @deprecated to be replaced by the bottom popup window + */ +@Deprecated +public class PopupWindows { + protected Context mContext; + protected PopupWindow mWindow; + protected View mRootView; + protected Drawable mBackground = null; + protected WindowManager mWindowManager; + + /** + * Constructor. + * + * @param context Context + */ + public PopupWindows(Context context) { + mContext = context; + mWindow = new PopupWindow(context); + + mWindow.setTouchInterceptor(new OnTouchListener() { + @Override + public boolean onTouch(View v, MotionEvent event) { + if (event.getAction() == MotionEvent.ACTION_OUTSIDE) { + mWindow.dismiss(); + + return true; + } + + return false; + } + }); + + mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); + } + + /** + * On dismiss + */ + protected void onDismiss() { + } + + /** + * On show + */ + protected void onShow() { + } + + /** + * On pre show + */ + protected void preShow() { + if (mRootView == null) + throw new IllegalStateException("setContentView was not called with a view to display."); + + onShow(); + + if (mBackground == null) + mWindow.setBackgroundDrawable(new BitmapDrawable()); + else + mWindow.setBackgroundDrawable(mBackground); + + mWindow.setWidth(WindowManager.LayoutParams.WRAP_CONTENT); + mWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT); + mWindow.setTouchable(true); + mWindow.setFocusable(true); + mWindow.setOutsideTouchable(true); + // FIXME workout some better solution + mWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED); + + mWindow.setContentView(mRootView); + } + + /** + * Set background drawable. + * + * @param background Background drawable + */ + public void setBackgroundDrawable(Drawable background) { + mBackground = background; + } + + /** + * Set content view. + * + * @param root Root view + */ + public void setContentView(View root) { + mRootView = root; + + mWindow.setContentView(root); + } + + /** + * Set content view. + * + * @param layoutResID Resource id + */ + public void setContentView(int layoutResID) { + LayoutInflater inflator = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + + setContentView(inflator.inflate(layoutResID, null)); + } + + /** + * Set listener on window dismissed. + * + * @param listener + */ + public void setOnDismissListener(PopupWindow.OnDismissListener listener) { + mWindow.setOnDismissListener(listener); + } + + /** + * Dismiss the popup window. + */ + public void dismiss() { + mWindow.dismiss(); + } } \ No newline at end of file diff --git a/src/org/kontalk/ui/PreferencesActivity.java b/src/org/kontalk/ui/PreferencesActivity.java index f45bac624..1e3ded81c 100644 --- a/src/org/kontalk/ui/PreferencesActivity.java +++ b/src/org/kontalk/ui/PreferencesActivity.java @@ -119,25 +119,25 @@ public boolean onPreferenceClick(Preference preference) { @Override public boolean onPreferenceClick(Preference preference) { - // TODO check for external storage presence + // TODO check for external storage presence - try { + try { - ((Kontalk)getApplicationContext()).exportPersonalKey(); + ((Kontalk)getApplicationContext()).exportPersonalKey(); Toast.makeText(PreferencesActivity.this, - R.string.msg_keypair_exported, + R.string.msg_keypair_exported, Toast.LENGTH_LONG).show(); - } - catch (Exception e) { + } + catch (Exception e) { Toast.makeText(PreferencesActivity.this, - // TODO i18n - "Unable to export personal key.", + // TODO i18n + "Unable to export personal key.", Toast.LENGTH_LONG).show(); - } + } return true; } diff --git a/src/org/kontalk/ui/QuickAction.java b/src/org/kontalk/ui/QuickAction.java index f014e78cd..e6aa646e8 100644 --- a/src/org/kontalk/ui/QuickAction.java +++ b/src/org/kontalk/ui/QuickAction.java @@ -45,192 +45,192 @@ */ @Deprecated public class QuickAction extends PopupWindows implements OnDismissListener { - private View mRootView; - private ImageView mArrowUp; - private ImageView mArrowDown; - private LayoutInflater mInflater; - private GridView mGrid; - private OnDismissListener mDismissListener; + private View mRootView; + private ImageView mArrowUp; + private ImageView mArrowDown; + private LayoutInflater mInflater; + private GridView mGrid; + private OnDismissListener mDismissListener; private int mAnimStyle; private int rootWidth=0; public static final int ANIM_GROW_FROM_LEFT = 1; - public static final int ANIM_GROW_FROM_RIGHT = 2; - public static final int ANIM_GROW_FROM_CENTER = 3; - public static final int ANIM_REFLECT = 4; - public static final int ANIM_AUTO = 5; + public static final int ANIM_GROW_FROM_RIGHT = 2; + public static final int ANIM_GROW_FROM_CENTER = 3; + public static final int ANIM_REFLECT = 4; + public static final int ANIM_AUTO = 5; public QuickAction(Context context, int rootView) { super(context); - mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); setRootViewId(rootView); - mAnimStyle = ANIM_AUTO; + mAnimStyle = ANIM_AUTO; } - /** - * Set root view. - * - * @param id Layout resource id - */ - public void setRootViewId(int id) { - mRootView = mInflater.inflate(id, null); + /** + * Set root view. + * + * @param id Layout resource id + */ + public void setRootViewId(int id) { + mRootView = mInflater.inflate(id, null); - mArrowDown = (ImageView) mRootView.findViewById(R.id.arrow_down); - mArrowUp = (ImageView) mRootView.findViewById(R.id.arrow_up); + mArrowDown = (ImageView) mRootView.findViewById(R.id.arrow_down); + mArrowUp = (ImageView) mRootView.findViewById(R.id.arrow_up); - mGrid = (GridView) mRootView.findViewById(R.id.scroller); + mGrid = (GridView) mRootView.findViewById(R.id.scroller); - //This was previously defined on show() method, moved here to prevent force close that occured - //when tapping fastly on a view to show quickaction dialog. - //Thanx to zammbi (github.com/zammbi) - mRootView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); + //This was previously defined on show() method, moved here to prevent force close that occured + //when tapping fastly on a view to show quickaction dialog. + //Thanx to zammbi (github.com/zammbi) + mRootView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); - setContentView(mRootView); - } + setContentView(mRootView); + } - /** - * Set animation style - * - * @param mAnimStyle animation style, default is set to ANIM_AUTO - */ - public void setAnimStyle(int mAnimStyle) { - this.mAnimStyle = mAnimStyle; - } + /** + * Set animation style + * + * @param mAnimStyle animation style, default is set to ANIM_AUTO + */ + public void setAnimStyle(int mAnimStyle) { + this.mAnimStyle = mAnimStyle; + } public void setGridAdapter(ListAdapter adapter, AdapterView.OnItemClickListener listener) { mGrid.setAdapter(adapter); mGrid.setOnItemClickListener(listener); } - /** - * Show quickaction popup. Popup is automatically positioned, on top or bottom of anchor view. - * - */ - public void show (View anchor) { - preShow(); + /** + * Show quickaction popup. Popup is automatically positioned, on top or bottom of anchor view. + * + */ + public void show (View anchor) { + preShow(); + + int xPos, yPos, arrowPos; + + int[] location = new int[2]; + + anchor.getLocationOnScreen(location); + + Rect anchorRect = new Rect(location[0], location[1], location[0] + anchor.getWidth(), location[1] + + anchor.getHeight()); + + //mRootView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); + + mRootView.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); + + int rootHeight = mRootView.getMeasuredHeight(); + + if (rootWidth == 0) { + rootWidth = mRootView.getMeasuredWidth(); + } + + int screenWidth = mWindowManager.getDefaultDisplay().getWidth(); + int screenHeight = mWindowManager.getDefaultDisplay().getHeight(); + + //automatically get X coord of popup (top left) + if ((anchorRect.left + rootWidth) > screenWidth) { + xPos = anchorRect.left - (rootWidth-anchor.getWidth()); + xPos = (xPos < 0) ? 0 : xPos; + + arrowPos = anchorRect.centerX()-xPos; + + } else { + if (anchor.getWidth() > rootWidth) { + xPos = anchorRect.centerX() - (rootWidth/2); + } else { + xPos = anchorRect.left; + } - int xPos, yPos, arrowPos; + arrowPos = anchorRect.centerX()-xPos; + } - int[] location = new int[2]; - - anchor.getLocationOnScreen(location); + int dyTop = anchorRect.top; + int dyBottom = screenHeight - anchorRect.bottom; - Rect anchorRect = new Rect(location[0], location[1], location[0] + anchor.getWidth(), location[1] - + anchor.getHeight()); - - //mRootView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); + boolean onTop = (dyTop > dyBottom) ? true : false; - mRootView.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); - - int rootHeight = mRootView.getMeasuredHeight(); - - if (rootWidth == 0) { - rootWidth = mRootView.getMeasuredWidth(); - } - - int screenWidth = mWindowManager.getDefaultDisplay().getWidth(); - int screenHeight = mWindowManager.getDefaultDisplay().getHeight(); - - //automatically get X coord of popup (top left) - if ((anchorRect.left + rootWidth) > screenWidth) { - xPos = anchorRect.left - (rootWidth-anchor.getWidth()); - xPos = (xPos < 0) ? 0 : xPos; - - arrowPos = anchorRect.centerX()-xPos; - - } else { - if (anchor.getWidth() > rootWidth) { - xPos = anchorRect.centerX() - (rootWidth/2); - } else { - xPos = anchorRect.left; - } - - arrowPos = anchorRect.centerX()-xPos; - } - - int dyTop = anchorRect.top; - int dyBottom = screenHeight - anchorRect.bottom; - - boolean onTop = (dyTop > dyBottom) ? true : false; - - if (onTop) { - if (rootHeight > dyTop) { - yPos = 15; - LayoutParams l = mGrid.getLayoutParams(); - l.height = dyTop - anchor.getHeight(); - } else { - yPos = anchorRect.top - rootHeight; - } - } else { - yPos = anchorRect.bottom; - - if (rootHeight > dyBottom) { - LayoutParams l = mGrid.getLayoutParams(); - l.height = dyBottom; - } - } - - showArrow(((onTop) ? R.id.arrow_down : R.id.arrow_up), arrowPos); - - setAnimationStyle(screenWidth, anchorRect.centerX(), onTop); - - mWindow.showAtLocation(anchor, Gravity.NO_GRAVITY, xPos, yPos); - } - - /** - * Set animation style - * - * @param screenWidth screen width - * @param requestedX distance from left edge - * @param onTop flag to indicate where the popup should be displayed. Set TRUE if displayed on top of anchor view - * and vice versa - */ - private void setAnimationStyle(int screenWidth, int requestedX, boolean onTop) { - /* - int arrowPos = requestedX - mArrowUp.getMeasuredWidth()/2; - - switch (mAnimStyle) { - case ANIM_GROW_FROM_LEFT: - mWindow.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Left : R.style.Animations_PopDownMenu_Left); - break; - - case ANIM_GROW_FROM_RIGHT: - mWindow.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Right : R.style.Animations_PopDownMenu_Right); - break; - - case ANIM_GROW_FROM_CENTER: - mWindow.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Center : R.style.Animations_PopDownMenu_Center); - break; - - case ANIM_REFLECT: - mWindow.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Reflect : R.style.Animations_PopDownMenu_Reflect); - break; - - case ANIM_AUTO: - if (arrowPos <= screenWidth/4) { - mWindow.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Left : R.style.Animations_PopDownMenu_Left); - } else if (arrowPos > screenWidth/4 && arrowPos < 3 * (screenWidth/4)) { - mWindow.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Center : R.style.Animations_PopDownMenu_Center); - } else { - mWindow.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Right : R.style.Animations_PopDownMenu_Right); - } - - break; - } - */ - } - - /** - * Show arrow - * - * @param whichArrow arrow type resource id - * @param requestedX distance from left screen - */ - private void showArrow(int whichArrow, int requestedX) { + if (onTop) { + if (rootHeight > dyTop) { + yPos = 15; + LayoutParams l = mGrid.getLayoutParams(); + l.height = dyTop - anchor.getHeight(); + } else { + yPos = anchorRect.top - rootHeight; + } + } else { + yPos = anchorRect.bottom; + + if (rootHeight > dyBottom) { + LayoutParams l = mGrid.getLayoutParams(); + l.height = dyBottom; + } + } + + showArrow(((onTop) ? R.id.arrow_down : R.id.arrow_up), arrowPos); + + setAnimationStyle(screenWidth, anchorRect.centerX(), onTop); + + mWindow.showAtLocation(anchor, Gravity.NO_GRAVITY, xPos, yPos); + } + + /** + * Set animation style + * + * @param screenWidth screen width + * @param requestedX distance from left edge + * @param onTop flag to indicate where the popup should be displayed. Set TRUE if displayed on top of anchor view + * and vice versa + */ + private void setAnimationStyle(int screenWidth, int requestedX, boolean onTop) { + /* + int arrowPos = requestedX - mArrowUp.getMeasuredWidth()/2; + + switch (mAnimStyle) { + case ANIM_GROW_FROM_LEFT: + mWindow.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Left : R.style.Animations_PopDownMenu_Left); + break; + + case ANIM_GROW_FROM_RIGHT: + mWindow.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Right : R.style.Animations_PopDownMenu_Right); + break; + + case ANIM_GROW_FROM_CENTER: + mWindow.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Center : R.style.Animations_PopDownMenu_Center); + break; + + case ANIM_REFLECT: + mWindow.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Reflect : R.style.Animations_PopDownMenu_Reflect); + break; + + case ANIM_AUTO: + if (arrowPos <= screenWidth/4) { + mWindow.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Left : R.style.Animations_PopDownMenu_Left); + } else if (arrowPos > screenWidth/4 && arrowPos < 3 * (screenWidth/4)) { + mWindow.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Center : R.style.Animations_PopDownMenu_Center); + } else { + mWindow.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Right : R.style.Animations_PopDownMenu_Right); + } + + break; + } + */ + } + + /** + * Show arrow + * + * @param whichArrow arrow type resource id + * @param requestedX distance from left screen + */ + private void showArrow(int whichArrow, int requestedX) { final View showArrow = (whichArrow == R.id.arrow_up) ? mArrowUp : mArrowDown; final View hideArrow = (whichArrow == R.id.arrow_up) ? mArrowDown : mArrowUp; @@ -245,28 +245,28 @@ private void showArrow(int whichArrow, int requestedX) { hideArrow.setVisibility(View.INVISIBLE); } - /** - * Set listener for window dismissed. This listener will only be fired if the quicakction dialog is dismissed - * by clicking outside the dialog or clicking on sticky item. - */ - public void setOnDismissListener(QuickAction.OnDismissListener listener) { - setOnDismissListener(this); - - mDismissListener = listener; - } - - @Override - public void onDismiss() { - if (mDismissListener != null) { - mDismissListener.onDismiss(); - } - } - - /** - * Listener for window dismiss - * - */ - public interface OnDismissListener { - public abstract void onDismiss(); - } + /** + * Set listener for window dismissed. This listener will only be fired if the quicakction dialog is dismissed + * by clicking outside the dialog or clicking on sticky item. + */ + public void setOnDismissListener(QuickAction.OnDismissListener listener) { + setOnDismissListener(this); + + mDismissListener = listener; + } + + @Override + public void onDismiss() { + if (mDismissListener != null) { + mDismissListener.onDismiss(); + } + } + + /** + * Listener for window dismiss + * + */ + public interface OnDismissListener { + public abstract void onDismiss(); + } } \ No newline at end of file diff --git a/src/org/kontalk/util/MediaStorage.java b/src/org/kontalk/util/MediaStorage.java index 4e279e551..4ac4de9ff 100644 --- a/src/org/kontalk/util/MediaStorage.java +++ b/src/org/kontalk/util/MediaStorage.java @@ -185,15 +185,15 @@ public static String getType(Context context, Uri uri) { * to persist permissions when asking for media files. */ public static boolean isStorageAccessFrameworkAvailable() { - return android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT; + return android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT; } @TargetApi(Build.VERSION_CODES.KITKAT) - public static void requestPersistablePermissions(Context context, Intent intent) { - final int takeFlags = intent.getFlags() + public static void requestPersistablePermissions(Context context, Intent intent) { + final int takeFlags = intent.getFlags() & (Intent.FLAG_GRANT_READ_URI_PERMISSION); - final Uri uri = intent.getData(); - context.getContentResolver().takePersistableUriPermission(uri, takeFlags); + final Uri uri = intent.getData(); + context.getContentResolver().takePersistableUriPermission(uri, takeFlags); } } diff --git a/src/org/kontalk/util/MessageUtils.java b/src/org/kontalk/util/MessageUtils.java index a5707a00b..cd5655131 100644 --- a/src/org/kontalk/util/MessageUtils.java +++ b/src/org/kontalk/util/MessageUtils.java @@ -72,7 +72,7 @@ public final class MessageUtils { - // TODO convert these to XML styles + // TODO convert these to XML styles private static final StyleSpan STYLE_BOLD = new StyleSpan(Typeface.BOLD); private static final ForegroundColorSpan STYLE_RED = new ForegroundColorSpan(Color.RED); private static final ForegroundColorSpan STYLE_GREEN = new ForegroundColorSpan(Color.rgb(0, 0xAA, 0)); @@ -282,19 +282,19 @@ private static String convertToHex(byte[] data) { } public static String sha1(String text) { - try { - MessageDigest md; - md = MessageDigest.getInstance("SHA-1"); - byte[] sha1hash = new byte[40]; - md.update(text.getBytes(), 0, text.length()); - sha1hash = md.digest(); - - return convertToHex(sha1hash); - } - catch (NoSuchAlgorithmException e) { - // no SHA-1?? WWWHHHHAAAAAATTTT???!?!?!?!?! - throw new RuntimeException("no SHA-1 available. What the crap of a device do you have?"); - } + try { + MessageDigest md; + md = MessageDigest.getInstance("SHA-1"); + byte[] sha1hash = new byte[40]; + md.update(text.getBytes(), 0, text.length()); + sha1hash = md.digest(); + + return convertToHex(sha1hash); + } + catch (NoSuchAlgorithmException e) { + // no SHA-1?? WWWHHHHAAAAAATTTT???!?!?!?!?! + throw new RuntimeException("no SHA-1 available. What the crap of a device do you have?"); + } } public static CharSequence getFileInfoMessage(Context context, CompositeMessage msg, String decodedPeer) { @@ -316,13 +316,13 @@ public static CharSequence getFileInfoMessage(Context context, CompositeMessage int resId = R.string.text_message; AttachmentComponent attachment = (AttachmentComponent) msg - .getComponent(AttachmentComponent.class); + .getComponent(AttachmentComponent.class); if (attachment != null) { - if (attachment instanceof ImageComponent) - resId = R.string.image_message; - else if (attachment instanceof VCardComponent) - resId = R.string.vcard_message; + if (attachment instanceof ImageComponent) + resId = R.string.image_message; + else if (attachment instanceof VCardComponent) + resId = R.string.vcard_message; } details.append(res.getString(resId)); @@ -334,15 +334,15 @@ else if (attachment instanceof VCardComponent) long length = -1; if (attachment != null) { // attachment length - length = attachment.getLength(); + length = attachment.getLength(); } else { - // text content length (if found) - TextComponent txt = (TextComponent) msg - .getComponent(TextComponent.class); + // text content length (if found) + TextComponent txt = (TextComponent) msg + .getComponent(TextComponent.class); - if (txt != null) - length = txt.getLength(); + if (txt != null) + length = txt.getLength(); } // otherwise unknown length @@ -363,13 +363,13 @@ public static CharSequence getMessageDetails(Context context, CompositeMessage m int resId = R.string.text_message; AttachmentComponent attachment = (AttachmentComponent) msg - .getComponent(AttachmentComponent.class); + .getComponent(AttachmentComponent.class); if (attachment != null) { - if (attachment instanceof ImageComponent) - resId = R.string.image_message; - else if (attachment instanceof VCardComponent) - resId = R.string.vcard_message; + if (attachment instanceof ImageComponent) + resId = R.string.image_message; + else if (attachment instanceof VCardComponent) + resId = R.string.vcard_message; } details.append(res.getString(resId)); @@ -391,61 +391,61 @@ else if (attachment instanceof VCardComponent) details.append(res.getString(R.string.yes)); // Security flags (verification status) - details.append('\n'); - details.append(res.getString(R.string.security_label)); + details.append('\n'); + details.append(res.getString(R.string.security_label)); - boolean securityError = Coder.isError(securityFlags); - // save start position for spans - int startPos = details.length(); + boolean securityError = Coder.isError(securityFlags); + // save start position for spans + int startPos = details.length(); - if (securityError) { - details.append(res.getString(R.string.security_status_bad)); + if (securityError) { + details.append(res.getString(R.string.security_status_bad)); - int stringId = 0; + int stringId = 0; - if ((securityFlags & Coder.SECURITY_ERROR_INVALID_SIGNATURE) != 0) { - stringId = R.string.security_error_invalid_signature; - } + if ((securityFlags & Coder.SECURITY_ERROR_INVALID_SIGNATURE) != 0) { + stringId = R.string.security_error_invalid_signature; + } - else if ((securityFlags & Coder.SECURITY_ERROR_INVALID_SENDER) != 0) { - stringId = R.string.security_error_invalid_sender; - } + else if ((securityFlags & Coder.SECURITY_ERROR_INVALID_SENDER) != 0) { + stringId = R.string.security_error_invalid_sender; + } - else if ((securityFlags & Coder.SECURITY_ERROR_INVALID_RECIPIENT) != 0) { - stringId = R.string.security_error_invalid_recipient; - } + else if ((securityFlags & Coder.SECURITY_ERROR_INVALID_RECIPIENT) != 0) { + stringId = R.string.security_error_invalid_recipient; + } - else if ((securityFlags & Coder.SECURITY_ERROR_INVALID_TIMESTAMP) != 0) { - stringId = R.string.security_error_invalid_timestamp; - } + else if ((securityFlags & Coder.SECURITY_ERROR_INVALID_TIMESTAMP) != 0) { + stringId = R.string.security_error_invalid_timestamp; + } - else if ((securityFlags & Coder.SECURITY_ERROR_INVALID_DATA) != 0) { - stringId = R.string.security_error_invalid_data; - } + else if ((securityFlags & Coder.SECURITY_ERROR_INVALID_DATA) != 0) { + stringId = R.string.security_error_invalid_data; + } - else if ((securityFlags & Coder.SECURITY_ERROR_DECRYPT_FAILED) != 0) { - stringId = R.string.security_error_decrypt_failed; - } + else if ((securityFlags & Coder.SECURITY_ERROR_DECRYPT_FAILED) != 0) { + stringId = R.string.security_error_decrypt_failed; + } - else if ((securityFlags & Coder.SECURITY_ERROR_INTEGRITY_CHECK) != 0) { - stringId = R.string.security_error_integrity_check; - } + else if ((securityFlags & Coder.SECURITY_ERROR_INTEGRITY_CHECK) != 0) { + stringId = R.string.security_error_integrity_check; + } - else if ((securityFlags & Coder.SECURITY_ERROR_PUBLIC_KEY_UNAVAILABLE) != 0) { - stringId = R.string.security_error_public_key_unavail; - } + else if ((securityFlags & Coder.SECURITY_ERROR_PUBLIC_KEY_UNAVAILABLE) != 0) { + stringId = R.string.security_error_public_key_unavail; + } - if (stringId > 0) - details.append(res.getString(stringId)); - } + if (stringId > 0) + details.append(res.getString(stringId)); + } - else { - details.append(res.getString(R.string.security_status_good)); - } + else { + details.append(res.getString(R.string.security_status_good)); + } details.setSpan(STYLE_BOLD, startPos, details.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); details.setSpan(securityError ? STYLE_RED : STYLE_GREEN, startPos, details.length(), - Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } else { @@ -463,15 +463,15 @@ else if ((securityFlags & Coder.SECURITY_ERROR_PUBLIC_KEY_UNAVAILABLE) != 0) { long length = -1; if (attachment != null) { // attachment length - length = attachment.getLength(); + length = attachment.getLength(); } else { - // text content length (if found) - TextComponent txt = (TextComponent) msg - .getComponent(TextComponent.class); + // text content length (if found) + TextComponent txt = (TextComponent) msg + .getComponent(TextComponent.class); - if (txt != null) - length = txt.getLength(); + if (txt != null) + length = txt.getLength(); } // otherwise unknown length @@ -818,24 +818,24 @@ public static void fillContentValues(ContentValues values, CompositeMessage msg) // message still encrypted - use whole body of raw component if (msg.isEncrypted()) { - RawComponent raw = (RawComponent) msg.getComponent(RawComponent.class); - // if raw it's null it's a bug - content = raw.getContent(); - mime = null; - checkAttachment = false; + RawComponent raw = (RawComponent) msg.getComponent(RawComponent.class); + // if raw it's null it's a bug + content = raw.getContent(); + mime = null; + checkAttachment = false; } else { - TextComponent txt = (TextComponent) msg.getComponent(TextComponent.class); + TextComponent txt = (TextComponent) msg.getComponent(TextComponent.class); - if (txt != null) { - content = txt.getContent().getBytes(); - mime = TextComponent.MIME_TYPE; - } + if (txt != null) { + content = txt.getContent().getBytes(); + mime = TextComponent.MIME_TYPE; + } - checkAttachment = true; + checkAttachment = true; } @@ -843,31 +843,31 @@ public static void fillContentValues(ContentValues values, CompositeMessage msg) if (checkAttachment) { - @SuppressWarnings("unchecked") - Class[] tryComponents = new Class[] { - ImageComponent.class, - VCardComponent.class, - }; + @SuppressWarnings("unchecked") + Class[] tryComponents = new Class[] { + ImageComponent.class, + VCardComponent.class, + }; - for (Class klass : tryComponents) { - AttachmentComponent att = (AttachmentComponent) msg.getComponent(klass); - if (att != null) { + for (Class klass : tryComponents) { + AttachmentComponent att = (AttachmentComponent) msg.getComponent(klass); + if (att != null) { - values.put(Messages.ATTACHMENT_MIME, att.getMime()); - values.put(Messages.ATTACHMENT_FETCH_URL, att.getFetchUrl()); - values.put(Messages.ATTACHMENT_LENGTH, att.getLength()); - values.put(Messages.ATTACHMENT_ENCRYPTED, att.isEncrypted()); - values.put(Messages.ATTACHMENT_SECURITY_FLAGS, att.getSecurityFlags()); + values.put(Messages.ATTACHMENT_MIME, att.getMime()); + values.put(Messages.ATTACHMENT_FETCH_URL, att.getFetchUrl()); + values.put(Messages.ATTACHMENT_LENGTH, att.getLength()); + values.put(Messages.ATTACHMENT_ENCRYPTED, att.isEncrypted()); + values.put(Messages.ATTACHMENT_SECURITY_FLAGS, att.getSecurityFlags()); - File previewFile = att.getPreviewFile(); - if (previewFile != null) - values.put(Messages.ATTACHMENT_PREVIEW_PATH, previewFile.getAbsolutePath()); + File previewFile = att.getPreviewFile(); + if (previewFile != null) + values.put(Messages.ATTACHMENT_PREVIEW_PATH, previewFile.getAbsolutePath()); - // only one attachment is supported - break; - } + // only one attachment is supported + break; + } - } + } } diff --git a/src/org/kontalk/util/Preferences.java b/src/org/kontalk/util/Preferences.java index 115a76377..b345591f2 100644 --- a/src/org/kontalk/util/Preferences.java +++ b/src/org/kontalk/util/Preferences.java @@ -50,12 +50,12 @@ */ public final class Preferences { - private static SharedPreferences sPreferences; + private static SharedPreferences sPreferences; private static Drawable sCustomBackground; private static String sBalloonTheme; public static void init(Context context) { - sPreferences = PreferenceManager.getDefaultSharedPreferences(context); + sPreferences = PreferenceManager.getDefaultSharedPreferences(context); } public static void setCachedCustomBackground(Drawable customBackground) { @@ -100,7 +100,7 @@ private static long getLong(Context context, String key, long defaultValue) { private static long getLongOnce(Context context, String key) { long value = sPreferences.getLong(key, -1); if (value >= 0) - sPreferences.edit().putLong(key, -1).commit(); + sPreferences.edit().putLong(key, -1).commit(); return value; } @@ -112,7 +112,7 @@ private static boolean getBoolean(Context context, String key, boolean defaultVa private static boolean getBooleanOnce(Context context, String key) { boolean value = sPreferences.getBoolean(key, false); if (!value) - sPreferences.edit().putBoolean(key, true).commit(); + sPreferences.edit().putBoolean(key, true).commit(); return value; } @@ -121,9 +121,9 @@ public static String getServerURI(Context context) { } public static boolean setServerURI(Context context, String serverURI) { - return sPreferences.edit() - .putString("pref_network_uri", serverURI) - .commit(); + return sPreferences.edit() + .putString("pref_network_uri", serverURI) + .commit(); } /** Returns a random server from the cached list or the user-defined server. */ @@ -151,7 +151,7 @@ public static boolean getSyncSIMContacts(Context context) { } public static boolean getAutoAcceptSubscriptions(Context context) { - return getBoolean(context, "pref_auto_accept_subscriptions", false); + return getBoolean(context, "pref_auto_accept_subscriptions", false); } public static boolean getPushNotificationsEnabled(Context context) { @@ -201,7 +201,7 @@ public static boolean setLastPushNotification(Context context, long timestamp) { } public static long getLastPushNotification(Context context) { - return getLongOnce(context, "pref_last_push_notification"); + return getLongOnce(context, "pref_last_push_notification"); } /** TODO cache value */ @@ -340,7 +340,7 @@ public static boolean setPushSenderId(Context context, String senderId) { } public static boolean getAcceptAnyCertificate(Context context) { - return getBoolean(context, "pref_accept_any_certificate", false); + return getBoolean(context, "pref_accept_any_certificate", false); } public static int getIdleTimeMillis(Context context, int minValue, int defaultValue) { @@ -352,7 +352,7 @@ public static int getWakeupTimeMillis(Context context, int minValue, int default } public static long getLastConnection(Context context) { - return getLong(context, "pref_last_connection", -1); + return getLong(context, "pref_last_connection", -1); } public static boolean setLastConnection(Context context) { @@ -362,7 +362,7 @@ public static boolean setLastConnection(Context context) { } public static boolean getEnterKeyEnabled(Context context) { - return getBoolean(context, "pref_text_enter", false); + return getBoolean(context, "pref_text_enter", false); } /** Recent statuses database helper. */ diff --git a/src/org/kontalk/util/XMPPUtils.java b/src/org/kontalk/util/XMPPUtils.java index 3de206eec..43ad952e4 100644 --- a/src/org/kontalk/util/XMPPUtils.java +++ b/src/org/kontalk/util/XMPPUtils.java @@ -34,50 +34,50 @@ public class XMPPUtils { public static final String XML_XMPP_TYPE = "application/xmpp+xml"; - private XMPPUtils() {} + private XMPPUtils() {} - private static XmlPullParserFactory _xmlFactory; + private static XmlPullParserFactory _xmlFactory; - private static XmlPullParser getPullParser(String data) throws XmlPullParserException { - if (_xmlFactory == null) { - _xmlFactory = XmlPullParserFactory.newInstance(); - _xmlFactory.setNamespaceAware(true); - } + private static XmlPullParser getPullParser(String data) throws XmlPullParserException { + if (_xmlFactory == null) { + _xmlFactory = XmlPullParserFactory.newInstance(); + _xmlFactory.setNamespaceAware(true); + } - XmlPullParser parser = _xmlFactory.newPullParser(); - parser.setInput(new StringReader(data)); + XmlPullParser parser = _xmlFactory.newPullParser(); + parser.setInput(new StringReader(data)); - return parser; - } + return parser; + } - /** Parses a <xmpp>-wrapped message stanza. */ - public static Message parseMessageStanza(String data) throws Exception { + /** Parses a <xmpp>-wrapped message stanza. */ + public static Message parseMessageStanza(String data) throws Exception { - XmlPullParser parser = getPullParser(data); - boolean done = false, in_xmpp = false; - Message msg = null; + XmlPullParser parser = getPullParser(data); + boolean done = false, in_xmpp = false; + Message msg = null; - while (!done) { - int eventType = parser.next(); + while (!done) { + int eventType = parser.next(); - if (eventType == XmlPullParser.START_TAG) { + if (eventType == XmlPullParser.START_TAG) { - if ("xmpp".equals(parser.getName())) - in_xmpp = true; + if ("xmpp".equals(parser.getName())) + in_xmpp = true; - else if ("message".equals(parser.getName()) && in_xmpp) { - msg = (Message) PacketParserUtils.parseMessage(parser); - } - } + else if ("message".equals(parser.getName()) && in_xmpp) { + msg = (Message) PacketParserUtils.parseMessage(parser); + } + } - else if (eventType == XmlPullParser.END_TAG) { + else if (eventType == XmlPullParser.END_TAG) { - if ("xmpp".equals(parser.getName())) - done = true; - } - } + if ("xmpp".equals(parser.getName())) + done = true; + } + } - return msg; - } + return msg; + } }