1/*
2 * Copyright (C) 2013 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy 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,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.inputmethod.latin.userdictionary;
18
19import com.android.inputmethod.latin.R;
20
21import android.app.ListFragment;
22import android.content.ContentResolver;
23import android.content.Context;
24import android.content.Intent;
25import android.database.Cursor;
26import android.os.Build;
27import android.os.Bundle;
28import android.provider.UserDictionary;
29import android.text.TextUtils;
30import android.view.LayoutInflater;
31import android.view.Menu;
32import android.view.MenuInflater;
33import android.view.MenuItem;
34import android.view.View;
35import android.view.ViewGroup;
36import android.widget.AlphabetIndexer;
37import android.widget.ListAdapter;
38import android.widget.ListView;
39import android.widget.SectionIndexer;
40import android.widget.SimpleCursorAdapter;
41import android.widget.TextView;
42
43import 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
49public 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        // WARNING: The following cursor is never closed! TODO: don't put that in a member, and
144        // make sure all cursors are correctly closed. Also, this comes from a call to
145        // Activity#managedQuery, which has been deprecated for a long time (and which FORBIDS
146        // closing the cursor, so take care when resolving this TODO). We should either use a
147        // regular query and close the cursor, or switch to a LoaderManager and a CursorLoader.
148        mCursor = createCursor(locale);
149        TextView emptyView = (TextView) getView().findViewById(android.R.id.empty);
150        emptyView.setText(R.string.user_dict_settings_empty_text);
151
152        final ListView listView = getListView();
153        listView.setAdapter(createAdapter());
154        listView.setFastScrollEnabled(true);
155        listView.setEmptyView(emptyView);
156
157        setHasOptionsMenu(true);
158        // Show the language as a subtitle of the action bar
159        getActivity().getActionBar().setSubtitle(
160                UserDictionarySettingsUtils.getLocaleDisplayName(getActivity(), mLocale));
161    }
162
163    @SuppressWarnings("deprecation")
164    private Cursor createCursor(final String locale) {
165        // Locale can be any of:
166        // - The string representation of a locale, as returned by Locale#toString()
167        // - The empty string. This means we want a cursor returning words valid for all locales.
168        // - null. This means we want a cursor for the current locale, whatever this is.
169        // Note that this contrasts with the data inside the database, where NULL means "all
170        // locales" and there should never be an empty string. The confusion is called by the
171        // historical use of null for "all locales".
172        // TODO: it should be easy to make this more readable by making the special values
173        // human-readable, like "all_locales" and "current_locales" strings, provided they
174        // can be guaranteed not to match locales that may exist.
175        if ("".equals(locale)) {
176            // Case-insensitive sort
177            return getActivity().managedQuery(UserDictionary.Words.CONTENT_URI, QUERY_PROJECTION,
178                    QUERY_SELECTION_ALL_LOCALES, null,
179                    "UPPER(" + UserDictionary.Words.WORD + ")");
180        } else {
181            final String queryLocale = null != locale ? locale : Locale.getDefault().toString();
182            return getActivity().managedQuery(UserDictionary.Words.CONTENT_URI, QUERY_PROJECTION,
183                    QUERY_SELECTION, new String[] { queryLocale },
184                    "UPPER(" + UserDictionary.Words.WORD + ")");
185        }
186    }
187
188    private ListAdapter createAdapter() {
189        return new MyAdapter(getActivity(), R.layout.user_dictionary_item, mCursor,
190                ADAPTER_FROM, ADAPTER_TO, this);
191    }
192
193    @Override
194    public void onListItemClick(ListView l, View v, int position, long id) {
195        final String word = getWord(position);
196        final String shortcut = getShortcut(position);
197        if (word != null) {
198            showAddOrEditDialog(word, shortcut);
199        }
200    }
201
202    @Override
203    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
204        if (!UserDictionarySettings.IS_SHORTCUT_API_SUPPORTED) {
205            final Locale systemLocale = getResources().getConfiguration().locale;
206            if (!TextUtils.isEmpty(mLocale) && !mLocale.equals(systemLocale.toString())) {
207                // Hide the add button for ICS because it doesn't support specifying a locale
208                // for an entry. This new "locale"-aware API has been added in conjunction
209                // with the shortcut API.
210                return;
211            }
212        }
213        MenuItem actionItem =
214                menu.add(0, OPTIONS_MENU_ADD, 0, R.string.user_dict_settings_add_menu_title)
215                .setIcon(R.drawable.ic_menu_add);
216        actionItem.setShowAsAction(
217                MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
218    }
219
220    @Override
221    public boolean onOptionsItemSelected(MenuItem item) {
222        if (item.getItemId() == OPTIONS_MENU_ADD) {
223            showAddOrEditDialog(null, null);
224            return true;
225        }
226        return false;
227    }
228
229    /**
230     * Add or edit a word. If editingWord is null, it's an add; otherwise, it's an edit.
231     * @param editingWord the word to edit, or null if it's an add.
232     * @param editingShortcut the shortcut for this entry, or null if none.
233     */
234    private void showAddOrEditDialog(final String editingWord, final String editingShortcut) {
235        final Bundle args = new Bundle();
236        args.putInt(UserDictionaryAddWordContents.EXTRA_MODE, null == editingWord
237                ? UserDictionaryAddWordContents.MODE_INSERT
238                : UserDictionaryAddWordContents.MODE_EDIT);
239        args.putString(UserDictionaryAddWordContents.EXTRA_WORD, editingWord);
240        args.putString(UserDictionaryAddWordContents.EXTRA_SHORTCUT, editingShortcut);
241        args.putString(UserDictionaryAddWordContents.EXTRA_LOCALE, mLocale);
242        android.preference.PreferenceActivity pa =
243                (android.preference.PreferenceActivity)getActivity();
244        pa.startPreferencePanel(UserDictionaryAddWordFragment.class.getName(),
245                args, R.string.user_dict_settings_add_dialog_title, null, null, 0);
246    }
247
248    private String getWord(final int position) {
249        if (null == mCursor) return null;
250        mCursor.moveToPosition(position);
251        // Handle a possible race-condition
252        if (mCursor.isAfterLast()) return null;
253
254        return mCursor.getString(
255                mCursor.getColumnIndexOrThrow(UserDictionary.Words.WORD));
256    }
257
258    private String getShortcut(final int position) {
259        if (!IS_SHORTCUT_API_SUPPORTED) return null;
260        if (null == mCursor) return null;
261        mCursor.moveToPosition(position);
262        // Handle a possible race-condition
263        if (mCursor.isAfterLast()) return null;
264
265        return mCursor.getString(
266                mCursor.getColumnIndexOrThrow(UserDictionary.Words.SHORTCUT));
267    }
268
269    public static void deleteWord(final String word, final String shortcut,
270            final ContentResolver resolver) {
271        if (!IS_SHORTCUT_API_SUPPORTED) {
272            resolver.delete(UserDictionary.Words.CONTENT_URI, DELETE_SELECTION_SHORTCUT_UNSUPPORTED,
273                    new String[] { word });
274        } else if (TextUtils.isEmpty(shortcut)) {
275            resolver.delete(
276                    UserDictionary.Words.CONTENT_URI, DELETE_SELECTION_WITHOUT_SHORTCUT,
277                    new String[] { word });
278        } else {
279            resolver.delete(
280                    UserDictionary.Words.CONTENT_URI, DELETE_SELECTION_WITH_SHORTCUT,
281                    new String[] { word, shortcut });
282        }
283    }
284
285    private static class MyAdapter extends SimpleCursorAdapter implements SectionIndexer {
286
287        private AlphabetIndexer mIndexer;
288
289        private ViewBinder mViewBinder = new ViewBinder() {
290
291            @Override
292            public boolean setViewValue(View v, Cursor c, int columnIndex) {
293                if (!IS_SHORTCUT_API_SUPPORTED) {
294                    // just let SimpleCursorAdapter set the view values
295                    return false;
296                }
297                if (columnIndex == INDEX_SHORTCUT) {
298                    final String shortcut = c.getString(INDEX_SHORTCUT);
299                    if (TextUtils.isEmpty(shortcut)) {
300                        v.setVisibility(View.GONE);
301                    } else {
302                        ((TextView)v).setText(shortcut);
303                        v.setVisibility(View.VISIBLE);
304                    }
305                    v.invalidate();
306                    return true;
307                }
308
309                return false;
310            }
311        };
312
313        @SuppressWarnings("deprecation")
314        public MyAdapter(Context context, int layout, Cursor c, String[] from, int[] to,
315                UserDictionarySettings settings) {
316            super(context, layout, c, from, to);
317
318            if (null != c) {
319                final String alphabet = context.getString(R.string.user_dict_fast_scroll_alphabet);
320                final int wordColIndex = c.getColumnIndexOrThrow(UserDictionary.Words.WORD);
321                mIndexer = new AlphabetIndexer(c, wordColIndex, alphabet);
322            }
323            setViewBinder(mViewBinder);
324        }
325
326        @Override
327        public int getPositionForSection(int section) {
328            return null == mIndexer ? 0 : mIndexer.getPositionForSection(section);
329        }
330
331        @Override
332        public int getSectionForPosition(int position) {
333            return null == mIndexer ? 0 : mIndexer.getSectionForPosition(position);
334        }
335
336        @Override
337        public Object[] getSections() {
338            return null == mIndexer ? null : mIndexer.getSections();
339        }
340    }
341}
342