From e226f45c26d043c359dfb783b75fa74e199770f0 Mon Sep 17 00:00:00 2001 From: Clam Date: Sat, 27 Jul 2013 18:52:20 +1000 Subject: [PATCH] Fixed some bugs and cleaned up codes * Fixed crash on backspacing from symbol (1 key) * Hopefully fixed weird crash trying to dismiss view * Fixed long press not working for SoftKeys --- AndroidManifest.xml | 4 +- res/values/strings.xml | 1 + .../android/traditionalt9/AbsSymDialog.java | 193 +++--- .../android/traditionalt9/AddWordAct.java | 28 +- .../android/traditionalt9/CandidateView.java | 395 +++++------ .../nyanya/android/traditionalt9/CharMap.java | 74 +- .../android/traditionalt9/DBException.java | 24 +- .../traditionalt9/InterfaceHandler.java | 96 +-- .../android/traditionalt9/SmileyDialog.java | 36 +- .../android/traditionalt9/SymbolDialog.java | 20 +- .../nyanya/android/traditionalt9/T9DB.java | 246 ++++--- .../android/traditionalt9/TraditionalT9.java | 653 +++++++++--------- .../traditionalt9/TraditionalT9Settings.java | 491 +++++++------ 13 files changed, 1169 insertions(+), 1092 deletions(-) diff --git a/AndroidManifest.xml b/AndroidManifest.xml index b25b1785..18d885a7 100644 --- a/AndroidManifest.xml +++ b/AndroidManifest.xml @@ -1,8 +1,8 @@ + android:versionCode="4" + android:versionName="git" > Add word OK Blank word not added. + Cannot add word with unmappable symbol. Word ( ) already in DB. Cancel diff --git a/src/org/nyanya/android/traditionalt9/AbsSymDialog.java b/src/org/nyanya/android/traditionalt9/AbsSymDialog.java index ff01b506..63d82fb4 100644 --- a/src/org/nyanya/android/traditionalt9/AbsSymDialog.java +++ b/src/org/nyanya/android/traditionalt9/AbsSymDialog.java @@ -8,80 +8,84 @@ import android.view.Window; import android.view.WindowManager; import android.widget.TextView; -public abstract class AbsSymDialog extends Dialog - implements View.OnClickListener { - +public abstract class AbsSymDialog extends Dialog implements + View.OnClickListener { + private TraditionalT9 parent; - private View mainview; - private int pagenum = 1; - private int pageoffset = (pagenum-1)*10; - - private int MAX_PAGE; - private String title; - private boolean started; - - private static final int[] buttons = { - R.id.text_keyone, R.id.text_keytwo, R.id.text_keythree, - R.id.text_keyfour, R.id.text_keyfive, R.id.text_keysix, - R.id.text_keyseven, R.id.text_keyeight, R.id.text_keynine, - R.id.text_keyzero }; - private static final int[] buttons2 = { R.id.text_keystar, R.id.text_keypound }; - + private View mainview; + private int pagenum = 1; + private int pageoffset = (pagenum - 1) * 10; + + private int MAX_PAGE; + private String title; + private boolean started; + + private static final int[] buttons = { + R.id.text_keyone, R.id.text_keytwo, + R.id.text_keythree, R.id.text_keyfour, R.id.text_keyfive, + R.id.text_keysix, R.id.text_keyseven, R.id.text_keyeight, + R.id.text_keynine, R.id.text_keyzero + }; + private static final int[] buttons2 = { + R.id.text_keystar, + R.id.text_keypound + }; + public AbsSymDialog(Context c, View mv) { - super(c); - parent = (TraditionalT9) c; - mainview = mv; - started = true; - setContentView(mv); - + super(c); + parent = (TraditionalT9) c; + mainview = mv; + started = true; + setContentView(mv); + View button; - for (int x = 0; x < buttons.length; x++){ + for (int x = 0; x < buttons.length; x++) { button = mv.findViewById(buttons[x]); button.setOnClickListener(this); } - for (int x = 0; x < buttons2.length; x++){ + for (int x = 0; x < buttons2.length; x++) { button = mv.findViewById(buttons2[x]); button.setOnClickListener(this); } MAX_PAGE = getMaxPage(); title = getTitleText(); - } - + } + @Override public void onClick(View v) { - //Log.d("SymbolPopup - onClick", "click happen: " + v); + // Log.d("SymbolPopup - onClick", "click happen: " + v); switch (v.getId()) { case R.id.text_keyone: - sendChar(pageoffset+0); + sendChar(pageoffset + 0); break; case R.id.text_keytwo: - sendChar(pageoffset+1); + sendChar(pageoffset + 1); break; case R.id.text_keythree: - sendChar(pageoffset+2); + sendChar(pageoffset + 2); break; case R.id.text_keyfour: - sendChar(pageoffset+3); + sendChar(pageoffset + 3); break; case R.id.text_keyfive: - sendChar(pageoffset+4); + sendChar(pageoffset + 4); break; case R.id.text_keysix: - sendChar(pageoffset+5); + sendChar(pageoffset + 5); break; case R.id.text_keyseven: - sendChar(pageoffset+6); + sendChar(pageoffset + 6); break; case R.id.text_keyeight: - sendChar(pageoffset+7); + sendChar(pageoffset + 7); break; case R.id.text_keynine: - sendChar(pageoffset+8); + sendChar(pageoffset + 8); break; case R.id.text_keyzero: - sendChar(pageoffset+9); + sendChar(pageoffset + 9); break; - + case R.id.text_keypound: pageChange(1); break; @@ -90,65 +94,68 @@ public abstract class AbsSymDialog extends Dialog break; } } - + protected abstract String getSymbol(int index); protected abstract String getTitleText(); protected abstract int getSymbolSize(); protected abstract int getMaxPage(); - + private void sendChar(int index) { - //Log.d("SymbolDialog - sendChar", "Sending index: " + index); - + // Log.d("SymbolDialog - sendChar", "Sending index: " + index); + if (index < getSymbolSize()) { parent.onText(getSymbol(index)); - //then close + // then close pagenum = 1; - pageoffset = (pagenum-1)*10; + pageoffset = (pagenum - 1) * 10; this.dismiss(); } } - + private void pageChange(int amt) { pagenum = pagenum + amt; - if (pagenum > MAX_PAGE ) { + if (pagenum > MAX_PAGE) { pagenum = 1; } else if (pagenum < 1) { pagenum = MAX_PAGE; } - pageoffset = (pagenum-1)*10; + pageoffset = (pagenum - 1) * 10; updateButtons(); } - + private void updateButtons() { // set page number text - setTitle("Insert "+ title + "\t\tPage " + pagenum + "/" + MAX_PAGE); + setTitle("Insert " + title + "\t\tPage " + pagenum + "/" + MAX_PAGE); // update button labels int symbx = pageoffset; int stop = symbx + 9; int nomore = stop; int symsize = getSymbolSize(); - if (nomore >= symsize-1) { - nomore = symsize-1; + if (nomore >= symsize - 1) { + nomore = symsize - 1; } for (int buttx = 0; symbx <= stop; symbx++) { - //Log.d("SymbolDialog - updateButtons", "buttx: " + buttx + " symbx: " + symbx); + // Log.d("SymbolDialog - updateButtons", "buttx: " + buttx + + // " symbx: " + symbx); if (symbx > nomore) { - ((TextView)mainview.findViewById(buttons[buttx])).setText(""); + ((TextView) mainview.findViewById(buttons[buttx])).setText(""); } else { - ((TextView)mainview.findViewById(buttons[buttx])).setText(String.valueOf(getSymbol(symbx))); + ((TextView) mainview.findViewById(buttons[buttx])) + .setText(String.valueOf(getSymbol(symbx))); } buttx++; } } - - @Override public boolean onKeyDown(int keyCode, KeyEvent event){ + + @Override + public boolean onKeyDown(int keyCode, KeyEvent event) { if (event.getRepeatCount() != 0) { return true; } if (started) { started = false; } - //TODO: remove emulator special keys + // TODO: remove emulator special keys switch (keyCode) { case 75: keyCode = KeyEvent.KEYCODE_POUND; @@ -156,10 +163,10 @@ public abstract class AbsSymDialog extends Dialog case 74: keyCode = KeyEvent.KEYCODE_STAR; break; - } - //Log.d("AbsSymDialog.onKeyDown", "bootan pres: " + keyCode); + } + // Log.d("AbsSymDialog.onKeyDown", "bootan pres: " + keyCode); switch (keyCode) { - + case KeyEvent.KEYCODE_0: case KeyEvent.KEYCODE_1: case KeyEvent.KEYCODE_2: @@ -171,20 +178,21 @@ public abstract class AbsSymDialog extends Dialog case KeyEvent.KEYCODE_8: case KeyEvent.KEYCODE_9: case KeyEvent.KEYCODE_POUND: - case KeyEvent.KEYCODE_STAR: + case KeyEvent.KEYCODE_STAR: event.startTracking(); return true; } return super.onKeyDown(keyCode, event); } - @Override public boolean onKeyUp(int keyCode, KeyEvent event) { - //Log.d("AbsSymDialog.onKeyUp", "Key: " + keyCode); + @Override + public boolean onKeyUp(int keyCode, KeyEvent event) { + // Log.d("AbsSymDialog.onKeyUp", "Key: " + keyCode); if (started) { started = false; return true; } - //TODO: remove emulator special keys + // TODO: remove emulator special keys switch (keyCode) { case 75: keyCode = KeyEvent.KEYCODE_POUND; @@ -194,7 +202,7 @@ public abstract class AbsSymDialog extends Dialog break; } switch (keyCode) { - //pass-through + // pass-through case KeyEvent.KEYCODE_0: case KeyEvent.KEYCODE_1: case KeyEvent.KEYCODE_2: @@ -210,47 +218,48 @@ public abstract class AbsSymDialog extends Dialog onKey(keyCode); return true; default: - //KeyCharacterMap.load(KeyCharacterMap.BUILT_IN_KEYBOARD).getNumber(keyCode) - //Log.w("onKeyUp", "Unhandled Key: " + keyCode + "(" + event.toString() + ")"); + // KeyCharacterMap.load(KeyCharacterMap.BUILT_IN_KEYBOARD).getNumber(keyCode) + // Log.w("onKeyUp", "Unhandled Key: " + keyCode + "(" + + // event.toString() + ")"); } return super.onKeyUp(keyCode, event); } - + private void onKey(int keyCode) { - //Log.d("OnKey", "pri: " + keyCode); - //Log.d("onKey", "START Cm: " + mCapsMode); - //HANDLE SPECIAL KEYS + // Log.d("OnKey", "pri: " + keyCode); + // Log.d("onKey", "START Cm: " + mCapsMode); + // HANDLE SPECIAL KEYS switch (keyCode) { case KeyEvent.KEYCODE_1: - sendChar(pageoffset+0); + sendChar(pageoffset + 0); break; case KeyEvent.KEYCODE_2: - sendChar(pageoffset+1); + sendChar(pageoffset + 1); break; case KeyEvent.KEYCODE_3: - sendChar(pageoffset+2); + sendChar(pageoffset + 2); break; case KeyEvent.KEYCODE_4: - sendChar(pageoffset+3); + sendChar(pageoffset + 3); break; case KeyEvent.KEYCODE_5: - sendChar(pageoffset+4); + sendChar(pageoffset + 4); break; case KeyEvent.KEYCODE_6: - sendChar(pageoffset+5); + sendChar(pageoffset + 5); break; case KeyEvent.KEYCODE_7: - sendChar(pageoffset+6); + sendChar(pageoffset + 6); break; case KeyEvent.KEYCODE_8: - sendChar(pageoffset+7); + sendChar(pageoffset + 7); break; case KeyEvent.KEYCODE_9: - sendChar(pageoffset+8); + sendChar(pageoffset + 8); break; case KeyEvent.KEYCODE_0: - sendChar(pageoffset+9); - break; + sendChar(pageoffset + 9); + break; case KeyEvent.KEYCODE_STAR: pageChange(-1); break; @@ -259,17 +268,17 @@ public abstract class AbsSymDialog extends Dialog break; } } - + protected void doShow(View v) { - // based on http://stackoverflow.com/a/13962770 + // based on http://stackoverflow.com/a/13962770 started = true; Window win = getWindow(); WindowManager.LayoutParams lp = win.getAttributes(); - lp.token = v.getWindowToken(); - lp.type = WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG; - win.setAttributes(lp); - win.addFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM); - updateButtons(); - show(); + lp.token = v.getWindowToken(); + lp.type = WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG; + win.setAttributes(lp); + win.addFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM); + updateButtons(); + show(); } } diff --git a/src/org/nyanya/android/traditionalt9/AddWordAct.java b/src/org/nyanya/android/traditionalt9/AddWordAct.java index 1b6f626a..405de26b 100644 --- a/src/org/nyanya/android/traditionalt9/AddWordAct.java +++ b/src/org/nyanya/android/traditionalt9/AddWordAct.java @@ -2,6 +2,7 @@ package org.nyanya.android.traditionalt9; import android.os.Bundle; import android.app.Activity; +import android.util.Log; import android.view.Menu; import android.view.View; import android.widget.EditText; @@ -9,34 +10,39 @@ import android.widget.EditText; public class AddWordAct extends Activity { View main; - + @Override protected void onCreate(Bundle savedData) { super.onCreate(savedData); View v = getLayoutInflater().inflate(R.layout.addwordview, null); - EditText et = (EditText)v.findViewById(R.id.add_word_text); + EditText et = (EditText) v.findViewById(R.id.add_word_text); String word = getIntent().getStringExtra("org.nyanya.android.traditionalt9.word"); - //Log.d("AddWord", "data.get: " + word); + // Log.d("AddWord", "data.get: " + word); et.setText(word); et.setSelection(word.length()); setContentView(v); main = v; } - + public void addWordButton(View v) { EditText et = (EditText) main.findViewById(R.id.add_word_text); - //Log.d("AddWordAct", "adding word: " + et.getText()); - TraditionalT9.ghettoaccess.doAddWord(et.getText().toString()); + // Log.d("AddWordAct", "adding word: " + et.getText()); + if (TraditionalT9.ghettoaccess == null) { + Log.e("AddWordAct.addWordbutton", "ghettoaccess is null? Oh no."); + } else { + TraditionalT9.ghettoaccess.doAddWord(et.getText().toString()); + } this.finish(); } - + public void cancelButton(View v) { - //Log.d("AddWordAct", "Cancelled..."); - //TraditionalT9.ghettoaccess.addCancel(); + // Log.d("AddWordAct", "Cancelled..."); + // TraditionalT9.ghettoaccess.addCancel(); this.finish(); } - - @Override public void onStop() { + + @Override + public void onStop() { TraditionalT9.ghettoaccess.addCancel(); super.onStop(); } diff --git a/src/org/nyanya/android/traditionalt9/CandidateView.java b/src/org/nyanya/android/traditionalt9/CandidateView.java index a46efbca..1d547943 100644 --- a/src/org/nyanya/android/traditionalt9/CandidateView.java +++ b/src/org/nyanya/android/traditionalt9/CandidateView.java @@ -4,7 +4,6 @@ import java.util.ArrayList; import java.util.List; import org.nyanya.android.traditionalt9.R; -import org.nyanya.android.traditionalt9.TraditionalT9; import android.content.Context; import android.content.res.Resources; @@ -16,223 +15,211 @@ import android.view.View; public class CandidateView extends View { - //private TraditionalT9 mService; - private List mSuggestions; - protected int mSelectedIndex; + // private TraditionalT9 mService; + private List mSuggestions; + protected int mSelectedIndex; - private Drawable mSelectionHighlight; - - private Rect mBgPadding; + private Drawable mSelectionHighlight; - private static final int MAX_SUGGESTIONS = 32; - private static final int SCROLL_PIXELS = 20; - - private int[] mWordWidth = new int[MAX_SUGGESTIONS]; - private int[] mWordX = new int[MAX_SUGGESTIONS]; + private Rect mBgPadding; - private static final int X_GAP = 10; - - private static final List EMPTY_LIST = new ArrayList(); + private static final int MAX_SUGGESTIONS = 32; + private static final int SCROLL_PIXELS = 20; - private int mColorNormal; - private int mColorRecommended; - private int mColorOther; - private int mVerticalPadding; - private Paint mPaint; - private int mTargetScrollX; - - private int mTotalWidth; - - Rect mPadding; + private int[] mWordWidth = new int[MAX_SUGGESTIONS]; + private int[] mWordX = new int[MAX_SUGGESTIONS]; - /** - * Construct a CandidateView for showing suggested words for completion. - * @param context - * @param attrs - */ - public CandidateView(Context context) { - super(context); - mSelectionHighlight = context.getResources().getDrawable( - android.R.drawable.list_selector_background); - mSelectionHighlight.setState(new int[] { - android.R.attr.state_enabled, - android.R.attr.state_focused, - android.R.attr.state_window_focused, - android.R.attr.state_pressed - }); + private static final int X_GAP = 10; - Resources r = context.getResources(); - - setBackgroundColor(r.getColor(R.color.candidate_background)); - - mColorNormal = r.getColor(R.color.candidate_normal); - mColorRecommended = r.getColor(R.color.candidate_recommended); - mColorOther = r.getColor(R.color.candidate_other); - mVerticalPadding = r.getDimensionPixelSize(R.dimen.candidate_vertical_padding); - - mPaint = new Paint(); - mPaint.setColor(mColorNormal); - mPaint.setAntiAlias(true); - mPaint.setTextSize(r.getDimensionPixelSize(R.dimen.candidate_font_height)); - mPaint.setStrokeWidth(0); - - mPadding = new Rect(); - - setHorizontalFadingEdgeEnabled(true); - setWillNotDraw(false); - setHorizontalScrollBarEnabled(false); - setVerticalScrollBarEnabled(false); - } - - /** - * A connection back to the service to communicate with the text field - * @param listener - */ - public void setService(TraditionalT9 listener) { - //mService = listener; - } - - @Override - public int computeHorizontalScrollRange() { - return mTotalWidth; - } + private static final List EMPTY_LIST = new ArrayList(); - @Override - protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { - int measuredWidth = resolveSize(50, widthMeasureSpec); - - // Get the desired height of the icon menu view (last row of items does - // not have a divider below) - - mSelectionHighlight.getPadding(mPadding); - final int desiredHeight = ((int)mPaint.getTextSize()) + mVerticalPadding - + mPadding.top + mPadding.bottom; - - // Maximum possible width and desired height - setMeasuredDimension(measuredWidth, - resolveSize(desiredHeight, heightMeasureSpec)); - } + private int mColorNormal; + private int mColorRecommended; + private int mColorOther; + private int mVerticalPadding; + private Paint mPaint; + private int mTargetScrollX; - /** - * If the canvas is null, then only touch calculations are performed to pick the target - * candidate. - */ - @Override - protected void onDraw(Canvas canvas) { - super.onDraw(canvas); - - mTotalWidth = 0; - if (mSuggestions == null) return; - - if (mBgPadding == null) { - mBgPadding = new Rect(0, 0, 0, 0); - if (getBackground() != null) { - getBackground().getPadding(mBgPadding); - } - } - int x = 0; - final int count = mSuggestions.size(); - final int height = getHeight(); - final Rect bgPadding = mBgPadding; - final Paint paint = mPaint; - final int y = (int) (((height - mPaint.getTextSize()) / 2) - mPaint.ascent()); + private int mTotalWidth; - for (int i = 0; i < count; i++) { - String suggestion = mSuggestions.get(i); - float textWidth = paint.measureText(suggestion); - final int wordWidth = (int) textWidth + X_GAP * 2; + Rect mPadding; - mWordX[i] = x; - mWordWidth[i] = wordWidth; - paint.setColor(mColorNormal); - //if (touchX + scrollX >= x && touchX + scrollX < x + wordWidth && !scrolled) { - if (i == mSelectedIndex) { - canvas.translate(x, 0); - mSelectionHighlight.setBounds(0, bgPadding.top, wordWidth, height); - mSelectionHighlight.draw(canvas); - canvas.translate(-x, 0); - paint.setFakeBoldText(true); - paint.setColor(mColorRecommended); - } - else { - paint.setColor(mColorOther); - } - - canvas.drawText(suggestion, x + X_GAP, y, paint); - paint.setColor(mColorOther); - canvas.drawLine(x + wordWidth + 0.5f, bgPadding.top, - x + wordWidth + 0.5f, height + 1, paint); - paint.setFakeBoldText(false); + /** + * Construct a CandidateView for showing suggested words for completion. + * + * @param context + * @param attrs + */ + public CandidateView(Context context) { + super(context); + mSelectionHighlight = context.getResources().getDrawable( + android.R.drawable.list_selector_background); + mSelectionHighlight.setState(new int[] { + android.R.attr.state_enabled, android.R.attr.state_focused, + android.R.attr.state_window_focused, android.R.attr.state_pressed }); - x += wordWidth; - } - mTotalWidth = x; - if (mTargetScrollX != getScrollX()) { - scrollToTarget(); - } - } - - private void scrollToTarget() { - int sx = getScrollX(); - if (mTargetScrollX > sx) { - sx += SCROLL_PIXELS; - if (sx >= mTargetScrollX) { - sx = mTargetScrollX; - requestLayout(); - } - } else { - sx -= SCROLL_PIXELS; - if (sx <= mTargetScrollX) { - sx = mTargetScrollX; - requestLayout(); - } - } - scrollTo(sx, getScrollY()); - invalidate(); - } - - public void setSuggestions(List suggestions, int initialSel) { - clear(); - if (suggestions != null) { - mSuggestions = suggestions; - mSelectedIndex = initialSel; - } - scrollTo(0, 0); - mTargetScrollX = 0; - // Compute the total width - //onDraw(null); - invalidate(); - requestLayout(); - } + Resources r = context.getResources(); - public void clear() { - mSuggestions = EMPTY_LIST; - mSelectedIndex = -1; - invalidate(); - } - - - protected void scrollSuggestion(int increment) { - if (mSuggestions != null && mSuggestions.size() > 1) { - mSelectedIndex = mSelectedIndex + increment; - if (mSelectedIndex == mSuggestions.size()) { - mSelectedIndex = 0; - } else if (mSelectedIndex < 0) { - mSelectedIndex = mSuggestions.size()-1; - } - - int fullsize = getWidth(); - int halfsize = fullsize/2; - mTargetScrollX = mWordX[mSelectedIndex] + (mWordWidth[mSelectedIndex]/2) - halfsize; + setBackgroundColor(r.getColor(R.color.candidate_background)); + + mColorNormal = r.getColor(R.color.candidate_normal); + mColorRecommended = r.getColor(R.color.candidate_recommended); + mColorOther = r.getColor(R.color.candidate_other); + mVerticalPadding = r.getDimensionPixelSize(R.dimen.candidate_vertical_padding); + + mPaint = new Paint(); + mPaint.setColor(mColorNormal); + mPaint.setAntiAlias(true); + mPaint.setTextSize(r.getDimensionPixelSize(R.dimen.candidate_font_height)); + mPaint.setStrokeWidth(0); + + mPadding = new Rect(); + + setHorizontalFadingEdgeEnabled(true); + setWillNotDraw(false); + setHorizontalScrollBarEnabled(false); + setVerticalScrollBarEnabled(false); + } + + @Override + public int computeHorizontalScrollRange() { + return mTotalWidth; + } + + @Override + protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { + int measuredWidth = resolveSize(50, widthMeasureSpec); + + // Get the desired height of the icon menu view (last row of items does + // not have a divider below) + + mSelectionHighlight.getPadding(mPadding); + final int desiredHeight = ((int) mPaint.getTextSize()) + mVerticalPadding + mPadding.top + + mPadding.bottom; + + // Maximum possible width and desired height + setMeasuredDimension(measuredWidth, resolveSize(desiredHeight, heightMeasureSpec)); + } + + /** + * If the canvas is null, then only touch calculations are performed to pick + * the target candidate. + */ + @Override + protected void onDraw(Canvas canvas) { + super.onDraw(canvas); + + mTotalWidth = 0; + if (mSuggestions == null) + return; + + if (mBgPadding == null) { + mBgPadding = new Rect(0, 0, 0, 0); + if (getBackground() != null) { + getBackground().getPadding(mBgPadding); + } + } + int x = 0; + final int count = mSuggestions.size(); + final int height = getHeight(); + final Rect bgPadding = mBgPadding; + final Paint paint = mPaint; + final int y = (int) (((height - mPaint.getTextSize()) / 2) - mPaint.ascent()); + + for (int i = 0; i < count; i++) { + String suggestion = mSuggestions.get(i); + float textWidth = paint.measureText(suggestion); + final int wordWidth = (int) textWidth + X_GAP * 2; + + mWordX[i] = x; + mWordWidth[i] = wordWidth; + paint.setColor(mColorNormal); + // if (touchX + scrollX >= x && touchX + scrollX < x + wordWidth && + // !scrolled) { + if (i == mSelectedIndex) { + canvas.translate(x, 0); + mSelectionHighlight.setBounds(0, bgPadding.top, wordWidth, height); + mSelectionHighlight.draw(canvas); + canvas.translate(-x, 0); + paint.setFakeBoldText(true); + paint.setColor(mColorRecommended); + } else { + paint.setColor(mColorOther); + } + + canvas.drawText(suggestion, x + X_GAP, y, paint); + paint.setColor(mColorOther); + canvas.drawLine(x + wordWidth + 0.5f, bgPadding.top, x + wordWidth + 0.5f, height + 1, + paint); + paint.setFakeBoldText(false); + + x += wordWidth; + } + mTotalWidth = x; + if (mTargetScrollX != getScrollX()) { + scrollToTarget(); + } + } + + private void scrollToTarget() { + int sx = getScrollX(); + if (mTargetScrollX > sx) { + sx += SCROLL_PIXELS; + if (sx >= mTargetScrollX) { + sx = mTargetScrollX; + requestLayout(); + } + } else { + sx -= SCROLL_PIXELS; + if (sx <= mTargetScrollX) { + sx = mTargetScrollX; + requestLayout(); + } + } + scrollTo(sx, getScrollY()); + invalidate(); + } + + public void setSuggestions(List suggestions, int initialSel) { + clear(); + if (suggestions != null) { + mSuggestions = suggestions; + mSelectedIndex = initialSel; + } + scrollTo(0, 0); + mTargetScrollX = 0; + // Compute the total width + // onDraw(null); + invalidate(); + requestLayout(); + } + + public void clear() { + mSuggestions = EMPTY_LIST; + mSelectedIndex = -1; + invalidate(); + } + + protected void scrollSuggestion(int increment) { + if (mSuggestions != null && mSuggestions.size() > 1) { + mSelectedIndex = mSelectedIndex + increment; + if (mSelectedIndex == mSuggestions.size()) { + mSelectedIndex = 0; + } else if (mSelectedIndex < 0) { + mSelectedIndex = mSuggestions.size() - 1; + } + + int fullsize = getWidth(); + int halfsize = fullsize / 2; + mTargetScrollX = mWordX[mSelectedIndex] + (mWordWidth[mSelectedIndex] / 2) - halfsize; if (mTargetScrollX < 0) { mTargetScrollX = 0; - } else if (mTargetScrollX > (mTotalWidth - fullsize) ) { + } else if (mTargetScrollX > (mTotalWidth - fullsize)) { mTargetScrollX = mTotalWidth - fullsize; } - - invalidate(); - } - } - -} + invalidate(); + } + } + +} diff --git a/src/org/nyanya/android/traditionalt9/CharMap.java b/src/org/nyanya/android/traditionalt9/CharMap.java index 1fc18909..13c78fe9 100644 --- a/src/org/nyanya/android/traditionalt9/CharMap.java +++ b/src/org/nyanya/android/traditionalt9/CharMap.java @@ -8,13 +8,18 @@ import java.util.Map; import android.util.Log; public class CharMap { - protected static final Map CHARTABLE; + protected static final Map CHARTABLE; static { Map aMap = new HashMap(); aMap.put('.', 1); aMap.put(',', 1); aMap.put('!', 1); aMap.put('?', 1); aMap.put('-', 1); aMap.put('"', 1); aMap.put('\'', 1); aMap.put('@', 1); aMap.put('#', 1); aMap.put('$', 1); aMap.put('%', 1); aMap.put('&', 1); aMap.put('*', 1); aMap.put('(', 1); aMap.put(')', 1); aMap.put('1', 1); + aMap.put(':', 1); aMap.put(';', 1); aMap.put('/', 1); aMap.put('\\', 1); + aMap.put('+', 1); aMap.put('=', 1); aMap.put('<', 1); aMap.put('>', 1); + aMap.put('[', 1); aMap.put(']', 1); aMap.put('{', 1); aMap.put('}', 1); + aMap.put('^', 1); aMap.put('|', 1); aMap.put('_', 1); aMap.put('~', 1); + aMap.put('`', 1); aMap.put('a', 2); aMap.put('\u00e1', 2); aMap.put('\u00e4', 2); aMap.put('\u00e2', 2); aMap.put('\u00e0', 2); aMap.put('\u00e5', 2); aMap.put('b', 2); aMap.put('c', 2); aMap.put('\u00e7', 2); @@ -35,46 +40,45 @@ public class CharMap { aMap.put('9', 9); aMap.put('+', 0); aMap.put('0', 0); CHARTABLE = Collections.unmodifiableMap(aMap); } - protected static final char[][] T9TABLE = { - {'0', '+'}, {'.', ',', '!', '?', '-', '"', '\'', '@', '#', '$', '%', '&', '*', '(', ')', '1'}, - {'a', 'b', 'c', 'A', 'B', 'C', '2'}, {'d', 'e', 'f', 'D', 'E', 'F', '3'}, - {'g', 'h', 'i', 'G', 'H', 'I', '4'}, {'j', 'k', 'l', 'J', 'K', 'L', '5'}, - {'m', 'n', 'o', 'M', 'N', 'O', '6'}, {'p', 'q', 'r', 's', 'P', 'Q', 'R', 'S', '7'}, - {'t', 'u', 'v', 'T', 'U', 'V', '8'}, {'w', 'x', 'y', 'z', 'W', 'X', 'Y', 'Z', '9'}, - {' ', '\n'} - }; - - protected static final int[] T9CAPSTART = { - 0, 0, 3, 3, 3, 3, 3, 4, 3, 4, 0 - }; - - protected static int[] getSequence(String word){ + protected static final char[][] T9TABLE = { { '0', '+' }, + { '.', ',', '!', '?', '-', '"', '\'', '@', '#', '$', '%', '&', '*', '(', ')', '1' }, + { 'a', 'b', 'c', 'A', 'B', 'C', '2' }, { 'd', 'e', 'f', 'D', 'E', 'F', '3' }, + { 'g', 'h', 'i', 'G', 'H', 'I', '4' }, { 'j', 'k', 'l', 'J', 'K', 'L', '5' }, + { 'm', 'n', 'o', 'M', 'N', 'O', '6' }, { 'p', 'q', 'r', 's', 'P', 'Q', 'R', 'S', '7' }, + { 't', 'u', 'v', 'T', 'U', 'V', '8' }, { 'w', 'x', 'y', 'z', 'W', 'X', 'Y', 'Z', '9' }, + { ' ', '\n' } }; + + protected static final int[] T9CAPSTART = { 0, 0, 3, 3, 3, 3, 3, 4, 3, 4, 0 }; + + protected static int[] getSequence(String word) { int[] intseq = new int[word.length()]; String tword = word.toLowerCase(Locale.ENGLISH); - for (int i = 0; i < word.length(); i++){ + for (int i = 0; i < word.length(); i++) { char c = tword.charAt(i); - Integer z = CharMap.CHARTABLE.get(c); - if (z == null){ - Log.e("getSequence", "ERROR: "+ (int)c + " NOT FOUND (" + Integer.toHexString((int)c) + ")"); - throw new NullPointerException(); - } - intseq[i] = z; + Integer z = CharMap.CHARTABLE.get(c); + if (z == null) { + Log.e("getSequence", + "ERROR: " + (int) c + " NOT FOUND (" + Integer.toHexString((int) c) + ")"); + throw new NullPointerException(); + } + intseq[i] = z; } return intseq; } - - protected static String getStringSequence(String word){ - StringBuilder seq = new StringBuilder(); - String tword = word.toLowerCase(Locale.ENGLISH); - for (int i = 0; i < word.length(); i++){ + + protected static String getStringSequence(String word) { + StringBuilder seq = new StringBuilder(); + String tword = word.toLowerCase(Locale.ENGLISH); + for (int i = 0; i < word.length(); i++) { char c = tword.charAt(i); - Integer z = CharMap.CHARTABLE.get(c); - if (z == null){ - Log.e("getStringSequence", "ERROR: "+ (int)c + " NOT FOUND (" + Integer.toHexString((int)c) + ")"); - throw new NullPointerException(); - } - seq.append(z.toString()); + Integer z = CharMap.CHARTABLE.get(c); + if (z == null) { + Log.e("getStringSequence", + "ERROR: " + (int) c + " NOT FOUND (" + Integer.toHexString((int) c) + ")"); + throw new NullPointerException(); + } + seq.append(z.toString()); } - return seq.toString(); - } + return seq.toString(); + } } diff --git a/src/org/nyanya/android/traditionalt9/DBException.java b/src/org/nyanya/android/traditionalt9/DBException.java index abee69c8..cdae4274 100644 --- a/src/org/nyanya/android/traditionalt9/DBException.java +++ b/src/org/nyanya/android/traditionalt9/DBException.java @@ -2,20 +2,20 @@ package org.nyanya.android.traditionalt9; public class DBException extends Exception { private static final long serialVersionUID = 376752656441823823L; - - public DBException() { - super(); + + public DBException() { + super(); } - - public DBException(String message) { - super(message); + + public DBException(String message) { + super(message); } - - public DBException(String message, Throwable cause) { - super(message, cause); + + public DBException(String message, Throwable cause) { + super(message, cause); } - - public DBException(Throwable cause) { - super(cause); + + public DBException(Throwable cause) { + super(cause); } } diff --git a/src/org/nyanya/android/traditionalt9/InterfaceHandler.java b/src/org/nyanya/android/traditionalt9/InterfaceHandler.java index 32e4415d..6cf7d7c8 100644 --- a/src/org/nyanya/android/traditionalt9/InterfaceHandler.java +++ b/src/org/nyanya/android/traditionalt9/InterfaceHandler.java @@ -14,27 +14,27 @@ public class InterfaceHandler implements View.OnClickListener, View.OnLongClickL private static final int[] buttons = { R.id.main_left, R.id.main_right, R.id.main_mid }; private TraditionalT9 parent; private View mainview; - + public InterfaceHandler(View mainview, TraditionalT9 iparent) { this.parent = iparent; changeView(mainview); } - + protected View getMainview() { return mainview; } - + protected void clearParent() { - ViewGroup vg = ((ViewGroup)mainview.getParent()); + ViewGroup vg = ((ViewGroup) mainview.getParent()); if (vg != null) { vg.removeView(mainview); } } - - protected void changeView(View v){ + + protected void changeView(View v) { this.mainview = v; View button; - for (int x = 0; x < buttons.length; x++){ + for (int x = 0; x < buttons.length; x++) { button = v.findViewById(buttons[x]); button.setOnClickListener(this); if (!parent.mAddingWord) { @@ -42,9 +42,10 @@ public class InterfaceHandler implements View.OnClickListener, View.OnLongClickL } } } - protected void setPressed(int keyCode, boolean pressed){ + + protected void setPressed(int keyCode, boolean pressed) { int id = 0; - switch(keyCode) { + switch (keyCode) { case KeyEvent.KEYCODE_SOFT_LEFT: id = R.id.main_left; break; @@ -59,51 +60,56 @@ public class InterfaceHandler implements View.OnClickListener, View.OnLongClickL ((View) mainview.findViewById(id)).setPressed(pressed); } } - - protected void showNotFound(boolean notfound){ + + protected void showNotFound(boolean notfound) { if (notfound) { - ((TextView) mainview.findViewById(R.id.left_hold_upper)).setText(R.string.main_left_notfound); - ((TextView) mainview.findViewById(R.id.left_hold_lower)).setText(R.string.main_left_insert); + ((TextView) mainview.findViewById(R.id.left_hold_upper)) + .setText(R.string.main_left_notfound); + ((TextView) mainview.findViewById(R.id.left_hold_lower)) + .setText(R.string.main_left_insert); } else { - ((TextView) mainview.findViewById(R.id.left_hold_upper)).setText(R.string.main_left_insert); - ((TextView) mainview.findViewById(R.id.left_hold_lower)).setText(R.string.main_left_addword); + ((TextView) mainview.findViewById(R.id.left_hold_upper)) + .setText(R.string.main_left_insert); + ((TextView) mainview.findViewById(R.id.left_hold_lower)) + .setText(R.string.main_left_addword); } } - + protected void emulateMiddleButton() { ((Button) mainview.findViewById(R.id.main_mid)).performClick(); } - - protected void midButtonUpdate(boolean composing){ + + protected void midButtonUpdate(boolean composing) { if (composing) { ((Button) mainview.findViewById(R.id.main_mid)).setText(R.string.main_mid_commit); } else { ((Button) mainview.findViewById(R.id.main_mid)).setText(R.string.main_mid); } } - - @Override public void onClick(View v) { + + @Override + public void onClick(View v) { switch (v.getId()) { - case R.id.main_left: - if (parent.mAddingWord) { + case R.id.main_left: + if (parent.mAddingWord) { + parent.showSymbolPage(); + } else { + if (parent.mWordFound) { parent.showSymbolPage(); } else { - if (parent.mWordFound) { - parent.showSymbolPage(); - } else { - parent.showAddWord(); - } + parent.showAddWord(); } - break; - case R.id.main_mid: - parent.handleMidButton(); - break; - case R.id.main_right: - parent.nextKeyMode(); - break; + } + break; + case R.id.main_mid: + parent.handleMidButton(); + break; + case R.id.main_right: + parent.nextKeyMode(); + break; } } - + protected void showHold(boolean show) { ViewSwitcher vs = (ViewSwitcher) mainview.findViewById(R.id.main_left); if (show) { @@ -113,16 +119,18 @@ public class InterfaceHandler implements View.OnClickListener, View.OnLongClickL } } - @Override public boolean onLongClick(View v) { + @Override + public boolean onLongClick(View v) { switch (v.getId()) { - case R.id.main_left: - parent.showAddWord(); - break; - case R.id.main_right: - ((InputMethodManager) parent.getSystemService (Context.INPUT_METHOD_SERVICE)).showInputMethodPicker(); - break; - default: - return false; + case R.id.main_left: + parent.showAddWord(); + break; + case R.id.main_right: + ((InputMethodManager) parent.getSystemService(Context.INPUT_METHOD_SERVICE)) + .showInputMethodPicker(); + break; + default: + return false; } return true; } diff --git a/src/org/nyanya/android/traditionalt9/SmileyDialog.java b/src/org/nyanya/android/traditionalt9/SmileyDialog.java index dcceb467..8eeebf00 100644 --- a/src/org/nyanya/android/traditionalt9/SmileyDialog.java +++ b/src/org/nyanya/android/traditionalt9/SmileyDialog.java @@ -4,26 +4,22 @@ import android.content.Context; import android.view.View; public class SmileyDialog extends AbsSymDialog { - - private static final String[] symbols = { - //lol wiki http://en.wikipedia.org/wiki/List_of_emoticons - ":-)", ":)", ":o)", ":]", ":3", ":c)", ":>", "=]", "=)", ":}", - ":-D", ":D", "8-D", "8D", "X-D", "XD", "=-D", "=D", "B^D", - ">:[", ":-(", ":(", ":c", ":-<", ":<", ":-[", ":[", ":{", - ":'-(", ":'(", ":'-)", ":')", ":@", "D:<", "D:", "D8", "D;", "D=", "DX", - "v.v", "D-':", ">:O", ":-O", ":O", ":O", "o_O", "o_0", "o.O", "8-0", - ":*", ";-)", ";)", ";-]", ";]", ";D", - ">:P", ":-P", ":P", "XP", "xp", ":-p", ":p", "=p", ":-b", ":b", - ">:\\", ">:/", ":-/", ":-.", ":/", ":\\", "=/", "=\\", ":L", "=L", ":S", ">.<", - ":|", ":-|", ":$", ":-X", ":X", ":-#", ":#", "O:-)", "0:-3", "0:3", "0:-)", "0:)", - ">:)", ">;)", ">:-)", ">_>", "<_<", "\\o/", "<3", "", "=]", "=)", ":}", ":-D", ":D", "8-D", + "8D", "X-D", "XD", "=-D", "=D", "B^D", ">:[", ":-(", ":(", ":c", ":-<", ":<", ":-[", + ":[", ":{", ":'-(", ":'(", ":'-)", ":')", ":@", "D:<", "D:", "D8", "D;", "D=", "DX", + "v.v", "D-':", ">:O", ":-O", ":O", ":O", "o_O", "o_0", "o.O", "8-0", ":*", ";-)", ";)", + ";-]", ";]", ";D", ">:P", ":-P", ":P", "XP", "xp", ":-p", ":p", "=p", ":-b", ":b", + ">:\\", ">:/", ":-/", ":-.", ":/", ":\\", "=/", "=\\", ":L", "=L", ":S", ">.<", ":|", + ":-|", ":$", ":-X", ":X", ":-#", ":#", "O:-)", "0:-3", "0:3", "0:-)", "0:)", ">:)", + ">;)", ">:-)", ">_>", "<_<", "\\o/", "<3", "', '[', ']', '{', '}', '^', '|', '_', '~', '`' - }; //32 - private static final int MAX_PAGE = (int)Math.ceil(symbols.length / 10.0); - + + private static final char[] symbols = { + '.', ',', '!', '?', '$', '&', '%', '#', '@', '"', '\'', ':', ';', '(', ')', '/', '\\', + '-', '+', '=', '*', '<', '>', '[', ']', '{', '}', '^', '|', '_', '~', '`' }; // 32 + private static final int MAX_PAGE = (int) Math.ceil(symbols.length / 10.0); + public SymbolDialog(Context c, View mv) { - super(c, mv); - } + super(c, mv); + } @Override protected String getSymbol(int index) { @@ -36,6 +34,4 @@ public class SymbolDialog extends AbsSymDialog { return MAX_PAGE; } - - } \ No newline at end of file diff --git a/src/org/nyanya/android/traditionalt9/T9DB.java b/src/org/nyanya/android/traditionalt9/T9DB.java index 2d5b2dfe..3c81a344 100644 --- a/src/org/nyanya/android/traditionalt9/T9DB.java +++ b/src/org/nyanya/android/traditionalt9/T9DB.java @@ -20,7 +20,7 @@ public class T9DB { protected static final int DATABASE_VERSION = 1; protected static final String WORD_TABLE_NAME = "word"; protected static final String FREQ_TRIGGER_NAME = "freqtrigger"; - //50k, 10k + // 50k, 10k private static final int FREQ_MAX = 50000; private static final int FREQ_DIV = 10000; @@ -32,34 +32,34 @@ public class T9DB { private static final int MAX_RESULTS = 8; - private static final int CAPS_OFF = 0; - private static final int CAPS_SINGLE = 1; - private static final int CAPS_ALL = 2; - + private static final int CAPS_OFF = 0; + private static final int CAPS_SINGLE = 1; + private static final int CAPS_ALL = 2; + private DatabaseHelper mOpenHelper; private SQLiteDatabase db; private Context parent; - + public T9DB(Context caller) { - //create db + // create db parent = caller; mOpenHelper = new DatabaseHelper(caller); } - + public static SQLiteDatabase getSQLDB(Context caller) { return new DatabaseHelper(caller).getWritableDatabase(); } - + public void init() { db = mOpenHelper.getWritableDatabase(); - //mOpenHelper.onUpgrade(db, 0, DATABASE_VERSION); + // mOpenHelper.onUpgrade(db, 0, DATABASE_VERSION); } - + public void close() { db.close(); } - + public void nuke() { init(); mOpenHelper.onUpgrade(db, 0, DATABASE_VERSION); @@ -70,43 +70,89 @@ public class T9DB { public void addWord(String iword) throws DBException { Resources r = parent.getResources(); if (iword.equals("")) { - throw new DBException(r.getString(R.string.add_word_blank)); + throw new DBException(r.getString(R.string.add_word_blank)); } - //get int sequence - String seq = CharMap.getStringSequence(iword); - //add int sequence into num table + // get int sequence + String seq; + try { + seq = CharMap.getStringSequence(iword); + } catch (NullPointerException e) { + throw new DBException(r.getString(R.string.add_word_badchar)); + } + // add int sequence into num table ContentValues values = new ContentValues(); values.put(COLUMN_SEQ, seq); - //add word into word + // add word into word values.put(COLUMN_WORD, iword); values.put(COLUMN_FREQUENCY, 1); try { db.insertOrThrow(WORD_TABLE_NAME, null, values); } catch (SQLiteConstraintException e) { - String msg = r.getString(R.string.add_word_exist1) + iword + r.getString(R.string.add_word_exist2); + String msg = r.getString(R.string.add_word_exist1) + iword + + r.getString(R.string.add_word_exist2); Log.w("T9DB.addWord", msg); throw new DBException(msg); } } public void incrementWord(int id) { - db.execSQL("UPDATE " + WORD_TABLE_NAME + " SET " + COLUMN_FREQUENCY + " = " + - COLUMN_FREQUENCY + "+ 1 WHERE " + COLUMN_ID + " = \"" + id + "\""); - // if id's freq is greater than X we should normalise those with the same seq + db.execSQL( + "UPDATE " + WORD_TABLE_NAME + + " SET " + COLUMN_FREQUENCY + " = " + COLUMN_FREQUENCY + "+ 1" + + " WHERE " + COLUMN_ID + " = \"" + id + "\""); + // if id's freq is greater than X we should normalise those with the + // same seq + } + + protected String getWord(String is) { + String result = null; + String q = + "SELECT " + COLUMN_WORD + " FROM " + WORD_TABLE_NAME + + " WHERE " + COLUMN_SEQ + "=?" + + " ORDER BY " + COLUMN_FREQUENCY + " DESC"; + Cursor cur = db.rawQuery(q, new String[] { is }); + int hits = 0; + if (cur.moveToFirst()) { + result = cur.getString(0); + } + cur.close(); + if (result != null) { + return result; + } else { + int islen = is.length(); + char c = is.charAt(islen - 1); + c++; + q = "SELECT " + COLUMN_WORD + " FROM " + WORD_TABLE_NAME + + " WHERE " + COLUMN_SEQ + " >= '" + is + "1" + "' AND " + COLUMN_SEQ + " < '" + + is.substring(0, islen - 1) + c + "'" + + " ORDER BY " + COLUMN_FREQUENCY + " DESC, " + COLUMN_SEQ + " ASC" + + " LIMIT " + (MAX_RESULTS - hits); + cur = db.rawQuery(q, null); + + if (cur.moveToFirst()) { + result = cur.getString(1); + } + if (result == null) { + result = ""; + } + cur.close(); + } + return result; } - public void updateWords(String is, ArrayList stringList, ArrayList intList, int capsMode){ + public void updateWords(String is, ArrayList stringList, ArrayList intList, + int capsMode) { stringList.clear(); intList.clear(); - //String[] sa = packInts(stringToInts(is), true); + // String[] sa = packInts(stringToInts(is), true); int islen = is.length(); - String q = "SELECT " + COLUMN_ID + ", " + COLUMN_WORD + - " FROM " + WORD_TABLE_NAME + - " WHERE " + COLUMN_SEQ + "=?" + + String q = + "SELECT " + COLUMN_ID + ", " + COLUMN_WORD + " FROM " + WORD_TABLE_NAME + + " WHERE " + COLUMN_SEQ + "=?" + " ORDER BY " + COLUMN_FREQUENCY + " DESC"; - Cursor cur = db.rawQuery(q, new String[] {is}); + Cursor cur = db.rawQuery(q, new String[] { is }); int hits = 0; - for(cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) { + for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) { intList.add(cur.getInt(0)); stringList.add(cur.getString(1)); if (hits >= 15) { @@ -116,22 +162,24 @@ public class T9DB { } cur.close(); if (hits < 4) { - char c = is.charAt(islen-1); + char c = is.charAt(islen - 1); c++; -// q = "SELECT " + COLUMN_WORD +", " + COLUMN_FREQUENCY + -// " FROM " + WORD_TABLE_NAME + -// " WHERE " + COLUMN_SEQ + " LIKE ?" + -// " ORDER BY " + COLUMN_SEQ + " ASC, " + COLUMN_FREQUENCY + " DESC;"; -// c = db.rawQuery(q, new String[] {is + "_%"}); - //above is hella slow below is gotta query fast + // q = "SELECT " + COLUMN_WORD +", " + COLUMN_FREQUENCY + + // " FROM " + WORD_TABLE_NAME + + // " WHERE " + COLUMN_SEQ + " LIKE ?" + + // " ORDER BY " + COLUMN_SEQ + " ASC, " + COLUMN_FREQUENCY + + // " DESC;"; + // c = db.rawQuery(q, new String[] {is + "_%"}); + // above is hella slow below is gotta query fast q = "SELECT " + COLUMN_ID + ", " + COLUMN_WORD + " FROM " + WORD_TABLE_NAME + - " WHERE " + COLUMN_SEQ + " >= '" + is + "1" + "' AND " + COLUMN_SEQ + " < '" + is.substring(0, islen-1) + c + "'" + - " ORDER BY " + COLUMN_FREQUENCY + " DESC, " + COLUMN_SEQ + " ASC" + + " WHERE " + COLUMN_SEQ + " >= '" + is + "1" + "' AND " + COLUMN_SEQ + " < '" + + is.substring(0, islen - 1) + c + "'" + + " ORDER BY " + COLUMN_FREQUENCY + " DESC, " + COLUMN_SEQ + " ASC" + " LIMIT " + (MAX_RESULTS - hits); cur = db.rawQuery(q, null); - - for(cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) { + + for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) { intList.add(cur.getInt(0)); stringList.add(cur.getString(1)); if (hits >= 10) { @@ -141,11 +189,11 @@ public class T9DB { } cur.close(); } - //Log.d("T9DB.updateWords", "pre: " + stringList); + // Log.d("T9DB.updateWords", "pre: " + stringList); if (capsMode == CAPS_OFF) { return; } - //Log.d("T9DB.updateWords", "filtering..."); + // Log.d("T9DB.updateWords", "filtering..."); // filter list Iterator iter = stringList.iterator(); String word; @@ -160,25 +208,25 @@ public class T9DB { if (wordtemp.equals(word)) { index++; continue; - } else if (stringList.contains(wordtemp)){ - //remove this entry + } else if (stringList.contains(wordtemp)) { + // remove this entry iter.remove(); removed = true; } else { stringList.set(index, wordtemp); } - break; + break; case CAPS_SINGLE: if (word.length() > 1) { wordtemp = word.substring(0, 1).toUpperCase(Locale.US) + word.substring(1); } else { - wordtemp = word.toUpperCase(Locale.US); + wordtemp = word.toUpperCase(Locale.US); } if (wordtemp.equals(word)) { index++; continue; - } else if (stringList.contains(wordtemp)){ - //remove this entry + } else if (stringList.contains(wordtemp)) { + // remove this entry iter.remove(); removed = true; } else { @@ -195,22 +243,21 @@ public class T9DB { } return; } - - - protected void updateWordsW(String is, ArrayList stringList, ArrayList intList, - ArrayList freq){ + + protected void updateWordsW(String is, ArrayList stringList, + ArrayList intList, ArrayList freq) { stringList.clear(); intList.clear(); freq.clear(); - //String[] sa = packInts(stringToInts(is), true); + // String[] sa = packInts(stringToInts(is), true); int islen = is.length(); String q = "SELECT " + COLUMN_ID + ", " + COLUMN_WORD + ", " + COLUMN_FREQUENCY + " FROM " + WORD_TABLE_NAME + - " WHERE " + COLUMN_SEQ + "=?" + + " WHERE " + COLUMN_SEQ + "=?" + " ORDER BY " + COLUMN_FREQUENCY + " DESC"; - Cursor cur = db.rawQuery(q, new String[] {is}); + Cursor cur = db.rawQuery(q, new String[] { is }); int hits = 0; - for(cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) { + for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) { intList.add(cur.getInt(0)); stringList.add(cur.getString(1)); freq.add(cur.getInt(2)); @@ -221,22 +268,24 @@ public class T9DB { } cur.close(); if (hits < 4) { - char c = is.charAt(islen-1); + char c = is.charAt(islen - 1); c++; -// q = "SELECT " + COLUMN_WORD +", " + COLUMN_FREQUENCY + -// " FROM " + WORD_TABLE_NAME + -// " WHERE " + COLUMN_SEQ + " LIKE ?" + -// " ORDER BY " + COLUMN_SEQ + " ASC, " + COLUMN_FREQUENCY + " DESC;"; -// c = db.rawQuery(q, new String[] {is + "_%"}); - //above is hella slow - q = "SELECT " + COLUMN_ID + ", " + COLUMN_WORD + ", " + COLUMN_FREQUENCY + + // q = "SELECT " + COLUMN_WORD +", " + COLUMN_FREQUENCY + + // " FROM " + WORD_TABLE_NAME + + // " WHERE " + COLUMN_SEQ + " LIKE ?" + + // " ORDER BY " + COLUMN_SEQ + " ASC, " + COLUMN_FREQUENCY + + // " DESC;"; + // c = db.rawQuery(q, new String[] {is + "_%"}); + // above is hella slow + q = "SELECT " + COLUMN_ID + ", " + COLUMN_WORD + ", " + COLUMN_FREQUENCY + " FROM " + WORD_TABLE_NAME + - " WHERE " + COLUMN_SEQ + " >= '" + is + "' AND " + COLUMN_SEQ + " < '" + is.substring(0, islen-1) + c + "'" + - " ORDER BY " + COLUMN_FREQUENCY + " DESC, " + COLUMN_SEQ + " ASC" + + " WHERE " + COLUMN_SEQ + " >= '" + is + "' AND " + COLUMN_SEQ + + " < '" + is.substring(0, islen - 1) + c + "'" + + " ORDER BY " + COLUMN_FREQUENCY + " DESC, " + COLUMN_SEQ + " ASC" + " LIMIT " + (MAX_RESULTS - hits); cur = db.rawQuery(q, null); - - for(cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) { + + for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) { intList.add(cur.getInt(0)); stringList.add(cur.getString(1)); freq.add(cur.getInt(2)); @@ -249,35 +298,6 @@ public class T9DB { } return; } - - - protected static int[] stringToInts(String s){ - int[] il = new int[s.length()]; - for (int x = 0; x < s.length(); x++){ - il[x] = s.charAt(x) - 48; //lol hope this is ASCII all the time - } - return il; - } - - protected static String[] packInts(int[] intseq, boolean stringArray){ - int[] ia = packInts(intseq); - String[] sa = {Integer.toString(ia[0]), Integer.toString(ia[1])}; - return sa; - } - protected static int[] packInts(int[] intseq){ - int[] ia = {0, 0}; - - for (int x = 0; x < intseq.length; x++){ - if (x < 8){ - //packing 8 ints (<10) into 32bit int ... I hope... - ia[0] = ia[0] | (intseq[x] << x*4); - } else { - ia[1] = intseq[x] << (x % 8) * 4; - } - } - - return ia; - } private static class DatabaseHelper extends SQLiteOpenHelper { @@ -287,27 +307,27 @@ public class T9DB { @Override public void onCreate(SQLiteDatabase db) { - db.execSQL("CREATE TABLE " + WORD_TABLE_NAME + " (" - + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " - + COLUMN_SEQ + " TEXT, " - + COLUMN_WORD + " TEXT UNIQUE, " - + COLUMN_FREQUENCY + " INTEGER" - + ")"); + db.execSQL("CREATE TABLE " + WORD_TABLE_NAME + " (" + + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + + COLUMN_SEQ + " TEXT, " + + COLUMN_WORD + " TEXT UNIQUE, " + + COLUMN_FREQUENCY + " INTEGER" + ")"); db.execSQL("CREATE INDEX idx ON " + WORD_TABLE_NAME + "(" - //+ COLUMN_NUMHIGH + ", " + COLUMN_NUMLOW + ")"); - + COLUMN_SEQ + " ASC, " + COLUMN_FREQUENCY + " DESC )"); - db.execSQL("CREATE TRIGGER " + FREQ_TRIGGER_NAME + " AFTER UPDATE ON " + WORD_TABLE_NAME - + " WHEN NEW." + COLUMN_FREQUENCY + " > " + FREQ_MAX - + " BEGIN" - + " UPDATE " + WORD_TABLE_NAME + " SET " + COLUMN_FREQUENCY - + " = " + COLUMN_FREQUENCY + " / " + FREQ_DIV + " WHERE " + COLUMN_SEQ + " = NEW." + COLUMN_SEQ + ";" - + " END;"); + + COLUMN_SEQ + " ASC, " + COLUMN_FREQUENCY + " DESC )"); + db.execSQL("CREATE TRIGGER " + FREQ_TRIGGER_NAME + + " AFTER UPDATE ON " + WORD_TABLE_NAME + + " WHEN NEW." + COLUMN_FREQUENCY + " > " + FREQ_MAX + + " BEGIN" + + " UPDATE " + WORD_TABLE_NAME + " SET " + COLUMN_FREQUENCY + " = " + + COLUMN_FREQUENCY + " / " + FREQ_DIV + + " WHERE " + COLUMN_SEQ + " = NEW." + COLUMN_SEQ + ";" + + " END;"); } - + @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { - Log.w("T9DB", "Upgrading database from version " + oldVersion + " to " - + newVersion + ", which will destroy all old data"); + Log.w("T9DB", "Upgrading database from version " + oldVersion + " to " + newVersion + + ", which will destroy all old data"); db.execSQL("DROP TABLE IF EXISTS " + WORD_TABLE_NAME); db.execSQL("DROP INDEX IF EXISTS idx"); onCreate(db); diff --git a/src/org/nyanya/android/traditionalt9/TraditionalT9.java b/src/org/nyanya/android/traditionalt9/TraditionalT9.java index 400699e9..31c868fd 100644 --- a/src/org/nyanya/android/traditionalt9/TraditionalT9.java +++ b/src/org/nyanya/android/traditionalt9/TraditionalT9.java @@ -15,6 +15,7 @@ import android.inputmethodservice.InputMethodService; import android.inputmethodservice.KeyboardView; import android.os.Handler; import android.preference.PreferenceManager; +import android.text.InputType; import android.text.TextUtils; import android.util.Log; import android.view.KeyEvent; @@ -26,8 +27,8 @@ import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputConnection; import android.view.inputmethod.InputMethodManager; -public class TraditionalT9 extends InputMethodService -implements KeyboardView.OnKeyboardActionListener { +public class TraditionalT9 extends InputMethodService implements + KeyboardView.OnKeyboardActionListener { private CandidateView mCandidateView; private InterfaceHandler interfacehandler = null; @@ -39,78 +40,70 @@ implements KeyboardView.OnKeyboardActionListener { private ArrayList mSuggestionInts = new ArrayList(10); private ArrayList mSuggestionSym = new ArrayList(16); - - private static final int NON_EDIT = 0; - private static final int EDITING = 1; + private static final int NON_EDIT = 0; + private static final int EDITING = 1; private static final int EDITING_NOSHOW = 2; private int mEditing = NON_EDIT; - + private boolean mFirstPress = false; - + private boolean mIgnoreDPADKeyUp = false; private KeyEvent mDPADkeyEvent = null; - + protected boolean mWordFound = true; - + private AbsSymDialog mSymbolPopup = null; private AbsSymDialog mSmileyPopup = null; protected boolean mAddingWord = false; - //private boolean mAddingSkipInput = false; + // private boolean mAddingSkipInput = false; private int mPrevious; private int mCharIndex; private int mCapsMode; - private static final int CAPS_OFF = 0; - private static final int CAPS_SINGLE = 1; - private static final int CAPS_ALL = 2; + private static final int CAPS_OFF = 0; + private static final int CAPS_SINGLE = 1; + private static final int CAPS_ALL = 2; private final static int[] CAPS_CYCLE = { CAPS_OFF, CAPS_SINGLE, CAPS_ALL }; - final Handler t9releasehandler = new Handler(); - Runnable mt9release = new Runnable() { - public void run() { + final Handler t9releasehandler = new Handler(); + Runnable mt9release = new Runnable() { + @Override + public void run() { commitReset(); - } + } }; private T9DB db; protected static TraditionalT9 ghettoaccess; - - public static final int MODE_EN = 0; - public static final int MODE_TEXT = 1; - public static final int MODE_NUM = 2; + + public static final int MODE_EN = 0; + public static final int MODE_TEXT = 1; + public static final int MODE_NUM = 2; private static final int[] MODE_CYCLE = { MODE_EN, MODE_TEXT, MODE_NUM }; private int mKeyMode; - /** - * Main initialization of the input method component. Be sure to call - * to super class. + * Main initialization of the input method component. Be sure to call to + * super class. */ - @Override public void onCreate() { + @Override + public void onCreate() { super.onCreate(); mPrevious = -1; mCharIndex = 0; db = new T9DB(this); db.init(); - + if (interfacehandler == null) { - interfacehandler = new InterfaceHandler( - getLayoutInflater().inflate(R.layout.mainview, null), this); + interfacehandler = new InterfaceHandler(getLayoutInflater().inflate(R.layout.mainview, + null), this); } } - /** - * This is the point where you can do all of your UI initialization. It - * is called after creation and any configuration change. - */ -// @Override public void onInitializeInterface() { -// //maybe do some stuff -// -// } - - @Override public boolean onEvaluateInputViewShown (){ + @Override + public boolean onEvaluateInputViewShown() { if (mEditing == EDITING_NOSHOW) { return false; } @@ -118,12 +111,13 @@ implements KeyboardView.OnKeyboardActionListener { } /** - * Called by the framework when your view for creating input needs to - * be generated. This will be called the first time your input method - * is displayed, and every time it needs to be re-created such as due to - * a configuration change. + * Called by the framework when your view for creating input needs to be + * generated. This will be called the first time your input method is + * displayed, and every time it needs to be re-created such as due to a + * configuration change. */ - @Override public View onCreateInputView() { + @Override + public View onCreateInputView() { updateKeyMode(); View v = getLayoutInflater().inflate(R.layout.mainview, null); interfacehandler.changeView(v); @@ -135,30 +129,32 @@ implements KeyboardView.OnKeyboardActionListener { return v; } - /** - * Called by the framework when your view for showing candidates needs to - * be generated, like {@link #onCreateInputView}. + * Called by the framework when your view for showing candidates needs to be + * generated, like {@link #onCreateInputView}. */ - @Override public View onCreateCandidatesView() { + @Override + public View onCreateCandidatesView() { mCandidateView = new CandidateView(this); - mCandidateView.setService(this); return mCandidateView; } protected void showSymbolPage() { if (mSymbolPopup == null) { - mSymbolPopup = new SymbolDialog(this, getLayoutInflater().inflate(R.layout.symbolview, null)); + mSymbolPopup = new SymbolDialog(this, getLayoutInflater().inflate(R.layout.symbolview, + null)); } mSymbolPopup.doShow(getWindow().getWindow().getDecorView()); } + protected void showSmileyPage() { if (mSmileyPopup == null) { - mSmileyPopup = new SmileyDialog(this, getLayoutInflater().inflate(R.layout.symbolview, null)); + mSmileyPopup = new SmileyDialog(this, getLayoutInflater().inflate(R.layout.symbolview, + null)); } mSmileyPopup.doShow(getWindow().getWindow().getDecorView()); } - + protected void showAddWord() { if (mKeyMode == MODE_EN) { ghettoaccess = this; @@ -167,49 +163,52 @@ implements KeyboardView.OnKeyboardActionListener { awintent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); awintent.putExtra("org.nyanya.android.traditionalt9.word", mComposing.toString()); startActivity(awintent); - } + } } - + public void doAddWord(String text) { try { db.addWord(text); } catch (DBException e) { AlertDialog.Builder builder = new AlertDialog.Builder(this); - builder.setMessage(e.getMessage()) - .setTitle(R.string.add_word).setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int id) { - dialog.dismiss(); - } - }); + builder.setMessage(e.getMessage()).setTitle(R.string.add_word) + .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int id) { + dialog.dismiss(); + } + }); AlertDialog dialog = builder.create(); - //so many ghettos to display dialogs from IME + // so many ghettos to display dialogs from IME Window win = dialog.getWindow(); WindowManager.LayoutParams lp = win.getAttributes(); - lp.token = getWindow().getWindow().getDecorView().getWindowToken(); - lp.type = WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG; - win.setAttributes(lp); - win.addFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM); - + lp.token = getWindow().getWindow().getDecorView().getWindowToken(); + lp.type = WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG; + win.setAttributes(lp); + win.addFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM); + dialog.show(); } } - + protected void addCancel() { interfacehandler.showNotFound(false); ghettoaccess = null; } - + /** * This is the main point where we do our initialization of the input method - * to begin operating on an application. At this point we have been - * bound to the client, and are now receiving all of the detailed information - * about the target of our edits. + * to begin operating on an application. At this point we have been bound to + * the client, and are now receiving all of the detailed information about + * the target of our edits. */ - @Override public void onStartInput(EditorInfo attribute, boolean restarting) { + @Override + public void onStartInput(EditorInfo attribute, boolean restarting) { super.onStartInput(attribute, restarting); - //Log.d("onStartInput", "attribute.inputType: " + attribute.inputType + " restarting? " + restarting); + // Log.d("onStartInput", "attribute.inputType: " + attribute.inputType + + // " restarting? " + restarting); if (attribute.inputType == 0) { - //don't do anything when not in any kind of edit field. + // don't do anything when not in any kind of edit field. // should also turn off input screen and stuff mEditing = NON_EDIT; requestHideSelf(0); @@ -218,14 +217,15 @@ implements KeyboardView.OnKeyboardActionListener { } mFirstPress = true; mEditing = EDITING; - // Reset our state. We want to do this even if restarting, because - // the underlying state of the text editor could have changed in any way. + // Reset our state. We want to do this even if restarting, because + // the underlying state of the text editor could have changed in any + // way. mSuggestionStrings.clear(); mSuggestionInts.clear(); mSuggestionSym.clear(); mComposing.setLength(0); mComposingI.setLength(0); - + SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this); updateCandidates(); @@ -237,22 +237,22 @@ implements KeyboardView.OnKeyboardActionListener { // We are now going to initialize our state based on the type of // text being edited. - switch (attribute.inputType & EditorInfo.TYPE_MASK_CLASS) { - case EditorInfo.TYPE_CLASS_NUMBER: - case EditorInfo.TYPE_CLASS_DATETIME: + switch (attribute.inputType & InputType.TYPE_MASK_CLASS) { + case InputType.TYPE_CLASS_NUMBER: + case InputType.TYPE_CLASS_DATETIME: // Numbers and dates default to the symbols keyboard, with // no extra features. mKeyMode = MODE_NUM; break; - case EditorInfo.TYPE_CLASS_PHONE: + case InputType.TYPE_CLASS_PHONE: // Phones will also default to the symbols keyboard, though // often you will want to have a dedicated phone keyboard. mKeyMode = MODE_NUM; break; - case EditorInfo.TYPE_CLASS_TEXT: - // This is general text editing. We will default to the + case InputType.TYPE_CLASS_TEXT: + // This is general text editing. We will default to the // normal alphabetic keyboard, and assume that we should // be doing predictive text (showing candidates as the // user types). @@ -260,34 +260,35 @@ implements KeyboardView.OnKeyboardActionListener { // We now look for a few special variations of text that will // modify our behavior. - int variation = attribute.inputType & EditorInfo.TYPE_MASK_VARIATION; - if (variation == EditorInfo.TYPE_TEXT_VARIATION_PASSWORD || - variation == EditorInfo.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) { + int variation = attribute.inputType & InputType.TYPE_MASK_VARIATION; + if (variation == InputType.TYPE_TEXT_VARIATION_PASSWORD + || variation == InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) { // Do not display predictions / what the user is typing // when they are entering a password. mKeyMode = MODE_TEXT; } - if (variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_ADDRESS - || variation == EditorInfo.TYPE_TEXT_VARIATION_URI - || variation == EditorInfo.TYPE_TEXT_VARIATION_FILTER) { + if (variation == InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS + || variation == InputType.TYPE_TEXT_VARIATION_URI + || variation == InputType.TYPE_TEXT_VARIATION_FILTER) { // Our predictions are not useful for e-mail addresses // or URIs. mKeyMode = MODE_TEXT; } - if ((attribute.inputType & EditorInfo.TYPE_TEXT_FLAG_AUTO_COMPLETE) != 0) { + if ((attribute.inputType & InputType.TYPE_TEXT_FLAG_AUTO_COMPLETE) != 0) { // If this is an auto-complete text view, then our predictions // will not be shown and instead we will allow the editor - // to supply their own. We only show the editor's + // to supply their own. We only show the editor's // candidates when in fullscreen mode, otherwise relying // own it displaying its own UI. // ???? mKeyMode = Integer.parseInt(pref.getString("pref_inputmode", "0")); } - - //handle filter list cases... do not hijack DPAD center and make sure back's go through proper - if ((attribute.inputType & EditorInfo.TYPE_TEXT_VARIATION_FILTER) != 0) { + + // handle filter list cases... do not hijack DPAD center and make + // sure back's go through proper + if ((attribute.inputType & InputType.TYPE_TEXT_VARIATION_FILTER) != 0) { mEditing = EDITING_NOSHOW; } @@ -303,20 +304,20 @@ implements KeyboardView.OnKeyboardActionListener { // keyboard with no special features. updateShiftKeyState(attribute); } - if (attribute.privateImeOptions != null && - attribute.privateImeOptions.equals("org.nyanya.android.traditionalt9.addword=true")) { + if (attribute.privateImeOptions != null + && attribute.privateImeOptions.equals("org.nyanya.android.traditionalt9.addword=true")) { mAddingWord = true; - //mAddingSkipInput = true; - //Log.d("onStartInput", "ADDING WORD"); + // mAddingSkipInput = true; + // Log.d("onStartInput", "ADDING WORD"); mKeyMode = MODE_TEXT; } else { mAddingWord = false; - //Log.d("onStartInput", "not adding word"); + // Log.d("onStartInput", "not adding word"); } - + // Update the label on the enter key, depending on what the application // says it will do. - //mCurKeyboard.setImeOptions(getResources(), attribute.imeOptions); + // mCurKeyboard.setImeOptions(getResources(), attribute.imeOptions); setSuggestions(null, -1); setCandidatesViewShown(false); mSuggestionStrings.clear(); @@ -325,72 +326,75 @@ implements KeyboardView.OnKeyboardActionListener { if (interfacehandler != null) { interfacehandler.midButtonUpdate(false); } - + updateKeyMode(); - //show Window()? - + // show Window()? } /** - * This is called when the user is done editing a field. We can use - * this to reset our state. + * This is called when the user is done editing a field. We can use this to + * reset our state. */ - @Override public void onFinishInput() { + @Override + public void onFinishInput() { super.onFinishInput(); - //Log.d("onFinishInput", "When is this called?"); + // Log.d("onFinishInput", "When is this called?"); if (mEditing == EDITING) { commitTyped(); finish(); } } -// @Override public void onFinishInputView (boolean finishingInput) { -// Log.d("onFinishInputView", "? " + finishingInput); -// } + // @Override public void onFinishInputView (boolean finishingInput) { + // Log.d("onFinishInputView", "? " + finishingInput); + // } private void finish() { - //Log.d("finish", "why?"); + // Log.d("finish", "why?"); // Clear current composing text and candidates. pickSelectedCandidate(getCurrentInputConnection()); mComposing.setLength(0); mComposingI.setLength(0); - //updateCandidates(); + // updateCandidates(); // We only hide the candidates window when finishing input on // a particular editor, to avoid popping the underlying application // up and down if the user is entering text into the bottom of // its window. - //setCandidatesViewShown(false); - - //TODO: check this? + // setCandidatesViewShown(false); + + // TODO: check this? mEditing = NON_EDIT; hideWindow(); hideStatusIcon(); } - @Override public void onDestroy() { + @Override + public void onDestroy() { db.close(); super.onDestroy(); } -// @Override public void onStartInputView(EditorInfo attribute, boolean restarting) { -// Log.d("onStartInputView", "attribute.inputType: " + attribute.inputType + " restarting? " + restarting); -// //super.onStartInputView(attribute, restarting); -// } + // @Override public void onStartInputView(EditorInfo attribute, boolean + // restarting) { + // Log.d("onStartInputView", "attribute.inputType: " + attribute.inputType + + // " restarting? " + restarting); + // //super.onStartInputView(attribute, restarting); + // } /** * Deal with the editor reporting movement of its cursor. */ - @Override public void onUpdateSelection(int oldSelStart, int oldSelEnd, - int newSelStart, int newSelEnd, - int candidatesStart, int candidatesEnd) { - super.onUpdateSelection(oldSelStart, oldSelEnd, newSelStart, newSelEnd, - candidatesStart, candidatesEnd); + @Override + public void onUpdateSelection(int oldSelStart, int oldSelEnd, int newSelStart, int newSelEnd, + int candidatesStart, int candidatesEnd) { + super.onUpdateSelection(oldSelStart, oldSelEnd, newSelStart, newSelEnd, candidatesStart, + candidatesEnd); // If the current selection in the text view changes, we should // clear whatever candidate text we have. - if ((mComposing.length() > 0 || mComposingI.length() > 0) && (newSelStart != candidatesEnd - || newSelEnd != candidatesEnd)) { + if ((mComposing.length() > 0 || mComposingI.length() > 0) + && (newSelStart != candidatesEnd || newSelEnd != candidatesEnd)) { mComposing.setLength(0); mComposingI.setLength(0); updateCandidates(); @@ -402,37 +406,33 @@ implements KeyboardView.OnKeyboardActionListener { } /** - * This tells us about completions that the editor has determined based - * on the current text in it. We want to use this in fullscreen mode - * to show the completions ourself, since the editor can not be seen - * in that situation. + * This tells us about completions that the editor has determined based on + * the current text in it. We want to use this in fullscreen mode to show + * the completions ourself, since the editor can not be seen in that + * situation. */ - @Override public void onDisplayCompletions(CompletionInfo[] completions) { - //?????????????? + @Override + public void onDisplayCompletions(CompletionInfo[] completions) { + // ?????????????? } /** - * Use this to monitor key events being delivered to the application. - * We get first crack at them, and can either resume them or let them - * continue to the app. + * Use this to monitor key events being delivered to the application. We get + * first crack at them, and can either resume them or let them continue to + * the app. */ - @Override public boolean onKeyDown(int keyCode, KeyEvent event) { - //Log.d("onKeyDown", "Key: " + event + " repeat?: " + event.getRepeatCount() + " long-time: " + event.isLongPress()); - //Log.d("onKeyDown", "Key: " + keyCode + " repeat?: " + event.getRepeatCount()); + @Override + public boolean onKeyDown(int keyCode, KeyEvent event) { + // Log.d("onKeyDown", "Key: " + event + " repeat?: " + + // event.getRepeatCount() + " long-time: " + event.isLongPress()); if (mEditing == NON_EDIT) { -// // catch for UI weirdness on up event thing -// if (mButtonClose && keyCode != KeyEvent.KEYCODE_DPAD_CENTER) { -// mButtonClose = false; -// return false; -// } - //Log.d("onKeyDown", "returned false"); - //return super.onKeyDown(keyCode, event); + // // catch for UI weirdness on up event thing return false; } mFirstPress = false; - - //Log.d("onKeyDown", "Key: " + keyCode); - //TODO: remove emulator special keys + + // Log.d("onKeyDown", "Key: " + keyCode); + // TODO: remove emulator special keys switch (keyCode) { case 75: keyCode = KeyEvent.KEYCODE_POUND; @@ -447,55 +447,55 @@ implements KeyboardView.OnKeyboardActionListener { keyCode = KeyEvent.KEYCODE_SOFT_LEFT; break; } - + switch (keyCode) { case KeyEvent.KEYCODE_DPAD_CENTER: if (interfacehandler != null) { interfacehandler.setPressed(keyCode, true); - } //pass-through + } // pass-through case KeyEvent.KEYCODE_DPAD_DOWN: case KeyEvent.KEYCODE_DPAD_UP: case KeyEvent.KEYCODE_DPAD_LEFT: case KeyEvent.KEYCODE_DPAD_RIGHT: - if (mEditing == EDITING_NOSHOW){ + if (mEditing == EDITING_NOSHOW) { return false; } return handleDPAD(keyCode, event, true); - + case KeyEvent.KEYCODE_SOFT_RIGHT: case KeyEvent.KEYCODE_SOFT_LEFT: if (!isInputViewShown()) { return super.onKeyDown(keyCode, event); } - + break; + case KeyEvent.KEYCODE_DEL: // Special handling of the delete key: if we currently are // composing text for the user, we want to modify that instead // of let the application to the delete itself. - //if (mComposing.length() > 0) { + // if (mComposing.length() > 0) { onKey(keyCode, null); return true; - //} - //break; + // } + // break; } - - - //only handle first press except for delete + + // only handle first press except for delete if (event.getRepeatCount() != 0) { return true; } - if (mKeyMode == MODE_TEXT){ + if (mKeyMode == MODE_TEXT) { t9releasehandler.removeCallbacks(mt9release); } switch (keyCode) { case KeyEvent.KEYCODE_BACK: // The InputMethodService already takes care of the back // key for us, to dismiss the input method if it is shown. - // but we will manage it ourselves because native Android handling of - // the input view is ... flakey at best. - //Log.d("onKeyDown", "back pres"); + // but we will manage it ourselves because native Android handling + // of the input view is ... flakey at best. + // Log.d("onKeyDown", "back pres"); if (isInputViewShown()) { - //Log.d("inKeyDown", "input shown"); + // Log.d("inKeyDown", "input shown"); return true; } return false; @@ -503,14 +503,14 @@ implements KeyboardView.OnKeyboardActionListener { case KeyEvent.KEYCODE_ENTER: // Let the underlying text editor always handle these. return false; - - //special case for softkeys + + // special case for softkeys case KeyEvent.KEYCODE_SOFT_RIGHT: case KeyEvent.KEYCODE_SOFT_LEFT: if (interfacehandler != null) { interfacehandler.setPressed(keyCode, true); } - //pass-through + // pass-through case KeyEvent.KEYCODE_0: case KeyEvent.KEYCODE_1: case KeyEvent.KEYCODE_2: @@ -526,20 +526,22 @@ implements KeyboardView.OnKeyboardActionListener { event.startTracking(); return true; default: - //KeyCharacterMap.load(KeyCharacterMap.BUILT_IN_KEYBOARD).getNumber(keyCode) - //Log.w("onKeyDown", "Unhandled Key: " + keyCode + "(" + event.toString() + ")"); + // KeyCharacterMap.load(KeyCharacterMap.BUILT_IN_KEYBOARD).getNumber(keyCode) + // Log.w("onKeyDown", "Unhandled Key: " + keyCode + "(" + + // event.toString() + ")"); } Log.w("onKeyDown", "Unhandled Key: " + keyCode + "(" + event.toString() + ")"); return super.onKeyDown(keyCode, event); } - + @Override - public boolean onKeyLongPress(int keyCode, KeyEvent event) { - //consume since we will assume we have already handled the long press if greater than 1 + public boolean onKeyLongPress(int keyCode, KeyEvent event) { + // consume since we will assume we have already handled the long press + // if greater than 1 if (event.getRepeatCount() != 1) { return true; } - //TODO: remove emulator special keys + // TODO: remove emulator special keys switch (keyCode) { case 75: keyCode = KeyEvent.KEYCODE_POUND; @@ -554,9 +556,9 @@ implements KeyboardView.OnKeyboardActionListener { keyCode = KeyEvent.KEYCODE_SOFT_LEFT; break; } - - //Log.d("onLongPress", "LONG PRESS: " + keyCode); - //HANDLE SPECIAL KEYS + + // Log.d("onLongPress", "LONG PRESS: " + keyCode); + // HANDLE SPECIAL KEYS switch (keyCode) { case KeyEvent.KEYCODE_POUND: commitReset(); @@ -584,8 +586,9 @@ implements KeyboardView.OnKeyboardActionListener { if (interfacehandler != null) { interfacehandler.setPressed(keyCode, false); } - ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).showInputMethodPicker(); - //show IME + ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)) + .showInputMethodPicker(); + // show IME return true; } if (keyCode >= KeyEvent.KEYCODE_0 && keyCode <= KeyEvent.KEYCODE_9) { @@ -593,33 +596,35 @@ implements KeyboardView.OnKeyboardActionListener { } else if (mKeyMode == MODE_TEXT) { commitReset(); - onText(String.valueOf(keyCode-KeyEvent.KEYCODE_0)); + onText(String.valueOf(keyCode - KeyEvent.KEYCODE_0)); } } return true; } /** - * Use this to monitor key events being delivered to the application. - * We get first crack at them, and can either resume them or let them - * continue to the app. + * Use this to monitor key events being delivered to the application. We get + * first crack at them, and can either resume them or let them continue to + * the app. */ - @Override public boolean onKeyUp(int keyCode, KeyEvent event) { - //Log.d("onKeyUp", "Key: " + keyCode + " repeat?: " + event.getRepeatCount()); + @Override + public boolean onKeyUp(int keyCode, KeyEvent event) { + // Log.d("onKeyUp", "Key: " + keyCode + " repeat?: " + + // event.getRepeatCount()); if (mEditing == NON_EDIT) { -// if (mButtonClose) { -// //handle UI weirdness on up event -// mButtonClose = false; -// return true; -// } - //Log.d("onKeyDown", "returned false"); + // if (mButtonClose) { + // //handle UI weirdness on up event + // mButtonClose = false; + // return true; + // } + // Log.d("onKeyDown", "returned false"); return false; } else if (mFirstPress) { // to make sure changing between input UI elements works correctly. return super.onKeyUp(keyCode, event); } - - //TODO: remove emulator special keys + + // TODO: remove emulator special keys switch (keyCode) { case 75: keyCode = KeyEvent.KEYCODE_POUND; @@ -633,8 +638,8 @@ implements KeyboardView.OnKeyboardActionListener { case 71: keyCode = KeyEvent.KEYCODE_SOFT_LEFT; break; - } - + } + switch (keyCode) { case KeyEvent.KEYCODE_DPAD_CENTER: if (interfacehandler != null) { @@ -648,24 +653,26 @@ implements KeyboardView.OnKeyboardActionListener { return false; } return handleDPAD(keyCode, event, false); - + case KeyEvent.KEYCODE_SOFT_RIGHT: case KeyEvent.KEYCODE_SOFT_LEFT: if (!isInputViewShown()) { return super.onKeyDown(keyCode, event); } + break; } - //Log.d("onKeyUp", "Key: " + keyCode); - //Log.d("onKeyUp", "Key: " + event + " cancelled?: " + event.isCanceled()); - if (event.isCanceled()){ + // Log.d("onKeyUp", "Key: " + keyCode); + // Log.d("onKeyUp", "Key: " + event + " cancelled?: " + + // event.isCanceled()); + if (event.isCanceled()) { return true; } switch (keyCode) { case KeyEvent.KEYCODE_BACK: - //Log.d("onKeyUp", "back pres"); + // Log.d("onKeyUp", "back pres"); if (isInputViewShown()) { - //Log.d("onKeyUp", "input shown"); + // Log.d("onKeyUp", "input shown"); hideWindow(); return true; } @@ -675,20 +682,21 @@ implements KeyboardView.OnKeyboardActionListener { case KeyEvent.KEYCODE_ENTER: return false; - //special case for softkeys + // special case for softkeys case KeyEvent.KEYCODE_SOFT_RIGHT: case KeyEvent.KEYCODE_SOFT_LEFT: -// if (mAddingWord){ -// Log.d("onKeyUp", "key: " + keyCode + " skip: " + mAddingSkipInput); -// if (mAddingSkipInput) { -// //mAddingSkipInput = false; -// return true; -// } -// } + // if (mAddingWord){ + // Log.d("onKeyUp", "key: " + keyCode + " skip: " + + // mAddingSkipInput); + // if (mAddingSkipInput) { + // //mAddingSkipInput = false; + // return true; + // } + // } if (interfacehandler != null) { interfacehandler.setPressed(keyCode, false); } - //pass-through + // pass-through case KeyEvent.KEYCODE_0: case KeyEvent.KEYCODE_1: case KeyEvent.KEYCODE_2: @@ -701,14 +709,14 @@ implements KeyboardView.OnKeyboardActionListener { case KeyEvent.KEYCODE_9: case KeyEvent.KEYCODE_POUND: case KeyEvent.KEYCODE_STAR: -// if (!isInputViewShown()){ -// Log.d("onKeyUp", "showing window."); -// //showWindow(true); -// } + // if (!isInputViewShown()){ + // Log.d("onKeyUp", "showing window."); + // //showWindow(true); + // } onKey(keyCode, null); return true; default: - //KeyCharacterMap.load(KeyCharacterMap.BUILT_IN_KEYBOARD).getNumber(keyCode) + // KeyCharacterMap.load(KeyCharacterMap.BUILT_IN_KEYBOARD).getNumber(keyCode) Log.w("onKeyUp", "Unhandled Key: " + keyCode + "(" + event.toString() + ")"); } return super.onKeyUp(keyCode, event); @@ -720,6 +728,7 @@ implements KeyboardView.OnKeyboardActionListener { private void commitTyped() { commitTyped(getCurrentInputConnection()); } + private void commitTyped(InputConnection ic) { if (interfacehandler != null) { interfacehandler.midButtonUpdate(false); @@ -739,14 +748,14 @@ implements KeyboardView.OnKeyboardActionListener { * editor state. */ private void updateShiftKeyState(EditorInfo attr) { - //Log.d("updateShift", "CM start: " + mCapsMode); + // Log.d("updateShift", "CM start: " + mCapsMode); if (attr != null && mCapsMode != CAPS_ALL) { int caps = 0; - if (attr != null && attr.inputType != EditorInfo.TYPE_NULL) { + if (attr != null && attr.inputType != InputType.TYPE_NULL) { caps = getCurrentInputConnection().getCursorCapsMode(attr.inputType); } - // mInputView.setShifted(mCapsLock || caps != 0); - //Log.d("updateShift", "caps: " + caps); + // mInputView.setShifted(mCapsLock || caps != 0); + // Log.d("updateShift", "caps: " + caps); if ((caps & TextUtils.CAP_MODE_CHARACTERS) == TextUtils.CAP_MODE_CHARACTERS) { mCapsMode = CAPS_ALL; } else if ((caps & TextUtils.CAP_MODE_SENTENCES) == TextUtils.CAP_MODE_SENTENCES) { @@ -758,52 +767,36 @@ implements KeyboardView.OnKeyboardActionListener { } updateKeyMode(); } - //Log.d("updateShift", "CM end: " + mCapsMode); + // Log.d("updateShift", "CM end: " + mCapsMode); } /** - * Helper to send a key down / key up pair to the current editor. - * NOTE: Not supposed to use this apparently. Need to use it for DEL. - * For other things I'll have to onText + * Helper to send a key down / key up pair to the current editor. NOTE: Not + * supposed to use this apparently. Need to use it for DEL. For other things + * I'll have to onText */ private void keyDownUp(int keyEventCode) { InputConnection ic = getCurrentInputConnection(); - KeyEvent kv = KeyEvent.changeFlags( - new KeyEvent(KeyEvent.ACTION_DOWN, keyEventCode), KeyEvent.FLAG_SOFT_KEYBOARD); + KeyEvent kv = KeyEvent.changeFlags(new KeyEvent(KeyEvent.ACTION_DOWN, keyEventCode), + KeyEvent.FLAG_SOFT_KEYBOARD); ic.sendKeyEvent(kv); - kv = KeyEvent.changeFlags( - new KeyEvent(KeyEvent.ACTION_UP, keyEventCode), KeyEvent.FLAG_SOFT_KEYBOARD); + kv = KeyEvent.changeFlags(new KeyEvent(KeyEvent.ACTION_UP, keyEventCode), + KeyEvent.FLAG_SOFT_KEYBOARD); ic.sendKeyEvent(kv); } - // /** - // * Helper to send a character to the editor as raw key events. - // */ - // private void sendKey(int keyCode) { - // switch (keyCode) { - // case '\n': - // keyDownUp(KeyEvent.KEYCODE_ENTER); - // break; - // default: - // if (keyCode >= '0' && keyCode <= '9') { - // keyDownUp(keyCode - '0' + KeyEvent.KEYCODE_0); - // } else { - // getCurrentInputConnection().commitText(String.valueOf((char) keyCode), 1); - // } - // break; - // } - // } // Implementation of KeyboardViewListener + @Override public void onKey(int keyCode, int[] keyCodes) { - //Log.d("OnKey", "pri: " + keyCode); - //Log.d("onKey", "START Cm: " + mCapsMode); - //HANDLE SPECIAL KEYS + // Log.d("OnKey", "pri: " + keyCode); + // Log.d("onKey", "START Cm: " + mCapsMode); + // HANDLE SPECIAL KEYS switch (keyCode) { case KeyEvent.KEYCODE_DEL: handleBackspace(); break; - //change case + // change case case KeyEvent.KEYCODE_STAR: if (mKeyMode == MODE_NUM) { handleCharacter(KeyEvent.KEYCODE_STAR); @@ -814,7 +807,7 @@ implements KeyboardView.OnKeyboardActionListener { case KeyEvent.KEYCODE_BACK: handleClose(); break; - //space + // space case KeyEvent.KEYCODE_POUND: handleCharacter(KeyEvent.KEYCODE_POUND); break; @@ -835,12 +828,14 @@ implements KeyboardView.OnKeyboardActionListener { Log.e("onKey", "This shouldn't happen, unknown key"); } } - //Log.d("onKey", "END Cm: " + mCapsMode); + // Log.d("onKey", "END Cm: " + mCapsMode); } + @Override public void onText(CharSequence text) { InputConnection ic = getCurrentInputConnection(); - if (ic == null) return; + if (ic == null) + return; ic.beginBatchEdit(); if (mComposing.length() > 0 || mComposingI.length() > 0) { commitTyped(ic); @@ -851,14 +846,15 @@ implements KeyboardView.OnKeyboardActionListener { } /** - * Used from interface to either close the input UI if not composing text or to accept the composing text + * Used from interface to either close the input UI if not composing text or + * to accept the composing text */ protected void handleMidButton() { if (!isInputViewShown()) { showWindow(true); return; } - if (mComposing.length() > 0){ + if (mComposing.length() > 0) { switch (mKeyMode) { case MODE_EN: commitTyped(); @@ -868,53 +864,57 @@ implements KeyboardView.OnKeyboardActionListener { charReset(); break; case MODE_NUM: - //shouldn't happen + // shouldn't happen break; } } else { hideWindow(); - } + } } /** - * Update the list of available candidates from the current composing - * text. This will need to be filled in by however you are determining - * candidates. + * Update the list of available candidates from the current composing text. + * This will need to be filled in by however you are determining candidates. */ private void updateCandidates() { if (mKeyMode == MODE_EN) { int len = mComposingI.length(); if (len > 0) { - if (mComposingI.charAt(len-1) == '1') { + if (mComposingI.charAt(len - 1) == '1') { boolean nosuggestion = mSuggestionStrings.isEmpty(); String prefix = ""; if (!nosuggestion) { prefix = mSuggestionStrings.get(mCandidateView.mSelectedIndex); + } else if (len > 1) { + prefix = db.getWord(mComposingI.substring(0, len - 1)); } mSuggestionInts.clear(); mSuggestionStrings.clear(); mSuggestionSym.clear(); db.updateWords("1", mSuggestionSym, mSuggestionInts, mCapsMode); - for (String a : mSuggestionSym){ - if (!nosuggestion) { - mSuggestionStrings.add(prefix+a); + for (String a : mSuggestionSym) { + if (prefix != "") { + mSuggestionStrings.add(prefix + a); } else { mSuggestionStrings.add(String.valueOf(a)); + mComposingI.setLength(0); + mComposingI.append("1"); } } } else { - db.updateWords(mComposingI.toString(), mSuggestionStrings, mSuggestionInts, mCapsMode); + db.updateWords(mComposingI.toString(), mSuggestionStrings, mSuggestionInts, + mCapsMode); } if (!mSuggestionStrings.isEmpty()) { mWordFound = true; mComposing.setLength(0); - mComposing.append(mSuggestionStrings.get(0).substring(0, len)); + mComposing.append(mSuggestionStrings.get(0)); if (interfacehandler != null) { interfacehandler.showNotFound(false); } } else { mWordFound = false; - mComposingI.setLength(len-1); + mComposingI.setLength(len - 1); setCandidatesViewShown(false); if (interfacehandler != null) { interfacehandler.showNotFound(true); @@ -928,12 +928,11 @@ implements KeyboardView.OnKeyboardActionListener { interfacehandler.showNotFound(false); } } - } - else if (mKeyMode == MODE_TEXT) { + } else if (mKeyMode == MODE_TEXT) { if (mComposing.length() > 0) { mSuggestionStrings.clear(); char[] ca = CharMap.T9TABLE[mPrevious]; - for (int i = 0; i < ca.length; i++){ + for (int i = 0; i < ca.length; i++) { mSuggestionStrings.add(String.valueOf(ca[i])); } setSuggestions(mSuggestionStrings, mCharIndex); @@ -964,9 +963,10 @@ implements KeyboardView.OnKeyboardActionListener { } if (length > 1 || length2 > 1) { - //Log.d("BS", "comp: " + length + " compI: " + length2); + // Log.d("BS", "comp: " + length + " compI: " + length2); mComposing.delete(length - 1, length); mComposingI.delete(length2 - 1, length2); + mSuggestionStrings.clear(); updateCandidates(); getCurrentInputConnection().setComposingText(mComposing, 1); } else if (length > 0 || length2 > 0) { @@ -974,13 +974,14 @@ implements KeyboardView.OnKeyboardActionListener { mComposingI.setLength(0); interfacehandler.midButtonUpdate(false); interfacehandler.showNotFound(false); + mSuggestionStrings.clear(); getCurrentInputConnection().commitText("", 0); updateCandidates(); } else { keyDownUp(KeyEvent.KEYCODE_DEL); } updateShiftKeyState(getCurrentInputEditorInfo()); - //Log.d("handleBS", "Cm: " + mCapsMode); + // Log.d("handleBS", "Cm: " + mCapsMode); // Why do I need to call this twice, android... updateShiftKeyState(getCurrentInputEditorInfo()); } @@ -989,12 +990,11 @@ implements KeyboardView.OnKeyboardActionListener { // do my own thing here if (mCapsMode == CAPS_CYCLE.length - 1) { mCapsMode = 0; - } - else { - mCapsMode++; + } else { + mCapsMode++; } - if (mKeyMode == MODE_EN && mComposing.length() > 0){ + if (mKeyMode == MODE_EN && mComposing.length() > 0) { updateCandidates(); getCurrentInputConnection().setComposingText(mComposing, 1); } @@ -1002,26 +1002,26 @@ implements KeyboardView.OnKeyboardActionListener { } /** - * handle input of a character. - * Precondition: ONLY 0-9 AND *# ARE ALLOWED + * handle input of a character. Precondition: ONLY 0-9 AND *# ARE ALLOWED + * * @param keyCode */ private void handleCharacter(int keyCode) { - // if (mInputView.isShifted()) { - // primaryCode = Character.toUpperCase(primaryCode); - // } + // if (mInputView.isShifted()) { + // primaryCode = Character.toUpperCase(primaryCode); + // } switch (mKeyMode) { case MODE_EN: - //it begins + // it begins // on POUND commit and space - if (keyCode == KeyEvent.KEYCODE_POUND){ + if (keyCode == KeyEvent.KEYCODE_POUND) { if (mComposing.length() > 0) { commitTyped(); } - //Log.d("handleChar", "SENDING SPACE?"); + // Log.d("handleChar", "SENDING SPACE?"); onText(" "); } else { - //do things + // do things if (interfacehandler != null) { interfacehandler.midButtonUpdate(true); } @@ -1039,27 +1039,27 @@ implements KeyboardView.OnKeyboardActionListener { keyCode--; } keyCode = keyCode - KeyEvent.KEYCODE_0; - //Log.d("handleChar", "PRIMARY CODE (num): " + keyCode); + // Log.d("handleChar", "PRIMARY CODE (num): " + keyCode); boolean newChar = false; - if (mPrevious == keyCode){ + if (mPrevious == keyCode) { mCharIndex++; } else { commitTyped(getCurrentInputConnection()); - //updateShiftKeyState(getCurrentInputEditorInfo()); + // updateShiftKeyState(getCurrentInputEditorInfo()); newChar = true; mCharIndex = 0; mPrevious = keyCode; } // start at caps if CapMode - //Log.d("handleChar", "Cm: " + mCapsMode); + // Log.d("handleChar", "Cm: " + mCapsMode); if (mCharIndex == 0 && mCapsMode != CAPS_OFF) { mCharIndex = CharMap.T9CAPSTART[keyCode]; } - // private int mPrevious; - // private int mCharindex; + // private int mPrevious; + // private int mCharindex; mComposing.setLength(0); mComposingI.setLength(0); char[] ca = CharMap.T9TABLE[keyCode]; @@ -1074,7 +1074,7 @@ implements KeyboardView.OnKeyboardActionListener { t9releasehandler.postDelayed(mt9release, 1500); if (newChar) { // consume single caps - if (mCapsMode == CAPS_SINGLE){ + if (mCapsMode == CAPS_SINGLE) { mCapsMode = CAPS_OFF; } } @@ -1084,7 +1084,7 @@ implements KeyboardView.OnKeyboardActionListener { case MODE_NUM: switch (keyCode) { - //Manual this + // Manual this case KeyEvent.KEYCODE_POUND: onText("#"); break; @@ -1092,7 +1092,7 @@ implements KeyboardView.OnKeyboardActionListener { onText("*"); break; default: - onText(String.valueOf(keyCode-KeyEvent.KEYCODE_0)); + onText(String.valueOf(keyCode - KeyEvent.KEYCODE_0)); } break; @@ -1107,9 +1107,11 @@ implements KeyboardView.OnKeyboardActionListener { // the underlying edit box in a somewhat reliable manner. // (somewhat because there are a few cases where this doesn't work properly or acts strangely.) private boolean handleDPAD(int keyCode, KeyEvent event, boolean keyDown) { - //Log.d("handleConsumeDPAD", "keyCode: " + keyCode + " isKeyDown: " + isKeyDown); + // Log.d("handleConsumeDPAD", "keyCode: " + keyCode + " isKeyDown: " + + // isKeyDown); if (keyDown) { - //track key, if seeing repeat count < 0, start sending this event and previous to super + // track key, if seeing repeat count < 0, start sending this event + // and previous to super if (event.getRepeatCount() == 0) { // store event mDPADkeyEvent = event; @@ -1126,7 +1128,8 @@ implements KeyboardView.OnKeyboardActionListener { } } } else { - // if we have been sending previous down events to super, do the same for up, else process the event + // if we have been sending previous down events to super, do the + // same for up, else process the event if (mIgnoreDPADKeyUp) { mIgnoreDPADKeyUp = false; return super.onKeyUp(keyCode, event); @@ -1142,45 +1145,49 @@ implements KeyboardView.OnKeyboardActionListener { case KeyEvent.KEYCODE_DPAD_LEFT: case KeyEvent.KEYCODE_DPAD_RIGHT: commitTyped(); -// getCurrentInputConnection().sendKeyEvent(mDPADkeyEvent); -// return super.onKeyUp(keyCode, event); + // getCurrentInputConnection().sendKeyEvent(mDPADkeyEvent); + // return super.onKeyUp(keyCode, event); return true; } } - switch(keyCode) { + switch (keyCode) { case KeyEvent.KEYCODE_DPAD_CENTER: handleMidButton(); return true; - default: - //Send stored event to input connection then pass current event onto super - getCurrentInputConnection().sendKeyEvent(mDPADkeyEvent); - return super.onKeyUp(keyCode, event); + default: + // Send stored event to input connection then pass current + // event onto super + getCurrentInputConnection().sendKeyEvent(mDPADkeyEvent); + return super.onKeyUp(keyCode, event); } } } } + private void commitReset() { commitTyped(getCurrentInputConnection()); charReset(); if (mCapsMode == CAPS_SINGLE) { mCapsMode = CAPS_OFF; } - //Log.d("commitReset", "CM pre: " + mCapsMode); + // Log.d("commitReset", "CM pre: " + mCapsMode); updateShiftKeyState(getCurrentInputEditorInfo()); - //Log.d("commitReset", "CM post: " + mCapsMode); + // Log.d("commitReset", "CM post: " + mCapsMode); } + private void charReset() { t9releasehandler.removeCallbacks(mt9release); mPrevious = -1; mCharIndex = 0; } + private void handleClose() { commitTyped(getCurrentInputConnection()); requestHideSelf(0); } protected void nextKeyMode() { - if (mKeyMode == MODE_CYCLE.length - 1) + if (mKeyMode == MODE_CYCLE.length - 1) mKeyMode = 0; else mKeyMode++; @@ -1197,9 +1204,10 @@ implements KeyboardView.OnKeyboardActionListener { mComposingI.setLength(0); getCurrentInputConnection().finishComposingText(); } + /** - * Set the status icon that is appropriate in current mode - * (based on openwmm-legacy) + * Set the status icon that is appropriate in current mode (based on + * openwmm-legacy) */ private void updateKeyMode() { int icon = 0; @@ -1225,7 +1233,7 @@ implements KeyboardView.OnKeyboardActionListener { } else { interfacehandler.showHold(true); } - switch (mCapsMode){ + switch (mCapsMode) { case CAPS_ALL: icon = R.drawable.ime_en_upper; break; @@ -1248,62 +1256,67 @@ implements KeyboardView.OnKeyboardActionListener { showStatusIcon(icon); } - private void pickSelectedCandidate(InputConnection ic) { pickSuggestionManually(-1, ic); } public void pickSuggestionManually(int index, InputConnection ic) { - //Log.d("pickSuggestMan", "Doing"); + // Log.d("pickSuggestMan", "Doing"); if (mComposing.length() > 0 || mComposingI.length() > 0) { // If we were generating candidate suggestions for the current - // text, we would commit one of them here. But for this sample, + // text, we would commit one of them here. But for this sample, // we will just commit the current text. if (!mSuggestionStrings.isEmpty()) { if (index < 0) { - //Log.d("pickSuggestMan", "picking SELECTED: " + mSuggestionStrings.get(mCandidateView.mSelectedIndex)); - //get and commit selected suggestion + // Log.d("pickSuggestMan", "picking SELECTED: " + + // mSuggestionStrings.get(mCandidateView.mSelectedIndex)); + // get and commit selected suggestion ic.commitText(mSuggestionStrings.get(mCandidateView.mSelectedIndex), 1); if (mKeyMode == MODE_EN) { - //update freq + // update freq db.incrementWord(mSuggestionInts.get(mCandidateView.mSelectedIndex)); } } else { - //commit suggestion index + // commit suggestion index ic.commitText(mSuggestionStrings.get(index), 1); if (mKeyMode == MODE_EN) { db.incrementWord(mSuggestionInts.get(index)); } } } - } + } } /** * Ignore this for now. */ + @Override public void swipeRight() { - // if (mPredictionOn) { - // pickDefaultCandidate(); - // } + // if (mPredictionOn) { + // pickDefaultCandidate(); + // } } + @Override public void swipeLeft() { handleBackspace(); } + @Override public void swipeDown() { handleClose(); } + @Override public void swipeUp() { } + @Override public void onPress(int primaryCode) { } + @Override public void onRelease(int primaryCode) { } } - diff --git a/src/org/nyanya/android/traditionalt9/TraditionalT9Settings.java b/src/org/nyanya/android/traditionalt9/TraditionalT9Settings.java index 20923f88..60bff5ef 100644 --- a/src/org/nyanya/android/traditionalt9/TraditionalT9Settings.java +++ b/src/org/nyanya/android/traditionalt9/TraditionalT9Settings.java @@ -35,29 +35,29 @@ import android.preference.PreferenceActivity; import android.util.Log; public class TraditionalT9Settings extends PreferenceActivity implements - DialogInterface.OnCancelListener { + DialogInterface.OnCancelListener { ProgressDialog pd = null; AsyncTask task = null; final String dictname = "dict50-utf8.jet"; final String backupname = "t9backup.txt"; final String backupdir = "traditionalt9"; - + final int BACKUP_Q_LIMIT = 1000; - + Context caller = null; - + private class Reply { public boolean status; public String message; - - protected Reply(){ + + protected Reply() { this.status = true; this.message = "None"; } - + } - + private void closeStream(Closeable is, Reply reply) { if (is == null) { return; @@ -70,10 +70,13 @@ public class TraditionalT9Settings extends PreferenceActivity implements reply.message = reply.message + "\n & Couldn't close stream: " + e.getMessage(); } } - + private class LoadDictTask extends AsyncTask { - /** The system calls this to perform work in a worker thread and - * delivers it the parameters given to AsyncTask.execute() */ + /** + * The system calls this to perform work in a worker thread and delivers + * it the parameters given to AsyncTask.execute() + */ + @Override protected Reply doInBackground(String... mode) { Reply reply = new Reply(); SQLiteDatabase db; @@ -82,13 +85,13 @@ public class TraditionalT9Settings extends PreferenceActivity implements long pos = 0; long last = 0; File backupfile = new File(Environment.getExternalStorageDirectory(), backupdir); - - if (mode[0].equals("backup")){ - //using external backup + + if (mode[0].equals("backup")) { + // using external backup backupfile = new File(backupfile, backupname); fsize = backupfile.length(); } else { - //using asset: + // using asset: AssetFileDescriptor descriptor; try { descriptor = getAssets().openFd(dictname); @@ -102,12 +105,11 @@ public class TraditionalT9Settings extends PreferenceActivity implements return reply; } } - - + db.setLockingEnabled(false); - + InsertHelper wordhelp = new InsertHelper(db, T9DB.WORD_TABLE_NAME); - + final int wordColumn = wordhelp.getColumnIndex(T9DB.COLUMN_WORD); final int freqColumn = wordhelp.getColumnIndex(T9DB.COLUMN_FREQUENCY); final int seqColumn = wordhelp.getColumnIndex(T9DB.COLUMN_SEQ); @@ -125,19 +127,19 @@ public class TraditionalT9Settings extends PreferenceActivity implements Log.d("doInBakground", "Adding dict..."); BufferedReader br; InputStream dictstream = null; - - if (mode[0].equals("backup")){ + + if (mode[0].equals("backup")) { try { - dictstream = new FileInputStream(backupfile); + dictstream = new FileInputStream(backupfile); } catch (FileNotFoundException e) { reply.status = false; reply.message = "Backup file not found: " + e.getMessage(); db.close(); - closeStream(dictstream, reply); // this is silly but it stops IDE nagging at me. + closeStream(dictstream, reply); // this is silly but it + // stops IDE nagging at me. return reply; } - } - else { + } else { try { dictstream = getAssets().open(dictname); } catch (IOException e) { @@ -159,7 +161,7 @@ public class TraditionalT9Settings extends PreferenceActivity implements closeStream(dictstream, reply); return reply; } - + String word; String[] ws; int freq; @@ -176,15 +178,15 @@ public class TraditionalT9Settings extends PreferenceActivity implements String seq; int linecount = 1; int wordlen; - + long startnow, endnow; startnow = SystemClock.uptimeMillis(); db.beginTransaction(); try { while (word != null) { if (isCancelled()) { - // this is useless because of dumb android bug that doesn't - // call onCancelled after this method finishes. + // this is useless because of dumb android bug that + // doesn't call onCancelled after this method finishes. reply.status = false; reply.message = "User cancelled."; break; @@ -193,7 +195,7 @@ public class TraditionalT9Settings extends PreferenceActivity implements ws = word.split(" "); word = ws[0]; try { - freq = Integer.parseInt(ws[1]); + freq = Integer.parseInt(ws[1]); } catch (NumberFormatException e) { reply.status = false; reply.message = "Number error."; @@ -214,7 +216,7 @@ public class TraditionalT9Settings extends PreferenceActivity implements return reply; } pos += wordlen; - try{ + try { seq = CharMap.getStringSequence(word); } catch (NullPointerException e) { reply.status = false; @@ -223,19 +225,20 @@ public class TraditionalT9Settings extends PreferenceActivity implements closeStream(dictstream, reply); return reply; } - + wordhelp.prepareForReplace(); wordhelp.bind(seqColumn, seq); wordhelp.bind(wordColumn, word); wordhelp.bind(freqColumn, freq); wordhelp.execute(); - - //System.out.println("Progress: " + pos + " Last: " + last + " fsize: " + fsize); + + // System.out.println("Progress: " + pos + " Last: " + last + // + " fsize: " + fsize); if ((pos - last) > 4096) { -// Log.d("doInBackground", "line: " + linecount); -// Log.d("doInBackground", "word: " + word); - publishProgress((int)((float)pos/fsize*10000)); + // Log.d("doInBackground", "line: " + linecount); + // Log.d("doInBackground", "word: " + word); + publishProgress((int) ((float) pos / fsize * 10000)); last = pos; } try { @@ -257,47 +260,58 @@ public class TraditionalT9Settings extends PreferenceActivity implements wordhelp.close(); } endnow = SystemClock.uptimeMillis(); - Log.d("TIMING", "Excution time: "+(endnow-startnow)+" ms"); + Log.d("TIMING", "Excution time: " + (endnow - startnow) + " ms"); Log.d("doInBackground", "line: " + linecount); db.close(); closeStream(dictstream, reply); return reply; } + @Override protected void onProgressUpdate(Integer... progress) { if (pd.isShowing()) { pd.setProgress(progress[0]); } - } - - protected void onCancelled() { - // Pointless callback. Thanks android. - } - - /** The system calls this to perform work in the UI thread and delivers - * the result from doInBackground() */ + } + + @Override + protected void onCancelled() { + // Pointless callback. Thanks android. + } + + /** + * The system calls this to perform work in the UI thread and delivers + * the result from doInBackground() + */ + @Override protected void onPostExecute(Reply result) { - if (pd == null){ - //Log.d("onPostExecute", "pd"); + if (pd == null) { + // Log.d("onPostExecute", "pd"); } else { - //Log.d("onPostExecute", "pd"); - pd.dismiss(); + // Log.d("onPostExecute", "pd"); + if (pd.isShowing()) { + pd.dismiss(); + } } - if (result == null){ - //bad thing happened + if (result == null) { + // bad thing happened Log.e("onPostExecute", "Bad things happen?"); } else { Log.d("onPostExecute", "Result: " + result.status + " " + result.message); if (!result.status) { - showErrorDialog(caller.getResources().getString(R.string.pref_restore_title), result.message); + showErrorDialog(caller.getResources().getString(R.string.pref_restore_title), + result.message); } } } } private class DumpDictTask extends AsyncTask { - /** The system calls this to perform work in a worker thread and - * delivers it the parameters given to AsyncTask.execute() */ + /** + * The system calls this to perform work in a worker thread and delivers + * it the parameters given to AsyncTask.execute() + */ + @Override protected Reply doInBackground(String... ignore) { Reply reply = new Reply(); SQLiteDatabase db; @@ -306,21 +320,23 @@ public class TraditionalT9Settings extends PreferenceActivity implements int current = 0; int pos = 0; int last = 0; - File backupfile = new File(new File(Environment.getExternalStorageDirectory(), backupdir), backupname); - + File backupfile = new File(new File(Environment.getExternalStorageDirectory(), + backupdir), backupname); + db.setLockingEnabled(false); - + Log.d("doInBakground", "Dumping dict..."); BufferedWriter bw; OutputStream dictstream = null; - + try { dictstream = new FileOutputStream(backupfile); } catch (FileNotFoundException e) { reply.status = false; reply.message = "Backup file error: " + e.getMessage(); db.close(); - closeStream(dictstream, reply); // this is silly but it stops IDE nagging at me. + closeStream(dictstream, reply); // this is silly but it stops + // IDE nagging at me. return reply; } @@ -336,24 +352,24 @@ public class TraditionalT9Settings extends PreferenceActivity implements } long startnow, endnow; startnow = SystemClock.uptimeMillis(); - + String q = "SELECT count(*) FROM " + T9DB.WORD_TABLE_NAME; Cursor cur = db.rawQuery(q, null); cur.moveToFirst(); entries = cur.getInt(0); - //pd.setMax((int)entries); + // pd.setMax((int)entries); cur.close(); - + while (current < entries) { - q = "SELECT " + T9DB.COLUMN_ID + ", " + T9DB.COLUMN_WORD + ", " + T9DB.COLUMN_FREQUENCY + - " FROM " + T9DB.WORD_TABLE_NAME + - " WHERE " + T9DB.COLUMN_ID + ">" + current + - " ORDER BY " + T9DB.COLUMN_ID + - " LIMIT " + BACKUP_Q_LIMIT; + q = "SELECT " + T9DB.COLUMN_ID + ", " + T9DB.COLUMN_WORD + ", " + + T9DB.COLUMN_FREQUENCY + " FROM " + T9DB.WORD_TABLE_NAME + " WHERE " + + T9DB.COLUMN_ID + ">" + current + " ORDER BY " + T9DB.COLUMN_ID + " LIMIT " + + BACKUP_Q_LIMIT; cur = db.rawQuery(q, null); - for(cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) { + for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) { if (isCancelled()) { - // this is useless because of dumb android bug that doesn't + // this is useless because of dumb android bug that + // doesn't // call onCancelled after this method finishes. reply.status = false; reply.message = "User cancelled."; @@ -375,7 +391,7 @@ public class TraditionalT9Settings extends PreferenceActivity implements return reply; // why complain? I closed the stream above } if ((pos - last) > 80) { - publishProgress((int)((float)current/entries*10000)); + publishProgress((int) ((float) current / entries * 10000)); last = current; } } @@ -384,7 +400,7 @@ public class TraditionalT9Settings extends PreferenceActivity implements publishProgress(100); endnow = SystemClock.uptimeMillis(); - Log.d("TIMING", "Excution time: "+(endnow-startnow)+" ms"); + Log.d("TIMING", "Excution time: " + (endnow - startnow) + " ms"); Log.d("doInBackground", "entries: " + entries + " last: " + pos); db.close(); try { @@ -396,40 +412,49 @@ public class TraditionalT9Settings extends PreferenceActivity implements return reply; } + @Override protected void onProgressUpdate(Integer... progress) { if (pd.isShowing()) { pd.setProgress(progress[0]); } - } - - protected void onCancelled() { - // Pointless callback. Thanks android. - } - - /** The system calls this to perform work in the UI thread and delivers - * the result from doInBackground() */ + } + + @Override + protected void onCancelled() { + // Pointless callback. Thanks android. + } + + /** + * The system calls this to perform work in the UI thread and delivers + * the result from doInBackground() + */ + @Override protected void onPostExecute(Reply result) { - if (pd == null){ - //Log.d("onPostExecute", "pd"); + if (pd == null) { + // Log.d("onPostExecute", "pd"); } else { - //Log.d("onPostExecute", "pd"); + // Log.d("onPostExecute", "pd"); pd.dismiss(); } - if (result == null){ - //bad thing happened + if (result == null) { + // bad thing happened Log.e("onPostExecute", "Bad things happen?"); } else { Log.d("onPostExecute", "Result: " + result.status + " " + result.message); if (!result.status) { - showErrorDialog(caller.getResources().getString(R.string.pref_backup_title), result.message); + showErrorDialog(caller.getResources().getString(R.string.pref_backup_title), + result.message); } } } } - + private class NukeDictTask extends AsyncTask { - /** The system calls this to perform work in a worker thread and - * delivers it the parameters given to AsyncTask.execute() */ + /** + * The system calls this to perform work in a worker thread and delivers + * it the parameters given to AsyncTask.execute() + */ + @Override protected Reply doInBackground(String... ignore) { Reply reply = new Reply(); Log.d("doInBakground", "Nuking dict..."); @@ -437,32 +462,37 @@ public class TraditionalT9Settings extends PreferenceActivity implements startnow = SystemClock.uptimeMillis(); T9DB t9db = new T9DB(caller); t9db.nuke(); - + endnow = SystemClock.uptimeMillis(); - Log.d("TIMING", "Excution time: "+(endnow-startnow)+" ms"); + Log.d("TIMING", "Excution time: " + (endnow - startnow) + " ms"); return reply; } - protected void onCancelled() { - // Pointless callback. Thanks android. - } - - /** The system calls this to perform work in the UI thread and delivers - * the result from doInBackground() */ + @Override + protected void onCancelled() { + // Pointless callback. Thanks android. + } + + /** + * The system calls this to perform work in the UI thread and delivers + * the result from doInBackground() + */ + @Override protected void onPostExecute(Reply result) { - if (pd == null){ - //Log.d("onPostExecute", "pd"); + if (pd == null) { + // Log.d("onPostExecute", "pd"); } else { - //Log.d("onPostExecute", "pd"); + // Log.d("onPostExecute", "pd"); pd.dismiss(); } - if (result == null){ - //bad thing happened + if (result == null) { + // bad thing happened Log.e("onPostExecute", "Bad things happen?"); } else { Log.d("onPostExecute", "Result: " + result.status + " " + result.message); if (!result.status) { - showErrorDialog(caller.getResources().getString(R.string.pref_nuke_title), result.message); + showErrorDialog(caller.getResources().getString(R.string.pref_nuke_title), + result.message); } } } @@ -472,7 +502,7 @@ public class TraditionalT9Settings extends PreferenceActivity implements protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.prefs); - Preference button = (Preference)getPreferenceManager().findPreference("loaddict"); + Preference button = getPreferenceManager().findPreference("loaddict"); if (button != null) { button.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override @@ -482,7 +512,7 @@ public class TraditionalT9Settings extends PreferenceActivity implements } }); } - button = (Preference)getPreferenceManager().findPreference("nukedict"); + button = getPreferenceManager().findPreference("nukedict"); if (button != null) { button.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override @@ -492,8 +522,8 @@ public class TraditionalT9Settings extends PreferenceActivity implements } }); } - - button = (Preference)getPreferenceManager().findPreference("backupdict"); + + button = getPreferenceManager().findPreference("backupdict"); if (button != null) { button.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override @@ -503,8 +533,8 @@ public class TraditionalT9Settings extends PreferenceActivity implements } }); } - - button = (Preference)getPreferenceManager().findPreference("restoredict"); + + button = getPreferenceManager().findPreference("restoredict"); if (button != null) { button.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override @@ -514,8 +544,8 @@ public class TraditionalT9Settings extends PreferenceActivity implements } }); } - - button = (Preference)getPreferenceManager().findPreference("querytest"); + + button = getPreferenceManager().findPreference("querytest"); if (button != null) { button.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override @@ -525,15 +555,15 @@ public class TraditionalT9Settings extends PreferenceActivity implements } }); } - + caller = this; } private void loadDict() { preloader(R.string.pref_loadingdict, ""); } - - private void preloader(int msgid, String mode){ + + private void preloader(int msgid, String mode) { pd = new ProgressDialog(this); pd.setMessage(getResources().getString(msgid)); pd.setOnCancelListener(this); @@ -543,19 +573,19 @@ public class TraditionalT9Settings extends PreferenceActivity implements task = new LoadDictTask(); task.execute(mode); } - + private void predumper(int msgid) { pd = new ProgressDialog(this); pd.setMessage(getResources().getString(msgid)); pd.setOnCancelListener(this); - //pd.setProgressNumberFormat(null); Why added in API11... + // pd.setProgressNumberFormat(null); Why added in API11... pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); pd.setMax(10000); pd.show(); task = new DumpDictTask(); task.execute(""); } - + private void prenuke(int msgid) { pd = new ProgressDialog(this); pd.setMessage(getResources().getString(msgid)); @@ -565,51 +595,51 @@ public class TraditionalT9Settings extends PreferenceActivity implements task = new NukeDictTask(); task.execute(""); } - + private void nukeDict() { AlertDialog.Builder builder = new AlertDialog.Builder(this); - builder.setMessage(R.string.pref_nuke_warn) - .setTitle(R.string.pref_nuke_title) - .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int id) { - prenuke(R.string.pref_nukingdict); - } - }) - .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int id) { - dialog.dismiss(); - } - }); + builder.setMessage(R.string.pref_nuke_warn).setTitle(R.string.pref_nuke_title) + .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int id) { + prenuke(R.string.pref_nukingdict); + } + }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int id) { + dialog.dismiss(); + } + }); AlertDialog dialog = builder.create(); dialog.show(); } - + private void backupDict() { AlertDialog.Builder builder = new AlertDialog.Builder(this); if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) { - + File saveloc = new File(Environment.getExternalStorageDirectory(), backupdir); saveloc.mkdirs(); - if (!saveloc.canWrite()){ + if (!saveloc.canWrite()) { Log.e("backupDict", "can't write : " + saveloc.getAbsolutePath()); showErrorDialogID(builder, R.string.pref_backup_title, R.string.pref_backup_noext); return; } - + saveloc = new File(saveloc, backupname); if (saveloc.exists()) { - builder.setMessage(R.string.pref_backup_warn) - .setTitle(R.string.pref_backup_title) - .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int id) { - predumper(R.string.pref_savingbackup); - } - }) - .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int id) { - dialog.dismiss(); - } - }); + builder.setMessage(R.string.pref_backup_warn).setTitle(R.string.pref_backup_title) + .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int id) { + predumper(R.string.pref_savingbackup); + } + }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int id) { + dialog.dismiss(); + } + }); AlertDialog dialog = builder.create(); dialog.show(); } else { @@ -619,126 +649,133 @@ public class TraditionalT9Settings extends PreferenceActivity implements showErrorDialogID(builder, R.string.pref_backup_title, R.string.pref_backup_noext); } } - + private void showErrorDialog(String title, String msg) { showErrorDialog(new AlertDialog.Builder(this), title, msg); } - + private void showErrorDialog(AlertDialog.Builder builder, String title, String msg) { - builder.setMessage(msg) - .setTitle(title) - .setNeutralButton(R.string.ok, new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int id) { - dialog.dismiss(); - } - }); + builder.setMessage(msg).setTitle(title) + .setNeutralButton(R.string.ok, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int id) { + dialog.dismiss(); + } + }); AlertDialog dialog = builder.create(); dialog.show(); } + private void showErrorDialogID(AlertDialog.Builder builder, int titleid, int msgid) { - builder.setMessage(msgid) - .setTitle(titleid) - .setNeutralButton(R.string.ok, new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int id) { - dialog.dismiss(); - } - }); + builder.setMessage(msgid).setTitle(titleid) + .setNeutralButton(R.string.ok, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int id) { + dialog.dismiss(); + } + }); AlertDialog dialog = builder.create(); dialog.show(); } - + private void restoreDict() { -// Environment.MEDIA_MOUNTED_READ_ONLY; -// Environment.MEDIA_MOUNTED; + // Environment.MEDIA_MOUNTED_READ_ONLY; + // Environment.MEDIA_MOUNTED; AlertDialog.Builder builder = new AlertDialog.Builder(this); - if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(Environment.getExternalStorageState()) || - Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) { - if ((new File(new File(Environment.getExternalStorageDirectory(), backupdir), backupname)).exists()) { - Resources res = getResources(); - builder.setMessage(res.getString(R.string.pref_restore_warn, res.getString(R.string.pref_nukedict))) - .setTitle(R.string.pref_restore_title) - .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int id) { - preloader(R.string.pref_loadingbackup, "backup"); - } - }) - .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int id) { - dialog.dismiss(); - } - }); - AlertDialog dialog = builder.create(); - dialog.show(); + if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(Environment.getExternalStorageState()) + || Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) { + if ((new File(new File(Environment.getExternalStorageDirectory(), backupdir), + backupname)).exists()) { + Resources res = getResources(); + builder + .setMessage( + res.getString(R.string.pref_restore_warn, + res.getString(R.string.pref_nukedict))) + .setTitle(R.string.pref_restore_title) + .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int id) { + preloader(R.string.pref_loadingbackup, "backup"); + } + }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int id) { + dialog.dismiss(); + } + }); + AlertDialog dialog = builder.create(); + dialog.show(); } else { - showErrorDialogID(builder, R.string.pref_restore_title, R.string.pref_restore_nofile); + showErrorDialogID(builder, R.string.pref_restore_title, + R.string.pref_restore_nofile); } } else { showErrorDialogID(builder, R.string.pref_restore_title, R.string.pref_restore_noext); } } - + @SuppressWarnings("unused") private void queryTestDebug() { long startnow, endnow; ArrayList words = new ArrayList(); ArrayList ids = new ArrayList(); - + startnow = SystemClock.uptimeMillis(); - + T9DB tdb = new T9DB(this); tdb.init(); Log.d("queryTestDebug", "Testing..."); - tdb.updateWords("123", words, ids, 0); - Log.d("queryTestDebug", "123->" + words.toString()); - Log.d("queryTestDebug", "269->"); - tdb.updateWords("269", words, ids, 0); - Iterator i = words.iterator(); - while (i.hasNext()){ - Log.d("queryTestDebug", "word: " + i.next()); - } - - Log.d("queryTestDebug", "228->"); - tdb.updateWords("228", words, ids, 0); - i = words.iterator(); - while (i.hasNext()){ - Log.d("queryTestDebug", "word: " + i.next()); - } + tdb.updateWords("123", words, ids, 0); + Log.d("queryTestDebug", "123->" + words.toString()); + Log.d("queryTestDebug", "269->"); + tdb.updateWords("269", words, ids, 0); + Iterator i = words.iterator(); + while (i.hasNext()) { + Log.d("queryTestDebug", "word: " + i.next()); + } + + Log.d("queryTestDebug", "228->"); + tdb.updateWords("228", words, ids, 0); + i = words.iterator(); + while (i.hasNext()) { + Log.d("queryTestDebug", "word: " + i.next()); + } endnow = SystemClock.uptimeMillis(); - Log.d("TIMING", "Excution time: "+(endnow-startnow)+" ms"); + Log.d("TIMING", "Excution time: " + (endnow - startnow) + " ms"); tdb.close(); } - + @SuppressWarnings("unused") private void queryTest() { long startnow, endnow; startnow = SystemClock.uptimeMillis(); - + T9DB tdb = new T9DB(this); tdb.init(); - -// tdb.getWords("123").iterator(); -// tdb.getWords("269").iterator(); -// tdb.getWords("228").iterator(); -// tdb.getWords("24371").iterator(); -// tdb.getWords("22376284").iterator(); -// tdb.getWords("68372667367283").iterator(); -// tdb.getWords("22637").iterator(); - + + // tdb.getWords("123").iterator(); + // tdb.getWords("269").iterator(); + // tdb.getWords("228").iterator(); + // tdb.getWords("24371").iterator(); + // tdb.getWords("22376284").iterator(); + // tdb.getWords("68372667367283").iterator(); + // tdb.getWords("22637").iterator(); + endnow = SystemClock.uptimeMillis(); - Log.d("TIMING", "Excution time: "+(endnow-startnow)+" ms"); + Log.d("TIMING", "Excution time: " + (endnow - startnow) + " ms"); tdb.close(); } - + private void queryTestSingle() { long startnow, endnow; int size; ArrayList words = new ArrayList(8); ArrayList ids = new ArrayList(8); startnow = SystemClock.uptimeMillis(); - + T9DB tdb = new T9DB(this); tdb.init(); - + tdb.updateWords("222", words, ids, 0); size = ids.size(); if (size > 0) { @@ -746,26 +783,26 @@ public class TraditionalT9Settings extends PreferenceActivity implements tdb.incrementWord(ids.get(0)); tdb.incrementWord(ids.get(0)); } - - for (int x=0; x freqs = new ArrayList(8); tdb.updateWordsW("222", words, ids, freqs); Log.d("VALUES", "..."); size = freqs.size(); - for (int x = 0; x < size; x++){ - Log.d("VALUES", "Word: " + words.get(x) + " id: " + ids.get(x) + " freq: " + freqs.get(x)); + for (int x = 0; x < size; x++) { + Log.d("VALUES", + "Word: " + words.get(x) + " id: " + ids.get(x) + " freq: " + freqs.get(x)); } Log.d("queryTestSingle", "done."); tdb.close(); } - - + @Override public void onCancel(DialogInterface dint) { task.cancel(false);