Home | History | Annotate | Download | only in userdictionary
      1 /**
      2  * Copyright (C) 2013 Google Inc.
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License"); you may not
      5  * use this file except in compliance with the License. You may obtain a copy
      6  * of the License at
      7  *
      8  * http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
     12  * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
     13  * License for the specific language governing permissions and limitations
     14  * under the License.
     15  */
     16 
     17 package com.android.inputmethod.latin.userdictionary;
     18 
     19 import com.android.inputmethod.latin.R;
     20 
     21 import android.app.ListFragment;
     22 import android.content.ContentResolver;
     23 import android.content.Context;
     24 import android.content.Intent;
     25 import android.database.Cursor;
     26 import android.os.Build;
     27 import android.os.Bundle;
     28 import android.provider.UserDictionary;
     29 import android.text.TextUtils;
     30 import android.view.LayoutInflater;
     31 import android.view.Menu;
     32 import android.view.MenuInflater;
     33 import android.view.MenuItem;
     34 import android.view.View;
     35 import android.view.ViewGroup;
     36 import android.widget.AlphabetIndexer;
     37 import android.widget.ListAdapter;
     38 import android.widget.ListView;
     39 import android.widget.SectionIndexer;
     40 import android.widget.SimpleCursorAdapter;
     41 import android.widget.TextView;
     42 
     43 import java.util.Locale;
     44 
     45 // Caveat: This class is basically taken from
     46 // packages/apps/Settings/src/com/android/settings/inputmethod/UserDictionarySettings.java
     47 // in order to deal with some devices that have issues with the user dictionary handling
     48 
     49 public class UserDictionarySettings extends ListFragment {
     50 
     51     public static final boolean IS_SHORTCUT_API_SUPPORTED =
     52             Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN;
     53 
     54     private static final String[] QUERY_PROJECTION_SHORTCUT_UNSUPPORTED =
     55             { UserDictionary.Words._ID, UserDictionary.Words.WORD};
     56     private static final String[] QUERY_PROJECTION_SHORTCUT_SUPPORTED =
     57             { UserDictionary.Words._ID, UserDictionary.Words.WORD, UserDictionary.Words.SHORTCUT};
     58     private static final String[] QUERY_PROJECTION =
     59             IS_SHORTCUT_API_SUPPORTED ?
     60                     QUERY_PROJECTION_SHORTCUT_SUPPORTED : QUERY_PROJECTION_SHORTCUT_UNSUPPORTED;
     61 
     62     // The index of the shortcut in the above array.
     63     private static final int INDEX_SHORTCUT = 2;
     64 
     65     private static final String[] ADAPTER_FROM_SHORTCUT_UNSUPPORTED = {
     66         UserDictionary.Words.WORD,
     67     };
     68 
     69     private static final String[] ADAPTER_FROM_SHORTCUT_SUPPORTED = {
     70         UserDictionary.Words.WORD, UserDictionary.Words.SHORTCUT
     71     };
     72 
     73     private static final String[] ADAPTER_FROM = IS_SHORTCUT_API_SUPPORTED ?
     74             ADAPTER_FROM_SHORTCUT_SUPPORTED : ADAPTER_FROM_SHORTCUT_UNSUPPORTED;
     75 
     76     private static final int[] ADAPTER_TO_SHORTCUT_UNSUPPORTED = {
     77         android.R.id.text1,
     78     };
     79 
     80     private static final int[] ADAPTER_TO_SHORTCUT_SUPPORTED = {
     81         android.R.id.text1, android.R.id.text2
     82     };
     83 
     84     private static final int[] ADAPTER_TO = IS_SHORTCUT_API_SUPPORTED ?
     85             ADAPTER_TO_SHORTCUT_SUPPORTED : ADAPTER_TO_SHORTCUT_UNSUPPORTED;
     86 
     87     // Either the locale is empty (means the word is applicable to all locales)
     88     // or the word equals our current locale
     89     private static final String QUERY_SELECTION =
     90             UserDictionary.Words.LOCALE + "=?";
     91     private static final String QUERY_SELECTION_ALL_LOCALES =
     92             UserDictionary.Words.LOCALE + " is null";
     93 
     94     private static final String DELETE_SELECTION_WITH_SHORTCUT = UserDictionary.Words.WORD
     95             + "=? AND " + UserDictionary.Words.SHORTCUT + "=?";
     96     private static final String DELETE_SELECTION_WITHOUT_SHORTCUT = UserDictionary.Words.WORD
     97             + "=? AND " + UserDictionary.Words.SHORTCUT + " is null OR "
     98             + UserDictionary.Words.SHORTCUT + "=''";
     99     private static final String DELETE_SELECTION_SHORTCUT_UNSUPPORTED =
    100             UserDictionary.Words.WORD + "=?";
    101 
    102     private static final int OPTIONS_MENU_ADD = Menu.FIRST;
    103 
    104     private Cursor mCursor;
    105 
    106     protected String mLocale;
    107 
    108     @Override
    109     public void onCreate(Bundle savedInstanceState) {
    110         super.onCreate(savedInstanceState);
    111         getActivity().getActionBar().setTitle(R.string.edit_personal_dictionary);
    112     }
    113 
    114     @Override
    115     public View onCreateView(
    116             LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    117         return inflater.inflate(
    118                 R.layout.user_dictionary_preference_list_fragment, container, false);
    119     }
    120 
    121     @Override
    122     public void onActivityCreated(Bundle savedInstanceState) {
    123         super.onActivityCreated(savedInstanceState);
    124 
    125         final Intent intent = getActivity().getIntent();
    126         final String localeFromIntent =
    127                 null == intent ? null : intent.getStringExtra("locale");
    128 
    129         final Bundle arguments = getArguments();
    130         final String localeFromArguments =
    131                 null == arguments ? null : arguments.getString("locale");
    132 
    133         final String locale;
    134         if (null != localeFromArguments) {
    135             locale = localeFromArguments;
    136         } else if (null != localeFromIntent) {
    137             locale = localeFromIntent;
    138         } else {
    139             locale = null;
    140         }
    141 
    142         mLocale = locale;
    143         mCursor = createCursor(locale);
    144         TextView emptyView = (TextView) getView().findViewById(android.R.id.empty);
    145         emptyView.setText(R.string.user_dict_settings_empty_text);
    146 
    147         final ListView listView = getListView();
    148         listView.setAdapter(createAdapter());
    149         listView.setFastScrollEnabled(true);
    150         listView.setEmptyView(emptyView);
    151 
    152         setHasOptionsMenu(true);
    153 
    154     }
    155 
    156     @SuppressWarnings("deprecation")
    157     private Cursor createCursor(final String locale) {
    158         // Locale can be any of:
    159         // - The string representation of a locale, as returned by Locale#toString()
    160         // - The empty string. This means we want a cursor returning words valid for all locales.
    161         // - null. This means we want a cursor for the current locale, whatever this is.
    162         // Note that this contrasts with the data inside the database, where NULL means "all
    163         // locales" and there should never be an empty string. The confusion is called by the
    164         // historical use of null for "all locales".
    165         // TODO: it should be easy to make this more readable by making the special values
    166         // human-readable, like "all_locales" and "current_locales" strings, provided they
    167         // can be guaranteed not to match locales that may exist.
    168         if ("".equals(locale)) {
    169             // Case-insensitive sort
    170             return getActivity().managedQuery(UserDictionary.Words.CONTENT_URI, QUERY_PROJECTION,
    171                     QUERY_SELECTION_ALL_LOCALES, null,
    172                     "UPPER(" + UserDictionary.Words.WORD + ")");
    173         } else {
    174             final String queryLocale = null != locale ? locale : Locale.getDefault().toString();
    175             return getActivity().managedQuery(UserDictionary.Words.CONTENT_URI, QUERY_PROJECTION,
    176                     QUERY_SELECTION, new String[] { queryLocale },
    177                     "UPPER(" + UserDictionary.Words.WORD + ")");
    178         }
    179     }
    180 
    181     private ListAdapter createAdapter() {
    182         return new MyAdapter(getActivity(), R.layout.user_dictionary_item, mCursor,
    183                 ADAPTER_FROM, ADAPTER_TO, this);
    184     }
    185 
    186     @Override
    187     public void onListItemClick(ListView l, View v, int position, long id) {
    188         final String word = getWord(position);
    189         final String shortcut = getShortcut(position);
    190         if (word != null) {
    191             showAddOrEditDialog(word, shortcut);
    192         }
    193     }
    194 
    195     @Override
    196     public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    197         if (!UserDictionarySettings.IS_SHORTCUT_API_SUPPORTED) {
    198             final Locale systemLocale = getResources().getConfiguration().locale;
    199             if (!TextUtils.isEmpty(mLocale) && !mLocale.equals(systemLocale.toString())) {
    200                 // Hide the add button for ICS because it doesn't support specifying a locale
    201                 // for an entry. This new "locale"-aware API has been added in conjunction
    202                 // with the shortcut API.
    203                 return;
    204             }
    205         }
    206         MenuItem actionItem =
    207                 menu.add(0, OPTIONS_MENU_ADD, 0, R.string.user_dict_settings_add_menu_title)
    208                 .setIcon(R.drawable.ic_menu_add);
    209         actionItem.setShowAsAction(
    210                 MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
    211     }
    212 
    213     @Override
    214     public boolean onOptionsItemSelected(MenuItem item) {
    215         if (item.getItemId() == OPTIONS_MENU_ADD) {
    216             showAddOrEditDialog(null, null);
    217             return true;
    218         }
    219         return false;
    220     }
    221 
    222     /**
    223      * Add or edit a word. If editingWord is null, it's an add; otherwise, it's an edit.
    224      * @param editingWord the word to edit, or null if it's an add.
    225      * @param editingShortcut the shortcut for this entry, or null if none.
    226      */
    227     private void showAddOrEditDialog(final String editingWord, final String editingShortcut) {
    228         final Bundle args = new Bundle();
    229         args.putInt(UserDictionaryAddWordContents.EXTRA_MODE, null == editingWord
    230                 ? UserDictionaryAddWordContents.MODE_INSERT
    231                 : UserDictionaryAddWordContents.MODE_EDIT);
    232         args.putString(UserDictionaryAddWordContents.EXTRA_WORD, editingWord);
    233         args.putString(UserDictionaryAddWordContents.EXTRA_SHORTCUT, editingShortcut);
    234         args.putString(UserDictionaryAddWordContents.EXTRA_LOCALE, mLocale);
    235         android.preference.PreferenceActivity pa =
    236                 (android.preference.PreferenceActivity)getActivity();
    237         pa.startPreferencePanel(UserDictionaryAddWordFragment.class.getName(),
    238                 args, R.string.user_dict_settings_add_dialog_title, null, null, 0);
    239     }
    240 
    241     private String getWord(final int position) {
    242         if (null == mCursor) return null;
    243         mCursor.moveToPosition(position);
    244         // Handle a possible race-condition
    245         if (mCursor.isAfterLast()) return null;
    246 
    247         return mCursor.getString(
    248                 mCursor.getColumnIndexOrThrow(UserDictionary.Words.WORD));
    249     }
    250 
    251     private String getShortcut(final int position) {
    252         if (!IS_SHORTCUT_API_SUPPORTED) return null;
    253         if (null == mCursor) return null;
    254         mCursor.moveToPosition(position);
    255         // Handle a possible race-condition
    256         if (mCursor.isAfterLast()) return null;
    257 
    258         return mCursor.getString(
    259                 mCursor.getColumnIndexOrThrow(UserDictionary.Words.SHORTCUT));
    260     }
    261 
    262     public static void deleteWord(final String word, final String shortcut,
    263             final ContentResolver resolver) {
    264         if (!IS_SHORTCUT_API_SUPPORTED) {
    265             resolver.delete(UserDictionary.Words.CONTENT_URI, DELETE_SELECTION_SHORTCUT_UNSUPPORTED,
    266                     new String[] { word });
    267         } else if (TextUtils.isEmpty(shortcut)) {
    268             resolver.delete(
    269                     UserDictionary.Words.CONTENT_URI, DELETE_SELECTION_WITHOUT_SHORTCUT,
    270                     new String[] { word });
    271         } else {
    272             resolver.delete(
    273                     UserDictionary.Words.CONTENT_URI, DELETE_SELECTION_WITH_SHORTCUT,
    274                     new String[] { word, shortcut });
    275         }
    276     }
    277 
    278     private static class MyAdapter extends SimpleCursorAdapter implements SectionIndexer {
    279 
    280         private AlphabetIndexer mIndexer;
    281 
    282         private ViewBinder mViewBinder = new ViewBinder() {
    283 
    284             @Override
    285             public boolean setViewValue(View v, Cursor c, int columnIndex) {
    286                 if (!IS_SHORTCUT_API_SUPPORTED) {
    287                     // just let SimpleCursorAdapter set the view values
    288                     return false;
    289                 }
    290                 if (columnIndex == INDEX_SHORTCUT) {
    291                     final String shortcut = c.getString(INDEX_SHORTCUT);
    292                     if (TextUtils.isEmpty(shortcut)) {
    293                         v.setVisibility(View.GONE);
    294                     } else {
    295                         ((TextView)v).setText(shortcut);
    296                         v.setVisibility(View.VISIBLE);
    297                     }
    298                     v.invalidate();
    299                     return true;
    300                 }
    301 
    302                 return false;
    303             }
    304         };
    305 
    306         @SuppressWarnings("deprecation")
    307         public MyAdapter(Context context, int layout, Cursor c, String[] from, int[] to,
    308                 UserDictionarySettings settings) {
    309             super(context, layout, c, from, to);
    310 
    311             if (null != c) {
    312                 final String alphabet = context.getString(R.string.user_dict_fast_scroll_alphabet);
    313                 final int wordColIndex = c.getColumnIndexOrThrow(UserDictionary.Words.WORD);
    314                 mIndexer = new AlphabetIndexer(c, wordColIndex, alphabet);
    315             }
    316             setViewBinder(mViewBinder);
    317         }
    318 
    319         @Override
    320         public int getPositionForSection(int section) {
    321             return null == mIndexer ? 0 : mIndexer.getPositionForSection(section);
    322         }
    323 
    324         @Override
    325         public int getSectionForPosition(int position) {
    326             return null == mIndexer ? 0 : mIndexer.getSectionForPosition(position);
    327         }
    328 
    329         @Override
    330         public Object[] getSections() {
    331             return null == mIndexer ? null : mIndexer.getSections();
    332         }
    333     }
    334 }
    335