src/com/android/inputmethod/pinyin/PinyinIME.java

文章推薦指數: 80 %
投票人數:10人

* The current IME status. *. * @see com.android.inputmethod.pinyin.PinyinIME.ImeState. android/platform/packages/inputmethods/PinyinIME/40056ae7c2757681d88d2e226c4681281bd07129/./src/com/android/inputmethod/pinyin/PinyinIME.javablob:8a21858bde9f7eb6bea4f04e7051e2c1ea0342de[file][log][blame]/**Copyright(C)2009TheAndroidOpenSourceProject**LicensedundertheApacheLicense,Version2.0(the"License");*youmaynotusethisfileexceptincompliancewiththeLicense.*YoumayobtainacopyoftheLicenseat**http://www.apache.org/licenses/LICENSE-2.0**Unlessrequiredbyapplicablelaworagreedtoinwriting,software*distributedundertheLicenseisdistributedonan"ASIS"BASIS,*WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied.*SeetheLicenseforthespecificlanguagegoverningpermissionsand*limitationsundertheLicense.*/packagecom.android.inputmethod.pinyin;importandroid.app.AlertDialog;importandroid.content.BroadcastReceiver;importandroid.content.ComponentName;importandroid.content.Context;importandroid.content.DialogInterface;importandroid.content.Intent;importandroid.content.ServiceConnection;importandroid.content.res.Configuration;importandroid.inputmethodservice.InputMethodService;importandroid.os.Handler;importandroid.os.IBinder;importandroid.os.RemoteException;importandroid.preference.PreferenceManager;importandroid.util.Log;importandroid.view.Gravity;importandroid.view.GestureDetector;importandroid.view.LayoutInflater;importandroid.view.KeyEvent;importandroid.view.MotionEvent;importandroid.view.View;importandroid.view.Window;importandroid.view.WindowManager;importandroid.view.View.MeasureSpec;importandroid.view.ViewGroup.LayoutParams;importandroid.view.inputmethod.CompletionInfo;importandroid.view.inputmethod.InputConnection;importandroid.view.inputmethod.EditorInfo;importandroid.view.inputmethod.InputMethodManager;importandroid.widget.LinearLayout;importandroid.widget.PopupWindow;importjava.util.ArrayList;importjava.util.List;importjava.util.Vector;/***MainclassofthePinyininputmethod.*/publicclassPinyinIMEextendsInputMethodService{/***TAGfordebug.*/staticfinalStringTAG="PinyinIME";/***Ifisistrue,IMEwillsimulatekeyeventsfordeletekey,andsendthe*eventsbacktotheapplication.*/privatestaticfinalbooleanSIMULATE_KEY_DELETE=true;/***NecessaryenvironmentconfigurationslikescreensizeforthisIME.*/privateEnvironmentmEnvironment;/***Usedtoswitchinputmode.*/privateInputModeSwitchermInputModeSwitcher;/***Softkeyboardcontainerviewtohostrealsoftkeyboardview.*/privateSkbContainermSkbContainer;/***Thefloatingcontainerwhichcontainsthecomposingview.Ifnecessary,*someotherviewlikecandiatescontainercanalsobeputhere.*/privateLinearLayoutmFloatingContainer;/***Viewtoshowthecomposingstring.*/privateComposingViewmComposingView;/***Windowtoshowthecomposingstring.*/privatePopupWindowmFloatingWindow;/***Usedtoshowthefloatingwindow.*/privatePopupTimermFloatingWindowTimer=newPopupTimer();/***Viewtoshowcandidateslist.*/privateCandidatesContainermCandidatesContainer;/***Balloonusedwhenuserpressesacandidate.*/privateBalloonHintmCandidatesBalloon;/***Usedtonotifytheinputmethodwhentheusertouchacandidate.*/privateChoiceNotifiermChoiceNotifier;/***Usedtonotifygesturesfromsoftkeyboard.*/privateOnGestureListenermGestureListenerSkb;/***Usedtonotifygesturesfromcandidatesview.*/privateOnGestureListenermGestureListenerCandidates;/***Theon-screenmovementgesturedetectorforsoftkeyboard.*/privateGestureDetectormGestureDetectorSkb;/***Theon-screenmovementgesturedetectorforcandidatesview.*/privateGestureDetectormGestureDetectorCandidates;/***OptiondialogtochoosesettingsandotherIMEs.*/privateAlertDialogmOptionsDialog;/***Connectionusedtobindthedecodingservice.*/privatePinyinDecoderServiceConnectionmPinyinDecoderServiceConnection;/***ThecurrentIMEstatus.**@seecom.android.inputmethod.pinyin.PinyinIME.ImeState*/privateImeStatemImeState=ImeState.STATE_IDLE;/***Thedecodinginformation,includespelling(Pinyin)string,decoding*result,etc.*/privateDecodingInfomDecInfo=newDecodingInfo();/***ForEnglishinput.*/privateEnglishInputProcessormImEn;//receiveringermodechangesprivateBroadcastReceivermReceiver=newBroadcastReceiver(){@OverridepublicvoidonReceive(Contextcontext,Intentintent){SoundManager.getInstance(context).updateRingerMode();}};@OverridepublicvoidonCreate(){mEnvironment=Environment.getInstance();if(mEnvironment.needDebug()){Log.d(TAG,"onCreate.");}super.onCreate();startPinyinDecoderService();mImEn=newEnglishInputProcessor();Settings.getInstance(PreferenceManager.getDefaultSharedPreferences(getApplicationContext()));mInputModeSwitcher=newInputModeSwitcher(this);mChoiceNotifier=newChoiceNotifier(this);mGestureListenerSkb=newOnGestureListener(false);mGestureListenerCandidates=newOnGestureListener(true);mGestureDetectorSkb=newGestureDetector(this,mGestureListenerSkb);mGestureDetectorCandidates=newGestureDetector(this,mGestureListenerCandidates);mEnvironment.onConfigurationChanged(getResources().getConfiguration(),this);}@OverridepublicvoidonDestroy(){if(mEnvironment.needDebug()){Log.d(TAG,"onDestroy.");}unbindService(mPinyinDecoderServiceConnection);Settings.releaseInstance();super.onDestroy();}@OverridepublicvoidonConfigurationChanged(ConfigurationnewConfig){Environmentenv=Environment.getInstance();if(mEnvironment.needDebug()){Log.d(TAG,"onConfigurationChanged");Log.d(TAG,"--lastconfig:"+env.getConfiguration().toString());Log.d(TAG,"---newconfig:"+newConfig.toString());}//WeneedtochangethelocalenvironmentfirstsothatUIcomponents//cangettheenvironmentinstancetohandlesizeissues.When//super.onConfigurationChanged()iscalled,onCreateCandidatesView()//andonCreateInputView()willbeexecutedifnecessary.env.onConfigurationChanged(newConfig,this);//ClearrelatedUIofthepreviousconfiguration.if(null!=mSkbContainer){mSkbContainer.dismissPopups();}if(null!=mCandidatesBalloon){mCandidatesBalloon.dismiss();}super.onConfigurationChanged(newConfig);resetToIdleState(false);}@OverridepublicbooleanonKeyDown(intkeyCode,KeyEventevent){if(processKey(event,0!=event.getRepeatCount()))returntrue;returnsuper.onKeyDown(keyCode,event);}@OverridepublicbooleanonKeyUp(intkeyCode,KeyEventevent){if(processKey(event,true))returntrue;returnsuper.onKeyUp(keyCode,event);}privatebooleanprocessKey(KeyEventevent,booleanrealAction){if(ImeState.STATE_BYPASS==mImeState)returnfalse;intkeyCode=event.getKeyCode();//SHIFT-SPACEisusedtoswitchbetweenChineseandEnglish//whenHKBison.if(KeyEvent.KEYCODE_SPACE==keyCode&&event.isShiftPressed()){if(!realAction)returntrue;updateIcon(mInputModeSwitcher.switchLanguageWithHkb());resetToIdleState(false);intallMetaState=KeyEvent.META_ALT_ON|KeyEvent.META_ALT_LEFT_ON|KeyEvent.META_ALT_RIGHT_ON|KeyEvent.META_SHIFT_ON|KeyEvent.META_SHIFT_LEFT_ON|KeyEvent.META_SHIFT_RIGHT_ON|KeyEvent.META_SYM_ON;getCurrentInputConnection().clearMetaKeyStates(allMetaState);returntrue;}//IfHKBisontoinputEnglish,by-passthekeyeventsothat//defaultkeylistenerwillhandleit.if(mInputModeSwitcher.isEnglishWithHkb()){returnfalse;}if(processFunctionKeys(keyCode,realAction)){returntrue;}intkeyChar=0;if(keyCode>=KeyEvent.KEYCODE_A&&keyCode<=KeyEvent.KEYCODE_Z){keyChar=keyCode-KeyEvent.KEYCODE_A+'a';}elseif(keyCode>=KeyEvent.KEYCODE_0&&keyCode<=KeyEvent.KEYCODE_9){keyChar=keyCode-KeyEvent.KEYCODE_0+'0';}elseif(keyCode==KeyEvent.KEYCODE_COMMA){keyChar=',';}elseif(keyCode==KeyEvent.KEYCODE_PERIOD){keyChar='.';}elseif(keyCode==KeyEvent.KEYCODE_SPACE){keyChar='';}elseif(keyCode==KeyEvent.KEYCODE_APOSTROPHE){keyChar='\'';}if(mInputModeSwitcher.isEnglishWithSkb()){returnmImEn.processKey(getCurrentInputConnection(),event,mInputModeSwitcher.isEnglishUpperCaseWithSkb(),realAction);}elseif(mInputModeSwitcher.isChineseText()){if(mImeState==ImeState.STATE_IDLE||mImeState==ImeState.STATE_APP_COMPLETION){mImeState=ImeState.STATE_IDLE;returnprocessStateIdle(keyChar,keyCode,event,realAction);}elseif(mImeState==ImeState.STATE_INPUT){returnprocessStateInput(keyChar,keyCode,event,realAction);}elseif(mImeState==ImeState.STATE_PREDICT){returnprocessStatePredict(keyChar,keyCode,event,realAction);}elseif(mImeState==ImeState.STATE_COMPOSING){returnprocessStateEditComposing(keyChar,keyCode,event,realAction);}}else{if(0!=keyChar&&realAction){commitResultText(String.valueOf((char)keyChar));}}returnfalse;}//keyCodecanbefrombothhardkeyorsoftkey.privatebooleanprocessFunctionKeys(intkeyCode,booleanrealAction){//BackkeyisusedtodismissallpopupUIinasoftkeyboard.if(keyCode==KeyEvent.KEYCODE_BACK){if(isInputViewShown()){if(mSkbContainer.handleBack(realAction))returntrue;}}//Chineserelatedinputishandleseparately.if(mInputModeSwitcher.isChineseText()){returnfalse;}if(null!=mCandidatesContainer&&mCandidatesContainer.isShown()&&!mDecInfo.isCandidatesListEmpty()){if(keyCode==KeyEvent.KEYCODE_DPAD_CENTER){if(!realAction)returntrue;chooseCandidate(-1);returntrue;}if(keyCode==KeyEvent.KEYCODE_DPAD_LEFT){if(!realAction)returntrue;mCandidatesContainer.activeCurseBackward();returntrue;}if(keyCode==KeyEvent.KEYCODE_DPAD_RIGHT){if(!realAction)returntrue;mCandidatesContainer.activeCurseForward();returntrue;}if(keyCode==KeyEvent.KEYCODE_DPAD_UP){if(!realAction)returntrue;mCandidatesContainer.pageBackward(false,true);returntrue;}if(keyCode==KeyEvent.KEYCODE_DPAD_DOWN){if(!realAction)returntrue;mCandidatesContainer.pageForward(false,true);returntrue;}if(keyCode==KeyEvent.KEYCODE_DEL&&ImeState.STATE_PREDICT==mImeState){if(!realAction)returntrue;resetToIdleState(false);returntrue;}}else{if(keyCode==KeyEvent.KEYCODE_DEL){if(!realAction)returntrue;if(SIMULATE_KEY_DELETE){simulateKeyEventDownUp(keyCode);}else{getCurrentInputConnection().deleteSurroundingText(1,0);}returntrue;}if(keyCode==KeyEvent.KEYCODE_ENTER){if(!realAction)returntrue;sendKeyChar('\n');returntrue;}if(keyCode==KeyEvent.KEYCODE_SPACE){if(!realAction)returntrue;sendKeyChar('');returntrue;}}returnfalse;}privatebooleanprocessStateIdle(intkeyChar,intkeyCode,KeyEventevent,booleanrealAction){//Inthisstatus,whenuserpresseskeysin[a..z],thestatuswill//changetoinputstate.if(keyChar>='a'&&keyChar<='z'&&!event.isAltPressed()){if(!realAction)returntrue;mDecInfo.addSplChar((char)keyChar,true);chooseAndUpdate(-1);returntrue;}elseif(keyCode==KeyEvent.KEYCODE_DEL){if(!realAction)returntrue;if(SIMULATE_KEY_DELETE){simulateKeyEventDownUp(keyCode);}else{getCurrentInputConnection().deleteSurroundingText(1,0);}returntrue;}elseif(keyCode==KeyEvent.KEYCODE_ENTER){if(!realAction)returntrue;sendKeyChar('\n');returntrue;}elseif(keyCode==KeyEvent.KEYCODE_ALT_LEFT||keyCode==KeyEvent.KEYCODE_ALT_RIGHT||keyCode==KeyEvent.KEYCODE_SHIFT_LEFT||keyCode==KeyEvent.KEYCODE_SHIFT_RIGHT){returntrue;}elseif(event.isAltPressed()){charfullwidth_char=KeyMapDream.getChineseLabel(keyCode);if(0!=fullwidth_char){if(realAction){Stringresult=String.valueOf(fullwidth_char);commitResultText(result);}returntrue;}else{if(keyCode>=KeyEvent.KEYCODE_A&&keyCode<=KeyEvent.KEYCODE_Z){returntrue;}}}elseif(keyChar!=0&&keyChar!='\t'){if(realAction){if(keyChar==','||keyChar=='.'){inputCommaPeriod("",keyChar,false,ImeState.STATE_IDLE);}else{if(0!=keyChar){Stringresult=String.valueOf((char)keyChar);commitResultText(result);}}}returntrue;}returnfalse;}privatebooleanprocessStateInput(intkeyChar,intkeyCode,KeyEventevent,booleanrealAction){//IfALTkeyispressed,inputalternativekey.Butifthe//alternativekeyisquotekey,itwillbeusedforinputasplitter//inPinyinstring.if(event.isAltPressed()){if('\''!=event.getUnicodeChar(event.getMetaState())){if(realAction){charfullwidth_char=KeyMapDream.getChineseLabel(keyCode);if(0!=fullwidth_char){commitResultText(mDecInfo.getCurrentFullSent(mCandidatesContainer.getActiveCandiatePos())+String.valueOf(fullwidth_char));resetToIdleState(false);}}returntrue;}else{keyChar='\'';}}if(keyChar>='a'&&keyChar<='z'||keyChar=='\''&&!mDecInfo.charBeforeCursorIsSeparator()||keyCode==KeyEvent.KEYCODE_DEL){if(!realAction)returntrue;returnprocessSurfaceChange(keyChar,keyCode);}elseif(keyChar==','||keyChar=='.'){if(!realAction)returntrue;inputCommaPeriod(mDecInfo.getCurrentFullSent(mCandidatesContainer.getActiveCandiatePos()),keyChar,true,ImeState.STATE_IDLE);returntrue;}elseif(keyCode==KeyEvent.KEYCODE_DPAD_UP||keyCode==KeyEvent.KEYCODE_DPAD_DOWN||keyCode==KeyEvent.KEYCODE_DPAD_LEFT||keyCode==KeyEvent.KEYCODE_DPAD_RIGHT){if(!realAction)returntrue;if(keyCode==KeyEvent.KEYCODE_DPAD_LEFT){mCandidatesContainer.activeCurseBackward();}elseif(keyCode==KeyEvent.KEYCODE_DPAD_RIGHT){mCandidatesContainer.activeCurseForward();}elseif(keyCode==KeyEvent.KEYCODE_DPAD_UP){//Ifithasbeenthefirstpage,aupkeywillshift//thestatetoeditcomposingstring.if(!mCandidatesContainer.pageBackward(false,true)){mCandidatesContainer.enableActiveHighlight(false);changeToStateComposing(true);updateComposingText(true);}}elseif(keyCode==KeyEvent.KEYCODE_DPAD_DOWN){mCandidatesContainer.pageForward(false,true);}returntrue;}elseif(keyCode>=KeyEvent.KEYCODE_1&&keyCode<=KeyEvent.KEYCODE_9){if(!realAction)returntrue;intactivePos=keyCode-KeyEvent.KEYCODE_1;intcurrentPage=mCandidatesContainer.getCurrentPage();if(activePos=0){chooseAndUpdate(activePos);}}returntrue;}elseif(keyCode==KeyEvent.KEYCODE_ENTER){if(!realAction)returntrue;if(mInputModeSwitcher.isEnterNoramlState()){commitResultText(mDecInfo.getOrigianlSplStr().toString());resetToIdleState(false);}else{commitResultText(mDecInfo.getCurrentFullSent(mCandidatesContainer.getActiveCandiatePos()));sendKeyChar('\n');resetToIdleState(false);}returntrue;}elseif(keyCode==KeyEvent.KEYCODE_DPAD_CENTER||keyCode==KeyEvent.KEYCODE_SPACE){if(!realAction)returntrue;chooseCandidate(-1);returntrue;}elseif(keyCode==KeyEvent.KEYCODE_BACK){if(!realAction)returntrue;resetToIdleState(false);requestHideSelf(0);returntrue;}returnfalse;}privatebooleanprocessStatePredict(intkeyChar,intkeyCode,KeyEventevent,booleanrealAction){if(!realAction)returntrue;//IfALTkeyispressed,inputalternativekey.if(event.isAltPressed()){charfullwidth_char=KeyMapDream.getChineseLabel(keyCode);if(0!=fullwidth_char){commitResultText(mDecInfo.getCandidate(mCandidatesContainer.getActiveCandiatePos())+String.valueOf(fullwidth_char));resetToIdleState(false);}returntrue;}//Inthisstatus,whenuserpresseskeysin[a..z],thestatuswill//changetoinputstate.if(keyChar>='a'&&keyChar<='z'){changeToStateInput(true);mDecInfo.addSplChar((char)keyChar,true);chooseAndUpdate(-1);}elseif(keyChar==','||keyChar=='.'){inputCommaPeriod("",keyChar,true,ImeState.STATE_IDLE);}elseif(keyCode==KeyEvent.KEYCODE_DPAD_UP||keyCode==KeyEvent.KEYCODE_DPAD_DOWN||keyCode==KeyEvent.KEYCODE_DPAD_LEFT||keyCode==KeyEvent.KEYCODE_DPAD_RIGHT){if(keyCode==KeyEvent.KEYCODE_DPAD_LEFT){mCandidatesContainer.activeCurseBackward();}if(keyCode==KeyEvent.KEYCODE_DPAD_RIGHT){mCandidatesContainer.activeCurseForward();}if(keyCode==KeyEvent.KEYCODE_DPAD_UP){mCandidatesContainer.pageBackward(false,true);}if(keyCode==KeyEvent.KEYCODE_DPAD_DOWN){mCandidatesContainer.pageForward(false,true);}}elseif(keyCode==KeyEvent.KEYCODE_DEL){resetToIdleState(false);}elseif(keyCode==KeyEvent.KEYCODE_BACK){resetToIdleState(false);requestHideSelf(0);}elseif(keyCode>=KeyEvent.KEYCODE_1&&keyCode<=KeyEvent.KEYCODE_9){intactivePos=keyCode-KeyEvent.KEYCODE_1;intcurrentPage=mCandidatesContainer.getCurrentPage();if(activePos=0){chooseAndUpdate(activePos);}}}elseif(keyCode==KeyEvent.KEYCODE_ENTER){sendKeyChar('\n');resetToIdleState(false);}elseif(keyCode==KeyEvent.KEYCODE_DPAD_CENTER||keyCode==KeyEvent.KEYCODE_SPACE){chooseCandidate(-1);}returntrue;}privatebooleanprocessStateEditComposing(intkeyChar,intkeyCode,KeyEventevent,booleanrealAction){if(!realAction)returntrue;ComposingView.ComposingStatuscmpsvStatus=mComposingView.getComposingStatus();//IfALTkeyispressed,inputalternativekey.Butifthe//alternativekeyisquotekey,itwillbeusedforinputasplitter//inPinyinstring.if(event.isAltPressed()){if('\''!=event.getUnicodeChar(event.getMetaState())){charfullwidth_char=KeyMapDream.getChineseLabel(keyCode);if(0!=fullwidth_char){StringretStr;if(ComposingView.ComposingStatus.SHOW_STRING_LOWERCASE==cmpsvStatus){retStr=mDecInfo.getOrigianlSplStr().toString();}else{retStr=mDecInfo.getComposingStr();}commitResultText(retStr+String.valueOf(fullwidth_char));resetToIdleState(false);}returntrue;}else{keyChar='\'';}}if(keyCode==KeyEvent.KEYCODE_DPAD_DOWN){if(!mDecInfo.selectionFinished()){changeToStateInput(true);}}elseif(keyCode==KeyEvent.KEYCODE_DPAD_LEFT||keyCode==KeyEvent.KEYCODE_DPAD_RIGHT){mComposingView.moveCursor(keyCode);}elseif((keyCode==KeyEvent.KEYCODE_ENTER&&mInputModeSwitcher.isEnterNoramlState())||keyCode==KeyEvent.KEYCODE_DPAD_CENTER||keyCode==KeyEvent.KEYCODE_SPACE){if(ComposingView.ComposingStatus.SHOW_STRING_LOWERCASE==cmpsvStatus){Stringstr=mDecInfo.getOrigianlSplStr().toString();if(!tryInputRawUnicode(str)){commitResultText(str);}}elseif(ComposingView.ComposingStatus.EDIT_PINYIN==cmpsvStatus){Stringstr=mDecInfo.getComposingStr();if(!tryInputRawUnicode(str)){commitResultText(str);}}else{commitResultText(mDecInfo.getComposingStr());}resetToIdleState(false);}elseif(keyCode==KeyEvent.KEYCODE_ENTER&&!mInputModeSwitcher.isEnterNoramlState()){StringretStr;if(!mDecInfo.isCandidatesListEmpty()){retStr=mDecInfo.getCurrentFullSent(mCandidatesContainer.getActiveCandiatePos());}else{retStr=mDecInfo.getComposingStr();}commitResultText(retStr);sendKeyChar('\n');resetToIdleState(false);}elseif(keyCode==KeyEvent.KEYCODE_BACK){resetToIdleState(false);requestHideSelf(0);returntrue;}else{returnprocessSurfaceChange(keyChar,keyCode);}returntrue;}privatebooleantryInputRawUnicode(Stringstr){if(str.length()>7){if(str.substring(0,7).compareTo("unicode")==0){try{StringdigitStr=str.substring(7);intstartPos=0;intradix=10;if(digitStr.length()>2&&digitStr.charAt(0)=='0'&&digitStr.charAt(1)=='x'){startPos=2;radix=16;}digitStr=digitStr.substring(startPos);intunicode=Integer.parseInt(digitStr,radix);if(unicode>0){charlow=(char)(unicode&0x0000ffff);charhigh=(char)((unicode&0xffff0000)>>16);commitResultText(String.valueOf(low));if(0!=high){commitResultText(String.valueOf(high));}}returntrue;}catch(NumberFormatExceptione){returnfalse;}}elseif(str.substring(str.length()-7,str.length()).compareTo("unicode")==0){StringresultStr="";for(intpos=0;pos0){resultStr+="";}resultStr+="0x"+Integer.toHexString(str.charAt(pos));}commitResultText(String.valueOf(resultStr));returntrue;}}returnfalse;}privatebooleanprocessSurfaceChange(intkeyChar,intkeyCode){if(mDecInfo.isSplStrFull()&&KeyEvent.KEYCODE_DEL!=keyCode){returntrue;}if((keyChar>='a'&&keyChar<='z')||(keyChar=='\''&&!mDecInfo.charBeforeCursorIsSeparator())||(((keyChar>='0'&&keyChar<='9')||keyChar=='')&&ImeState.STATE_COMPOSING==mImeState)){mDecInfo.addSplChar((char)keyChar,false);chooseAndUpdate(-1);}elseif(keyCode==KeyEvent.KEYCODE_DEL){mDecInfo.prepareDeleteBeforeCursor();chooseAndUpdate(-1);}returntrue;}privatevoidchangeToStateComposing(booleanupdateUi){mImeState=ImeState.STATE_COMPOSING;if(!updateUi)return;if(null!=mSkbContainer&&mSkbContainer.isShown()){mSkbContainer.toggleCandidateMode(true);}}privatevoidchangeToStateInput(booleanupdateUi){mImeState=ImeState.STATE_INPUT;if(!updateUi)return;if(null!=mSkbContainer&&mSkbContainer.isShown()){mSkbContainer.toggleCandidateMode(true);}showCandidateWindow(true);}privatevoidsimulateKeyEventDownUp(intkeyCode){InputConnectionic=getCurrentInputConnection();if(null==ic)return;ic.sendKeyEvent(newKeyEvent(KeyEvent.ACTION_DOWN,keyCode));ic.sendKeyEvent(newKeyEvent(KeyEvent.ACTION_UP,keyCode));}privatevoidcommitResultText(StringresultText){InputConnectionic=getCurrentInputConnection();if(null!=ic)ic.commitText(resultText,1);if(null!=mComposingView){mComposingView.setVisibility(View.INVISIBLE);mComposingView.invalidate();}}privatevoidupdateComposingText(booleanvisible){if(!visible){mComposingView.setVisibility(View.INVISIBLE);}else{mComposingView.setDecodingInfo(mDecInfo,mImeState);mComposingView.setVisibility(View.VISIBLE);}mComposingView.invalidate();}privatevoidinputCommaPeriod(StringpreEdit,intkeyChar,booleandismissCandWindow,ImeStatenextState){if(keyChar==',')preEdit+='\uff0c';elseif(keyChar=='.')preEdit+='\u3002';elsereturn;commitResultText(preEdit);if(dismissCandWindow)resetCandidateWindow();mImeState=nextState;}privatevoidresetToIdleState(booleanresetInlineText){if(ImeState.STATE_IDLE==mImeState)return;mImeState=ImeState.STATE_IDLE;mDecInfo.reset();if(null!=mComposingView)mComposingView.reset();if(resetInlineText)commitResultText("");resetCandidateWindow();}privatevoidchooseAndUpdate(intcandId){if(!mInputModeSwitcher.isChineseText()){Stringchoice=mDecInfo.getCandidate(candId);if(null!=choice){commitResultText(choice);}resetToIdleState(false);return;}if(ImeState.STATE_PREDICT!=mImeState){//Getresultcandidatelist,ifchoice_id<0,doanewdecoding.//Ifchoice_id>=0,selectthecandidate,andgetthenewcandidate//list.mDecInfo.chooseDecodingCandidate(candId);}else{//Chooseapredictionitem.mDecInfo.choosePredictChoice(candId);}if(mDecInfo.getComposingStr().length()>0){StringresultStr;resultStr=mDecInfo.getComposingStrActivePart();//choiceId>=0meansuserfinishesachoiceselection.if(candId>=0&&mDecInfo.canDoPrediction()){commitResultText(resultStr);mImeState=ImeState.STATE_PREDICT;if(null!=mSkbContainer&&mSkbContainer.isShown()){mSkbContainer.toggleCandidateMode(false);}//Trytogetthepredictionlist.if(Settings.getPrediction()){InputConnectionic=getCurrentInputConnection();if(null!=ic){CharSequencecs=ic.getTextBeforeCursor(3,0);if(null!=cs){mDecInfo.preparePredicts(cs);}}}else{mDecInfo.resetCandidates();}if(mDecInfo.mCandidatesList.size()>0){showCandidateWindow(false);}else{resetToIdleState(false);}}else{if(ImeState.STATE_IDLE==mImeState){if(mDecInfo.getSplStrDecodedLen()==0){changeToStateComposing(true);}else{changeToStateInput(true);}}else{if(mDecInfo.selectionFinished()){changeToStateComposing(true);}}showCandidateWindow(true);}}else{resetToIdleState(false);}}//IfactiveCandNoislessthan0,getthecurrentactivecandidatenumber//fromcandidateview,otherwiseuseactiveCandNo.privatevoidchooseCandidate(intactiveCandNo){if(activeCandNo<0){activeCandNo=mCandidatesContainer.getActiveCandiatePos();}if(activeCandNo>=0){chooseAndUpdate(activeCandNo);}}privatebooleanstartPinyinDecoderService(){if(null==mDecInfo.mIPinyinDecoderService){IntentserviceIntent=newIntent();serviceIntent.setClass(this,PinyinDecoderService.class);if(null==mPinyinDecoderServiceConnection){mPinyinDecoderServiceConnection=newPinyinDecoderServiceConnection();}//Bindserviceif(bindService(serviceIntent,mPinyinDecoderServiceConnection,Context.BIND_AUTO_CREATE)){returntrue;}else{returnfalse;}}returntrue;}@OverridepublicViewonCreateCandidatesView(){if(mEnvironment.needDebug()){Log.d(TAG,"onCreateCandidatesView.");}LayoutInflaterinflater=getLayoutInflater();//InflatethefloatingcontainerviewmFloatingContainer=(LinearLayout)inflater.inflate(R.layout.floating_container,null);//Thefirstchildisthecomposingview.mComposingView=(ComposingView)mFloatingContainer.getChildAt(0);mCandidatesContainer=(CandidatesContainer)inflater.inflate(R.layout.candidates_container,null);//Createballoonhintforcandidatesview.mCandidatesBalloon=newBalloonHint(this,mCandidatesContainer,MeasureSpec.UNSPECIFIED);mCandidatesBalloon.setBalloonBackground(getResources().getDrawable(R.drawable.candidate_balloon_bg));mCandidatesContainer.initialize(mChoiceNotifier,mCandidatesBalloon,mGestureDetectorCandidates);//Thefloatingwindowif(null!=mFloatingWindow&&mFloatingWindow.isShowing()){mFloatingWindowTimer.cancelShowing();mFloatingWindow.dismiss();}mFloatingWindow=newPopupWindow(this);mFloatingWindow.setClippingEnabled(false);mFloatingWindow.setBackgroundDrawable(null);mFloatingWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED);mFloatingWindow.setContentView(mFloatingContainer);setCandidatesViewShown(true);returnmCandidatesContainer;}publicvoidresponseSoftKeyEvent(SoftKeysKey){if(null==sKey)return;InputConnectionic=getCurrentInputConnection();if(ic==null)return;intkeyCode=sKey.getKeyCode();//Processsomegeneralkeys,includingKEYCODE_DEL,KEYCODE_SPACE,//KEYCODE_ENTERandKEYCODE_DPAD_CENTER.if(sKey.isKeyCodeKey()){if(processFunctionKeys(keyCode,true))return;}if(sKey.isUserDefKey()){updateIcon(mInputModeSwitcher.switchModeForUserKey(keyCode));resetToIdleState(false);mSkbContainer.updateInputMode();}else{if(sKey.isKeyCodeKey()){KeyEventeDown=newKeyEvent(0,0,KeyEvent.ACTION_DOWN,keyCode,0,0,0,0,KeyEvent.FLAG_SOFT_KEYBOARD);KeyEventeUp=newKeyEvent(0,0,KeyEvent.ACTION_UP,keyCode,0,0,0,0,KeyEvent.FLAG_SOFT_KEYBOARD);onKeyDown(keyCode,eDown);onKeyUp(keyCode,eUp);}elseif(sKey.isUniStrKey()){booleankUsed=false;StringkeyLabel=sKey.getKeyLabel();if(mInputModeSwitcher.isChineseTextWithSkb()&&(ImeState.STATE_INPUT==mImeState||ImeState.STATE_COMPOSING==mImeState)){if(mDecInfo.length()>0&&keyLabel.length()==1&&keyLabel.charAt(0)=='\''){processSurfaceChange('\'',0);kUsed=true;}}if(!kUsed){if(ImeState.STATE_INPUT==mImeState){commitResultText(mDecInfo.getCurrentFullSent(mCandidatesContainer.getActiveCandiatePos()));}elseif(ImeState.STATE_COMPOSING==mImeState){commitResultText(mDecInfo.getComposingStr());}commitResultText(keyLabel);resetToIdleState(false);}}//Ifthecurrentsoftkeyboardisnotsticky,IMEneedstogo//backtotheprevioussoftkeyboardautomatically.if(!mSkbContainer.isCurrentSkbSticky()){updateIcon(mInputModeSwitcher.requestBackToPreviousSkb());resetToIdleState(false);mSkbContainer.updateInputMode();}}}privatevoidshowCandidateWindow(booleanshowComposingView){if(mEnvironment.needDebug()){Log.d(TAG,"Candidateswindowisshown.Parent="+mCandidatesContainer);}setCandidatesViewShown(true);if(null!=mSkbContainer)mSkbContainer.requestLayout();if(null==mCandidatesContainer){resetToIdleState(false);return;}updateComposingText(showComposingView);mCandidatesContainer.showCandidates(mDecInfo,ImeState.STATE_COMPOSING!=mImeState);mFloatingWindowTimer.postShowFloatingWindow();}privatevoiddismissCandidateWindow(){if(mEnvironment.needDebug()){Log.d(TAG,"Candidateswindowistobedismissed");}if(null==mCandidatesContainer)return;try{mFloatingWindowTimer.cancelShowing();mFloatingWindow.dismiss();}catch(Exceptione){Log.e(TAG,"FailtoshowthePopupWindow.");}setCandidatesViewShown(false);if(null!=mSkbContainer&&mSkbContainer.isShown()){mSkbContainer.toggleCandidateMode(false);}}privatevoidresetCandidateWindow(){if(mEnvironment.needDebug()){Log.d(TAG,"Candidateswindowistobereset");}if(null==mCandidatesContainer)return;try{mFloatingWindowTimer.cancelShowing();mFloatingWindow.dismiss();}catch(Exceptione){Log.e(TAG,"FailtoshowthePopupWindow.");}if(null!=mSkbContainer&&mSkbContainer.isShown()){mSkbContainer.toggleCandidateMode(false);}mDecInfo.resetCandidates();if(null!=mCandidatesContainer&&mCandidatesContainer.isShown()){showCandidateWindow(false);}}privatevoidupdateIcon(inticonId){if(iconId>0){showStatusIcon(iconId);}else{hideStatusIcon();}}@OverridepublicViewonCreateInputView(){if(mEnvironment.needDebug()){Log.d(TAG,"onCreateInputView.");}LayoutInflaterinflater=getLayoutInflater();mSkbContainer=(SkbContainer)inflater.inflate(R.layout.skb_container,null);mSkbContainer.setService(this);mSkbContainer.setInputModeSwitcher(mInputModeSwitcher);mSkbContainer.setGestureDetector(mGestureDetectorSkb);returnmSkbContainer;}@OverridepublicvoidonStartInput(EditorInfoeditorInfo,booleanrestarting){if(mEnvironment.needDebug()){Log.d(TAG,"onStartInput"+"ccontentType:"+String.valueOf(editorInfo.inputType)+"Restarting:"+String.valueOf(restarting));}updateIcon(mInputModeSwitcher.requestInputWithHkb(editorInfo));resetToIdleState(false);}@OverridepublicvoidonStartInputView(EditorInfoeditorInfo,booleanrestarting){if(mEnvironment.needDebug()){Log.d(TAG,"onStartInputView"+"contentType:"+String.valueOf(editorInfo.inputType)+"Restarting:"+String.valueOf(restarting));}updateIcon(mInputModeSwitcher.requestInputWithSkb(editorInfo));resetToIdleState(false);mSkbContainer.updateInputMode();setCandidatesViewShown(false);}@OverridepublicvoidonFinishInputView(booleanfinishingInput){if(mEnvironment.needDebug()){Log.d(TAG,"onFinishInputView.");}resetToIdleState(false);super.onFinishInputView(finishingInput);}@OverridepublicvoidonFinishInput(){if(mEnvironment.needDebug()){Log.d(TAG,"onFinishInput.");}resetToIdleState(false);super.onFinishInput();}@OverridepublicvoidonFinishCandidatesView(booleanfinishingInput){if(mEnvironment.needDebug()){Log.d(TAG,"onFinishCandidateView.");}resetToIdleState(false);super.onFinishCandidatesView(finishingInput);}@OverridepublicvoidonDisplayCompletions(CompletionInfo[]completions){if(!isFullscreenMode())return;if(null==completions||completions.length<=0)return;if(null==mSkbContainer||!mSkbContainer.isShown())return;if(!mInputModeSwitcher.isChineseText()||ImeState.STATE_IDLE==mImeState||ImeState.STATE_PREDICT==mImeState){mImeState=ImeState.STATE_APP_COMPLETION;mDecInfo.prepareAppCompletions(completions);showCandidateWindow(false);}}privatevoidonChoiceTouched(intactiveCandNo){if(mImeState==ImeState.STATE_COMPOSING){changeToStateInput(true);}elseif(mImeState==ImeState.STATE_INPUT||mImeState==ImeState.STATE_PREDICT){chooseCandidate(activeCandNo);}elseif(mImeState==ImeState.STATE_APP_COMPLETION){if(null!=mDecInfo.mAppCompletions&&activeCandNo>=0&&activeCandNo=0){mIme.onChoiceTouched(choiceId);}}publicvoidonToLeftGesture(){if(ImeState.STATE_COMPOSING==mImeState){changeToStateInput(true);}mCandidatesContainer.pageForward(true,false);}publicvoidonToRightGesture(){if(ImeState.STATE_COMPOSING==mImeState){changeToStateInput(true);}mCandidatesContainer.pageBackward(true,false);}publicvoidonToTopGesture(){}publicvoidonToBottomGesture(){}}publicclassOnGestureListenerextendsGestureDetector.SimpleOnGestureListener{/***Whenuserpressesanddrags,theminimumx-distancetomakea*responsetothedragevent.*/privatestaticfinalintMIN_X_FOR_DRAG=60;/***Whenuserpressesanddrags,theminimumy-distancetomakea*responsetothedragevent.*/privatestaticfinalintMIN_Y_FOR_DRAG=40;/***Velocitythresholdforascreen-movegesture.Iftheminimum*x-velocityislessthanit,nogesture.*/staticprivatefinalfloatVELOCITY_THRESHOLD_X1=0.3f;/***Velocitythresholdforascreen-movegesture.Ifthemaximum*x-velocityislessthanit,nogesture.*/staticprivatefinalfloatVELOCITY_THRESHOLD_X2=0.7f;/***Velocitythresholdforascreen-movegesture.Iftheminimum*y-velocityislessthanit,nogesture.*/staticprivatefinalfloatVELOCITY_THRESHOLD_Y1=0.2f;/***Velocitythresholdforascreen-movegesture.Ifthemaximum*y-velocityislessthanit,nogesture.*/staticprivatefinalfloatVELOCITY_THRESHOLD_Y2=0.45f;/**Ifitfalse,wewillnotresponsedetectedgestures.*/privatebooleanmReponseGestures;/**TheminimumXvelocityobservedinthegesture.*/privatefloatmMinVelocityX=Float.MAX_VALUE;/**TheminimumYvelocityobservedinthegesture.*/privatefloatmMinVelocityY=Float.MAX_VALUE;/**Thefirstdowntimefortheseriesoftoucheventsforanaction.*/privatelongmTimeDown;/**ThelasttimewhenonScroll()iscalled.*/privatelongmTimeLastOnScroll;/**Thisflagusedtoindicatethatthisgestureisnotagesture.*/privatebooleanmNotGesture;/**Thisflagusedtoindicatethatthisgesturehasbeenrecognized.*/privatebooleanmGestureRecognized;publicOnGestureListener(booleanreponseGestures){mReponseGestures=reponseGestures;}@OverridepublicbooleanonDown(MotionEvente){mMinVelocityX=Integer.MAX_VALUE;mMinVelocityY=Integer.MAX_VALUE;mTimeDown=e.getEventTime();mTimeLastOnScroll=mTimeDown;mNotGesture=false;mGestureRecognized=false;returnfalse;}@OverridepublicbooleanonScroll(MotionEvente1,MotionEvente2,floatdistanceX,floatdistanceY){if(mNotGesture)returnfalse;if(mGestureRecognized)returntrue;if(Math.abs(e1.getX()-e2.getX())VELOCITY_THRESHOLD_X2&&absVYTotalVELOCITY_THRESHOLD_Y2&&absVXTotalmCandidatesList=newVector();/***Elementistoresthestartingpositionofpagei.*/publicVectormPageStart=newVector();/***Elementistoresthenumberofcharacterstopagei.*/publicVectormCnToPage=newVector();/***ThepositiontodeleteinPinyinstring.Ifitislessthan0,IME*willdoanincrementalsearch,otherwiseIMEwilldoadeletion*operation.if{@link#mIsPosInSpl}istrue,IMEwilldeletethewhole*stringformPosDelSpl-thspelling,otherwiseitwillonlydelete*mPosDelSpl-thcharacterinthePinyinstring.*/publicintmPosDelSpl=-1;/***If{@link#mPosDelSpl}isbigthanorequalto0,thismemberisused*toindicatethatwhetherthepostioniscountedinspellingidor*character.*/publicbooleanmIsPosInSpl;publicDecodingInfo(){mSurface=newStringBuffer();mSurfaceDecodedLen=0;}publicvoidreset(){mSurface.delete(0,mSurface.length());mSurfaceDecodedLen=0;mCursorPos=0;mFullSent="";mFixedLen=0;mFinishSelection=false;mComposingStr="";mComposingStrDisplay="";mActiveCmpsLen=0;mActiveCmpsDisplayLen=0;resetCandidates();}publicbooleanisCandidatesListEmpty(){returnmCandidatesList.size()==0;}publicbooleanisSplStrFull(){if(mSurface.length()>=PY_STRING_MAX-1)returntrue;returnfalse;}publicvoidaddSplChar(charch,booleanreset){if(reset){mSurface.delete(0,mSurface.length());mSurfaceDecodedLen=0;mCursorPos=0;try{mIPinyinDecoderService.imResetSearch();}catch(RemoteExceptione){}}mSurface.insert(mCursorPos,ch);mCursorPos++;}//Preparetodeletebeforecursor.Wemaydeleteaspellingcharif//thecursorisintherangeofunfixedpart,deleteawholespelling//ifthecursorininsidetherangeofthefixedpart.//Thisfunctiononlymarksthepositionusedtodelete.publicvoidprepareDeleteBeforeCursor(){if(mCursorPos>0){intpos;for(pos=0;pos=mCursorPos&&mSplStart[pos+1]mSurface.length())mCursorPos=mSurface.length();mComposingStr=mFullSent.substring(0,mFixedLen)+mSurface.substring(mSplStart[mFixedLen+1]);mActiveCmpsLen=mComposingStr.length();if(mSurfaceDecodedLen>0){mActiveCmpsLen=mActiveCmpsLen-(mSurface.length()-mSurfaceDecodedLen);}//Preparethedisplaystring.if(0==mSurfaceDecodedLen){mComposingStrDisplay=mComposingStr;mActiveCmpsDisplayLen=mComposingStr.length();}else{mComposingStrDisplay=mFullSent.substring(0,mFixedLen);for(intpos=mFixedLen+1;pos=mTotalChoicesNum){return;}Stringtmp=mCandidatesList.get(choiceId);resetCandidates();mCandidatesList.add(tmp);mTotalChoicesNum=1;mSurface.replace(0,mSurface.length(),"");mCursorPos=0;mFullSent=tmp;mFixedLen=tmp.length();mComposingStr=mFullSent;mActiveCmpsLen=mFixedLen;mFinishSelection=true;}publicStringgetCandidate(intcandId){//Onlyloadeditemscanbegotten,soweusemCandidatesList.size()//insteadmTotalChoiceNum.if(candId<0||candId>mCandidatesList.size()){returnnull;}returnmCandidatesList.get(candId);}privatevoidgetCandiagtesForCache(){intfetchStart=mCandidatesList.size();intfetchSize=mTotalChoicesNum-fetchStart;if(fetchSize>MAX_PAGE_SIZE_DISPLAY){fetchSize=MAX_PAGE_SIZE_DISPLAY;}try{ListnewList=null;if(ImeState.STATE_INPUT==mImeState||ImeState.STATE_IDLE==mImeState||ImeState.STATE_COMPOSING==mImeState){newList=mIPinyinDecoderService.imGetChoiceList(fetchStart,fetchSize,mFixedLen);}elseif(ImeState.STATE_PREDICT==mImeState){newList=mIPinyinDecoderService.imGetPredictList(fetchStart,fetchSize);}elseif(ImeState.STATE_APP_COMPLETION==mImeState){newList=newArrayList();if(null!=mAppCompletions){for(intpos=fetchStart;pospageNo+1){returntrue;}//IfcacheditemsisenoughforpagepageNo.if(mCandidatesList.size()-mPageStart.elementAt(pageNo)>=MAX_PAGE_SIZE_DISPLAY){returntrue;}//TrytogetmoreitemsfromenginegetCandiagtesForCache();//Trytofindifthereareavailablenewitemstodisplay.//Ifnonewitem,returnfalse;if(mPageStart.elementAt(pageNo)>=mCandidatesList.size()){returnfalse;}//Iftherearenewitems,returntrue;returntrue;}publicvoidpreparePredicts(CharSequencehistory){if(null==history)return;resetCandidates();if(Settings.getPrediction()){StringpreEdit=history.toString();intpredictNum=0;if(null!=preEdit){try{mTotalChoicesNum=mIPinyinDecoderService.imGetPredictsNum(preEdit);}catch(RemoteExceptione){return;}}}preparePage(0);mFinishSelection=false;}privatevoidprepareAppCompletions(CompletionInfocompletions[]){resetCandidates();mAppCompletions=completions;mTotalChoicesNum=completions.length;preparePage(0);mFinishSelection=false;return;}publicintgetCurrentPageSize(intcurrentPage){if(mPageStart.size()<=currentPage+1)return0;returnmPageStart.elementAt(currentPage+1)-mPageStart.elementAt(currentPage);}publicintgetCurrentPageStart(intcurrentPage){if(mPageStart.size()=mTotalChoicesNum){returnfalse;}returntrue;}publicbooleanpageBackwardable(intcurrentPage){if(currentPage>0)returntrue;returnfalse;}publicbooleancharBeforeCursorIsSeparator(){intlen=mSurface.length();if(mCursorPos>len)returnfalse;if(mCursorPos>0&&mSurface.charAt(mCursorPos-1)=='\''){returntrue;}returnfalse;}publicintgetCursorPos(){returnmCursorPos;}publicintgetCursorPosInCmps(){intcursorPos=mCursorPos;intfixedLen=0;for(inthzPos=0;hzPos=mSplStart[hzPos+2]){cursorPos-=mSplStart[hzPos+2]-mSplStart[hzPos+1];cursorPos+=1;}}returncursorPos;}publicintgetCursorPosInCmpsDisplay(){intcursorPos=getCursorPosInCmps();//+2isbecause:oneformSplStart[0],whichisusedforother//purpose(Thelengthofthesegmentationstring),andanother//forthefirstspellingwhichdoesnotneedaspacebeforeit.for(intpos=mFixedLen+2;pos1||offset0){offset=mSplStart[hzPos]-mSplStart[hzPos+1];}}else{if(hzPosmSurface.length()){mCursorPos=mSurface.length();}}publicintgetSplNum(){returnmSplStart[0];}publicintgetFixedLen(){returnmFixedLen;}}}



請為這篇文章評分?