1 /**
2  * Copyright (C) 2009 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.settings;
18 
19 import android.app.ListFragment;
20 import android.content.ContentResolver;
21 import android.content.Context;
22 import android.content.Intent;
23 import android.database.Cursor;
24 import android.os.Bundle;
25 import android.provider.UserDictionary;
26 import android.text.TextUtils;
27 import android.view.LayoutInflater;
28 import android.view.Menu;
29 import android.view.MenuInflater;
30 import android.view.MenuItem;
31 import android.view.View;
32 import android.view.ViewGroup;
33 import android.widget.AlphabetIndexer;
34 import android.widget.ListAdapter;
35 import android.widget.ListView;
36 import android.widget.SectionIndexer;
37 import android.widget.SimpleCursorAdapter;
38 import android.widget.TextView;
39 
40 import com.android.settings.inputmethod.UserDictionaryAddWordContents;
41 import com.android.settings.inputmethod.UserDictionarySettingsUtils;
42 
43 import java.util.Locale;
44 
45 public class UserDictionarySettings extends ListFragment {
46     private static final String TAG = "UserDictionarySettings";
47 
48     private static final String[] QUERY_PROJECTION = {
49         UserDictionary.Words._ID, UserDictionary.Words.WORD, UserDictionary.Words.SHORTCUT
50     };
51 
52     // The index of the shortcut in the above array.
53     private static final int INDEX_SHORTCUT = 2;
54 
55     // Either the locale is empty (means the word is applicable to all locales)
56     // or the word equals our current locale
57     private static final String QUERY_SELECTION =
58             UserDictionary.Words.LOCALE + "=?";
59     private static final String QUERY_SELECTION_ALL_LOCALES =
60             UserDictionary.Words.LOCALE + " is null";
61 
62     private static final String DELETE_SELECTION_WITH_SHORTCUT = UserDictionary.Words.WORD
63             + "=? AND " + UserDictionary.Words.SHORTCUT + "=?";
64     private static final String DELETE_SELECTION_WITHOUT_SHORTCUT = UserDictionary.Words.WORD
65             + "=? AND " + UserDictionary.Words.SHORTCUT + " is null OR "
66             + UserDictionary.Words.SHORTCUT + "=''";
67 
68     private static final int OPTIONS_MENU_ADD = Menu.FIRST;
69 
70     private Cursor mCursor;
71 
72     protected String mLocale;
73 
74     @Override
onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)75     public View onCreateView(
76             LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
77         return inflater.inflate(
78                 com.android.internal.R.layout.preference_list_fragment, container, false);
79     }
80 
81     @Override
onActivityCreated(Bundle savedInstanceState)82     public void onActivityCreated(Bundle savedInstanceState) {
83         super.onActivityCreated(savedInstanceState);
84         getActivity().getActionBar().setTitle(R.string.user_dict_settings_title);
85 
86         final Intent intent = getActivity().getIntent();
87         final String localeFromIntent =
88                 null == intent ? null : intent.getStringExtra("locale");
89 
90         final Bundle arguments = getArguments();
91         final String localeFromArguments =
92                 null == arguments ? null : arguments.getString("locale");
93 
94         final String locale;
95         if (null != localeFromArguments) {
96             locale = localeFromArguments;
97         } else if (null != localeFromIntent) {
98             locale = localeFromIntent;
99         } else {
100             locale = null;
101         }
102 
103         mLocale = locale;
104         mCursor = createCursor(locale);
105         TextView emptyView = (TextView) getView().findViewById(android.R.id.empty);
106         emptyView.setText(R.string.user_dict_settings_empty_text);
107 
108         final ListView listView = getListView();
109         listView.setAdapter(createAdapter());
110         listView.setFastScrollEnabled(true);
111         listView.setEmptyView(emptyView);
112 
113         setHasOptionsMenu(true);
114         // Show the language as a subtitle of the action bar
115         getActivity().getActionBar().setSubtitle(
116                 UserDictionarySettingsUtils.getLocaleDisplayName(getActivity(), mLocale));
117     }
118 
createCursor(final String locale)119     private Cursor createCursor(final String locale) {
120         // Locale can be any of:
121         // - The string representation of a locale, as returned by Locale#toString()
122         // - The empty string. This means we want a cursor returning words valid for all locales.
123         // - null. This means we want a cursor for the current locale, whatever this is.
124         // Note that this contrasts with the data inside the database, where NULL means "all
125         // locales" and there should never be an empty string. The confusion is called by the
126         // historical use of null for "all locales".
127         // TODO: it should be easy to make this more readable by making the special values
128         // human-readable, like "all_locales" and "current_locales" strings, provided they
129         // can be guaranteed not to match locales that may exist.
130         if ("".equals(locale)) {
131             // Case-insensitive sort
132             return getActivity().managedQuery(UserDictionary.Words.CONTENT_URI, QUERY_PROJECTION,
133                     QUERY_SELECTION_ALL_LOCALES, null,
134                     "UPPER(" + UserDictionary.Words.WORD + ")");
135         } else {
136             final String queryLocale = null != locale ? locale : Locale.getDefault().toString();
137             return getActivity().managedQuery(UserDictionary.Words.CONTENT_URI, QUERY_PROJECTION,
138                     QUERY_SELECTION, new String[] { queryLocale },
139                     "UPPER(" + UserDictionary.Words.WORD + ")");
140         }
141     }
142 
createAdapter()143     private ListAdapter createAdapter() {
144         return new MyAdapter(getActivity(),
145                 R.layout.user_dictionary_item, mCursor,
146                 new String[] { UserDictionary.Words.WORD, UserDictionary.Words.SHORTCUT },
147                 new int[] { android.R.id.text1, android.R.id.text2 }, this);
148     }
149 
150     @Override
onListItemClick(ListView l, View v, int position, long id)151     public void onListItemClick(ListView l, View v, int position, long id) {
152         final String word = getWord(position);
153         final String shortcut = getShortcut(position);
154         if (word != null) {
155             showAddOrEditDialog(word, shortcut);
156         }
157     }
158 
159     @Override
onCreateOptionsMenu(Menu menu, MenuInflater inflater)160     public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
161         MenuItem actionItem =
162                 menu.add(0, OPTIONS_MENU_ADD, 0, R.string.user_dict_settings_add_menu_title)
163                 .setIcon(R.drawable.ic_menu_add_dark);
164         actionItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM |
165                 MenuItem.SHOW_AS_ACTION_WITH_TEXT);
166     }
167 
168     @Override
onOptionsItemSelected(MenuItem item)169     public boolean onOptionsItemSelected(MenuItem item) {
170         if (item.getItemId() == OPTIONS_MENU_ADD) {
171             showAddOrEditDialog(null, null);
172             return true;
173         }
174         return false;
175     }
176 
177     /**
178      * Add or edit a word. If editingWord is null, it's an add; otherwise, it's an edit.
179      * @param editingWord the word to edit, or null if it's an add.
180      * @param editingShortcut the shortcut for this entry, or null if none.
181      */
showAddOrEditDialog(final String editingWord, final String editingShortcut)182     private void showAddOrEditDialog(final String editingWord, final String editingShortcut) {
183         final Bundle args = new Bundle();
184         args.putInt(UserDictionaryAddWordContents.EXTRA_MODE, null == editingWord
185                 ? UserDictionaryAddWordContents.MODE_INSERT
186                 : UserDictionaryAddWordContents.MODE_EDIT);
187         args.putString(UserDictionaryAddWordContents.EXTRA_WORD, editingWord);
188         args.putString(UserDictionaryAddWordContents.EXTRA_SHORTCUT, editingShortcut);
189         args.putString(UserDictionaryAddWordContents.EXTRA_LOCALE, mLocale);
190         SettingsActivity sa = (SettingsActivity) getActivity();
191         sa.startPreferencePanel(
192                 com.android.settings.inputmethod.UserDictionaryAddWordFragment.class.getName(),
193                 args, R.string.user_dict_settings_add_dialog_title, null, null, 0);
194     }
195 
getWord(final int position)196     private String getWord(final int position) {
197         if (null == mCursor) return null;
198         mCursor.moveToPosition(position);
199         // Handle a possible race-condition
200         if (mCursor.isAfterLast()) return null;
201 
202         return mCursor.getString(
203                 mCursor.getColumnIndexOrThrow(UserDictionary.Words.WORD));
204     }
205 
getShortcut(final int position)206     private String getShortcut(final int position) {
207         if (null == mCursor) return null;
208         mCursor.moveToPosition(position);
209         // Handle a possible race-condition
210         if (mCursor.isAfterLast()) return null;
211 
212         return mCursor.getString(
213                 mCursor.getColumnIndexOrThrow(UserDictionary.Words.SHORTCUT));
214     }
215 
deleteWord(final String word, final String shortcut, final ContentResolver resolver)216     public static void deleteWord(final String word, final String shortcut,
217             final ContentResolver resolver) {
218         if (TextUtils.isEmpty(shortcut)) {
219             resolver.delete(
220                     UserDictionary.Words.CONTENT_URI, DELETE_SELECTION_WITHOUT_SHORTCUT,
221                     new String[] { word });
222         } else {
223             resolver.delete(
224                     UserDictionary.Words.CONTENT_URI, DELETE_SELECTION_WITH_SHORTCUT,
225                     new String[] { word, shortcut });
226         }
227     }
228 
229     private static class MyAdapter extends SimpleCursorAdapter implements SectionIndexer {
230 
231         private AlphabetIndexer mIndexer;
232 
233         private final ViewBinder mViewBinder = new ViewBinder() {
234 
235             @Override
236             public boolean setViewValue(View v, Cursor c, int columnIndex) {
237                 if (columnIndex == INDEX_SHORTCUT) {
238                     final String shortcut = c.getString(INDEX_SHORTCUT);
239                     if (TextUtils.isEmpty(shortcut)) {
240                         v.setVisibility(View.GONE);
241                     } else {
242                         ((TextView)v).setText(shortcut);
243                         v.setVisibility(View.VISIBLE);
244                     }
245                     v.invalidate();
246                     return true;
247                 }
248 
249                 return false;
250             }
251         };
252 
MyAdapter(Context context, int layout, Cursor c, String[] from, int[] to, UserDictionarySettings settings)253         public MyAdapter(Context context, int layout, Cursor c, String[] from, int[] to,
254                 UserDictionarySettings settings) {
255             super(context, layout, c, from, to);
256 
257             if (null != c) {
258                 final String alphabet = context.getString(
259                         com.android.internal.R.string.fast_scroll_alphabet);
260                 final int wordColIndex = c.getColumnIndexOrThrow(UserDictionary.Words.WORD);
261                 mIndexer = new AlphabetIndexer(c, wordColIndex, alphabet);
262             }
263             setViewBinder(mViewBinder);
264         }
265 
266         @Override
getPositionForSection(int section)267         public int getPositionForSection(int section) {
268             return null == mIndexer ? 0 : mIndexer.getPositionForSection(section);
269         }
270 
271         @Override
getSectionForPosition(int position)272         public int getSectionForPosition(int position) {
273             return null == mIndexer ? 0 : mIndexer.getSectionForPosition(position);
274         }
275 
276         @Override
getSections()277         public Object[] getSections() {
278             return null == mIndexer ? null : mIndexer.getSections();
279         }
280     }
281 }
282