Skip to content

Commit

Permalink
simplified word adding
Browse files Browse the repository at this point in the history
  • Loading branch information
sspanak committed Aug 17, 2023
1 parent bd5385d commit d8c2f7f
Show file tree
Hide file tree
Showing 17 changed files with 110 additions and 117 deletions.
20 changes: 4 additions & 16 deletions res/layout/addwordview.xml
Original file line number Diff line number Diff line change
Expand Up @@ -5,24 +5,12 @@
android:paddingHorizontal="6dp"
android:orientation="vertical" >

<EditText
android:id="@+id/add_word_text"
<TextView
android:id="@+id/add_word_dialog_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginVertical="4dp"
android:layout_marginStart="10dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="10dp"
android:hint="@string/add_word_field_placeholder"
android:imeOptions="actionSend"
android:importantForAutofill="no"
android:inputType="text"
android:maxWidth="480dp"
android:minHeight="48dp"
android:privateImeOptions="io.github.sspanak.tt9.addword=true">

<requestFocus />
</EditText>
android:layout_margin="10dp">
</TextView>

<LinearLayout
android:layout_width="match_parent"
Expand Down
4 changes: 3 additions & 1 deletion res/values-bg/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@
<string name="error_unexpected">Възникна неочаквана грешка.</string>
<string name="failed_loading_language_definitions">Не може да се заредят езиковите дефиниции.</string>
<string name="add_word_add">Добави</string>
<string name="add_word_no_selection">Преместете показалеца върху дума, за да я добавите към речника.</string>
<string name="add_word_blank">Не може да се въведе празна дума.</string>
<string name="add_word_exist">Думата „%1$s“ е вече речника.</string>
<string name="add_word_success">„%1$s“ е добавена.</string>
<string name="add_word_title">Добавяне на дума</string>
<string name="pref_category_about">За приложението</string>
<string name="pref_help">Помощ</string>
Expand Down Expand Up @@ -62,7 +64,6 @@
<string name="pref_double_zero_char">Символ при двойно натисната \"0\"</string>
<string name="char_newline">Нов ред</string>
<string name="char_space">Интервал</string>
<string name="add_word_field_placeholder">Напишете дума…</string>
<string name="pref_upside_down_keys">Бутони в обратен ред</string>
<string name="pref_upside_down_keys_summary">Включете настройката, ако на първият ред са 7–8–9, вместо 1–2–3.</string>
<string name="dictionary_truncate_unselected">Изтрий неизбраните</string>
Expand All @@ -75,4 +76,5 @@
<string name="pref_dark_theme_yes">Да</string>
<string name="pref_dark_theme_no">Не</string>
<string name="pref_dark_theme_auto">Автоматично</string>
<string name="add_word_confirm">Да се добави ли „%1$s“ към %2$s?</string>
</resources>
1 change: 1 addition & 0 deletions res/values-de/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
<string name="add_word_add">Hinzufügen</string>
<string name="add_word_blank">Leeres Wort nicht hinzugefügt.</string>
<string name="add_word_exist">Das Wort \"%1$s\" ist bereits in Wörterbuch.</string>
<string name="add_word_success">\"%1$s\" hinzugefügt.</string>
<string name="add_word_title">Wort hinzufügen</string>

<string name="pref_category_about">Über die Anwendung</string>
Expand Down
2 changes: 1 addition & 1 deletion res/values-es/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
<string name="no_language">Sin idioma</string>
<string name="error_unexpected">Ocurrió un error inesperado.</string>
<string name="add_word_exist">La palabra \"%1$s\" ya esta en el diccionario.</string>
<string name="add_word_success">\"%1$s\" añadida.</string>
<string name="add_word_title">Agregar palabra</string>
<string name="pref_category_abc_mode">Modo ABC</string>
<string name="pref_category_hacks">Compatibilidad</string>
Expand All @@ -28,7 +29,6 @@
<string name="dictionary_load_title">Cargar diccionario</string>
<string name="dictionary_loading_indeterminate">Cargando diccionario</string>
<string name="dictionary_loading">Cargando diccionario (%1$s)…</string>
<string name="add_word_field_placeholder">Escriba una palabra…</string>
<string name="pref_category_about">Acerca de esta aplicación</string>
<string name="dictionary_missing_go_load_it">No hay diccionario para el idioma \"%1$s\". Vaya a Configuración para cargarlo.</string>
<string name="dictionary_not_found">Falló al cargar. No se encontró el diccionario para \"%1$s\".</string>
Expand Down
4 changes: 3 additions & 1 deletion res/values-fr/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@
<string name="error_unexpected">Une erreur inattendue s\'est produite.</string>
<string name="failed_loading_language_definitions">Impossible de charger aucune définition de langue</string>
<string name="add_word_add">Ajouter</string>
<string name="add_word_no_selection">Déplacez le curseur dans un mot pour l\'ajouter.</string>
<string name="add_word_blank">Mot vide non ajouté.</string>
<string name="add_word_exist">Le mot «%1$s» est déjà dans le dictionnaire.</string>
<string name="add_word_success">« %1$s » est ajouté</string>
<string name="add_word_title">Ajouter un mot</string>
<string name="pref_category_about">À propos de l\'application</string>
<string name="pref_help">Aide</string>
Expand Down Expand Up @@ -58,7 +60,6 @@
<string name="setup_click_here_to_enable">Cliquez ici pour activer TT9 dans les paramètres Android.</string>
<string name="char_newline">Nouvelle ligne</string>
<string name="pref_double_zero_char">Caractère lorsque «0» est appuyé deux fois</string>
<string name="add_word_field_placeholder">Tapez un mot…</string>
<string name="pref_upside_down_keys">Inverser l\'ordre des clés</string>
<string name="pref_upside_down_keys_summary">Activez le paramètre s\'il y a 7–8–9 sur le premier rang, au lieu de 1–2–3.</string>
<string name="dictionary_truncate_unselected">Supprimer les non sélectionnés</string>
Expand All @@ -69,4 +70,5 @@
<string name="pref_dark_theme_yes">Oui</string>
<string name="pref_dark_theme_no">Non</string>
<string name="pref_dark_theme_auto">Automatique</string>
<string name="add_word_confirm">Ajouter mot « %1$s » à %2$s?</string>
</resources>
1 change: 1 addition & 0 deletions res/values-it/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
<string name="add_word_add">Aggiungere</string>
<string name="add_word_blank">Nessuna parola da aggiungere.</string>
<string name="add_word_exist">Parola “%1$s” già nel dizionario.</string>
<string name="add_word_success">\"%1$s\" aggiunta.</string>
<string name="add_word_title">Aggiungi parola</string>

<string name="pref_category_about">Sull\'applicazione</string>
Expand Down
1 change: 0 additions & 1 deletion res/values-iw/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
<string name="add_word_blank">מילה ריקה לא נוספה</string>
<string name="add_word_exist">המילה \"%1$s\" כבר קיימת במילון.</string>
<string name="add_word_title">הוסף מילה</string>
<string name="add_word_field_placeholder">הקלד מילה…</string>

<string name="pref_category_about">אודות</string>
<string name="pref_category_hacks">הגדרות תאימות</string>
Expand Down
1 change: 1 addition & 0 deletions res/values-nl/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
<string name="add_word_add">Toevoegen</string>
<string name="add_word_blank">Leeg woord niet toegevoegd.</string>
<string name="add_word_exist">Woord \"%1$s\" staat al in het woordenboek.</string>
<string name="add_word_success">\"%1$s\" toegevoegd.</string>
<string name="add_word_title">Woord toevoegen</string>
<string name="pref_category_about">Over de applicatie</string>
<string name="pref_help">Helpen</string>
Expand Down
2 changes: 1 addition & 1 deletion res/values-pt-rBR/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@
<string name="add_word_add">Adicionar</string>
<string name="add_word_blank">Palavra em branco, impossível adicionar.</string>
<string name="add_word_exist">Palavra \"%1$s\" já está registrada.</string>
<string name="add_word_success">\"%1$s\" adicionada.</string>
<string name="add_word_title">Adicionar Palavra</string>
<string name="add_word_field_placeholder">Escreva uma palavra…</string>

<string name="pref_category_about">Sobre</string>
<string name="pref_category_hacks">Compatibilidade</string>
Expand Down
4 changes: 3 additions & 1 deletion res/values-ru/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@
<string name="error_unexpected">Произошла непредвиденная ошибка.</string>
<string name="failed_loading_language_definitions">Не удалось загрузить какое-либо определение языка.</string>
<string name="add_word_add">Добавить</string>
<string name="add_word_no_selection">Переместите курсор внутрь слова, чтобы добавить его.</string>
<string name="add_word_blank">Невозможно добавить слово.</string>
<string name="add_word_exist">Слово «%1$s» уже есть в словаре.</string>
<string name="add_word_success">« %1$s » добавлено</string>
<string name="add_word_title">Добавить слово</string>
<string name="pref_category_about">О приложении</string>
<string name="pref_help">Помощь</string>
Expand Down Expand Up @@ -62,7 +64,6 @@
<string name="key_hold_key">(зажать)</string>
<string name="key_back">Назад</string>
<string name="key_call">Позвонить</string>
<string name="add_word_field_placeholder">Введите слово…</string>
<string name="pref_upside_down_keys">Перевернутая клавиатура</string>
<string name="pref_upside_down_keys_summary">Используйте настройку, если в первом ряду 7–8–9 вместо 1–2–3.</string>
<string name="dictionary_truncate_unselected">Удалить невыбранные</string>
Expand All @@ -75,4 +76,5 @@
<string name="pref_dark_theme_yes">Да</string>
<string name="pref_dark_theme_no">Нет</string>
<string name="pref_dark_theme_auto">Автоматически</string>
<string name="add_word_confirm">Добавить слово «%1$s» в %2$s?</string>
</resources>
4 changes: 3 additions & 1 deletion res/values-uk/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@
<string name="error_unexpected">Сталася неочікувана помилка.</string>
<string name="failed_loading_language_definitions">Не вдалося завантажити всі визначення мови.</string>
<string name="add_word_add">Додати</string>
<string name="add_word_no_selection">Перемістіть курсор у слово, щоб додати його.</string>
<string name="add_word_blank">Неможливо додати слово.</string>
<string name="add_word_exist">Слово «%1$s» вже є в словнику.</string>
<string name="add_word_success">« %1$s » додано</string>
<string name="add_word_title">Додати слово</string>
<string name="pref_category_about">Про додаток</string>
<string name="pref_help">Допомога</string>
Expand Down Expand Up @@ -62,7 +64,6 @@
<string name="dictionary_truncated">Словник успішно видалено.</string>
<string name="dictionary_missing_go_load_it">Немає словника для мови «%1$s». Перейдіть до Налаштувань, щоб завантажити його.</string>
<string name="dictionary_load_bad_char">Помилка завантаження. Недійсне слово «%1$s» в рядку %2$d мови «%3$s».</string>
<string name="add_word_field_placeholder">Введіть слово…</string>
<string name="pref_upside_down_keys">Зворотна клавіатура</string>
<string name="pref_upside_down_keys_summary">Використовуйте налаштування, якщо 7–8–9 у першому рядку замість 1–2–3.</string>
<string name="dictionary_truncate_unselected">Видалити невибрані</string>
Expand All @@ -75,4 +76,5 @@
<string name="pref_dark_theme_yes">Так</string>
<string name="pref_dark_theme_no">Ні</string>
<string name="pref_dark_theme_auto">Автоматично</string>
<string name="add_word_confirm">Додати слово «%1$s» до %2$s?</string>
</resources>
4 changes: 3 additions & 1 deletion res/values/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,13 @@
<string name="failed_loading_language_definitions">Failed loading all language definitions.</string>

<string name="add_word_add">Add</string>
<string name="add_word_confirm">Add word \"%1$s\" to %2$s?</string>
<string name="add_word_no_selection">Move the cursor inside a word to add it.</string>
<string name="add_word_blank">Blank word not added.</string>
<string name="add_word_exist">Word \"%1$s\" is already in the dictionary.</string>
<string name="add_word_invalid_language" translatable="false">Cannot add a word when no language is selected.</string>
<string name="add_word_success">\"%1$s\" added.</string>
<string name="add_word_title">Add Word</string>
<string name="add_word_field_placeholder">Type a word…</string>

<string name="pref_category_about">About</string>
<string name="pref_category_abc_mode">ABC Mode</string>
Expand Down
7 changes: 2 additions & 5 deletions src/io/github/sspanak/tt9/db/DictionaryDb.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import android.database.sqlite.SQLiteConstraintException;
import android.os.Handler;

import androidx.annotation.NonNull;
import androidx.sqlite.db.SimpleSQLiteQuery;

import java.util.ArrayList;
Expand Down Expand Up @@ -118,11 +119,7 @@ public static void deleteWords(Runnable notification, ArrayList<Integer> languag
}


public static void insertWord(ConsumerCompat<Integer> statusHandler, Language language, String word) throws Exception {
if (language == null) {
throw new InvalidLanguageException();
}

public static void insertWord(ConsumerCompat<Integer> statusHandler, @NonNull Language language, String word) throws Exception {
if (word == null || word.length() == 0) {
throw new InsertBlankWordException();
}
Expand Down
69 changes: 31 additions & 38 deletions src/io/github/sspanak/tt9/ime/TraditionalT9.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package io.github.sspanak.tt9.ime;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
Expand All @@ -9,12 +10,13 @@
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;

import org.jetbrains.annotations.NotNull;
import androidx.annotation.NonNull;

import java.util.ArrayList;
import java.util.List;

import io.github.sspanak.tt9.Logger;
import io.github.sspanak.tt9.R;
import io.github.sspanak.tt9.db.DictionaryDb;
import io.github.sspanak.tt9.ime.helpers.InputModeValidator;
import io.github.sspanak.tt9.ime.helpers.InputType;
Expand All @@ -24,6 +26,7 @@
import io.github.sspanak.tt9.languages.LanguageCollection;
import io.github.sspanak.tt9.preferences.SettingsStore;
import io.github.sspanak.tt9.preferences.helpers.Hotkeys;
import io.github.sspanak.tt9.ui.AddWordAct;
import io.github.sspanak.tt9.ui.UI;
import io.github.sspanak.tt9.ui.main.MainView;
import io.github.sspanak.tt9.ui.tray.StatusBar;
Expand All @@ -32,9 +35,9 @@
public class TraditionalT9 extends KeyPadHandler {
// internal settings/data
private boolean isActive = false;
@NotNull private TextField textField = new TextField(null, null);
@NotNull private InputType inputType = new InputType(null, null);
@NotNull private final Handler autoAcceptHandler = new Handler(Looper.getMainLooper());
@NonNull private TextField textField = new TextField(null, null);
@NonNull private InputType inputType = new InputType(null, null);
@NonNull private final Handler autoAcceptHandler = new Handler(Looper.getMainLooper());

// input mode
private ArrayList<Integer> allowedInputModes = new ArrayList<>();
Expand All @@ -49,7 +52,6 @@ public class TraditionalT9 extends KeyPadHandler {
private StatusBar statusBar = null;
private SuggestionsBar suggestionBar = null;


private static TraditionalT9 self;
public static Context getMainContext() {
return self.getApplicationContext();
Expand Down Expand Up @@ -120,6 +122,20 @@ private void determineTextCase() {
}


@Override
public int onStartCommand(Intent intent, int flags, int startId) {
int result = super.onStartCommand(intent, flags, startId);

String message = intent.getStringExtra(AddWordAct.INTENT_FILTER);
if (message != null && !message.isEmpty()) {
forceShowWindowIfHidden();
UI.toastLong(self, message);
}

return result;
}


protected void onInit() {
self = this;

Expand All @@ -133,7 +149,6 @@ protected void onInit() {

loadSettings();
validateFunctionKeys();
settings.clearLastWord();
}


Expand Down Expand Up @@ -185,7 +200,6 @@ protected void onStart(EditorInfo input) {

initTyping();
initUi();
restoreAddedWordIfAny();

isActive = true;
}
Expand Down Expand Up @@ -333,7 +347,16 @@ public boolean onKeyAddWord(boolean validateOnly) {
}

cancelAutoAccept();
showAddWord();
textField.finishComposingText();
clearSuggestions();

String word = textField.getSurroundingWord();
if (word.isEmpty()) {
UI.toastLong(this, R.string.add_word_no_selection);
} else {
UI.showAddWordDialog(this, mLanguage.getId(), word);
}

return true;
}

Expand Down Expand Up @@ -726,36 +749,6 @@ private boolean performOKAction() {
}


private void showAddWord() {
textField.finishComposingText();
clearSuggestions();

UI.showAddWordDialog(this, mLanguage.getId(), textField.getSurroundingWord());
}


/**
* restoreAddedWordIfAny
* If a new word was added to the dictionary, this function will append add it to the current input field.
*/
private void restoreAddedWordIfAny() {
String word = settings.getLastWord();
settings.clearLastWord();

if (word.length() == 0 || word.equals(textField.getSurroundingWord())) {
return;
}

try {
Logger.d("restoreAddedWordIfAny", "Restoring word: '" + word + "'...");
textField.setText(word);
mInputMode.reset();
} catch (Exception e) {
Logger.w("restoreLastWord", "Could not restore the last added word. " + e.getMessage());
}
}


/**
* createSoftKeyView
* Generates the actual UI of TT9.
Expand Down
4 changes: 3 additions & 1 deletion src/io/github/sspanak/tt9/ime/helpers/TextField.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
import android.view.inputmethod.ExtractedTextRequest;
import android.view.inputmethod.InputConnection;

import androidx.annotation.NonNull;

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
Expand Down Expand Up @@ -189,7 +191,7 @@ public String getTextAfterCursor() {
* getSurroundingWord
* Returns the word next or around the cursor. Scanning length is up to 50 chars in each direction.
*/
public String getSurroundingWord() {
@NonNull public String getSurroundingWord() {
Matcher before = beforeCursorWordRegex.matcher(getTextBeforeCursor());
Matcher after = afterCursorWordRegex.matcher(getTextAfterCursor());

Expand Down
Loading

0 comments on commit d8c2f7f

Please sign in to comment.