]> gitweb.fperrin.net Git - Dictionary.git/commitdiff
go
authorThad Hughes <thad.hughes@gmail.com>
Mon, 18 Oct 2010 18:34:04 +0000 (11:34 -0700)
committerThad Hughes <thad.hughes@gmail.com>
Mon, 18 Oct 2010 18:34:04 +0000 (11:34 -0700)
17 files changed:
.classpath
res/layout/about_activity.xml
res/layout/edit_activity.xml
res/layout/no_dictionary.xml [deleted file]
res/values/strings.xml
src/com/hughes/android/dictionary/AboutActivity.java
src/com/hughes/android/dictionary/DictionaryActivity.java
src/com/hughes/android/dictionary/DictionaryEditActivity.java
src/com/hughes/android/dictionary/DictionaryListActivity.java
src/com/hughes/android/dictionary/QuickDicConfig.java [new file with mode: 0644]
src/com/hughes/android/dictionary/engine/Dictionary.java
src/com/hughes/android/dictionary/engine/Index.java
src/com/hughes/android/dictionary/engine/PairEntry.java
src/com/hughes/android/dictionary/engine/RowBase.java
src/com/hughes/android/dictionary/engine/TextEntry.java
src/com/hughes/android/dictionary/engine/TokenRow.java
src/com/hughes/android/util/PersistentObjectCache.java

index b198e6b1160b70d00a10ac1695ca98fd2efe570b..f033a2aba58ce0061634524784b17f98308eac4c 100644 (file)
@@ -2,7 +2,7 @@
 <classpath>
        <classpathentry kind="src" path="src"/>
        <classpathentry kind="src" path="gen"/>
-       <classpathentry kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>
+       <classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>
        <classpathentry exported="true" kind="lib" path="jars/icu4j-4_2_1-src/icu4j.jar"/>
        <classpathentry combineaccessrules="false" exported="true" kind="src" path="/Util"/>
        <classpathentry kind="output" path="bin"/>
index 29e070120af3159acc727b498aef5a3c80baf1ae..bf7759cf7104649a316a5b9f4360e6e5b37b7e1e 100755 (executable)
                android:layout_gravity="left"
                android:paddingBottom="10dip"/>
 
-       <TextView 
-               android:id="@+id/currentDictInfoTitle"
-               android:textAppearance="?android:attr/textAppearanceLarge"
-               android:layout_width="fill_parent" 
-               android:layout_height="wrap_content"
-               android:text="@string/currentDictInfo"/>
-
-       <TextView 
-               android:id="@+id/currentDictInfo"
-               android:text="@string/noDictLoaded" 
-               android:layout_width="fill_parent" 
-               android:layout_height="wrap_content"/>
-
 </LinearLayout>
 
 </ScrollView>
\ No newline at end of file
index 58e4b3568c4379500ca44ef49f31c6a3dbaf3e73..d2d6e0683d69c91e9f4fc370f398874652969e7a 100755 (executable)
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" />
 
+  <TextView 
+    android:id="@+id/dictionaryInfoTitle" 
+    android:text="@string/dictionaryInfo"
+    android:layout_width="wrap_content" 
+    android:layout_height="wrap_content"
+    android:paddingTop="5dip" />
+  <TextView 
+    android:id="@+id/dictionaryInfo" 
+    android:text=""
+    android:layout_width="wrap_content" 
+    android:layout_height="wrap_content"
+    android:paddingTop="20dip" />
 
-  String localFile = "";
-  String wordList = "";
-  
-  int openIndex = 0;
-  String openWord = "";
 </LinearLayout>
 
 </ScrollView>
\ No newline at end of file
diff --git a/res/layout/no_dictionary.xml b/res/layout/no_dictionary.xml
deleted file mode 100755 (executable)
index abc1b86..0000000
+++ /dev/null
@@ -1,44 +0,0 @@
-<ScrollView android:id="@+id/ScrollView01"
-       xmlns:android="http://schemas.android.com/apk/res/android"
-       android:layout_width="wrap_content" 
-       android:layout_height="wrap_content">
-       
-<LinearLayout 
-       android:id="@+id/LinearLayout01"
-       android:orientation="vertical"
-       android:layout_width="fill_parent"
-       android:layout_height="wrap_content"
-       >
-
-       <TextView 
-               android:id="@+id/statusTextId" 
-               android:layout_width="wrap_content" 
-               android:layout_height="wrap_content"
-               android:layout_gravity="center_vertical|fill_vertical"
-               android:layout_marginBottom="5dip"
-       />
-
-  <Button 
-    android:id="@+id/downloadDict"
-    android:text="@string/downloadDictionary"
-    android:layout_width="fill_parent"
-    android:layout_height="wrap_content"
-  />
-
-  <Button 
-    android:id="@+id/preferences"
-    android:text="@string/preferences"
-    android:layout_width="fill_parent"
-    android:layout_height="wrap_content"
-  />
-
-  <Button 
-    android:id="@+id/launchDict"
-    android:text="@string/launchDict"
-    android:layout_width="fill_parent"
-    android:layout_height="wrap_content"
-  />
-
-</LinearLayout>
-
-</ScrollView>
\ No newline at end of file
index c7925a1de0138b3f031216de27ef30ed5d45284a..7a60885343af24ccc941c93273beb428f6c3f207 100644 (file)
   <!-- DictionaryEditActivity -->
   <string name="dictionaryName">Dictionary name</string>
   <string name="downloadUrl">Dictionary download URL</string>
+  <string name="dictionaryInfo">Dictionary info:</string>
   <string name="localFile">Dictionary file</string>
   <string name="wordListFile">Word list file</string>
+  <string name="fileNotFound">File not found: '%s'</string>
+  <string name="invalidDictionary">Invalid dictionary: file=%s, error=%s</string>
+  <string name="numPairEntries">Entries: %d</string>
+  <string name="numTokens">Tokens: %d</string>
+  <string name="numRows">Rows: %d</string>
  
        <!-- Main -->
        <string name="searchText">Search Text</string>
        <string name="thadHughes">Thad Hughes</string>
        <string name="contactMe">If you\'re using QuickDic, I\'d love to hear from you.  Please send comments, suggestions, bug reports, or just a quick hello to:</string>
        <string name="myEmail">thad.hughes\+quickdic@gmail.com</string>
-       <string name="currentDictInfo">Current dictionary info:</string>
-       <string name="noDictLoaded">No dictionary loaded.</string>
-  <string name="aboutText"><![CDATA[%s\n
-\n
-Entry count: %d\n
-%s:\n
-  Unique token count: %d\n
-  Row count: %d\n
-%s:\n
-  Unique token count: %d\n
-  Row count: %d\n
-]]></string>
        
        <!-- Download. -->
        <string name="downloading">Downloading, %d of %d bytes.</string>
index 9697ae6bdb571fbba2696e281ed6ec00b639df89..e3880f5985f78f4ef364e7df76ed79356cd8e3ed 100755 (executable)
@@ -1,9 +1,7 @@
 package com.hughes.android.dictionary;\r
 \r
 import android.app.Activity;\r
-import android.content.Intent;\r
 import android.os.Bundle;\r
-import android.widget.TextView;\r
 \r
 public final class AboutActivity extends Activity {\r
 \r
@@ -14,11 +12,6 @@ public final class AboutActivity extends Activity {
   public void onCreate(final Bundle savedInstanceState) {\r
     super.onCreate(savedInstanceState);\r
     setContentView(R.layout.about_activity);\r
-\r
-    final Intent intent = getIntent();\r
-\r
-    final TextView currentDictInfo = (TextView) findViewById(R.id.currentDictInfo);\r
-    currentDictInfo.setText(intent.getStringExtra(CURRENT_DICT_INFO));\r
   }\r
 \r
 }\r
index f1699f1eb6b0f5c594a0e09e453ad0283f3cdeee..7f156cfea69d776c5c927da37223c06712fe76a6 100644 (file)
-package com.hughes.android.dictionary;
-
-import java.io.File;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.io.RandomAccessFile;
-import java.text.SimpleDateFormat;
-import java.util.Arrays;
-import java.util.Date;
-import java.util.concurrent.Executor;
-import java.util.concurrent.Executors;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-import android.app.ListActivity;
-import android.content.Context;
-import android.content.Intent;
-import android.content.SharedPreferences;
-import android.content.SharedPreferences.Editor;
-import android.graphics.Typeface;
-import android.os.Bundle;
-import android.os.Handler;
-import android.preference.PreferenceManager;
-import android.text.ClipboardManager;
-import android.text.Editable;
-import android.text.Spannable;
-import android.text.TextWatcher;
-import android.text.style.StyleSpan;
-import android.util.Log;
-import android.view.ContextMenu;
-import android.view.KeyEvent;
-import android.view.Menu;
-import android.view.MenuItem;
-import android.view.View;
-import android.view.ViewGroup;
-import android.view.ContextMenu.ContextMenuInfo;
-import android.view.MenuItem.OnMenuItemClickListener;
-import android.view.View.OnClickListener;
-import android.view.inputmethod.InputMethodManager;
-import android.widget.AdapterView;
-import android.widget.BaseAdapter;
-import android.widget.Button;
-import android.widget.EditText;
-import android.widget.ListView;
-import android.widget.TableLayout;
-import android.widget.TableRow;
-import android.widget.TextView;
-import android.widget.Toast;
-
-import com.hughes.android.dictionary.engine.Dictionary;
-import com.hughes.android.dictionary.engine.Language;
-import com.ibm.icu.text.Collator;
-
-public class DictionaryActivity extends ListActivity {
-  
-  // TO DO:
-  // * Easy reverse lookup.
-  // * Download latest dicts.
-  //   * http://ftp.tu-chemnitz.de/pub/Local/urz/ding/de-en-devel/
-  //   * http://www1.dict.cc/translation_file_request.php?l=e
-  // * Compress all the strings everywhere, put compression table in file.
-  // Done:
-  // * Only one way to way for current search to end. (won't do).
-
-  static final String LOG = "QuickDic";
-  static final String PREF_DICT_ACTIVE_LANG = "DICT_DIR_PREF";
-  static final String PREF_ACTIVE_SEARCH_TEXT = "ACTIVE_WORD_PREF";
-
-  // package for test.
-  final Handler uiHandler = new Handler();
-  private final Executor searchExecutor = Executors.newSingleThreadExecutor();
-
-  EditText searchText;
-  Button langButton;
-  int lastSelectedRow = 0;  // TODO: I'm evil.
-
-  private boolean prefsMightHaveChanged = true;
-
-  // Never null.
-  private File wordList = null;
-  private RandomAccessFile dictRaf = null;
-  private Dictionary dictionary = null;
-  private boolean saveOnlyFirstSubentry = false;
-
-  // Visible for testing.
-  IndexAdapter indexAdapter = null;
-  private SearchOperation searchOperation = null;
-  
-  public DictionaryActivity() {
-
-    searchExecutor.execute(new Runnable() {
-      public void run() {
-        final long startMillis = System.currentTimeMillis();
-        for (final String lang : Arrays.asList("EN", "DE")) {
-          Language.lookup(lang).getFindCollator(); 
-          final Collator c = Language.lookup(lang).getSortCollator(); 
-          if (c.compare("pre-print", "preppy") >= 0) {
-            Log.e(LOG, c.getClass() + " is buggy, lookups may not work properly.");
-          }
-        }
-        Log.d(LOG, "Loading collators took:" + (System.currentTimeMillis() - startMillis));
-      }
-    });
-
-  }
-
-  /** Called when the activity is first created. */
-  @Override
-  public void onCreate(Bundle savedInstanceState) {
-    super.onCreate(savedInstanceState);
-    Log.d(LOG, "onCreate:" + this);
-
-    try {
-      initDictionaryAndPrefs();
-    } catch (Exception e) {
-      return;
-    }
-
-    // UI init.
-
-    setContentView(R.layout.dictionary_activity);
-    searchText = (EditText) findViewById(R.id.SearchText);
-    langButton = (Button) findViewById(R.id.LangButton);
-    
-    searchText.addTextChangedListener(new SearchTextWatcher());
-    
-    getListView().setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
-      public void onItemSelected(AdapterView<?> arg0, View arg1, int row,
-          long arg3) {
-        setSelectedRow(row);
-      }
-      public void onNothingSelected(AdapterView<?> arg0) {
-      }
-    });
-    
-    getListView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
-      public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int row,
-          long arg3) {
-        setSelectedRow(row);
-        return false;
-      }
-    });
-    
-    final Button clearSearchTextButton = (Button) findViewById(R.id.ClearSearchTextButton);
-    clearSearchTextButton.setOnClickListener(new OnClickListener() {
-      public void onClick(View v) {
-        onClearSearchTextButton(clearSearchTextButton);
-      }
-    });
-    clearSearchTextButton.setVisibility(PreferenceManager.getDefaultSharedPreferences(this).getBoolean(
-        getString(R.string.showClearSearchTextButtonKey), true) ? View.VISIBLE
-        : View.GONE);
-    
-    final Button langButton = (Button) findViewById(R.id.LangButton);
-    langButton.setOnClickListener(new OnClickListener() {
-      public void onClick(View v) {
-        onLanguageButton();
-      }
-    });
-    
-    final Button upButton = (Button) findViewById(R.id.UpButton);
-    upButton.setOnClickListener(new OnClickListener() {
-      public void onClick(View v) {
-        onUpButton();
-      }
-    });
-    final Button downButton = (Button) findViewById(R.id.DownButton);
-    downButton.setOnClickListener(new OnClickListener() {
-      public void onClick(View v) {
-        onDownButton();
-      }
-    });
-
-    // ContextMenu.
-    registerForContextMenu(getListView());
-
-    updateLangButton();
-  }
-  
-  private void initDictionaryAndPrefs() throws Exception {
-    if (!prefsMightHaveChanged) {
-      return;
-    }
-    closeCurrentDictionary();
-    
-    final SharedPreferences prefs = PreferenceManager
-        .getDefaultSharedPreferences(this);
-    wordList = new File(prefs.getString(getString(R.string.wordListFileKey),
-        getString(R.string.wordListFileDefault)));
-    Log.d(LOG, "wordList=" + wordList);
-    
-    saveOnlyFirstSubentry = prefs.getBoolean(getString(R.string.saveOnlyFirstSubentryKey), false);
-
-    final File dictFile = new File(prefs.getString(getString(R.string.dictFileKey),
-        getString(R.string.dictFileDefault)));
-    Log.d(LOG, "dictFile=" + dictFile);
-    
-    try {
-      if (!dictFile.canRead()) {
-        throw new IOException("Unable to read dictionary file.");
-      }
-      
-      dictRaf = new RandomAccessFile(dictFile, "r");
-      final long startMillis = System.currentTimeMillis();
-      dictionary = new Dictionary(dictRaf);
-      Log.d(LOG, "Read dictionary millis: " + (System.currentTimeMillis() - startMillis));
-    } catch (IOException e) {
-      Log.e(LOG, "Couldn't open dictionary.", e);
-      
-      this.startActivity(new asdfIntent(this, DictionaryEditActivity.class));
-      finish();
-    }
-    
-    final byte lang = prefs.getInt(PREF_DICT_ACTIVE_LANG, SimpleEntry.LANG1) == SimpleEntry.LANG1 ? SimpleEntry.LANG1
-        : SimpleEntry.LANG2;
-    
-    indexAdapter = new IndexAdapter(dictionary.languageDatas[lang]);
-    setListAdapter(indexAdapter);
-    prefsMightHaveChanged = false;
-  }
-
-  @Override
-  public void onResume() {
-    super.onResume();
-    Log.d(LOG, "onResume:" + this);
-
-    try {
-      initDictionaryAndPrefs();
-    } catch (Exception e) {
-      return;
-    }
-    
-    final SharedPreferences prefs = PreferenceManager
-        .getDefaultSharedPreferences(this);
-    final String searchTextString = prefs
-        .getString(PREF_ACTIVE_SEARCH_TEXT, "");
-    searchText.setText(searchTextString);
-    getListView().requestFocus();
-    onSearchTextChange(searchTextString);
-  }
-
-  @Override
-  public void onPause() {
-    super.onPause();
-    Log.d(LOG, "onPause:" + this);
-    final Editor prefs = PreferenceManager.getDefaultSharedPreferences(this)
-        .edit();
-    prefs.putInt(PREF_DICT_ACTIVE_LANG, indexAdapter.languageData.lang);
-    prefs.putString(PREF_ACTIVE_SEARCH_TEXT, searchText.getText().toString());
-    prefs.commit();
-  }
-
-  @Override
-  public void onStop() {
-    super.onStop();
-    Log.d(LOG, "onStop:" + this);
-    if (isFinishing()) {
-      Log.i(LOG, "isFinishing()==true, closing dictionary.");
-      closeCurrentDictionary();
-    }
-  }
-
-  private void closeCurrentDictionary() {
-    Log.i(LOG, "closeCurrentDictionary");
-    if (dictionary == null) {
-      return;
-    }
-    waitForSearchEnd();
-    indexAdapter = null;
-    setListAdapter(null);
-    Log.d(LOG, "setListAdapter finished.");
-    dictionary = null;
-    try {
-      if (dictRaf != null) {
-        dictRaf.close();
-      }
-    } catch (IOException e) {
-      throw new RuntimeException(e);
-    }
-    dictRaf = null;
-  }
-
-  public String getSelectedRowRawText(final boolean onlyFirstSubentry) {
-    final Row row = indexAdapter.languageData.rows.get(getSelectedRow());
-    return indexAdapter.languageData.rowToString(row, onlyFirstSubentry);
-  }
-
-  // ----------------------------------------------------------------
-  // OptionsMenu
-  // ----------------------------------------------------------------
-
-  private MenuItem switchLanguageMenuItem = null;
-
-  @Override
-  public boolean onCreateOptionsMenu(final Menu menu) {
-    switchLanguageMenuItem = menu.add(getString(R.string.switchToLanguage));
-    switchLanguageMenuItem
-        .setOnMenuItemClickListener(new OnMenuItemClickListener() {
-          public boolean onMenuItemClick(final MenuItem menuItem) {
-            onLanguageButton();
-            return false;
-          }
-        });
-
-    final MenuItem preferences = menu.add(getString(R.string.preferences));
-    preferences.setOnMenuItemClickListener(new OnMenuItemClickListener() {
-      public boolean onMenuItemClick(final MenuItem menuItem) {
-        prefsMightHaveChanged = true;
-        startActivity(new Intent(DictionaryActivity.this,
-            PreferenceActivity.class));
-        return false;
-      }
-    });
-
-    final MenuItem about = menu.add(getString(R.string.about));
-    about.setOnMenuItemClickListener(new OnMenuItemClickListener() {
-      public boolean onMenuItemClick(final MenuItem menuItem) {
-        final Intent intent = new Intent().setClassName(AboutActivity.class
-            .getPackage().getName(), AboutActivity.class.getCanonicalName());
-        final String currentDictInfo;
-        if (dictionary == null) {
-          currentDictInfo = getString(R.string.noDictLoaded);
-        } else {
-          final LanguageData lang0 = dictionary.languageDatas[0];
-          final LanguageData lang1 = dictionary.languageDatas[1];
-          currentDictInfo = getString(R.string.aboutText, dictionary.dictionaryInfo, dictionary.entries.size(), 
-              lang0.language.symbol, lang0.sortedIndex.size(), lang0.rows.size(),
-              lang1.language.symbol, lang1.sortedIndex.size(), lang1.rows.size());
-        }
-        intent.putExtra(AboutActivity.CURRENT_DICT_INFO, currentDictInfo
-            .toString());
-        startActivity(intent);
-        return false;
-      }
-    });
-
-    final MenuItem download = menu.add(getString(R.string.downloadDictionary));
-    download.setOnMenuItemClickListener(new OnMenuItemClickListener() {
-      public boolean onMenuItemClick(final MenuItem menuItem) {
-        prefsMightHaveChanged = true;
-        startDownloadDictActivity(DictionaryActivity.this);
-        return false;
-      }
-    });
-
-    return true;
-  }
-
-  @Override
-  public boolean onPrepareOptionsMenu(final Menu menu) {
-    switchLanguageMenuItem.setTitle(getString(R.string.switchToLanguage,
-        dictionary.languageDatas[SimpleEntry
-            .otherLang(indexAdapter.languageData.lang)].language.symbol));
-    return super.onPrepareOptionsMenu(menu);
-  }
-  
-  void updateLangButton() {
-    langButton.setText(indexAdapter.languageData.language.symbol);
-  }
-
-  // ----------------------------------------------------------------
-  // Event handlers.
-  // ----------------------------------------------------------------
-  
-  void onLanguageButton() {
-    waitForSearchEnd();
-    indexAdapter = new IndexAdapter(
-        dictionary.languageDatas[(indexAdapter.languageData == dictionary.languageDatas[0]) ? 1
-            : 0]);
-    Log.d(LOG, "onLanguageButton, newLang=" + indexAdapter.languageData.language.symbol);
-    setListAdapter(indexAdapter);
-    updateLangButton();
-    onSearchTextChange(searchText.getText().toString());
-  }
-
-  void onUpButton() {
-    final int destRowIndex = indexAdapter.languageData.getPrevTokenRow(getSelectedRow());
-    Log.d(LOG, "onUpButton, destRowIndex=" + destRowIndex);
-    jumpToRow(indexAdapter, destRowIndex);
-  }
-
-  void onDownButton() {
-    final int destRowIndex = indexAdapter.languageData.getNextTokenRow(getSelectedRow());
-    Log.d(LOG, "onDownButton, destRowIndex=" + destRowIndex);
-    jumpToRow(indexAdapter, destRowIndex);
-  }
-
-  void onAppendToWordList() {
-    final int row = getSelectedRow();
-    if (row < 0) {
-      return;
-    }
-    final StringBuilder rawText = new StringBuilder();
-    final String word = indexAdapter.languageData.getIndexEntryForRow(row).word;
-    rawText.append(
-        new SimpleDateFormat("yyyy.MM.dd HH:mm:ss").format(new Date()))
-        .append("\t");
-    rawText.append(word).append("\t");
-    rawText.append(getSelectedRowRawText(saveOnlyFirstSubentry));
-    Log.d(LOG, "Writing : " + rawText);
-    try {
-      wordList.getParentFile().mkdirs();
-      final PrintWriter out = new PrintWriter(
-          new FileWriter(wordList, true));
-      out.println(rawText.toString());
-      out.close();
-    } catch (IOException e) {
-      Log.e(LOG, "Unable to append to " + wordList.getAbsolutePath(), e);
-      Toast.makeText(this, getString(R.string.failedAddingToWordList, wordList.getAbsolutePath()), Toast.LENGTH_LONG);
-    }
-    return;
-  }
-
-  void onCopy() {
-    final int row = getSelectedRow();
-    if (row < 0) {
-      return;
-    }
-    Log.d(LOG, "Copy." + DictionaryActivity.this.getSelectedRow());
-    final StringBuilder result = new StringBuilder();
-    result.append(getSelectedRowRawText(false));
-    final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
-    clipboardManager.setText(result.toString());
-    Log.d(LOG, "Copied: " + result);
-  }
-
-  @Override
-  public boolean onKeyDown(int keyCode, KeyEvent event) {
-    if (event.getUnicodeChar() != 0) {
-      if (!searchText.hasFocus()) {
-        searchText.setText("" + (char) event.getUnicodeChar());
-        onSearchTextChange(searchText.getText().toString());
-        searchText.requestFocus();
-      }
-      return true;
-    }
-    return super.onKeyDown(keyCode, event);
-  }
-
-  @Override
-  protected void onListItemClick(ListView l, View v, int row, long id) {
-    setSelectedRow(row);
-    openContextMenu(getListView());
-  }
-
-  void onSearchTextChange(final String searchText) {
-    Log.d(LOG, "onSearchTextChange: " + searchText);
-    synchronized (this) {
-      searchOperation = new SearchOperation(indexAdapter, searchText.trim(), searchOperation);
-      searchExecutor.execute(searchOperation);
-    }
-  }
-
-  private void onClearSearchTextButton(final Button clearSearchTextButton) {
-    clearSearchTextButton.requestFocus();
-    searchText.setText("");
-    searchText.requestFocus();
-    Log.d(LOG, "Trying to show soft keyboard.");
-    final InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
-    manager.showSoftInput(searchText, InputMethodManager.SHOW_IMPLICIT);
-  }
-
-  // ----------------------------------------------------------------
-  // ContextMenu
-  // ----------------------------------------------------------------
-
-  @Override
-  public void onCreateContextMenu(ContextMenu menu, View v,
-      ContextMenuInfo menuInfo) {
-    final int row = getSelectedRow();
-    if (row < 0) {
-      return;
-    }
-
-    final MenuItem addToWordlist = menu.add(getString(R.string.addToWordList, wordList.getName()));
-    addToWordlist.setOnMenuItemClickListener(new OnMenuItemClickListener() {
-      public boolean onMenuItemClick(MenuItem item) {
-        onAppendToWordList();
-        return false;
-      }
-    });
-
-    final MenuItem copy = menu.add(android.R.string.copy);
-    copy.setOnMenuItemClickListener(new OnMenuItemClickListener() {
-      public boolean onMenuItemClick(MenuItem item) {
-        onCopy();
-        return false;
-      }
-    });
-
-  }
-
-  private void jumpToRow(final IndexAdapter dictionaryListAdapter,
-      final int rowIndex) {
-    Log.d(LOG, "jumpToRow: " + rowIndex);
-    if (dictionaryListAdapter != this.indexAdapter) {
-      Log.w(LOG, "skipping jumpToRow for old list adapter: " + rowIndex);
-      return;
-    }
-    setSelection(rowIndex);
-    setSelectedRow(rowIndex);
-    getListView().setSelected(true);
-  }
-  
-  // TODO: delete me somehow.
-  private int getSelectedRow() {
-    return lastSelectedRow;
-  }
-  private void setSelectedRow(final int row) {
-    lastSelectedRow = row;
-    Log.d(LOG, "Selected: " + getSelectedRowRawText(true));
-    updateSearchText();
-  }
-
-  private void updateSearchText() {
-    Log.d(LOG, "updateSearchText");
-    final int selectedRowIndex = getSelectedRow();
-    if (!searchText.hasFocus()) {
-      if (selectedRowIndex >= 0) {
-        final String word = indexAdapter.languageData
-            .getIndexEntryForRow(selectedRowIndex).word;
-        if (!word.equals(searchText.getText().toString())) {
-          Log.d(LOG, "updateSearchText: setText: " + word);
-          searchText.setText(word);
-        }
-      } else {
-        Log.w(LOG, "updateSearchText: nothing selected.");
-      }
-    }
-  }
-
-  static void startDownloadDictActivity(final Context context) {
-    final Intent intent = new Intent(context, DownloadActivity.class);
-    final SharedPreferences prefs = PreferenceManager
-        .getDefaultSharedPreferences(context);
-    final String dictFetchUrl = prefs.getString(context
-        .getString(R.string.dictFetchUrlKey), context
-        .getString(R.string.dictFetchUrlDefault));
-    final String dictFileName = prefs.getString(context
-        .getString(R.string.dictFileKey), context
-        .getString(R.string.dictFileDefault));
-    intent.putExtra(DownloadActivity.SOURCE, dictFetchUrl);
-    intent.putExtra(DownloadActivity.DEST, dictFileName);
-    context.startActivity(intent);
-  }
-
-  class IndexAdapter extends BaseAdapter {
-
-    // Visible for testing.
-    final LanguageData languageData;
-
-    IndexAdapter(final LanguageData languageData) {
-      this.languageData = languageData;
-    }
-
-    public int getCount() {
-      return languageData.rows.size();
-    }
-
-    public Dictionary.Row getItem(int rowIndex) {
-      assert rowIndex < languageData.rows.size();
-      return languageData.rows.get(rowIndex);
-    }
-
-    public long getItemId(int rowIndex) {
-      return rowIndex;
-    }
-
-    public View getView(final int rowIndex, final View convertView,
-        final ViewGroup parent) {
-      final Row row = getItem(rowIndex);
-
-      // Token row.
-      if (row.isToken()) {
-        TextView result = null;
-        if (convertView instanceof TextView) {
-          result = (TextView) convertView;
-        } else {
-          result = new TextView(parent.getContext());
-        }
-        if (row == null) {
-          return result;
-        }
-        result.setText(languageData.rowToString(row, false));
-        result.setTextAppearance(parent.getContext(),
-            android.R.style.TextAppearance_Large);
-        result.setClickable(false);
-        return result;
-      }
-
-      // Entry row(s).
-      final TableLayout result = new TableLayout(parent.getContext());
-
-      final SimpleEntry entry = new SimpleEntry(null, null);//.entries.get(row.getIndex());
-      final int rowCount = entry.getRowCount();
-      for (int r = 0; r < rowCount; ++r) {
-        final TableRow tableRow = new TableRow(result.getContext());
-
-        TextView column1 = new TextView(tableRow.getContext());
-        TextView column2 = new TextView(tableRow.getContext());
-        final TableRow.LayoutParams layoutParams = new TableRow.LayoutParams();
-        layoutParams.weight = 0.5f;
-
-        if (r > 0) {
-          final TextView spacer = new TextView(tableRow.getContext());
-          spacer.setText(r == 0 ? "� " : " ï¿½ ");
-          tableRow.addView(spacer);
-        }
-        tableRow.addView(column1, layoutParams);
-        if (r > 0) {
-          final TextView spacer = new TextView(tableRow.getContext());
-          spacer.setText(r == 0 ? "� " : " ï¿½ ");
-          tableRow.addView(spacer);
-        }
-        tableRow.addView(column2, layoutParams);
-
-        column1.setWidth(1);
-        column2.setWidth(1);
-        // column1.setTextAppearance(parent.getContext(), android.R.style.Text);
-
-        // TODO: color words by gender
-        final String col1Text = entry.getAllText(languageData.lang)[r];
-        column1.setText(col1Text, TextView.BufferType.SPANNABLE);
-        final Spannable col1Spannable = (Spannable) column1.getText();
-        int startPos = 0;
-        final String token = languageData.getIndexEntryForRow(rowIndex).word;
-        while ((startPos = col1Text.indexOf(token, startPos)) != -1) {
-          col1Spannable.setSpan(new StyleSpan(Typeface.BOLD), startPos,
-              startPos + token.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
-          startPos += token.length();
-        }
-
-        column2.setText(
-            entry.getAllText(SimpleEntry.otherLang(languageData.lang))[r],
-            TextView.BufferType.NORMAL);
-
-        result.addView(tableRow);
-      }
-
-      return result;
-    }
-
-  } // DictionaryListAdapter
-
-  private final class SearchOperation implements Runnable {
-    SearchOperation previousSearchOperation;
-    
-    final IndexAdapter listAdapter;
-    final LanguageData languageData;
-    final String searchText;
-    final AtomicBoolean interrupted = new AtomicBoolean(false);
-    boolean searchFinished = false;
-
-    SearchOperation(final IndexAdapter listAdapter,
-        final String searchText, final SearchOperation previousSearchOperation) {
-      this.listAdapter = listAdapter;
-      this.languageData = listAdapter.languageData;
-      this.searchText = searchText;
-      this.previousSearchOperation = previousSearchOperation;
-    }
-
-    public void run() {
-      if (previousSearchOperation != null) {
-        previousSearchOperation.stopAndWait();
-      }
-      previousSearchOperation = null;
-      
-      Log.d(LOG, "SearchOperation: " + searchText);
-      final int indexLocation = languageData.lookup(searchText, interrupted);
-      if (!interrupted.get()) {
-        final IndexEntry indexEntry = languageData.sortedIndex.get(indexLocation);
-        
-        Log.d(LOG, "SearchOperation completed: " + indexEntry.toString());
-        uiHandler.post(new Runnable() {
-          public void run() {
-            // Check is just a performance operation.
-            if (!interrupted.get()) {
-              // This is safe, because it checks that the listAdapter hasn't changed.
-              jumpToRow(listAdapter, indexEntry.startRow);
-            }
-            synchronized (DictionaryActivity.this) {
-              searchOperation = null;
-              DictionaryActivity.this.notifyAll();
-            }
-          }
-        });
-      }      
-      synchronized (this) {
-        searchFinished = true;
-        this.notifyAll();
-      }
-    }
-    
-    private void stopAndWait() {
-      interrupted.set(true);
-      synchronized (this) {
-        while (!searchFinished) {
-          Log.d(LOG, "stopAndWait: " + searchText);
-          try {
-            this.wait();
-          } catch (InterruptedException e) {
-            Log.e(LOG, "Interrupted", e);
-          }
-        }
-      }
-    }
-  }  // SearchOperation
-
-  void waitForSearchEnd() {
-    synchronized (this) {
-      while (searchOperation != null) {
-        Log.d(LOG, "waitForSearchEnd");
-        try {
-          this.wait();
-        } catch (InterruptedException e) {
-          Log.e(LOG, "Interrupted.", e);
-        }
-      }
-    }
-  }
-
-  private class SearchTextWatcher implements TextWatcher {
-    public void afterTextChanged(final Editable searchTextEditable) {
-      Log.d(LOG, "Search text changed: " + searchText.getText().toString());
-      if (searchText.hasFocus()) {
-        // If they were typing to cause the change, update the UI.
-        onSearchTextChange(searchText.getText().toString());
-      }
-    }
-
-    public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
-        int arg3) {
-    }
-
-    public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
-    }
-  }
-
-}
\ No newline at end of file
+package com.hughes.android.dictionary;\r
+\r
+import java.io.File;\r
+import java.io.IOException;\r
+import java.io.RandomAccessFile;\r
+import java.util.concurrent.Executor;\r
+import java.util.concurrent.Executors;\r
+import java.util.concurrent.atomic.AtomicBoolean;\r
+\r
+import android.app.ListActivity;\r
+import android.content.Intent;\r
+import android.graphics.Typeface;\r
+import android.os.Bundle;\r
+import android.os.Handler;\r
+import android.preference.PreferenceManager;\r
+import android.text.Editable;\r
+import android.text.Spannable;\r
+import android.text.TextWatcher;\r
+import android.text.style.StyleSpan;\r
+import android.util.Log;\r
+import android.view.View;\r
+import android.view.ViewGroup;\r
+import android.view.View.OnClickListener;\r
+import android.widget.BaseAdapter;\r
+import android.widget.Button;\r
+import android.widget.EditText;\r
+import android.widget.ListAdapter;\r
+import android.widget.TableLayout;\r
+import android.widget.TableRow;\r
+import android.widget.TextView;\r
+\r
+import com.hughes.android.dictionary.engine.Dictionary;\r
+import com.hughes.android.dictionary.engine.Index;\r
+import com.hughes.android.dictionary.engine.PairEntry;\r
+import com.hughes.android.dictionary.engine.RowBase;\r
+import com.hughes.android.dictionary.engine.TokenRow;\r
+import com.hughes.android.util.PersistentObjectCache;\r
+\r
+public class DictionaryActivity extends ListActivity {\r
+\r
+  static final String LOG = "QuickDic";\r
+\r
+  RandomAccessFile dictRaf = null;\r
+  Dictionary dictionary = null;\r
+  int indexIndex = 0;\r
+  Index index = null;\r
+  \r
+  // package for test.\r
+  final Handler uiHandler = new Handler();\r
+  private final Executor searchExecutor = Executors.newSingleThreadExecutor();\r
+  private SearchOperation currentSearchOperation = null;\r
+\r
+  EditText searchText;\r
+  Button langButton;\r
+\r
+  // Never null.\r
+  private File wordList = null;\r
+  private boolean saveOnlyFirstSubentry = false;\r
+\r
+  // Visible for testing.\r
+  ListAdapter indexAdapter = null;\r
+\r
+  \r
+  public static Intent getIntent(final int dictIndex, final int indexIndex, final String searchToken) {\r
+    final Intent intent = new Intent();\r
+    intent.setClassName(DictionaryActivity.class.getPackage().getName(), DictionaryActivity.class.getName());\r
+    intent.putExtra(C.DICT_INDEX, dictIndex);\r
+    intent.putExtra(C.INDEX_INDEX, indexIndex);\r
+    intent.putExtra(C.SEARCH_TOKEN, searchToken);\r
+    return intent;\r
+  }\r
+\r
+  @Override\r
+  public void onCreate(Bundle savedInstanceState) {\r
+    super.onCreate(savedInstanceState);\r
+    \r
+    PersistentObjectCache.init(this);\r
+    QuickDicConfig quickDicConfig = PersistentObjectCache.init(\r
+        this).read(C.DICTIONARY_CONFIGS, QuickDicConfig.class);\r
+    \r
+    final Intent intent = getIntent();\r
+    \r
+    final DictionaryConfig dictionaryConfig = quickDicConfig.dictionaryConfigs.get(intent.getIntExtra(C.DICT_INDEX, 0));\r
+    try {\r
+      dictRaf = new RandomAccessFile(dictionaryConfig.localFile, "r");\r
+      dictionary = new Dictionary(dictRaf); \r
+    } catch (IOException e) {\r
+      Log.e(LOG, "Unable to load dictionary.", e);\r
+      // TODO: Start up the editor.\r
+      finish();\r
+      return;\r
+    }\r
+    \r
+    indexIndex = intent.getIntExtra(C.INDEX_INDEX, 0);\r
+    index = dictionary.indices.get(indexIndex);\r
+    setListAdapter(new IndexAdapter(index));\r
+    \r
+    setContentView(R.layout.dictionary_activity);\r
+    searchText = (EditText) findViewById(R.id.SearchText);\r
+    langButton = (Button) findViewById(R.id.LangButton);\r
+    \r
+    searchText.addTextChangedListener(new SearchTextWatcher());\r
+    \r
+    \r
+    final Button clearSearchTextButton = (Button) findViewById(R.id.ClearSearchTextButton);\r
+    clearSearchTextButton.setOnClickListener(new OnClickListener() {\r
+      public void onClick(View v) {\r
+        //onClearSearchTextButton(clearSearchTextButton);\r
+      }\r
+    });\r
+    clearSearchTextButton.setVisibility(PreferenceManager.getDefaultSharedPreferences(this).getBoolean(\r
+        getString(R.string.showClearSearchTextButtonKey), true) ? View.VISIBLE\r
+        : View.GONE);\r
+    \r
+    final Button langButton = (Button) findViewById(R.id.LangButton);\r
+    langButton.setOnClickListener(new OnClickListener() {\r
+      public void onClick(View v) {\r
+        onLanguageButton();\r
+      }\r
+    });\r
+    \r
+    final Button upButton = (Button) findViewById(R.id.UpButton);\r
+    upButton.setOnClickListener(new OnClickListener() {\r
+      public void onClick(View v) {\r
+        //onUpButton();\r
+      }\r
+    });\r
+    final Button downButton = (Button) findViewById(R.id.DownButton);\r
+    downButton.setOnClickListener(new OnClickListener() {\r
+      public void onClick(View v) {\r
+        //onDownButton();\r
+      }\r
+    });\r
+\r
+    // ContextMenu.\r
+    registerForContextMenu(getListView());\r
+\r
+    updateLangButton();\r
+\r
+  }\r
+  \r
+  void updateLangButton() {\r
+    langButton.setText(index.shortName.toUpperCase());\r
+  }\r
+\r
+\r
+  \r
+  \r
+  void onLanguageButton() {\r
+    // TODO: synchronized, stop search.\r
+    \r
+    indexIndex = (indexIndex + 1) % dictionary.indices.size();\r
+    index = dictionary.indices.get(indexIndex);\r
+    indexAdapter = new IndexAdapter(index);\r
+    Log.d(LOG, "onLanguageButton, newLang=" + index.longName);\r
+    setListAdapter(indexAdapter);\r
+    updateLangButton();\r
+    onSearchTextChange(searchText.getText().toString());\r
+  }\r
+  \r
+  // --------------------------------------------------------------------------\r
+  // SearchOperation\r
+  // --------------------------------------------------------------------------\r
+\r
+  private void searchFinished(final SearchOperation searchOperation) {\r
+    if (searchOperation == this.currentSearchOperation) {\r
+      setSelection(searchOperation.tokenRow.index());\r
+      getListView().setSelected(true);\r
+    }\r
+  }\r
+\r
+  final class SearchOperation implements Runnable {\r
+    \r
+    final AtomicBoolean interrupted = new AtomicBoolean(false);\r
+    final String searchText;\r
+    final Index index;\r
+    \r
+    boolean failed = false;\r
+    TokenRow tokenRow;\r
+    \r
+    SearchOperation(final String searchText, final Index index) {\r
+      this.searchText = searchText.trim();\r
+      this.index = index;\r
+    }\r
+\r
+    @Override\r
+    public void run() {\r
+      tokenRow = index.findInsertionPoint(searchText, interrupted);\r
+      failed = false; // TODO\r
+      if (!interrupted.get()) {\r
+        uiHandler.post(new Runnable() {\r
+          @Override\r
+          public void run() {            \r
+            searchFinished(SearchOperation.this);\r
+          }\r
+        });\r
+      }\r
+    }\r
+  }\r
+\r
+  \r
+  // --------------------------------------------------------------------------\r
+  // IndexAdapter\r
+  // --------------------------------------------------------------------------\r
+\r
+  static final class IndexAdapter extends BaseAdapter {\r
+    \r
+    final Index index;\r
+\r
+    IndexAdapter(final Index index) {\r
+      this.index = index;\r
+    }\r
+\r
+    @Override\r
+    public int getCount() {\r
+      return index.rows.size();\r
+    }\r
+\r
+    @Override\r
+    public Object getItem(int position) {\r
+      return index.rows.get(position);\r
+    }\r
+\r
+    @Override\r
+    public long getItemId(int position) {\r
+      return position;\r
+    }\r
+\r
+    @Override\r
+    public View getView(int position, View convertView, ViewGroup parent) {\r
+      final RowBase row = index.rows.get(position);\r
+      if (row instanceof PairEntry.Row) {\r
+        return getView((PairEntry.Row) row, parent);\r
+      } else if (row instanceof TokenRow) {\r
+        return getView((TokenRow) row, parent);\r
+      } else {\r
+        throw new IllegalArgumentException("Unsupported Row type: " + row.getClass());\r
+      }\r
+    }\r
+\r
+    private View getView(PairEntry.Row row, ViewGroup parent) {\r
+      final TableLayout result = new TableLayout(parent.getContext());\r
+      final PairEntry entry = row.getEntry();\r
+      final int rowCount = entry.pairs.length;\r
+      for (int r = 0; r < rowCount; ++r) {\r
+        final TableRow tableRow = new TableRow(result.getContext());\r
+\r
+        TextView column1 = new TextView(tableRow.getContext());\r
+        TextView column2 = new TextView(tableRow.getContext());\r
+        final TableRow.LayoutParams layoutParams = new TableRow.LayoutParams();\r
+        layoutParams.weight = 0.5f;\r
+\r
+        if (r > 0) {\r
+          final TextView spacer = new TextView(tableRow.getContext());\r
+          spacer.setText(" â€¢ ");\r
+          tableRow.addView(spacer);\r
+        }\r
+        tableRow.addView(column1, layoutParams);\r
+        if (r > 0) {\r
+          final TextView spacer = new TextView(tableRow.getContext());\r
+          spacer.setText(" â€¢ ");\r
+          tableRow.addView(spacer);\r
+        }\r
+        tableRow.addView(column2, layoutParams);\r
+\r
+        column1.setWidth(1);\r
+        column2.setWidth(1);\r
+\r
+        // TODO: color words by gender\r
+        final String col1Text = index.swapPairEntries ? entry.pairs[r].lang2 : entry.pairs[r].lang1;\r
+        column1.setText(col1Text, TextView.BufferType.SPANNABLE);\r
+        final Spannable col1Spannable = (Spannable) column1.getText();\r
+        \r
+        int startPos = 0;\r
+        final String token = row.getTokenRow(true).getToken();\r
+        while ((startPos = col1Text.indexOf(token, startPos)) != -1) {\r
+          col1Spannable.setSpan(new StyleSpan(Typeface.BOLD), startPos,\r
+              startPos + token.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);\r
+          startPos += token.length();\r
+        }\r
+\r
+        final String col2Text = index.swapPairEntries ? entry.pairs[r].lang1 : entry.pairs[r].lang2;\r
+        column2.setText(col2Text, TextView.BufferType.NORMAL);\r
+\r
+        result.addView(tableRow);\r
+      }\r
+\r
+      return result;\r
+    }\r
+\r
+    private View getView(TokenRow row, ViewGroup parent) {\r
+      final TextView textView = new TextView(parent.getContext());\r
+      textView.setText(row.getToken());\r
+      textView.setTextSize(20);\r
+      return textView;\r
+    }\r
+    \r
+  }\r
+\r
+  // --------------------------------------------------------------------------\r
+  // SearchText\r
+  // --------------------------------------------------------------------------\r
+\r
+  void onSearchTextChange(final String searchText) {\r
+    Log.d(LOG, "onSearchTextChange: " + searchText);\r
+    if (currentSearchOperation != null) {\r
+      currentSearchOperation.interrupted.set(true);\r
+    }\r
+    currentSearchOperation = new SearchOperation(searchText, index);\r
+    searchExecutor.execute(currentSearchOperation);\r
+  }\r
+  \r
+  private class SearchTextWatcher implements TextWatcher {\r
+    public void afterTextChanged(final Editable searchTextEditable) {\r
+      Log.d(LOG, "Search text changed: " + searchText.getText());\r
+      if (searchText.hasFocus()) {\r
+        // If they were typing to cause the change, update the UI.\r
+        onSearchTextChange(searchText.getText().toString());\r
+      }\r
+    }\r
+\r
+    public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,\r
+        int arg3) {\r
+    }\r
+\r
+    public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {\r
+    }\r
+  }\r
+\r
+}\r
index 3c2f5a0b8e8e8e8160286176491433fe5ada99a5..1e3615607d7ca27105f04d6cc0c2f96bbc948c4b 100644 (file)
@@ -1,38 +1,50 @@
 package com.hughes.android.dictionary;
 
-import java.util.List;
+import java.io.File;
+import java.io.IOException;
+import java.io.RandomAccessFile;
 
 import android.app.Activity;
 import android.content.Context;
 import android.content.Intent;
 import android.os.Bundle;
+import android.text.Editable;
+import android.text.TextWatcher;
 import android.view.Menu;
 import android.view.MenuItem;
 import android.view.MenuItem.OnMenuItemClickListener;
 import android.widget.EditText;
+import android.widget.TextView;
 
+import com.hughes.android.dictionary.engine.Dictionary;
+import com.hughes.android.dictionary.engine.Index;
 import com.hughes.android.util.PersistentObjectCache;
 
 public class DictionaryEditActivity extends Activity {
 
-  List<DictionaryConfig> dictionaryConfigs;
+  QuickDicConfig quickDicConfig;
   private DictionaryConfig dictionaryConfig;
 
-  public static final String DICT_INDEX = "dictIndex";
+  
+  public static Intent getIntent(final int dictIndex) {
+    final Intent intent = new Intent();
+    intent.setClassName(DictionaryEditActivity.class.getPackage().getName(), DictionaryEditActivity.class.getName());
+    intent.putExtra(C.DICT_INDEX, dictIndex);
+    return intent;
+  }
 
   /** Called when the activity is first created. */
-  @SuppressWarnings("unchecked")
   @Override
   public void onCreate(final Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.edit_activity);
 
     PersistentObjectCache.init(this);
-    dictionaryConfigs = (List<DictionaryConfig>) PersistentObjectCache.init(
-        this).read(DictionaryListActivity.DICTIONARY_CONFIGS);
+    quickDicConfig = PersistentObjectCache.init(
+        this).read(C.DICTIONARY_CONFIGS, QuickDicConfig.class);
 
     final Intent intent = getIntent();
-    dictionaryConfig = dictionaryConfigs.get(intent.getIntExtra(DICT_INDEX, 0));
+    dictionaryConfig = quickDicConfig.dictionaryConfigs.get(intent.getIntExtra(C.DICT_INDEX, 0));
 
     // Write stuff from object into fields.
     
@@ -40,6 +52,23 @@ public class DictionaryEditActivity extends Activity {
     ((EditText) findViewById(R.id.localFile)).setText(dictionaryConfig.localFile);
     ((EditText) findViewById(R.id.wordListFile)).setText(dictionaryConfig.wordList);
     ((EditText) findViewById(R.id.downloadUrl)).setText(dictionaryConfig.downloadUrl);
+    
+    updateDictInfo();
+    ((EditText) findViewById(R.id.localFile)).addTextChangedListener(new TextWatcher() {
+      @Override
+      public void onTextChanged(CharSequence s, int start, int before, int count) {
+      }
+      
+      @Override
+      public void beforeTextChanged(CharSequence s, int start, int count, int after) {
+      }
+      
+      @Override
+      public void afterTextChanged(Editable s) {
+        updateDictInfo();
+      }
+    });
+    
   }
 
   @Override
@@ -52,8 +81,7 @@ public class DictionaryEditActivity extends Activity {
     dictionaryConfig.wordList = ((EditText) findViewById(R.id.wordListFile)).getText().toString();
     dictionaryConfig.downloadUrl = ((EditText) findViewById(R.id.downloadUrl)).getText().toString();
     
-    PersistentObjectCache.getInstance().write(
-        DictionaryListActivity.DICTIONARY_CONFIGS, dictionaryConfigs);
+    PersistentObjectCache.getInstance().write(C.DICTIONARY_CONFIGS, quickDicConfig);
   }
   
   public boolean onCreateOptionsMenu(final Menu menu) {
@@ -67,6 +95,34 @@ public class DictionaryEditActivity extends Activity {
     
     return true;
   }
+  
+  void updateDictInfo() {
+    final TextView dictInfo = (TextView) findViewById(R.id.dictionaryInfo);
+    final String localFile = ((EditText) findViewById(R.id.localFile)).getText().toString();
+    
+    if (!new File(localFile).canRead()) {
+      dictInfo.setText(getString(R.string.fileNotFound, localFile));
+      return;
+    }
+    
+    try {
+      final RandomAccessFile raf = new RandomAccessFile(localFile, "r");
+      final Dictionary dict = new Dictionary(raf);
+      final StringBuilder builder = new StringBuilder();
+      builder.append(dict.dictInfo).append("\n");
+      builder.append(getString(R.string.numPairEntries, dict.pairEntries.size())).append("\n");
+      for (final Index index : dict.indices) {
+        builder.append("\n");
+        builder.append(index.longName).append("\n");
+        builder.append("  ").append(getString(R.string.numTokens, index.sortedIndexEntries.size())).append("\n");
+        builder.append("  ").append(getString(R.string.numRows, index.rows.size())).append("\n");
+      }
+      raf.close();
+      dictInfo.setText(builder.toString());
+    } catch (IOException e) {
+      dictInfo.setText(getString(R.string.invalidDictionary, localFile, e.toString()));
+    }
+  }
 
   static void startDownloadDictActivity(final Context context, final DictionaryConfig dictionaryConfig) {
     final Intent intent = new Intent(context, DownloadActivity.class);
@@ -75,5 +131,4 @@ public class DictionaryEditActivity extends Activity {
     context.startActivity(intent);
   }
 
-
 }
index 1f9936aff11b67db2392157c04bf23e122166400..26f7075563ddb7c57b1ade9ecf720bcc1085bc4c 100644 (file)
@@ -1,8 +1,5 @@
 package com.hughes.android.dictionary;
 
-import java.util.ArrayList;
-import java.util.List;
-
 import android.app.ListActivity;
 import android.content.Intent;
 import android.os.Bundle;
@@ -14,13 +11,12 @@ import android.view.View;
 import android.view.ViewGroup;
 import android.view.ContextMenu.ContextMenuInfo;
 import android.view.MenuItem.OnMenuItemClickListener;
-import android.view.View.OnFocusChangeListener;
 import android.widget.AdapterView;
 import android.widget.BaseAdapter;
-import android.widget.EditText;
 import android.widget.TableLayout;
 import android.widget.TextView;
 import android.widget.AdapterView.AdapterContextMenuInfo;
+import android.widget.AdapterView.OnItemClickListener;
 
 import com.hughes.android.util.PersistentObjectCache;
 
@@ -28,9 +24,8 @@ public class DictionaryListActivity extends ListActivity {
 
   static final String LOG = "QuickDic";
   
-  static final String DICTIONARY_CONFIGS = "dictionaryConfigs";
+  QuickDicConfig quickDicConfig = new QuickDicConfig();
   
-  List<DictionaryConfig> dictionaries = new ArrayList<DictionaryConfig>();
   
   public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
@@ -38,33 +33,42 @@ public class DictionaryListActivity extends ListActivity {
 
     // UI init.
     setContentView(R.layout.list_activity);
-    
+
+    /*
     getListView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
       public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int row,
           long arg3) {
         return false;
       }
     });
-    
+    */
+
+    getListView().setOnItemClickListener(new OnItemClickListener() {
+      @Override
+      public void onItemClick(AdapterView<?> arg0, View arg1, int index,
+          long id) {
+        onClick(index);
+      }
+    });
+
     // ContextMenu.
     registerForContextMenu(getListView());
     
-    getListView().setItemsCanFocus(true);
   }
   
-  @SuppressWarnings("unchecked")
+  private void onClick(int dictIndex) {
+    final Intent intent = DictionaryActivity.getIntent(dictIndex, 0, "");
+    startActivity(intent);
+  }
+  
   @Override
   protected void onResume() {
     super.onResume();
 
-    dictionaries = (List<DictionaryConfig>) PersistentObjectCache.init(this).read(DICTIONARY_CONFIGS);
-    if (dictionaries == null) {
-      dictionaries = new ArrayList<DictionaryConfig>();
-    }
-    if (dictionaries.size() == 0) {
-      final DictionaryConfig dictionaryConfig = DictionaryConfig.defaultConfig();
-      dictionaries.add(dictionaryConfig);
-      PersistentObjectCache.getInstance().write(DICTIONARY_CONFIGS, dictionaries);
+    quickDicConfig = PersistentObjectCache.init(this).read(C.DICTIONARY_CONFIGS, QuickDicConfig.class);
+    if (quickDicConfig == null) {
+      quickDicConfig = new QuickDicConfig();
+      PersistentObjectCache.getInstance().write(C.DICTIONARY_CONFIGS, quickDicConfig);
     }
 
     setListAdapter(new Adapter());
@@ -76,7 +80,7 @@ public class DictionaryListActivity extends ListActivity {
           public boolean onMenuItemClick(final MenuItem menuItem) {
             final DictionaryConfig dictionaryConfig = new DictionaryConfig();
             dictionaryConfig.name = getString(R.string.newDictionary);
-            dictionaries.add(0, dictionaryConfig);
+            quickDicConfig.dictionaryConfigs.add(0, dictionaryConfig);
             dictionaryConfigsChanged();
             return false;
           }
@@ -97,9 +101,7 @@ public class DictionaryListActivity extends ListActivity {
     editMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
       @Override
       public boolean onMenuItemClick(MenuItem item) {
-        final Intent intent = new Intent(DictionaryListActivity.this, DictionaryEditActivity.class);
-        intent.putExtra(DictionaryEditActivity.DICT_INDEX, adapterContextMenuInfo.position);
-        startActivity(intent);
+        startActivity(DictionaryEditActivity.getIntent(adapterContextMenuInfo.position));
         return true;
       }
     });
@@ -109,8 +111,8 @@ public class DictionaryListActivity extends ListActivity {
       moveUpMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
         @Override
         public boolean onMenuItemClick(MenuItem item) {
-          final DictionaryConfig dictionaryConfig = dictionaries.remove(adapterContextMenuInfo.position);
-          dictionaries.add(adapterContextMenuInfo.position - 1, dictionaryConfig);
+          final DictionaryConfig dictionaryConfig = quickDicConfig.dictionaryConfigs.remove(adapterContextMenuInfo.position);
+          quickDicConfig.dictionaryConfigs.add(adapterContextMenuInfo.position - 1, dictionaryConfig);
           dictionaryConfigsChanged();
           return true;
         }
@@ -121,7 +123,7 @@ public class DictionaryListActivity extends ListActivity {
     deleteMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
       @Override
       public boolean onMenuItemClick(MenuItem item) {
-        dictionaries.remove(adapterContextMenuInfo.position);
+        quickDicConfig.dictionaryConfigs.remove(adapterContextMenuInfo.position);
         dictionaryConfigsChanged();
         return true;
       }
@@ -130,33 +132,20 @@ public class DictionaryListActivity extends ListActivity {
   }
 
   private void dictionaryConfigsChanged() {
-    PersistentObjectCache.getInstance().write(DICTIONARY_CONFIGS, dictionaries);
+    PersistentObjectCache.getInstance().write(C.DICTIONARY_CONFIGS, quickDicConfig);
     setListAdapter(getListAdapter());
   }
 
-  static final OnFocusChangeListener focusListener = new OnFocusChangeListener() {
-    @Override
-    public void onFocusChange(View v, boolean hasFocus) {
-      final TextView textView = (TextView) v;
-      if (hasFocus) {
-        textView.setTextAppearance(v.getContext(), R.style.Theme_QuickDic);
-      } else {
-        //textView.setTextAppearance(v.getContext(), android.R.style.TextAppearance_Medium);
-      }
-    }
-  };
-
-
   class Adapter extends BaseAdapter {
 
     @Override
     public int getCount() {
-      return dictionaries.size();
+      return quickDicConfig.dictionaryConfigs.size();
     }
 
     @Override
     public DictionaryConfig getItem(int position) {
-      return dictionaries.get(position);
+      return quickDicConfig.dictionaryConfigs.get(position);
     }
 
     @Override
@@ -172,16 +161,8 @@ public class DictionaryListActivity extends ListActivity {
 
       view.setText(dictionaryConfig.name);
       view.setTextSize(20);
-      view.setFocusable(true);
-      view.setOnFocusChangeListener(focusListener);
       tableLayout.addView(view);
 
-      final EditText view2 = new EditText(parent.getContext());
-      view2.setText(dictionaryConfig.name + "2");
-      view2.setFocusable(true);
-      view2.setOnFocusChangeListener(focusListener);
-      tableLayout.addView(view2);
-
       return tableLayout;
     }
     
diff --git a/src/com/hughes/android/dictionary/QuickDicConfig.java b/src/com/hughes/android/dictionary/QuickDicConfig.java
new file mode 100644 (file)
index 0000000..79f88ec
--- /dev/null
@@ -0,0 +1,17 @@
+package com.hughes.android.dictionary;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.List;
+
+public final class QuickDicConfig implements Serializable {
+  
+  private static final long serialVersionUID = 6711617368780900979L;
+  
+  final List<DictionaryConfig> dictionaryConfigs = new ArrayList<DictionaryConfig>();
+  
+  public QuickDicConfig() {
+    dictionaryConfigs.add(DictionaryConfig.defaultConfig());
+  }
+
+}
index aab0ea25acfb5e668b5f22b00a34c6f09ab4c8a3..cbe76fb716adcc359522bf80620c251307cd7ba0 100644 (file)
@@ -20,11 +20,11 @@ public class Dictionary implements RAFSerializable<Dictionary> {
   
   // persisted
   final int dictFileVersion;
-  final String dictInfo;
-  final List<PairEntry> pairEntries;
-  final List<TextEntry> textEntries;
-  final List<EntrySource> sources;
-  final List<Index> indices;
+  public final String dictInfo;
+  public final List<PairEntry> pairEntries;
+  public final List<TextEntry> textEntries;
+  public final List<EntrySource> sources;
+  public final List<Index> indices;
   
   public Dictionary(final String dictInfo) {
     this.dictFileVersion = 0;
index e2c2fee96e145fff7ec15caff0b71a17be031bd9..6e53cf24db1894df4e0daabd864d25e649649f82 100644 (file)
@@ -24,27 +24,30 @@ public final class Index implements RAFSerializable<Index> {
   
   final Dictionary dict;
   
-  final String shortName;
-  final String longName;
+  public final String shortName;
+  public final String longName;
   
   // persisted: tells how the entries are sorted.
-  final Language sortLanguage;
+  public final Language sortLanguage;
     
   // persisted
-  final List<IndexEntry> sortedIndexEntries;
+  public final List<IndexEntry> sortedIndexEntries;
 
   // One big list!
   // Various sub-types.
   // persisted
-  final List<RowBase> rows;
+  public final List<RowBase> rows;
+  
+  public final boolean swapPairEntries;
   
   // --------------------------------------------------------------------------
   
-  public Index(final Dictionary dict, final String shortName, final String longName, final Language sortLanguage) {
+  public Index(final Dictionary dict, final String shortName, final String longName, final Language sortLanguage, final boolean swapPairEntries) {
     this.dict = dict;
     this.shortName = shortName;
     this.longName = longName;
     this.sortLanguage = sortLanguage;
+    this.swapPairEntries = swapPairEntries;
     sortedIndexEntries = new ArrayList<IndexEntry>();
     rows = new ArrayList<RowBase>();
   }
@@ -55,6 +58,7 @@ public final class Index implements RAFSerializable<Index> {
     longName = raf.readUTF();
     final String languageCode = raf.readUTF();
     sortLanguage = Language.lookup(languageCode);
+    swapPairEntries = raf.readBoolean();
     if (sortLanguage == null) {
       throw new IOException("Unsupported language: " + languageCode);
     }
@@ -62,21 +66,21 @@ public final class Index implements RAFSerializable<Index> {
     rows = CachingList.create(UniformRAFList.create(raf, new RowBase.Serializer(this), raf.getFilePointer()), CACHE_SIZE);
   }
   
-  public void print(final PrintStream out) {
-    for (final RowBase row : rows) {
-      row.print(out);
-    }
-  }
-  
   @Override
   public void write(final RandomAccessFile raf) throws IOException {
     raf.writeUTF(shortName);
     raf.writeUTF(longName);
     raf.writeUTF(sortLanguage.getSymbol());
+    raf.writeBoolean(swapPairEntries);
     RAFList.write(raf, sortedIndexEntries, IndexEntry.SERIALIZER);
     UniformRAFList.write(raf, (Collection<RowBase>) rows, new RowBase.Serializer(this), 5);
   }
 
+  public void print(final PrintStream out) {
+    for (final RowBase row : rows) {
+      row.print(out);
+    }
+  }
   
   static final class IndexEntry implements RAFSerializable<Index.IndexEntry> {
     String token;
@@ -112,15 +116,9 @@ public final class Index implements RAFSerializable<Index> {
     public String toString() {
       return token + "@" + startRow;
     }
-}
-  
-
-  private TokenRow sortedIndexToToken(final int sortedIndex) {
-    final IndexEntry indexEntry = sortedIndexEntries.get(sortedIndex);
-    return (TokenRow) rows.get(indexEntry.startRow);
   }
-
-  public TokenRow find(String token, final AtomicBoolean interrupted) {
+  
+  public IndexEntry findInsertionPoint(String token, final AtomicBoolean interrupted) {
     token = sortLanguage.textNorm(token, true);
 
     int start = 0;
@@ -130,14 +128,14 @@ public final class Index implements RAFSerializable<Index> {
     while (start < end) {
       final int mid = (start + end) / 2;
       if (interrupted.get()) {
-        return sortedIndexToToken(mid);
+        return null;
       }
       final IndexEntry midEntry = sortedIndexEntries.get(mid);
 
       final int comp = sortCollator.compare(token, sortLanguage.textNorm(midEntry.token, true));
       if (comp == 0) {
-        final int result = windBack(token, mid, sortCollator, interrupted);
-        return sortedIndexToToken(result);
+        final int result = windBackCase(token, mid, sortCollator, interrupted);
+        return sortedIndexEntries.get(result);
       } else if (comp < 0) {
 //        Log.d("THAD", "Upper bound: " + midEntry);
         end = mid;
@@ -146,15 +144,46 @@ public final class Index implements RAFSerializable<Index> {
         start = mid + 1;
       }
     }
+
+    // If we search for a substring of a string that's in there, return that.
     int result = Math.min(start, sortedIndexEntries.size() - 1);
-    result = windBack(token, result, sortCollator, interrupted);
-    if (result > 0 && sortCollator.compare(sortLanguage.textNorm(sortedIndexEntries.get(result).token, true), token) > 0) {
-      result = windBack(sortLanguage.textNorm(sortedIndexEntries.get(result - 1).token, true), result, sortCollator, interrupted);
+    result = windBackCase(sortLanguage.textNorm(sortedIndexEntries.get(result).token, true), result, sortCollator, interrupted);
+    return sortedIndexEntries.get(result);
+  }
+  
+  public static final class SearchResult {
+    final IndexEntry insertionPoint;
+    final IndexEntry longestPrefix;
+    final String longestPrefixString;
+    
+    public SearchResult(IndexEntry insertionPoint, IndexEntry longestPrefix,
+        String longestPrefixString) {
+      this.insertionPoint = insertionPoint;
+      this.longestPrefix = longestPrefix;
+      this.longestPrefixString = longestPrefixString;
     }
-    return sortedIndexToToken(result);
   }
   
-  private final int windBack(final String token, int result, final Collator sortCollator, final AtomicBoolean interrupted) {
+  public SearchResult findLongestSubstring(String token, final AtomicBoolean interrupted) {
+    IndexEntry insertionPoint = null;
+    IndexEntry result = null;
+    while (!interrupted.get() && token.length() > 0) {
+      result = findInsertionPoint(token, interrupted);
+      if (result == null) {
+        return null;
+      }
+      if (insertionPoint == null) {
+        insertionPoint = result;
+      }
+      if (sortLanguage.textNorm(result.token, true).startsWith(sortLanguage.textNorm(token, true))) {
+        return new SearchResult(insertionPoint, result, token);
+      }
+      token = token.substring(0, token.length() - 1);      
+    }
+    return new SearchResult(insertionPoint, sortedIndexEntries.get(0), "");
+  }
+  
+  private final int windBackCase(final String token, int result, final Collator sortCollator, final AtomicBoolean interrupted) {
     while (result > 0 && sortCollator.compare(sortLanguage.textNorm(sortedIndexEntries.get(result - 1).token, true), token) >= 0) {
       --result;
       if (interrupted.get()) {
@@ -164,4 +193,5 @@ public final class Index implements RAFSerializable<Index> {
     return result;
   }
 
+
 }
\ No newline at end of file
index 1557c9bcaacf49f43f7e4ca41347ac0c3785100e..4f7c6a56f280fa55c47d0d7999d694c8f381ed51 100644 (file)
@@ -10,18 +10,21 @@ import com.hughes.util.raf.RAFSerializer;
 public class PairEntry extends Entry implements RAFSerializable<PairEntry> {
   
   public static final class Pair {
-    final String lang1;
-    final String lang2;
+    
+    public final String lang1;
+    public final String lang2;
+    
     public Pair(final String lang1, final String lang2) {
       this.lang1 = lang1;
       this.lang2 = lang2;
     }
+    
     public String toString() {
       return lang1 + " :: " + lang2;
     }
   }
   
-  final Pair[] pairs;
+  public final Pair[] pairs;
   
   public PairEntry(final Pair[] pairs) {
     this.pairs = pairs;
@@ -72,12 +75,6 @@ public class PairEntry extends Entry implements RAFSerializable<PairEntry> {
       return index.dict.pairEntries.get(referenceIndex);
     }
     
-    @Override
-    public Object draw(String searchText) {
-      // TODO Auto-generated method stub
-      return null;
-    }
-
     @Override
     public void print(PrintStream out) {
       final PairEntry pairEntry = getEntry();
index d62edf16a49ac550df3a7866c52962e124f19ee0..2d8bf21fee8636dad299fd331b72df030ef72309 100644 (file)
@@ -63,12 +63,8 @@ public abstract class RowBase extends IndexedObject {
     this.tokenRow = tokenRow;
   }
 
-
   public abstract void print(PrintStream out);
   
-  public abstract Object draw(final String searchText);
-
-
   // RowBase must manage "disk-based" polymorphism.  All other polymorphism is
   // dealt with in the normal manner.
   static class Serializer implements RAFListSerializer<RowBase> {
@@ -101,5 +97,4 @@ public abstract class RowBase extends IndexedObject {
     }
   }
 
-
 }
index 87d29d7c0c8bbac45854eadee749e88e68c8f87f..4aba121122fe0ea90e44903af7d793700d217c66 100644 (file)
@@ -43,12 +43,6 @@ public class TextEntry extends Entry implements RAFSerializable<TextEntry> {
       return index.dict.textEntries.get(referenceIndex);
     }
     
-    @Override
-    public Object draw(String searchText) {
-      // TODO Auto-generated method stub
-      return null;
-    }
-
     @Override
     public void print(PrintStream out) {
       out.println("  " + getEntry().text);
index 0488f0aa491390b52ec8801646cfddb8dd9f77d7..3cfce02caac5a8692081ca8b0dab2e398bb2c8c3 100644 (file)
@@ -32,12 +32,6 @@ public class TokenRow extends RowBase {
     return index.sortedIndexEntries.get(referenceIndex).token;
   }
 
-  @Override
-  public Object draw(String searchText) {
-    // TODO Auto-generated method stub
-    return null;
-  }
-
   @Override
   public void print(final PrintStream out) {
     out.println(getToken());
index 2d9d2ff9910dd484e2895d36c76aff426fc4db2b..cd5b5e3c27e351c558f856203401201cbb788b06 100644 (file)
@@ -16,27 +16,31 @@ public class PersistentObjectCache {
   private final File dir;
   private final Map<String, Object> objects = new LinkedHashMap<String, Object>();
   
-  public synchronized Object read(final String filename) {
-    Object object = (objects.get(filename));
-    if (object != null) {
-      return object;
-    }
-    Log.d(getClass().getSimpleName(), "Cache miss.");
-    final File src = new File(dir, filename);
-    if (!src.canRead()) {
-      Log.d(getClass().getSimpleName(), "File empty: " + src);
-      return null;
-    }
+  public synchronized <T> T read(final String filename, final Class<T> resultClass) {
     try {
-      final ObjectInputStream in = new ObjectInputStream(new FileInputStream(src));
-      object = in.readObject();
-      in.close();
-    } catch (Exception e) {
-      Log.e(getClass().getSimpleName(), "Deserialization failed: " + src, e);
+      Object object = (objects.get(filename));
+      if (object != null) {
+        return resultClass.cast(object);
+      }
+      Log.d(getClass().getSimpleName(), "Cache miss.");
+      final File src = new File(dir, filename);
+      if (!src.canRead()) {
+        Log.d(getClass().getSimpleName(), "File empty: " + src);
+        return null;
+      }
+      try {
+        final ObjectInputStream in = new ObjectInputStream(new FileInputStream(src));
+        object = in.readObject();
+        in.close();
+      } catch (Exception e) {
+        Log.e(getClass().getSimpleName(), "Deserialization failed: " + src, e);
+        return null;
+      }
+      objects.put(filename, object);
+      return resultClass.cast(object);
+    } catch (ClassCastException e) {
       return null;
     }
-    objects.put(filename, object);
-    return object;
   }
   
   public synchronized void write(final String filename, final Object object) {