]> gitweb.fperrin.net Git - Dictionary.git/blobdiff - src/com/hughes/android/dictionary/DictionaryActivity.java
Add menu entry to jump to random word.
[Dictionary.git] / src / com / hughes / android / dictionary / DictionaryActivity.java
index f15a186869c1c1deb01f69b9fbdb022ce1ec0a6e..bb749f82fc333ba587d07a9ce7cc2f226c343cbf 100644 (file)
@@ -28,6 +28,12 @@ import android.os.Handler;
 import android.preference.PreferenceManager;
 import android.speech.tts.TextToSpeech;
 import android.speech.tts.TextToSpeech.OnInitListener;
+import android.support.v4.view.MenuItemCompat;
+import android.support.v7.app.ActionBar;
+import android.support.v7.app.ActionBarActivity;
+import android.support.v7.widget.SearchView;
+import android.support.v7.widget.SearchView.OnQueryTextListener;
+import android.support.v7.widget.Toolbar;
 import android.text.ClipboardManager;
 import android.text.Spannable;
 import android.text.method.LinkMovementMethod;
@@ -39,6 +45,9 @@ import android.view.ContextMenu;
 import android.view.ContextMenu.ContextMenuInfo;
 import android.view.Gravity;
 import android.view.KeyEvent;
+import android.view.Menu;
+import android.view.MenuItem;
+import android.view.MenuItem.OnMenuItemClickListener;
 import android.view.MotionEvent;
 import android.view.View;
 import android.view.View.OnClickListener;
@@ -47,7 +56,9 @@ import android.view.ViewGroup;
 import android.view.WindowManager;
 import android.view.inputmethod.EditorInfo;
 import android.view.inputmethod.InputMethodManager;
+import android.widget.AdapterView;
 import android.widget.AdapterView.AdapterContextMenuInfo;
+import android.widget.AdapterView.OnItemClickListener;
 import android.widget.BaseAdapter;
 import android.widget.Button;
 import android.widget.FrameLayout;
@@ -63,20 +74,12 @@ import android.widget.TextView;
 import android.widget.TextView.BufferType;
 import android.widget.Toast;
 
-import com.actionbarsherlock.app.ActionBar;
-import com.actionbarsherlock.app.SherlockListActivity;
-import com.actionbarsherlock.view.Menu;
-import com.actionbarsherlock.view.MenuItem;
-import com.actionbarsherlock.view.MenuItem.OnMenuItemClickListener;
-import com.actionbarsherlock.widget.SearchView;
-import com.actionbarsherlock.widget.SearchView.OnQueryTextListener;
 import com.hughes.android.dictionary.DictionaryInfo.IndexInfo;
 import com.hughes.android.dictionary.engine.Dictionary;
 import com.hughes.android.dictionary.engine.EntrySource;
 import com.hughes.android.dictionary.engine.HtmlEntry;
 import com.hughes.android.dictionary.engine.Index;
 import com.hughes.android.dictionary.engine.Index.IndexEntry;
-import com.hughes.android.dictionary.engine.Language;
 import com.hughes.android.dictionary.engine.Language.LanguageResources;
 import com.hughes.android.dictionary.engine.PairEntry;
 import com.hughes.android.dictionary.engine.PairEntry.Pair;
@@ -109,7 +112,7 @@ import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 
-public class DictionaryActivity extends SherlockListActivity {
+public class DictionaryActivity extends ActionBarActivity {
 
     static final String LOG = "QuickDic";
 
@@ -126,6 +129,8 @@ public class DictionaryActivity extends SherlockListActivity {
 
     List<RowBase> rowsToShow = null; // if not null, just show these rows.
 
+    final Random rand = new Random();
+
     final Handler uiHandler = new Handler();
 
     private final Executor searchExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() {
@@ -141,15 +146,31 @@ public class DictionaryActivity extends SherlockListActivity {
     volatile boolean ttsReady;
 
     Typeface typeface;
-    C.Theme theme = C.Theme.LIGHT;
+    DictionaryApplication.Theme theme = DictionaryApplication.Theme.LIGHT;
     int textColorFg = Color.BLACK;
     int fontSizeSp;
 
+    private ListView listView;
+    private ListView getListView() {
+        if (listView == null) {
+            listView = (ListView)findViewById(android.R.id.list);
+        }
+        return listView;
+    }
+
+    private void setListAdapter(ListAdapter adapter) {
+        getListView().setAdapter(adapter);
+    }
+
+    private ListAdapter getListAdapter() {
+        return getListView().getAdapter();
+    }
+
     SearchView searchView;
     ImageButton languageButton;
     SearchView.OnQueryTextListener onQueryTextListener;
 
-    MenuItem nextWordMenuItem, previousWordMenuItem;
+    MenuItem nextWordMenuItem, previousWordMenuItem, randomWordMenuItem;
 
     // Never null.
     private File wordList = null;
@@ -169,11 +190,9 @@ public class DictionaryActivity extends SherlockListActivity {
     public DictionaryActivity() {
     }
 
-    public static Intent getLaunchIntent(final File dictFile, final String indexShortName,
+    public static Intent getLaunchIntent(Context c, final File dictFile, final String indexShortName,
             final String searchToken) {
-        final Intent intent = new Intent();
-        intent.setClassName(DictionaryActivity.class.getPackage().getName(),
-                DictionaryActivity.class.getName());
+        final Intent intent = new Intent(c, DictionaryActivity.class);
         intent.putExtra(C.DICT_FILE, dictFile.getPath());
         intent.putExtra(C.INDEX_SHORT_NAME, indexShortName);
         intent.putExtra(C.SEARCH_TOKEN, searchToken);
@@ -188,15 +207,13 @@ public class DictionaryActivity extends SherlockListActivity {
         outState.putString(C.SEARCH_TOKEN, searchView.getQuery().toString());
     }
 
-    @Override
-    protected void onRestoreInstanceState(final Bundle savedInstanceState) {
-        super.onRestoreInstanceState(savedInstanceState);
-        Log.d(LOG, "onRestoreInstanceState: " + savedInstanceState.getString(C.SEARCH_TOKEN));
-        onCreate(savedInstanceState);
-    }
-
     @Override
     public void onCreate(Bundle savedInstanceState) {
+        // This needs to be before super.onCreate, otherwise ActionbarSherlock
+        // doesn't makes the background of the actionbar white when you're
+        // in the dark theme.
+        setTheme(((DictionaryApplication) getApplication()).getSelectedTheme().themeId);
+
         Log.d(LOG, "onCreate:" + this);
         super.onCreate(savedInstanceState);
 
@@ -205,7 +222,7 @@ public class DictionaryActivity extends SherlockListActivity {
         // Don't auto-launch if this fails.
         prefs.edit().remove(C.DICT_FILE).commit();
 
-        setTheme(((DictionaryApplication) getApplication()).getSelectedTheme().themeId);
+        setContentView(R.layout.dictionary_activity);
 
         application = (DictionaryApplication) getApplication();
         theme = application.getSelectedTheme();
@@ -299,7 +316,7 @@ public class DictionaryActivity extends SherlockListActivity {
         if (dictFilename == null)
         {
             Toast.makeText(this, getString(R.string.no_dict_file), Toast.LENGTH_LONG).show();
-            startActivity(DictionaryManagerActivity.getLaunchIntent());
+            startActivity(DictionaryManagerActivity.getLaunchIntent(getApplicationContext()));
             finish();
             return;
         }
@@ -332,7 +349,7 @@ public class DictionaryActivity extends SherlockListActivity {
             }
             Toast.makeText(this, getString(R.string.invalidDictionary, "", e.getMessage()),
                     Toast.LENGTH_LONG).show();
-            startActivity(DictionaryManagerActivity.getLaunchIntent());
+            startActivity(DictionaryManagerActivity.getLaunchIntent(getApplicationContext()));
             finish();
             return;
         }
@@ -354,6 +371,7 @@ public class DictionaryActivity extends SherlockListActivity {
         // Pre-load the collators.
         new Thread(new Runnable() {
             public void run() {
+                android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
                 final long startMillis = System.currentTimeMillis();
                 try {
                     TransliteratorManager.init(new TransliteratorManager.Callback() {
@@ -384,10 +402,19 @@ public class DictionaryActivity extends SherlockListActivity {
             }
         }).start();
 
-        String fontName = prefs.getString(getString(R.string.fontKey), "FreeSerif.ttf.jpg");
+        String fontName = prefs.getString(getString(R.string.fontKey), "FreeSerif.otf.jpg");
         if ("SYSTEM".equals(fontName)) {
             typeface = Typeface.DEFAULT;
+       } else if ("SERIF".equals(fontName)) {
+            typeface = Typeface.SERIF;
+       } else if ("SANS_SERIF".equals(fontName)) {
+            typeface = Typeface.SANS_SERIF;
+       } else if ("MONOSPACE".equals(fontName)) {
+            typeface = Typeface.MONOSPACE;
         } else {
+            if ("FreeSerif.ttf.jpg".equals(fontName)) {
+                fontName = "FreeSerif.otf.jpg";
+            }
             try {
                 typeface = Typeface.createFromAsset(getAssets(), fontName);
             } catch (Exception e) {
@@ -407,14 +434,11 @@ public class DictionaryActivity extends SherlockListActivity {
             fontSizeSp = 14;
         }
 
-        setContentView(R.layout.dictionary_activity);
-
         // ContextMenu.
         registerForContextMenu(getListView());
 
         // Cache some prefs.
-        wordList = new File(prefs.getString(getString(R.string.wordListFileKey),
-                new File(application.getDictDir(), "wordList.txt").getAbsolutePath()));
+        wordList = application.getWordListFile();
         saveOnlyFirstSubentry = prefs.getBoolean(getString(R.string.saveOnlyFirstSubentryKey),
                 false);
         clickOpensContextMenu = prefs.getBoolean(getString(R.string.clickOpensContextMenuKey),
@@ -440,7 +464,7 @@ public class DictionaryActivity extends SherlockListActivity {
         searchView.requestFocus();
 
         // http://stackoverflow.com/questions/2833057/background-listview-becomes-black-when-scrolling
-        getListView().setCacheColorHint(0);
+//        getListView().setCacheColorHint(0);
     }
 
     private void onCreateSetupActionBarAndSearchView() {
@@ -454,12 +478,17 @@ public class DictionaryActivity extends SherlockListActivity {
         final int width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 300,
                 getResources().getDisplayMetrics());
         final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
-                width, ViewGroup.LayoutParams.WRAP_CONTENT);
+                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
         customSearchView.setLayoutParams(layoutParams);
 
+        listView.setOnItemClickListener(new OnItemClickListener() {
+            @Override
+            public void onItemClick(AdapterView<?> parent, View view, int row, long id) {
+                onListItemClick(getListView(), view, row, id);
+            }
+        });
+
         languageButton = new ImageButton(customSearchView.getContext());
-        languageButton.setMinimumWidth(application.languageButtonPixels);
-        languageButton.setMinimumHeight(application.languageButtonPixels * 2 / 3);
         languageButton.setScaleType(ScaleType.FIT_CENTER);
         languageButton.setOnClickListener(new OnClickListener() {
             @Override
@@ -474,18 +503,16 @@ public class DictionaryActivity extends SherlockListActivity {
                 return true;
             }
         });
-        customSearchView.addView(languageButton);
+        languageButton.setAdjustViewBounds(true);
+        LinearLayout.LayoutParams lpb = new LinearLayout.LayoutParams(application.languageButtonPixels, LinearLayout.LayoutParams.MATCH_PARENT);
+        customSearchView.addView(languageButton, lpb);
 
-        searchView = new SearchView(customSearchView.getContext());
+        searchView = new SearchView(getSupportActionBar().getThemedContext());
         searchView.setIconifiedByDefault(false);
         // searchView.setIconified(false); // puts the magnifying glass in the
         // wrong place.
         searchView.setQueryHint(getString(R.string.searchText));
         searchView.setSubmitButtonEnabled(false);
-        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(0,
-                FrameLayout.LayoutParams.WRAP_CONTENT);
-        lp.weight = 1;
-        searchView.setLayoutParams(lp);
         searchView.setImeOptions(
                 EditorInfo.IME_ACTION_SEARCH |
                         EditorInfo.IME_FLAG_NO_EXTRACT_UI |
@@ -510,17 +537,16 @@ public class DictionaryActivity extends SherlockListActivity {
         };
         searchView.setOnQueryTextListener(onQueryTextListener);
         searchView.setFocusable(true);
-        customSearchView.addView(searchView);
-
-        // Clear the searchHint icon so that it takes as little space as possible.
-        ImageView searchHintIcon = (ImageView) searchView.findViewById(R.id.abs__search_mag_icon);
-        searchHintIcon.setBackgroundResource(android.R.color.transparent);
-        searchHintIcon.setLayoutParams(new LinearLayout.LayoutParams(1, 1));
-        searchHintIcon.setAdjustViewBounds(true);
-        searchHintIcon.setPadding(0, 0, 0, 0);
-        
+        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(0,
+                FrameLayout.LayoutParams.WRAP_CONTENT, 1);
+        customSearchView.addView(searchView, lp);
+
         actionBar.setCustomView(customSearchView);
         actionBar.setDisplayShowCustomEnabled(true);
+
+       // Avoid wasting space on large left inset
+        Toolbar tb = (Toolbar)customSearchView.getParent();
+        tb.setContentInsetsRelative(0, 0);
     }
 
     @Override
@@ -616,7 +642,7 @@ public class DictionaryActivity extends SherlockListActivity {
 
     void updateLangButton() {
         final LanguageResources languageResources =
-                Language.isoCodeToResources.get(index.shortName);
+                DictionaryApplication.isoCodeToResources.get(index.shortName);
         if (languageResources != null && languageResources.flagId != 0) {
             languageButton.setImageResource(languageResources.flagId);
         } else {
@@ -668,12 +694,12 @@ public class DictionaryActivity extends SherlockListActivity {
         final String name = getString(R.string.dictionaryManager);
         button.setText(name);
         final IntentLauncher intentLauncher = new IntentLauncher(listView.getContext(),
-                DictionaryManagerActivity.getLaunchIntent()) {
+                DictionaryManagerActivity.getLaunchIntent(getApplicationContext())) {
             @Override
             protected void onGo() {
                 dialog.dismiss();
                 DictionaryActivity.this.finish();
-            };
+            }
         };
         button.setOnClickListener(intentLauncher);
         listView.addHeaderView(button);
@@ -690,14 +716,14 @@ public class DictionaryActivity extends SherlockListActivity {
                     final View button = application.createButton(parent.getContext(),
                             dictionaryInfo, indexInfo);
                     final IntentLauncher intentLauncher = new IntentLauncher(parent.getContext(),
-                            getLaunchIntent(
+                            getLaunchIntent(getApplicationContext(),
                                     application.getPath(dictionaryInfo.uncompressedFilename),
                                     indexInfo.shortName, searchView.getQuery().toString())) {
                         @Override
                         protected void onGo() {
                             dialog.dismiss();
                             DictionaryActivity.this.finish();
-                        };
+                        }
                     };
                     button.setOnClickListener(intentLauncher);
                     result.addView(button);
@@ -760,6 +786,14 @@ public class DictionaryActivity extends SherlockListActivity {
         defocusSearchText();
     }
 
+    void onRandomWordButton() {
+        int destIndexEntry = rand.nextInt(index.sortedIndexEntries.size());
+        final Index.IndexEntry dest = index.sortedIndexEntries.get(destIndexEntry);
+        setSearchText(dest.token, false);
+        jumpToRow(index.sortedIndexEntries.get(destIndexEntry).startRow);
+        defocusSearchText();
+    }
+
     // --------------------------------------------------------------------------
     // Options Menu
     // --------------------------------------------------------------------------
@@ -774,7 +808,7 @@ public class DictionaryActivity extends SherlockListActivity {
             // Next word.
             nextWordMenuItem = menu.add(getString(R.string.nextWord))
                     .setIcon(R.drawable.arrow_down_float);
-            nextWordMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
+            MenuItemCompat.setShowAsAction(nextWordMenuItem, MenuItem.SHOW_AS_ACTION_IF_ROOM);
             nextWordMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
                 @Override
                 public boolean onMenuItemClick(MenuItem item) {
@@ -786,7 +820,7 @@ public class DictionaryActivity extends SherlockListActivity {
             // Previous word.
             previousWordMenuItem = menu.add(getString(R.string.previousWord))
                     .setIcon(R.drawable.arrow_up_float);
-            previousWordMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
+            MenuItemCompat.setShowAsAction(previousWordMenuItem, MenuItem.SHOW_AS_ACTION_IF_ROOM);
             previousWordMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
                 @Override
                 public boolean onMenuItemClick(MenuItem item) {
@@ -796,14 +830,23 @@ public class DictionaryActivity extends SherlockListActivity {
             });
         }
 
+        randomWordMenuItem = menu.add(getString(R.string.randomWord));
+        randomWordMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
+            @Override
+            public boolean onMenuItemClick(MenuItem item) {
+                onRandomWordButton();
+                return true;
+            }
+        });
+
         application.onCreateGlobalOptionsMenu(this, menu);
 
         {
             final MenuItem dictionaryManager = menu.add(getString(R.string.dictionaryManager));
-            dictionaryManager.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
+            MenuItemCompat.setShowAsAction(dictionaryManager, MenuItem.SHOW_AS_ACTION_NEVER);
             dictionaryManager.setOnMenuItemClickListener(new OnMenuItemClickListener() {
                 public boolean onMenuItemClick(final MenuItem menuItem) {
-                    startActivity(DictionaryManagerActivity.getLaunchIntent());
+                    startActivity(DictionaryManagerActivity.getLaunchIntent(getApplicationContext()));
                     finish();
                     return false;
                 }
@@ -812,7 +855,7 @@ public class DictionaryActivity extends SherlockListActivity {
 
         {
             final MenuItem aboutDictionary = menu.add(getString(R.string.aboutDictionary));
-            aboutDictionary.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
+            MenuItemCompat.setShowAsAction(aboutDictionary, MenuItem.SHOW_AS_ACTION_NEVER);
             aboutDictionary.setOnMenuItemClickListener(new OnMenuItemClickListener() {
                 public boolean onMenuItemClick(final MenuItem menuItem) {
                     final Context context = getListView().getContext();
@@ -920,6 +963,8 @@ public class DictionaryActivity extends SherlockListActivity {
                             return false;
                         }
                     });
+            // Rats, this won't be shown:
+            //searchForSelection.setIcon(R.drawable.abs__ic_search);
         }
 
         if (row instanceof TokenRow && ttsReady) {
@@ -984,7 +1029,6 @@ public class DictionaryActivity extends SherlockListActivity {
         // searchView.selectAll();
     }
 
-    @Override
     protected void onListItemClick(ListView l, View v, int row, long id) {
         defocusSearchText();
         if (clickOpensContextMenu && dictRaf != null) {
@@ -1008,7 +1052,7 @@ public class DictionaryActivity extends SherlockListActivity {
             final PrintWriter out = new PrintWriter(new FileWriter(wordList, true));
             out.println(rawText.toString());
             out.close();
-        } catch (IOException e) {
+        } catch (Exception e) {
             Log.e(LOG, "Unable to append to " + wordList.getAbsolutePath(), e);
             Toast.makeText(this,
                     getString(R.string.failedAddingToWordList, wordList.getAbsolutePath()),
@@ -1079,6 +1123,11 @@ public class DictionaryActivity extends SherlockListActivity {
         searchView.setQuery(text, false);
         moveCursorToRight();
         searchView.setOnQueryTextListener(onQueryTextListener);
+
+        // Hide search icon once text is entered
+        searchView.setIconifiedByDefault(text.length() > 0);
+        searchView.setIconified(false);
+
         if (triggerSearch) {
             onQueryTextListener.onQueryTextChange(text);
         }
@@ -1451,7 +1500,7 @@ public class DictionaryActivity extends SherlockListActivity {
                         String html = HtmlEntry.htmlBody(htmlEntries, index.shortName);
                         // Log.d(LOG, "html=" + html);
                         startActivityForResult(
-                                HtmlDisplayActivity.getHtmlIntent(String.format(
+                                HtmlDisplayActivity.getHtmlIntent(getApplicationContext(), String.format(
                                         "<html><head></head><body>%s</body></html>", html),
                                         htmlTextToHighlight, false),
                                 0);
@@ -1554,6 +1603,11 @@ public class DictionaryActivity extends SherlockListActivity {
             Log.d(LOG, "searchText changed during shutdown, doing nothing.");
             return;
         }
+
+        // Hide search icon once text is entered
+        searchView.setIconifiedByDefault(text.length() > 0);
+        searchView.setIconified(false);
+
         // if (!searchView.hasFocus()) {
         // Log.d(LOG, "searchText changed without focus, doing nothing.");
         // return;