drop clipboard backwards compatibility for api level < 11

This commit is contained in:
Vincent Breitmoser 2015-06-20 05:08:49 +02:00
parent 3b791f6633
commit 09da00d800
12 changed files with 78 additions and 96 deletions

View File

@ -17,6 +17,8 @@
package org.sufficientlysecure.keychain.compatibility;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import org.sufficientlysecure.keychain.Constants;
@ -28,72 +30,24 @@ public class ClipboardReflection {
private static final String clipboardLabel = "Keychain";
/**
* Wrapper around ClipboardManager based on Android version using Reflection API
*
* @param context
* @param text
*/
public static void copyToClipboard(Context context, String text) {
Object clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE);
try {
if ("android.text.ClipboardManager".equals(clipboard.getClass().getName())) {
Method methodSetText = clipboard.getClass()
.getMethod("setText", CharSequence.class);
methodSetText.invoke(clipboard, text);
} else if ("android.content.ClipboardManager".equals(clipboard.getClass().getName())) {
Class<?> classClipData = Class.forName("android.content.ClipData");
Method methodNewPlainText = classClipData.getMethod("newPlainText",
CharSequence.class, CharSequence.class);
Object clip = methodNewPlainText.invoke(null, clipboardLabel, text);
methodNewPlainText = clipboard.getClass()
.getMethod("setPrimaryClip", classClipData);
methodNewPlainText.invoke(clipboard, clip);
}
} catch (Exception e) {
Log.e(Constants.TAG, "There was an error copying the text to the clipboard", e);
}
ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText(clipboardLabel, text);
clipboard.setPrimaryClip(clip);
}
/**
* Wrapper around ClipboardManager based on Android version using Reflection API
*
* @param context
*/
public static CharSequence getClipboardText(Context context) {
Object clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE);
try {
if ("android.text.ClipboardManager".equals(clipboard.getClass().getName())) {
// CharSequence text = clipboard.getText();
Method methodGetText = clipboard.getClass().getMethod("getText");
Object text = methodGetText.invoke(clipboard);
ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
return (CharSequence) text;
} else if ("android.content.ClipboardManager".equals(clipboard.getClass().getName())) {
// ClipData clipData = clipboard.getPrimaryClip();
Method methodGetPrimaryClip = clipboard.getClass().getMethod("getPrimaryClip");
Object clipData = methodGetPrimaryClip.invoke(clipboard);
if (clipData == null) {
ClipData clip = clipboard.getPrimaryClip();
if (clip == null || clip.getItemCount() == 0) {
Log.e(Constants.TAG, "No clipboard data!");
return null;
}
// ClipData.Item clipDataItem = clipData.getItemAt(0);
Method methodGetItemAt = clipData.getClass().getMethod("getItemAt", int.class);
Object clipDataItem = methodGetItemAt.invoke(clipData, 0);
// CharSequence text = clipDataItem.coerceToText(context);
Method methodGetString = clipDataItem.getClass().getMethod("coerceToText",
Context.class);
Object text = methodGetString.invoke(clipDataItem, context);
return (CharSequence) text;
} else {
return null;
}
} catch (Exception e) {
Log.e(Constants.TAG, "There was an error getting the text from the clipboard", e);
return null;
}
ClipData.Item item = clip.getItemAt(0);
return item.coerceToText(context);
}
}

View File

@ -26,6 +26,8 @@ import java.util.List;
import java.util.Set;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
@ -413,8 +415,20 @@ public class EncryptFilesFragment
break;
case COPY:
byte[] resultBytes = result.getResultBytes();
ClipboardReflection.copyToClipboard(getActivity(), new String(resultBytes));
Activity activity = getActivity();
if (activity == null) {
// it's gone, there's nothing we can do here
return;
}
ClipboardManager clipMan = (ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE);
// ClipData clip = ClipData.newUri(getActivity().getContentResolver(),
// getString(R.string.label_clip_title), mOutputUris.get(0));
ClipData clip = new ClipData(getString(R.string.label_clip_title),
new String[] { "text/plain" },
new ClipData.Item(mOutputUris.get(0))
);
clipMan.setPrimaryClip(clip);
result.createNotify(getActivity()).show();
break;
@ -436,32 +450,44 @@ public class EncryptFilesFragment
Notify.create(getActivity(), R.string.no_file_selected, Notify.Style.ERROR)
.show(this);
return true;
} else if (mFilesModels.size() > 1 && mAfterEncryptAction != AfterEncryptAction.SHARE) {
Log.e(Constants.TAG, "Aborting: mInputUris.size() > 1 && !afterEncryptAction");
// This should be impossible...
return true;
}
if (mAfterEncryptAction == AfterEncryptAction.SHARE) {
switch (mAfterEncryptAction) {
default:
case SHARE:
mOutputUris = new ArrayList<>();
int filenameCounter = 1;
for (FilesAdapter.ViewModel model : mFilesModels) {
String targetName =
(mEncryptFilenames ? String.valueOf(filenameCounter) : FileHelper.getFilename(getActivity(), model.inputUri))
String targetName = (mEncryptFilenames
? String.valueOf(filenameCounter) : FileHelper.getFilename(getActivity(), model.inputUri))
+ (mUseArmor ? Constants.FILE_EXTENSION_ASC : Constants.FILE_EXTENSION_PGP_MAIN);
mOutputUris.add(TemporaryStorageProvider.createFile(getActivity(), targetName));
filenameCounter++;
}
return false;
} else {
case SAVE:
if (mFilesModels.size() > 1) {
Notify.create(getActivity(), R.string.error_multi_not_supported,
Notify.Style.ERROR).show(this);
Notify.create(getActivity(), R.string.error_multi_files, Notify.Style.ERROR).show(this);
return true;
}
showOutputFileDialog();
return true;
case COPY:
// nothing to do here, but make sure
if (mFilesModels.size() > 1) {
Notify.create(getActivity(), R.string.error_multi_clipboard, Notify.Style.ERROR).show(this);
return true;
}
mOutputUris = new ArrayList<>();
String targetName = (mEncryptFilenames
? String.valueOf(1) : FileHelper.getFilename(getActivity(), mFilesModels.get(0).inputUri))
+ Constants.FILE_EXTENSION_ASC;
mOutputUris.add(TemporaryStorageProvider.createFile(getActivity(), targetName, "text/plain"));
return false;
}
}
protected SignEncryptParcel createOperationInput() {
@ -516,7 +542,7 @@ public class EncryptFilesFragment
data.setCompressionId(CompressionAlgorithmTags.UNCOMPRESSED);
}
data.setHiddenRecipients(mHiddenRecipients);
data.setEnableAsciiArmorOutput(mUseArmor);
data.setEnableAsciiArmorOutput(mAfterEncryptAction == AfterEncryptAction.COPY || mUseArmor);
data.setSymmetricEncryptionAlgorithm(PgpConstants.OpenKeychainSymmetricKeyAlgorithmTags.USE_PREFERRED);
data.setSignatureHashAlgorithm(PgpConstants.OpenKeychainSymmetricKeyAlgorithmTags.USE_PREFERRED);
@ -622,7 +648,7 @@ public class EncryptFilesFragment
if (resultCode == Activity.RESULT_OK && data != null) {
mOutputUris = new ArrayList<>(1);
mOutputUris.add(data.getData());
// make sure this is correct!
// make sure this is correct at this point
mAfterEncryptAction = AfterEncryptAction.SAVE;
cryptoOperation();
}

View File

@ -1132,7 +1132,7 @@
<string name="contact_show_key">Schlüssel anzeigen (%s)</string>
<string name="swipe_to_update">Nach unten wischen um von Schlüsselserver zu aktualisieren</string>
<string name="error_no_file_selected">Mindestens eine Datei zum Verschlüsseln auswählen!</string>
<string name="error_multi_not_supported">Das speichern von mehreren Dateien wird nicht unterstützt. Dies ist eine Einschränkung der aktuellen Android Version.</string>
<string name="error_multi_files">Das speichern von mehreren Dateien wird nicht unterstützt. Dies ist eine Einschränkung der aktuellen Android Version.</string>
<string name="key_colon">Schlüssel:</string>
<string name="exchange_description">Um einen Schlüsselaustausch zu starten wähle auf der rechten Seite die Teilnehmer aus, drücke dann den \"Austausch starten\"-Knopf.\n\nDu wirst zusätzlich zwei Fragen gestellt bekommen um sicherzustellen, dass nur die richtigen Teilnehmer am Austausch beteiligt sind und deren Fingerabdrücke korrekt sind.</string>
<string name="btn_start_exchange">Austausch starten</string>

View File

@ -1131,7 +1131,7 @@
<string name="contact_show_key">Mostrar clave (%s)</string>
<string name="swipe_to_update">Gesto de barrido hacia abajo para actualizar desde el servidor de claves</string>
<string name="error_no_file_selected">¡Seleccione al menos un fichero a cifrar!</string>
<string name="error_multi_not_supported">El guardado de múltiples ficheros no está soportado. Esto es una limitación de su Android actual.</string>
<string name="error_multi_files">El guardado de múltiples ficheros no está soportado. Esto es una limitación de su Android actual.</string>
<string name="key_colon">Clave:</string>
<string name="exchange_description">Para iniciar un intercambio de claves, en el lado derecho elija el número de participantes, y luego pulse el botón \"Iniciar intercambio\".\n\nSe le formularán dos preguntas más para asegurar que sólo están en el intercambio los participantes debidos, y que sus huellas de validación son correctas.</string>
<string name="btn_start_exchange">Comenzar intercambio</string>

View File

@ -1131,7 +1131,7 @@
<string name="contact_show_key">Montrer la clef (%s)</string>
<string name="swipe_to_update">Glisser vers le bas pour mettre à jour à partir du serveur de clefs</string>
<string name="error_no_file_selected">Choisir au moins un fichier à chiffrer !</string>
<string name="error_multi_not_supported">L\'enregistrement des fichiers multiples n\'est pas pris en charge. Ceci est actuellement une limitation d\'Android.</string>
<string name="error_multi_files">L\'enregistrement des fichiers multiples n\'est pas pris en charge. Ceci est actuellement une limitation d\'Android.</string>
<string name="key_colon">Clef :</string>
<string name="exchange_description">Pour démarrer un échange de clef, choisir le nombre de participants du côté droit, puis cliquer sur le bouton « Démarrer l\'échange ».\n\Deux questions de plus seront posées pour s\'assurer que seuls les bons participants sont dans l\'échange et que les empreintes sont correctes.</string>
<string name="btn_start_exchange">Démarrer l\'échange</string>

View File

@ -686,7 +686,7 @@ Permetti accesso?\n\nATTENZIONE: Se non sai perche\' questo schermata e\' appars
<string name="info_no_manual_account_creation">Non creare account OpenKeychain manualmente.\nPer ulteriori informazioni, vedere la Guida.</string>
<string name="contact_show_key">Mostra chiave (%s)</string>
<string name="error_no_file_selected">Seleziona almeno un file da codificare!</string>
<string name="error_multi_not_supported">Il salvataggio di più file non è supportato. Questa è una limitazione corrente di Android.</string>
<string name="error_multi_files">Il salvataggio di più file non è supportato. Questa è una limitazione corrente di Android.</string>
<string name="key_colon">Chiave:</string>
<!--Passphrase wizard-->
<!--TODO: rename all the things!-->

View File

@ -1102,7 +1102,7 @@
<string name="contact_show_key">鍵 (%s) を表示</string>
<string name="swipe_to_update">下スワイプでキーサーバから更新します</string>
<string name="error_no_file_selected">暗号化するファイルを少なくとも1つ選択して下さい。</string>
<string name="error_multi_not_supported">複数ファイルの保存はサポートされていません。これは現在のAndroidでの制限です。</string>
<string name="error_multi_files">複数ファイルの保存はサポートされていません。これは現在のAndroidでの制限です。</string>
<string name="key_colon">鍵:</string>
<string name="exchange_description">鍵交換の開始は、右側の参加者の番号を選択し、その後、\"交換開始\"ボタンを推します。\n\n2つ以上の質問で交換にいる右の参加者とその指紋が正しいかを確認してください。</string>
<string name="btn_start_exchange">交換開始</string>

View File

@ -1131,7 +1131,7 @@
<string name="contact_show_key">Toon sleutel (%s)</string>
<string name="swipe_to_update">Veeg naar beneden om van sleutelserver te updaten</string>
<string name="error_no_file_selected">Selecteer minstens een bestand om te versleutelen!</string>
<string name="error_multi_not_supported">Opslaan van meerdere bestanden wordt niet ondersteund. Dit is een beperking van Android.</string>
<string name="error_multi_files">Opslaan van meerdere bestanden wordt niet ondersteund. Dit is een beperking van Android.</string>
<string name="key_colon">Sleutel:</string>
<string name="exchange_description">Selecteer om een sleuteluitwisseling te starten het aantal deelnemers aan de rechterkant, en klik vervolgens op de knop \'Start uitwisseling\'.\n\nJe zal twee vragne gesteld worden om zeker te zijn dat enkel de juiste deelnemers zich in de uitwisseling bevinden en dat hun vingerafdrukken correct zijn.</string>
<string name="btn_start_exchange">Uitwisseling starten</string>

View File

@ -1112,7 +1112,7 @@
<string name="contact_show_key">Прикажи кључ (%s)</string>
<string name="swipe_to_update">Превуците прстом доле да ажурирате са сервера кључева</string>
<string name="error_no_file_selected">Изаберите бар један фајл за шифровање!</string>
<string name="error_multi_not_supported">Упис више фајлова није подржан. Ово је ограничење у текућем издању Андроида.</string>
<string name="error_multi_files">Упис више фајлова није подржан. Ово је ограничење у текућем издању Андроида.</string>
<string name="key_colon">Кључ:</string>
<string name="exchange_description">Да бисте почели размену кључева, са десне стране изаберите број учесника и додирните дугме „Почни размену“.\n\nБиће вам постављено још два питања да би се осигурало да су само исправни учесници у размени и да су њихови отисци тачни.</string>
<string name="btn_start_exchange">Почни размену</string>

View File

@ -873,7 +873,7 @@
<string name="contact_show_key">Visa nyckel (%s)</string>
<string name="swipe_to_update">Dra nedåt för att uppdatera från nyckelserver</string>
<string name="error_no_file_selected">Välj åtminstone en fil att kryptera!</string>
<string name="error_multi_not_supported">Att spara flera filer stöds ej. Detta är en begränsning i nuvarande Android.</string>
<string name="error_multi_files">Att spara flera filer stöds ej. Detta är en begränsning i nuvarande Android.</string>
<string name="key_colon">Nyckel:</string>
<string name="user_id_none"><![CDATA[<none>]]></string>
<!--Passphrase wizard-->

View File

@ -480,7 +480,7 @@
<string name="contact_show_key">Anahtarı göster (%s)</string>
<string name="swipe_to_update">Anahtar sunucudan güncelleme almak için parmağınızı aşağıya doğru kaydırın</string>
<string name="error_no_file_selected">Şifrelemek için en az bir dosya seçin!</string>
<string name="error_multi_not_supported">Birden çok dosyanın kaydedilmesi desteklenmiyor. Bu şu anki Android\'in bir kısıtlamasıdır.</string>
<string name="error_multi_files">Birden çok dosyanın kaydedilmesi desteklenmiyor. Bu şu anki Android\'in bir kısıtlamasıdır.</string>
<string name="key_colon">Anahtar:</string>
<string name="exchange_description">Anahtar değiş tokuşu başlatmak için sağ taraftan katılımcıların sayısını seçin ve \"Değiş tokuşu başlat\" tuşuna tıklayın.\n\nSadece istenilen katılımcıların değişim işleminde olduğundan ve parmak izlerinin doğruluğundan emin olmak için size iki soru daha sorulacak.</string>
<!--Passphrase wizard-->

View File

@ -1264,7 +1264,8 @@
<string name="contact_show_key">"Show key (%s)"</string>
<string name="swipe_to_update">"Swipe down to update from keyserver"</string>
<string name="error_no_file_selected">"Select at least one file to encrypt!"</string>
<string name="error_multi_not_supported">"Saving of multiple files not supported. This is a limitation on current Android."</string>
<string name="error_multi_files">"Saving of multiple files not supported. This is a limitation on current Android."</string>
<string name="error_multi_clipboard">"Encryption of multiple files to clipboard not supported."</string>
<string name="error_empty_text">"Type some text to encrypt!"</string>
<string name="key_colon">"Key:"</string>
<string name="exchange_description">"To start a key exchange, choose the number of participants on the right side, then hit the “Start exchange” button.\n\nYou will be asked two more questions to make sure only the right participants are in the exchange and their fingerprints are correct."</string>
@ -1339,5 +1340,6 @@
<string name="intent_show">Show Signed/Encrypted Content</string>
<string name="view_internal">"View in OpenKeychain"</string>
<string name="error_preparing_data">"Error preparing data!"</string>
<string name="label_clip_title">"Encrypted Data"</string>
</resources>