code
stringlengths
3
1.18M
language
stringclasses
1 value
package org.jedit.syntax; /* * PerlTokenMarker.java - Perl token marker * Copyright (C) 1998, 1999 Slava Pestov * * You may use and modify this package for any purpose. Redistribution is * permitted, in both source and binary form, provided that this notice * remains intact in all source distributions of this package. */ import javax.swing.text.Segment; /** * Perl token marker. * * @author Slava Pestov * @version $Id: PerlTokenMarker.java,v 1.11 1999/12/13 03:40:30 sp Exp $ */ public class PerlTokenMarker extends TokenMarker { // public members public static final byte S_ONE = Token.INTERNAL_FIRST; public static final byte S_TWO = (byte)(Token.INTERNAL_FIRST + 1); public static final byte S_END = (byte)(Token.INTERNAL_FIRST + 2); public PerlTokenMarker() { this(getKeywords()); } public PerlTokenMarker(KeywordMap keywords) { this.keywords = keywords; } public byte markTokensImpl(byte _token, Segment line, int lineIndex) { char[] array = line.array; int offset = line.offset; token = _token; lastOffset = offset; lastKeyword = offset; matchChar = '\0'; matchCharBracket = false; matchSpacesAllowed = false; int length = line.count + offset; if(token == Token.LITERAL1 && lineIndex != 0 && lineInfo[lineIndex - 1].obj != null) { String str = (String)lineInfo[lineIndex - 1].obj; if(str != null && str.length() == line.count && SyntaxUtilities.regionMatches(false,line, offset,str)) { addToken(line.count,token); return Token.NULL; } else { addToken(line.count,token); lineInfo[lineIndex].obj = str; return token; } } boolean backslash = false; loop: for(int i = offset; i < length; i++) { int i1 = (i+1); char c = array[i]; if(c == '\\') { backslash = !backslash; continue; } switch(token) { case Token.NULL: switch(c) { case '#': if(doKeyword(line,i,c)) break; if(backslash) backslash = false; else { addToken(i - lastOffset,token); addToken(length - i,Token.COMMENT1); lastOffset = lastKeyword = length; break loop; } break; case '=': backslash = false; if(i == offset) { token = Token.COMMENT2; addToken(length - i,token); lastOffset = lastKeyword = length; break loop; } else doKeyword(line,i,c); break; case '$': case '&': case '%': case '@': backslash = false; if(doKeyword(line,i,c)) break; if(length - i > 1) { if(c == '&' && (array[i1] == '&' || Character.isWhitespace( array[i1]))) i++; else { addToken(i - lastOffset,token); lastOffset = lastKeyword = i; token = Token.KEYWORD2; } } break; case '"': if(doKeyword(line,i,c)) break; if(backslash) backslash = false; else { addToken(i - lastOffset,token); token = Token.LITERAL1; lineInfo[lineIndex].obj = null; lastOffset = lastKeyword = i; } break; case '\'': if(backslash) backslash = false; else { int oldLastKeyword = lastKeyword; if(doKeyword(line,i,c)) break; if(i != oldLastKeyword) break; addToken(i - lastOffset,token); token = Token.LITERAL2; lastOffset = lastKeyword = i; } break; case '`': if(doKeyword(line,i,c)) break; if(backslash) backslash = false; else { addToken(i - lastOffset,token); token = Token.OPERATOR; lastOffset = lastKeyword = i; } break; case '<': if(doKeyword(line,i,c)) break; if(backslash) backslash = false; else { if(length - i > 2 && array[i1] == '<' && !Character.isWhitespace(array[i+2])) { addToken(i - lastOffset,token); lastOffset = lastKeyword = i; token = Token.LITERAL1; int len = length - (i+2); if(array[length - 1] == ';') len--; lineInfo[lineIndex].obj = createReadinString(array,i + 2,len); } } break; case ':': backslash = false; if(doKeyword(line,i,c)) break; // Doesn't pick up all labels, // but at least doesn't mess up // XXX::YYY if(lastKeyword != 0) break; addToken(i1 - lastOffset,Token.LABEL); lastOffset = lastKeyword = i1; break; case '-': backslash = false; if(doKeyword(line,i,c)) break; if(i != lastKeyword || length - i <= 1) break; switch(array[i1]) { case 'r': case 'w': case 'x': case 'o': case 'R': case 'W': case 'X': case 'O': case 'e': case 'z': case 's': case 'f': case 'd': case 'l': case 'p': case 'S': case 'b': case 'c': case 't': case 'u': case 'g': case 'k': case 'T': case 'B': case 'M': case 'A': case 'C': addToken(i - lastOffset,token); addToken(2,Token.KEYWORD3); lastOffset = lastKeyword = i+2; i++; } break; case '/': case '?': if(doKeyword(line,i,c)) break; if(length - i > 1) { backslash = false; char ch = array[i1]; if(Character.isWhitespace(ch)) break; matchChar = c; matchSpacesAllowed = false; addToken(i - lastOffset,token); token = S_ONE; lastOffset = lastKeyword = i; } break; default: backslash = false; if(!Character.isLetterOrDigit(c) && c != '_') doKeyword(line,i,c); break; } break; case Token.KEYWORD2: backslash = false; // This test checks for an end-of-variable // condition if(!Character.isLetterOrDigit(c) && c != '_' && c != '#' && c != '\'' && c != ':' && c != '&') { // If this is the first character // of the variable name ($'aaa) // ignore it if(i != offset && array[i-1] == '$') { addToken(i1 - lastOffset,token); lastOffset = lastKeyword = i1; } // Otherwise, end of variable... else { addToken(i - lastOffset,token); lastOffset = lastKeyword = i; // Wind back so that stuff // like $hello$fred is picked // up i--; token = Token.NULL; } } break; case S_ONE: case S_TWO: if(backslash) backslash = false; else { if(matchChar == '\0') { if(Character.isWhitespace(matchChar) && !matchSpacesAllowed) break; else matchChar = c; } else { switch(matchChar) { case '(': matchChar = ')'; matchCharBracket = true; break; case '[': matchChar = ']'; matchCharBracket = true; break; case '{': matchChar = '}'; matchCharBracket = true; break; case '<': matchChar = '>'; matchCharBracket = true; break; default: matchCharBracket = false; break; } if(c != matchChar) break; if(token == S_TWO) { token = S_ONE; if(matchCharBracket) matchChar = '\0'; } else { token = S_END; addToken(i1 - lastOffset, Token.LITERAL2); lastOffset = lastKeyword = i1; } } } break; case S_END: backslash = false; if(!Character.isLetterOrDigit(c) && c != '_') doKeyword(line,i,c); break; case Token.COMMENT2: backslash = false; if(i == offset) { addToken(line.count,token); if(length - i > 3 && SyntaxUtilities .regionMatches(false,line,offset,"=cut")) token = Token.NULL; lastOffset = lastKeyword = length; break loop; } break; case Token.LITERAL1: if(backslash) backslash = false; /* else if(c == '$') backslash = true; */ else if(c == '"') { addToken(i1 - lastOffset,token); token = Token.NULL; lastOffset = lastKeyword = i1; } break; case Token.LITERAL2: if(backslash) backslash = false; /* else if(c == '$') backslash = true; */ else if(c == '\'') { addToken(i1 - lastOffset,Token.LITERAL1); token = Token.NULL; lastOffset = lastKeyword = i1; } break; case Token.OPERATOR: if(backslash) backslash = false; else if(c == '`') { addToken(i1 - lastOffset,token); token = Token.NULL; lastOffset = lastKeyword = i1; } break; default: throw new InternalError("Invalid state: " + token); } } if(token == Token.NULL) doKeyword(line,length,'\0'); switch(token) { case Token.KEYWORD2: addToken(length - lastOffset,token); token = Token.NULL; break; case Token.LITERAL2: addToken(length - lastOffset,Token.LITERAL1); break; case S_END: addToken(length - lastOffset,Token.LITERAL2); token = Token.NULL; break; case S_ONE: case S_TWO: addToken(length - lastOffset,Token.INVALID); // XXX token = Token.NULL; break; default: addToken(length - lastOffset,token); break; } return token; } // private members private KeywordMap keywords; private byte token; private int lastOffset; private int lastKeyword; private char matchChar; private boolean matchCharBracket; private boolean matchSpacesAllowed; private boolean doKeyword(Segment line, int i, char c) { int i1 = i+1; if(token == S_END) { addToken(i - lastOffset,Token.LITERAL2); token = Token.NULL; lastOffset = i; lastKeyword = i1; return false; } int len = i - lastKeyword; byte id = keywords.lookup(line,lastKeyword,len); if(id == S_ONE || id == S_TWO) { if(lastKeyword != lastOffset) addToken(lastKeyword - lastOffset,Token.NULL); addToken(len,Token.LITERAL2); lastOffset = i; lastKeyword = i1; if(Character.isWhitespace(c)) matchChar = '\0'; else matchChar = c; matchSpacesAllowed = true; token = id; return true; } else if(id != Token.NULL) { if(lastKeyword != lastOffset) addToken(lastKeyword - lastOffset,Token.NULL); addToken(len,id); lastOffset = i; } lastKeyword = i1; return false; } // Converts < EOF >, < 'EOF' >, etc to <EOF> private String createReadinString(char[] array, int start, int len) { int idx1 = start; int idx2 = start + len - 1; while((idx1 <= idx2) && (!Character.isLetterOrDigit(array[idx1]))) idx1++; while((idx1 <= idx2) && (!Character.isLetterOrDigit(array[idx2]))) idx2--; return new String(array, idx1, idx2 - idx1 + 1); } private static KeywordMap perlKeywords; private static KeywordMap getKeywords() { if(perlKeywords == null) { perlKeywords = new KeywordMap(false); perlKeywords.add("my",Token.KEYWORD1); perlKeywords.add("local",Token.KEYWORD1); perlKeywords.add("new",Token.KEYWORD1); perlKeywords.add("if",Token.KEYWORD1); perlKeywords.add("until",Token.KEYWORD1); perlKeywords.add("while",Token.KEYWORD1); perlKeywords.add("elsif",Token.KEYWORD1); perlKeywords.add("else",Token.KEYWORD1); perlKeywords.add("eval",Token.KEYWORD1); perlKeywords.add("unless",Token.KEYWORD1); perlKeywords.add("foreach",Token.KEYWORD1); perlKeywords.add("continue",Token.KEYWORD1); perlKeywords.add("exit",Token.KEYWORD1); perlKeywords.add("die",Token.KEYWORD1); perlKeywords.add("last",Token.KEYWORD1); perlKeywords.add("goto",Token.KEYWORD1); perlKeywords.add("next",Token.KEYWORD1); perlKeywords.add("redo",Token.KEYWORD1); perlKeywords.add("goto",Token.KEYWORD1); perlKeywords.add("return",Token.KEYWORD1); perlKeywords.add("do",Token.KEYWORD1); perlKeywords.add("sub",Token.KEYWORD1); perlKeywords.add("use",Token.KEYWORD1); perlKeywords.add("require",Token.KEYWORD1); perlKeywords.add("package",Token.KEYWORD1); perlKeywords.add("BEGIN",Token.KEYWORD1); perlKeywords.add("END",Token.KEYWORD1); perlKeywords.add("eq",Token.OPERATOR); perlKeywords.add("ne",Token.OPERATOR); perlKeywords.add("not",Token.OPERATOR); perlKeywords.add("and",Token.OPERATOR); perlKeywords.add("or",Token.OPERATOR); perlKeywords.add("abs",Token.KEYWORD3); perlKeywords.add("accept",Token.KEYWORD3); perlKeywords.add("alarm",Token.KEYWORD3); perlKeywords.add("atan2",Token.KEYWORD3); perlKeywords.add("bind",Token.KEYWORD3); perlKeywords.add("binmode",Token.KEYWORD3); perlKeywords.add("bless",Token.KEYWORD3); perlKeywords.add("caller",Token.KEYWORD3); perlKeywords.add("chdir",Token.KEYWORD3); perlKeywords.add("chmod",Token.KEYWORD3); perlKeywords.add("chomp",Token.KEYWORD3); perlKeywords.add("chr",Token.KEYWORD3); perlKeywords.add("chroot",Token.KEYWORD3); perlKeywords.add("chown",Token.KEYWORD3); perlKeywords.add("closedir",Token.KEYWORD3); perlKeywords.add("close",Token.KEYWORD3); perlKeywords.add("connect",Token.KEYWORD3); perlKeywords.add("cos",Token.KEYWORD3); perlKeywords.add("crypt",Token.KEYWORD3); perlKeywords.add("dbmclose",Token.KEYWORD3); perlKeywords.add("dbmopen",Token.KEYWORD3); perlKeywords.add("defined",Token.KEYWORD3); perlKeywords.add("delete",Token.KEYWORD3); perlKeywords.add("die",Token.KEYWORD3); perlKeywords.add("dump",Token.KEYWORD3); perlKeywords.add("each",Token.KEYWORD3); perlKeywords.add("endgrent",Token.KEYWORD3); perlKeywords.add("endhostent",Token.KEYWORD3); perlKeywords.add("endnetent",Token.KEYWORD3); perlKeywords.add("endprotoent",Token.KEYWORD3); perlKeywords.add("endpwent",Token.KEYWORD3); perlKeywords.add("endservent",Token.KEYWORD3); perlKeywords.add("eof",Token.KEYWORD3); perlKeywords.add("exec",Token.KEYWORD3); perlKeywords.add("exists",Token.KEYWORD3); perlKeywords.add("exp",Token.KEYWORD3); perlKeywords.add("fctnl",Token.KEYWORD3); perlKeywords.add("fileno",Token.KEYWORD3); perlKeywords.add("flock",Token.KEYWORD3); perlKeywords.add("fork",Token.KEYWORD3); perlKeywords.add("format",Token.KEYWORD3); perlKeywords.add("formline",Token.KEYWORD3); perlKeywords.add("getc",Token.KEYWORD3); perlKeywords.add("getgrent",Token.KEYWORD3); perlKeywords.add("getgrgid",Token.KEYWORD3); perlKeywords.add("getgrnam",Token.KEYWORD3); perlKeywords.add("gethostbyaddr",Token.KEYWORD3); perlKeywords.add("gethostbyname",Token.KEYWORD3); perlKeywords.add("gethostent",Token.KEYWORD3); perlKeywords.add("getlogin",Token.KEYWORD3); perlKeywords.add("getnetbyaddr",Token.KEYWORD3); perlKeywords.add("getnetbyname",Token.KEYWORD3); perlKeywords.add("getnetent",Token.KEYWORD3); perlKeywords.add("getpeername",Token.KEYWORD3); perlKeywords.add("getpgrp",Token.KEYWORD3); perlKeywords.add("getppid",Token.KEYWORD3); perlKeywords.add("getpriority",Token.KEYWORD3); perlKeywords.add("getprotobyname",Token.KEYWORD3); perlKeywords.add("getprotobynumber",Token.KEYWORD3); perlKeywords.add("getprotoent",Token.KEYWORD3); perlKeywords.add("getpwent",Token.KEYWORD3); perlKeywords.add("getpwnam",Token.KEYWORD3); perlKeywords.add("getpwuid",Token.KEYWORD3); perlKeywords.add("getservbyname",Token.KEYWORD3); perlKeywords.add("getservbyport",Token.KEYWORD3); perlKeywords.add("getservent",Token.KEYWORD3); perlKeywords.add("getsockname",Token.KEYWORD3); perlKeywords.add("getsockopt",Token.KEYWORD3); perlKeywords.add("glob",Token.KEYWORD3); perlKeywords.add("gmtime",Token.KEYWORD3); perlKeywords.add("grep",Token.KEYWORD3); perlKeywords.add("hex",Token.KEYWORD3); perlKeywords.add("import",Token.KEYWORD3); perlKeywords.add("index",Token.KEYWORD3); perlKeywords.add("int",Token.KEYWORD3); perlKeywords.add("ioctl",Token.KEYWORD3); perlKeywords.add("join",Token.KEYWORD3); perlKeywords.add("keys",Token.KEYWORD3); perlKeywords.add("kill",Token.KEYWORD3); perlKeywords.add("lcfirst",Token.KEYWORD3); perlKeywords.add("lc",Token.KEYWORD3); perlKeywords.add("length",Token.KEYWORD3); perlKeywords.add("link",Token.KEYWORD3); perlKeywords.add("listen",Token.KEYWORD3); perlKeywords.add("log",Token.KEYWORD3); perlKeywords.add("localtime",Token.KEYWORD3); perlKeywords.add("lstat",Token.KEYWORD3); perlKeywords.add("map",Token.KEYWORD3); perlKeywords.add("mkdir",Token.KEYWORD3); perlKeywords.add("msgctl",Token.KEYWORD3); perlKeywords.add("msgget",Token.KEYWORD3); perlKeywords.add("msgrcv",Token.KEYWORD3); perlKeywords.add("no",Token.KEYWORD3); perlKeywords.add("oct",Token.KEYWORD3); perlKeywords.add("opendir",Token.KEYWORD3); perlKeywords.add("open",Token.KEYWORD3); perlKeywords.add("ord",Token.KEYWORD3); perlKeywords.add("pack",Token.KEYWORD3); perlKeywords.add("pipe",Token.KEYWORD3); perlKeywords.add("pop",Token.KEYWORD3); perlKeywords.add("pos",Token.KEYWORD3); perlKeywords.add("printf",Token.KEYWORD3); perlKeywords.add("print",Token.KEYWORD3); perlKeywords.add("push",Token.KEYWORD3); perlKeywords.add("quotemeta",Token.KEYWORD3); perlKeywords.add("rand",Token.KEYWORD3); perlKeywords.add("readdir",Token.KEYWORD3); perlKeywords.add("read",Token.KEYWORD3); perlKeywords.add("readlink",Token.KEYWORD3); perlKeywords.add("recv",Token.KEYWORD3); perlKeywords.add("ref",Token.KEYWORD3); perlKeywords.add("rename",Token.KEYWORD3); perlKeywords.add("reset",Token.KEYWORD3); perlKeywords.add("reverse",Token.KEYWORD3); perlKeywords.add("rewinddir",Token.KEYWORD3); perlKeywords.add("rindex",Token.KEYWORD3); perlKeywords.add("rmdir",Token.KEYWORD3); perlKeywords.add("scalar",Token.KEYWORD3); perlKeywords.add("seekdir",Token.KEYWORD3); perlKeywords.add("seek",Token.KEYWORD3); perlKeywords.add("select",Token.KEYWORD3); perlKeywords.add("semctl",Token.KEYWORD3); perlKeywords.add("semget",Token.KEYWORD3); perlKeywords.add("semop",Token.KEYWORD3); perlKeywords.add("send",Token.KEYWORD3); perlKeywords.add("setgrent",Token.KEYWORD3); perlKeywords.add("sethostent",Token.KEYWORD3); perlKeywords.add("setnetent",Token.KEYWORD3); perlKeywords.add("setpgrp",Token.KEYWORD3); perlKeywords.add("setpriority",Token.KEYWORD3); perlKeywords.add("setprotoent",Token.KEYWORD3); perlKeywords.add("setpwent",Token.KEYWORD3); perlKeywords.add("setsockopt",Token.KEYWORD3); perlKeywords.add("shift",Token.KEYWORD3); perlKeywords.add("shmctl",Token.KEYWORD3); perlKeywords.add("shmget",Token.KEYWORD3); perlKeywords.add("shmread",Token.KEYWORD3); perlKeywords.add("shmwrite",Token.KEYWORD3); perlKeywords.add("shutdown",Token.KEYWORD3); perlKeywords.add("sin",Token.KEYWORD3); perlKeywords.add("sleep",Token.KEYWORD3); perlKeywords.add("socket",Token.KEYWORD3); perlKeywords.add("socketpair",Token.KEYWORD3); perlKeywords.add("sort",Token.KEYWORD3); perlKeywords.add("splice",Token.KEYWORD3); perlKeywords.add("split",Token.KEYWORD3); perlKeywords.add("sprintf",Token.KEYWORD3); perlKeywords.add("sqrt",Token.KEYWORD3); perlKeywords.add("srand",Token.KEYWORD3); perlKeywords.add("stat",Token.KEYWORD3); perlKeywords.add("study",Token.KEYWORD3); perlKeywords.add("substr",Token.KEYWORD3); perlKeywords.add("symlink",Token.KEYWORD3); perlKeywords.add("syscall",Token.KEYWORD3); perlKeywords.add("sysopen",Token.KEYWORD3); perlKeywords.add("sysread",Token.KEYWORD3); perlKeywords.add("syswrite",Token.KEYWORD3); perlKeywords.add("telldir",Token.KEYWORD3); perlKeywords.add("tell",Token.KEYWORD3); perlKeywords.add("tie",Token.KEYWORD3); perlKeywords.add("tied",Token.KEYWORD3); perlKeywords.add("time",Token.KEYWORD3); perlKeywords.add("times",Token.KEYWORD3); perlKeywords.add("truncate",Token.KEYWORD3); perlKeywords.add("uc",Token.KEYWORD3); perlKeywords.add("ucfirst",Token.KEYWORD3); perlKeywords.add("umask",Token.KEYWORD3); perlKeywords.add("undef",Token.KEYWORD3); perlKeywords.add("unlink",Token.KEYWORD3); perlKeywords.add("unpack",Token.KEYWORD3); perlKeywords.add("unshift",Token.KEYWORD3); perlKeywords.add("untie",Token.KEYWORD3); perlKeywords.add("utime",Token.KEYWORD3); perlKeywords.add("values",Token.KEYWORD3); perlKeywords.add("vec",Token.KEYWORD3); perlKeywords.add("wait",Token.KEYWORD3); perlKeywords.add("waitpid",Token.KEYWORD3); perlKeywords.add("wantarray",Token.KEYWORD3); perlKeywords.add("warn",Token.KEYWORD3); perlKeywords.add("write",Token.KEYWORD3); perlKeywords.add("m",S_ONE); perlKeywords.add("q",S_ONE); perlKeywords.add("qq",S_ONE); perlKeywords.add("qw",S_ONE); perlKeywords.add("qx",S_ONE); perlKeywords.add("s",S_TWO); perlKeywords.add("tr",S_TWO); perlKeywords.add("y",S_TWO); } return perlKeywords; } }
Java
package org.jedit.syntax; /* * DefaultInputHandler.java - Default implementation of an input handler * Copyright (C) 1999 Slava Pestov * * You may use and modify this package for any purpose. Redistribution is * permitted, in both source and binary form, provided that this notice * remains intact in all source distributions of this package. */ import javax.swing.KeyStroke; import java.awt.event.*; import java.awt.Toolkit; import java.util.Hashtable; import java.util.StringTokenizer; /** * The default input handler. It maps sequences of keystrokes into actions * and inserts key typed events into the text area. * @author Slava Pestov * @version $Id: DefaultInputHandler.java,v 1.18 1999/12/13 03:40:30 sp Exp $ */ public class DefaultInputHandler extends InputHandler { /** * Creates a new input handler with no key bindings defined. */ public DefaultInputHandler() { bindings = currentBindings = new Hashtable(); } /** * Sets up the default key bindings. */ public void addDefaultKeyBindings() { addKeyBinding("BACK_SPACE",BACKSPACE); addKeyBinding("C+BACK_SPACE",BACKSPACE_WORD); addKeyBinding("DELETE",DELETE); addKeyBinding("C+DELETE",DELETE_WORD); addKeyBinding("ENTER",INSERT_BREAK); addKeyBinding("TAB",INSERT_TAB); addKeyBinding("INSERT",OVERWRITE); addKeyBinding("C+\\",TOGGLE_RECT); addKeyBinding("HOME",HOME); addKeyBinding("END",END); addKeyBinding("S+HOME",SELECT_HOME); addKeyBinding("S+END",SELECT_END); addKeyBinding("C+HOME",DOCUMENT_HOME); addKeyBinding("C+END",DOCUMENT_END); addKeyBinding("CS+HOME",SELECT_DOC_HOME); addKeyBinding("CS+END",SELECT_DOC_END); addKeyBinding("PAGE_UP",PREV_PAGE); addKeyBinding("PAGE_DOWN",NEXT_PAGE); addKeyBinding("S+PAGE_UP",SELECT_PREV_PAGE); addKeyBinding("S+PAGE_DOWN",SELECT_NEXT_PAGE); addKeyBinding("LEFT",PREV_CHAR); addKeyBinding("S+LEFT",SELECT_PREV_CHAR); addKeyBinding("C+LEFT",PREV_WORD); addKeyBinding("CS+LEFT",SELECT_PREV_WORD); addKeyBinding("RIGHT",NEXT_CHAR); addKeyBinding("S+RIGHT",SELECT_NEXT_CHAR); addKeyBinding("C+RIGHT",NEXT_WORD); addKeyBinding("CS+RIGHT",SELECT_NEXT_WORD); addKeyBinding("UP",PREV_LINE); addKeyBinding("S+UP",SELECT_PREV_LINE); addKeyBinding("DOWN",NEXT_LINE); addKeyBinding("S+DOWN",SELECT_NEXT_LINE); addKeyBinding("C+ENTER",REPEAT); } /** * Adds a key binding to this input handler. The key binding is * a list of white space separated key strokes of the form * <i>[modifiers+]key</i> where modifier is C for Control, A for Alt, * or S for Shift, and key is either a character (a-z) or a field * name in the KeyEvent class prefixed with VK_ (e.g., BACK_SPACE) * @param keyBinding The key binding * @param action The action */ public void addKeyBinding(String keyBinding, ActionListener action) { Hashtable current = bindings; StringTokenizer st = new StringTokenizer(keyBinding); while(st.hasMoreTokens()) { KeyStroke keyStroke = parseKeyStroke(st.nextToken()); if(keyStroke == null) return; if(st.hasMoreTokens()) { Object o = current.get(keyStroke); if(o instanceof Hashtable) current = (Hashtable)o; else { o = new Hashtable(); current.put(keyStroke,o); current = (Hashtable)o; } } else current.put(keyStroke,action); } } /** * Removes a key binding from this input handler. This is not yet * implemented. * @param keyBinding The key binding */ public void removeKeyBinding(String keyBinding) { throw new InternalError("Not yet implemented"); } /** * Removes all key bindings from this input handler. */ public void removeAllKeyBindings() { bindings.clear(); } /** * Returns a copy of this input handler that shares the same * key bindings. Setting key bindings in the copy will also * set them in the original. */ public InputHandler copy() { return new DefaultInputHandler(this); } /** * Handle a key pressed event. This will look up the binding for * the key stroke and execute it. */ public void keyPressed(KeyEvent evt) { int keyCode = evt.getKeyCode(); int modifiers = evt.getModifiers(); if(keyCode == KeyEvent.VK_CONTROL || keyCode == KeyEvent.VK_SHIFT || keyCode == KeyEvent.VK_ALT || keyCode == KeyEvent.VK_META) return; if((modifiers & ~KeyEvent.SHIFT_MASK) != 0 || evt.isActionKey() || keyCode == KeyEvent.VK_BACK_SPACE || keyCode == KeyEvent.VK_DELETE || keyCode == KeyEvent.VK_ENTER || keyCode == KeyEvent.VK_TAB || keyCode == KeyEvent.VK_ESCAPE) { if(grabAction != null) { handleGrabAction(evt); return; } KeyStroke keyStroke = KeyStroke.getKeyStroke(keyCode, modifiers); Object o = currentBindings.get(keyStroke); if(o == null) { // Don't beep if the user presses some // key we don't know about unless a // prefix is active. Otherwise it will // beep when caps lock is pressed, etc. if(currentBindings != bindings) { Toolkit.getDefaultToolkit().beep(); // F10 should be passed on, but C+e F10 // shouldn't repeatCount = 0; repeat = false; evt.consume(); } currentBindings = bindings; return; } else if(o instanceof ActionListener) { currentBindings = bindings; executeAction(((ActionListener)o), evt.getSource(),null); evt.consume(); return; } else if(o instanceof Hashtable) { currentBindings = (Hashtable)o; evt.consume(); return; } } } /** * Handle a key typed event. This inserts the key into the text area. */ public void keyTyped(KeyEvent evt) { int modifiers = evt.getModifiers(); char c = evt.getKeyChar(); if(c != KeyEvent.CHAR_UNDEFINED && (modifiers & KeyEvent.ALT_MASK) == 0) { if(c >= 0x20 && c != 0x7f) { KeyStroke keyStroke = KeyStroke.getKeyStroke( Character.toUpperCase(c)); Object o = currentBindings.get(keyStroke); if(o instanceof Hashtable) { currentBindings = (Hashtable)o; return; } else if(o instanceof ActionListener) { currentBindings = bindings; executeAction((ActionListener)o, evt.getSource(), String.valueOf(c)); return; } currentBindings = bindings; if(grabAction != null) { handleGrabAction(evt); return; } // 0-9 adds another 'digit' to the repeat number if(repeat && Character.isDigit(c)) { repeatCount *= 10; repeatCount += (c - '0'); return; } executeAction(INSERT_CHAR,evt.getSource(), String.valueOf(evt.getKeyChar())); repeatCount = 0; repeat = false; } } } /** * Converts a string to a keystroke. The string should be of the * form <i>modifiers</i>+<i>shortcut</i> where <i>modifiers</i> * is any combination of A for Alt, C for Control, S for Shift * or M for Meta, and <i>shortcut</i> is either a single character, * or a keycode name from the <code>KeyEvent</code> class, without * the <code>VK_</code> prefix. * @param keyStroke A string description of the key stroke */ public static KeyStroke parseKeyStroke(String keyStroke) { if(keyStroke == null) return null; int modifiers = 0; int index = keyStroke.indexOf('+'); if(index != -1) { for(int i = 0; i < index; i++) { switch(Character.toUpperCase(keyStroke .charAt(i))) { case 'A': modifiers |= InputEvent.ALT_MASK; break; case 'C': modifiers |= InputEvent.CTRL_MASK; break; case 'M': modifiers |= InputEvent.META_MASK; break; case 'S': modifiers |= InputEvent.SHIFT_MASK; break; } } } String key = keyStroke.substring(index + 1); if(key.length() == 1) { char ch = Character.toUpperCase(key.charAt(0)); if(modifiers == 0) return KeyStroke.getKeyStroke(ch); else return KeyStroke.getKeyStroke(ch,modifiers); } else if(key.length() == 0) { System.err.println("Invalid key stroke: " + keyStroke); return null; } else { int ch; try { ch = KeyEvent.class.getField("VK_".concat(key)) .getInt(null); } catch(Exception e) { System.err.println("Invalid key stroke: " + keyStroke); return null; } return KeyStroke.getKeyStroke(ch,modifiers); } } // private members private Hashtable bindings; private Hashtable currentBindings; private DefaultInputHandler(DefaultInputHandler copy) { bindings = currentBindings = copy.bindings; } }
Java
package org.jedit.syntax; /* * MakefileTokenMarker.java - Makefile token marker * Copyright (C) 1998, 1999 Slava Pestov * * You may use and modify this package for any purpose. Redistribution is * permitted, in both source and binary form, provided that this notice * remains intact in all source distributions of this package. */ import javax.swing.text.Segment; /** * Makefile token marker. * * @author Slava Pestov * @version $Id: MakefileTokenMarker.java,v 1.18 1999/12/13 03:40:30 sp Exp $ */ public class MakefileTokenMarker extends TokenMarker { // public members public byte markTokensImpl(byte token, Segment line, int lineIndex) { char[] array = line.array; int offset = line.offset; int lastOffset = offset; int length = line.count + offset; boolean backslash = false; loop: for(int i = offset; i < length; i++) { int i1 = (i+1); char c = array[i]; if(c == '\\') { backslash = !backslash; continue; } switch(token) { case Token.NULL: switch(c) { case ':': case '=': case ' ': case '\t': backslash = false; if(lastOffset == offset) { addToken(i1 - lastOffset,Token.KEYWORD1); lastOffset = i1; } break; case '#': if(backslash) backslash = false; else { addToken(i - lastOffset,token); addToken(length - i,Token.COMMENT1); lastOffset = length; break loop; } break; case '$': if(backslash) backslash = false; else if(lastOffset != offset) { addToken(i - lastOffset,token); lastOffset = i; if(length - i > 1) { char c1 = array[i1]; if(c1 == '(' || c1 == '{') token = Token.KEYWORD2; else { addToken(2,Token.KEYWORD2); lastOffset += 2; i++; } } } break; case '"': if(backslash) backslash = false; else { addToken(i - lastOffset,token); token = Token.LITERAL1; lastOffset = i; } break; case '\'': if(backslash) backslash = false; else { addToken(i - lastOffset,token); token = Token.LITERAL2; lastOffset = i; } break; default: backslash = false; break; } case Token.KEYWORD2: backslash = false; if(c == ')' || c == '}') { addToken(i1 - lastOffset,token); token = Token.NULL; lastOffset = i1; } break; case Token.LITERAL1: if(backslash) backslash = false; else if(c == '"') { addToken(i1 - lastOffset,token); token = Token.NULL; lastOffset = i1; } else backslash = false; break; case Token.LITERAL2: if(backslash) backslash = false; else if(c == '\'') { addToken(i1 - lastOffset,Token.LITERAL1); token = Token.NULL; lastOffset = i1; } else backslash = false; break; } } switch(token) { case Token.KEYWORD2: addToken(length - lastOffset,Token.INVALID); token = Token.NULL; break; case Token.LITERAL2: addToken(length - lastOffset,Token.LITERAL1); break; default: addToken(length - lastOffset,token); break; } return token; } }
Java
package org.jedit.syntax; /* * IDLTokenMarker.java - IDL token marker * Copyright (C) 1999 Slava Pestov * Copyright (C) 1999 Juha Lindfors * * You may use and modify this package for any purpose. Redistribution is * permitted, in both source and binary form, provided that this notice * remains intact in all source distributions of this package. */ import javax.swing.text.Segment; /** * IDL token marker. * * @author Slava Pestov * @author Juha Lindfors * @version $Id: IDLTokenMarker.java,v 1.2 1999/12/18 06:10:56 sp Exp $ */ public class IDLTokenMarker extends CTokenMarker { public IDLTokenMarker() { super(true,getKeywords()); } public static KeywordMap getKeywords() { if(idlKeywords == null) { idlKeywords = new KeywordMap(false); idlKeywords.add("any", Token.KEYWORD3); idlKeywords.add("attribute",Token.KEYWORD1); idlKeywords.add("boolean", Token.KEYWORD3); idlKeywords.add("case", Token.KEYWORD1); idlKeywords.add("char", Token.KEYWORD3); idlKeywords.add("const", Token.KEYWORD1); idlKeywords.add("context", Token.KEYWORD1); idlKeywords.add("default", Token.KEYWORD1); idlKeywords.add("double", Token.KEYWORD3); idlKeywords.add("enum", Token.KEYWORD3); idlKeywords.add("exception",Token.KEYWORD1); idlKeywords.add("FALSE", Token.LITERAL2); idlKeywords.add("fixed", Token.KEYWORD1); idlKeywords.add("float", Token.KEYWORD3); idlKeywords.add("in", Token.KEYWORD1); idlKeywords.add("inout", Token.KEYWORD1); idlKeywords.add("interface",Token.KEYWORD1); idlKeywords.add("long", Token.KEYWORD3); idlKeywords.add("module", Token.KEYWORD1); idlKeywords.add("Object", Token.KEYWORD3); idlKeywords.add("octet", Token.KEYWORD3); idlKeywords.add("oneway", Token.KEYWORD1); idlKeywords.add("out", Token.KEYWORD1); idlKeywords.add("raises", Token.KEYWORD1); idlKeywords.add("readonly", Token.KEYWORD1); idlKeywords.add("sequence", Token.KEYWORD3); idlKeywords.add("short", Token.KEYWORD3); idlKeywords.add("string", Token.KEYWORD3); idlKeywords.add("struct", Token.KEYWORD3); idlKeywords.add("switch", Token.KEYWORD1); idlKeywords.add("TRUE", Token.LITERAL2); idlKeywords.add("typedef", Token.KEYWORD3); idlKeywords.add("unsigned", Token.KEYWORD3); idlKeywords.add("union", Token.KEYWORD3); idlKeywords.add("void", Token.KEYWORD3); idlKeywords.add("wchar", Token.KEYWORD3); idlKeywords.add("wstring", Token.KEYWORD3); } return idlKeywords; } // private members private static KeywordMap idlKeywords; }
Java
package org.jedit.syntax; /* * TSQLTokenMarker.java - Transact-SQL token marker * Copyright (C) 1999 mike dillon * * You may use and modify this package for any purpose. Redistribution is * permitted, in both source and binary form, provided that this notice * remains intact in all source distributions of this package. */ import javax.swing.text.Segment; /** * Transact-SQL token marker. * * @author mike dillon * @version $Id: TSQLTokenMarker.java,v 1.9 1999/12/13 03:40:30 sp Exp $ */ public class TSQLTokenMarker extends SQLTokenMarker { // public members public TSQLTokenMarker() { super(getKeywordMap(), true); } public static KeywordMap getKeywordMap() { if (tsqlKeywords == null) { tsqlKeywords = new KeywordMap(true); addKeywords(); addDataTypes(); addSystemFunctions(); addOperators(); addSystemStoredProcedures(); addSystemTables(); } return tsqlKeywords; } private static void addKeywords() { tsqlKeywords.add("ADD",Token.KEYWORD1); tsqlKeywords.add("ALTER",Token.KEYWORD1); tsqlKeywords.add("ANSI_NULLS",Token.KEYWORD1); tsqlKeywords.add("AS",Token.KEYWORD1); tsqlKeywords.add("ASC",Token.KEYWORD1); tsqlKeywords.add("AUTHORIZATION",Token.KEYWORD1); tsqlKeywords.add("BACKUP",Token.KEYWORD1); tsqlKeywords.add("BEGIN",Token.KEYWORD1); tsqlKeywords.add("BREAK",Token.KEYWORD1); tsqlKeywords.add("BROWSE",Token.KEYWORD1); tsqlKeywords.add("BULK",Token.KEYWORD1); tsqlKeywords.add("BY",Token.KEYWORD1); tsqlKeywords.add("CASCADE",Token.KEYWORD1); tsqlKeywords.add("CHECK",Token.KEYWORD1); tsqlKeywords.add("CHECKPOINT",Token.KEYWORD1); tsqlKeywords.add("CLOSE",Token.KEYWORD1); tsqlKeywords.add("CLUSTERED",Token.KEYWORD1); tsqlKeywords.add("COLUMN",Token.KEYWORD1); tsqlKeywords.add("COMMIT",Token.KEYWORD1); tsqlKeywords.add("COMMITTED",Token.KEYWORD1); tsqlKeywords.add("COMPUTE",Token.KEYWORD1); tsqlKeywords.add("CONFIRM",Token.KEYWORD1); tsqlKeywords.add("CONSTRAINT",Token.KEYWORD1); tsqlKeywords.add("CONTAINS",Token.KEYWORD1); tsqlKeywords.add("CONTAINSTABLE",Token.KEYWORD1); tsqlKeywords.add("CONTINUE",Token.KEYWORD1); tsqlKeywords.add("CONTROLROW",Token.KEYWORD1); tsqlKeywords.add("CREATE",Token.KEYWORD1); tsqlKeywords.add("CURRENT",Token.KEYWORD1); tsqlKeywords.add("CURRENT_DATE",Token.KEYWORD1); tsqlKeywords.add("CURRENT_TIME",Token.KEYWORD1); tsqlKeywords.add("CURSOR",Token.KEYWORD1); tsqlKeywords.add("DATABASE",Token.KEYWORD1); tsqlKeywords.add("DBCC",Token.KEYWORD1); tsqlKeywords.add("DEALLOCATE",Token.KEYWORD1); tsqlKeywords.add("DECLARE",Token.KEYWORD1); tsqlKeywords.add("DEFAULT",Token.KEYWORD1); tsqlKeywords.add("DELETE",Token.KEYWORD1); tsqlKeywords.add("DENY",Token.KEYWORD1); tsqlKeywords.add("DESC",Token.KEYWORD1); tsqlKeywords.add("DISK",Token.KEYWORD1); tsqlKeywords.add("DISTINCT",Token.KEYWORD1); tsqlKeywords.add("DISTRIBUTED",Token.KEYWORD1); tsqlKeywords.add("DOUBLE",Token.KEYWORD1); tsqlKeywords.add("DROP",Token.KEYWORD1); tsqlKeywords.add("DUMMY",Token.KEYWORD1); tsqlKeywords.add("DUMP",Token.KEYWORD1); tsqlKeywords.add("ELSE",Token.KEYWORD1); tsqlKeywords.add("END",Token.KEYWORD1); tsqlKeywords.add("ERRLVL",Token.KEYWORD1); tsqlKeywords.add("ERROREXIT",Token.KEYWORD1); tsqlKeywords.add("ESCAPE",Token.KEYWORD1); tsqlKeywords.add("EXCEPT",Token.KEYWORD1); tsqlKeywords.add("EXEC",Token.KEYWORD1); tsqlKeywords.add("EXECUTE",Token.KEYWORD1); tsqlKeywords.add("EXIT",Token.KEYWORD1); tsqlKeywords.add("FETCH",Token.KEYWORD1); tsqlKeywords.add("FILE",Token.KEYWORD1); tsqlKeywords.add("FILLFACTOR",Token.KEYWORD1); tsqlKeywords.add("FLOPPY",Token.KEYWORD1); tsqlKeywords.add("FOR",Token.KEYWORD1); tsqlKeywords.add("FOREIGN",Token.KEYWORD1); tsqlKeywords.add("FREETEXT",Token.KEYWORD1); tsqlKeywords.add("FREETEXTTABLE",Token.KEYWORD1); tsqlKeywords.add("FROM",Token.KEYWORD1); tsqlKeywords.add("FULL",Token.KEYWORD1); tsqlKeywords.add("GOTO",Token.KEYWORD1); tsqlKeywords.add("GRANT",Token.KEYWORD1); tsqlKeywords.add("GROUP",Token.KEYWORD1); tsqlKeywords.add("HAVING",Token.KEYWORD1); tsqlKeywords.add("HOLDLOCK",Token.KEYWORD1); tsqlKeywords.add("IDENTITY_INSERT",Token.KEYWORD1); tsqlKeywords.add("IDENTITYCOL",Token.KEYWORD1); tsqlKeywords.add("ID",Token.KEYWORD1); tsqlKeywords.add("IF",Token.KEYWORD1); tsqlKeywords.add("INDEX",Token.KEYWORD1); tsqlKeywords.add("INNER",Token.KEYWORD1); tsqlKeywords.add("INSERT",Token.KEYWORD1); tsqlKeywords.add("INTO",Token.KEYWORD1); tsqlKeywords.add("IS",Token.KEYWORD1); tsqlKeywords.add("ISOLATION",Token.KEYWORD1); tsqlKeywords.add("KEY",Token.KEYWORD1); tsqlKeywords.add("KILL",Token.KEYWORD1); tsqlKeywords.add("LEVEL",Token.KEYWORD1); tsqlKeywords.add("LINENO",Token.KEYWORD1); tsqlKeywords.add("LOAD",Token.KEYWORD1); tsqlKeywords.add("MAX",Token.KEYWORD1); tsqlKeywords.add("MIN",Token.KEYWORD1); tsqlKeywords.add("MIRROREXIT",Token.KEYWORD1); tsqlKeywords.add("NATIONAL",Token.KEYWORD1); tsqlKeywords.add("NOCHECK",Token.KEYWORD1); tsqlKeywords.add("NONCLUSTERED",Token.KEYWORD1); tsqlKeywords.add("OF",Token.KEYWORD1); tsqlKeywords.add("OFF",Token.KEYWORD1); tsqlKeywords.add("OFFSETS",Token.KEYWORD1); tsqlKeywords.add("ON",Token.KEYWORD1); tsqlKeywords.add("ONCE",Token.KEYWORD1); tsqlKeywords.add("ONLY",Token.KEYWORD1); tsqlKeywords.add("OPEN",Token.KEYWORD1); tsqlKeywords.add("OPENDATASOURCE",Token.KEYWORD1); tsqlKeywords.add("OPENQUERY",Token.KEYWORD1); tsqlKeywords.add("OPENROWSET",Token.KEYWORD1); tsqlKeywords.add("OPTION",Token.KEYWORD1); tsqlKeywords.add("ORDER",Token.KEYWORD1); tsqlKeywords.add("OVER",Token.KEYWORD1); tsqlKeywords.add("PERCENT",Token.KEYWORD1); tsqlKeywords.add("PERM",Token.KEYWORD1); tsqlKeywords.add("PERMANENT",Token.KEYWORD1); tsqlKeywords.add("PIPE",Token.KEYWORD1); tsqlKeywords.add("PLAN",Token.KEYWORD1); tsqlKeywords.add("PRECISION",Token.KEYWORD1); tsqlKeywords.add("PREPARE",Token.KEYWORD1); tsqlKeywords.add("PRIMARY",Token.KEYWORD1); tsqlKeywords.add("PRINT",Token.KEYWORD1); tsqlKeywords.add("PRIVILEGES",Token.KEYWORD1); tsqlKeywords.add("PROC",Token.KEYWORD1); tsqlKeywords.add("PROCEDURE",Token.KEYWORD1); tsqlKeywords.add("PROCESSEXIT",Token.KEYWORD1); tsqlKeywords.add("PUBLIC",Token.KEYWORD1); tsqlKeywords.add("QUOTED_IDENTIFIER",Token.KEYWORD1); tsqlKeywords.add("RAISERROR",Token.KEYWORD1); tsqlKeywords.add("READ",Token.KEYWORD1); tsqlKeywords.add("READTEXT",Token.KEYWORD1); tsqlKeywords.add("RECONFIGURE",Token.KEYWORD1); tsqlKeywords.add("REFERENCES",Token.KEYWORD1); tsqlKeywords.add("REPEATABLE",Token.KEYWORD1); tsqlKeywords.add("REPLICATION",Token.KEYWORD1); tsqlKeywords.add("RESTORE",Token.KEYWORD1); tsqlKeywords.add("RESTRICT",Token.KEYWORD1); tsqlKeywords.add("RETURN",Token.KEYWORD1); tsqlKeywords.add("REVOKE",Token.KEYWORD1); tsqlKeywords.add("ROLLBACK",Token.KEYWORD1); tsqlKeywords.add("ROWGUIDCOL",Token.KEYWORD1); tsqlKeywords.add("RULE",Token.KEYWORD1); tsqlKeywords.add("SAVE",Token.KEYWORD1); tsqlKeywords.add("SCHEMA",Token.KEYWORD1); tsqlKeywords.add("SELECT",Token.KEYWORD1); tsqlKeywords.add("SERIALIZABLE",Token.KEYWORD1); tsqlKeywords.add("SET",Token.KEYWORD1); tsqlKeywords.add("SETUSER",Token.KEYWORD1); tsqlKeywords.add("SHUTDOWN",Token.KEYWORD1); tsqlKeywords.add("STATISTICS",Token.KEYWORD1); tsqlKeywords.add("TABLE",Token.KEYWORD1); tsqlKeywords.add("TAPE",Token.KEYWORD1); tsqlKeywords.add("TEMP",Token.KEYWORD1); tsqlKeywords.add("TEMPORARY",Token.KEYWORD1); tsqlKeywords.add("TEXTIMAGE_ON",Token.KEYWORD1); tsqlKeywords.add("THEN",Token.KEYWORD1); tsqlKeywords.add("TO",Token.KEYWORD1); tsqlKeywords.add("TOP",Token.KEYWORD1); tsqlKeywords.add("TRAN",Token.KEYWORD1); tsqlKeywords.add("TRANSACTION",Token.KEYWORD1); tsqlKeywords.add("TRIGGER",Token.KEYWORD1); tsqlKeywords.add("TRUNCATE",Token.KEYWORD1); tsqlKeywords.add("TSEQUAL",Token.KEYWORD1); tsqlKeywords.add("UNCOMMITTED",Token.KEYWORD1); tsqlKeywords.add("UNION",Token.KEYWORD1); tsqlKeywords.add("UNIQUE",Token.KEYWORD1); tsqlKeywords.add("UPDATE",Token.KEYWORD1); tsqlKeywords.add("UPDATETEXT",Token.KEYWORD1); tsqlKeywords.add("USE",Token.KEYWORD1); tsqlKeywords.add("VALUES",Token.KEYWORD1); tsqlKeywords.add("VARYING",Token.KEYWORD1); tsqlKeywords.add("VIEW",Token.KEYWORD1); tsqlKeywords.add("WAITFOR",Token.KEYWORD1); tsqlKeywords.add("WHEN",Token.KEYWORD1); tsqlKeywords.add("WHERE",Token.KEYWORD1); tsqlKeywords.add("WHILE",Token.KEYWORD1); tsqlKeywords.add("WITH",Token.KEYWORD1); tsqlKeywords.add("WORK",Token.KEYWORD1); tsqlKeywords.add("WRITETEXT",Token.KEYWORD1); } private static void addDataTypes() { tsqlKeywords.add("binary",Token.KEYWORD1); tsqlKeywords.add("bit",Token.KEYWORD1); tsqlKeywords.add("char",Token.KEYWORD1); tsqlKeywords.add("character",Token.KEYWORD1); tsqlKeywords.add("datetime",Token.KEYWORD1); tsqlKeywords.add("decimal",Token.KEYWORD1); tsqlKeywords.add("float",Token.KEYWORD1); tsqlKeywords.add("image",Token.KEYWORD1); tsqlKeywords.add("int",Token.KEYWORD1); tsqlKeywords.add("integer",Token.KEYWORD1); tsqlKeywords.add("money",Token.KEYWORD1); tsqlKeywords.add("name",Token.KEYWORD1); tsqlKeywords.add("numeric",Token.KEYWORD1); tsqlKeywords.add("nchar",Token.KEYWORD1); tsqlKeywords.add("nvarchar",Token.KEYWORD1); tsqlKeywords.add("ntext",Token.KEYWORD1); tsqlKeywords.add("real",Token.KEYWORD1); tsqlKeywords.add("smalldatetime",Token.KEYWORD1); tsqlKeywords.add("smallint",Token.KEYWORD1); tsqlKeywords.add("smallmoney",Token.KEYWORD1); tsqlKeywords.add("text",Token.KEYWORD1); tsqlKeywords.add("timestamp",Token.KEYWORD1); tsqlKeywords.add("tinyint",Token.KEYWORD1); tsqlKeywords.add("uniqueidentifier",Token.KEYWORD1); tsqlKeywords.add("varbinary",Token.KEYWORD1); tsqlKeywords.add("varchar",Token.KEYWORD1); } private static void addSystemFunctions() { tsqlKeywords.add("@@CONNECTIONS",Token.KEYWORD2); tsqlKeywords.add("@@CPU_BUSY",Token.KEYWORD2); tsqlKeywords.add("@@CURSOR_ROWS",Token.KEYWORD2); tsqlKeywords.add("@@DATEFIRST",Token.KEYWORD2); tsqlKeywords.add("@@DBTS",Token.KEYWORD2); tsqlKeywords.add("@@ERROR",Token.KEYWORD2); tsqlKeywords.add("@@FETCH_STATUS",Token.KEYWORD2); tsqlKeywords.add("@@IDENTITY",Token.KEYWORD2); tsqlKeywords.add("@@IDLE",Token.KEYWORD2); tsqlKeywords.add("@@IO_BUSY",Token.KEYWORD2); tsqlKeywords.add("@@LANGID",Token.KEYWORD2); tsqlKeywords.add("@@LANGUAGE",Token.KEYWORD2); tsqlKeywords.add("@@LOCK_TIMEOUT",Token.KEYWORD2); tsqlKeywords.add("@@MAX_CONNECTIONS",Token.KEYWORD2); tsqlKeywords.add("@@MAX_PRECISION",Token.KEYWORD2); tsqlKeywords.add("@@NESTLEVEL",Token.KEYWORD2); tsqlKeywords.add("@@OPTIONS",Token.KEYWORD2); tsqlKeywords.add("@@PACK_RECEIVED",Token.KEYWORD2); tsqlKeywords.add("@@PACK_SENT",Token.KEYWORD2); tsqlKeywords.add("@@PACKET_ERRORS",Token.KEYWORD2); tsqlKeywords.add("@@PROCID",Token.KEYWORD2); tsqlKeywords.add("@@REMSERVER",Token.KEYWORD2); tsqlKeywords.add("@@ROWCOUNT",Token.KEYWORD2); tsqlKeywords.add("@@SERVERNAME",Token.KEYWORD2); tsqlKeywords.add("@@SERVICENAME",Token.KEYWORD2); tsqlKeywords.add("@@SPID",Token.KEYWORD2); tsqlKeywords.add("@@TEXTSIZE",Token.KEYWORD2); tsqlKeywords.add("@@TIMETICKS",Token.KEYWORD2); tsqlKeywords.add("@@TOTAL_ERRORS",Token.KEYWORD2); tsqlKeywords.add("@@TOTAL_READ",Token.KEYWORD2); tsqlKeywords.add("@@TOTAL_WRITE",Token.KEYWORD2); tsqlKeywords.add("@@TRANCOUNT",Token.KEYWORD2); tsqlKeywords.add("@@VERSION",Token.KEYWORD2); tsqlKeywords.add("ABS",Token.KEYWORD2); tsqlKeywords.add("ACOS",Token.KEYWORD2); tsqlKeywords.add("APP_NAME",Token.KEYWORD2); tsqlKeywords.add("ASCII",Token.KEYWORD2); tsqlKeywords.add("ASIN",Token.KEYWORD2); tsqlKeywords.add("ATAN",Token.KEYWORD2); tsqlKeywords.add("ATN2",Token.KEYWORD2); tsqlKeywords.add("CASE",Token.KEYWORD2); tsqlKeywords.add("CAST",Token.KEYWORD2); tsqlKeywords.add("CEILING",Token.KEYWORD2); // tsqlKeywords.add("CHAR",Token.KEYWORD2); tsqlKeywords.add("CHARINDEX",Token.KEYWORD2); tsqlKeywords.add("COALESCE",Token.KEYWORD2); tsqlKeywords.add("COL_LENGTH",Token.KEYWORD2); tsqlKeywords.add("COL_NAME",Token.KEYWORD2); tsqlKeywords.add("COLUMNPROPERTY",Token.KEYWORD2); tsqlKeywords.add("CONVERT",Token.KEYWORD2); tsqlKeywords.add("COS",Token.KEYWORD2); tsqlKeywords.add("COT",Token.KEYWORD2); tsqlKeywords.add("CURRENT_TIME",Token.KEYWORD2); tsqlKeywords.add("CURRENT_DATE",Token.KEYWORD2); tsqlKeywords.add("CURRENT_TIMESTAMP",Token.KEYWORD2); tsqlKeywords.add("CURRENT_USER",Token.KEYWORD2); tsqlKeywords.add("CURSOR_STATUS",Token.KEYWORD2); tsqlKeywords.add("DATABASEPROPERTY",Token.KEYWORD2); tsqlKeywords.add("DATALENGTH",Token.KEYWORD2); tsqlKeywords.add("DATEADD",Token.KEYWORD2); tsqlKeywords.add("DATEDIFF",Token.KEYWORD2); tsqlKeywords.add("DATENAME",Token.KEYWORD2); tsqlKeywords.add("DATEPART",Token.KEYWORD2); tsqlKeywords.add("DAY",Token.KEYWORD2); tsqlKeywords.add("DB_ID",Token.KEYWORD2); tsqlKeywords.add("DB_NAME",Token.KEYWORD2); tsqlKeywords.add("DEGREES",Token.KEYWORD2); tsqlKeywords.add("DIFFERENCE",Token.KEYWORD2); tsqlKeywords.add("EXP",Token.KEYWORD2); tsqlKeywords.add("FILE_ID",Token.KEYWORD2); tsqlKeywords.add("FILE_NAME",Token.KEYWORD2); tsqlKeywords.add("FILEGROUP_ID",Token.KEYWORD2); tsqlKeywords.add("FILEGROUP_NAME",Token.KEYWORD2); tsqlKeywords.add("FILEGROUPPROPERTY",Token.KEYWORD2); tsqlKeywords.add("FILEPROPERTY",Token.KEYWORD2); tsqlKeywords.add("FLOOR",Token.KEYWORD2); tsqlKeywords.add("FORMATMESSAGE",Token.KEYWORD2); tsqlKeywords.add("FULLTEXTCATALOGPROPERTY",Token.KEYWORD2); tsqlKeywords.add("FULLTEXTSERVICEPROPERTY",Token.KEYWORD2); tsqlKeywords.add("GETANSINULL",Token.KEYWORD2); tsqlKeywords.add("GETDATE",Token.KEYWORD2); tsqlKeywords.add("HOST_ID",Token.KEYWORD2); tsqlKeywords.add("HOST_NAME",Token.KEYWORD2); tsqlKeywords.add("IDENT_INCR",Token.KEYWORD2); tsqlKeywords.add("IDENT_SEED",Token.KEYWORD2); // tsqlKeywords.add("IDENTITY",Token.KEYWORD2); tsqlKeywords.add("IDENTITY_INSERT",Token.KEYWORD2); tsqlKeywords.add("INDEX_COL",Token.KEYWORD2); tsqlKeywords.add("INDEXPROPERTY",Token.KEYWORD2); tsqlKeywords.add("IS_MEMBER",Token.KEYWORD2); tsqlKeywords.add("IS_SRVROLEMEMBER",Token.KEYWORD2); tsqlKeywords.add("ISDATE",Token.KEYWORD2); tsqlKeywords.add("ISNULL",Token.KEYWORD2); tsqlKeywords.add("ISNUMERIC",Token.KEYWORD2); tsqlKeywords.add("LEFT",Token.KEYWORD2); tsqlKeywords.add("LEN",Token.KEYWORD2); tsqlKeywords.add("LOG",Token.KEYWORD2); tsqlKeywords.add("LOG10",Token.KEYWORD2); tsqlKeywords.add("LOWER",Token.KEYWORD2); tsqlKeywords.add("LTRIM",Token.KEYWORD2); tsqlKeywords.add("MONTH",Token.KEYWORD2); // tsqlKeywords.add("NCHAR",Token.KEYWORD2); tsqlKeywords.add("NEWID",Token.KEYWORD2); tsqlKeywords.add("NULLIF",Token.KEYWORD2); tsqlKeywords.add("OBJECT_ID",Token.KEYWORD2); tsqlKeywords.add("OBJECT_NAME",Token.KEYWORD2); tsqlKeywords.add("OBJECTPROPERTY",Token.KEYWORD2); tsqlKeywords.add("PARSENAME",Token.KEYWORD2); tsqlKeywords.add("PATINDEX",Token.KEYWORD2); tsqlKeywords.add("PERMISSIONS",Token.KEYWORD2); tsqlKeywords.add("PI",Token.KEYWORD2); tsqlKeywords.add("POWER",Token.KEYWORD2); tsqlKeywords.add("QUOTENAME",Token.KEYWORD2); tsqlKeywords.add("RADIANS",Token.KEYWORD2); tsqlKeywords.add("RAND",Token.KEYWORD2); tsqlKeywords.add("REPLACE",Token.KEYWORD2); tsqlKeywords.add("REPLICATE",Token.KEYWORD2); tsqlKeywords.add("REVERSE",Token.KEYWORD2); tsqlKeywords.add("RIGHT",Token.KEYWORD2); tsqlKeywords.add("ROUND",Token.KEYWORD2); tsqlKeywords.add("RTRIM",Token.KEYWORD2); tsqlKeywords.add("SESSION_USER",Token.KEYWORD2); tsqlKeywords.add("SIGN",Token.KEYWORD2); tsqlKeywords.add("SIN",Token.KEYWORD2); tsqlKeywords.add("SOUNDEX",Token.KEYWORD2); tsqlKeywords.add("SPACE",Token.KEYWORD2); tsqlKeywords.add("SQRT",Token.KEYWORD2); tsqlKeywords.add("SQUARE",Token.KEYWORD2); tsqlKeywords.add("STATS_DATE",Token.KEYWORD2); tsqlKeywords.add("STR",Token.KEYWORD2); tsqlKeywords.add("STUFF",Token.KEYWORD2); tsqlKeywords.add("SUBSTRING",Token.KEYWORD2); tsqlKeywords.add("SUSER_ID",Token.KEYWORD2); tsqlKeywords.add("SUSER_NAME",Token.KEYWORD2); tsqlKeywords.add("SUSER_SID",Token.KEYWORD2); tsqlKeywords.add("SUSER_SNAME",Token.KEYWORD2); tsqlKeywords.add("SYSTEM_USER",Token.KEYWORD2); tsqlKeywords.add("TAN",Token.KEYWORD2); tsqlKeywords.add("TEXTPTR",Token.KEYWORD2); tsqlKeywords.add("TEXTVALID",Token.KEYWORD2); tsqlKeywords.add("TYPEPROPERTY",Token.KEYWORD2); tsqlKeywords.add("UNICODE",Token.KEYWORD2); tsqlKeywords.add("UPPER",Token.KEYWORD2); tsqlKeywords.add("USER_ID",Token.KEYWORD2); tsqlKeywords.add("USER_NAME",Token.KEYWORD2); tsqlKeywords.add("USER",Token.KEYWORD2); tsqlKeywords.add("YEAR",Token.KEYWORD2); } private static void addOperators() { tsqlKeywords.add("ALL",Token.KEYWORD1); tsqlKeywords.add("AND",Token.KEYWORD1); tsqlKeywords.add("ANY",Token.KEYWORD1); tsqlKeywords.add("BETWEEN",Token.KEYWORD1); tsqlKeywords.add("CROSS",Token.KEYWORD1); tsqlKeywords.add("EXISTS",Token.KEYWORD1); tsqlKeywords.add("IN",Token.KEYWORD1); tsqlKeywords.add("INTERSECT",Token.KEYWORD1); tsqlKeywords.add("JOIN",Token.KEYWORD1); tsqlKeywords.add("LIKE",Token.KEYWORD1); tsqlKeywords.add("NOT",Token.KEYWORD1); tsqlKeywords.add("NULL",Token.KEYWORD1); tsqlKeywords.add("OR",Token.KEYWORD1); tsqlKeywords.add("OUTER",Token.KEYWORD1); tsqlKeywords.add("SOME",Token.KEYWORD1); } private static void addSystemStoredProcedures() { tsqlKeywords.add("sp_add_agent_parameter",Token.KEYWORD3); tsqlKeywords.add("sp_add_agent_profile",Token.KEYWORD3); tsqlKeywords.add("sp_add_alert",Token.KEYWORD3); tsqlKeywords.add("sp_add_category",Token.KEYWORD3); tsqlKeywords.add("sp_add_data_file_recover_suspect_db",Token.KEYWORD3); tsqlKeywords.add("sp_add_job",Token.KEYWORD3); tsqlKeywords.add("sp_add_jobschedule",Token.KEYWORD3); tsqlKeywords.add("sp_add_jobserver",Token.KEYWORD3); tsqlKeywords.add("sp_add_jobstep",Token.KEYWORD3); tsqlKeywords.add("sp_add_log_file_recover_suspect_db",Token.KEYWORD3); tsqlKeywords.add("sp_add_notification",Token.KEYWORD3); tsqlKeywords.add("sp_add_operator",Token.KEYWORD3); tsqlKeywords.add("sp_add_targetservergroup",Token.KEYWORD3); tsqlKeywords.add("sp_add_targetsvrgrp_member",Token.KEYWORD3); tsqlKeywords.add("sp_addalias",Token.KEYWORD3); tsqlKeywords.add("sp_addapprole",Token.KEYWORD3); tsqlKeywords.add("sp_addarticle",Token.KEYWORD3); tsqlKeywords.add("sp_adddistpublisher",Token.KEYWORD3); tsqlKeywords.add("sp_adddistributiondb",Token.KEYWORD3); tsqlKeywords.add("sp_adddistributor",Token.KEYWORD3); tsqlKeywords.add("sp_addextendedproc",Token.KEYWORD3); tsqlKeywords.add("sp_addgroup",Token.KEYWORD3); tsqlKeywords.add("sp_addlinkedserver",Token.KEYWORD3); tsqlKeywords.add("sp_addlinkedsrvlogin",Token.KEYWORD3); tsqlKeywords.add("sp_addlinkedsrvlogin",Token.KEYWORD3); tsqlKeywords.add("sp_addlogin",Token.KEYWORD3); tsqlKeywords.add("sp_addmergearticle",Token.KEYWORD3); tsqlKeywords.add("sp_addmergefilter",Token.KEYWORD3); tsqlKeywords.add("sp_addmergepublication",Token.KEYWORD3); tsqlKeywords.add("sp_addmergepullsubscription",Token.KEYWORD3); tsqlKeywords.add("sp_addmergepullsubscription_agent",Token.KEYWORD3); tsqlKeywords.add("sp_addmergesubscription",Token.KEYWORD3); tsqlKeywords.add("sp_addmessage",Token.KEYWORD3); tsqlKeywords.add("sp_addpublication",Token.KEYWORD3); tsqlKeywords.add("sp_addpublication_snapshot",Token.KEYWORD3); tsqlKeywords.add("sp_addpublisher70",Token.KEYWORD3); tsqlKeywords.add("sp_addpullsubscription",Token.KEYWORD3); tsqlKeywords.add("sp_addpullsubscription_agent",Token.KEYWORD3); tsqlKeywords.add("sp_addremotelogin",Token.KEYWORD3); tsqlKeywords.add("sp_addrole",Token.KEYWORD3); tsqlKeywords.add("sp_addrolemember",Token.KEYWORD3); tsqlKeywords.add("sp_addserver",Token.KEYWORD3); tsqlKeywords.add("sp_addsrvrolemember",Token.KEYWORD3); tsqlKeywords.add("sp_addsubscriber",Token.KEYWORD3); tsqlKeywords.add("sp_addsubscriber_schedule",Token.KEYWORD3); tsqlKeywords.add("sp_addsubscription",Token.KEYWORD3); tsqlKeywords.add("sp_addsynctriggers",Token.KEYWORD3); tsqlKeywords.add("sp_addtabletocontents",Token.KEYWORD3); tsqlKeywords.add("sp_addtask",Token.KEYWORD3); tsqlKeywords.add("sp_addtype",Token.KEYWORD3); tsqlKeywords.add("sp_addumpdevice",Token.KEYWORD3); tsqlKeywords.add("sp_adduser",Token.KEYWORD3); tsqlKeywords.add("sp_altermessage",Token.KEYWORD3); tsqlKeywords.add("sp_apply_job_to_targets",Token.KEYWORD3); tsqlKeywords.add("sp_approlepassword",Token.KEYWORD3); tsqlKeywords.add("sp_article_validation",Token.KEYWORD3); tsqlKeywords.add("sp_articlecolumn",Token.KEYWORD3); tsqlKeywords.add("sp_articlefilter",Token.KEYWORD3); tsqlKeywords.add("sp_articlesynctranprocs",Token.KEYWORD3); tsqlKeywords.add("sp_articleview",Token.KEYWORD3); tsqlKeywords.add("sp_attach_db",Token.KEYWORD3); tsqlKeywords.add("sp_attach_single_file_db",Token.KEYWORD3); tsqlKeywords.add("sp_autostats",Token.KEYWORD3); tsqlKeywords.add("sp_bindefault",Token.KEYWORD3); tsqlKeywords.add("sp_bindrule",Token.KEYWORD3); tsqlKeywords.add("sp_bindsession",Token.KEYWORD3); tsqlKeywords.add("sp_browsereplcmds",Token.KEYWORD3); tsqlKeywords.add("sp_catalogs",Token.KEYWORD3); tsqlKeywords.add("sp_certify_removable",Token.KEYWORD3); tsqlKeywords.add("sp_change_agent_parameter",Token.KEYWORD3); tsqlKeywords.add("sp_change_agent_profile",Token.KEYWORD3); tsqlKeywords.add("sp_change_subscription_properties",Token.KEYWORD3); tsqlKeywords.add("sp_change_users_login",Token.KEYWORD3); tsqlKeywords.add("sp_changearticle",Token.KEYWORD3); tsqlKeywords.add("sp_changedbowner",Token.KEYWORD3); tsqlKeywords.add("sp_changedistpublisher",Token.KEYWORD3); tsqlKeywords.add("sp_changedistributiondb",Token.KEYWORD3); tsqlKeywords.add("sp_changedistributor_password",Token.KEYWORD3); tsqlKeywords.add("sp_changedistributor_property",Token.KEYWORD3); tsqlKeywords.add("sp_changegroup",Token.KEYWORD3); tsqlKeywords.add("sp_changemergearticle",Token.KEYWORD3); tsqlKeywords.add("sp_changemergefilter",Token.KEYWORD3); tsqlKeywords.add("sp_changemergepublication",Token.KEYWORD3); tsqlKeywords.add("sp_changemergepullsubscription",Token.KEYWORD3); tsqlKeywords.add("sp_changemergesubscription",Token.KEYWORD3); tsqlKeywords.add("sp_changeobjectowner",Token.KEYWORD3); tsqlKeywords.add("sp_changepublication",Token.KEYWORD3); tsqlKeywords.add("sp_changesubscriber",Token.KEYWORD3); tsqlKeywords.add("sp_changesubscriber_schedule",Token.KEYWORD3); tsqlKeywords.add("sp_changesubstatus",Token.KEYWORD3); tsqlKeywords.add("sp_check_for_sync_trigger",Token.KEYWORD3); tsqlKeywords.add("sp_column_privileges",Token.KEYWORD3); tsqlKeywords.add("sp_column_privileges_ex",Token.KEYWORD3); tsqlKeywords.add("sp_columns",Token.KEYWORD3); tsqlKeywords.add("sp_columns_ex",Token.KEYWORD3); tsqlKeywords.add("sp_configure",Token.KEYWORD3); tsqlKeywords.add("sp_create_removable",Token.KEYWORD3); tsqlKeywords.add("sp_createorphan",Token.KEYWORD3); tsqlKeywords.add("sp_createstats",Token.KEYWORD3); tsqlKeywords.add("sp_cursor",Token.KEYWORD3); tsqlKeywords.add("sp_cursor_list",Token.KEYWORD3); tsqlKeywords.add("sp_cursorclose",Token.KEYWORD3); tsqlKeywords.add("sp_cursorexecute",Token.KEYWORD3); tsqlKeywords.add("sp_cursorfetch",Token.KEYWORD3); tsqlKeywords.add("sp_cursoropen",Token.KEYWORD3); tsqlKeywords.add("sp_cursoroption",Token.KEYWORD3); tsqlKeywords.add("sp_cursorprepare",Token.KEYWORD3); tsqlKeywords.add("sp_cursorunprepare",Token.KEYWORD3); tsqlKeywords.add("sp_cycle_errorlog",Token.KEYWORD3); tsqlKeywords.add("sp_databases",Token.KEYWORD3); tsqlKeywords.add("sp_datatype_info",Token.KEYWORD3); tsqlKeywords.add("sp_dbcmptlevel",Token.KEYWORD3); tsqlKeywords.add("sp_dbfixedrolepermission",Token.KEYWORD3); tsqlKeywords.add("sp_dboption",Token.KEYWORD3); tsqlKeywords.add("sp_defaultdb",Token.KEYWORD3); tsqlKeywords.add("sp_defaultlanguage",Token.KEYWORD3); tsqlKeywords.add("sp_delete_alert",Token.KEYWORD3); tsqlKeywords.add("sp_delete_backuphistory",Token.KEYWORD3); tsqlKeywords.add("sp_delete_category",Token.KEYWORD3); tsqlKeywords.add("sp_delete_job",Token.KEYWORD3); tsqlKeywords.add("sp_delete_jobschedule",Token.KEYWORD3); tsqlKeywords.add("sp_delete_jobserver",Token.KEYWORD3); tsqlKeywords.add("sp_delete_jobstep",Token.KEYWORD3); tsqlKeywords.add("sp_delete_notification",Token.KEYWORD3); tsqlKeywords.add("sp_delete_operator",Token.KEYWORD3); tsqlKeywords.add("sp_delete_targetserver",Token.KEYWORD3); tsqlKeywords.add("sp_delete_targetservergroup",Token.KEYWORD3); tsqlKeywords.add("sp_delete_targetsvrgrp_member",Token.KEYWORD3); tsqlKeywords.add("sp_deletemergeconflictrow",Token.KEYWORD3); tsqlKeywords.add("sp_denylogin",Token.KEYWORD3); tsqlKeywords.add("sp_depends",Token.KEYWORD3); tsqlKeywords.add("sp_describe_cursor",Token.KEYWORD3); tsqlKeywords.add("sp_describe_cursor_columns",Token.KEYWORD3); tsqlKeywords.add("sp_describe_cursor_tables",Token.KEYWORD3); tsqlKeywords.add("sp_detach_db",Token.KEYWORD3); tsqlKeywords.add("sp_drop_agent_parameter",Token.KEYWORD3); tsqlKeywords.add("sp_drop_agent_profile",Token.KEYWORD3); tsqlKeywords.add("sp_dropalias",Token.KEYWORD3); tsqlKeywords.add("sp_dropapprole",Token.KEYWORD3); tsqlKeywords.add("sp_droparticle",Token.KEYWORD3); tsqlKeywords.add("sp_dropdevice",Token.KEYWORD3); tsqlKeywords.add("sp_dropdistpublisher",Token.KEYWORD3); tsqlKeywords.add("sp_dropdistributiondb",Token.KEYWORD3); tsqlKeywords.add("sp_dropdistributor",Token.KEYWORD3); tsqlKeywords.add("sp_dropextendedproc",Token.KEYWORD3); tsqlKeywords.add("sp_dropgroup",Token.KEYWORD3); tsqlKeywords.add("sp_droplinkedsrvlogin",Token.KEYWORD3); tsqlKeywords.add("sp_droplinkedsrvlogin",Token.KEYWORD3); tsqlKeywords.add("sp_droplogin",Token.KEYWORD3); tsqlKeywords.add("sp_dropmergearticle",Token.KEYWORD3); tsqlKeywords.add("sp_dropmergefilter",Token.KEYWORD3); tsqlKeywords.add("sp_dropmergepublication",Token.KEYWORD3); tsqlKeywords.add("sp_dropmergepullsubscription",Token.KEYWORD3); tsqlKeywords.add("sp_dropmergesubscription",Token.KEYWORD3); tsqlKeywords.add("sp_dropmessage",Token.KEYWORD3); tsqlKeywords.add("sp_droporphans",Token.KEYWORD3); tsqlKeywords.add("sp_droppublication",Token.KEYWORD3); tsqlKeywords.add("sp_droppullsubscription",Token.KEYWORD3); tsqlKeywords.add("sp_dropremotelogin",Token.KEYWORD3); tsqlKeywords.add("sp_droprole",Token.KEYWORD3); tsqlKeywords.add("sp_droprolemember",Token.KEYWORD3); tsqlKeywords.add("sp_dropserver",Token.KEYWORD3); tsqlKeywords.add("sp_dropsrvrolemember",Token.KEYWORD3); tsqlKeywords.add("sp_dropsubscriber",Token.KEYWORD3); tsqlKeywords.add("sp_dropsubscription",Token.KEYWORD3); tsqlKeywords.add("sp_droptask",Token.KEYWORD3); tsqlKeywords.add("sp_droptype",Token.KEYWORD3); tsqlKeywords.add("sp_dropuser",Token.KEYWORD3); tsqlKeywords.add("sp_dropwebtask",Token.KEYWORD3); tsqlKeywords.add("sp_dsninfo",Token.KEYWORD3); tsqlKeywords.add("sp_dumpparamcmd",Token.KEYWORD3); tsqlKeywords.add("sp_enumcodepages",Token.KEYWORD3); tsqlKeywords.add("sp_enumcustomresolvers",Token.KEYWORD3); tsqlKeywords.add("sp_enumdsn",Token.KEYWORD3); tsqlKeywords.add("sp_enumfullsubscribers",Token.KEYWORD3); tsqlKeywords.add("sp_execute",Token.KEYWORD3); tsqlKeywords.add("sp_executesql",Token.KEYWORD3); tsqlKeywords.add("sp_expired_subscription_cleanup",Token.KEYWORD3); tsqlKeywords.add("sp_fkeys",Token.KEYWORD3); tsqlKeywords.add("sp_foreignkeys",Token.KEYWORD3); tsqlKeywords.add("sp_fulltext_catalog",Token.KEYWORD3); tsqlKeywords.add("sp_fulltext_column",Token.KEYWORD3); tsqlKeywords.add("sp_fulltext_database",Token.KEYWORD3); tsqlKeywords.add("sp_fulltext_service",Token.KEYWORD3); tsqlKeywords.add("sp_fulltext_table",Token.KEYWORD3); tsqlKeywords.add("sp_generatefilters",Token.KEYWORD3); tsqlKeywords.add("sp_get_distributor",Token.KEYWORD3); tsqlKeywords.add("sp_getbindtoken",Token.KEYWORD3); tsqlKeywords.add("sp_getmergedeletetype",Token.KEYWORD3); tsqlKeywords.add("sp_grant_publication_access",Token.KEYWORD3); tsqlKeywords.add("sp_grantdbaccess",Token.KEYWORD3); tsqlKeywords.add("sp_grantlogin",Token.KEYWORD3); tsqlKeywords.add("sp_help",Token.KEYWORD3); tsqlKeywords.add("sp_help_agent_default",Token.KEYWORD3); tsqlKeywords.add("sp_help_agent_parameter",Token.KEYWORD3); tsqlKeywords.add("sp_help_agent_profile",Token.KEYWORD3); tsqlKeywords.add("sp_help_alert",Token.KEYWORD3); tsqlKeywords.add("sp_help_category",Token.KEYWORD3); tsqlKeywords.add("sp_help_downloadlist",Token.KEYWORD3); tsqlKeywords.add("sp_help_fulltext_catalogs",Token.KEYWORD3); tsqlKeywords.add("sp_help_fulltext_catalogs_cursor",Token.KEYWORD3); tsqlKeywords.add("sp_help_fulltext_columns",Token.KEYWORD3); tsqlKeywords.add("sp_help_fulltext_columns_cursor",Token.KEYWORD3); tsqlKeywords.add("sp_help_fulltext_tables",Token.KEYWORD3); tsqlKeywords.add("sp_help_fulltext_tables_cursor",Token.KEYWORD3); tsqlKeywords.add("sp_help_job",Token.KEYWORD3); tsqlKeywords.add("sp_help_jobhistory",Token.KEYWORD3); tsqlKeywords.add("sp_help_jobschedule",Token.KEYWORD3); tsqlKeywords.add("sp_help_jobserver",Token.KEYWORD3); tsqlKeywords.add("sp_help_jobstep",Token.KEYWORD3); tsqlKeywords.add("sp_help_notification",Token.KEYWORD3); tsqlKeywords.add("sp_help_operator",Token.KEYWORD3); tsqlKeywords.add("sp_help_publication_access",Token.KEYWORD3); tsqlKeywords.add("sp_help_targetserver",Token.KEYWORD3); tsqlKeywords.add("sp_help_targetservergroup",Token.KEYWORD3); tsqlKeywords.add("sp_helparticle",Token.KEYWORD3); tsqlKeywords.add("sp_helparticlecolumns",Token.KEYWORD3); tsqlKeywords.add("sp_helpconstraint",Token.KEYWORD3); tsqlKeywords.add("sp_helpdb",Token.KEYWORD3); tsqlKeywords.add("sp_helpdbfixedrole",Token.KEYWORD3); tsqlKeywords.add("sp_helpdevice",Token.KEYWORD3); tsqlKeywords.add("sp_helpdistpublisher",Token.KEYWORD3); tsqlKeywords.add("sp_helpdistributiondb",Token.KEYWORD3); tsqlKeywords.add("sp_helpdistributor",Token.KEYWORD3); tsqlKeywords.add("sp_helpextendedproc",Token.KEYWORD3); tsqlKeywords.add("sp_helpfile",Token.KEYWORD3); tsqlKeywords.add("sp_helpfilegroup",Token.KEYWORD3); tsqlKeywords.add("sp_helpgroup",Token.KEYWORD3); tsqlKeywords.add("sp_helphistory",Token.KEYWORD3); tsqlKeywords.add("sp_helpindex",Token.KEYWORD3); tsqlKeywords.add("sp_helplanguage",Token.KEYWORD3); tsqlKeywords.add("sp_helplinkedsrvlogin",Token.KEYWORD3); tsqlKeywords.add("sp_helplogins",Token.KEYWORD3); tsqlKeywords.add("sp_helpmergearticle",Token.KEYWORD3); tsqlKeywords.add("sp_helpmergearticleconflicts",Token.KEYWORD3); tsqlKeywords.add("sp_helpmergeconflictrows",Token.KEYWORD3); tsqlKeywords.add("sp_helpmergedeleteconflictrows",Token.KEYWORD3); tsqlKeywords.add("sp_helpmergefilter",Token.KEYWORD3); tsqlKeywords.add("sp_helpmergepublication",Token.KEYWORD3); tsqlKeywords.add("sp_helpmergepullsubscription",Token.KEYWORD3); tsqlKeywords.add("sp_helpmergesubscription",Token.KEYWORD3); tsqlKeywords.add("sp_helpntgroup",Token.KEYWORD3); tsqlKeywords.add("sp_helppublication",Token.KEYWORD3); tsqlKeywords.add("sp_helppullsubscription",Token.KEYWORD3); tsqlKeywords.add("sp_helpremotelogin",Token.KEYWORD3); tsqlKeywords.add("sp_helpreplicationdboption",Token.KEYWORD3); tsqlKeywords.add("sp_helprole",Token.KEYWORD3); tsqlKeywords.add("sp_helprolemember",Token.KEYWORD3); tsqlKeywords.add("sp_helprotect",Token.KEYWORD3); tsqlKeywords.add("sp_helpserver",Token.KEYWORD3); tsqlKeywords.add("sp_helpsort",Token.KEYWORD3); tsqlKeywords.add("sp_helpsrvrole",Token.KEYWORD3); tsqlKeywords.add("sp_helpsrvrolemember",Token.KEYWORD3); tsqlKeywords.add("sp_helpsubscriberinfo",Token.KEYWORD3); tsqlKeywords.add("sp_helpsubscription",Token.KEYWORD3); tsqlKeywords.add("sp_helpsubscription_properties",Token.KEYWORD3); tsqlKeywords.add("sp_helptask",Token.KEYWORD3); tsqlKeywords.add("sp_helptext",Token.KEYWORD3); tsqlKeywords.add("sp_helptrigger",Token.KEYWORD3); tsqlKeywords.add("sp_helpuser",Token.KEYWORD3); tsqlKeywords.add("sp_indexes",Token.KEYWORD3); tsqlKeywords.add("sp_indexoption",Token.KEYWORD3); tsqlKeywords.add("sp_link_publication",Token.KEYWORD3); tsqlKeywords.add("sp_linkedservers",Token.KEYWORD3); tsqlKeywords.add("sp_lock",Token.KEYWORD3); tsqlKeywords.add("sp_makewebtask",Token.KEYWORD3); tsqlKeywords.add("sp_manage_jobs_by_login",Token.KEYWORD3); tsqlKeywords.add("sp_mergedummyupdate",Token.KEYWORD3); tsqlKeywords.add("sp_mergesubscription_cleanup",Token.KEYWORD3); tsqlKeywords.add("sp_monitor",Token.KEYWORD3); tsqlKeywords.add("sp_msx_defect",Token.KEYWORD3); tsqlKeywords.add("sp_msx_enlist",Token.KEYWORD3); tsqlKeywords.add("sp_OACreate",Token.KEYWORD3); tsqlKeywords.add("sp_OADestroy",Token.KEYWORD3); tsqlKeywords.add("sp_OAGetErrorInfo",Token.KEYWORD3); tsqlKeywords.add("sp_OAGetProperty",Token.KEYWORD3); tsqlKeywords.add("sp_OAMethod",Token.KEYWORD3); tsqlKeywords.add("sp_OASetProperty",Token.KEYWORD3); tsqlKeywords.add("sp_OAStop",Token.KEYWORD3); tsqlKeywords.add("sp_password",Token.KEYWORD3); tsqlKeywords.add("sp_pkeys",Token.KEYWORD3); tsqlKeywords.add("sp_post_msx_operation",Token.KEYWORD3); tsqlKeywords.add("sp_prepare",Token.KEYWORD3); tsqlKeywords.add("sp_primarykeys",Token.KEYWORD3); tsqlKeywords.add("sp_processmail",Token.KEYWORD3); tsqlKeywords.add("sp_procoption",Token.KEYWORD3); tsqlKeywords.add("sp_publication_validation",Token.KEYWORD3); tsqlKeywords.add("sp_purge_jobhistory",Token.KEYWORD3); tsqlKeywords.add("sp_purgehistory",Token.KEYWORD3); tsqlKeywords.add("sp_reassigntask",Token.KEYWORD3); tsqlKeywords.add("sp_recompile",Token.KEYWORD3); tsqlKeywords.add("sp_refreshsubscriptions",Token.KEYWORD3); tsqlKeywords.add("sp_refreshview",Token.KEYWORD3); tsqlKeywords.add("sp_reinitmergepullsubscription",Token.KEYWORD3); tsqlKeywords.add("sp_reinitmergesubscription",Token.KEYWORD3); tsqlKeywords.add("sp_reinitpullsubscription",Token.KEYWORD3); tsqlKeywords.add("sp_reinitsubscription",Token.KEYWORD3); tsqlKeywords.add("sp_remoteoption",Token.KEYWORD3); tsqlKeywords.add("sp_remove_job_from_targets",Token.KEYWORD3); tsqlKeywords.add("sp_removedbreplication",Token.KEYWORD3); tsqlKeywords.add("sp_rename",Token.KEYWORD3); tsqlKeywords.add("sp_renamedb",Token.KEYWORD3); tsqlKeywords.add("sp_replcmds",Token.KEYWORD3); tsqlKeywords.add("sp_replcounters",Token.KEYWORD3); tsqlKeywords.add("sp_repldone",Token.KEYWORD3); tsqlKeywords.add("sp_replflush",Token.KEYWORD3); tsqlKeywords.add("sp_replication_agent_checkup",Token.KEYWORD3); tsqlKeywords.add("sp_replicationdboption",Token.KEYWORD3); tsqlKeywords.add("sp_replsetoriginator",Token.KEYWORD3); tsqlKeywords.add("sp_replshowcmds",Token.KEYWORD3); tsqlKeywords.add("sp_repltrans",Token.KEYWORD3); tsqlKeywords.add("sp_reset_connection",Token.KEYWORD3); tsqlKeywords.add("sp_resync_targetserver",Token.KEYWORD3); tsqlKeywords.add("sp_revoke_publication_access",Token.KEYWORD3); tsqlKeywords.add("sp_revokedbaccess",Token.KEYWORD3); tsqlKeywords.add("sp_revokelogin",Token.KEYWORD3); tsqlKeywords.add("sp_runwebtask",Token.KEYWORD3); tsqlKeywords.add("sp_script_synctran_commands",Token.KEYWORD3); tsqlKeywords.add("sp_scriptdelproc",Token.KEYWORD3); tsqlKeywords.add("sp_scriptinsproc",Token.KEYWORD3); tsqlKeywords.add("sp_scriptmappedupdproc",Token.KEYWORD3); tsqlKeywords.add("sp_scriptupdproc",Token.KEYWORD3); tsqlKeywords.add("sp_sdidebug",Token.KEYWORD3); tsqlKeywords.add("sp_server_info",Token.KEYWORD3); tsqlKeywords.add("sp_serveroption",Token.KEYWORD3); tsqlKeywords.add("sp_serveroption",Token.KEYWORD3); tsqlKeywords.add("sp_setapprole",Token.KEYWORD3); tsqlKeywords.add("sp_setnetname",Token.KEYWORD3); tsqlKeywords.add("sp_spaceused",Token.KEYWORD3); tsqlKeywords.add("sp_special_columns",Token.KEYWORD3); tsqlKeywords.add("sp_sproc_columns",Token.KEYWORD3); tsqlKeywords.add("sp_srvrolepermission",Token.KEYWORD3); tsqlKeywords.add("sp_start_job",Token.KEYWORD3); tsqlKeywords.add("sp_statistics",Token.KEYWORD3); tsqlKeywords.add("sp_stop_job",Token.KEYWORD3); tsqlKeywords.add("sp_stored_procedures",Token.KEYWORD3); tsqlKeywords.add("sp_subscription_cleanup",Token.KEYWORD3); tsqlKeywords.add("sp_table_privileges",Token.KEYWORD3); tsqlKeywords.add("sp_table_privileges_ex",Token.KEYWORD3); tsqlKeywords.add("sp_table_validation",Token.KEYWORD3); tsqlKeywords.add("sp_tableoption",Token.KEYWORD3); tsqlKeywords.add("sp_tables",Token.KEYWORD3); tsqlKeywords.add("sp_tables_ex",Token.KEYWORD3); tsqlKeywords.add("sp_unbindefault",Token.KEYWORD3); tsqlKeywords.add("sp_unbindrule",Token.KEYWORD3); tsqlKeywords.add("sp_unprepare",Token.KEYWORD3); tsqlKeywords.add("sp_update_agent_profile",Token.KEYWORD3); tsqlKeywords.add("sp_update_alert",Token.KEYWORD3); tsqlKeywords.add("sp_update_category",Token.KEYWORD3); tsqlKeywords.add("sp_update_job",Token.KEYWORD3); tsqlKeywords.add("sp_update_jobschedule",Token.KEYWORD3); tsqlKeywords.add("sp_update_jobstep",Token.KEYWORD3); tsqlKeywords.add("sp_update_notification",Token.KEYWORD3); tsqlKeywords.add("sp_update_operator",Token.KEYWORD3); tsqlKeywords.add("sp_update_targetservergroup",Token.KEYWORD3); tsqlKeywords.add("sp_updatestats",Token.KEYWORD3); tsqlKeywords.add("sp_updatetask",Token.KEYWORD3); tsqlKeywords.add("sp_validatelogins",Token.KEYWORD3); tsqlKeywords.add("sp_validname",Token.KEYWORD3); tsqlKeywords.add("sp_who",Token.KEYWORD3); tsqlKeywords.add("xp_cmdshell",Token.KEYWORD3); tsqlKeywords.add("xp_deletemail",Token.KEYWORD3); tsqlKeywords.add("xp_enumgroups",Token.KEYWORD3); tsqlKeywords.add("xp_findnextmsg",Token.KEYWORD3); tsqlKeywords.add("xp_findnextmsg",Token.KEYWORD3); tsqlKeywords.add("xp_grantlogin",Token.KEYWORD3); tsqlKeywords.add("xp_logevent",Token.KEYWORD3); tsqlKeywords.add("xp_loginconfig",Token.KEYWORD3); tsqlKeywords.add("xp_logininfo",Token.KEYWORD3); tsqlKeywords.add("xp_msver",Token.KEYWORD3); tsqlKeywords.add("xp_readmail",Token.KEYWORD3); tsqlKeywords.add("xp_revokelogin",Token.KEYWORD3); tsqlKeywords.add("xp_sendmail",Token.KEYWORD3); tsqlKeywords.add("xp_sprintf",Token.KEYWORD3); tsqlKeywords.add("xp_sqlinventory",Token.KEYWORD3); tsqlKeywords.add("xp_sqlmaint",Token.KEYWORD3); tsqlKeywords.add("xp_sqltrace",Token.KEYWORD3); tsqlKeywords.add("xp_sscanf",Token.KEYWORD3); tsqlKeywords.add("xp_startmail",Token.KEYWORD3); tsqlKeywords.add("xp_stopmail",Token.KEYWORD3); tsqlKeywords.add("xp_trace_addnewqueue",Token.KEYWORD3); tsqlKeywords.add("xp_trace_deletequeuedefinition",Token.KEYWORD3); tsqlKeywords.add("xp_trace_destroyqueue",Token.KEYWORD3); tsqlKeywords.add("xp_trace_enumqueuedefname",Token.KEYWORD3); tsqlKeywords.add("xp_trace_enumqueuehandles",Token.KEYWORD3); tsqlKeywords.add("xp_trace_eventclassrequired",Token.KEYWORD3); tsqlKeywords.add("xp_trace_flushqueryhistory",Token.KEYWORD3); tsqlKeywords.add("xp_trace_generate_event",Token.KEYWORD3); tsqlKeywords.add("xp_trace_getappfilter",Token.KEYWORD3); tsqlKeywords.add("xp_trace_getconnectionidfilter",Token.KEYWORD3); tsqlKeywords.add("xp_trace_getcpufilter",Token.KEYWORD3); tsqlKeywords.add("xp_trace_getdbidfilter",Token.KEYWORD3); tsqlKeywords.add("xp_trace_getdurationfilter",Token.KEYWORD3); tsqlKeywords.add("xp_trace_geteventfilter",Token.KEYWORD3); tsqlKeywords.add("xp_trace_geteventnames",Token.KEYWORD3); tsqlKeywords.add("xp_trace_getevents",Token.KEYWORD3); tsqlKeywords.add("xp_trace_gethostfilter",Token.KEYWORD3); tsqlKeywords.add("xp_trace_gethpidfilter",Token.KEYWORD3); tsqlKeywords.add("xp_trace_getindidfilter",Token.KEYWORD3); tsqlKeywords.add("xp_trace_getntdmfilter",Token.KEYWORD3); tsqlKeywords.add("xp_trace_getntnmfilter",Token.KEYWORD3); tsqlKeywords.add("xp_trace_getobjidfilter",Token.KEYWORD3); tsqlKeywords.add("xp_trace_getqueueautostart",Token.KEYWORD3); tsqlKeywords.add("xp_trace_getqueuedestination",Token.KEYWORD3); tsqlKeywords.add("xp_trace_getqueueproperties",Token.KEYWORD3); tsqlKeywords.add("xp_trace_getreadfilter",Token.KEYWORD3); tsqlKeywords.add("xp_trace_getserverfilter",Token.KEYWORD3); tsqlKeywords.add("xp_trace_getseverityfilter",Token.KEYWORD3); tsqlKeywords.add("xp_trace_getspidfilter",Token.KEYWORD3); tsqlKeywords.add("xp_trace_getsysobjectsfilter",Token.KEYWORD3); tsqlKeywords.add("xp_trace_gettextfilter",Token.KEYWORD3); tsqlKeywords.add("xp_trace_getuserfilter",Token.KEYWORD3); tsqlKeywords.add("xp_trace_getwritefilter",Token.KEYWORD3); tsqlKeywords.add("xp_trace_loadqueuedefinition",Token.KEYWORD3); tsqlKeywords.add("xp_trace_pausequeue",Token.KEYWORD3); tsqlKeywords.add("xp_trace_restartqueue",Token.KEYWORD3); tsqlKeywords.add("xp_trace_savequeuedefinition",Token.KEYWORD3); tsqlKeywords.add("xp_trace_setappfilter",Token.KEYWORD3); tsqlKeywords.add("xp_trace_setconnectionidfilter",Token.KEYWORD3); tsqlKeywords.add("xp_trace_setcpufilter",Token.KEYWORD3); tsqlKeywords.add("xp_trace_setdbidfilter",Token.KEYWORD3); tsqlKeywords.add("xp_trace_setdurationfilter",Token.KEYWORD3); tsqlKeywords.add("xp_trace_seteventclassrequired",Token.KEYWORD3); tsqlKeywords.add("xp_trace_seteventfilter",Token.KEYWORD3); tsqlKeywords.add("xp_trace_sethostfilter",Token.KEYWORD3); tsqlKeywords.add("xp_trace_sethpidfilter",Token.KEYWORD3); tsqlKeywords.add("xp_trace_setindidfilter",Token.KEYWORD3); tsqlKeywords.add("xp_trace_setntdmfilter",Token.KEYWORD3); tsqlKeywords.add("xp_trace_setntnmfilter",Token.KEYWORD3); tsqlKeywords.add("xp_trace_setobjidfilter",Token.KEYWORD3); tsqlKeywords.add("xp_trace_setqueryhistory",Token.KEYWORD3); tsqlKeywords.add("xp_trace_setqueueautostart",Token.KEYWORD3); tsqlKeywords.add("xp_trace_setqueuecreateinfo",Token.KEYWORD3); tsqlKeywords.add("xp_trace_setqueuedestination",Token.KEYWORD3); tsqlKeywords.add("xp_trace_setreadfilter",Token.KEYWORD3); tsqlKeywords.add("xp_trace_setserverfilter",Token.KEYWORD3); tsqlKeywords.add("xp_trace_setseverityfilter",Token.KEYWORD3); tsqlKeywords.add("xp_trace_setspidfilter",Token.KEYWORD3); tsqlKeywords.add("xp_trace_setsysobjectsfilter",Token.KEYWORD3); tsqlKeywords.add("xp_trace_settextfilter",Token.KEYWORD3); tsqlKeywords.add("xp_trace_setuserfilter",Token.KEYWORD3); tsqlKeywords.add("xp_trace_setwritefilter",Token.KEYWORD3); } private static void addSystemTables() { tsqlKeywords.add("backupfile",Token.KEYWORD3); tsqlKeywords.add("backupmediafamily",Token.KEYWORD3); tsqlKeywords.add("backupmediaset",Token.KEYWORD3); tsqlKeywords.add("backupset",Token.KEYWORD3); tsqlKeywords.add("MSagent_parameters",Token.KEYWORD3); tsqlKeywords.add("MSagent_profiles",Token.KEYWORD3); tsqlKeywords.add("MSarticles",Token.KEYWORD3); tsqlKeywords.add("MSdistpublishers",Token.KEYWORD3); tsqlKeywords.add("MSdistribution_agents",Token.KEYWORD3); tsqlKeywords.add("MSdistribution_history",Token.KEYWORD3); tsqlKeywords.add("MSdistributiondbs",Token.KEYWORD3); tsqlKeywords.add("MSdistributor",Token.KEYWORD3); tsqlKeywords.add("MSlogreader_agents",Token.KEYWORD3); tsqlKeywords.add("MSlogreader_history",Token.KEYWORD3); tsqlKeywords.add("MSmerge_agents",Token.KEYWORD3); tsqlKeywords.add("MSmerge_contents",Token.KEYWORD3); tsqlKeywords.add("MSmerge_delete_conflicts",Token.KEYWORD3); tsqlKeywords.add("MSmerge_genhistory",Token.KEYWORD3); tsqlKeywords.add("MSmerge_history",Token.KEYWORD3); tsqlKeywords.add("MSmerge_replinfo",Token.KEYWORD3); tsqlKeywords.add("MSmerge_subscriptions",Token.KEYWORD3); tsqlKeywords.add("MSmerge_tombstone",Token.KEYWORD3); tsqlKeywords.add("MSpublication_access",Token.KEYWORD3); tsqlKeywords.add("Mspublications",Token.KEYWORD3); tsqlKeywords.add("Mspublisher_databases",Token.KEYWORD3); tsqlKeywords.add("MSrepl_commands",Token.KEYWORD3); tsqlKeywords.add("MSrepl_errors",Token.KEYWORD3); tsqlKeywords.add("Msrepl_originators",Token.KEYWORD3); tsqlKeywords.add("MSrepl_transactions",Token.KEYWORD3); tsqlKeywords.add("MSrepl_version",Token.KEYWORD3); tsqlKeywords.add("MSreplication_objects",Token.KEYWORD3); tsqlKeywords.add("MSreplication_subscriptions",Token.KEYWORD3); tsqlKeywords.add("MSsnapshot_agents",Token.KEYWORD3); tsqlKeywords.add("MSsnapshot_history",Token.KEYWORD3); tsqlKeywords.add("MSsubscriber_info",Token.KEYWORD3); tsqlKeywords.add("MSsubscriber_schedule",Token.KEYWORD3); tsqlKeywords.add("MSsubscription_properties",Token.KEYWORD3); tsqlKeywords.add("MSsubscriptions",Token.KEYWORD3); tsqlKeywords.add("restorefile",Token.KEYWORD3); tsqlKeywords.add("restorefilegroup",Token.KEYWORD3); tsqlKeywords.add("restorehistory",Token.KEYWORD3); tsqlKeywords.add("sysalerts",Token.KEYWORD3); tsqlKeywords.add("sysallocations",Token.KEYWORD3); tsqlKeywords.add("sysaltfiles",Token.KEYWORD3); tsqlKeywords.add("sysarticles",Token.KEYWORD3); tsqlKeywords.add("sysarticleupdates",Token.KEYWORD3); tsqlKeywords.add("syscacheobjects",Token.KEYWORD3); tsqlKeywords.add("syscategories",Token.KEYWORD3); tsqlKeywords.add("syscharsets",Token.KEYWORD3); tsqlKeywords.add("syscolumns",Token.KEYWORD3); tsqlKeywords.add("syscomments",Token.KEYWORD3); tsqlKeywords.add("sysconfigures",Token.KEYWORD3); tsqlKeywords.add("sysconstraints",Token.KEYWORD3); tsqlKeywords.add("syscurconfigs",Token.KEYWORD3); tsqlKeywords.add("sysdatabases",Token.KEYWORD3); tsqlKeywords.add("sysdatabases",Token.KEYWORD3); tsqlKeywords.add("sysdepends",Token.KEYWORD3); tsqlKeywords.add("sysdevices",Token.KEYWORD3); tsqlKeywords.add("sysdownloadlist",Token.KEYWORD3); tsqlKeywords.add("sysfilegroups",Token.KEYWORD3); tsqlKeywords.add("sysfiles",Token.KEYWORD3); tsqlKeywords.add("sysforeignkeys",Token.KEYWORD3); tsqlKeywords.add("sysfulltextcatalogs",Token.KEYWORD3); tsqlKeywords.add("sysindexes",Token.KEYWORD3); tsqlKeywords.add("sysindexkeys",Token.KEYWORD3); tsqlKeywords.add("sysjobhistory",Token.KEYWORD3); tsqlKeywords.add("sysjobs",Token.KEYWORD3); tsqlKeywords.add("sysjobschedules",Token.KEYWORD3); tsqlKeywords.add("sysjobservers",Token.KEYWORD3); tsqlKeywords.add("sysjobsteps",Token.KEYWORD3); tsqlKeywords.add("syslanguages",Token.KEYWORD3); tsqlKeywords.add("syslockinfo",Token.KEYWORD3); tsqlKeywords.add("syslogins",Token.KEYWORD3); tsqlKeywords.add("sysmembers",Token.KEYWORD3); tsqlKeywords.add("sysmergearticles",Token.KEYWORD3); tsqlKeywords.add("sysmergepublications",Token.KEYWORD3); tsqlKeywords.add("sysmergeschemachange",Token.KEYWORD3); tsqlKeywords.add("sysmergesubscriptions",Token.KEYWORD3); tsqlKeywords.add("sysmergesubsetfilters",Token.KEYWORD3); tsqlKeywords.add("sysmessages",Token.KEYWORD3); tsqlKeywords.add("sysnotifications",Token.KEYWORD3); tsqlKeywords.add("sysobjects",Token.KEYWORD3); tsqlKeywords.add("sysobjects",Token.KEYWORD3); tsqlKeywords.add("sysoledbusers",Token.KEYWORD3); tsqlKeywords.add("sysoperators",Token.KEYWORD3); tsqlKeywords.add("sysperfinfo",Token.KEYWORD3); tsqlKeywords.add("syspermissions",Token.KEYWORD3); tsqlKeywords.add("sysprocesses",Token.KEYWORD3); tsqlKeywords.add("sysprotects",Token.KEYWORD3); tsqlKeywords.add("syspublications",Token.KEYWORD3); tsqlKeywords.add("sysreferences",Token.KEYWORD3); tsqlKeywords.add("sysremotelogins",Token.KEYWORD3); tsqlKeywords.add("sysreplicationalerts",Token.KEYWORD3); tsqlKeywords.add("sysservers",Token.KEYWORD3); tsqlKeywords.add("sysservers",Token.KEYWORD3); tsqlKeywords.add("syssubscriptions",Token.KEYWORD3); tsqlKeywords.add("systargetservergroupmembers",Token.KEYWORD3); tsqlKeywords.add("systargetservergroups",Token.KEYWORD3); tsqlKeywords.add("systargetservers",Token.KEYWORD3); tsqlKeywords.add("systaskids",Token.KEYWORD3); tsqlKeywords.add("systypes",Token.KEYWORD3); tsqlKeywords.add("sysusers",Token.KEYWORD3); } private static KeywordMap tsqlKeywords; }
Java
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.android.inputmethod.latin; import android.test.AndroidTestCase; import com.android.inputmethod.latin.tests.R; public class SuggestTests extends AndroidTestCase { private static final String TAG = "SuggestTests"; private SuggestHelper sh; @Override protected void setUp() { int[] resId = new int[] { R.raw.test }; sh = new SuggestHelper(TAG, getTestContext(), resId); } /************************** Tests ************************/ /** * Tests for simple completions of one character. */ public void testCompletion1char() { assertTrue(sh.isDefaultSuggestion("peopl", "people")); assertTrue(sh.isDefaultSuggestion("abou", "about")); assertTrue(sh.isDefaultSuggestion("thei", "their")); } /** * Tests for simple completions of two characters. */ public void testCompletion2char() { assertTrue(sh.isDefaultSuggestion("peop", "people")); assertTrue(sh.isDefaultSuggestion("calli", "calling")); assertTrue(sh.isDefaultSuggestion("busine", "business")); } /** * Tests for proximity errors. */ public void testProximityPositive() { assertTrue(sh.isDefaultSuggestion("peiple", "people")); assertTrue(sh.isDefaultSuggestion("peoole", "people")); assertTrue(sh.isDefaultSuggestion("pwpple", "people")); } /** * Tests for proximity errors - negative, when the error key is not near. */ public void testProximityNegative() { assertFalse(sh.isDefaultSuggestion("arout", "about")); assertFalse(sh.isDefaultSuggestion("ire", "are")); } /** * Tests for checking if apostrophes are added automatically. */ public void testApostropheInsertion() { assertTrue(sh.isDefaultSuggestion("im", "I'm")); assertTrue(sh.isDefaultSuggestion("dont", "don't")); } /** * Test to make sure apostrophed word is not suggested for an apostrophed word. */ public void testApostrophe() { assertFalse(sh.isDefaultSuggestion("don't", "don't")); } /** * Tests for suggestion of capitalized version of a word. */ public void testCapitalization() { assertTrue(sh.isDefaultSuggestion("i'm", "I'm")); assertTrue(sh.isDefaultSuggestion("sunday", "Sunday")); assertTrue(sh.isDefaultSuggestion("sundat", "Sunday")); } /** * Tests to see if more than one completion is provided for certain prefixes. */ public void testMultipleCompletions() { assertTrue(sh.isASuggestion("com", "come")); assertTrue(sh.isASuggestion("com", "company")); assertTrue(sh.isASuggestion("th", "the")); assertTrue(sh.isASuggestion("th", "that")); assertTrue(sh.isASuggestion("th", "this")); assertTrue(sh.isASuggestion("th", "they")); } /** * Does the suggestion engine recognize zero frequency words as valid words. */ public void testZeroFrequencyAccepted() { assertTrue(sh.isValid("yikes")); assertFalse(sh.isValid("yike")); } /** * Tests to make sure that zero frequency words are not suggested as completions. */ public void testZeroFrequencySuggestionsNegative() { assertFalse(sh.isASuggestion("yike", "yikes")); assertFalse(sh.isASuggestion("what", "whatcha")); } /** * Tests to ensure that words with large edit distances are not suggested, in some cases * and not considered corrections, in some cases. */ public void testTooLargeEditDistance() { assertFalse(sh.isASuggestion("sniyr", "about")); assertFalse(sh.isDefaultCorrection("rjw", "the")); } /** * Make sure sh.isValid is case-sensitive. */ public void testValidityCaseSensitivity() { assertTrue(sh.isValid("Sunday")); assertFalse(sh.isValid("sunday")); } /** * Are accented forms of words suggested as corrections? */ public void testAccents() { // ni<LATIN SMALL LETTER N WITH TILDE>o assertTrue(sh.isDefaultCorrection("nino", "ni\u00F1o")); // ni<LATIN SMALL LETTER N WITH TILDE>o assertTrue(sh.isDefaultCorrection("nimo", "ni\u00F1o")); // Mar<LATIN SMALL LETTER I WITH ACUTE>a assertTrue(sh.isDefaultCorrection("maria", "Mar\u00EDa")); } /** * Make sure bigrams are showing when first character is typed * and don't show any when there aren't any */ public void testBigramsAtFirstChar() { assertTrue(sh.isDefaultNextSuggestion("about", "p", "part")); assertTrue(sh.isDefaultNextSuggestion("I'm", "a", "about")); assertTrue(sh.isDefaultNextSuggestion("about", "b", "business")); assertTrue(sh.isASuggestion("about", "b", "being")); assertFalse(sh.isDefaultNextSuggestion("about", "p", "business")); } /** * Make sure bigrams score affects the original score */ public void testBigramsScoreEffect() { assertTrue(sh.isDefaultCorrection("pa", "page")); assertTrue(sh.isDefaultNextCorrection("about", "pa", "part")); assertTrue(sh.isDefaultCorrection("sa", "said")); assertTrue(sh.isDefaultNextCorrection("from", "sa", "same")); } }
Java
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.android.inputmethod.latin; import android.test.AndroidTestCase; import android.util.Log; import com.android.inputmethod.latin.tests.R; import java.io.InputStreamReader; import java.io.InputStream; import java.io.BufferedReader; import java.util.StringTokenizer; public class SuggestPerformanceTests extends AndroidTestCase { private static final String TAG = "SuggestPerformanceTests"; private String mTestText; private SuggestHelper sh; @Override protected void setUp() { // TODO Figure out a way to directly using the dictionary rather than copying it over // For testing with real dictionary, TEMPORARILY COPY main dictionary into test directory. // DO NOT SUBMIT real dictionary under test directory. //int[] resId = new int[] { R.raw.main0, R.raw.main1, R.raw.main2 }; int[] resId = new int[] { R.raw.test }; sh = new SuggestHelper(TAG, getTestContext(), resId); loadString(); } private void loadString() { try { InputStream is = getTestContext().getResources().openRawResource(R.raw.testtext); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = reader.readLine(); while (line != null) { sb.append(line + " "); line = reader.readLine(); } mTestText = sb.toString(); } catch (Exception e) { e.printStackTrace(); } } /************************** Helper functions ************************/ private int lookForSuggestion(String prevWord, String currentWord) { for (int i = 1; i < currentWord.length(); i++) { if (i == 1) { if (sh.isDefaultNextSuggestion(prevWord, currentWord.substring(0, i), currentWord)) { return i; } } else { if (sh.isDefaultNextCorrection(prevWord, currentWord.substring(0, i), currentWord)) { return i; } } } return currentWord.length(); } private double runText(boolean withBigrams) { StringTokenizer st = new StringTokenizer(mTestText); String prevWord = null; int typeCount = 0; int characterCount = 0; // without space int wordCount = 0; while (st.hasMoreTokens()) { String currentWord = st.nextToken(); boolean endCheck = false; if (currentWord.matches("[\\w]*[\\.|?|!|*|@|&|/|:|;]")) { currentWord = currentWord.substring(0, currentWord.length() - 1); endCheck = true; } if (withBigrams && prevWord != null) { typeCount += lookForSuggestion(prevWord, currentWord); } else { typeCount += lookForSuggestion(null, currentWord); } characterCount += currentWord.length(); if (!endCheck) prevWord = currentWord; wordCount++; } double result = (double) (characterCount - typeCount) / characterCount * 100; if (withBigrams) { Log.i(TAG, "with bigrams -> " + result + " % saved!"); } else { Log.i(TAG, "without bigrams -> " + result + " % saved!"); } Log.i(TAG, "\ttotal number of words: " + wordCount); Log.i(TAG, "\ttotal number of characters: " + mTestText.length()); Log.i(TAG, "\ttotal number of characters without space: " + characterCount); Log.i(TAG, "\ttotal number of characters typed: " + typeCount); return result; } /************************** Performance Tests ************************/ /** * Compare the Suggest with and without bigram * Check the log for detail */ public void testSuggestPerformance() { assertTrue(runText(false) <= runText(true)); } }
Java
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.android.inputmethod.latin; import android.content.Context; import android.text.TextUtils; import android.util.Log; import com.android.inputmethod.latin.Suggest; import com.android.inputmethod.latin.UserBigramDictionary; import com.android.inputmethod.latin.WordComposer; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.channels.Channels; import java.util.List; import java.util.Locale; import java.util.StringTokenizer; public class SuggestHelper { private Suggest mSuggest; private UserBigramDictionary mUserBigram; private final String TAG; /** Uses main dictionary only **/ public SuggestHelper(String tag, Context context, int[] resId) { TAG = tag; InputStream[] is = null; try { // merging separated dictionary into one if dictionary is separated int total = 0; is = new InputStream[resId.length]; for (int i = 0; i < resId.length; i++) { is[i] = context.getResources().openRawResource(resId[i]); total += is[i].available(); } ByteBuffer byteBuffer = ByteBuffer.allocateDirect(total).order(ByteOrder.nativeOrder()); int got = 0; for (int i = 0; i < resId.length; i++) { got += Channels.newChannel(is[i]).read(byteBuffer); } if (got != total) { Log.w(TAG, "Read " + got + " bytes, expected " + total); } else { mSuggest = new Suggest(context, byteBuffer); Log.i(TAG, "Created mSuggest " + total + " bytes"); } } catch (IOException e) { Log.w(TAG, "No available memory for binary dictionary"); } finally { try { if (is != null) { for (int i = 0; i < is.length; i++) { is[i].close(); } } } catch (IOException e) { Log.w(TAG, "Failed to close input stream"); } } mSuggest.setAutoTextEnabled(false); mSuggest.setCorrectionMode(Suggest.CORRECTION_FULL_BIGRAM); } /** Uses both main dictionary and user-bigram dictionary **/ public SuggestHelper(String tag, Context context, int[] resId, int userBigramMax, int userBigramDelete) { this(tag, context, resId); mUserBigram = new UserBigramDictionary(context, null, Locale.US.toString(), Suggest.DIC_USER); mUserBigram.setDatabaseMax(userBigramMax); mUserBigram.setDatabaseDelete(userBigramDelete); mSuggest.setUserBigramDictionary(mUserBigram); } void changeUserBigramLocale(Context context, Locale locale) { if (mUserBigram != null) { flushUserBigrams(); mUserBigram.close(); mUserBigram = new UserBigramDictionary(context, null, locale.toString(), Suggest.DIC_USER); mSuggest.setUserBigramDictionary(mUserBigram); } } private WordComposer createWordComposer(CharSequence s) { WordComposer word = new WordComposer(); for (int i = 0; i < s.length(); i++) { final char c = s.charAt(i); int[] codes; // If it's not a lowercase letter, don't find adjacent letters if (c < 'a' || c > 'z') { codes = new int[] { c }; } else { codes = adjacents[c - 'a']; } word.add(c, codes); } return word; } private void showList(String title, List<CharSequence> suggestions) { Log.i(TAG, title); for (int i = 0; i < suggestions.size(); i++) { Log.i(title, suggestions.get(i) + ", "); } } private boolean isDefaultSuggestion(List<CharSequence> suggestions, CharSequence word) { // Check if either the word is what you typed or the first alternative return suggestions.size() > 0 && (/*TextUtils.equals(suggestions.get(0), word) || */ (suggestions.size() > 1 && TextUtils.equals(suggestions.get(1), word))); } boolean isDefaultSuggestion(CharSequence typed, CharSequence expected) { WordComposer word = createWordComposer(typed); List<CharSequence> suggestions = mSuggest.getSuggestions(null, word, false, null); return isDefaultSuggestion(suggestions, expected); } boolean isDefaultCorrection(CharSequence typed, CharSequence expected) { WordComposer word = createWordComposer(typed); List<CharSequence> suggestions = mSuggest.getSuggestions(null, word, false, null); return isDefaultSuggestion(suggestions, expected) && mSuggest.hasMinimalCorrection(); } boolean isASuggestion(CharSequence typed, CharSequence expected) { WordComposer word = createWordComposer(typed); List<CharSequence> suggestions = mSuggest.getSuggestions(null, word, false, null); for (int i = 1; i < suggestions.size(); i++) { if (TextUtils.equals(suggestions.get(i), expected)) return true; } return false; } private void getBigramSuggestions(CharSequence previous, CharSequence typed) { if (!TextUtils.isEmpty(previous) && (typed.length() > 1)) { WordComposer firstChar = createWordComposer(Character.toString(typed.charAt(0))); mSuggest.getSuggestions(null, firstChar, false, previous); } } boolean isDefaultNextSuggestion(CharSequence previous, CharSequence typed, CharSequence expected) { WordComposer word = createWordComposer(typed); getBigramSuggestions(previous, typed); List<CharSequence> suggestions = mSuggest.getSuggestions(null, word, false, previous); return isDefaultSuggestion(suggestions, expected); } boolean isDefaultNextCorrection(CharSequence previous, CharSequence typed, CharSequence expected) { WordComposer word = createWordComposer(typed); getBigramSuggestions(previous, typed); List<CharSequence> suggestions = mSuggest.getSuggestions(null, word, false, previous); return isDefaultSuggestion(suggestions, expected) && mSuggest.hasMinimalCorrection(); } boolean isASuggestion(CharSequence previous, CharSequence typed, CharSequence expected) { WordComposer word = createWordComposer(typed); getBigramSuggestions(previous, typed); List<CharSequence> suggestions = mSuggest.getSuggestions(null, word, false, previous); for (int i = 1; i < suggestions.size(); i++) { if (TextUtils.equals(suggestions.get(i), expected)) return true; } return false; } boolean isValid(CharSequence typed) { return mSuggest.isValidWord(typed); } boolean isUserBigramSuggestion(CharSequence previous, char typed, CharSequence expected) { WordComposer word = createWordComposer(Character.toString(typed)); if (mUserBigram == null) return false; flushUserBigrams(); if (!TextUtils.isEmpty(previous) && !TextUtils.isEmpty(Character.toString(typed))) { WordComposer firstChar = createWordComposer(Character.toString(typed)); mSuggest.getSuggestions(null, firstChar, false, previous); boolean reloading = mUserBigram.reloadDictionaryIfRequired(); if (reloading) mUserBigram.waitForDictionaryLoading(); mUserBigram.getBigrams(firstChar, previous, mSuggest, null); } List<CharSequence> suggestions = mSuggest.mBigramSuggestions; for (int i = 0; i < suggestions.size(); i++) { if (TextUtils.equals(suggestions.get(i), expected)) return true; } return false; } void addToUserBigram(String sentence) { StringTokenizer st = new StringTokenizer(sentence); String previous = null; while (st.hasMoreTokens()) { String current = st.nextToken(); if (previous != null) { addToUserBigram(new String[] {previous, current}); } previous = current; } } void addToUserBigram(String[] pair) { if (mUserBigram != null && pair.length == 2) { mUserBigram.addBigrams(pair[0], pair[1]); } } void flushUserBigrams() { if (mUserBigram != null) { mUserBigram.flushPendingWrites(); mUserBigram.waitUntilUpdateDBDone(); } } final int[][] adjacents = { {'a','s','w','q',-1}, {'b','h','v','n','g','j',-1}, {'c','v','f','x','g',}, {'d','f','r','e','s','x',-1}, {'e','w','r','s','d',-1}, {'f','g','d','c','t','r',-1}, {'g','h','f','y','t','v',-1}, {'h','j','u','g','b','y',-1}, {'i','o','u','k',-1}, {'j','k','i','h','u','n',-1}, {'k','l','o','j','i','m',-1}, {'l','k','o','p',-1}, {'m','k','n','l',-1}, {'n','m','j','k','b',-1}, {'o','p','i','l',-1}, {'p','o',-1}, {'q','w',-1}, {'r','t','e','f',-1}, {'s','d','e','w','a','z',-1}, {'t','y','r',-1}, {'u','y','i','h','j',-1}, {'v','b','g','c','h',-1}, {'w','e','q',-1}, {'x','c','d','z','f',-1}, {'y','u','t','h','g',-1}, {'z','s','x','a','d',-1}, }; }
Java
/* * Copyright (C) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.android.inputmethod.latin; import com.android.inputmethod.latin.SwipeTracker.EventRingBuffer; import android.test.AndroidTestCase; public class EventRingBufferTests extends AndroidTestCase { @Override protected void setUp() throws Exception { super.setUp(); } @Override protected void tearDown() throws Exception { super.tearDown(); } private static float X_BASE = 1000f; private static float Y_BASE = 2000f; private static long TIME_BASE = 3000l; private static float x(int id) { return X_BASE + id; } private static float y(int id) { return Y_BASE + id; } private static long time(int id) { return TIME_BASE + id; } private static void addEvent(EventRingBuffer buf, int id) { buf.add(x(id), y(id), time(id)); } private static void assertEventSize(EventRingBuffer buf, int size) { assertEquals(size, buf.size()); } private static void assertEvent(EventRingBuffer buf, int pos, int id) { assertEquals(x(id), buf.getX(pos), 0f); assertEquals(y(id), buf.getY(pos), 0f); assertEquals(time(id), buf.getTime(pos)); } public void testClearBuffer() { EventRingBuffer buf = new EventRingBuffer(4); assertEventSize(buf, 0); addEvent(buf, 0); addEvent(buf, 1); addEvent(buf, 2); addEvent(buf, 3); addEvent(buf, 4); assertEventSize(buf, 4); buf.clear(); assertEventSize(buf, 0); } public void testRingBuffer() { EventRingBuffer buf = new EventRingBuffer(4); assertEventSize(buf, 0); // [0] addEvent(buf, 0); assertEventSize(buf, 1); // [1] 0 assertEvent(buf, 0, 0); addEvent(buf, 1); addEvent(buf, 2); assertEventSize(buf, 3); // [3] 2 1 0 assertEvent(buf, 0, 0); assertEvent(buf, 1, 1); assertEvent(buf, 2, 2); addEvent(buf, 3); assertEventSize(buf, 4); // [4] 3 2 1 0 assertEvent(buf, 0, 0); assertEvent(buf, 1, 1); assertEvent(buf, 2, 2); assertEvent(buf, 3, 3); addEvent(buf, 4); addEvent(buf, 5); assertEventSize(buf, 4); // [4] 5 4|3 2(1 0) assertEvent(buf, 0, 2); assertEvent(buf, 1, 3); assertEvent(buf, 2, 4); assertEvent(buf, 3, 5); addEvent(buf, 6); addEvent(buf, 7); addEvent(buf, 8); assertEventSize(buf, 4); // [4] 8 7 6 5|(4 3 2)1|0 assertEvent(buf, 0, 5); assertEvent(buf, 1, 6); assertEvent(buf, 2, 7); assertEvent(buf, 3, 8); } public void testDropOldest() { EventRingBuffer buf = new EventRingBuffer(4); addEvent(buf, 0); assertEventSize(buf, 1); // [1] 0 assertEvent(buf, 0, 0); buf.dropOldest(); assertEventSize(buf, 0); // [0] (0) addEvent(buf, 1); addEvent(buf, 2); addEvent(buf, 3); addEvent(buf, 4); assertEventSize(buf, 4); // [4] 4|3 2 1(0) assertEvent(buf, 0, 1); buf.dropOldest(); assertEventSize(buf, 3); // [3] 4|3 2(1)0 assertEvent(buf, 0, 2); buf.dropOldest(); assertEventSize(buf, 2); // [2] 4|3(2)10 assertEvent(buf, 0, 3); buf.dropOldest(); assertEventSize(buf, 1); // [1] 4|(3)210 assertEvent(buf, 0, 4); buf.dropOldest(); assertEventSize(buf, 0); // [0] (4)|3210 } }
Java
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.android.inputmethod.latin; import android.test.AndroidTestCase; import com.android.inputmethod.latin.tests.R; import java.util.Locale; public class UserBigramTests extends AndroidTestCase { private static final String TAG = "UserBigramTests"; private static final int SUGGESTION_STARTS = 6; private static final int MAX_DATA = 20; private static final int DELETE_DATA = 10; private SuggestHelper sh; @Override protected void setUp() { int[] resId = new int[] { R.raw.test }; sh = new SuggestHelper(TAG, getTestContext(), resId, MAX_DATA, DELETE_DATA); } /************************** Tests ************************/ /** * Test suggestion started at right time */ public void testUserBigram() { for (int i = 0; i < SUGGESTION_STARTS; i++) sh.addToUserBigram(pair1); for (int i = 0; i < (SUGGESTION_STARTS - 1); i++) sh.addToUserBigram(pair2); assertTrue(sh.isUserBigramSuggestion("user", 'b', "bigram")); assertFalse(sh.isUserBigramSuggestion("android", 'p', "platform")); } /** * Test loading correct (locale) bigrams */ public void testOpenAndClose() { for (int i = 0; i < SUGGESTION_STARTS; i++) sh.addToUserBigram(pair1); assertTrue(sh.isUserBigramSuggestion("user", 'b', "bigram")); // change to fr_FR sh.changeUserBigramLocale(getTestContext(), Locale.FRANCE); for (int i = 0; i < SUGGESTION_STARTS; i++) sh.addToUserBigram(pair3); assertTrue(sh.isUserBigramSuggestion("locale", 'f', "france")); assertFalse(sh.isUserBigramSuggestion("user", 'b', "bigram")); // change back to en_US sh.changeUserBigramLocale(getTestContext(), Locale.US); assertFalse(sh.isUserBigramSuggestion("locale", 'f', "france")); assertTrue(sh.isUserBigramSuggestion("user", 'b', "bigram")); } /** * Test data gets pruned when it is over maximum */ public void testPruningData() { for (int i = 0; i < SUGGESTION_STARTS; i++) sh.addToUserBigram(sentence0); sh.flushUserBigrams(); assertTrue(sh.isUserBigramSuggestion("Hello", 'w', "world")); sh.addToUserBigram(sentence1); sh.addToUserBigram(sentence2); assertTrue(sh.isUserBigramSuggestion("Hello", 'w', "world")); // pruning should happen sh.addToUserBigram(sentence3); sh.addToUserBigram(sentence4); // trying to reopen database to check pruning happened in database sh.changeUserBigramLocale(getTestContext(), Locale.US); assertFalse(sh.isUserBigramSuggestion("Hello", 'w', "world")); } final String[] pair1 = new String[] {"user", "bigram"}; final String[] pair2 = new String[] {"android","platform"}; final String[] pair3 = new String[] {"locale", "france"}; final String sentence0 = "Hello world"; final String sentence1 = "This is a test for user input based bigram"; final String sentence2 = "It learns phrases that contain both dictionary and nondictionary " + "words"; final String sentence3 = "This should give better suggestions than the previous version"; final String sentence4 = "Android stock keyboard is improving"; }
Java
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.pocketworkstation.pckeyboard; import android.content.ContentResolver; import android.content.Context; import android.database.ContentObserver; import android.database.Cursor; import android.os.SystemClock; import android.provider.ContactsContract.Contacts; import android.text.TextUtils; import android.util.Log; public class ContactsDictionary extends ExpandableDictionary { private static final String[] PROJECTION = { Contacts._ID, Contacts.DISPLAY_NAME, }; private static final String TAG = "ContactsDictionary"; /** * Frequency for contacts information into the dictionary */ private static final int FREQUENCY_FOR_CONTACTS = 128; private static final int FREQUENCY_FOR_CONTACTS_BIGRAM = 90; private static final int INDEX_NAME = 1; private ContentObserver mObserver; private long mLastLoadedContacts; public ContactsDictionary(Context context, int dicTypeId) { super(context, dicTypeId); // Perform a managed query. The Activity will handle closing and requerying the cursor // when needed. ContentResolver cres = context.getContentResolver(); cres.registerContentObserver( Contacts.CONTENT_URI, true,mObserver = new ContentObserver(null) { @Override public void onChange(boolean self) { setRequiresReload(true); } }); loadDictionary(); } @Override public synchronized void close() { if (mObserver != null) { getContext().getContentResolver().unregisterContentObserver(mObserver); mObserver = null; } super.close(); } @Override public void startDictionaryLoadingTaskLocked() { long now = SystemClock.uptimeMillis(); if (mLastLoadedContacts == 0 || now - mLastLoadedContacts > 30 * 60 * 1000 /* 30 minutes */) { super.startDictionaryLoadingTaskLocked(); } } @Override public void loadDictionaryAsync() { try { Cursor cursor = getContext().getContentResolver() .query(Contacts.CONTENT_URI, PROJECTION, null, null, null); if (cursor != null) { addWords(cursor); } } catch(IllegalStateException e) { Log.e(TAG, "Contacts DB is having problems"); } mLastLoadedContacts = SystemClock.uptimeMillis(); } private void addWords(Cursor cursor) { clearDictionary(); final int maxWordLength = getMaxWordLength(); try { if (cursor.moveToFirst()) { while (!cursor.isAfterLast()) { String name = cursor.getString(INDEX_NAME); if (name != null) { int len = name.length(); String prevWord = null; // TODO: Better tokenization for non-Latin writing systems for (int i = 0; i < len; i++) { if (Character.isLetter(name.charAt(i))) { int j; for (j = i + 1; j < len; j++) { char c = name.charAt(j); if (!(c == '-' || c == '\'' || Character.isLetter(c))) { break; } } String word = name.substring(i, j); i = j - 1; // Safeguard against adding really long words. Stack // may overflow due to recursion // Also don't add single letter words, possibly confuses // capitalization of i. final int wordLen = word.length(); if (wordLen < maxWordLength && wordLen > 1) { super.addWord(word, FREQUENCY_FOR_CONTACTS); if (!TextUtils.isEmpty(prevWord)) { // TODO Do not add email address // Not so critical super.setBigram(prevWord, word, FREQUENCY_FOR_CONTACTS_BIGRAM); } prevWord = word; } } } } cursor.moveToNext(); } } cursor.close(); } catch(IllegalStateException e) { Log.e(TAG, "Contacts DB is having problems"); } } }
Java
/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.pocketworkstation.pckeyboard; import android.content.Context; import android.graphics.drawable.Drawable; import android.os.Handler; import android.os.Message; import android.text.Layout; import android.text.SpannableStringBuilder; import android.text.StaticLayout; import android.view.Gravity; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.widget.PopupWindow; import android.widget.TextView; import java.util.ArrayList; import java.util.List; public class Tutorial implements OnTouchListener { private List<Bubble> mBubbles = new ArrayList<Bubble>(); private View mInputView; private LatinIME mIme; private int[] mLocation = new int[2]; private static final int MSG_SHOW_BUBBLE = 0; private int mBubbleIndex; Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case MSG_SHOW_BUBBLE: Bubble bubba = (Bubble) msg.obj; bubba.show(mLocation[0], mLocation[1]); break; } } }; class Bubble { Drawable bubbleBackground; int x; int y; int width; int gravity; CharSequence text; boolean dismissOnTouch; boolean dismissOnClose; PopupWindow window; TextView textView; View inputView; Bubble(Context context, View inputView, int backgroundResource, int bx, int by, int textResource1, int textResource2) { bubbleBackground = context.getResources().getDrawable(backgroundResource); x = bx; y = by; width = (int) (inputView.getWidth() * 0.9); this.gravity = Gravity.TOP | Gravity.LEFT; text = new SpannableStringBuilder() .append(context.getResources().getText(textResource1)) .append("\n") .append(context.getResources().getText(textResource2)); this.dismissOnTouch = true; this.dismissOnClose = false; this.inputView = inputView; window = new PopupWindow(context); window.setBackgroundDrawable(null); LayoutInflater inflate = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); textView = (TextView) inflate.inflate(R.layout.bubble_text, null); textView.setBackgroundDrawable(bubbleBackground); textView.setText(text); //textView.setText(textResource1); window.setContentView(textView); window.setFocusable(false); window.setTouchable(true); window.setOutsideTouchable(false); } private int chooseSize(PopupWindow pop, View parentView, CharSequence text, TextView tv) { int wid = tv.getPaddingLeft() + tv.getPaddingRight(); int ht = tv.getPaddingTop() + tv.getPaddingBottom(); /* * Figure out how big the text would be if we laid it out to the * full width of this view minus the border. */ int cap = width - wid; Layout l = new StaticLayout(text, tv.getPaint(), cap, Layout.Alignment.ALIGN_NORMAL, 1, 0, true); float max = 0; for (int i = 0; i < l.getLineCount(); i++) { max = Math.max(max, l.getLineWidth(i)); } /* * Now set the popup size to be big enough for the text plus the border. */ pop.setWidth(width); pop.setHeight(ht + l.getHeight()); return l.getHeight(); } void show(int offx, int offy) { int textHeight = chooseSize(window, inputView, text, textView); offy -= textView.getPaddingTop() + textHeight; if (inputView.getVisibility() == View.VISIBLE && inputView.getWindowVisibility() == View.VISIBLE) { try { if ((gravity & Gravity.BOTTOM) == Gravity.BOTTOM) offy -= window.getHeight(); if ((gravity & Gravity.RIGHT) == Gravity.RIGHT) offx -= window.getWidth(); textView.setOnTouchListener(new View.OnTouchListener() { public boolean onTouch(View view, MotionEvent me) { Tutorial.this.next(); return true; } }); window.showAtLocation(inputView, Gravity.NO_GRAVITY, x + offx, y + offy); } catch (Exception e) { // Input view is not valid } } } void hide() { if (window.isShowing()) { textView.setOnTouchListener(null); window.dismiss(); } } boolean isShowing() { return window.isShowing(); } } public Tutorial(LatinIME ime, LatinKeyboardView inputView) { Context context = inputView.getContext(); mIme = ime; int inputWidth = inputView.getWidth(); final int x = inputWidth / 20; // Half of 1/10th Bubble bWelcome = new Bubble(context, inputView, R.drawable.dialog_bubble_step02, x, 0, R.string.tip_to_open_keyboard, R.string.touch_to_continue); mBubbles.add(bWelcome); Bubble bAccents = new Bubble(context, inputView, R.drawable.dialog_bubble_step02, x, 0, R.string.tip_to_view_accents, R.string.touch_to_continue); mBubbles.add(bAccents); Bubble b123 = new Bubble(context, inputView, R.drawable.dialog_bubble_step07, x, 0, R.string.tip_to_open_symbols, R.string.touch_to_continue); mBubbles.add(b123); Bubble bABC = new Bubble(context, inputView, R.drawable.dialog_bubble_step07, x, 0, R.string.tip_to_close_symbols, R.string.touch_to_continue); mBubbles.add(bABC); Bubble bSettings = new Bubble(context, inputView, R.drawable.dialog_bubble_step07, x, 0, R.string.tip_to_launch_settings, R.string.touch_to_continue); mBubbles.add(bSettings); Bubble bDone = new Bubble(context, inputView, R.drawable.dialog_bubble_step02, x, 0, R.string.tip_to_start_typing, R.string.touch_to_finish); mBubbles.add(bDone); mInputView = inputView; } void start() { mInputView.getLocationInWindow(mLocation); mBubbleIndex = -1; mInputView.setOnTouchListener(this); next(); } boolean next() { if (mBubbleIndex >= 0) { // If the bubble is not yet showing, don't move to the next. if (!mBubbles.get(mBubbleIndex).isShowing()) { return true; } // Hide all previous bubbles as well, as they may have had a delayed show for (int i = 0; i <= mBubbleIndex; i++) { mBubbles.get(i).hide(); } } mBubbleIndex++; if (mBubbleIndex >= mBubbles.size()) { mInputView.setOnTouchListener(null); mIme.sendDownUpKeyEvents(-1); // Inform the setupwizard that tutorial is in last bubble mIme.tutorialDone(); return false; } if (mBubbleIndex == 3 || mBubbleIndex == 4) { mIme.mKeyboardSwitcher.toggleSymbols(); } mHandler.sendMessageDelayed( mHandler.obtainMessage(MSG_SHOW_BUBBLE, mBubbles.get(mBubbleIndex)), 500); return true; } void hide() { for (int i = 0; i < mBubbles.size(); i++) { mBubbles.get(i).hide(); } mInputView.setOnTouchListener(null); } boolean close() { mHandler.removeMessages(MSG_SHOW_BUBBLE); hide(); return true; } public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { next(); } return true; } }
Java
/* * Copyright (C) 2011 Darren Salt * * Licensed under the Apache License, Version 2.0 (the "Licence"); you may * not use this file except in compliance with the Licence. You may obtain * a copy of the Licence at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the Licence is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * Licence for the specific language governing permissions and limitations * under the Licence. */ package org.pocketworkstation.pckeyboard; public class ComposeSequence extends ComposeBase { public ComposeSequence(ComposeSequencing user) { init(user); } static { put("++", "#"); put("' ", "'"); put(" '", "'"); put("AT", "@"); put("((", "["); put("//", "\\"); put("/<", "\\"); put("</", "\\"); put("))", "]"); put("^ ", "^"); put(" ^", "^"); put("> ", "^"); put(" >", "^"); put("` ", "`"); put(" `", "`"); put(", ", "¸"); put(" ,", "¸"); put("(-", "{"); put("-(", "{"); put("/^", "|"); put("^/", "|"); put("VL", "|"); put("LV", "|"); put("vl", "|"); put("lv", "|"); put(")-", "}"); put("-)", "}"); put("~ ", "~"); put(" ~", "~"); put("- ", "~"); put(" -", "~"); put(" ", " "); put(" .", " "); put("oc", "©"); put("oC", "©"); put("Oc", "©"); put("OC", "©"); put("or", "®"); put("oR", "®"); put("Or", "®"); put("OR", "®"); put(".>", "›"); put(".<", "‹"); put("..", "…"); put(".-", "·"); put(".=", "•"); put("!^", "¦"); put("!!", "¡"); put("p!", "¶"); put("P!", "¶"); put("+-", "±"); put("??", "¿"); put("-d", "đ"); put("-D", "Đ"); put("ss", "ß"); put("SS", "ẞ"); put("oe", "œ"); put("OE", "Œ"); put("ae", "æ"); put("AE", "Æ"); put("oo", "°"); put("\"\\", "〝"); put("\"/", "〞"); put("<<", "«"); put(">>", "»"); put("<'", "‘"); put("'<", "‘"); put(">'", "’"); put("'>", "’"); put(",'", "‚"); put("',", "‚"); put("<\"", "“"); put("\"<", "“"); put(">\"", "”"); put("\">", "”"); put(",\"", "„"); put("\",", "„"); put("%o", "‰"); put("CE", "₠"); put("C/", "₡"); put("/C", "₡"); put("Cr", "₢"); put("Fr", "₣"); put("L=", "₤"); put("=L", "₤"); put("m/", "₥"); put("/m", "₥"); put("N=", "₦"); put("=N", "₦"); put("Pt", "₧"); put("Rs", "₨"); put("W=", "₩"); put("=W", "₩"); put("d-", "₫"); put("C=", "€"); put("=C", "€"); put("c=", "€"); put("=c", "€"); put("E=", "€"); put("=E", "€"); put("e=", "€"); put("=e", "€"); put("|c", "¢"); put("c|", "¢"); put("c/", "¢"); put("/c", "¢"); put("L-", "£"); put("-L", "£"); put("Y=", "¥"); put("=Y", "¥"); put("fs", "ſ"); put("fS", "ſ"); put("--.", "–"); put("---", "—"); put("#b", "♭"); put("#f", "♮"); put("##", "♯"); put("so", "§"); put("os", "§"); put("ox", "¤"); put("xo", "¤"); put("PP", "¶"); put("No", "№"); put("NO", "№"); put("?!", "⸘"); put("!?", "‽"); put("CCCP", "☭"); put("OA", "Ⓐ"); put("<3", "♥"); put(":)", "☺"); put(":(", "☹"); put(",-", "¬"); put("-,", "¬"); put("^_a", "ª"); put("^2", "²"); put("^3", "³"); put("mu", "µ"); put("^1", "¹"); put("^_o", "º"); put("14", "¼"); put("12", "½"); put("34", "¾"); put("`A", "À"); put("'A", "Á"); put("^A", "Â"); put("~A", "Ã"); put("\"A", "Ä"); put("oA", "Å"); put(",C", "Ç"); put("`E", "È"); put("'E", "É"); put("^E", "Ê"); put("\"E", "Ë"); put("`I", "Ì"); put("'I", "Í"); put("^I", "Î"); put("\"I", "Ï"); put("DH", "Ð"); put("~N", "Ñ"); put("`O", "Ò"); put("'O", "Ó"); put("^O", "Ô"); put("~O", "Õ"); put("\"O", "Ö"); put("xx", "×"); put("/O", "Ø"); put("`U", "Ù"); put("'U", "Ú"); put("^U", "Û"); put("\"U", "Ü"); put("'Y", "Ý"); put("TH", "Þ"); put("`a", "à"); put("'a", "á"); put("^a", "â"); put("~a", "ã"); put("\"a", "ä"); put("oa", "å"); put(",c", "ç"); put("`e", "è"); put("'e", "é"); put("^e", "ê"); put("\"e", "ë"); put("`i", "ì"); put("'i", "í"); put("^i", "î"); put("\"i", "ï"); put("dh", "ð"); put("~n", "ñ"); put("`o", "ò"); put("'o", "ó"); put("^o", "ô"); put("~o", "õ"); put("\"o", "ö"); put(":-", "÷"); put("-:", "÷"); put("/o", "ø"); put("`u", "ù"); put("'u", "ú"); put("^u", "û"); put("\"u", "ü"); put("'y", "ý"); put("th", "þ"); put("\"y", "ÿ"); put("_A", "Ā"); put("_a", "ā"); put("UA", "Ă"); put("bA", "Ă"); put("Ua", "ă"); put("ba", "ă"); put(";A", "Ą"); put(",A", "Ą"); put(";a", "ą"); put(",a", "ą"); put("'C", "Ć"); put("'c", "ć"); put("^C", "Ĉ"); put("^c", "ĉ"); put(".C", "Ċ"); put(".c", "ċ"); put("cC", "Č"); put("cc", "č"); put("cD", "Ď"); put("cd", "ď"); put("/D", "Đ"); put("/d", "đ"); put("_E", "Ē"); put("_e", "ē"); put("UE", "Ĕ"); put("bE", "Ĕ"); put("Ue", "ĕ"); put("be", "ĕ"); put(".E", "Ė"); put(".e", "ė"); put(";E", "Ę"); put(",E", "Ę"); put(";e", "ę"); put(",e", "ę"); put("cE", "Ě"); put("ce", "ě"); //put("ff", "ff"); // Not usable, interferes with ffi/ffl prefix put("+f", "ff"); put("f+", "ff"); put("fi", "fi"); put("fl", "fl"); put("ffi", "ffi"); put("ffl", "ffl"); put("^G", "Ĝ"); put("^g", "ĝ"); put("UG", "Ğ"); put("bG", "Ğ"); put("Ug", "ğ"); put("bg", "ğ"); put(".G", "Ġ"); put(".g", "ġ"); put(",G", "Ģ"); put(",g", "ģ"); put("^H", "Ĥ"); put("^h", "ĥ"); put("/H", "Ħ"); put("/h", "ħ"); put("~I", "Ĩ"); put("~i", "ĩ"); put("_I", "Ī"); put("_i", "ī"); put("UI", "Ĭ"); put("bI", "Ĭ"); put("Ui", "ĭ"); put("bi", "ĭ"); put(";I", "Į"); put(",I", "Į"); put(";i", "į"); put(",i", "į"); put(".I", "İ"); put("i.", "ı"); put("^J", "Ĵ"); put("^j", "ĵ"); put(",K", "Ķ"); put(",k", "ķ"); put("kk", "ĸ"); put("'L", "Ĺ"); put("'l", "ĺ"); put(",L", "Ļ"); put(",l", "ļ"); put("cL", "Ľ"); put("cl", "ľ"); put("/L", "Ł"); put("/l", "ł"); put("'N", "Ń"); put("'n", "ń"); put(",N", "Ņ"); put(",n", "ņ"); put("cN", "Ň"); put("cn", "ň"); put("NG", "Ŋ"); put("ng", "ŋ"); put("_O", "Ō"); put("_o", "ō"); put("UO", "Ŏ"); put("bO", "Ŏ"); put("Uo", "ŏ"); put("bo", "ŏ"); put("=O", "Ő"); put("=o", "ő"); put("'R", "Ŕ"); put("'r", "ŕ"); put(",R", "Ŗ"); put(",r", "ŗ"); put("cR", "Ř"); put("cr", "ř"); put("'S", "Ś"); put("'s", "ś"); put("^S", "Ŝ"); put("^s", "ŝ"); put(",S", "Ş"); put(",s", "ş"); put("cS", "Š"); put("cs", "š"); put(",T", "Ţ"); put(",t", "ţ"); put("cT", "Ť"); put("ct", "ť"); put("/T", "Ŧ"); put("/t", "ŧ"); put("~U", "Ũ"); put("~u", "ũ"); put("_U", "Ū"); put("_u", "ū"); put("UU", "Ŭ"); put("bU", "Ŭ"); put("Uu", "ŭ"); put("uu", "ŭ"); put("bu", "ŭ"); put("oU", "Ů"); put("ou", "ů"); put("=U", "Ű"); put("=u", "ű"); put(";U", "Ų"); put(",U", "Ų"); put(";u", "ų"); put(",u", "ų"); put("^W", "Ŵ"); put("^w", "ŵ"); put("^Y", "Ŷ"); put("^y", "ŷ"); put("\"Y", "Ÿ"); put("'Z", "Ź"); put("'z", "ź"); put(".Z", "Ż"); put(".z", "ż"); put("cZ", "Ž"); put("cz", "ž"); put("/b", "ƀ"); put("/I", "Ɨ"); put("+O", "Ơ"); put("+o", "ơ"); put("+U", "Ư"); put("+u", "ư"); put("/Z", "Ƶ"); put("/z", "ƶ"); put("cA", "Ǎ"); put("ca", "ǎ"); put("cI", "Ǐ"); put("ci", "ǐ"); put("cO", "Ǒ"); put("co", "ǒ"); put("cU", "Ǔ"); put("cu", "ǔ"); put("_Ü", "Ǖ"); put("_\"U", "Ǖ"); put("_ü", "ǖ"); put("_\"u", "ǖ"); put("'Ü", "Ǘ"); put("'\"U", "Ǘ"); put("'ü", "ǘ"); put("'\"u", "ǘ"); put("cÜ", "Ǚ"); put("c\"U", "Ǚ"); put("cü", "ǚ"); put("c\"u", "ǚ"); put("`Ü", "Ǜ"); put("`\"U", "Ǜ"); put("`ü", "ǜ"); put("`\"u", "ǜ"); put("_Ä", "Ǟ"); put("_\"A", "Ǟ"); put("_ä", "ǟ"); put("_\"a", "ǟ"); put("_.A", "Ǡ"); put("_.a", "ǡ"); put("_Æ", "Ǣ"); put("_æ", "ǣ"); put("/G", "Ǥ"); put("/g", "ǥ"); put("cG", "Ǧ"); put("cg", "ǧ"); put("cK", "Ǩ"); put("ck", "ǩ"); put(";O", "Ǫ"); put(";o", "ǫ"); put("_;O", "Ǭ"); put("_;o", "ǭ"); put("cj", "ǰ"); put("'G", "Ǵ"); put("'g", "ǵ"); put("`N", "Ǹ"); put("`n", "ǹ"); put("'Å", "Ǻ"); put("o'A", "Ǻ"); put("'å", "ǻ"); put("o'a", "ǻ"); put("'Æ", "Ǽ"); put("'æ", "ǽ"); put("'Ø", "Ǿ"); put("'/O", "Ǿ"); put("'ø", "ǿ"); put("'/o", "ǿ"); put("cH", "Ȟ"); put("ch", "ȟ"); put(".A", "Ȧ"); put(".a", "ȧ"); put("_Ö", "Ȫ"); put("_\"O", "Ȫ"); put("_ö", "ȫ"); put("_\"o", "ȫ"); put("_Õ", "Ȭ"); put("_~O", "Ȭ"); put("_õ", "ȭ"); put("_~o", "ȭ"); put(".O", "Ȯ"); put(".o", "ȯ"); put("_.O", "Ȱ"); put("_.o", "ȱ"); put("_Y", "Ȳ"); put("_y", "ȳ"); put("ee", "ə"); put("/i", "ɨ"); put("^_h", "ʰ"); put("^_j", "ʲ"); put("^_r", "ʳ"); put("^_w", "ʷ"); put("^_y", "ʸ"); put("^_l", "ˡ"); put("^_s", "ˢ"); put("^_x", "ˣ"); put("\"'", "̈́"); put(".B", "Ḃ"); put(".b", "ḃ"); put("!B", "Ḅ"); put("!b", "ḅ"); put("'Ç", "Ḉ"); put("'ç", "ḉ"); put(".D", "Ḋ"); put(".d", "ḋ"); put("!D", "Ḍ"); put("!d", "ḍ"); put(",D", "Ḑ"); put(",d", "ḑ"); put("`Ē", "Ḕ"); put("`_E", "Ḕ"); put("`ē", "ḕ"); put("`_e", "ḕ"); put("'Ē", "Ḗ"); put("'_E", "Ḗ"); put("'ē", "ḗ"); put("'_e", "ḗ"); put("U,E", "Ḝ"); put("b,E", "Ḝ"); put("U,e", "ḝ"); put("b,e", "ḝ"); put(".F", "Ḟ"); put(".f", "ḟ"); put("_G", "Ḡ"); put("_g", "ḡ"); put(".H", "Ḣ"); put(".h", "ḣ"); put("!H", "Ḥ"); put("!h", "ḥ"); put("\"H", "Ḧ"); put("\"h", "ḧ"); put(",H", "Ḩ"); put(",h", "ḩ"); put("'Ï", "Ḯ"); put("'\"I", "Ḯ"); put("'ï", "ḯ"); put("'\"i", "ḯ"); put("'K", "Ḱ"); put("'k", "ḱ"); put("!K", "Ḳ"); put("!k", "ḳ"); put("!L", "Ḷ"); put("!l", "ḷ"); put("_!L", "Ḹ"); put("_!l", "ḹ"); put("'M", "Ḿ"); put("'m", "ḿ"); put(".M", "Ṁ"); put(".m", "ṁ"); put("!M", "Ṃ"); put("!m", "ṃ"); put(".N", "Ṅ"); put(".n", "ṅ"); put("!N", "Ṇ"); put("!n", "ṇ"); put("'Õ", "Ṍ"); put("'~O", "Ṍ"); put("'õ", "ṍ"); put("'~o", "ṍ"); put("\"Õ", "Ṏ"); put("\"~O", "Ṏ"); put("\"õ", "ṏ"); put("\"~o", "ṏ"); put("`Ō", "Ṑ"); put("`_O", "Ṑ"); put("`ō", "ṑ"); put("`_o", "ṑ"); put("'Ō", "Ṓ"); put("'_O", "Ṓ"); put("'ō", "ṓ"); put("'_o", "ṓ"); put("'P", "Ṕ"); put("'p", "ṕ"); put(".P", "Ṗ"); put(".p", "ṗ"); put(".R", "Ṙ"); put(".r", "ṙ"); put("!R", "Ṛ"); put("!r", "ṛ"); put("_!R", "Ṝ"); put("_!r", "ṝ"); put(".S", "Ṡ"); put(".s", "ṡ"); put("!S", "Ṣ"); put("!s", "ṣ"); put(".Ś", "Ṥ"); put(".'S", "Ṥ"); put(".ś", "ṥ"); put(".'s", "ṥ"); put(".Š", "Ṧ"); put(".š", "ṧ"); put(".!S", "Ṩ"); put(".!s", "ṩ"); put(".T", "Ṫ"); put(".t", "ṫ"); put("!T", "Ṭ"); put("!t", "ṭ"); put("'Ũ", "Ṹ"); put("'~U", "Ṹ"); put("'ũ", "ṹ"); put("'~u", "ṹ"); put("\"Ū", "Ṻ"); put("\"_U", "Ṻ"); put("\"ū", "ṻ"); put("\"_u", "ṻ"); put("~V", "Ṽ"); put("~v", "ṽ"); put("!V", "Ṿ"); put("!v", "ṿ"); put("`W", "Ẁ"); put("`w", "ẁ"); put("'W", "Ẃ"); put("'w", "ẃ"); put("\"W", "Ẅ"); put("\"w", "ẅ"); put(".W", "Ẇ"); put(".w", "ẇ"); put("!W", "Ẉ"); put("!w", "ẉ"); put(".X", "Ẋ"); put(".x", "ẋ"); put("\"X", "Ẍ"); put("\"x", "ẍ"); put(".Y", "Ẏ"); put(".y", "ẏ"); put("^Z", "Ẑ"); put("^z", "ẑ"); put("!Z", "Ẓ"); put("!z", "ẓ"); put("\"t", "ẗ"); put("ow", "ẘ"); put("oy", "ẙ"); put("!A", "Ạ"); put("!a", "ạ"); put("?A", "Ả"); put("?a", "ả"); put("'Â", "Ấ"); put("'^A", "Ấ"); put("'â", "ấ"); put("'^a", "ấ"); put("`Â", "Ầ"); put("`^A", "Ầ"); put("`â", "ầ"); put("`^a", "ầ"); put("?Â", "Ẩ"); put("?^A", "Ẩ"); put("?â", "ẩ"); put("?^a", "ẩ"); put("~Â", "Ẫ"); put("~^A", "Ẫ"); put("~â", "ẫ"); put("~^a", "ẫ"); put("^!A", "Ậ"); put("^!a", "ậ"); put("'Ă", "Ắ"); put("'bA", "Ắ"); put("'ă", "ắ"); put("'ba", "ắ"); put("`Ă", "Ằ"); put("`bA", "Ằ"); put("`ă", "ằ"); put("`ba", "ằ"); put("?Ă", "Ẳ"); put("?bA", "Ẳ"); put("?ă", "ẳ"); put("?ba", "ẳ"); put("~Ă", "Ẵ"); put("~bA", "Ẵ"); put("~ă", "ẵ"); put("~ba", "ẵ"); put("U!A", "Ặ"); put("b!A", "Ặ"); put("U!a", "ặ"); put("b!a", "ặ"); put("!E", "Ẹ"); put("!e", "ẹ"); put("?E", "Ẻ"); put("?e", "ẻ"); put("~E", "Ẽ"); put("~e", "ẽ"); put("'Ê", "Ế"); put("'^E", "Ế"); put("'ê", "ế"); put("'^e", "ế"); put("`Ê", "Ề"); put("`^E", "Ề"); put("`ê", "ề"); put("`^e", "ề"); put("?Ê", "Ể"); put("?^E", "Ể"); put("?ê", "ể"); put("?^e", "ể"); put("~Ê", "Ễ"); put("~^E", "Ễ"); put("~ê", "ễ"); put("~^e", "ễ"); put("^!E", "Ệ"); put("^!e", "ệ"); put("?I", "Ỉ"); put("?i", "ỉ"); put("!I", "Ị"); put("!i", "ị"); put("!O", "Ọ"); put("!o", "ọ"); put("?O", "Ỏ"); put("?o", "ỏ"); put("'Ô", "Ố"); put("'^O", "Ố"); put("'ô", "ố"); put("'^o", "ố"); put("`Ô", "Ồ"); put("`^O", "Ồ"); put("`ô", "ồ"); put("`^o", "ồ"); put("?Ô", "Ổ"); put("?^O", "Ổ"); put("?ô", "ổ"); put("?^o", "ổ"); put("~Ô", "Ỗ"); put("~^O", "Ỗ"); put("~ô", "ỗ"); put("~^o", "ỗ"); put("^!O", "Ộ"); put("^!o", "ộ"); put("'Ơ", "Ớ"); put("'+O", "Ớ"); put("'ơ", "ớ"); put("'+o", "ớ"); put("`Ơ", "Ờ"); put("`+O", "Ờ"); put("`ơ", "ờ"); put("`+o", "ờ"); put("?Ơ", "Ở"); put("?+O", "Ở"); put("?ơ", "ở"); put("?+o", "ở"); put("~Ơ", "Ỡ"); put("~+O", "Ỡ"); put("~ơ", "ỡ"); put("~+o", "ỡ"); put("!Ơ", "Ợ"); put("!+O", "Ợ"); put("!ơ", "ợ"); put("!+o", "ợ"); put("!U", "Ụ"); put("!u", "ụ"); put("?U", "Ủ"); put("?u", "ủ"); put("'Ư", "Ứ"); put("'+U", "Ứ"); put("'ư", "ứ"); put("'+u", "ứ"); put("`Ư", "Ừ"); put("`+U", "Ừ"); put("`ư", "ừ"); put("`+u", "ừ"); put("?Ư", "Ử"); put("?+U", "Ử"); put("?ư", "ử"); put("?+u", "ử"); put("~Ư", "Ữ"); put("~+U", "Ữ"); put("~ư", "ữ"); put("~+u", "ữ"); put("!Ư", "Ự"); put("!+U", "Ự"); put("!ư", "ự"); put("!+u", "ự"); put("`Y", "Ỳ"); put("`y", "ỳ"); put("!Y", "Ỵ"); put("!y", "ỵ"); put("?Y", "Ỷ"); put("?y", "ỷ"); put("~Y", "Ỹ"); put("~y", "ỹ"); put("^0", "⁰"); put("^_i", "ⁱ"); put("^4", "⁴"); put("^5", "⁵"); put("^6", "⁶"); put("^7", "⁷"); put("^8", "⁸"); put("^9", "⁹"); put("^+", "⁺"); put("^=", "⁼"); put("^(", "⁽"); put("^)", "⁾"); put("^_n", "ⁿ"); put("_0", "₀"); put("_1", "₁"); put("_2", "₂"); put("_3", "₃"); put("_4", "₄"); put("_5", "₅"); put("_6", "₆"); put("_7", "₇"); put("_8", "₈"); put("_9", "₉"); put("_+", "₊"); put("_=", "₌"); put("_(", "₍"); put("_)", "₎"); put("SM", "℠"); put("sM", "℠"); put("Sm", "℠"); put("sm", "℠"); put("TM", "™"); put("tM", "™"); put("Tm", "™"); put("tm", "™"); put("13", "⅓"); put("23", "⅔"); put("15", "⅕"); put("25", "⅖"); put("35", "⅗"); put("45", "⅘"); put("16", "⅙"); put("56", "⅚"); put("18", "⅛"); put("38", "⅜"); put("58", "⅝"); put("78", "⅞"); put("/←", "↚"); put("/→", "↛"); put("<-", "←"); put("->", "→"); put("/=", "≠"); put("=/", "≠"); put("<=", "≤"); put(">=", "≥"); put("(1)", "①"); put("(2)", "②"); put("(3)", "③"); put("(4)", "④"); put("(5)", "⑤"); put("(6)", "⑥"); put("(7)", "⑦"); put("(8)", "⑧"); put("(9)", "⑨"); put("(10)", "⑩"); put("(11)", "⑪"); put("(12)", "⑫"); put("(13)", "⑬"); put("(14)", "⑭"); put("(15)", "⑮"); put("(16)", "⑯"); put("(17)", "⑰"); put("(18)", "⑱"); put("(19)", "⑲"); put("(20)", "⑳"); put("(A)", "Ⓐ"); put("(B)", "Ⓑ"); put("(C)", "Ⓒ"); put("(D)", "Ⓓ"); put("(E)", "Ⓔ"); put("(F)", "Ⓕ"); put("(G)", "Ⓖ"); put("(H)", "Ⓗ"); put("(I)", "Ⓘ"); put("(J)", "Ⓙ"); put("(K)", "Ⓚ"); put("(L)", "Ⓛ"); put("(M)", "Ⓜ"); put("(N)", "Ⓝ"); put("(O)", "Ⓞ"); put("(P)", "Ⓟ"); put("(Q)", "Ⓠ"); put("(R)", "Ⓡ"); put("(S)", "Ⓢ"); put("(T)", "Ⓣ"); put("(U)", "Ⓤ"); put("(V)", "Ⓥ"); put("(W)", "Ⓦ"); put("(X)", "Ⓧ"); put("(Y)", "Ⓨ"); put("(Z)", "Ⓩ"); put("(a)", "ⓐ"); put("(b)", "ⓑ"); put("(c)", "ⓒ"); put("(d)", "ⓓ"); put("(e)", "ⓔ"); put("(f)", "ⓕ"); put("(g)", "ⓖ"); put("(h)", "ⓗ"); put("(i)", "ⓘ"); put("(j)", "ⓙ"); put("(k)", "ⓚ"); put("(l)", "ⓛ"); put("(m)", "ⓜ"); put("(n)", "ⓝ"); put("(o)", "ⓞ"); put("(p)", "ⓟ"); put("(q)", "ⓠ"); put("(r)", "ⓡ"); put("(s)", "ⓢ"); put("(t)", "ⓣ"); put("(u)", "ⓤ"); put("(v)", "ⓥ"); put("(w)", "ⓦ"); put("(x)", "ⓧ"); put("(y)", "ⓨ"); put("(z)", "ⓩ"); put("(0)", "⓪"); put("(21)", "㉑"); put("(22)", "㉒"); put("(23)", "㉓"); put("(24)", "㉔"); put("(25)", "㉕"); put("(26)", "㉖"); put("(27)", "㉗"); put("(28)", "㉘"); put("(29)", "㉙"); put("(30)", "㉚"); put("(31)", "㉛"); put("(32)", "㉜"); put("(33)", "㉝"); put("(34)", "㉞"); put("(35)", "㉟"); put("(36)", "㊱"); put("(37)", "㊲"); put("(38)", "㊳"); put("(39)", "㊴"); put("(40)", "㊵"); put("(41)", "㊶"); put("(42)", "㊷"); put("(43)", "㊸"); put("(44)", "㊹"); put("(45)", "㊺"); put("(46)", "㊻"); put("(47)", "㊼"); put("(48)", "㊽"); put("(49)", "㊾"); put("(50)", "㊿"); put("\\o/", "🙌"); } }
Java
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.pocketworkstation.pckeyboard; import android.view.inputmethod.InputMethodManager; import android.content.Context; import android.os.AsyncTask; import android.text.format.DateUtils; import android.util.Log; public class LatinIMEUtil { /** * Cancel an {@link AsyncTask}. * * @param mayInterruptIfRunning <tt>true</tt> if the thread executing this * task should be interrupted; otherwise, in-progress tasks are allowed * to complete. */ public static void cancelTask(AsyncTask<?, ?, ?> task, boolean mayInterruptIfRunning) { if (task != null && task.getStatus() != AsyncTask.Status.FINISHED) { task.cancel(mayInterruptIfRunning); } } public static class GCUtils { private static final String TAG = "GCUtils"; public static final int GC_TRY_COUNT = 2; // GC_TRY_LOOP_MAX is used for the hard limit of GC wait, // GC_TRY_LOOP_MAX should be greater than GC_TRY_COUNT. public static final int GC_TRY_LOOP_MAX = 5; private static final long GC_INTERVAL = DateUtils.SECOND_IN_MILLIS; private static GCUtils sInstance = new GCUtils(); private int mGCTryCount = 0; public static GCUtils getInstance() { return sInstance; } public void reset() { mGCTryCount = 0; } public boolean tryGCOrWait(String metaData, Throwable t) { if (mGCTryCount == 0) { System.gc(); } if (++mGCTryCount > GC_TRY_COUNT) { LatinImeLogger.logOnException(metaData, t); return false; } else { try { Thread.sleep(GC_INTERVAL); return true; } catch (InterruptedException e) { Log.e(TAG, "Sleep was interrupted."); LatinImeLogger.logOnException(metaData, t); return false; } } } } /* package */ static class RingCharBuffer { private static RingCharBuffer sRingCharBuffer = new RingCharBuffer(); private static final char PLACEHOLDER_DELIMITER_CHAR = '\uFFFC'; private static final int INVALID_COORDINATE = -2; /* package */ static final int BUFSIZE = 20; private Context mContext; private boolean mEnabled = false; private int mEnd = 0; /* package */ int mLength = 0; private char[] mCharBuf = new char[BUFSIZE]; private int[] mXBuf = new int[BUFSIZE]; private int[] mYBuf = new int[BUFSIZE]; private RingCharBuffer() { } public static RingCharBuffer getInstance() { return sRingCharBuffer; } public static RingCharBuffer init(Context context, boolean enabled) { sRingCharBuffer.mContext = context; sRingCharBuffer.mEnabled = enabled; return sRingCharBuffer; } private int normalize(int in) { int ret = in % BUFSIZE; return ret < 0 ? ret + BUFSIZE : ret; } public void push(char c, int x, int y) { if (!mEnabled) return; mCharBuf[mEnd] = c; mXBuf[mEnd] = x; mYBuf[mEnd] = y; mEnd = normalize(mEnd + 1); if (mLength < BUFSIZE) { ++mLength; } } public char pop() { if (mLength < 1) { return PLACEHOLDER_DELIMITER_CHAR; } else { mEnd = normalize(mEnd - 1); --mLength; return mCharBuf[mEnd]; } } public char getLastChar() { if (mLength < 1) { return PLACEHOLDER_DELIMITER_CHAR; } else { return mCharBuf[normalize(mEnd - 1)]; } } public int getPreviousX(char c, int back) { int index = normalize(mEnd - 2 - back); if (mLength <= back || Character.toLowerCase(c) != Character.toLowerCase(mCharBuf[index])) { return INVALID_COORDINATE; } else { return mXBuf[index]; } } public int getPreviousY(char c, int back) { int index = normalize(mEnd - 2 - back); if (mLength <= back || Character.toLowerCase(c) != Character.toLowerCase(mCharBuf[index])) { return INVALID_COORDINATE; } else { return mYBuf[index]; } } public String getLastString() { StringBuffer sb = new StringBuffer(); for (int i = 0; i < mLength; ++i) { char c = mCharBuf[normalize(mEnd - 1 - i)]; if (!((LatinIME)mContext).isWordSeparator(c)) { sb.append(c); } else { break; } } return sb.reverse().toString(); } public void reset() { mLength = 0; } } }
Java
/* * Copyright (C) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.pocketworkstation.pckeyboard; import java.util.Locale; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.preference.PreferenceManager; import android.text.TextUtils; import android.util.Log; /** * Keeps track of list of selected input languages and the current * input language that the user has selected. */ public class LanguageSwitcher { private static final String TAG = "HK/LanguageSwitcher"; private Locale[] mLocales; private LatinIME mIme; private String[] mSelectedLanguageArray; private String mSelectedLanguages; private int mCurrentIndex = 0; private String mDefaultInputLanguage; private Locale mDefaultInputLocale; private Locale mSystemLocale; public LanguageSwitcher(LatinIME ime) { mIme = ime; mLocales = new Locale[0]; } public Locale[] getLocales() { return mLocales; } public int getLocaleCount() { return mLocales.length; } /** * Loads the currently selected input languages from shared preferences. * @param sp * @return whether there was any change */ public boolean loadLocales(SharedPreferences sp) { String selectedLanguages = sp.getString(LatinIME.PREF_SELECTED_LANGUAGES, null); String currentLanguage = sp.getString(LatinIME.PREF_INPUT_LANGUAGE, null); if (selectedLanguages == null || selectedLanguages.length() < 1) { loadDefaults(); if (mLocales.length == 0) { return false; } mLocales = new Locale[0]; return true; } if (selectedLanguages.equals(mSelectedLanguages)) { return false; } mSelectedLanguageArray = selectedLanguages.split(","); mSelectedLanguages = selectedLanguages; // Cache it for comparison later constructLocales(); mCurrentIndex = 0; if (currentLanguage != null) { // Find the index mCurrentIndex = 0; for (int i = 0; i < mLocales.length; i++) { if (mSelectedLanguageArray[i].equals(currentLanguage)) { mCurrentIndex = i; break; } } // If we didn't find the index, use the first one } return true; } private void loadDefaults() { mDefaultInputLocale = mIme.getResources().getConfiguration().locale; String country = mDefaultInputLocale.getCountry(); mDefaultInputLanguage = mDefaultInputLocale.getLanguage() + (TextUtils.isEmpty(country) ? "" : "_" + country); } private void constructLocales() { mLocales = new Locale[mSelectedLanguageArray.length]; for (int i = 0; i < mLocales.length; i++) { final String lang = mSelectedLanguageArray[i]; mLocales[i] = new Locale(lang.substring(0, 2), lang.length() > 4 ? lang.substring(3, 5) : ""); } } /** * Returns the currently selected input language code, or the display language code if * no specific locale was selected for input. */ public String getInputLanguage() { if (getLocaleCount() == 0) return mDefaultInputLanguage; return mSelectedLanguageArray[mCurrentIndex]; } public boolean allowAutoCap() { String lang = getInputLanguage(); if (lang.length() > 2) lang = lang.substring(0, 2); return !InputLanguageSelection.NOCAPS_LANGUAGES.contains(lang); } public boolean allowDeadKeys() { String lang = getInputLanguage(); if (lang.length() > 2) lang = lang.substring(0, 2); return !InputLanguageSelection.NODEADKEY_LANGUAGES.contains(lang); } public boolean allowAutoSpace() { String lang = getInputLanguage(); if (lang.length() > 2) lang = lang.substring(0, 2); return !InputLanguageSelection.NOAUTOSPACE_LANGUAGES.contains(lang); } /** * Returns the list of enabled language codes. */ public String[] getEnabledLanguages() { return mSelectedLanguageArray; } /** * Returns the currently selected input locale, or the display locale if no specific * locale was selected for input. * @return */ public Locale getInputLocale() { Locale locale; if (getLocaleCount() == 0) { locale = mDefaultInputLocale; } else { locale = mLocales[mCurrentIndex]; } LatinIME.sKeyboardSettings.inputLocale = (locale != null) ? locale : Locale.getDefault(); return locale; } /** * Returns the next input locale in the list. Wraps around to the beginning of the * list if we're at the end of the list. * @return */ public Locale getNextInputLocale() { if (getLocaleCount() == 0) return mDefaultInputLocale; return mLocales[(mCurrentIndex + 1) % mLocales.length]; } /** * Sets the system locale (display UI) used for comparing with the input language. * @param locale the locale of the system */ public void setSystemLocale(Locale locale) { mSystemLocale = locale; } /** * Returns the system locale. * @return the system locale */ public Locale getSystemLocale() { return mSystemLocale; } /** * Returns the previous input locale in the list. Wraps around to the end of the * list if we're at the beginning of the list. * @return */ public Locale getPrevInputLocale() { if (getLocaleCount() == 0) return mDefaultInputLocale; return mLocales[(mCurrentIndex - 1 + mLocales.length) % mLocales.length]; } public void reset() { mCurrentIndex = 0; mSelectedLanguages = ""; loadLocales(PreferenceManager.getDefaultSharedPreferences(mIme)); } public void next() { mCurrentIndex++; if (mCurrentIndex >= mLocales.length) mCurrentIndex = 0; // Wrap around } public void prev() { mCurrentIndex--; if (mCurrentIndex < 0) mCurrentIndex = mLocales.length - 1; // Wrap around } public void persist() { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(mIme); Editor editor = sp.edit(); editor.putString(LatinIME.PREF_INPUT_LANGUAGE, getInputLanguage()); SharedPreferencesCompat.apply(editor); } static String toTitleCase(String s) { if (s.length() == 0) { return s; } return Character.toUpperCase(s.charAt(0)) + s.substring(1); } }
Java
/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.pocketworkstation.pckeyboard; import java.io.InputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.channels.Channels; import java.util.Arrays; import android.content.Context; import android.util.Log; /** * Implements a static, compacted, binary dictionary of standard words. */ public class BinaryDictionary extends Dictionary { /** * There is difference between what java and native code can handle. * This value should only be used in BinaryDictionary.java * It is necessary to keep it at this value because some languages e.g. German have * really long words. */ protected static final int MAX_WORD_LENGTH = 48; private static final String TAG = "BinaryDictionary"; private static final int MAX_ALTERNATIVES = 16; private static final int MAX_WORDS = 18; private static final int MAX_BIGRAMS = 60; private static final int TYPED_LETTER_MULTIPLIER = 2; private static final boolean ENABLE_MISSED_CHARACTERS = true; private int mDicTypeId; private int mNativeDict; private int mDictLength; private int[] mInputCodes = new int[MAX_WORD_LENGTH * MAX_ALTERNATIVES]; private char[] mOutputChars = new char[MAX_WORD_LENGTH * MAX_WORDS]; private char[] mOutputChars_bigrams = new char[MAX_WORD_LENGTH * MAX_BIGRAMS]; private int[] mFrequencies = new int[MAX_WORDS]; private int[] mFrequencies_bigrams = new int[MAX_BIGRAMS]; // Keep a reference to the native dict direct buffer in Java to avoid // unexpected deallocation of the direct buffer. private ByteBuffer mNativeDictDirectBuffer; static { try { System.loadLibrary("jni_pckeyboard"); Log.i("PCKeyboard", "loaded jni_pckeyboard"); } catch (UnsatisfiedLinkError ule) { Log.e("BinaryDictionary", "Could not load native library jni_pckeyboard"); } } /** * Create a dictionary from a raw resource file * @param context application context for reading resources * @param resId the resource containing the raw binary dictionary */ public BinaryDictionary(Context context, int[] resId, int dicTypeId) { if (resId != null && resId.length > 0 && resId[0] != 0) { loadDictionary(context, resId); } mDicTypeId = dicTypeId; } /** * Create a dictionary from input streams * @param context application context for reading resources * @param streams the resource streams containing the raw binary dictionary */ public BinaryDictionary(Context context, InputStream[] streams, int dicTypeId) { if (streams != null && streams.length > 0) { loadDictionary(streams); } mDicTypeId = dicTypeId; } /** * Create a dictionary from a byte buffer. This is used for testing. * @param context application context for reading resources * @param byteBuffer a ByteBuffer containing the binary dictionary */ public BinaryDictionary(Context context, ByteBuffer byteBuffer, int dicTypeId) { if (byteBuffer != null) { if (byteBuffer.isDirect()) { mNativeDictDirectBuffer = byteBuffer; } else { mNativeDictDirectBuffer = ByteBuffer.allocateDirect(byteBuffer.capacity()); byteBuffer.rewind(); mNativeDictDirectBuffer.put(byteBuffer); } mDictLength = byteBuffer.capacity(); mNativeDict = openNative(mNativeDictDirectBuffer, TYPED_LETTER_MULTIPLIER, FULL_WORD_FREQ_MULTIPLIER, mDictLength); } mDicTypeId = dicTypeId; } private native int openNative(ByteBuffer bb, int typedLetterMultiplier, int fullWordMultiplier, int dictSize); private native void closeNative(int dict); private native boolean isValidWordNative(int nativeData, char[] word, int wordLength); private native int getSuggestionsNative(int dict, int[] inputCodes, int codesSize, char[] outputChars, int[] frequencies, int maxWordLength, int maxWords, int maxAlternatives, int skipPos, int[] nextLettersFrequencies, int nextLettersSize); private native int getBigramsNative(int dict, char[] prevWord, int prevWordLength, int[] inputCodes, int inputCodesLength, char[] outputChars, int[] frequencies, int maxWordLength, int maxBigrams, int maxAlternatives); private final void loadDictionary(InputStream[] is) { try { // merging separated dictionary into one if dictionary is separated int total = 0; for (int i = 0; i < is.length; i++) { total += is[i].available(); } mNativeDictDirectBuffer = ByteBuffer.allocateDirect(total).order(ByteOrder.nativeOrder()); int got = 0; for (int i = 0; i < is.length; i++) { got += Channels.newChannel(is[i]).read(mNativeDictDirectBuffer); } if (got != total) { Log.e(TAG, "Read " + got + " bytes, expected " + total); } else { mNativeDict = openNative(mNativeDictDirectBuffer, TYPED_LETTER_MULTIPLIER, FULL_WORD_FREQ_MULTIPLIER, total); mDictLength = total; } if (mDictLength > 10000) Log.i("PCKeyboard", "Loaded dictionary, len=" + mDictLength); } catch (IOException e) { Log.w(TAG, "No available memory for binary dictionary"); } catch (UnsatisfiedLinkError e) { Log.w(TAG, "Failed to load native dictionary", e); } finally { try { if (is != null) { for (int i = 0; i < is.length; i++) { is[i].close(); } } } catch (IOException e) { Log.w(TAG, "Failed to close input stream"); } } } private final void loadDictionary(Context context, int[] resId) { InputStream[] is = null; is = new InputStream[resId.length]; for (int i = 0; i < resId.length; i++) { is[i] = context.getResources().openRawResource(resId[i]); } loadDictionary(is); } @Override public void getBigrams(final WordComposer codes, final CharSequence previousWord, final WordCallback callback, int[] nextLettersFrequencies) { char[] chars = previousWord.toString().toCharArray(); Arrays.fill(mOutputChars_bigrams, (char) 0); Arrays.fill(mFrequencies_bigrams, 0); int codesSize = codes.size(); Arrays.fill(mInputCodes, -1); int[] alternatives = codes.getCodesAt(0); System.arraycopy(alternatives, 0, mInputCodes, 0, Math.min(alternatives.length, MAX_ALTERNATIVES)); int count = getBigramsNative(mNativeDict, chars, chars.length, mInputCodes, codesSize, mOutputChars_bigrams, mFrequencies_bigrams, MAX_WORD_LENGTH, MAX_BIGRAMS, MAX_ALTERNATIVES); for (int j = 0; j < count; j++) { if (mFrequencies_bigrams[j] < 1) break; int start = j * MAX_WORD_LENGTH; int len = 0; while (mOutputChars_bigrams[start + len] != 0) { len++; } if (len > 0) { callback.addWord(mOutputChars_bigrams, start, len, mFrequencies_bigrams[j], mDicTypeId, DataType.BIGRAM); } } } @Override public void getWords(final WordComposer codes, final WordCallback callback, int[] nextLettersFrequencies) { final int codesSize = codes.size(); // Won't deal with really long words. if (codesSize > MAX_WORD_LENGTH - 1) return; Arrays.fill(mInputCodes, -1); for (int i = 0; i < codesSize; i++) { int[] alternatives = codes.getCodesAt(i); System.arraycopy(alternatives, 0, mInputCodes, i * MAX_ALTERNATIVES, Math.min(alternatives.length, MAX_ALTERNATIVES)); } Arrays.fill(mOutputChars, (char) 0); Arrays.fill(mFrequencies, 0); if (mNativeDict == 0) return; int count = getSuggestionsNative(mNativeDict, mInputCodes, codesSize, mOutputChars, mFrequencies, MAX_WORD_LENGTH, MAX_WORDS, MAX_ALTERNATIVES, -1, nextLettersFrequencies, nextLettersFrequencies != null ? nextLettersFrequencies.length : 0); // If there aren't sufficient suggestions, search for words by allowing wild cards at // the different character positions. This feature is not ready for prime-time as we need // to figure out the best ranking for such words compared to proximity corrections and // completions. if (ENABLE_MISSED_CHARACTERS && count < 5) { for (int skip = 0; skip < codesSize; skip++) { int tempCount = getSuggestionsNative(mNativeDict, mInputCodes, codesSize, mOutputChars, mFrequencies, MAX_WORD_LENGTH, MAX_WORDS, MAX_ALTERNATIVES, skip, null, 0); count = Math.max(count, tempCount); if (tempCount > 0) break; } } for (int j = 0; j < count; j++) { if (mFrequencies[j] < 1) break; int start = j * MAX_WORD_LENGTH; int len = 0; while (mOutputChars[start + len] != 0) { len++; } if (len > 0) { callback.addWord(mOutputChars, start, len, mFrequencies[j], mDicTypeId, DataType.UNIGRAM); } } } @Override public boolean isValidWord(CharSequence word) { if (word == null || mNativeDict == 0) return false; char[] chars = word.toString().toCharArray(); return isValidWordNative(mNativeDict, chars, chars.length); } public int getSize() { return mDictLength; // This value is initialized on the call to openNative() } @Override public synchronized void close() { if (mNativeDict != 0) { closeNative(mNativeDict); mNativeDict = 0; } } @Override protected void finalize() throws Throwable { close(); super.finalize(); } }
Java
/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.pocketworkstation.pckeyboard; import android.content.Context; import org.pocketworkstation.pckeyboard.Keyboard.Key; import android.text.format.DateFormat; import android.util.Log; import java.io.FileOutputStream; import java.io.IOException; import java.util.Calendar; public class TextEntryState { private static final boolean DBG = false; private static final String TAG = "TextEntryState"; private static boolean LOGGING = false; private static int sBackspaceCount = 0; private static int sAutoSuggestCount = 0; private static int sAutoSuggestUndoneCount = 0; private static int sManualSuggestCount = 0; private static int sWordNotInDictionaryCount = 0; private static int sSessionCount = 0; private static int sTypedChars; private static int sActualChars; public enum State { UNKNOWN, START, IN_WORD, ACCEPTED_DEFAULT, PICKED_SUGGESTION, PUNCTUATION_AFTER_WORD, PUNCTUATION_AFTER_ACCEPTED, SPACE_AFTER_ACCEPTED, SPACE_AFTER_PICKED, UNDO_COMMIT, CORRECTING, PICKED_CORRECTION; } private static State sState = State.UNKNOWN; private static FileOutputStream sKeyLocationFile; private static FileOutputStream sUserActionFile; public static void newSession(Context context) { sSessionCount++; sAutoSuggestCount = 0; sBackspaceCount = 0; sAutoSuggestUndoneCount = 0; sManualSuggestCount = 0; sWordNotInDictionaryCount = 0; sTypedChars = 0; sActualChars = 0; sState = State.START; if (LOGGING) { try { sKeyLocationFile = context.openFileOutput("key.txt", Context.MODE_APPEND); sUserActionFile = context.openFileOutput("action.txt", Context.MODE_APPEND); } catch (IOException ioe) { Log.e("TextEntryState", "Couldn't open file for output: " + ioe); } } } public static void endSession() { if (sKeyLocationFile == null) { return; } try { sKeyLocationFile.close(); // Write to log file // Write timestamp, settings, String out = DateFormat.format("MM:dd hh:mm:ss", Calendar.getInstance().getTime()) .toString() + " BS: " + sBackspaceCount + " auto: " + sAutoSuggestCount + " manual: " + sManualSuggestCount + " typed: " + sWordNotInDictionaryCount + " undone: " + sAutoSuggestUndoneCount + " saved: " + ((float) (sActualChars - sTypedChars) / sActualChars) + "\n"; sUserActionFile.write(out.getBytes()); sUserActionFile.close(); sKeyLocationFile = null; sUserActionFile = null; } catch (IOException ioe) { } } public static void acceptedDefault(CharSequence typedWord, CharSequence actualWord) { if (typedWord == null) return; if (!typedWord.equals(actualWord)) { sAutoSuggestCount++; } sTypedChars += typedWord.length(); sActualChars += actualWord.length(); sState = State.ACCEPTED_DEFAULT; LatinImeLogger.logOnAutoSuggestion(typedWord.toString(), actualWord.toString()); displayState(); } // State.ACCEPTED_DEFAULT will be changed to other sub-states // (see "case ACCEPTED_DEFAULT" in typedCharacter() below), // and should be restored back to State.ACCEPTED_DEFAULT after processing for each sub-state. public static void backToAcceptedDefault(CharSequence typedWord) { if (typedWord == null) return; switch (sState) { case SPACE_AFTER_ACCEPTED: case PUNCTUATION_AFTER_ACCEPTED: case IN_WORD: sState = State.ACCEPTED_DEFAULT; break; } displayState(); } public static void manualTyped(CharSequence typedWord) { sState = State.START; displayState(); } public static void acceptedTyped(CharSequence typedWord) { sWordNotInDictionaryCount++; sState = State.PICKED_SUGGESTION; displayState(); } public static void acceptedSuggestion(CharSequence typedWord, CharSequence actualWord) { sManualSuggestCount++; State oldState = sState; if (typedWord.equals(actualWord)) { acceptedTyped(typedWord); } if (oldState == State.CORRECTING || oldState == State.PICKED_CORRECTION) { sState = State.PICKED_CORRECTION; } else { sState = State.PICKED_SUGGESTION; } displayState(); } public static void selectedForCorrection() { sState = State.CORRECTING; displayState(); } public static void typedCharacter(char c, boolean isSeparator) { boolean isSpace = c == ' '; switch (sState) { case IN_WORD: if (isSpace || isSeparator) { sState = State.START; } else { // State hasn't changed. } break; case ACCEPTED_DEFAULT: case SPACE_AFTER_PICKED: if (isSpace) { sState = State.SPACE_AFTER_ACCEPTED; } else if (isSeparator) { sState = State.PUNCTUATION_AFTER_ACCEPTED; } else { sState = State.IN_WORD; } break; case PICKED_SUGGESTION: case PICKED_CORRECTION: if (isSpace) { sState = State.SPACE_AFTER_PICKED; } else if (isSeparator) { // Swap sState = State.PUNCTUATION_AFTER_ACCEPTED; } else { sState = State.IN_WORD; } break; case START: case UNKNOWN: case SPACE_AFTER_ACCEPTED: case PUNCTUATION_AFTER_ACCEPTED: case PUNCTUATION_AFTER_WORD: if (!isSpace && !isSeparator) { sState = State.IN_WORD; } else { sState = State.START; } break; case UNDO_COMMIT: if (isSpace || isSeparator) { sState = State.ACCEPTED_DEFAULT; } else { sState = State.IN_WORD; } break; case CORRECTING: sState = State.START; break; } displayState(); } public static void backspace() { if (sState == State.ACCEPTED_DEFAULT) { sState = State.UNDO_COMMIT; sAutoSuggestUndoneCount++; LatinImeLogger.logOnAutoSuggestionCanceled(); } else if (sState == State.UNDO_COMMIT) { sState = State.IN_WORD; } sBackspaceCount++; displayState(); } public static void reset() { sState = State.START; displayState(); } public static State getState() { if (DBG) { Log.d(TAG, "Returning state = " + sState); } return sState; } public static boolean isCorrecting() { return sState == State.CORRECTING || sState == State.PICKED_CORRECTION; } public static void keyPressedAt(Key key, int x, int y) { if (LOGGING && sKeyLocationFile != null && key.codes[0] >= 32) { String out = "KEY: " + (char) key.codes[0] + " X: " + x + " Y: " + y + " MX: " + (key.x + key.width / 2) + " MY: " + (key.y + key.height / 2) + "\n"; try { sKeyLocationFile.write(out.getBytes()); } catch (IOException ioe) { // TODO: May run out of space } } } private static void displayState() { if (DBG) { //Log.w(TAG, "State = " + sState, new Throwable()); Log.i(TAG, "State = " + sState); } } }
Java
/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.pocketworkstation.pckeyboard; import java.util.ArrayList; /** * A place to store the currently composing word with information such as adjacent key codes as well */ public class WordComposer { /** * The list of unicode values for each keystroke (including surrounding keys) */ private final ArrayList<int[]> mCodes; /** * The word chosen from the candidate list, until it is committed. */ private String mPreferredWord; private final StringBuilder mTypedWord; private int mCapsCount; private boolean mAutoCapitalized; /** * Whether the user chose to capitalize the first char of the word. */ private boolean mIsFirstCharCapitalized; public WordComposer() { mCodes = new ArrayList<int[]>(12); mTypedWord = new StringBuilder(20); } WordComposer(WordComposer copy) { mCodes = new ArrayList<int[]>(copy.mCodes); mPreferredWord = copy.mPreferredWord; mTypedWord = new StringBuilder(copy.mTypedWord); mCapsCount = copy.mCapsCount; mAutoCapitalized = copy.mAutoCapitalized; mIsFirstCharCapitalized = copy.mIsFirstCharCapitalized; } /** * Clear out the keys registered so far. */ public void reset() { mCodes.clear(); mIsFirstCharCapitalized = false; mPreferredWord = null; mTypedWord.setLength(0); mCapsCount = 0; } /** * Number of keystrokes in the composing word. * @return the number of keystrokes */ public int size() { return mCodes.size(); } /** * Returns the codes at a particular position in the word. * @param index the position in the word * @return the unicode for the pressed and surrounding keys */ public int[] getCodesAt(int index) { return mCodes.get(index); } /** * Add a new keystroke, with codes[0] containing the pressed key's unicode and the rest of * the array containing unicode for adjacent keys, sorted by reducing probability/proximity. * @param codes the array of unicode values */ public void add(int primaryCode, int[] codes) { mTypedWord.append((char) primaryCode); correctPrimaryJuxtapos(primaryCode, codes); correctCodesCase(codes); mCodes.add(codes); if (Character.isUpperCase((char) primaryCode)) mCapsCount++; } /** * Swaps the first and second values in the codes array if the primary code is not the first * value in the array but the second. This happens when the preferred key is not the key that * the user released the finger on. * @param primaryCode the preferred character * @param codes array of codes based on distance from touch point */ private void correctPrimaryJuxtapos(int primaryCode, int[] codes) { if (codes.length < 2) return; if (codes[0] > 0 && codes[1] > 0 && codes[0] != primaryCode && codes[1] == primaryCode) { codes[1] = codes[0]; codes[0] = primaryCode; } } // Prediction expects the keyKodes to be lowercase private void correctCodesCase(int[] codes) { for (int i = 0; i < codes.length; ++i) { int code = codes[i]; if (code > 0) codes[i] = Character.toLowerCase(code); } } /** * Delete the last keystroke as a result of hitting backspace. */ public void deleteLast() { final int codesSize = mCodes.size(); if (codesSize > 0) { mCodes.remove(codesSize - 1); final int lastPos = mTypedWord.length() - 1; char last = mTypedWord.charAt(lastPos); mTypedWord.deleteCharAt(lastPos); if (Character.isUpperCase(last)) mCapsCount--; } } /** * Returns the word as it was typed, without any correction applied. * @return the word that was typed so far */ public CharSequence getTypedWord() { int wordSize = mCodes.size(); if (wordSize == 0) { return null; } return mTypedWord; } public void setFirstCharCapitalized(boolean capitalized) { mIsFirstCharCapitalized = capitalized; } /** * Whether or not the user typed a capital letter as the first letter in the word * @return capitalization preference */ public boolean isFirstCharCapitalized() { return mIsFirstCharCapitalized; } /** * Whether or not all of the user typed chars are upper case * @return true if all user typed chars are upper case, false otherwise */ public boolean isAllUpperCase() { return (mCapsCount > 0) && (mCapsCount == size()); } /** * Stores the user's selected word, before it is actually committed to the text field. * @param preferred */ public void setPreferredWord(String preferred) { mPreferredWord = preferred; } /** * Return the word chosen by the user, or the typed word if no other word was chosen. * @return the preferred word */ public CharSequence getPreferredWord() { return mPreferredWord != null ? mPreferredWord : getTypedWord(); } /** * Returns true if more than one character is upper case, otherwise returns false. */ public boolean isMostlyCaps() { return mCapsCount > 1; } /** * Saves the reason why the word is capitalized - whether it was automatic or * due to the user hitting shift in the middle of a sentence. * @param auto whether it was an automatic capitalization due to start of sentence */ public void setAutoCapitalized(boolean auto) { mAutoCapitalized = auto; } /** * Returns whether the word was automatically capitalized. * @return whether the word was automatically capitalized */ public boolean isAutoCapitalized() { return mAutoCapitalized; } }
Java
/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.pocketworkstation.pckeyboard; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.database.ContentObserver; import android.database.Cursor; import android.provider.UserDictionary.Words; import android.util.Log; public class UserDictionary extends ExpandableDictionary { private static final String[] PROJECTION = { Words._ID, Words.WORD, Words.FREQUENCY }; private static final int INDEX_WORD = 1; private static final int INDEX_FREQUENCY = 2; private static final String TAG = "HK/UserDictionary"; private ContentObserver mObserver; private String mLocale; public UserDictionary(Context context, String locale) { super(context, Suggest.DIC_USER); mLocale = locale; // Perform a managed query. The Activity will handle closing and requerying the cursor // when needed. ContentResolver cres = context.getContentResolver(); cres.registerContentObserver(Words.CONTENT_URI, true, mObserver = new ContentObserver(null) { @Override public void onChange(boolean self) { setRequiresReload(true); } }); loadDictionary(); } @Override public synchronized void close() { if (mObserver != null) { getContext().getContentResolver().unregisterContentObserver(mObserver); mObserver = null; } super.close(); } @Override public void loadDictionaryAsync() { Cursor cursor = getContext().getContentResolver() .query(Words.CONTENT_URI, PROJECTION, "(locale IS NULL) or (locale=?)", new String[] { mLocale }, null); addWords(cursor); } /** * Adds a word to the dictionary and makes it persistent. * @param word the word to add. If the word is capitalized, then the dictionary will * recognize it as a capitalized word when searched. * @param frequency the frequency of occurrence of the word. A frequency of 255 is considered * the highest. * @TODO use a higher or float range for frequency */ @Override public synchronized void addWord(String word, int frequency) { // Force load the dictionary here synchronously if (getRequiresReload()) loadDictionaryAsync(); // Safeguard against adding long words. Can cause stack overflow. if (word.length() >= getMaxWordLength()) return; super.addWord(word, frequency); // Update the user dictionary provider final ContentValues values = new ContentValues(5); values.put(Words.WORD, word); values.put(Words.FREQUENCY, frequency); values.put(Words.LOCALE, mLocale); values.put(Words.APP_ID, 0); final ContentResolver contentResolver = getContext().getContentResolver(); new Thread("addWord") { public void run() { contentResolver.insert(Words.CONTENT_URI, values); } }.start(); // In case the above does a synchronous callback of the change observer setRequiresReload(false); } @Override public synchronized void getWords(final WordComposer codes, final WordCallback callback, int[] nextLettersFrequencies) { super.getWords(codes, callback, nextLettersFrequencies); } @Override public synchronized boolean isValidWord(CharSequence word) { return super.isValidWord(word); } private void addWords(Cursor cursor) { if (cursor == null) { Log.w(TAG, "Unexpected null cursor in addWords()"); return; } clearDictionary(); final int maxWordLength = getMaxWordLength(); if (cursor.moveToFirst()) { while (!cursor.isAfterLast()) { String word = cursor.getString(INDEX_WORD); int frequency = cursor.getInt(INDEX_FREQUENCY); // Safeguard against adding really long words. Stack may overflow due // to recursion if (word.length() < maxWordLength) { super.addWord(word, frequency); } cursor.moveToNext(); } } cursor.close(); } }
Java
/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.pocketworkstation.pckeyboard; import android.app.backup.BackupManager; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceActivity; public class PrefScreenActions extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener { @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); addPreferencesFromResource(R.xml.prefs_actions); SharedPreferences prefs = getPreferenceManager().getSharedPreferences(); prefs.registerOnSharedPreferenceChangeListener(this); } @Override protected void onDestroy() { getPreferenceManager().getSharedPreferences().unregisterOnSharedPreferenceChangeListener( this); super.onDestroy(); } public void onSharedPreferenceChanged(SharedPreferences prefs, String key) { (new BackupManager(this)).dataChanged(); } }
Java
package org.pocketworkstation.pckeyboard; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; import android.view.inputmethod.InputMethodManager; public class NotificationReceiver extends BroadcastReceiver { static final String TAG = "PCKeyboard/Notification"; private LatinIME mIME; NotificationReceiver(LatinIME ime) { super(); mIME = ime; Log.i(TAG, "NotificationReceiver created, ime=" + mIME); } @Override public void onReceive(Context context, Intent intent) { Log.i(TAG, "NotificationReceiver.onReceive called"); InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); if (imm != null) { imm.showSoftInputFromInputMethod(mIME.mToken, InputMethodManager.SHOW_FORCED); } } }
Java
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.pocketworkstation.pckeyboard; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.os.Bundle; import android.preference.CheckBoxPreference; import android.preference.PreferenceActivity; import android.util.Log; public class LatinIMEDebugSettings extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener { private static final String TAG = "LatinIMEDebugSettings"; private static final String DEBUG_MODE_KEY = "debug_mode"; private CheckBoxPreference mDebugMode; @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); addPreferencesFromResource(R.xml.prefs_for_debug); SharedPreferences prefs = getPreferenceManager().getSharedPreferences(); prefs.registerOnSharedPreferenceChangeListener(this); mDebugMode = (CheckBoxPreference) findPreference(DEBUG_MODE_KEY); updateDebugMode(); } public void onSharedPreferenceChanged(SharedPreferences prefs, String key) { if (key.equals(DEBUG_MODE_KEY)) { if (mDebugMode != null) { mDebugMode.setChecked(prefs.getBoolean(DEBUG_MODE_KEY, false)); updateDebugMode(); } } } private void updateDebugMode() { if (mDebugMode == null) { return; } boolean isDebugMode = mDebugMode.isChecked(); String version = ""; try { PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), 0); version = "Version " + info.versionName; } catch (NameNotFoundException e) { Log.e(TAG, "Could not find version info."); } if (!isDebugMode) { mDebugMode.setTitle(version); mDebugMode.setSummary(""); } else { mDebugMode.setTitle(getResources().getString(R.string.prefs_debug_mode)); mDebugMode.setSummary(version); } } }
Java
/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.pocketworkstation.pckeyboard; import android.app.backup.BackupManager; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.ListPreference; import android.preference.PreferenceActivity; public class PrefScreenFeedback extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener { @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); addPreferencesFromResource(R.xml.prefs_feedback); SharedPreferences prefs = getPreferenceManager().getSharedPreferences(); prefs.registerOnSharedPreferenceChangeListener(this); } @Override protected void onDestroy() { getPreferenceManager().getSharedPreferences().unregisterOnSharedPreferenceChangeListener( this); super.onDestroy(); } public void onSharedPreferenceChanged(SharedPreferences prefs, String key) { (new BackupManager(this)).dataChanged(); } @Override protected void onResume() { super.onResume(); } }
Java
package org.pocketworkstation.pckeyboard; import java.util.HashMap; import java.util.Locale; import java.util.Map; import android.content.SharedPreferences; import android.content.res.Resources; import android.util.Log; /** * Global current settings for the keyboard. * * <p> * Yes, globals are evil. But the persisted shared preferences are global data * by definition, and trying to hide this by propagating the current manually * just adds a lot of complication. This is especially annoying due to Views * getting constructed in a way that doesn't support adding additional * constructor arguments, requiring post-construction method calls, which is * error-prone and fragile. * * <p> * The comments below indicate which class is responsible for updating the * value, and for recreating keyboards or views as necessary. Other classes * MUST treat the fields as read-only values, and MUST NOT attempt to save * these values or results derived from them across re-initializations. * * @author klaus.weidner@gmail.com */ public final class GlobalKeyboardSettings { protected static final String TAG = "HK/Globals"; /* Simple prefs updated by this class */ // // Read by Keyboard public int popupKeyboardFlags = 0x1; public float topRowScale = 1.0f; // // Read by LatinKeyboardView public boolean showTouchPos = false; // // Read by LatinIME public String suggestedPunctuation = "!?,."; public int keyboardModePortrait = 0; public int keyboardModeLandscape = 2; public boolean compactModeEnabled = false; public int chordingCtrlKey = 0; public int chordingAltKey = 0; public float keyClickVolume = 0.0f; public int keyClickMethod = 0; public boolean capsLock = true; public boolean shiftLockModifiers = false; // // Read by LatinKeyboardBaseView public float labelScalePref = 1.0f; // // Read by CandidateView public float candidateScalePref = 1.0f; // // Read by PointerTracker public int sendSlideKeys = 0; /* Updated by LatinIME */ // // Read by KeyboardSwitcher public int keyboardMode = 0; public boolean useExtension = false; // // Read by LatinKeyboardView and KeyboardSwitcher public float keyboardHeightPercent = 40.0f; // percent of screen height // // Read by LatinKeyboardBaseView public int hintMode = 0; public int renderMode = 1; // // Read by PointerTracker public int longpressTimeout = 400; // // Read by LatinIMESettings // These are cached values for informational display, don't use for other purposes public String editorPackageName; public String editorFieldName; public int editorFieldId; public int editorInputType; /* Updated by KeyboardSwitcher */ // // Used by LatinKeyboardBaseView and LatinIME /* Updated by LanguageSwitcher */ // // Used by Keyboard and KeyboardSwitcher public Locale inputLocale = Locale.getDefault(); // Auto pref implementation follows private Map<String, BooleanPref> mBoolPrefs = new HashMap<String, BooleanPref>(); private Map<String, StringPref> mStringPrefs = new HashMap<String, StringPref>(); public static final int FLAG_PREF_NONE = 0; public static final int FLAG_PREF_NEED_RELOAD = 0x1; public static final int FLAG_PREF_NEW_PUNC_LIST = 0x2; public static final int FLAG_PREF_RECREATE_INPUT_VIEW = 0x4; public static final int FLAG_PREF_RESET_KEYBOARDS = 0x8; public static final int FLAG_PREF_RESET_MODE_OVERRIDE = 0x10; private int mCurrentFlags = 0; private interface BooleanPref { void set(boolean val); boolean getDefault(); int getFlags(); } private interface StringPref { void set(String val); String getDefault(); int getFlags(); } public void initPrefs(SharedPreferences prefs, Resources resources) { final Resources res = resources; addBooleanPref("pref_compact_mode_enabled", new BooleanPref() { public void set(boolean val) { compactModeEnabled = val; Log.i(TAG, "Setting compactModeEnabled to " + val); } public boolean getDefault() { return res.getBoolean(R.bool.default_compact_mode_enabled); } public int getFlags() { return FLAG_PREF_RESET_MODE_OVERRIDE; } }); addStringPref("pref_keyboard_mode_portrait", new StringPref() { public void set(String val) { keyboardModePortrait = Integer.valueOf(val); } public String getDefault() { return res.getString(R.string.default_keyboard_mode_portrait); } public int getFlags() { return FLAG_PREF_RESET_KEYBOARDS | FLAG_PREF_RESET_MODE_OVERRIDE; } }); addStringPref("pref_keyboard_mode_landscape", new StringPref() { public void set(String val) { keyboardModeLandscape = Integer.valueOf(val); } public String getDefault() { return res.getString(R.string.default_keyboard_mode_landscape); } public int getFlags() { return FLAG_PREF_RESET_KEYBOARDS | FLAG_PREF_RESET_MODE_OVERRIDE; } }); addStringPref("pref_slide_keys_int", new StringPref() { public void set(String val) { sendSlideKeys = Integer.valueOf(val); } public String getDefault() { return "0"; } public int getFlags() { return FLAG_PREF_NONE; } }); addBooleanPref("pref_touch_pos", new BooleanPref() { public void set(boolean val) { showTouchPos = val; } public boolean getDefault() { return false; } public int getFlags() { return FLAG_PREF_NONE; } }); addStringPref("pref_popup_content", new StringPref() { public void set(String val) { popupKeyboardFlags = Integer.valueOf(val); } public String getDefault() { return res.getString(R.string.default_popup_content); } public int getFlags() { return FLAG_PREF_RESET_KEYBOARDS; } }); addStringPref("pref_suggested_punctuation", new StringPref() { public void set(String val) { suggestedPunctuation = val; } public String getDefault() { return res.getString(R.string.suggested_punctuations_default); } public int getFlags() { return FLAG_PREF_NEW_PUNC_LIST; } }); addStringPref("pref_label_scale", new StringPref() { public void set(String val) { labelScalePref = Float.valueOf(val); } public String getDefault() { return "1.0"; } public int getFlags() { return FLAG_PREF_RECREATE_INPUT_VIEW; } }); addStringPref("pref_candidate_scale", new StringPref() { public void set(String val) { candidateScalePref = Float.valueOf(val); } public String getDefault() { return "1.0"; } public int getFlags() { return FLAG_PREF_RESET_KEYBOARDS; } }); addStringPref("pref_top_row_scale", new StringPref() { public void set(String val) { topRowScale = Float.valueOf(val); } public String getDefault() { return "1.0"; } public int getFlags() { return FLAG_PREF_RESET_KEYBOARDS; } }); addStringPref("pref_chording_ctrl_key", new StringPref() { public void set(String val) { chordingCtrlKey = Integer.valueOf(val); } public String getDefault() { return res.getString(R.string.default_chording_ctrl_key); } public int getFlags() { return FLAG_PREF_RESET_KEYBOARDS; } }); addStringPref("pref_chording_alt_key", new StringPref() { public void set(String val) { chordingAltKey = Integer.valueOf(val); } public String getDefault() { return res.getString(R.string.default_chording_alt_key); } public int getFlags() { return FLAG_PREF_RESET_KEYBOARDS; } }); addStringPref("pref_click_volume", new StringPref() { public void set(String val) { keyClickVolume = Float.valueOf(val); } public String getDefault() { return res.getString(R.string.default_click_volume); } public int getFlags() { return FLAG_PREF_NONE; } }); addStringPref("pref_click_method", new StringPref() { public void set(String val) { keyClickMethod = Integer.valueOf(val); } public String getDefault() { return res.getString(R.string.default_click_method); } public int getFlags() { return FLAG_PREF_NONE; } }); addBooleanPref("pref_caps_lock", new BooleanPref() { public void set(boolean val) { capsLock = val; } public boolean getDefault() { return res.getBoolean(R.bool.default_caps_lock); } public int getFlags() { return FLAG_PREF_NONE; } }); addBooleanPref("pref_shift_lock_modifiers", new BooleanPref() { public void set(boolean val) { shiftLockModifiers = val; } public boolean getDefault() { return res.getBoolean(R.bool.default_shift_lock_modifiers); } public int getFlags() { return FLAG_PREF_NONE; } }); // Set initial values for (String key : mBoolPrefs.keySet()) { BooleanPref pref = mBoolPrefs.get(key); pref.set(prefs.getBoolean(key, pref.getDefault())); } for (String key : mStringPrefs.keySet()) { StringPref pref = mStringPrefs.get(key); pref.set(prefs.getString(key, pref.getDefault())); } } public void sharedPreferenceChanged(SharedPreferences prefs, String key) { boolean found = false; mCurrentFlags = FLAG_PREF_NONE; BooleanPref bPref = mBoolPrefs.get(key); if (bPref != null) { found = true; bPref.set(prefs.getBoolean(key, bPref.getDefault())); mCurrentFlags |= bPref.getFlags(); } StringPref sPref = mStringPrefs.get(key); if (sPref != null) { found = true; sPref.set(prefs.getString(key, sPref.getDefault())); mCurrentFlags |= sPref.getFlags(); } //if (!found) Log.i(TAG, "sharedPreferenceChanged: unhandled key=" + key); } public boolean hasFlag(int flag) { if ((mCurrentFlags & flag) != 0) { mCurrentFlags &= ~flag; return true; } return false; } public int unhandledFlags() { return mCurrentFlags; } private void addBooleanPref(String key, BooleanPref setter) { mBoolPrefs.put(key, setter); } private void addStringPref(String key, StringPref setter) { mStringPrefs.put(key, setter); } }
Java
/* * Copyright (C) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.pocketworkstation.pckeyboard; import android.text.TextUtils; import android.view.inputmethod.ExtractedText; import android.view.inputmethod.ExtractedTextRequest; import android.view.inputmethod.InputConnection; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.regex.Pattern; /** * Utility methods to deal with editing text through an InputConnection. */ public class EditingUtil { /** * Number of characters we want to look back in order to identify the previous word */ private static final int LOOKBACK_CHARACTER_NUM = 15; // Cache Method pointers private static boolean sMethodsInitialized; private static Method sMethodGetSelectedText; private static Method sMethodSetComposingRegion; private EditingUtil() {}; /** * Append newText to the text field represented by connection. * The new text becomes selected. */ public static void appendText(InputConnection connection, String newText) { if (connection == null) { return; } // Commit the composing text connection.finishComposingText(); // Add a space if the field already has text. CharSequence charBeforeCursor = connection.getTextBeforeCursor(1, 0); if (charBeforeCursor != null && !charBeforeCursor.equals(" ") && (charBeforeCursor.length() > 0)) { newText = " " + newText; } connection.setComposingText(newText, 1); } private static int getCursorPosition(InputConnection connection) { ExtractedText extracted = connection.getExtractedText( new ExtractedTextRequest(), 0); if (extracted == null) { return -1; } return extracted.startOffset + extracted.selectionStart; } /** * @param connection connection to the current text field. * @param sep characters which may separate words * @param range the range object to store the result into * @return the word that surrounds the cursor, including up to one trailing * separator. For example, if the field contains "he|llo world", where | * represents the cursor, then "hello " will be returned. */ public static String getWordAtCursor( InputConnection connection, String separators, Range range) { Range r = getWordRangeAtCursor(connection, separators, range); return (r == null) ? null : r.word; } /** * Removes the word surrounding the cursor. Parameters are identical to * getWordAtCursor. */ public static void deleteWordAtCursor( InputConnection connection, String separators) { Range range = getWordRangeAtCursor(connection, separators, null); if (range == null) return; connection.finishComposingText(); // Move cursor to beginning of word, to avoid crash when cursor is outside // of valid range after deleting text. int newCursor = getCursorPosition(connection) - range.charsBefore; connection.setSelection(newCursor, newCursor); connection.deleteSurroundingText(0, range.charsBefore + range.charsAfter); } /** * Represents a range of text, relative to the current cursor position. */ public static class Range { /** Characters before selection start */ public int charsBefore; /** * Characters after selection start, including one trailing word * separator. */ public int charsAfter; /** The actual characters that make up a word */ public String word; public Range() {} public Range(int charsBefore, int charsAfter, String word) { if (charsBefore < 0 || charsAfter < 0) { throw new IndexOutOfBoundsException(); } this.charsBefore = charsBefore; this.charsAfter = charsAfter; this.word = word; } } private static Range getWordRangeAtCursor( InputConnection connection, String sep, Range range) { if (connection == null || sep == null) { return null; } CharSequence before = connection.getTextBeforeCursor(1000, 0); CharSequence after = connection.getTextAfterCursor(1000, 0); if (before == null || after == null) { return null; } // Find first word separator before the cursor int start = before.length(); while (start > 0 && !isWhitespace(before.charAt(start - 1), sep)) start--; // Find last word separator after the cursor int end = -1; while (++end < after.length() && !isWhitespace(after.charAt(end), sep)); int cursor = getCursorPosition(connection); if (start >= 0 && cursor + end <= after.length() + before.length()) { String word = before.toString().substring(start, before.length()) + after.toString().substring(0, end); Range returnRange = range != null? range : new Range(); returnRange.charsBefore = before.length() - start; returnRange.charsAfter = end; returnRange.word = word; return returnRange; } return null; } private static boolean isWhitespace(int code, String whitespace) { return whitespace.contains(String.valueOf((char) code)); } private static final Pattern spaceRegex = Pattern.compile("\\s+"); public static CharSequence getPreviousWord(InputConnection connection, String sentenceSeperators) { //TODO: Should fix this. This could be slow! CharSequence prev = connection.getTextBeforeCursor(LOOKBACK_CHARACTER_NUM, 0); if (prev == null) { return null; } String[] w = spaceRegex.split(prev); if (w.length >= 2 && w[w.length-2].length() > 0) { char lastChar = w[w.length-2].charAt(w[w.length-2].length() -1); if (sentenceSeperators.contains(String.valueOf(lastChar))) { return null; } return w[w.length-2]; } else { return null; } } public static class SelectedWord { public int start; public int end; public CharSequence word; } /** * Takes a character sequence with a single character and checks if the character occurs * in a list of word separators or is empty. * @param singleChar A CharSequence with null, zero or one character * @param wordSeparators A String containing the word separators * @return true if the character is at a word boundary, false otherwise */ private static boolean isWordBoundary(CharSequence singleChar, String wordSeparators) { return TextUtils.isEmpty(singleChar) || wordSeparators.contains(singleChar); } /** * Checks if the cursor is inside a word or the current selection is a whole word. * @param ic the InputConnection for accessing the text field * @param selStart the start position of the selection within the text field * @param selEnd the end position of the selection within the text field. This could be * the same as selStart, if there's no selection. * @param wordSeparators the word separator characters for the current language * @return an object containing the text and coordinates of the selected/touching word, * null if the selection/cursor is not marking a whole word. */ public static SelectedWord getWordAtCursorOrSelection(final InputConnection ic, int selStart, int selEnd, String wordSeparators) { if (selStart == selEnd) { // There is just a cursor, so get the word at the cursor EditingUtil.Range range = new EditingUtil.Range(); CharSequence touching = getWordAtCursor(ic, wordSeparators, range); if (!TextUtils.isEmpty(touching)) { SelectedWord selWord = new SelectedWord(); selWord.word = touching; selWord.start = selStart - range.charsBefore; selWord.end = selEnd + range.charsAfter; return selWord; } } else { // Is the previous character empty or a word separator? If not, return null. CharSequence charsBefore = ic.getTextBeforeCursor(1, 0); if (!isWordBoundary(charsBefore, wordSeparators)) { return null; } // Is the next character empty or a word separator? If not, return null. CharSequence charsAfter = ic.getTextAfterCursor(1, 0); if (!isWordBoundary(charsAfter, wordSeparators)) { return null; } // Extract the selection alone CharSequence touching = getSelectedText(ic, selStart, selEnd); if (TextUtils.isEmpty(touching)) return null; // Is any part of the selection a separator? If so, return null. final int length = touching.length(); for (int i = 0; i < length; i++) { if (wordSeparators.contains(touching.subSequence(i, i + 1))) { return null; } } // Prepare the selected word SelectedWord selWord = new SelectedWord(); selWord.start = selStart; selWord.end = selEnd; selWord.word = touching; return selWord; } return null; } /** * Cache method pointers for performance */ private static void initializeMethodsForReflection() { try { // These will either both exist or not, so no need for separate try/catch blocks. // If other methods are added later, use separate try/catch blocks. sMethodGetSelectedText = InputConnection.class.getMethod("getSelectedText", int.class); sMethodSetComposingRegion = InputConnection.class.getMethod("setComposingRegion", int.class, int.class); } catch (NoSuchMethodException exc) { // Ignore } sMethodsInitialized = true; } /** * Returns the selected text between the selStart and selEnd positions. */ private static CharSequence getSelectedText(InputConnection ic, int selStart, int selEnd) { // Use reflection, for backward compatibility CharSequence result = null; if (!sMethodsInitialized) { initializeMethodsForReflection(); } if (sMethodGetSelectedText != null) { try { result = (CharSequence) sMethodGetSelectedText.invoke(ic, 0); return result; } catch (InvocationTargetException exc) { // Ignore } catch (IllegalArgumentException e) { // Ignore } catch (IllegalAccessException e) { // Ignore } } // Reflection didn't work, try it the poor way, by moving the cursor to the start, // getting the text after the cursor and moving the text back to selected mode. // TODO: Verify that this works properly in conjunction with // LatinIME#onUpdateSelection ic.setSelection(selStart, selEnd); result = ic.getTextAfterCursor(selEnd - selStart, 0); ic.setSelection(selStart, selEnd); return result; } /** * Tries to set the text into composition mode if there is support for it in the framework. */ public static void underlineWord(InputConnection ic, SelectedWord word) { // Use reflection, for backward compatibility // If method not found, there's nothing we can do. It still works but just wont underline // the word. if (!sMethodsInitialized) { initializeMethodsForReflection(); } if (sMethodSetComposingRegion != null) { try { sMethodSetComposingRegion.invoke(ic, word.start, word.end); } catch (InvocationTargetException exc) { // Ignore } catch (IllegalArgumentException e) { // Ignore } catch (IllegalAccessException e) { // Ignore } } } }
Java
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.pocketworkstation.pckeyboard; import org.pocketworkstation.pckeyboard.Dictionary.DataType; import android.content.Context; import android.content.SharedPreferences; import java.util.List; public class LatinImeLogger implements SharedPreferences.OnSharedPreferenceChangeListener { public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { } public static void init(Context context) { } public static void commit() { } public static void onDestroy() { } public static void logOnManualSuggestion( String before, String after, int position, List<CharSequence> suggestions) { } public static void logOnAutoSuggestion(String before, String after) { } public static void logOnAutoSuggestionCanceled() { } public static void logOnDelete() { } public static void logOnInputChar() { } public static void logOnException(String metaData, Throwable e) { } public static void logOnWarning(String warning) { } public static void onStartSuggestion(CharSequence previousWords) { } public static void onAddSuggestedWord(String word, int typeId, DataType dataType) { } public static void onSetKeyboard(Keyboard kb) { } }
Java
package org.pocketworkstation.pckeyboard; import java.util.regex.Matcher; import java.util.regex.Pattern; import android.content.Context; import android.content.res.TypedArray; import android.util.AttributeSet; /** * Variant of SeekBarPreference that stores values as string preferences. * * This is for compatibility with existing preferences, switching types * leads to runtime errors when upgrading or downgrading. */ public class SeekBarPreferenceString extends SeekBarPreference { private static Pattern FLOAT_RE = Pattern.compile("(\\d+\\.?\\d*).*"); public SeekBarPreferenceString(Context context, AttributeSet attrs) { super(context, attrs); init(context, attrs); } // Some saved preferences from old versions have " ms" or "%" suffix, remove that. private float floatFromString(String pref) { Matcher num = FLOAT_RE.matcher(pref); if (!num.matches()) return 0.0f; return Float.valueOf(num.group(1)); } @Override protected Float onGetDefaultValue(TypedArray a, int index) { return floatFromString(a.getString(index)); } @Override protected void onSetInitialValue(boolean restorePersistedValue, Object defaultValue) { if (restorePersistedValue) { setVal(floatFromString(getPersistedString("0.0"))); } else { setVal(Float.valueOf((Float) defaultValue)); } savePrevVal(); } @Override protected void onDialogClosed(boolean positiveResult) { if (!positiveResult) { restoreVal(); return; } if (shouldPersist()) { savePrevVal(); persistString(getValString()); } notifyChanged(); } }
Java
/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.pocketworkstation.pckeyboard; import android.content.Context; import android.content.res.Resources; import android.content.res.TypedArray; import android.content.res.XmlResourceParser; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.ColorFilter; import android.graphics.Paint; import android.graphics.Paint.Align; import android.graphics.PixelFormat; import android.graphics.PorterDuff; import android.graphics.Rect; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.text.TextPaint; import android.util.Log; import android.view.ViewConfiguration; import android.view.inputmethod.EditorInfo; import java.util.List; import java.util.Locale; public class LatinKeyboard extends Keyboard { private static final boolean DEBUG_PREFERRED_LETTER = true; private static final String TAG = "PCKeyboardLK"; private static final int OPACITY_FULLY_OPAQUE = 255; private static final int SPACE_LED_LENGTH_PERCENT = 80; private Drawable mShiftLockIcon; private Drawable mShiftLockPreviewIcon; private Drawable mOldShiftIcon; private Drawable mSpaceIcon; private Drawable mSpaceAutoCompletionIndicator; private Drawable mSpacePreviewIcon; private Drawable mMicIcon; private Drawable mMicPreviewIcon; private Drawable mSettingsIcon; private Drawable mSettingsPreviewIcon; private Drawable m123MicIcon; private Drawable m123MicPreviewIcon; private final Drawable mButtonArrowLeftIcon; private final Drawable mButtonArrowRightIcon; private Key mShiftKey; private Key mEnterKey; private Key mF1Key; private final Drawable mHintIcon; private Key mSpaceKey; private Key m123Key; private final int[] mSpaceKeyIndexArray; private int mSpaceDragStartX; private int mSpaceDragLastDiff; private Locale mLocale; private LanguageSwitcher mLanguageSwitcher; private final Resources mRes; private final Context mContext; private int mMode; // Whether this keyboard has voice icon on it private boolean mHasVoiceButton; // Whether voice icon is enabled at all private boolean mVoiceEnabled; private final boolean mIsAlphaKeyboard; private final boolean mIsAlphaFullKeyboard; private final boolean mIsFnFullKeyboard; private CharSequence m123Label; private boolean mCurrentlyInSpace; private SlidingLocaleDrawable mSlidingLocaleIcon; private int[] mPrefLetterFrequencies; private int mPrefLetter; private int mPrefLetterX; private int mPrefLetterY; private int mPrefDistance; private int mExtensionResId; // TODO: remove this attribute when either Keyboard.mDefaultVerticalGap or Key.parent becomes // non-private. private final int mVerticalGap; private LatinKeyboard mExtensionKeyboard; private static final float SPACEBAR_DRAG_THRESHOLD = 0.51f; private static final float OVERLAP_PERCENTAGE_LOW_PROB = 0.70f; private static final float OVERLAP_PERCENTAGE_HIGH_PROB = 0.85f; // Minimum width of space key preview (proportional to keyboard width) private static final float SPACEBAR_POPUP_MIN_RATIO = 0.4f; // Minimum width of space key preview (proportional to screen height) private static final float SPACEBAR_POPUP_MAX_RATIO = 0.4f; // Height in space key the language name will be drawn. (proportional to space key height) private static final float SPACEBAR_LANGUAGE_BASELINE = 0.6f; // If the full language name needs to be smaller than this value to be drawn on space key, // its short language name will be used instead. private static final float MINIMUM_SCALE_OF_LANGUAGE_NAME = 0.8f; private static int sSpacebarVerticalCorrection; public LatinKeyboard(Context context, int xmlLayoutResId) { this(context, xmlLayoutResId, 0, 0); } public LatinKeyboard(Context context, int xmlLayoutResId, int mode, float kbHeightPercent) { super(context, 0, xmlLayoutResId, mode, kbHeightPercent); final Resources res = context.getResources(); //Log.i("PCKeyboard", "keyHeight=" + this.getKeyHeight()); //this.setKeyHeight(30); // is useless, see http://code.google.com/p/android/issues/detail?id=4532 mContext = context; mMode = mode; mRes = res; mShiftLockIcon = res.getDrawable(R.drawable.sym_keyboard_shift_locked); mShiftLockPreviewIcon = res.getDrawable(R.drawable.sym_keyboard_feedback_shift_locked); setDefaultBounds(mShiftLockPreviewIcon); mSpaceIcon = res.getDrawable(R.drawable.sym_keyboard_space); mSpaceAutoCompletionIndicator = res.getDrawable(R.drawable.sym_keyboard_space_led); mSpacePreviewIcon = res.getDrawable(R.drawable.sym_keyboard_feedback_space); mMicIcon = res.getDrawable(R.drawable.sym_keyboard_mic); mMicPreviewIcon = res.getDrawable(R.drawable.sym_keyboard_feedback_mic); mSettingsIcon = res.getDrawable(R.drawable.sym_keyboard_settings); mSettingsPreviewIcon = res.getDrawable(R.drawable.sym_keyboard_feedback_settings); setDefaultBounds(mMicPreviewIcon); mButtonArrowLeftIcon = res.getDrawable(R.drawable.sym_keyboard_language_arrows_left); mButtonArrowRightIcon = res.getDrawable(R.drawable.sym_keyboard_language_arrows_right); m123MicIcon = res.getDrawable(R.drawable.sym_keyboard_123_mic); m123MicPreviewIcon = res.getDrawable(R.drawable.sym_keyboard_feedback_123_mic); mHintIcon = res.getDrawable(R.drawable.hint_popup); setDefaultBounds(m123MicPreviewIcon); sSpacebarVerticalCorrection = res.getDimensionPixelOffset( R.dimen.spacebar_vertical_correction); mIsAlphaKeyboard = xmlLayoutResId == R.xml.kbd_qwerty; mIsAlphaFullKeyboard = xmlLayoutResId == R.xml.kbd_full; mIsFnFullKeyboard = xmlLayoutResId == R.xml.kbd_full_fn; // The index of space key is available only after Keyboard constructor has finished. mSpaceKeyIndexArray = new int[] { indexOf(LatinIME.ASCII_SPACE) }; // TODO remove this initialization after cleanup mVerticalGap = super.getVerticalGap(); } @Override protected Key createKeyFromXml(Resources res, Row parent, int x, int y, XmlResourceParser parser) { Key key = new LatinKey(res, parent, x, y, parser); if (key.codes == null) return key; switch (key.codes[0]) { case LatinIME.ASCII_ENTER: mEnterKey = key; break; case LatinKeyboardView.KEYCODE_F1: mF1Key = key; break; case LatinIME.ASCII_SPACE: mSpaceKey = key; break; case KEYCODE_MODE_CHANGE: m123Key = key; m123Label = key.label; break; } return key; } void setImeOptions(Resources res, int mode, int options) { mMode = mode; // TODO should clean up this method if (mEnterKey != null) { // Reset some of the rarely used attributes. mEnterKey.popupCharacters = null; mEnterKey.popupResId = 0; mEnterKey.text = null; switch (options&(EditorInfo.IME_MASK_ACTION|EditorInfo.IME_FLAG_NO_ENTER_ACTION)) { case EditorInfo.IME_ACTION_GO: mEnterKey.iconPreview = null; mEnterKey.icon = null; mEnterKey.label = res.getText(R.string.label_go_key); break; case EditorInfo.IME_ACTION_NEXT: mEnterKey.iconPreview = null; mEnterKey.icon = null; mEnterKey.label = res.getText(R.string.label_next_key); break; case EditorInfo.IME_ACTION_DONE: mEnterKey.iconPreview = null; mEnterKey.icon = null; mEnterKey.label = res.getText(R.string.label_done_key); break; case EditorInfo.IME_ACTION_SEARCH: mEnterKey.iconPreview = res.getDrawable( R.drawable.sym_keyboard_feedback_search); mEnterKey.icon = res.getDrawable(R.drawable.sym_keyboard_search); mEnterKey.label = null; break; case EditorInfo.IME_ACTION_SEND: mEnterKey.iconPreview = null; mEnterKey.icon = null; mEnterKey.label = res.getText(R.string.label_send_key); break; default: // Keep Return key in IM mode, we have a dedicated smiley key. mEnterKey.iconPreview = res.getDrawable( R.drawable.sym_keyboard_feedback_return); mEnterKey.icon = res.getDrawable(R.drawable.sym_keyboard_return); mEnterKey.label = null; break; } // Set the initial size of the preview icon if (mEnterKey.iconPreview != null) { setDefaultBounds(mEnterKey.iconPreview); } } } void enableShiftLock() { int index = getShiftKeyIndex(); if (index >= 0) { mShiftKey = getKeys().get(index); mOldShiftIcon = mShiftKey.icon; } } @Override public boolean setShiftState(int shiftState) { if (mShiftKey != null) { // Tri-state LED tracks "on" and "lock" states, icon shows Caps state. mShiftKey.on = shiftState == SHIFT_ON || shiftState == SHIFT_LOCKED; mShiftKey.locked = shiftState == SHIFT_LOCKED || shiftState == SHIFT_CAPS_LOCKED; mShiftKey.icon = (shiftState == SHIFT_OFF || shiftState == SHIFT_ON || shiftState == SHIFT_LOCKED) ? mOldShiftIcon : mShiftLockIcon; return super.setShiftState(shiftState, false); } else { return super.setShiftState(shiftState, true); } } /* package */ boolean isAlphaKeyboard() { return mIsAlphaKeyboard; } public void setExtension(LatinKeyboard extKeyboard) { mExtensionKeyboard = extKeyboard; } public LatinKeyboard getExtension() { return mExtensionKeyboard; } public void updateSymbolIcons(boolean isAutoCompletion) { updateDynamicKeys(); if (mSpaceKey != null) { updateSpaceBarForLocale(isAutoCompletion); } } private void setDefaultBounds(Drawable drawable) { drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight()); } public void setVoiceMode(boolean hasVoiceButton, boolean hasVoice) { mHasVoiceButton = hasVoiceButton; mVoiceEnabled = hasVoice; updateDynamicKeys(); } private void updateDynamicKeys() { update123Key(); updateF1Key(); } private void update123Key() { // Update KEYCODE_MODE_CHANGE key only on alphabet mode, not on symbol mode. if (m123Key != null && mIsAlphaKeyboard) { if (mVoiceEnabled && !mHasVoiceButton) { m123Key.icon = m123MicIcon; m123Key.iconPreview = m123MicPreviewIcon; m123Key.label = null; } else { m123Key.icon = null; m123Key.iconPreview = null; m123Key.label = m123Label; } } } private void updateF1Key() { // Update KEYCODE_F1 key. Please note that some keyboard layouts have no F1 key. if (mF1Key == null) return; if (mIsAlphaKeyboard) { if (mMode == KeyboardSwitcher.MODE_URL) { setNonMicF1Key(mF1Key, "/", R.xml.popup_slash); } else if (mMode == KeyboardSwitcher.MODE_EMAIL) { setNonMicF1Key(mF1Key, "@", R.xml.popup_at); } else { if (mVoiceEnabled && mHasVoiceButton) { setMicF1Key(mF1Key); } else { setNonMicF1Key(mF1Key, ",", R.xml.popup_comma); } } } else if (mIsAlphaFullKeyboard) { if (mVoiceEnabled && mHasVoiceButton) { setMicF1Key(mF1Key); } else { setSettingsF1Key(mF1Key); } } else if (mIsFnFullKeyboard) { setMicF1Key(mF1Key); } else { // Symbols keyboard if (mVoiceEnabled && mHasVoiceButton) { setMicF1Key(mF1Key); } else { setNonMicF1Key(mF1Key, ",", R.xml.popup_comma); } } } private void setMicF1Key(Key key) { // HACK: draw mMicIcon and mHintIcon at the same time final Drawable micWithSettingsHintDrawable = new BitmapDrawable(mRes, drawSynthesizedSettingsHintImage(key.width, key.height, mMicIcon, mHintIcon)); if (key.popupResId == 0) { key.popupResId = R.xml.popup_mic; } else { key.modifier = true; if (key.label != null) { key.popupCharacters = (key.popupCharacters == null) ? key.label : key.label + key.popupCharacters.toString(); } } key.label = null; key.codes = new int[] { LatinKeyboardView.KEYCODE_VOICE }; key.icon = micWithSettingsHintDrawable; key.iconPreview = mMicPreviewIcon; } private void setSettingsF1Key(Key key) { if (key.shiftLabel != null && key.label != null) { key.codes = new int[] { key.label.charAt(0) }; return; // leave key otherwise unmodified } final Drawable settingsHintDrawable = new BitmapDrawable(mRes, drawSynthesizedSettingsHintImage(key.width, key.height, mSettingsIcon, mHintIcon)); key.label = null; key.icon = settingsHintDrawable; key.codes = new int[] { LatinKeyboardView.KEYCODE_OPTIONS }; key.popupResId = R.xml.popup_mic; key.iconPreview = mSettingsPreviewIcon; } private void setNonMicF1Key(Key key, String label, int popupResId) { if (key.shiftLabel != null) { key.codes = new int[] { key.label.charAt(0) }; return; // leave key unmodified } key.label = label; key.codes = new int[] { label.charAt(0) }; key.popupResId = popupResId; key.icon = mHintIcon; key.iconPreview = null; } public boolean isF1Key(Key key) { return key == mF1Key; } public static boolean hasPuncOrSmileysPopup(Key key) { return key.popupResId == R.xml.popup_punctuation || key.popupResId == R.xml.popup_smileys; } /** * @return a key which should be invalidated. */ public Key onAutoCompletionStateChanged(boolean isAutoCompletion) { updateSpaceBarForLocale(isAutoCompletion); return mSpaceKey; } public boolean isLanguageSwitchEnabled() { return mLocale != null; } private void updateSpaceBarForLocale(boolean isAutoCompletion) { // If application locales are explicitly selected. if (mLocale != null) { mSpaceKey.icon = new BitmapDrawable(mRes, drawSpaceBar(OPACITY_FULLY_OPAQUE, isAutoCompletion)); } else { // sym_keyboard_space_led can be shared with Black and White symbol themes. if (isAutoCompletion) { mSpaceKey.icon = new BitmapDrawable(mRes, drawSpaceBar(OPACITY_FULLY_OPAQUE, isAutoCompletion)); } else { mSpaceKey.icon = mRes.getDrawable(R.drawable.sym_keyboard_space); } } } // Compute width of text with specified text size using paint. private static int getTextWidth(Paint paint, String text, float textSize, Rect bounds) { paint.setTextSize(textSize); paint.getTextBounds(text, 0, text.length(), bounds); return bounds.width(); } // Overlay two images: mainIcon and hintIcon. private Bitmap drawSynthesizedSettingsHintImage( int width, int height, Drawable mainIcon, Drawable hintIcon) { if (mainIcon == null || hintIcon == null) return null; Rect hintIconPadding = new Rect(0, 0, 0, 0); hintIcon.getPadding(hintIconPadding); final Bitmap buffer = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); final Canvas canvas = new Canvas(buffer); canvas.drawColor(mRes.getColor(R.color.latinkeyboard_transparent), PorterDuff.Mode.CLEAR); // Draw main icon at the center of the key visual // Assuming the hintIcon shares the same padding with the key's background drawable final int drawableX = (width + hintIconPadding.left - hintIconPadding.right - mainIcon.getIntrinsicWidth()) / 2; final int drawableY = (height + hintIconPadding.top - hintIconPadding.bottom - mainIcon.getIntrinsicHeight()) / 2; setDefaultBounds(mainIcon); canvas.translate(drawableX, drawableY); mainIcon.draw(canvas); canvas.translate(-drawableX, -drawableY); // Draw hint icon fully in the key hintIcon.setBounds(0, 0, width, height); hintIcon.draw(canvas); return buffer; } // Layout local language name and left and right arrow on space bar. private static String layoutSpaceBar(Paint paint, Locale locale, Drawable lArrow, Drawable rArrow, int width, int height, float origTextSize, boolean allowVariableTextSize) { final float arrowWidth = lArrow.getIntrinsicWidth(); final float arrowHeight = lArrow.getIntrinsicHeight(); final float maxTextWidth = width - (arrowWidth + arrowWidth); final Rect bounds = new Rect(); // Estimate appropriate language name text size to fit in maxTextWidth. String language = LanguageSwitcher.toTitleCase(locale.getDisplayLanguage(locale)); int textWidth = getTextWidth(paint, language, origTextSize, bounds); // Assuming text width and text size are proportional to each other. float textSize = origTextSize * Math.min(maxTextWidth / textWidth, 1.0f); final boolean useShortName; if (allowVariableTextSize) { textWidth = getTextWidth(paint, language, textSize, bounds); // If text size goes too small or text does not fit, use short name useShortName = textSize / origTextSize < MINIMUM_SCALE_OF_LANGUAGE_NAME || textWidth > maxTextWidth; } else { useShortName = textWidth > maxTextWidth; textSize = origTextSize; } if (useShortName) { language = LanguageSwitcher.toTitleCase(locale.getLanguage()); textWidth = getTextWidth(paint, language, origTextSize, bounds); textSize = origTextSize * Math.min(maxTextWidth / textWidth, 1.0f); } paint.setTextSize(textSize); // Place left and right arrow just before and after language text. final float baseline = height * SPACEBAR_LANGUAGE_BASELINE; final int top = (int)(baseline - arrowHeight); final float remains = (width - textWidth) / 2; lArrow.setBounds((int)(remains - arrowWidth), top, (int)remains, (int)baseline); rArrow.setBounds((int)(remains + textWidth), top, (int)(remains + textWidth + arrowWidth), (int)baseline); return language; } private Bitmap drawSpaceBar(int opacity, boolean isAutoCompletion) { final int width = mSpaceKey.width; final int height = mSpaceIcon.getIntrinsicHeight(); final Bitmap buffer = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); final Canvas canvas = new Canvas(buffer); canvas.drawColor(mRes.getColor(R.color.latinkeyboard_transparent), PorterDuff.Mode.CLEAR); // If application locales are explicitly selected. if (mLocale != null) { final Paint paint = new Paint(); paint.setAlpha(opacity); paint.setAntiAlias(true); paint.setTextAlign(Align.CENTER); final boolean allowVariableTextSize = true; Locale locale = mLanguageSwitcher.getInputLocale(); //Log.i("PCKeyboard", "input locale: " + locale); final String language = layoutSpaceBar(paint, locale, mButtonArrowLeftIcon, mButtonArrowRightIcon, width, height, getTextSizeFromTheme(android.R.style.TextAppearance_Small, 14), allowVariableTextSize); // Draw language text with shadow final int shadowColor = mRes.getColor(R.color.latinkeyboard_bar_language_shadow_white); final float baseline = height * SPACEBAR_LANGUAGE_BASELINE; final float descent = paint.descent(); paint.setColor(shadowColor); canvas.drawText(language, width / 2, baseline - descent - 1, paint); paint.setColor(mRes.getColor(R.color.latinkeyboard_dim_color_white)); canvas.drawText(language, width / 2, baseline - descent, paint); // Put arrows that are already layed out on either side of the text if (mLanguageSwitcher.getLocaleCount() > 1) { mButtonArrowLeftIcon.draw(canvas); mButtonArrowRightIcon.draw(canvas); } } // Draw the spacebar icon at the bottom if (isAutoCompletion) { final int iconWidth = width * SPACE_LED_LENGTH_PERCENT / 100; final int iconHeight = mSpaceAutoCompletionIndicator.getIntrinsicHeight(); int x = (width - iconWidth) / 2; int y = height - iconHeight; mSpaceAutoCompletionIndicator.setBounds(x, y, x + iconWidth, y + iconHeight); mSpaceAutoCompletionIndicator.draw(canvas); } else { final int iconWidth = mSpaceIcon.getIntrinsicWidth(); final int iconHeight = mSpaceIcon.getIntrinsicHeight(); int x = (width - iconWidth) / 2; int y = height - iconHeight; mSpaceIcon.setBounds(x, y, x + iconWidth, y + iconHeight); mSpaceIcon.draw(canvas); } return buffer; } private int getSpacePreviewWidth() { final int width = Math.min( Math.max(mSpaceKey.width, (int)(getMinWidth() * SPACEBAR_POPUP_MIN_RATIO)), (int)(getScreenHeight() * SPACEBAR_POPUP_MAX_RATIO)); return width; } private void updateLocaleDrag(int diff) { if (mSlidingLocaleIcon == null) { final int width = getSpacePreviewWidth(); final int height = mSpacePreviewIcon.getIntrinsicHeight(); mSlidingLocaleIcon = new SlidingLocaleDrawable(mSpacePreviewIcon, width, height); mSlidingLocaleIcon.setBounds(0, 0, width, height); mSpaceKey.iconPreview = mSlidingLocaleIcon; } mSlidingLocaleIcon.setDiff(diff); if (Math.abs(diff) == Integer.MAX_VALUE) { mSpaceKey.iconPreview = mSpacePreviewIcon; } else { mSpaceKey.iconPreview = mSlidingLocaleIcon; } mSpaceKey.iconPreview.invalidateSelf(); } public int getLanguageChangeDirection() { if (mSpaceKey == null || mLanguageSwitcher.getLocaleCount() < 2 || Math.abs(mSpaceDragLastDiff) < getSpacePreviewWidth() * SPACEBAR_DRAG_THRESHOLD) { return 0; // No change } return mSpaceDragLastDiff > 0 ? 1 : -1; } public void setLanguageSwitcher(LanguageSwitcher switcher, boolean isAutoCompletion) { mLanguageSwitcher = switcher; Locale locale = mLanguageSwitcher.getLocaleCount() > 0 ? mLanguageSwitcher.getInputLocale() : null; // If the language count is 1 and is the same as the system language, don't show it. if (locale != null && mLanguageSwitcher.getLocaleCount() == 1 && mLanguageSwitcher.getSystemLocale().getLanguage() .equalsIgnoreCase(locale.getLanguage())) { locale = null; } mLocale = locale; updateSymbolIcons(isAutoCompletion); } boolean isCurrentlyInSpace() { return mCurrentlyInSpace; } void setPreferredLetters(int[] frequencies) { mPrefLetterFrequencies = frequencies; mPrefLetter = 0; } void keyReleased() { mCurrentlyInSpace = false; mSpaceDragLastDiff = 0; mPrefLetter = 0; mPrefLetterX = 0; mPrefLetterY = 0; mPrefDistance = Integer.MAX_VALUE; if (mSpaceKey != null) { updateLocaleDrag(Integer.MAX_VALUE); } } /** * Does the magic of locking the touch gesture into the spacebar when * switching input languages. */ boolean isInside(LatinKey key, int x, int y) { final int code = key.codes[0]; if (code == KEYCODE_SHIFT || code == KEYCODE_DELETE) { // Adjust target area for these keys y -= key.height / 10; if (code == KEYCODE_SHIFT) { if (key.x == 0) { x += key.width / 6; // left shift } else { x -= key.width / 6; // right shift } } if (code == KEYCODE_DELETE) x -= key.width / 6; } else if (code == LatinIME.ASCII_SPACE) { y += LatinKeyboard.sSpacebarVerticalCorrection; if (mLanguageSwitcher.getLocaleCount() > 1) { if (mCurrentlyInSpace) { int diff = x - mSpaceDragStartX; if (Math.abs(diff - mSpaceDragLastDiff) > 0) { updateLocaleDrag(diff); } mSpaceDragLastDiff = diff; return true; } else { boolean insideSpace = key.isInsideSuper(x, y); if (insideSpace) { mCurrentlyInSpace = true; mSpaceDragStartX = x; updateLocaleDrag(0); } return insideSpace; } } } else if (mPrefLetterFrequencies != null) { // New coordinate? Reset if (mPrefLetterX != x || mPrefLetterY != y) { mPrefLetter = 0; mPrefDistance = Integer.MAX_VALUE; } // Handle preferred next letter final int[] pref = mPrefLetterFrequencies; if (mPrefLetter > 0) { if (DEBUG_PREFERRED_LETTER) { if (mPrefLetter == code && !key.isInsideSuper(x, y)) { Log.d(TAG, "CORRECTED !!!!!!"); } } return mPrefLetter == code; } else { final boolean inside = key.isInsideSuper(x, y); int[] nearby = getNearestKeys(x, y); List<Key> nearbyKeys = getKeys(); if (inside) { // If it's a preferred letter if (inPrefList(code, pref)) { // Check if its frequency is much lower than a nearby key mPrefLetter = code; mPrefLetterX = x; mPrefLetterY = y; for (int i = 0; i < nearby.length; i++) { Key k = nearbyKeys.get(nearby[i]); if (k != key && inPrefList(k.codes[0], pref)) { final int dist = distanceFrom(k, x, y); if (dist < (int) (k.width * OVERLAP_PERCENTAGE_LOW_PROB) && (pref[k.codes[0]] > pref[mPrefLetter] * 3)) { mPrefLetter = k.codes[0]; mPrefDistance = dist; if (DEBUG_PREFERRED_LETTER) { Log.d(TAG, "CORRECTED ALTHOUGH PREFERRED !!!!!!"); } break; } } } return mPrefLetter == code; } } // Get the surrounding keys and intersect with the preferred list // For all in the intersection // if distance from touch point is within a reasonable distance // make this the pref letter // If no pref letter // return inside; // else return thiskey == prefletter; for (int i = 0; i < nearby.length; i++) { Key k = nearbyKeys.get(nearby[i]); if (inPrefList(k.codes[0], pref)) { final int dist = distanceFrom(k, x, y); if (dist < (int) (k.width * OVERLAP_PERCENTAGE_HIGH_PROB) && dist < mPrefDistance) { mPrefLetter = k.codes[0]; mPrefLetterX = x; mPrefLetterY = y; mPrefDistance = dist; } } } // Didn't find any if (mPrefLetter == 0) { return inside; } else { return mPrefLetter == code; } } } // Lock into the spacebar if (mCurrentlyInSpace) return false; return key.isInsideSuper(x, y); } private boolean inPrefList(int code, int[] pref) { if (code < pref.length && code >= 0) return pref[code] > 0; return false; } private int distanceFrom(Key k, int x, int y) { if (y > k.y && y < k.y + k.height) { return Math.abs(k.x + k.width / 2 - x); } else { return Integer.MAX_VALUE; } } @Override public int[] getNearestKeys(int x, int y) { if (mCurrentlyInSpace) { return mSpaceKeyIndexArray; } else { // Avoid dead pixels at edges of the keyboard return super.getNearestKeys(Math.max(0, Math.min(x, getMinWidth() - 1)), Math.max(0, Math.min(y, getHeight() - 1))); } } private int indexOf(int code) { List<Key> keys = getKeys(); int count = keys.size(); for (int i = 0; i < count; i++) { if (keys.get(i).codes[0] == code) return i; } return -1; } private int getTextSizeFromTheme(int style, int defValue) { TypedArray array = mContext.getTheme().obtainStyledAttributes( style, new int[] { android.R.attr.textSize }); int resId = array.getResourceId(0, 0); if (resId >= array.length()) { Log.i(TAG, "getTextSizeFromTheme error: resId " + resId + " > " + array.length()); return defValue; } int textSize = array.getDimensionPixelSize(resId, defValue); return textSize; } // TODO LatinKey could be static class class LatinKey extends Key { // functional normal state (with properties) private final int[] KEY_STATE_FUNCTIONAL_NORMAL = { android.R.attr.state_single }; // functional pressed state (with properties) private final int[] KEY_STATE_FUNCTIONAL_PRESSED = { android.R.attr.state_single, android.R.attr.state_pressed }; public LatinKey(Resources res, Keyboard.Row parent, int x, int y, XmlResourceParser parser) { super(res, parent, x, y, parser); } // sticky is used for shift key. If a key is not sticky and is modifier, // the key will be treated as functional. private boolean isFunctionalKey() { return !sticky && modifier; } /** * Overriding this method so that we can reduce the target area for certain keys. */ @Override public boolean isInside(int x, int y) { // TODO This should be done by parent.isInside(this, x, y) // if Key.parent were protected. boolean result = LatinKeyboard.this.isInside(this, x, y); return result; } boolean isInsideSuper(int x, int y) { return super.isInside(x, y); } @Override public int[] getCurrentDrawableState() { if (isFunctionalKey()) { if (pressed) { return KEY_STATE_FUNCTIONAL_PRESSED; } else { return KEY_STATE_FUNCTIONAL_NORMAL; } } return super.getCurrentDrawableState(); } @Override public int squaredDistanceFrom(int x, int y) { // We should count vertical gap between rows to calculate the center of this Key. final int verticalGap = LatinKeyboard.this.mVerticalGap; final int xDist = this.x + width / 2 - x; final int yDist = this.y + (height + verticalGap) / 2 - y; return xDist * xDist + yDist * yDist; } } /** * Animation to be displayed on the spacebar preview popup when switching * languages by swiping the spacebar. It draws the current, previous and * next languages and moves them by the delta of touch movement on the spacebar. */ class SlidingLocaleDrawable extends Drawable { private final int mWidth; private final int mHeight; private final Drawable mBackground; private final TextPaint mTextPaint; private final int mMiddleX; private final Drawable mLeftDrawable; private final Drawable mRightDrawable; private final int mThreshold; private int mDiff; private boolean mHitThreshold; private String mCurrentLanguage; private String mNextLanguage; private String mPrevLanguage; public SlidingLocaleDrawable(Drawable background, int width, int height) { mBackground = background; setDefaultBounds(mBackground); mWidth = width; mHeight = height; mTextPaint = new TextPaint(); mTextPaint.setTextSize(getTextSizeFromTheme(android.R.style.TextAppearance_Medium, 18)); mTextPaint.setColor(R.color.latinkeyboard_transparent); mTextPaint.setTextAlign(Align.CENTER); mTextPaint.setAlpha(OPACITY_FULLY_OPAQUE); mTextPaint.setAntiAlias(true); mMiddleX = (mWidth - mBackground.getIntrinsicWidth()) / 2; mLeftDrawable = mRes.getDrawable(R.drawable.sym_keyboard_feedback_language_arrows_left); mRightDrawable = mRes.getDrawable(R.drawable.sym_keyboard_feedback_language_arrows_right); mThreshold = ViewConfiguration.get(mContext).getScaledTouchSlop(); } private void setDiff(int diff) { if (diff == Integer.MAX_VALUE) { mHitThreshold = false; mCurrentLanguage = null; return; } mDiff = diff; if (mDiff > mWidth) mDiff = mWidth; if (mDiff < -mWidth) mDiff = -mWidth; if (Math.abs(mDiff) > mThreshold) mHitThreshold = true; invalidateSelf(); } private String getLanguageName(Locale locale) { return LanguageSwitcher.toTitleCase(locale.getDisplayLanguage(locale)); } @Override public void draw(Canvas canvas) { canvas.save(); if (mHitThreshold) { Paint paint = mTextPaint; final int width = mWidth; final int height = mHeight; final int diff = mDiff; final Drawable lArrow = mLeftDrawable; final Drawable rArrow = mRightDrawable; canvas.clipRect(0, 0, width, height); if (mCurrentLanguage == null) { final LanguageSwitcher languageSwitcher = mLanguageSwitcher; mCurrentLanguage = getLanguageName(languageSwitcher.getInputLocale()); mNextLanguage = getLanguageName(languageSwitcher.getNextInputLocale()); mPrevLanguage = getLanguageName(languageSwitcher.getPrevInputLocale()); } // Draw language text with shadow final float baseline = mHeight * SPACEBAR_LANGUAGE_BASELINE - paint.descent(); paint.setColor(mRes.getColor(R.color.latinkeyboard_feedback_language_text)); canvas.drawText(mCurrentLanguage, width / 2 + diff, baseline, paint); canvas.drawText(mNextLanguage, diff - width / 2, baseline, paint); canvas.drawText(mPrevLanguage, diff + width + width / 2, baseline, paint); setDefaultBounds(lArrow); rArrow.setBounds(width - rArrow.getIntrinsicWidth(), 0, width, rArrow.getIntrinsicHeight()); lArrow.draw(canvas); rArrow.draw(canvas); } if (mBackground != null) { canvas.translate(mMiddleX, 0); mBackground.draw(canvas); } canvas.restore(); } @Override public int getOpacity() { return PixelFormat.TRANSLUCENT; } @Override public void setAlpha(int alpha) { // Ignore } @Override public void setColorFilter(ColorFilter cf) { // Ignore } @Override public int getIntrinsicWidth() { return mWidth; } @Override public int getIntrinsicHeight() { return mHeight; } } }
Java
/* * Copyright (C) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.pocketworkstation.pckeyboard; import org.pocketworkstation.pckeyboard.Keyboard.Key; import java.util.Arrays; import java.util.List; abstract class KeyDetector { protected Keyboard mKeyboard; private Key[] mKeys; protected int mCorrectionX; protected int mCorrectionY; protected boolean mProximityCorrectOn; protected int mProximityThresholdSquare; public Key[] setKeyboard(Keyboard keyboard, float correctionX, float correctionY) { if (keyboard == null) throw new NullPointerException(); mCorrectionX = (int)correctionX; mCorrectionY = (int)correctionY; mKeyboard = keyboard; List<Key> keys = mKeyboard.getKeys(); Key[] array = keys.toArray(new Key[keys.size()]); mKeys = array; return array; } protected int getTouchX(int x) { return x + mCorrectionX; } protected int getTouchY(int y) { return y + mCorrectionY; } protected Key[] getKeys() { if (mKeys == null) throw new IllegalStateException("keyboard isn't set"); // mKeyboard is guaranteed not to be null at setKeybaord() method if mKeys is not null return mKeys; } public void setProximityCorrectionEnabled(boolean enabled) { mProximityCorrectOn = enabled; } public boolean isProximityCorrectionEnabled() { return mProximityCorrectOn; } public void setProximityThreshold(int threshold) { mProximityThresholdSquare = threshold * threshold; } /** * Allocates array that can hold all key indices returned by {@link #getKeyIndexAndNearbyCodes} * method. The maximum size of the array should be computed by {@link #getMaxNearbyKeys}. * * @return Allocates and returns an array that can hold all key indices returned by * {@link #getKeyIndexAndNearbyCodes} method. All elements in the returned array are * initialized by {@link org.pocketworkstation.pckeyboard.LatinKeyboardView.NOT_A_KEY} * value. */ public int[] newCodeArray() { int[] codes = new int[getMaxNearbyKeys()]; Arrays.fill(codes, LatinKeyboardBaseView.NOT_A_KEY); return codes; } /** * Computes maximum size of the array that can contain all nearby key indices returned by * {@link #getKeyIndexAndNearbyCodes}. * * @return Returns maximum size of the array that can contain all nearby key indices returned * by {@link #getKeyIndexAndNearbyCodes}. */ abstract protected int getMaxNearbyKeys(); /** * Finds all possible nearby key indices around a touch event point and returns the nearest key * index. The algorithm to determine the nearby keys depends on the threshold set by * {@link #setProximityThreshold(int)} and the mode set by * {@link #setProximityCorrectionEnabled(boolean)}. * * @param x The x-coordinate of a touch point * @param y The y-coordinate of a touch point * @param allKeys All nearby key indices are returned in this array * @return The nearest key index */ abstract public int getKeyIndexAndNearbyCodes(int x, int y, int[] allKeys); }
Java
/* * Copyright (C) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.pocketworkstation.pckeyboard; class ModifierKeyState { private static final int RELEASING = 0; private static final int PRESSING = 1; private static final int MOMENTARY = 2; private int mState = RELEASING; public void onPress() { mState = PRESSING; } public void onRelease() { mState = RELEASING; } public void onOtherKeyPressed() { if (mState == PRESSING) mState = MOMENTARY; } public boolean isMomentary() { return mState == MOMENTARY; } public String toString() { return "ModifierKeyState:" + mState; } }
Java
/* * Copyright (C) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.pocketworkstation.pckeyboard; import java.util.ArrayList; import java.util.List; import org.pocketworkstation.pckeyboard.LatinKeyboardBaseView.OnKeyboardActionListener; import org.pocketworkstation.pckeyboard.LatinKeyboardBaseView.UIHandler; import android.content.res.Resources; import org.pocketworkstation.pckeyboard.Keyboard.Key; import android.util.Log; import android.view.MotionEvent; public class PointerTracker { private static final String TAG = "PointerTracker"; private static final boolean DEBUG = false; private static final boolean DEBUG_MOVE = false; public interface UIProxy { public void invalidateKey(Key key); public void showPreview(int keyIndex, PointerTracker tracker); public boolean hasDistinctMultitouch(); } public final int mPointerId; // Timing constants private final int mDelayBeforeKeyRepeatStart; private final int mMultiTapKeyTimeout; // Miscellaneous constants private static final int NOT_A_KEY = LatinKeyboardBaseView.NOT_A_KEY; private static final int[] KEY_DELETE = { Keyboard.KEYCODE_DELETE }; private final UIProxy mProxy; private final UIHandler mHandler; private final KeyDetector mKeyDetector; private OnKeyboardActionListener mListener; private final KeyboardSwitcher mKeyboardSwitcher; private final boolean mHasDistinctMultitouch; private Key[] mKeys; private int mKeyHysteresisDistanceSquared = -1; private final KeyState mKeyState; // true if keyboard layout has been changed. private boolean mKeyboardLayoutHasBeenChanged; // true if event is already translated to a key action (long press or mini-keyboard) private boolean mKeyAlreadyProcessed; // true if this pointer is repeatable key private boolean mIsRepeatableKey; // true if this pointer is in sliding key input private boolean mIsInSlidingKeyInput; // For multi-tap private int mLastSentIndex; private int mTapCount; private long mLastTapTime; private boolean mInMultiTap; private final StringBuilder mPreviewLabel = new StringBuilder(1); // pressed key private int mPreviousKey = NOT_A_KEY; private static boolean sSlideKeyHack; private static List<Key> sSlideKeys = new ArrayList<Key>(10); // This class keeps track of a key index and a position where this pointer is. private static class KeyState { private final KeyDetector mKeyDetector; // The position and time at which first down event occurred. private int mStartX; private int mStartY; private long mDownTime; // The current key index where this pointer is. private int mKeyIndex = NOT_A_KEY; // The position where mKeyIndex was recognized for the first time. private int mKeyX; private int mKeyY; // Last pointer position. private int mLastX; private int mLastY; public KeyState(KeyDetector keyDetecor) { mKeyDetector = keyDetecor; } public int getKeyIndex() { return mKeyIndex; } public int getKeyX() { return mKeyX; } public int getKeyY() { return mKeyY; } public int getStartX() { return mStartX; } public int getStartY() { return mStartY; } public long getDownTime() { return mDownTime; } public int getLastX() { return mLastX; } public int getLastY() { return mLastY; } public int onDownKey(int x, int y, long eventTime) { mStartX = x; mStartY = y; mDownTime = eventTime; return onMoveToNewKey(onMoveKeyInternal(x, y), x, y); } private int onMoveKeyInternal(int x, int y) { mLastX = x; mLastY = y; return mKeyDetector.getKeyIndexAndNearbyCodes(x, y, null); } public int onMoveKey(int x, int y) { return onMoveKeyInternal(x, y); } public int onMoveToNewKey(int keyIndex, int x, int y) { mKeyIndex = keyIndex; mKeyX = x; mKeyY = y; return keyIndex; } public int onUpKey(int x, int y) { return onMoveKeyInternal(x, y); } } public PointerTracker(int id, UIHandler handler, KeyDetector keyDetector, UIProxy proxy, Resources res, boolean slideKeyHack) { if (proxy == null || handler == null || keyDetector == null) throw new NullPointerException(); mPointerId = id; mProxy = proxy; mHandler = handler; mKeyDetector = keyDetector; mKeyboardSwitcher = KeyboardSwitcher.getInstance(); mKeyState = new KeyState(keyDetector); mHasDistinctMultitouch = proxy.hasDistinctMultitouch(); mDelayBeforeKeyRepeatStart = res.getInteger(R.integer.config_delay_before_key_repeat_start); mMultiTapKeyTimeout = res.getInteger(R.integer.config_multi_tap_key_timeout); sSlideKeyHack = slideKeyHack; resetMultiTap(); } public void setOnKeyboardActionListener(OnKeyboardActionListener listener) { mListener = listener; } public void setKeyboard(Key[] keys, float keyHysteresisDistance) { if (keys == null || keyHysteresisDistance < 0) throw new IllegalArgumentException(); mKeys = keys; mKeyHysteresisDistanceSquared = (int)(keyHysteresisDistance * keyHysteresisDistance); // Mark that keyboard layout has been changed. mKeyboardLayoutHasBeenChanged = true; } public boolean isInSlidingKeyInput() { return mIsInSlidingKeyInput; } public void setSlidingKeyInputState(boolean state) { mIsInSlidingKeyInput = state; } private boolean isValidKeyIndex(int keyIndex) { return keyIndex >= 0 && keyIndex < mKeys.length; } public Key getKey(int keyIndex) { return isValidKeyIndex(keyIndex) ? mKeys[keyIndex] : null; } private boolean isModifierInternal(int keyIndex) { Key key = getKey(keyIndex); if (key == null || key.codes == null) return false; int primaryCode = key.codes[0]; return primaryCode == Keyboard.KEYCODE_SHIFT || primaryCode == Keyboard.KEYCODE_MODE_CHANGE || primaryCode == LatinKeyboardView.KEYCODE_CTRL_LEFT || primaryCode == LatinKeyboardView.KEYCODE_ALT_LEFT || primaryCode == LatinKeyboardView.KEYCODE_FN; } public boolean isModifier() { return isModifierInternal(mKeyState.getKeyIndex()); } public boolean isOnModifierKey(int x, int y) { return isModifierInternal(mKeyDetector.getKeyIndexAndNearbyCodes(x, y, null)); } public boolean isSpaceKey(int keyIndex) { Key key = getKey(keyIndex); return key != null && key.codes != null && key.codes[0] == LatinIME.ASCII_SPACE; } public void updateKey(int keyIndex) { if (mKeyAlreadyProcessed) return; int oldKeyIndex = mPreviousKey; mPreviousKey = keyIndex; if (keyIndex != oldKeyIndex) { if (isValidKeyIndex(oldKeyIndex)) { // if new key index is not a key, old key was just released inside of the key. final boolean inside = (keyIndex == NOT_A_KEY); mKeys[oldKeyIndex].onReleased(inside); mProxy.invalidateKey(mKeys[oldKeyIndex]); } if (isValidKeyIndex(keyIndex)) { mKeys[keyIndex].onPressed(); mProxy.invalidateKey(mKeys[keyIndex]); } } } public void setAlreadyProcessed() { mKeyAlreadyProcessed = true; } public void onTouchEvent(int action, int x, int y, long eventTime) { switch (action) { case MotionEvent.ACTION_MOVE: onMoveEvent(x, y, eventTime); break; case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_POINTER_DOWN: onDownEvent(x, y, eventTime); break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_POINTER_UP: onUpEvent(x, y, eventTime); break; case MotionEvent.ACTION_CANCEL: onCancelEvent(x, y, eventTime); break; } } public void onDownEvent(int x, int y, long eventTime) { if (DEBUG) debugLog("onDownEvent:", x, y); int keyIndex = mKeyState.onDownKey(x, y, eventTime); mKeyboardLayoutHasBeenChanged = false; mKeyAlreadyProcessed = false; mIsRepeatableKey = false; mIsInSlidingKeyInput = false; checkMultiTap(eventTime, keyIndex); if (mListener != null) { if (isValidKeyIndex(keyIndex)) { Key key = mKeys[keyIndex]; if (key.codes != null) mListener.onPress(key.getPrimaryCode()); // This onPress call may have changed keyboard layout. Those cases are detected at // {@link #setKeyboard}. In those cases, we should update keyIndex according to the // new keyboard layout. if (mKeyboardLayoutHasBeenChanged) { mKeyboardLayoutHasBeenChanged = false; keyIndex = mKeyState.onDownKey(x, y, eventTime); } } } if (isValidKeyIndex(keyIndex)) { if (mKeys[keyIndex].repeatable) { repeatKey(keyIndex); mHandler.startKeyRepeatTimer(mDelayBeforeKeyRepeatStart, keyIndex, this); mIsRepeatableKey = true; } startLongPressTimer(keyIndex); } showKeyPreviewAndUpdateKey(keyIndex); } private static void addSlideKey(Key key) { if (!sSlideKeyHack || LatinIME.sKeyboardSettings.sendSlideKeys == 0) return; if (key == null) return; if (key.modifier) { clearSlideKeys(); } else { sSlideKeys.add(key); } } /*package*/ static void clearSlideKeys() { sSlideKeys.clear(); } void sendSlideKeys() { if (!sSlideKeyHack) return; int slideMode = LatinIME.sKeyboardSettings.sendSlideKeys; if ((slideMode & 4) > 0) { // send all for (Key key : sSlideKeys) { detectAndSendKey(key, key.x, key.y, -1); } } else { // Send first and/or last key only. int n = sSlideKeys.size(); if (n > 0 && (slideMode & 1) > 0) { Key key = sSlideKeys.get(0); detectAndSendKey(key, key.x, key.y, -1); } if (n > 1 && (slideMode & 2) > 0) { Key key = sSlideKeys.get(n - 1); detectAndSendKey(key, key.x, key.y, -1); } } clearSlideKeys(); } public void onMoveEvent(int x, int y, long eventTime) { if (DEBUG_MOVE) debugLog("onMoveEvent:", x, y); if (mKeyAlreadyProcessed) return; final KeyState keyState = mKeyState; int keyIndex = keyState.onMoveKey(x, y); final Key oldKey = getKey(keyState.getKeyIndex()); if (isValidKeyIndex(keyIndex)) { boolean isMinorMoveBounce = isMinorMoveBounce(x, y, keyIndex); if (DEBUG_MOVE) Log.i(TAG, "isMinorMoveBounce=" +isMinorMoveBounce + " oldKey=" + (oldKey== null ? "null" : oldKey)); if (oldKey == null) { // The pointer has been slid in to the new key, but the finger was not on any keys. // In this case, we must call onPress() to notify that the new key is being pressed. if (mListener != null) { Key key = getKey(keyIndex); if (key.codes != null) mListener.onPress(key.getPrimaryCode()); // This onPress call may have changed keyboard layout. Those cases are detected // at {@link #setKeyboard}. In those cases, we should update keyIndex according // to the new keyboard layout. if (mKeyboardLayoutHasBeenChanged) { mKeyboardLayoutHasBeenChanged = false; keyIndex = keyState.onMoveKey(x, y); } } keyState.onMoveToNewKey(keyIndex, x, y); startLongPressTimer(keyIndex); } else if (!isMinorMoveBounce) { // The pointer has been slid in to the new key from the previous key, we must call // onRelease() first to notify that the previous key has been released, then call // onPress() to notify that the new key is being pressed. mIsInSlidingKeyInput = true; if (mListener != null && oldKey.codes != null) mListener.onRelease(oldKey.getPrimaryCode()); resetMultiTap(); if (mListener != null) { Key key = getKey(keyIndex); if (key.codes != null) mListener.onPress(key.getPrimaryCode()); // This onPress call may have changed keyboard layout. Those cases are detected // at {@link #setKeyboard}. In those cases, we should update keyIndex according // to the new keyboard layout. if (mKeyboardLayoutHasBeenChanged) { mKeyboardLayoutHasBeenChanged = false; keyIndex = keyState.onMoveKey(x, y); } addSlideKey(oldKey); } keyState.onMoveToNewKey(keyIndex, x, y); startLongPressTimer(keyIndex); } } else { if (oldKey != null && !isMinorMoveBounce(x, y, keyIndex)) { // The pointer has been slid out from the previous key, we must call onRelease() to // notify that the previous key has been released. mIsInSlidingKeyInput = true; if (mListener != null && oldKey.codes != null) mListener.onRelease(oldKey.getPrimaryCode()); resetMultiTap(); keyState.onMoveToNewKey(keyIndex, x ,y); mHandler.cancelLongPressTimer(); } } showKeyPreviewAndUpdateKey(keyState.getKeyIndex()); } public void onUpEvent(int x, int y, long eventTime) { if (DEBUG) debugLog("onUpEvent :", x, y); mHandler.cancelKeyTimers(); mHandler.cancelPopupPreview(); showKeyPreviewAndUpdateKey(NOT_A_KEY); mIsInSlidingKeyInput = false; sendSlideKeys(); if (mKeyAlreadyProcessed) return; int keyIndex = mKeyState.onUpKey(x, y); if (isMinorMoveBounce(x, y, keyIndex)) { // Use previous fixed key index and coordinates. keyIndex = mKeyState.getKeyIndex(); x = mKeyState.getKeyX(); y = mKeyState.getKeyY(); } if (!mIsRepeatableKey) { detectAndSendKey(keyIndex, x, y, eventTime); } if (isValidKeyIndex(keyIndex)) mProxy.invalidateKey(mKeys[keyIndex]); } public void onCancelEvent(int x, int y, long eventTime) { if (DEBUG) debugLog("onCancelEvt:", x, y); mHandler.cancelKeyTimers(); mHandler.cancelPopupPreview(); showKeyPreviewAndUpdateKey(NOT_A_KEY); mIsInSlidingKeyInput = false; int keyIndex = mKeyState.getKeyIndex(); if (isValidKeyIndex(keyIndex)) mProxy.invalidateKey(mKeys[keyIndex]); } public void repeatKey(int keyIndex) { Key key = getKey(keyIndex); if (key != null) { // While key is repeating, because there is no need to handle multi-tap key, we can // pass -1 as eventTime argument. detectAndSendKey(keyIndex, key.x, key.y, -1); } } public int getLastX() { return mKeyState.getLastX(); } public int getLastY() { return mKeyState.getLastY(); } public long getDownTime() { return mKeyState.getDownTime(); } // These package scope methods are only for debugging purpose. /* package */ int getStartX() { return mKeyState.getStartX(); } /* package */ int getStartY() { return mKeyState.getStartY(); } private boolean isMinorMoveBounce(int x, int y, int newKey) { if (mKeys == null || mKeyHysteresisDistanceSquared < 0) throw new IllegalStateException("keyboard and/or hysteresis not set"); int curKey = mKeyState.getKeyIndex(); if (newKey == curKey) { return true; } else if (isValidKeyIndex(curKey)) { //return false; // TODO(klausw): tweak this? return getSquareDistanceToKeyEdge(x, y, mKeys[curKey]) < mKeyHysteresisDistanceSquared; } else { return false; } } private static int getSquareDistanceToKeyEdge(int x, int y, Key key) { final int left = key.x; final int right = key.x + key.width; final int top = key.y; final int bottom = key.y + key.height; final int edgeX = x < left ? left : (x > right ? right : x); final int edgeY = y < top ? top : (y > bottom ? bottom : y); final int dx = x - edgeX; final int dy = y - edgeY; return dx * dx + dy * dy; } private void showKeyPreviewAndUpdateKey(int keyIndex) { updateKey(keyIndex); // The modifier key, such as shift key, should not be shown as preview when multi-touch is // supported. On the other hand, if multi-touch is not supported, the modifier key should // be shown as preview. if (mHasDistinctMultitouch && isModifier()) { mProxy.showPreview(NOT_A_KEY, this); } else { mProxy.showPreview(keyIndex, this); } } private void startLongPressTimer(int keyIndex) { if (mKeyboardSwitcher.isInMomentaryAutoModeSwitchState()) { // We use longer timeout for sliding finger input started from the symbols mode key. mHandler.startLongPressTimer(LatinIME.sKeyboardSettings.longpressTimeout * 3, keyIndex, this); } else { mHandler.startLongPressTimer(LatinIME.sKeyboardSettings.longpressTimeout, keyIndex, this); } } private void detectAndSendKey(int index, int x, int y, long eventTime) { detectAndSendKey(getKey(index), x, y, eventTime); mLastSentIndex = index; } private void detectAndSendKey(Key key, int x, int y, long eventTime) { final OnKeyboardActionListener listener = mListener; if (key == null) { if (listener != null) listener.onCancel(); } else { if (key.text != null) { if (listener != null) { listener.onText(key.text); listener.onRelease(0); // dummy key code } } else { if (key.codes == null) return; int code = key.getPrimaryCode(); int[] codes = mKeyDetector.newCodeArray(); mKeyDetector.getKeyIndexAndNearbyCodes(x, y, codes); // Multi-tap if (mInMultiTap) { if (mTapCount != -1) { mListener.onKey(Keyboard.KEYCODE_DELETE, KEY_DELETE, x, y); } else { mTapCount = 0; } code = key.codes[mTapCount]; } /* * Swap the first and second values in the codes array if the primary code is not * the first value but the second value in the array. This happens when key * debouncing is in effect. */ if (codes.length >= 2 && codes[0] != code && codes[1] == code) { codes[1] = codes[0]; codes[0] = code; } if (listener != null) { listener.onKey(code, codes, x, y); listener.onRelease(code); } } mLastTapTime = eventTime; } } /** * Handle multi-tap keys by producing the key label for the current multi-tap state. */ public CharSequence getPreviewText(Key key) { if (mInMultiTap) { // Multi-tap mPreviewLabel.setLength(0); mPreviewLabel.append((char) key.codes[mTapCount < 0 ? 0 : mTapCount]); return mPreviewLabel; } else { if (key.isDeadKey()) { return DeadAccentSequence.normalize(" " + key.label); } else { return key.label; } } } private void resetMultiTap() { mLastSentIndex = NOT_A_KEY; mTapCount = 0; mLastTapTime = -1; mInMultiTap = false; } private void checkMultiTap(long eventTime, int keyIndex) { Key key = getKey(keyIndex); if (key == null || key.codes == null) return; final boolean isMultiTap = (eventTime < mLastTapTime + mMultiTapKeyTimeout && keyIndex == mLastSentIndex); if (key.codes.length > 1) { mInMultiTap = true; if (isMultiTap) { mTapCount = (mTapCount + 1) % key.codes.length; return; } else { mTapCount = -1; return; } } if (!isMultiTap) { resetMultiTap(); } } private void debugLog(String title, int x, int y) { int keyIndex = mKeyDetector.getKeyIndexAndNearbyCodes(x, y, null); Key key = getKey(keyIndex); final String code; if (key == null || key.codes == null) { code = "----"; } else { int primaryCode = key.codes[0]; code = String.format((primaryCode < 0) ? "%4d" : "0x%02x", primaryCode); } Log.d(TAG, String.format("%s%s[%d] %3d,%3d %3d(%s) %s", title, (mKeyAlreadyProcessed ? "-" : " "), mPointerId, x, y, keyIndex, code, (isModifier() ? "modifier" : ""))); } }
Java
/* * Copyright (C) 2011 Darren Salt * * Licensed under the Apache License, Version 2.0 (the "Licence"); you may * not use this file except in compliance with the Licence. You may obtain * a copy of the Licence at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the Licence is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * Licence for the specific language governing permissions and limitations * under the Licence. */ package org.pocketworkstation.pckeyboard; import java.text.Normalizer; import android.util.Log; public class DeadAccentSequence extends ComposeBase { private static final String TAG = "HK/DeadAccent"; public DeadAccentSequence(ComposeSequencing user) { init(user); } private static void putAccent(String nonSpacing, String spacing, String ascii) { if (ascii == null) ascii = spacing; put("" + nonSpacing + " ", ascii); put(nonSpacing + nonSpacing, spacing); put(Keyboard.DEAD_KEY_PLACEHOLDER + nonSpacing, spacing); } public static String getSpacing(char nonSpacing) { String spacing = get("" + Keyboard.DEAD_KEY_PLACEHOLDER + nonSpacing); if (spacing == null) spacing = DeadAccentSequence.normalize(" " + nonSpacing); if (spacing == null) return "" + nonSpacing; return spacing; } static { // space + combining diacritical // cf. http://unicode.org/charts/PDF/U0300.pdf putAccent("\u0300", "\u02cb", "`"); // grave putAccent("\u0301", "\u02ca", "´"); // acute putAccent("\u0302", "\u02c6", "^"); // circumflex putAccent("\u0303", "\u02dc", "~"); // small tilde putAccent("\u0304", "\u02c9", "¯"); // macron putAccent("\u0305", "\u00af", "¯"); // overline putAccent("\u0306", "\u02d8", null); // breve putAccent("\u0307", "\u02d9", null); // dot above putAccent("\u0308", "\u00a8", "¨"); // diaeresis putAccent("\u0309", "\u02c0", null); // hook above putAccent("\u030a", "\u02da", "°"); // ring above putAccent("\u030b", "\u02dd", "\""); // double acute putAccent("\u030c", "\u02c7", null); // caron putAccent("\u030d", "\u02c8", null); // vertical line above putAccent("\u030e", "\"", "\""); // double vertical line above putAccent("\u0313", "\u02bc", null); // comma above putAccent("\u0314", "\u02bd", null); // reversed comma above put("\u0308\u0301\u03b9", "\u0390"); // Greek Dialytika+Tonos, iota put("\u0301\u0308\u03b9", "\u0390"); // Greek Dialytika+Tonos, iota put("\u0301\u03ca", "\u0390"); // Greek Dialytika+Tonos, iota put("\u0308\u0301\u03c5", "\u03b0"); // Greek Dialytika+Tonos, upsilon put("\u0301\u0308\u03c5", "\u03b0"); // Greek Dialytika+Tonos, upsilon put("\u0301\u03cb", "\u03b0"); // Greek Dialytika+Tonos, upsilon /* // include? put("̃ ", "~"); put("̃̃", "~"); put("́ ", "'"); put("́́", "´"); put("̀ ", "`"); put("̀̀", "`"); put("̂ ", "^"); put("̂̂", "^"); put("̊ ", "°"); put("̊̊", "°"); put("̄ ", "¯"); put("̄̄", "¯"); put("̆ ", "˘"); put("̆̆", "˘"); put("̇ ", "˙"); put("̇̇", "˙"); put("̈̈", "¨"); put("̈ ", "\""); put("̋ ", "˝"); put("̋̋", "˝"); put("̌ ", "ˇ"); put("̌̌", "ˇ"); put("̧ ", "¸"); put("̧̧", "¸"); put("̨ ", "˛"); put("̨̨", "˛"); put("̂2", "²"); put("̂3", "³"); put("̂1", "¹"); // include end? put("̀A", "À"); put("́A", "Á"); put("̂A", "Â"); put("̃A", "Ã"); put("̈A", "Ä"); put("̊A", "Å"); put("̧C", "Ç"); put("̀E", "È"); put("́E", "É"); put("̂E", "Ê"); put("̈E", "Ë"); put("̀I", "Ì"); put("́I", "Í"); put("̂I", "Î"); put("̈I", "Ï"); put("̃N", "Ñ"); put("̀O", "Ò"); put("́O", "Ó"); put("̂O", "Ô"); put("̃O", "Õ"); put("̈O", "Ö"); put("̀U", "Ù"); put("́U", "Ú"); put("̂U", "Û"); put("̈U", "Ü"); put("́Y", "Ý"); put("̀a", "à"); put("́a", "á"); put("̂a", "â"); put("̃a", "ã"); put("̈a", "ä"); put("̊a", "å"); put("̧c", "ç"); put("̀e", "è"); put("́e", "é"); put("̂e", "ê"); put("̈e", "ë"); put("̀i", "ì"); put("́i", "í"); put("̂i", "î"); put("̈i", "ï"); put("̃n", "ñ"); put("̀o", "ò"); put("́o", "ó"); put("̂o", "ô"); put("̃o", "õ"); put("̈o", "ö"); put("̀u", "ù"); put("́u", "ú"); put("̂u", "û"); put("̈u", "ü"); put("́y", "ý"); put("̈y", "ÿ"); put("̄A", "Ā"); put("̄a", "ā"); put("̆A", "Ă"); put("̆a", "ă"); put("̨A", "Ą"); put("̨a", "ą"); put("́C", "Ć"); put("́c", "ć"); put("̂C", "Ĉ"); put("̂c", "ĉ"); put("̇C", "Ċ"); put("̇c", "ċ"); put("̌C", "Č"); put("̌c", "č"); put("̌D", "Ď"); put("̌d", "ď"); put("̄E", "Ē"); put("̄e", "ē"); put("̆E", "Ĕ"); put("̆e", "ĕ"); put("̇E", "Ė"); put("̇e", "ė"); put("̨E", "Ę"); put("̨e", "ę"); put("̌E", "Ě"); put("̌e", "ě"); put("̂G", "Ĝ"); put("̂g", "ĝ"); put("̆G", "Ğ"); put("̆g", "ğ"); put("̇G", "Ġ"); put("̇g", "ġ"); put("̧G", "Ģ"); put("̧g", "ģ"); put("̂H", "Ĥ"); put("̂h", "ĥ"); put("̃I", "Ĩ"); put("̃i", "ĩ"); put("̄I", "Ī"); put("̄i", "ī"); put("̆I", "Ĭ"); put("̆i", "ĭ"); put("̨I", "Į"); put("̨i", "į"); put("̇I", "İ"); put("̇i", "ı"); put("̂J", "Ĵ"); put("̂j", "ĵ"); put("̧K", "Ķ"); put("̧k", "ķ"); put("́L", "Ĺ"); put("́l", "ĺ"); put("̧L", "Ļ"); put("̧l", "ļ"); put("̌L", "Ľ"); put("̌l", "ľ"); put("́N", "Ń"); put("́n", "ń"); put("̧N", "Ņ"); put("̧n", "ņ"); put("̌N", "Ň"); put("̌n", "ň"); put("̄O", "Ō"); put("̄o", "ō"); put("̆O", "Ŏ"); put("̆o", "ŏ"); put("̋O", "Ő"); put("̋o", "ő"); put("́R", "Ŕ"); put("́r", "ŕ"); put("̧R", "Ŗ"); put("̧r", "ŗ"); put("̌R", "Ř"); put("̌r", "ř"); put("́S", "Ś"); put("́s", "ś"); put("̂S", "Ŝ"); put("̂s", "ŝ"); put("̧S", "Ş"); put("̧s", "ş"); put("̌S", "Š"); put("̌s", "š"); put("̧T", "Ţ"); put("̧t", "ţ"); put("̌T", "Ť"); put("̌t", "ť"); put("̃U", "Ũ"); put("̃u", "ũ"); put("̄U", "Ū"); put("̄u", "ū"); put("̆U", "Ŭ"); put("̆u", "ŭ"); put("̊U", "Ů"); put("̊u", "ů"); put("̋U", "Ű"); put("̋u", "ű"); put("̨U", "Ų"); put("̨u", "ų"); put("̂W", "Ŵ"); put("̂w", "ŵ"); put("̂Y", "Ŷ"); put("̂y", "ŷ"); put("̈Y", "Ÿ"); put("́Z", "Ź"); put("́z", "ź"); put("̇Z", "Ż"); put("̇z", "ż"); put("̌Z", "Ž"); put("̌z", "ž"); put("̛O", "Ơ"); put("̛o", "ơ"); put("̛U", "Ư"); put("̛u", "ư"); put("̌A", "Ǎ"); put("̌a", "ǎ"); put("̌I", "Ǐ"); put("̌i", "ǐ"); put("̌O", "Ǒ"); put("̌o", "ǒ"); put("̌U", "Ǔ"); put("̌u", "ǔ"); put("̄Ü", "Ǖ"); put("̄̈U", "Ǖ"); put("̄ü", "ǖ"); put("̄̈u", "ǖ"); put("́Ü", "Ǘ"); put("́̈U", "Ǘ"); put("́ü", "ǘ"); put("́̈u", "ǘ"); put("̌Ü", "Ǚ"); put("̌̈U", "Ǚ"); put("̌ü", "ǚ"); put("̌̈u", "ǚ"); put("̀Ü", "Ǜ"); put("̀̈U", "Ǜ"); put("̀ü", "ǜ"); put("̀̈u", "ǜ"); put("̄Ä", "Ǟ"); put("̄̈A", "Ǟ"); put("̄ä", "ǟ"); put("̄̈a", "ǟ"); put("̄Ȧ", "Ǡ"); put("̄̇A", "Ǡ"); put("̄ȧ", "ǡ"); put("̄̇a", "ǡ"); put("̄Æ", "Ǣ"); put("̄æ", "ǣ"); put("̌G", "Ǧ"); put("̌g", "ǧ"); put("̌K", "Ǩ"); put("̌k", "ǩ"); put("̨O", "Ǫ"); put("̨o", "ǫ"); put("̄Ǫ", "Ǭ"); put("̨̄O", "Ǭ"); put("̄ǫ", "ǭ"); put("̨̄o", "ǭ"); put("̌Ʒ", "Ǯ"); put("̌ʒ", "ǯ"); put("̌j", "ǰ"); put("́G", "Ǵ"); put("́g", "ǵ"); put("̀N", "Ǹ"); put("̀n", "ǹ"); put("́Å", "Ǻ"); put("́̊A", "Ǻ"); put("́å", "ǻ"); put("́̊a", "ǻ"); put("́Æ", "Ǽ"); put("́æ", "ǽ"); put("́Ø", "Ǿ"); put("́ø", "ǿ"); put("̏A", "Ȁ"); put("̏a", "ȁ"); put("̑A", "Ȃ"); put("̑a", "ȃ"); put("̏E", "Ȅ"); put("̏e", "ȅ"); put("̑E", "Ȇ"); put("̑e", "ȇ"); put("̏I", "Ȉ"); put("̏i", "ȉ"); put("̑I", "Ȋ"); put("̑i", "ȋ"); put("̏O", "Ȍ"); put("̏o", "ȍ"); put("̑O", "Ȏ"); put("̑o", "ȏ"); put("̏R", "Ȑ"); put("̏r", "ȑ"); put("̑R", "Ȓ"); put("̑r", "ȓ"); put("̏U", "Ȕ"); put("̏u", "ȕ"); put("̑U", "Ȗ"); put("̑u", "ȗ"); put("̌H", "Ȟ"); put("̌h", "ȟ"); put("̇A", "Ȧ"); put("̇a", "ȧ"); put("̧E", "Ȩ"); put("̧e", "ȩ"); put("̄Ö", "Ȫ"); put("̄̈O", "Ȫ"); put("̄ö", "ȫ"); put("̄̈o", "ȫ"); put("̄Õ", "Ȭ"); put("̄ ̃O", "Ȭ"); put("̄õ", "ȭ"); put("̄ ̃o", "ȭ"); put("̇O", "Ȯ"); put("̇o", "ȯ"); put("̄Ȯ", "Ȱ"); put("̄̇O", "Ȱ"); put("̄ȯ", "ȱ"); put("̄̇o", "ȱ"); put("̄Y", "Ȳ"); put("̄y", "ȳ"); put("̥A", "Ḁ"); put("̥a", "ḁ"); put("̇B", "Ḃ"); put("̇b", "ḃ"); put("̣B", "Ḅ"); put("̣b", "ḅ"); put("̱B", "Ḇ"); put("̱b", "ḇ"); put("́Ç", "Ḉ"); put("̧́C", "Ḉ"); put("́ç", "ḉ"); put("̧́c", "ḉ"); put("̇D", "Ḋ"); put("̇d", "ḋ"); put("̣D", "Ḍ"); put("̣d", "ḍ"); put("̱D", "Ḏ"); put("̱d", "ḏ"); put("̧D", "Ḑ"); put("̧d", "ḑ"); put("̭D", "Ḓ"); put("̭d", "ḓ"); put("̀Ē", "Ḕ"); put("̀ ̄E", "Ḕ"); put("̀ē", "ḕ"); put("̀ ̄e", "ḕ"); put("́Ē", "Ḗ"); put("́ ̄E", "Ḗ"); put("́ē", "ḗ"); put("́ ̄e", "ḗ"); put("̭E", "Ḙ"); put("̭e", "ḙ"); put("̰E", "Ḛ"); put("̰e", "ḛ"); put("̆Ȩ", "Ḝ"); put("̧̆E", "Ḝ"); put("̆ȩ", "ḝ"); put("̧̆e", "ḝ"); put("̇F", "Ḟ"); put("̇f", "ḟ"); put("̄G", "Ḡ"); put("̄g", "ḡ"); put("̇H", "Ḣ"); put("̇h", "ḣ"); put("̣H", "Ḥ"); put("̣h", "ḥ"); put("̈H", "Ḧ"); put("̈h", "ḧ"); put("̧H", "Ḩ"); put("̧h", "ḩ"); put("̮H", "Ḫ"); put("̮h", "ḫ"); put("̰I", "Ḭ"); put("̰i", "ḭ"); put("́Ï", "Ḯ"); put("́̈I", "Ḯ"); put("́ï", "ḯ"); put("́̈i", "ḯ"); put("́K", "Ḱ"); put("́k", "ḱ"); put("̣K", "Ḳ"); put("̣k", "ḳ"); put("̱K", "Ḵ"); put("̱k", "ḵ"); put("̣L", "Ḷ"); put("̣l", "ḷ"); put("̄Ḷ", "Ḹ"); put("̣̄L", "Ḹ"); put("̄ḷ", "ḹ"); put("̣̄l", "ḹ"); put("̱L", "Ḻ"); put("̱l", "ḻ"); put("̭L", "Ḽ"); put("̭l", "ḽ"); put("́M", "Ḿ"); put("́m", "ḿ"); put("̇M", "Ṁ"); put("̇m", "ṁ"); put("̣M", "Ṃ"); put("̣m", "ṃ"); put("̇N", "Ṅ"); put("̇n", "ṅ"); put("̣N", "Ṇ"); put("̣n", "ṇ"); put("̱N", "Ṉ"); put("̱n", "ṉ"); put("̭N", "Ṋ"); put("̭n", "ṋ"); put("́Õ", "Ṍ"); put("́ ̃O", "Ṍ"); put("́õ", "ṍ"); put("́ ̃o", "ṍ"); put("̈Õ", "Ṏ"); put("̈ ̃O", "Ṏ"); put("̈õ", "ṏ"); put("̈ ̃o", "ṏ"); put("̀Ō", "Ṑ"); put("̀ ̄O", "Ṑ"); put("̀ō", "ṑ"); put("̀ ̄o", "ṑ"); put("́Ō", "Ṓ"); put("́ ̄O", "Ṓ"); put("́ō", "ṓ"); put("́ ̄o", "ṓ"); put("́P", "Ṕ"); put("́p", "ṕ"); put("̇P", "Ṗ"); put("̇p", "ṗ"); put("̇R", "Ṙ"); put("̇r", "ṙ"); put("̣R", "Ṛ"); put("̣r", "ṛ"); put("̄Ṛ", "Ṝ"); put("̣̄R", "Ṝ"); put("̄ṛ", "ṝ"); put("̣̄r", "ṝ"); put("̱R", "Ṟ"); put("̱r", "ṟ"); put("̇S", "Ṡ"); put("̇s", "ṡ"); put("̣S", "Ṣ"); put("̣s", "ṣ"); put("̇Ś", "Ṥ"); put("̇ ́S", "Ṥ"); put("̇ś", "ṥ"); put("̇ ́s", "ṥ"); put("̇Š", "Ṧ"); put("̇̌S", "Ṧ"); put("̇š", "ṧ"); put("̇̌s", "ṧ"); put("̇Ṣ", "Ṩ"); put("̣̇S", "Ṩ"); put("̇ṣ", "ṩ"); put("̣̇s", "ṩ"); put("̇T", "Ṫ"); put("̇t", "ṫ"); put("̣T", "Ṭ"); put("̣t", "ṭ"); put("̱T", "Ṯ"); put("̱t", "ṯ"); put("̭T", "Ṱ"); put("̭t", "ṱ"); put("̤U", "Ṳ"); put("̤u", "ṳ"); put("̰U", "Ṵ"); put("̰u", "ṵ"); put("̭U", "Ṷ"); put("̭u", "ṷ"); put("́Ũ", "Ṹ"); put("́ ̃U", "Ṹ"); put("́ũ", "ṹ"); put("́ ̃u", "ṹ"); put("̈Ū", "Ṻ"); put("̈ ̄U", "Ṻ"); put("̈ū", "ṻ"); put("̈ ̄u", "ṻ"); put("̃V", "Ṽ"); put("̃v", "ṽ"); put("̣V", "Ṿ"); put("̣v", "ṿ"); put("̀W", "Ẁ"); put("̀w", "ẁ"); put("́W", "Ẃ"); put("́w", "ẃ"); put("̈W", "Ẅ"); put("̈w", "ẅ"); put("̇W", "Ẇ"); put("̇w", "ẇ"); put("̣W", "Ẉ"); put("̣w", "ẉ"); put("̇X", "Ẋ"); put("̇x", "ẋ"); put("̈X", "Ẍ"); put("̈x", "ẍ"); put("̇Y", "Ẏ"); put("̇y", "ẏ"); put("̂Z", "Ẑ"); put("̂z", "ẑ"); put("̣Z", "Ẓ"); put("̣z", "ẓ"); put("̱Z", "Ẕ"); put("̱z", "ẕ"); put("̱h", "ẖ"); put("̈t", "ẗ"); put("̊w", "ẘ"); put("̊y", "ẙ"); put("̇ſ", "ẛ"); put("̣A", "Ạ"); put("̣a", "ạ"); put("̉A", "Ả"); put("̉a", "ả"); put("́Â", "Ấ"); put("́ ̂A", "Ấ"); put("́â", "ấ"); put("́ ̂a", "ấ"); put("̀Â", "Ầ"); put("̀ ̂A", "Ầ"); put("̀â", "ầ"); put("̀ ̂a", "ầ"); put("̉Â", "Ẩ"); put("̉ ̂A", "Ẩ"); put("̉â", "ẩ"); put("̉ ̂a", "ẩ"); put("̃Â", "Ẫ"); put("̃ ̂A", "Ẫ"); put("̃â", "ẫ"); put("̃ ̂a", "ẫ"); put("̂Ạ", "Ậ"); put("̣̂A", "Ậ"); put("̣Â", "Ậ"); put("̂ạ", "ậ"); put("̣̂a", "ậ"); put("̣â", "ậ"); put("́Ă", "Ắ"); put("́̆A", "Ắ"); put("́ă", "ắ"); put("́̆a", "ắ"); put("̀Ă", "Ằ"); put("̀̆A", "Ằ"); put("̀ă", "ằ"); put("̀̆a", "ằ"); put("̉Ă", "Ẳ"); put("̉̆A", "Ẳ"); put("̉ă", "ẳ"); put("̉̆a", "ẳ"); put("̃Ă", "Ẵ"); put("̃̆A", "Ẵ"); put("̃ă", "ẵ"); put("̃̆a", "ẵ"); put("̆Ạ", "Ặ"); put("̣̆A", "Ặ"); put("̣Ă", "Ặ"); put("̆ạ", "ặ"); put("̣̆a", "ặ"); put("̣ă", "ặ"); put("̣E", "Ẹ"); put("̣e", "ẹ"); put("̉E", "Ẻ"); put("̉e", "ẻ"); put("̃E", "Ẽ"); put("̃e", "ẽ"); put("́Ê", "Ế"); put("́ ̂E", "Ế"); put("́ê", "ế"); put("́ ̂e", "ế"); put("̀Ê", "Ề"); put("̀ ̂E", "Ề"); put("̀ê", "ề"); put("̀ ̂e", "ề"); put("̉Ê", "Ể"); put("̉ ̂E", "Ể"); put("̉ê", "ể"); put("̉ ̂e", "ể"); put("̃Ê", "Ễ"); put("̃ ̂E", "Ễ"); put("̃ê", "ễ"); put("̃ ̂e", "ễ"); put("̂Ẹ", "Ệ"); put("̣̂E", "Ệ"); put("̣Ê", "Ệ"); put("̂ẹ", "ệ"); put("̣̂e", "ệ"); put("̣ê", "ệ"); put("̉I", "Ỉ"); put("̉i", "ỉ"); put("̣I", "Ị"); put("̣i", "ị"); put("̣O", "Ọ"); put("̣o", "ọ"); put("̉O", "Ỏ"); put("̉o", "ỏ"); put("́Ô", "Ố"); put("́ ̂O", "Ố"); put("́ô", "ố"); put("́ ̂o", "ố"); put("̀Ô", "Ồ"); put("̀ ̂O", "Ồ"); put("̀ô", "ồ"); put("̀ ̂o", "ồ"); put("̉Ô", "Ổ"); put("̉ ̂O", "Ổ"); put("̉ô", "ổ"); put("̉ ̂o", "ổ"); put("̃Ô", "Ỗ"); put("̃ ̂O", "Ỗ"); put("̃ô", "ỗ"); put("̃ ̂o", "ỗ"); put("̂Ọ", "Ộ"); put("̣̂O", "Ộ"); put("̣Ô", "Ộ"); put("̂ọ", "ộ"); put("̣̂o", "ộ"); put("̣ô", "ộ"); put("́Ơ", "Ớ"); put("̛́O", "Ớ"); put("́ơ", "ớ"); put("̛́o", "ớ"); put("̀Ơ", "Ờ"); put("̛̀O", "Ờ"); put("̀ơ", "ờ"); put("̛̀o", "ờ"); put("̉Ơ", "Ở"); put("̛̉O", "Ở"); put("̉ơ", "ở"); put("̛̉o", "ở"); put("̃Ơ", "Ỡ"); put("̛̃O", "Ỡ"); put("̃ơ", "ỡ"); put("̛̃o", "ỡ"); put("̣Ơ", "Ợ"); put("̛̣O", "Ợ"); put("̣ơ", "ợ"); put("̛̣o", "ợ"); put("̣U", "Ụ"); put("̣u", "ụ"); put("̉U", "Ủ"); put("̉u", "ủ"); put("́Ư", "Ứ"); put("̛́U", "Ứ"); put("́ư", "ứ"); put("̛́u", "ứ"); put("̀Ư", "Ừ"); put("̛̀U", "Ừ"); put("̀ư", "ừ"); put("̛̀u", "ừ"); put("̉Ư", "Ử"); put("̛̉U", "Ử"); put("̉ư", "ử"); put("̛̉u", "ử"); put("̃Ư", "Ữ"); put("̛̃U", "Ữ"); put("̃ư", "ữ"); put("̛̃u", "ữ"); put("̣Ư", "Ự"); put("̛̣U", "Ự"); put("̣ư", "ự"); put("̛̣u", "ự"); put("̀Y", "Ỳ"); put("̀y", "ỳ"); put("̣Y", "Ỵ"); put("̣y", "ỵ"); put("̉Y", "Ỷ"); put("̉y", "ỷ"); put("̃Y", "Ỹ"); put("̃y", "ỹ"); // include? put("̂0", "⁰"); put("̂4", "⁴"); put("̂5", "⁵"); put("̂6", "⁶"); put("̂7", "⁷"); put("̂8", "⁸"); put("̂9", "⁹"); put("̂+", "⁺"); put("̂−", "⁻"); put("̂=", "⁼"); put("̂(", "⁽"); put("̂)", "⁾"); put("̣+", "⨥"); put("̰+", "⨦"); put("̣-", "⨪"); put("̣=", "⩦"); put("̤̈=", "⩷"); put("̤̈=", "⩷"); // include end? put("̥|", "⫰"); put("̇Ā", "Ǡ"); put("̇ā", "ǡ"); put("̇j", "ȷ"); put("̇L", "Ŀ"); put("̇l", "ŀ"); put("̇Ō", "Ȱ"); put("̇ō", "ȱ"); put("́Ṡ", "Ṥ"); put("́ṡ", "ṥ"); put("́V", "Ǘ"); put("́v", "ǘ"); put("̣Ṡ", "Ṩ"); put("̣ṡ", "ṩ"); put("̣̣", "̣"); put("̣ ", "̣"); put("̆Á", "Ắ"); put("̆À", "Ằ"); put("̆Ả", "Ẳ"); put("̆Ã", "Ẵ"); put("̆a", "ắ"); put("̆à", "ằ"); put("̆ả", "ẳ"); put("̆ã", "ẵ"); // include? put("̌(", "₍"); put("̌)", "₎"); put("̌+", "₊"); put("̌-", "₋"); put("̌0", "₀"); put("̌1", "₁"); put("̌2", "₂"); put("̌3", "₃"); put("̌4", "₄"); put("̌5", "₅"); put("̌6", "₆"); put("̌7", "₇"); put("̌8", "₈"); put("̌9", "₉"); put("̌=", "₌"); // include end? put("̌Dz", "Dž"); put("̌Ṡ", "Ṧ"); put("̌ṡ", "ṧ"); put("̌V", "Ǚ"); put("̌v", "ǚ"); put("̧C", "Ḉ"); put("̧c", "ḉ"); put("̧¢", "₵"); put("̧Ĕ", "Ḝ"); put("̧ĕ", "ḝ"); put("̂-", "⁻"); put("̂Á", "Ấ"); put("̂À", "Ầ"); put("̂Ả", "Ẩ"); put("̂Ã", "Ẫ"); put("̂á", "ấ"); put("̂à", "ầ"); put("̂ả", "ẩ"); put("̂ã", "ẫ"); put("̂É", "Ế"); put("̂È", "Ề"); put("̂Ẻ", "Ể"); put("̂Ẽ", "Ễ"); put("̂é", "ế"); put("̂è", "ề"); put("̂ẻ", "ể"); put("̂ẽ", "ễ"); put("̂Ó", "Ố"); put("̂Ò", "Ồ"); put("̂Ỏ", "Ổ"); put("̂Õ", "Ỗ"); put("̂ó", "ố"); put("̂ò", "ồ"); put("̂ỏ", "ổ"); put("̂õ", "ỗ"); put("̦S", "Ș"); put("̦s", "ș"); put("̦T", "Ț"); put("̦t", "ț"); put("̦̦", ","); put("̦ ", ","); put("̈Ā", "Ǟ"); put("̈ā", "ǟ"); put("̈Í", "Ḯ"); put("̈í", "ḯ"); put("̈Ō", "Ȫ"); put("̈ō", "ȫ"); put("̈Ú", "Ǘ"); put("̈Ǔ", "Ǚ"); put("̈Ù", "Ǜ"); put("̈ú", "ǘ"); put("̈ǔ", "ǚ"); put("̈ù", "ǜ"); put("̀V", "Ǜ"); put("̀v", "ǜ"); put("̉B", "Ɓ"); put("̉b", "ɓ"); put("̉C", "Ƈ"); put("̉c", "ƈ"); put("̉D", "Ɗ"); put("̉d", "ɗ"); put("̉ɖ", "ᶑ"); put("̉F", "Ƒ"); put("̉f", "ƒ"); put("̉G", "Ɠ"); put("̉g", "ɠ"); put("̉h", "ɦ"); put("̉ɟ", "ʄ"); put("̉K", "Ƙ"); put("̉k", "ƙ"); put("̉M", "Ɱ"); put("̉m", "ɱ"); put("̉N", "Ɲ"); put("̉n", "ɲ"); put("̉P", "Ƥ"); put("̉p", "ƥ"); put("̉q", "ʠ"); put("̉ɜ", "ɝ"); put("̉s", "ʂ"); put("̉ə", "ɚ"); put("̉T", "Ƭ"); put("̉t", "ƭ"); put("̉ɹ", "ɻ"); put("̉V", "Ʋ"); put("̉v", "ʋ"); put("̉W", "Ⱳ"); put("̉w", "ⱳ"); put("̉Z", "Ȥ"); put("̉z", "ȥ"); put("̉̉", "̉"); put("̉ ", "̉"); put("̛Ó", "Ớ"); put("̛O", "Ợ"); put("̛Ò", "Ờ"); put("̛Ỏ", "Ở"); put("̛Õ", "Ỡ"); put("̛ó", "ớ"); put("̛ọ", "ợ"); put("̛ò", "ờ"); put("̛ỏ", "ở"); put("̛õ", "ỡ"); put("̛Ú", "Ứ"); put("̛Ụ", "Ự"); put("̛Ù", "Ừ"); put("̛Ủ", "Ử"); put("̛Ũ", "Ữ"); put("̛ú", "ứ"); put("̛ụ", "ự"); put("̛ù", "ừ"); put("̛ủ", "ử"); put("̛ũ", "ữ"); put("̛̛", "̛"); put("̛ ", "̛"); put("̄É", "Ḗ"); put("̄È", "Ḕ"); put("̄é", "ḗ"); put("̄è", "ḕ"); put("̄Ó", "Ṓ"); put("̄Ò", "Ṑ"); put("̄ó", "ṓ"); put("̄ò", "ṑ"); put("̄V", "Ǖ"); put("̄v", "ǖ"); put("̨Ō", "Ǭ"); put("̨ō", "ǭ"); put("̊Á", "Ǻ"); put("̊á", "ǻ"); put("̃Ó", "Ṍ"); put("̃Ö", "Ṏ"); put("̃Ō", "Ȭ"); put("̃ó", "ṍ"); put("̃ö", "ṏ"); put("̃ō", "ȭ"); put("̃Ú", "Ṹ"); put("̃ú", "ṹ"); put("̃=", "≃"); put("̃<", "≲"); put("̃>", "≳"); put("́̇S", "Ṥ"); put("́̇s", "ṥ"); put("̣̇S", "Ṩ"); put("̣̇s", "ṩ"); put("̌̇S", "Ṧ"); put("̌̇s", "ṧ"); put("̇ ̄A", "Ǡ"); put("̇ ̄a", "ǡ"); put("̇ ̄O", "Ȱ"); put("̇ ̄o", "ȱ"); put("̆ ́A", "Ắ"); put("̆ ́a", "ắ"); put("̧ ́C", "Ḉ"); put("̧ ́c", "ḉ"); put("̂ ́A", "Ấ"); put("̂ ́a", "ấ"); put("̂ ́E", "Ế"); put("̂ ́e", "ế"); put("̂ ́O", "Ố"); put("̂ ́o", "ố"); put("̈ ́I", "Ḯ"); put("̈ ́i", "ḯ"); put("̈ ́U", "Ǘ"); put("̈ ́u", "ǘ"); put("̛ ́O", "Ớ"); put("̛ ́o", "ớ"); put("̛ ́U", "Ứ"); put("̛ ́u", "ứ"); put("̄ ́E", "Ḗ"); put("̄ ́e", "ḗ"); put("̄ ́O", "Ṓ"); put("̄ ́o", "ṓ"); put("̊ ́A", "Ǻ"); put("̊ ́a", "ǻ"); put("̃ ́O", "Ṍ"); put("̃ ́o", "ṍ"); put("̃ ́U", "Ṹ"); put("̃ ́u", "ṹ"); put("̣̆A", "Ặ"); put("̣̆a", "ặ"); put("̣ ̂A", "Ậ"); put("̣ ̂a", "ậ"); put("̣ ̂E", "Ệ"); put("̣ ̂e", "ệ"); put("̣ ̂O", "Ộ"); put("̣ ̂o", "ộ"); put("̛̣O", "Ợ"); put("̛̣o", "ợ"); put("̛̣U", "Ự"); put("̛̣u", "ự"); put("̣ ̄L", "Ḹ"); put("̣ ̄l", "ḹ"); put("̣ ̄R", "Ṝ"); put("̣ ̄r", "ṝ"); put("̧̆E", "Ḝ"); put("̧̆e", "ḝ"); put("̆ ̀A", "Ằ"); put("̆ ̀a", "ằ"); put("̆̉A", "Ẳ"); put("̆̉a", "ẳ"); put("̆ ̃A", "Ẵ"); put("̆ ̃a", "ẵ"); put("̈̌U", "Ǚ"); put("̈̌u", "ǚ"); put("̂ ̀A", "Ầ"); put("̂ ̀a", "ầ"); put("̂ ̀E", "Ề"); put("̂ ̀e", "ề"); put("̂ ̀O", "Ồ"); put("̂ ̀o", "ồ"); put("̂̉A", "Ẩ"); put("̂̉a", "ẩ"); put("̂̉E", "Ể"); put("̂̉e", "ể"); put("̂̉O", "Ổ"); put("̂̉o", "ổ"); put("̂ ̃A", "Ẫ"); put("̂ ̃a", "ẫ"); put("̂ ̃E", "Ễ"); put("̂ ̃e", "ễ"); put("̂ ̃O", "Ỗ"); put("̂ ̃o", "ỗ"); put("̈ ̀U", "Ǜ"); put("̈ ̀u", "ǜ"); put("̈ ̄A", "Ǟ"); put("̈ ̄a", "ǟ"); put("̈ ̄O", "Ȫ"); put("̈ ̄o", "ȫ"); put("̃̈O", "Ṏ"); put("̃̈o", "ṏ"); put("̛ ̀O", "Ờ"); put("̛ ̀o", "ờ"); put("̛ ̀U", "Ừ"); put("̛ ̀u", "ừ"); put("̄ ̀E", "Ḕ"); put("̄ ̀e", "ḕ"); put("̄ ̀O", "Ṑ"); put("̄ ̀o", "ṑ"); put("̛̉O", "Ở"); put("̛̉o", "ở"); put("̛̉U", "Ử"); put("̛̉u", "ử"); put("̛ ̃O", "Ỡ"); put("̛ ̃o", "ỡ"); put("̛ ̃U", "Ữ"); put("̛ ̃u", "ữ"); put("̨ ̄O", "Ǭ"); put("̨ ̄o", "ǭ"); put("̃ ̄O", "Ȭ"); put("̃ ̄o", "ȭ"); */ } public static String normalize(String input) { String lookup = mMap.get(input); if (lookup != null) return lookup; return Normalizer.normalize(input, Normalizer.Form.NFC); } public boolean execute(int code) { String composed = executeToString(code); if (composed != null) { //Log.i(TAG, "composed=" + composed + " len=" + composed.length()); if (composed.equals("")) { // Unrecognised - try to use the built-in Java text normalisation int c = composeBuffer.codePointAt(composeBuffer.length() - 1); if (Character.getType(c) != Character.NON_SPACING_MARK) { // Put the combining character(s) at the end, else this won't work composeBuffer.reverse(); composed = Normalizer.normalize(composeBuffer.toString(), Normalizer.Form.NFC); if (composed.equals("")) { return true; // incomplete :-) } } else { return true; // there may be multiple combining accents } } clear(); composeUser.onText(composed); return false; } return true; } }
Java
/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.pocketworkstation.pckeyboard; import org.pocketworkstation.pckeyboard.LatinIMEUtil.RingCharBuffer; import com.android.inputmethod.voice.FieldContext; import com.android.inputmethod.voice.SettingsUtil; import com.android.inputmethod.voice.VoiceInput; import org.xmlpull.v1.XmlPullParserException; import android.app.AlertDialog; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.res.Configuration; import android.content.res.Resources; import android.content.res.XmlResourceParser; import android.inputmethodservice.InputMethodService; import android.media.AudioManager; import android.os.Debug; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.os.SystemClock; import android.os.Vibrator; import android.preference.PreferenceActivity; import android.preference.PreferenceManager; import android.speech.SpeechRecognizer; import android.text.ClipboardManager; import android.text.TextUtils; import android.util.DisplayMetrics; import android.util.Log; import android.util.PrintWriterPrinter; import android.util.Printer; import android.view.HapticFeedbackConstants; import android.view.KeyCharacterMap; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; import android.view.Window; import android.view.WindowManager; import android.view.inputmethod.CompletionInfo; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.ExtractedText; import android.view.inputmethod.ExtractedTextRequest; import android.view.inputmethod.InputConnection; import android.view.inputmethod.InputMethodManager; import android.widget.LinearLayout; import android.widget.Toast; import java.io.FileDescriptor; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.regex.Pattern; import java.util.regex.Matcher; /** * Input method implementation for Qwerty'ish keyboard. */ public class LatinIME extends InputMethodService implements ComposeSequencing, LatinKeyboardBaseView.OnKeyboardActionListener, VoiceInput.UiListener, SharedPreferences.OnSharedPreferenceChangeListener { private static final String TAG = "PCKeyboardIME"; private static final boolean PERF_DEBUG = false; static final boolean DEBUG = false; static final boolean TRACE = false; static final boolean VOICE_INSTALLED = true; static final boolean ENABLE_VOICE_BUTTON = true; static Map<Integer, String> ESC_SEQUENCES; static Map<Integer, Integer> CTRL_SEQUENCES; private static final String PREF_VIBRATE_ON = "vibrate_on"; static final String PREF_VIBRATE_LEN = "vibrate_len"; private static final String PREF_SOUND_ON = "sound_on"; private static final String PREF_POPUP_ON = "popup_on"; private static final String PREF_AUTO_CAP = "auto_cap"; private static final String PREF_QUICK_FIXES = "quick_fixes"; private static final String PREF_SHOW_SUGGESTIONS = "show_suggestions"; private static final String PREF_AUTO_COMPLETE = "auto_complete"; // private static final String PREF_BIGRAM_SUGGESTIONS = // "bigram_suggestion"; private static final String PREF_VOICE_MODE = "voice_mode"; // Whether or not the user has used voice input before (and thus, whether to // show the // first-run warning dialog or not). private static final String PREF_HAS_USED_VOICE_INPUT = "has_used_voice_input"; // Whether or not the user has used voice input from an unsupported locale // UI before. // For example, the user has a Chinese UI but activates voice input. private static final String PREF_HAS_USED_VOICE_INPUT_UNSUPPORTED_LOCALE = "has_used_voice_input_unsupported_locale"; // A list of locales which are supported by default for voice input, unless // we get a // different list from Gservices. public static final String DEFAULT_VOICE_INPUT_SUPPORTED_LOCALES = "en " + "en_US " + "en_GB " + "en_AU " + "en_CA " + "en_IE " + "en_IN " + "en_NZ " + "en_SG " + "en_ZA "; // The private IME option used to indicate that no microphone should be // shown for a // given text field. For instance this is specified by the search dialog // when the // dialog is already showing a voice search button. private static final String IME_OPTION_NO_MICROPHONE = "nm"; public static final String PREF_SELECTED_LANGUAGES = "selected_languages"; public static final String PREF_INPUT_LANGUAGE = "input_language"; private static final String PREF_RECORRECTION_ENABLED = "recorrection_enabled"; static final String PREF_FULLSCREEN_OVERRIDE = "fullscreen_override"; static final String PREF_FORCE_KEYBOARD_ON = "force_keyboard_on"; static final String PREF_KEYBOARD_NOTIFICATION = "keyboard_notification"; static final String PREF_CONNECTBOT_TAB_HACK = "connectbot_tab_hack"; static final String PREF_FULL_KEYBOARD_IN_PORTRAIT = "full_keyboard_in_portrait"; static final String PREF_SUGGESTIONS_IN_LANDSCAPE = "suggestions_in_landscape"; static final String PREF_HEIGHT_PORTRAIT = "settings_height_portrait"; static final String PREF_HEIGHT_LANDSCAPE = "settings_height_landscape"; static final String PREF_HINT_MODE = "pref_hint_mode"; static final String PREF_LONGPRESS_TIMEOUT = "pref_long_press_duration"; static final String PREF_RENDER_MODE = "pref_render_mode"; static final String PREF_SWIPE_UP = "pref_swipe_up"; static final String PREF_SWIPE_DOWN = "pref_swipe_down"; static final String PREF_SWIPE_LEFT = "pref_swipe_left"; static final String PREF_SWIPE_RIGHT = "pref_swipe_right"; static final String PREF_VOL_UP = "pref_vol_up"; static final String PREF_VOL_DOWN = "pref_vol_down"; private static final int MSG_UPDATE_SUGGESTIONS = 0; private static final int MSG_START_TUTORIAL = 1; private static final int MSG_UPDATE_SHIFT_STATE = 2; private static final int MSG_VOICE_RESULTS = 3; private static final int MSG_UPDATE_OLD_SUGGESTIONS = 4; // How many continuous deletes at which to start deleting at a higher speed. private static final int DELETE_ACCELERATE_AT = 20; // Key events coming any faster than this are long-presses. private static final int QUICK_PRESS = 200; static final int ASCII_ENTER = '\n'; static final int ASCII_SPACE = ' '; static final int ASCII_PERIOD = '.'; // Contextual menu positions private static final int POS_METHOD = 0; private static final int POS_SETTINGS = 1; // private LatinKeyboardView mInputView; private LinearLayout mCandidateViewContainer; private CandidateView mCandidateView; private Suggest mSuggest; private CompletionInfo[] mCompletions; private AlertDialog mOptionsDialog; private AlertDialog mVoiceWarningDialog; /* package */KeyboardSwitcher mKeyboardSwitcher; private UserDictionary mUserDictionary; private UserBigramDictionary mUserBigramDictionary; private ContactsDictionary mContactsDictionary; private AutoDictionary mAutoDictionary; private Hints mHints; private Resources mResources; private String mInputLocale; private String mSystemLocale; private LanguageSwitcher mLanguageSwitcher; private StringBuilder mComposing = new StringBuilder(); private WordComposer mWord = new WordComposer(); private int mCommittedLength; private boolean mPredicting; private boolean mRecognizing; private boolean mAfterVoiceInput; private boolean mImmediatelyAfterVoiceInput; private boolean mShowingVoiceSuggestions; private boolean mVoiceInputHighlighted; private boolean mEnableVoiceButton; private CharSequence mBestWord; private boolean mPredictionOnForMode; private boolean mPredictionOnPref; private boolean mCompletionOn; private boolean mHasDictionary; private boolean mAutoSpace; private boolean mJustAddedAutoSpace; private boolean mAutoCorrectEnabled; private boolean mReCorrectionEnabled; // Bigram Suggestion is disabled in this version. private final boolean mBigramSuggestionEnabled = false; private boolean mAutoCorrectOn; // TODO move this state variable outside LatinIME private boolean mModCtrl; private boolean mModAlt; private boolean mModFn; // Saved shift state when leaving alphabet mode, or when applying multitouch shift private int mSavedShiftState; private boolean mPasswordText; private boolean mVibrateOn; private int mVibrateLen; private boolean mSoundOn; private boolean mPopupOn; private boolean mAutoCapPref; private boolean mAutoCapActive; private boolean mDeadKeysActive; private boolean mQuickFixes; private boolean mHasUsedVoiceInput; private boolean mHasUsedVoiceInputUnsupportedLocale; private boolean mLocaleSupportedForVoiceInput; private boolean mShowSuggestions; private boolean mIsShowingHint; private boolean mConnectbotTabHack; private boolean mFullscreenOverride; private boolean mForceKeyboardOn; private boolean mKeyboardNotification; private boolean mSuggestionsInLandscape; private boolean mSuggestionForceOn; private boolean mSuggestionForceOff; private String mSwipeUpAction; private String mSwipeDownAction; private String mSwipeLeftAction; private String mSwipeRightAction; private String mVolUpAction; private String mVolDownAction; public static final GlobalKeyboardSettings sKeyboardSettings = new GlobalKeyboardSettings(); private int mHeightPortrait; private int mHeightLandscape; private int mNumKeyboardModes = 3; private int mKeyboardModeOverridePortrait; private int mKeyboardModeOverrideLandscape; private int mCorrectionMode; private boolean mEnableVoice = true; private boolean mVoiceOnPrimary; private int mOrientation; private List<CharSequence> mSuggestPuncList; // Keep track of the last selection range to decide if we need to show word // alternatives private int mLastSelectionStart; private int mLastSelectionEnd; // Input type is such that we should not auto-correct private boolean mInputTypeNoAutoCorrect; // Indicates whether the suggestion strip is to be on in landscape private boolean mJustAccepted; private CharSequence mJustRevertedSeparator; private int mDeleteCount; private long mLastKeyTime; // Modifier keys state private ModifierKeyState mShiftKeyState = new ModifierKeyState(); private ModifierKeyState mSymbolKeyState = new ModifierKeyState(); private ModifierKeyState mCtrlKeyState = new ModifierKeyState(); private ModifierKeyState mAltKeyState = new ModifierKeyState(); private ModifierKeyState mFnKeyState = new ModifierKeyState(); // Compose sequence handling private boolean mComposeMode = false; private ComposeBase mComposeBuffer = new ComposeSequence(this); private ComposeBase mDeadAccentBuffer = new DeadAccentSequence(this); private Tutorial mTutorial; private AudioManager mAudioManager; // Align sound effect volume on music volume private final float FX_VOLUME = -1.0f; private final float FX_VOLUME_RANGE_DB = 72.0f; private boolean mSilentMode; /* package */String mWordSeparators; private String mSentenceSeparators; private VoiceInput mVoiceInput; private VoiceResults mVoiceResults = new VoiceResults(); private boolean mConfigurationChanging; // Keeps track of most recently inserted text (multi-character key) for // reverting private CharSequence mEnteredText; private boolean mRefreshKeyboardRequired; // For each word, a list of potential replacements, usually from voice. private Map<String, List<CharSequence>> mWordToSuggestions = new HashMap<String, List<CharSequence>>(); private ArrayList<WordAlternatives> mWordHistory = new ArrayList<WordAlternatives>(); private PluginManager mPluginManager; private NotificationReceiver mNotificationReceiver; private class VoiceResults { List<String> candidates; Map<String, List<CharSequence>> alternatives; } public abstract static class WordAlternatives { protected CharSequence mChosenWord; public WordAlternatives() { // Nothing } public WordAlternatives(CharSequence chosenWord) { mChosenWord = chosenWord; } @Override public int hashCode() { return mChosenWord.hashCode(); } public abstract CharSequence getOriginalWord(); public CharSequence getChosenWord() { return mChosenWord; } public abstract List<CharSequence> getAlternatives(); } public class TypedWordAlternatives extends WordAlternatives { private WordComposer word; public TypedWordAlternatives() { // Nothing } public TypedWordAlternatives(CharSequence chosenWord, WordComposer wordComposer) { super(chosenWord); word = wordComposer; } @Override public CharSequence getOriginalWord() { return word.getTypedWord(); } @Override public List<CharSequence> getAlternatives() { return getTypedSuggestions(word); } } /* package */Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case MSG_UPDATE_SUGGESTIONS: updateSuggestions(); break; case MSG_UPDATE_OLD_SUGGESTIONS: setOldSuggestions(); break; case MSG_START_TUTORIAL: if (mTutorial == null) { if (mKeyboardSwitcher.getInputView().isShown()) { mTutorial = new Tutorial(LatinIME.this, mKeyboardSwitcher.getInputView()); mTutorial.start(); } else { // Try again soon if the view is not yet showing sendMessageDelayed(obtainMessage(MSG_START_TUTORIAL), 100); } } break; case MSG_UPDATE_SHIFT_STATE: updateShiftKeyState(getCurrentInputEditorInfo()); break; case MSG_VOICE_RESULTS: handleVoiceResults(); break; } } }; @Override public void onCreate() { Log.i("PCKeyboard", "onCreate(), os.version=" + System.getProperty("os.version")); LatinImeLogger.init(this); KeyboardSwitcher.init(this); super.onCreate(); // setStatusIcon(R.drawable.ime_qwerty); mResources = getResources(); final Configuration conf = mResources.getConfiguration(); mOrientation = conf.orientation; final SharedPreferences prefs = PreferenceManager .getDefaultSharedPreferences(this); mLanguageSwitcher = new LanguageSwitcher(this); mLanguageSwitcher.loadLocales(prefs); mKeyboardSwitcher = KeyboardSwitcher.getInstance(); mKeyboardSwitcher.setLanguageSwitcher(mLanguageSwitcher); mSystemLocale = conf.locale.toString(); mLanguageSwitcher.setSystemLocale(conf.locale); String inputLanguage = mLanguageSwitcher.getInputLanguage(); if (inputLanguage == null) { inputLanguage = conf.locale.toString(); } Resources res = getResources(); mReCorrectionEnabled = prefs.getBoolean(PREF_RECORRECTION_ENABLED, res.getBoolean(R.bool.default_recorrection_enabled)); mConnectbotTabHack = prefs.getBoolean(PREF_CONNECTBOT_TAB_HACK, res.getBoolean(R.bool.default_connectbot_tab_hack)); mFullscreenOverride = prefs.getBoolean(PREF_FULLSCREEN_OVERRIDE, res.getBoolean(R.bool.default_fullscreen_override)); mForceKeyboardOn = prefs.getBoolean(PREF_FORCE_KEYBOARD_ON, res.getBoolean(R.bool.default_force_keyboard_on)); mKeyboardNotification = prefs.getBoolean(PREF_KEYBOARD_NOTIFICATION, res.getBoolean(R.bool.default_keyboard_notification)); mSuggestionsInLandscape = prefs.getBoolean(PREF_SUGGESTIONS_IN_LANDSCAPE, res.getBoolean(R.bool.default_suggestions_in_landscape)); mHeightPortrait = getHeight(prefs, PREF_HEIGHT_PORTRAIT, res.getString(R.string.default_height_portrait)); mHeightLandscape = getHeight(prefs, PREF_HEIGHT_LANDSCAPE, res.getString(R.string.default_height_landscape)); LatinIME.sKeyboardSettings.hintMode = Integer.parseInt(prefs.getString(PREF_HINT_MODE, res.getString(R.string.default_hint_mode))); LatinIME.sKeyboardSettings.longpressTimeout = getPrefInt(prefs, PREF_LONGPRESS_TIMEOUT, res.getString(R.string.default_long_press_duration)); LatinIME.sKeyboardSettings.renderMode = getPrefInt(prefs, PREF_RENDER_MODE, res.getString(R.string.default_render_mode)); mSwipeUpAction = prefs.getString(PREF_SWIPE_UP, res.getString(R.string.default_swipe_up)); mSwipeDownAction = prefs.getString(PREF_SWIPE_DOWN, res.getString(R.string.default_swipe_down)); mSwipeLeftAction = prefs.getString(PREF_SWIPE_LEFT, res.getString(R.string.default_swipe_left)); mSwipeRightAction = prefs.getString(PREF_SWIPE_RIGHT, res.getString(R.string.default_swipe_right)); mVolUpAction = prefs.getString(PREF_VOL_UP, res.getString(R.string.default_vol_up)); mVolDownAction = prefs.getString(PREF_VOL_DOWN, res.getString(R.string.default_vol_down)); sKeyboardSettings.initPrefs(prefs, res); updateKeyboardOptions(); PluginManager.getPluginDictionaries(getApplicationContext()); mPluginManager = new PluginManager(this); final IntentFilter pFilter = new IntentFilter(); pFilter.addDataScheme("package"); pFilter.addAction("android.intent.action.PACKAGE_ADDED"); pFilter.addAction("android.intent.action.PACKAGE_REPLACED"); pFilter.addAction("android.intent.action.PACKAGE_REMOVED"); registerReceiver(mPluginManager, pFilter); LatinIMEUtil.GCUtils.getInstance().reset(); boolean tryGC = true; for (int i = 0; i < LatinIMEUtil.GCUtils.GC_TRY_LOOP_MAX && tryGC; ++i) { try { initSuggest(inputLanguage); tryGC = false; } catch (OutOfMemoryError e) { tryGC = LatinIMEUtil.GCUtils.getInstance().tryGCOrWait( inputLanguage, e); } } mOrientation = conf.orientation; // register to receive ringer mode changes for silent mode IntentFilter filter = new IntentFilter( AudioManager.RINGER_MODE_CHANGED_ACTION); registerReceiver(mReceiver, filter); if (VOICE_INSTALLED) { mVoiceInput = new VoiceInput(this, this); mHints = new Hints(this, new Hints.Display() { public void showHint(int viewResource) { LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(viewResource, null); setCandidatesView(view); setCandidatesViewShown(true); mIsShowingHint = true; } }); } prefs.registerOnSharedPreferenceChangeListener(this); setNotification(mKeyboardNotification); } private int getKeyboardModeNum(int origMode, int override) { if (mNumKeyboardModes == 2 && origMode == 2) origMode = 1; // skip "compact". FIXME! int num = (origMode + override) % mNumKeyboardModes; if (mNumKeyboardModes == 2 && num == 1) num = 2; // skip "compact". FIXME! return num; } private void updateKeyboardOptions() { //Log.i(TAG, "setFullKeyboardOptions " + fullInPortrait + " " + heightPercentPortrait + " " + heightPercentLandscape); boolean isPortrait = isPortrait(); int kbMode; mNumKeyboardModes = sKeyboardSettings.compactModeEnabled ? 3 : 2; // FIXME! if (isPortrait) { kbMode = getKeyboardModeNum(sKeyboardSettings.keyboardModePortrait, mKeyboardModeOverridePortrait); } else { kbMode = getKeyboardModeNum(sKeyboardSettings.keyboardModeLandscape, mKeyboardModeOverrideLandscape); } // Convert overall keyboard height to per-row percentage int screenHeightPercent = isPortrait ? mHeightPortrait : mHeightLandscape; LatinIME.sKeyboardSettings.keyboardMode = kbMode; LatinIME.sKeyboardSettings.keyboardHeightPercent = (float) screenHeightPercent; } private void setNotification(boolean visible) { final String ACTION = "org.pocketworkstation.pckeyboard.SHOW"; final int ID = 1; String ns = Context.NOTIFICATION_SERVICE; NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns); if (visible && mNotificationReceiver == null) { int icon = R.drawable.icon; CharSequence text = "Keyboard notification enabled."; long when = System.currentTimeMillis(); Notification notification = new Notification(icon, text, when); // TODO: clean this up? mNotificationReceiver = new NotificationReceiver(this); final IntentFilter pFilter = new IntentFilter(ACTION); registerReceiver(mNotificationReceiver, pFilter); Intent notificationIntent = new Intent(ACTION); PendingIntent contentIntent = PendingIntent.getBroadcast(getApplicationContext(), 1, notificationIntent, 0); //PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); String title = "Show Hacker's Keyboard"; String body = "Select this to open the keyboard. Disable in settings."; notification.flags |= Notification.FLAG_ONGOING_EVENT | Notification.FLAG_NO_CLEAR; notification.setLatestEventInfo(getApplicationContext(), title, body, contentIntent); mNotificationManager.notify(ID, notification); } else if (mNotificationReceiver != null) { mNotificationManager.cancel(ID); unregisterReceiver(mNotificationReceiver); mNotificationReceiver = null; } } private boolean isPortrait() { return (mOrientation == Configuration.ORIENTATION_PORTRAIT); } private boolean suggestionsDisabled() { if (mSuggestionForceOff) return true; if (mSuggestionForceOn) return false; return !(mSuggestionsInLandscape || isPortrait()); } /** * Loads a dictionary or multiple separated dictionary * * @return returns array of dictionary resource ids */ /* package */static int[] getDictionary(Resources res) { String packageName = LatinIME.class.getPackage().getName(); XmlResourceParser xrp = res.getXml(R.xml.dictionary); ArrayList<Integer> dictionaries = new ArrayList<Integer>(); try { int current = xrp.getEventType(); while (current != XmlResourceParser.END_DOCUMENT) { if (current == XmlResourceParser.START_TAG) { String tag = xrp.getName(); if (tag != null) { if (tag.equals("part")) { String dictFileName = xrp.getAttributeValue(null, "name"); dictionaries.add(res.getIdentifier(dictFileName, "raw", packageName)); } } } xrp.next(); current = xrp.getEventType(); } } catch (XmlPullParserException e) { Log.e(TAG, "Dictionary XML parsing failure"); } catch (IOException e) { Log.e(TAG, "Dictionary XML IOException"); } int count = dictionaries.size(); int[] dict = new int[count]; for (int i = 0; i < count; i++) { dict[i] = dictionaries.get(i); } return dict; } private void initSuggest(String locale) { mInputLocale = locale; Resources orig = getResources(); Configuration conf = orig.getConfiguration(); Locale saveLocale = conf.locale; conf.locale = new Locale(locale); orig.updateConfiguration(conf, orig.getDisplayMetrics()); if (mSuggest != null) { mSuggest.close(); } SharedPreferences sp = PreferenceManager .getDefaultSharedPreferences(this); mQuickFixes = sp.getBoolean(PREF_QUICK_FIXES, getResources() .getBoolean(R.bool.default_quick_fixes)); int[] dictionaries = getDictionary(orig); mSuggest = new Suggest(this, dictionaries); updateAutoTextEnabled(saveLocale); if (mUserDictionary != null) mUserDictionary.close(); mUserDictionary = new UserDictionary(this, mInputLocale); if (mContactsDictionary == null) { mContactsDictionary = new ContactsDictionary(this, Suggest.DIC_CONTACTS); } if (mAutoDictionary != null) { mAutoDictionary.close(); } mAutoDictionary = new AutoDictionary(this, this, mInputLocale, Suggest.DIC_AUTO); if (mUserBigramDictionary != null) { mUserBigramDictionary.close(); } mUserBigramDictionary = new UserBigramDictionary(this, this, mInputLocale, Suggest.DIC_USER); mSuggest.setUserBigramDictionary(mUserBigramDictionary); mSuggest.setUserDictionary(mUserDictionary); mSuggest.setContactsDictionary(mContactsDictionary); mSuggest.setAutoDictionary(mAutoDictionary); updateCorrectionMode(); mWordSeparators = mResources.getString(R.string.word_separators); mSentenceSeparators = mResources .getString(R.string.sentence_separators); initSuggestPuncList(); conf.locale = saveLocale; orig.updateConfiguration(conf, orig.getDisplayMetrics()); } @Override public void onDestroy() { if (mUserDictionary != null) { mUserDictionary.close(); } if (mContactsDictionary != null) { mContactsDictionary.close(); } unregisterReceiver(mReceiver); unregisterReceiver(mPluginManager); if (mNotificationReceiver != null) { unregisterReceiver(mNotificationReceiver); mNotificationReceiver = null; } if (VOICE_INSTALLED && mVoiceInput != null) { mVoiceInput.destroy(); } LatinImeLogger.commit(); LatinImeLogger.onDestroy(); super.onDestroy(); } @Override public void onConfigurationChanged(Configuration conf) { Log.i("PCKeyboard", "onConfigurationChanged()"); // If the system locale changes and is different from the saved // locale (mSystemLocale), then reload the input locale list from the // latin ime settings (shared prefs) and reset the input locale // to the first one. final String systemLocale = conf.locale.toString(); if (!TextUtils.equals(systemLocale, mSystemLocale)) { mSystemLocale = systemLocale; if (mLanguageSwitcher != null) { mLanguageSwitcher.loadLocales(PreferenceManager .getDefaultSharedPreferences(this)); mLanguageSwitcher.setSystemLocale(conf.locale); toggleLanguage(true, true); } else { reloadKeyboards(); } } // If orientation changed while predicting, commit the change if (conf.orientation != mOrientation) { InputConnection ic = getCurrentInputConnection(); commitTyped(ic, true); if (ic != null) ic.finishComposingText(); // For voice input mOrientation = conf.orientation; reloadKeyboards(); removeCandidateViewContainer(); } mConfigurationChanging = true; super.onConfigurationChanged(conf); if (mRecognizing) { switchToRecognitionStatusView(); } mConfigurationChanging = false; } @Override public View onCreateInputView() { setCandidatesViewShown(false); // Workaround for "already has a parent" when reconfiguring mKeyboardSwitcher.recreateInputView(); mKeyboardSwitcher.makeKeyboards(true); mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_TEXT, 0, shouldShowVoiceButton(makeFieldContext(), getCurrentInputEditorInfo())); return mKeyboardSwitcher.getInputView(); } @Override public AbstractInputMethodImpl onCreateInputMethodInterface() { return new MyInputMethodImpl(); } IBinder mToken; public class MyInputMethodImpl extends InputMethodImpl { @Override public void attachToken(IBinder token) { super.attachToken(token); Log.i(TAG, "attachToken " + token); if (mToken == null) { mToken = token; } } } @Override public View onCreateCandidatesView() { //Log.i(TAG, "onCreateCandidatesView(), mCandidateViewContainer=" + mCandidateViewContainer); //mKeyboardSwitcher.makeKeyboards(true); if (mCandidateViewContainer == null) { mCandidateViewContainer = (LinearLayout) getLayoutInflater().inflate( R.layout.candidates, null); mCandidateView = (CandidateView) mCandidateViewContainer .findViewById(R.id.candidates); mCandidateView.setPadding(0, 0, 0, 0); mCandidateView.setService(this); setCandidatesView(mCandidateViewContainer); } return mCandidateViewContainer; } private void removeCandidateViewContainer() { //Log.i(TAG, "removeCandidateViewContainer(), mCandidateViewContainer=" + mCandidateViewContainer); if (mCandidateViewContainer != null) { mCandidateViewContainer.removeAllViews(); ViewParent parent = mCandidateViewContainer.getParent(); if (parent != null && parent instanceof ViewGroup) { ((ViewGroup) parent).removeView(mCandidateViewContainer); } mCandidateViewContainer = null; mCandidateView = null; } resetPrediction(); } private void resetPrediction() { mComposing.setLength(0); mPredicting = false; mDeleteCount = 0; mJustAddedAutoSpace = false; } @Override public void onStartInputView(EditorInfo attribute, boolean restarting) { sKeyboardSettings.editorPackageName = attribute.packageName; sKeyboardSettings.editorFieldName = attribute.fieldName; sKeyboardSettings.editorFieldId = attribute.fieldId; sKeyboardSettings.editorInputType = attribute.inputType; //Log.i("PCKeyboard", "onStartInputView " + attribute + ", inputType= " + Integer.toHexString(attribute.inputType) + ", restarting=" + restarting); LatinKeyboardView inputView = mKeyboardSwitcher.getInputView(); // In landscape mode, this method gets called without the input view // being created. if (inputView == null) { return; } if (mRefreshKeyboardRequired) { mRefreshKeyboardRequired = false; toggleLanguage(true, true); } mKeyboardSwitcher.makeKeyboards(false); TextEntryState.newSession(this); // Most such things we decide below in the switch statement, but we need to know // now whether this is a password text field, because we need to know now (before // the switch statement) whether we want to enable the voice button. mPasswordText = false; int variation = attribute.inputType & EditorInfo.TYPE_MASK_VARIATION; if (variation == EditorInfo.TYPE_TEXT_VARIATION_PASSWORD || variation == EditorInfo.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD || variation == 0xe0 /* EditorInfo.TYPE_TEXT_VARIATION_WEB_PASSWORD */ ) { if ((attribute.inputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_TEXT) { mPasswordText = true; } } mEnableVoiceButton = shouldShowVoiceButton(makeFieldContext(), attribute); final boolean enableVoiceButton = mEnableVoiceButton && mEnableVoice; mAfterVoiceInput = false; mImmediatelyAfterVoiceInput = false; mShowingVoiceSuggestions = false; mVoiceInputHighlighted = false; mInputTypeNoAutoCorrect = false; mPredictionOnForMode = false; mCompletionOn = false; mCompletions = null; mModCtrl = false; mModAlt = false; mModFn = false; mEnteredText = null; mSuggestionForceOn = false; mSuggestionForceOff = false; mKeyboardModeOverridePortrait = 0; mKeyboardModeOverrideLandscape = 0; sKeyboardSettings.useExtension = false; switch (attribute.inputType & EditorInfo.TYPE_MASK_CLASS) { case EditorInfo.TYPE_CLASS_NUMBER: case EditorInfo.TYPE_CLASS_DATETIME: // fall through // NOTE: For now, we use the phone keyboard for NUMBER and DATETIME // until we get // a dedicated number entry keypad. // TODO: Use a dedicated number entry keypad here when we get one. case EditorInfo.TYPE_CLASS_PHONE: mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_PHONE, attribute.imeOptions, enableVoiceButton); break; case EditorInfo.TYPE_CLASS_TEXT: mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_TEXT, attribute.imeOptions, enableVoiceButton); // startPrediction(); mPredictionOnForMode = true; // Make sure that passwords are not displayed in candidate view if (mPasswordText) { mPredictionOnForMode = false; } if (variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_ADDRESS || variation == EditorInfo.TYPE_TEXT_VARIATION_PERSON_NAME || !mLanguageSwitcher.allowAutoSpace()) { mAutoSpace = false; } else { mAutoSpace = true; } if (variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_ADDRESS) { mPredictionOnForMode = false; mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_EMAIL, attribute.imeOptions, enableVoiceButton); } else if (variation == EditorInfo.TYPE_TEXT_VARIATION_URI) { mPredictionOnForMode = false; mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_URL, attribute.imeOptions, enableVoiceButton); } else if (variation == EditorInfo.TYPE_TEXT_VARIATION_SHORT_MESSAGE) { mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_IM, attribute.imeOptions, enableVoiceButton); } else if (variation == EditorInfo.TYPE_TEXT_VARIATION_FILTER) { mPredictionOnForMode = false; } else if (variation == EditorInfo.TYPE_TEXT_VARIATION_WEB_EDIT_TEXT) { mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_WEB, attribute.imeOptions, enableVoiceButton); // If it's a browser edit field and auto correct is not ON // explicitly, then // disable auto correction, but keep suggestions on. if ((attribute.inputType & EditorInfo.TYPE_TEXT_FLAG_AUTO_CORRECT) == 0) { mInputTypeNoAutoCorrect = true; } } // If NO_SUGGESTIONS is set, don't do prediction. if ((attribute.inputType & EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS) != 0) { mPredictionOnForMode = false; mInputTypeNoAutoCorrect = true; } // If it's not multiline and the autoCorrect flag is not set, then // don't correct if ((attribute.inputType & EditorInfo.TYPE_TEXT_FLAG_AUTO_CORRECT) == 0 && (attribute.inputType & EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE) == 0) { mInputTypeNoAutoCorrect = true; } if ((attribute.inputType & EditorInfo.TYPE_TEXT_FLAG_AUTO_COMPLETE) != 0) { mPredictionOnForMode = false; mCompletionOn = isFullscreenMode(); } break; default: mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_TEXT, attribute.imeOptions, enableVoiceButton); } inputView.closing(); resetPrediction(); loadSettings(); updateShiftKeyState(attribute); mPredictionOnPref = (mCorrectionMode > 0 || mShowSuggestions); setCandidatesViewShownInternal(isCandidateStripVisible() || mCompletionOn, false /* needsInputViewShown */); updateSuggestions(); // If the dictionary is not big enough, don't auto correct mHasDictionary = mSuggest.hasMainDictionary(); updateCorrectionMode(); inputView.setPreviewEnabled(mPopupOn); inputView.setProximityCorrectionEnabled(true); // If we just entered a text field, maybe it has some old text that // requires correction checkReCorrectionOnStart(); checkTutorial(attribute.privateImeOptions); if (TRACE) Debug.startMethodTracing("/data/trace/latinime"); } private void checkReCorrectionOnStart() { if (mReCorrectionEnabled && isPredictionOn()) { // First get the cursor position. This is required by // setOldSuggestions(), so that // it can pass the correct range to setComposingRegion(). At this // point, we don't // have valid values for mLastSelectionStart/Stop because // onUpdateSelection() has // not been called yet. InputConnection ic = getCurrentInputConnection(); if (ic == null) return; ExtractedTextRequest etr = new ExtractedTextRequest(); etr.token = 0; // anything is fine here ExtractedText et = ic.getExtractedText(etr, 0); if (et == null) return; mLastSelectionStart = et.startOffset + et.selectionStart; mLastSelectionEnd = et.startOffset + et.selectionEnd; // Then look for possible corrections in a delayed fashion if (!TextUtils.isEmpty(et.text) && isCursorTouchingWord()) { postUpdateOldSuggestions(); } } } @Override public void onFinishInput() { super.onFinishInput(); LatinImeLogger.commit(); onAutoCompletionStateChanged(false); if (VOICE_INSTALLED && !mConfigurationChanging) { if (mAfterVoiceInput) { mVoiceInput.flushAllTextModificationCounters(); mVoiceInput.logInputEnded(); } mVoiceInput.flushLogs(); mVoiceInput.cancel(); } if (mKeyboardSwitcher.getInputView() != null) { mKeyboardSwitcher.getInputView().closing(); } if (mAutoDictionary != null) mAutoDictionary.flushPendingWrites(); if (mUserBigramDictionary != null) mUserBigramDictionary.flushPendingWrites(); } @Override public void onFinishInputView(boolean finishingInput) { super.onFinishInputView(finishingInput); // Remove penging messages related to update suggestions mHandler.removeMessages(MSG_UPDATE_SUGGESTIONS); mHandler.removeMessages(MSG_UPDATE_OLD_SUGGESTIONS); } @Override public void onUpdateExtractedText(int token, ExtractedText text) { super.onUpdateExtractedText(token, text); InputConnection ic = getCurrentInputConnection(); if (!mImmediatelyAfterVoiceInput && mAfterVoiceInput && ic != null) { if (mHints.showPunctuationHintIfNecessary(ic)) { mVoiceInput.logPunctuationHintDisplayed(); } } mImmediatelyAfterVoiceInput = false; } @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 (DEBUG) { Log.i(TAG, "onUpdateSelection: oss=" + oldSelStart + ", ose=" + oldSelEnd + ", nss=" + newSelStart + ", nse=" + newSelEnd + ", cs=" + candidatesStart + ", ce=" + candidatesEnd); } if (mAfterVoiceInput) { mVoiceInput.setCursorPos(newSelEnd); mVoiceInput.setSelectionSpan(newSelEnd - newSelStart); } // If the current selection in the text view changes, we should // clear whatever candidate text we have. if ((((mComposing.length() > 0 && mPredicting) || mVoiceInputHighlighted) && (newSelStart != candidatesEnd || newSelEnd != candidatesEnd) && mLastSelectionStart != newSelStart)) { mComposing.setLength(0); mPredicting = false; postUpdateSuggestions(); TextEntryState.reset(); InputConnection ic = getCurrentInputConnection(); if (ic != null) { ic.finishComposingText(); } mVoiceInputHighlighted = false; } else if (!mPredicting && !mJustAccepted) { switch (TextEntryState.getState()) { case ACCEPTED_DEFAULT: TextEntryState.reset(); // fall through case SPACE_AFTER_PICKED: mJustAddedAutoSpace = false; // The user moved the cursor. break; } } mJustAccepted = false; postUpdateShiftKeyState(); // Make a note of the cursor position mLastSelectionStart = newSelStart; mLastSelectionEnd = newSelEnd; if (mReCorrectionEnabled) { // Don't look for corrections if the keyboard is not visible if (mKeyboardSwitcher != null && mKeyboardSwitcher.getInputView() != null && mKeyboardSwitcher.getInputView().isShown()) { // Check if we should go in or out of correction mode. if (isPredictionOn() && mJustRevertedSeparator == null && (candidatesStart == candidatesEnd || newSelStart != oldSelStart || TextEntryState .isCorrecting()) && (newSelStart < newSelEnd - 1 || (!mPredicting)) && !mVoiceInputHighlighted) { if (isCursorTouchingWord() || mLastSelectionStart < mLastSelectionEnd) { postUpdateOldSuggestions(); } else { abortCorrection(false); // Show the punctuation suggestions list if the current // one is not // and if not showing "Touch again to save". if (mCandidateView != null && !mSuggestPuncList.equals(mCandidateView .getSuggestions()) && !mCandidateView .isShowingAddToDictionaryHint()) { setNextSuggestions(); } } } } } } /** * This is called when the user has clicked on the extracted text view, when * running in fullscreen mode. The default implementation hides the * candidates view when this happens, but only if the extracted text editor * has a vertical scroll bar because its text doesn't fit. Here we override * the behavior due to the possibility that a re-correction could cause the * candidate strip to disappear and re-appear. */ @Override public void onExtractedTextClicked() { if (mReCorrectionEnabled && isPredictionOn()) return; super.onExtractedTextClicked(); } /** * This is called when the user has performed a cursor movement in the * extracted text view, when it is running in fullscreen mode. The default * implementation hides the candidates view when a vertical movement * happens, but only if the extracted text editor has a vertical scroll bar * because its text doesn't fit. Here we override the behavior due to the * possibility that a re-correction could cause the candidate strip to * disappear and re-appear. */ @Override public void onExtractedCursorMovement(int dx, int dy) { if (mReCorrectionEnabled && isPredictionOn()) return; super.onExtractedCursorMovement(dx, dy); } @Override public void hideWindow() { LatinImeLogger.commit(); onAutoCompletionStateChanged(false); if (TRACE) Debug.stopMethodTracing(); if (mOptionsDialog != null && mOptionsDialog.isShowing()) { mOptionsDialog.dismiss(); mOptionsDialog = null; } if (!mConfigurationChanging) { if (mAfterVoiceInput) mVoiceInput.logInputEnded(); if (mVoiceWarningDialog != null && mVoiceWarningDialog.isShowing()) { mVoiceInput.logKeyboardWarningDialogDismissed(); mVoiceWarningDialog.dismiss(); mVoiceWarningDialog = null; } if (VOICE_INSTALLED & mRecognizing) { mVoiceInput.cancel(); } } mWordToSuggestions.clear(); mWordHistory.clear(); super.hideWindow(); TextEntryState.endSession(); } @Override public void onDisplayCompletions(CompletionInfo[] completions) { if (DEBUG) { Log.i("foo", "Received completions:"); for (int i = 0; i < (completions != null ? completions.length : 0); i++) { Log.i("foo", " #" + i + ": " + completions[i]); } } if (mCompletionOn) { mCompletions = completions; if (completions == null) { clearSuggestions(); return; } List<CharSequence> stringList = new ArrayList<CharSequence>(); for (int i = 0; i < (completions != null ? completions.length : 0); i++) { CompletionInfo ci = completions[i]; if (ci != null) stringList.add(ci.getText()); } // When in fullscreen mode, show completions generated by the // application setSuggestions(stringList, true, true, true); mBestWord = null; setCandidatesViewShown(true); } } private void setCandidatesViewShownInternal(boolean shown, boolean needsInputViewShown) { // Log.i(TAG, "setCandidatesViewShownInternal(" + shown + ", " + needsInputViewShown + // " mCompletionOn=" + mCompletionOn + // " mPredictionOnForMode=" + mPredictionOnForMode + // " mPredictionOnPref=" + mPredictionOnPref + // " mPredicting=" + mPredicting // ); // TODO: Remove this if we support candidates with hard keyboard boolean visible = shown && onEvaluateInputViewShown() && mKeyboardSwitcher.getInputView() != null && isPredictionOn() && (needsInputViewShown ? mKeyboardSwitcher.getInputView().isShown() : true); if (visible) { if (mCandidateViewContainer == null) { onCreateCandidatesView(); setNextSuggestions(); } } else { if (mCandidateViewContainer != null) { removeCandidateViewContainer(); commitTyped(getCurrentInputConnection(), true); } } super.setCandidatesViewShown(visible); } @Override public void onFinishCandidatesView(boolean finishingInput) { //Log.i(TAG, "onFinishCandidatesView(), mCandidateViewContainer=" + mCandidateViewContainer); super.onFinishCandidatesView(finishingInput); if (mCandidateViewContainer != null) { removeCandidateViewContainer(); } } @Override public boolean onEvaluateInputViewShown() { boolean parent = super.onEvaluateInputViewShown(); boolean wanted = mForceKeyboardOn || parent; //Log.i(TAG, "OnEvaluateInputViewShown, parent=" + parent + " + " wanted=" + wanted); return wanted; } @Override public void setCandidatesViewShown(boolean shown) { setCandidatesViewShownInternal(shown, true /* needsInputViewShown */); } @Override public void onComputeInsets(InputMethodService.Insets outInsets) { super.onComputeInsets(outInsets); if (!isFullscreenMode()) { outInsets.contentTopInsets = outInsets.visibleTopInsets; } } @Override public boolean onEvaluateFullscreenMode() { DisplayMetrics dm = getResources().getDisplayMetrics(); float displayHeight = dm.heightPixels; // If the display is more than X inches high, don't go to fullscreen // mode float dimen = getResources().getDimension( R.dimen.max_height_for_fullscreen); if (displayHeight > dimen || mFullscreenOverride || isConnectbot()) { return false; } else { return super.onEvaluateFullscreenMode(); } } public boolean isKeyboardVisible() { return (mKeyboardSwitcher != null && mKeyboardSwitcher.getInputView() != null && mKeyboardSwitcher.getInputView().isShown()); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_BACK: if (event.getRepeatCount() == 0 && mKeyboardSwitcher.getInputView() != null) { if (mKeyboardSwitcher.getInputView().handleBack()) { return true; } else if (mTutorial != null) { mTutorial.close(); mTutorial = null; } } break; case KeyEvent.KEYCODE_DPAD_DOWN: case KeyEvent.KEYCODE_DPAD_UP: case KeyEvent.KEYCODE_DPAD_LEFT: case KeyEvent.KEYCODE_DPAD_RIGHT: // If tutorial is visible, don't allow dpad to work if (mTutorial != null) { return true; } break; case KeyEvent.KEYCODE_VOLUME_UP: if (!mVolUpAction.equals("none") && isKeyboardVisible()) { return true; } break; case KeyEvent.KEYCODE_VOLUME_DOWN: if (!mVolDownAction.equals("none") && isKeyboardVisible()) { return true; } break; } return super.onKeyDown(keyCode, event); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_DPAD_DOWN: case KeyEvent.KEYCODE_DPAD_UP: case KeyEvent.KEYCODE_DPAD_LEFT: case KeyEvent.KEYCODE_DPAD_RIGHT: // If tutorial is visible, don't allow dpad to work if (mTutorial != null) { return true; } LatinKeyboardView inputView = mKeyboardSwitcher.getInputView(); // Enable shift key and DPAD to do selections if (inputView != null && inputView.isShown() && inputView.getShiftState() == Keyboard.SHIFT_ON) { event = new KeyEvent(event.getDownTime(), event.getEventTime(), event.getAction(), event.getKeyCode(), event .getRepeatCount(), event.getDeviceId(), event .getScanCode(), KeyEvent.META_SHIFT_LEFT_ON | KeyEvent.META_SHIFT_ON); InputConnection ic = getCurrentInputConnection(); if (ic != null) ic.sendKeyEvent(event); return true; } break; case KeyEvent.KEYCODE_VOLUME_UP: if (!mVolUpAction.equals("none") && isKeyboardVisible()) { return doSwipeAction(mVolUpAction); } break; case KeyEvent.KEYCODE_VOLUME_DOWN: if (!mVolDownAction.equals("none") && isKeyboardVisible()) { return doSwipeAction(mVolDownAction); } break; } return super.onKeyUp(keyCode, event); } private void revertVoiceInput() { InputConnection ic = getCurrentInputConnection(); if (ic != null) ic.commitText("", 1); updateSuggestions(); mVoiceInputHighlighted = false; } private void commitVoiceInput() { InputConnection ic = getCurrentInputConnection(); if (ic != null) ic.finishComposingText(); updateSuggestions(); mVoiceInputHighlighted = false; } private void reloadKeyboards() { mKeyboardSwitcher.setLanguageSwitcher(mLanguageSwitcher); if (mKeyboardSwitcher.getInputView() != null && mKeyboardSwitcher.getKeyboardMode() != KeyboardSwitcher.MODE_NONE) { mKeyboardSwitcher.setVoiceMode(mEnableVoice && mEnableVoiceButton, mVoiceOnPrimary); } updateKeyboardOptions(); mKeyboardSwitcher.makeKeyboards(true); } private void commitTyped(InputConnection inputConnection, boolean manual) { if (mPredicting) { mPredicting = false; if (mComposing.length() > 0) { if (inputConnection != null) { inputConnection.commitText(mComposing, 1); } mCommittedLength = mComposing.length(); if (manual) { TextEntryState.manualTyped(mComposing); } else { TextEntryState.acceptedTyped(mComposing); } addToDictionaries(mComposing, AutoDictionary.FREQUENCY_FOR_TYPED); } updateSuggestions(); } } private void postUpdateShiftKeyState() { // TODO(klausw): disabling, I have no idea what this is supposed to accomplish. // //updateShiftKeyState(getCurrentInputEditorInfo()); // // // FIXME: why the delay? // mHandler.removeMessages(MSG_UPDATE_SHIFT_STATE); // // TODO: Should remove this 300ms delay? // mHandler.sendMessageDelayed(mHandler // .obtainMessage(MSG_UPDATE_SHIFT_STATE), 300); } public void updateShiftKeyState(EditorInfo attr) { InputConnection ic = getCurrentInputConnection(); if (ic != null && attr != null && mKeyboardSwitcher.isAlphabetMode()) { int oldState = getShiftState(); boolean isShifted = mShiftKeyState.isMomentary(); boolean isCapsLock = (oldState == Keyboard.SHIFT_CAPS_LOCKED || oldState == Keyboard.SHIFT_LOCKED); boolean isCaps = isCapsLock || getCursorCapsMode(ic, attr) != 0; //Log.i(TAG, "updateShiftKeyState isShifted=" + isShifted + " isCaps=" + isCaps + " isMomentary=" + mShiftKeyState.isMomentary() + " cursorCaps=" + getCursorCapsMode(ic, attr)); int newState = Keyboard.SHIFT_OFF; if (isShifted) { newState = (mSavedShiftState == Keyboard.SHIFT_LOCKED) ? Keyboard.SHIFT_CAPS : Keyboard.SHIFT_ON; } else if (isCaps) { newState = isCapsLock ? getCapsOrShiftLockState() : Keyboard.SHIFT_CAPS; } //Log.i(TAG, "updateShiftKeyState " + oldState + " -> " + newState); mKeyboardSwitcher.setShiftState(newState); } if (ic != null) { // Clear modifiers other than shift, to avoid them getting stuck int states = KeyEvent.META_ALT_ON | KeyEvent.META_ALT_LEFT_ON | KeyEvent.META_ALT_RIGHT_ON | 0x8 // KeyEvent.META_FUNCTION_ON; | 0x7000 // KeyEvent.META_CTRL_MASK | 0x70000 // KeyEvent.META_META_MASK | KeyEvent.META_SYM_ON; ic.clearMetaKeyStates(states); } } private int getShiftState() { if (mKeyboardSwitcher != null) { LatinKeyboardView view = mKeyboardSwitcher.getInputView(); if (view != null) { return view.getShiftState(); } } return Keyboard.SHIFT_OFF; } private boolean isShiftCapsMode() { if (mKeyboardSwitcher != null) { LatinKeyboardView view = mKeyboardSwitcher.getInputView(); if (view != null) { return view.isShiftCaps(); } } return false; } private int getCursorCapsMode(InputConnection ic, EditorInfo attr) { int caps = 0; EditorInfo ei = getCurrentInputEditorInfo(); if (mAutoCapActive && ei != null && ei.inputType != EditorInfo.TYPE_NULL) { caps = ic.getCursorCapsMode(attr.inputType); } return caps; } private void swapPunctuationAndSpace() { final InputConnection ic = getCurrentInputConnection(); if (ic == null) return; CharSequence lastTwo = ic.getTextBeforeCursor(2, 0); if (lastTwo != null && lastTwo.length() == 2 && lastTwo.charAt(0) == ASCII_SPACE && isSentenceSeparator(lastTwo.charAt(1))) { ic.beginBatchEdit(); ic.deleteSurroundingText(2, 0); ic.commitText(lastTwo.charAt(1) + " ", 1); ic.endBatchEdit(); updateShiftKeyState(getCurrentInputEditorInfo()); mJustAddedAutoSpace = true; } } private void reswapPeriodAndSpace() { final InputConnection ic = getCurrentInputConnection(); if (ic == null) return; CharSequence lastThree = ic.getTextBeforeCursor(3, 0); if (lastThree != null && lastThree.length() == 3 && lastThree.charAt(0) == ASCII_PERIOD && lastThree.charAt(1) == ASCII_SPACE && lastThree.charAt(2) == ASCII_PERIOD) { ic.beginBatchEdit(); ic.deleteSurroundingText(3, 0); ic.commitText(" ..", 1); ic.endBatchEdit(); updateShiftKeyState(getCurrentInputEditorInfo()); } } private void doubleSpace() { // if (!mAutoPunctuate) return; if (mCorrectionMode == Suggest.CORRECTION_NONE) return; final InputConnection ic = getCurrentInputConnection(); if (ic == null) return; CharSequence lastThree = ic.getTextBeforeCursor(3, 0); if (lastThree != null && lastThree.length() == 3 && Character.isLetterOrDigit(lastThree.charAt(0)) && lastThree.charAt(1) == ASCII_SPACE && lastThree.charAt(2) == ASCII_SPACE) { ic.beginBatchEdit(); ic.deleteSurroundingText(2, 0); ic.commitText(". ", 1); ic.endBatchEdit(); updateShiftKeyState(getCurrentInputEditorInfo()); mJustAddedAutoSpace = true; } } private void maybeRemovePreviousPeriod(CharSequence text) { final InputConnection ic = getCurrentInputConnection(); if (ic == null || text.length() == 0) return; // When the text's first character is '.', remove the previous period // if there is one. CharSequence lastOne = ic.getTextBeforeCursor(1, 0); if (lastOne != null && lastOne.length() == 1 && lastOne.charAt(0) == ASCII_PERIOD && text.charAt(0) == ASCII_PERIOD) { ic.deleteSurroundingText(1, 0); } } private void removeTrailingSpace() { final InputConnection ic = getCurrentInputConnection(); if (ic == null) return; CharSequence lastOne = ic.getTextBeforeCursor(1, 0); if (lastOne != null && lastOne.length() == 1 && lastOne.charAt(0) == ASCII_SPACE) { ic.deleteSurroundingText(1, 0); } } public boolean addWordToDictionary(String word) { mUserDictionary.addWord(word, 128); // Suggestion strip should be updated after the operation of adding word // to the // user dictionary postUpdateSuggestions(); return true; } private boolean isAlphabet(int code) { if (Character.isLetter(code)) { return true; } else { return false; } } private void showInputMethodPicker() { ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)) .showInputMethodPicker(); } private void onOptionKeyPressed() { if (!isShowingOptionDialog()) { showOptionsMenu(); } } private void onOptionKeyLongPressed() { if (!isShowingOptionDialog()) { showInputMethodPicker(); } } private boolean isShowingOptionDialog() { return mOptionsDialog != null && mOptionsDialog.isShowing(); } private boolean isConnectbot() { EditorInfo ei = getCurrentInputEditorInfo(); String pkg = ei.packageName; if (ei == null || pkg == null) return false; return ((pkg.equalsIgnoreCase("org.connectbot") || pkg.equalsIgnoreCase("org.woltage.irssiconnectbot") || pkg.equalsIgnoreCase("com.pslib.connectbot") || pkg.equalsIgnoreCase("sk.vx.connectbot") ) && ei.inputType == 0); // FIXME } private int getMetaState(boolean shifted) { int meta = 0; if (shifted) meta |= KeyEvent.META_SHIFT_ON | KeyEvent.META_SHIFT_LEFT_ON; if (mModCtrl) meta |= 0x3000; // KeyEvent.META_CTRL_ON | KeyEvent.META_CTRL_LEFT_ON; if (mModAlt) meta |= 0x30000; // KeyEvent.META_ALT_ON | KeyEvent.META_ALT_LEFT_ON; return meta; } private void sendKeyDown(InputConnection ic, int key, int meta) { long now = System.currentTimeMillis(); if (ic != null) ic.sendKeyEvent(new KeyEvent( now, now, KeyEvent.ACTION_DOWN, key, 0, meta)); } private void sendKeyUp(InputConnection ic, int key, int meta) { long now = System.currentTimeMillis(); if (ic != null) ic.sendKeyEvent(new KeyEvent( now, now, KeyEvent.ACTION_UP, key, 0, meta)); } private void sendModifiedKeyDownUp(int key, boolean shifted) { InputConnection ic = getCurrentInputConnection(); int meta = getMetaState(shifted); sendModifierKeysDown(shifted); sendKeyDown(ic, key, meta); sendKeyUp(ic, key, meta); sendModifierKeysUp(shifted); } private boolean isShiftMod() { if (mShiftKeyState.isMomentary()) return true; if (mKeyboardSwitcher != null) { LatinKeyboardView kb = mKeyboardSwitcher.getInputView(); if (kb != null) return kb.isShiftAll(); } return false; } private boolean delayChordingCtrlModifier() { return sKeyboardSettings.chordingCtrlKey == 0; } private boolean delayChordingAltModifier() { return sKeyboardSettings.chordingAltKey == 0; } private void sendModifiedKeyDownUp(int key) { sendModifiedKeyDownUp(key, isShiftMod()); } private void sendShiftKey(InputConnection ic, boolean isDown) { int key = KeyEvent.KEYCODE_SHIFT_LEFT; int meta = KeyEvent.META_SHIFT_ON | KeyEvent.META_SHIFT_LEFT_ON; if (isDown) { sendKeyDown(ic, key, meta); } else { sendKeyUp(ic, key, meta); } } private void sendCtrlKey(InputConnection ic, boolean isDown, boolean chording) { if (chording && delayChordingCtrlModifier()) return; int key = sKeyboardSettings.chordingCtrlKey; if (key == 0) key = 113; // KeyEvent.KEYCODE_CTRL_LEFT int meta = 0x3000; // KeyEvent.META_CTRL_ON | KeyEvent.META_CTRL_LEFT_ON if (isDown) { sendKeyDown(ic, key, meta); } else { sendKeyUp(ic, key, meta); } } private void sendAltKey(InputConnection ic, boolean isDown, boolean chording) { if (chording && delayChordingAltModifier()) return; int key = sKeyboardSettings.chordingAltKey; if (key == 0) key = 57; // KeyEvent.KEYCODE_ALT_LEFT int meta = 0x30000; // KeyEvent.META_ALT_ON | KeyEvent.META_ALT_LEFT_ON if (isDown) { sendKeyDown(ic, key, meta); } else { sendKeyUp(ic, key, meta); } } private void sendModifierKeysDown(boolean shifted) { InputConnection ic = getCurrentInputConnection(); if (shifted) { //Log.i(TAG, "send SHIFT down"); sendShiftKey(ic, true); } if (mModCtrl && (!mCtrlKeyState.isMomentary() || delayChordingCtrlModifier())) { sendCtrlKey(ic, true, false); } if (mModAlt && (!mAltKeyState.isMomentary() || delayChordingAltModifier())) { sendAltKey(ic, true, false); } } private void handleModifierKeysUp(boolean shifted, boolean sendKey) { InputConnection ic = getCurrentInputConnection(); if (mModAlt && !mAltKeyState.isMomentary()) { if (sendKey) sendAltKey(ic, false, false); setModAlt(false); } if (mModCtrl && !mCtrlKeyState.isMomentary()) { if (sendKey) sendCtrlKey(ic, false, false); setModCtrl(false); } if (shifted) { //Log.i(TAG, "send SHIFT up"); if (sendKey) sendShiftKey(ic, false); int shiftState = getShiftState(); if (!(mShiftKeyState.isMomentary() || shiftState == Keyboard.SHIFT_LOCKED)) { resetShift(); } } } private void sendModifierKeysUp(boolean shifted) { handleModifierKeysUp(shifted, true); } private void sendSpecialKey(int code) { if (!isConnectbot()) { commitTyped(getCurrentInputConnection(), true); sendModifiedKeyDownUp(code); return; } // TODO(klausw): properly support xterm sequences for Ctrl/Alt modifiers? // See http://slackware.osuosl.org/slackware-12.0/source/l/ncurses/xterm.terminfo // and the output of "$ infocmp -1L". Support multiple sets, and optional // true numpad keys? if (ESC_SEQUENCES == null) { ESC_SEQUENCES = new HashMap<Integer, String>(); CTRL_SEQUENCES = new HashMap<Integer, Integer>(); // VT escape sequences without leading Escape ESC_SEQUENCES.put(-LatinKeyboardView.KEYCODE_HOME, "[1~"); ESC_SEQUENCES.put(-LatinKeyboardView.KEYCODE_END, "[4~"); ESC_SEQUENCES.put(-LatinKeyboardView.KEYCODE_PAGE_UP, "[5~"); ESC_SEQUENCES.put(-LatinKeyboardView.KEYCODE_PAGE_DOWN, "[6~"); ESC_SEQUENCES.put(-LatinKeyboardView.KEYCODE_FKEY_F1, "OP"); ESC_SEQUENCES.put(-LatinKeyboardView.KEYCODE_FKEY_F2, "OQ"); ESC_SEQUENCES.put(-LatinKeyboardView.KEYCODE_FKEY_F3, "OR"); ESC_SEQUENCES.put(-LatinKeyboardView.KEYCODE_FKEY_F4, "OS"); ESC_SEQUENCES.put(-LatinKeyboardView.KEYCODE_FKEY_F5, "[15~"); ESC_SEQUENCES.put(-LatinKeyboardView.KEYCODE_FKEY_F6, "[17~"); ESC_SEQUENCES.put(-LatinKeyboardView.KEYCODE_FKEY_F7, "[18~"); ESC_SEQUENCES.put(-LatinKeyboardView.KEYCODE_FKEY_F8, "[19~"); ESC_SEQUENCES.put(-LatinKeyboardView.KEYCODE_FKEY_F9, "[20~"); ESC_SEQUENCES.put(-LatinKeyboardView.KEYCODE_FKEY_F10, "[21~"); ESC_SEQUENCES.put(-LatinKeyboardView.KEYCODE_FKEY_F11, "[23~"); ESC_SEQUENCES.put(-LatinKeyboardView.KEYCODE_FKEY_F12, "[24~"); ESC_SEQUENCES.put(-LatinKeyboardView.KEYCODE_FORWARD_DEL, "[3~"); ESC_SEQUENCES.put(-LatinKeyboardView.KEYCODE_INSERT, "[2~"); // Special ConnectBot hack: Ctrl-1 to Ctrl-0 for F1-F10. CTRL_SEQUENCES.put(-LatinKeyboardView.KEYCODE_FKEY_F1, KeyEvent.KEYCODE_1); CTRL_SEQUENCES.put(-LatinKeyboardView.KEYCODE_FKEY_F2, KeyEvent.KEYCODE_2); CTRL_SEQUENCES.put(-LatinKeyboardView.KEYCODE_FKEY_F3, KeyEvent.KEYCODE_3); CTRL_SEQUENCES.put(-LatinKeyboardView.KEYCODE_FKEY_F4, KeyEvent.KEYCODE_4); CTRL_SEQUENCES.put(-LatinKeyboardView.KEYCODE_FKEY_F5, KeyEvent.KEYCODE_5); CTRL_SEQUENCES.put(-LatinKeyboardView.KEYCODE_FKEY_F6, KeyEvent.KEYCODE_6); CTRL_SEQUENCES.put(-LatinKeyboardView.KEYCODE_FKEY_F7, KeyEvent.KEYCODE_7); CTRL_SEQUENCES.put(-LatinKeyboardView.KEYCODE_FKEY_F8, KeyEvent.KEYCODE_8); CTRL_SEQUENCES.put(-LatinKeyboardView.KEYCODE_FKEY_F9, KeyEvent.KEYCODE_9); CTRL_SEQUENCES.put(-LatinKeyboardView.KEYCODE_FKEY_F10, KeyEvent.KEYCODE_0); // Natively supported by ConnectBot // ESC_SEQUENCES.put(-LatinKeyboardView.KEYCODE_DPAD_UP, "OA"); // ESC_SEQUENCES.put(-LatinKeyboardView.KEYCODE_DPAD_DOWN, "OB"); // ESC_SEQUENCES.put(-LatinKeyboardView.KEYCODE_DPAD_LEFT, "OD"); // ESC_SEQUENCES.put(-LatinKeyboardView.KEYCODE_DPAD_RIGHT, "OC"); // No VT equivalents? // ESC_SEQUENCES.put(-LatinKeyboardView.KEYCODE_DPAD_CENTER, ""); // ESC_SEQUENCES.put(-LatinKeyboardView.KEYCODE_SYSRQ, ""); // ESC_SEQUENCES.put(-LatinKeyboardView.KEYCODE_BREAK, ""); // ESC_SEQUENCES.put(-LatinKeyboardView.KEYCODE_NUM_LOCK, ""); // ESC_SEQUENCES.put(-LatinKeyboardView.KEYCODE_SCROLL_LOCK, ""); } InputConnection ic = getCurrentInputConnection(); Integer ctrlseq = null; if (mConnectbotTabHack) { ctrlseq = CTRL_SEQUENCES.get(code); } String seq = ESC_SEQUENCES.get(code); if (ctrlseq != null) { if (mModAlt) { // send ESC prefix for "Meta" ic.commitText(Character.toString((char) 27), 1); } ic.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER)); ic.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER)); ic.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, ctrlseq)); ic.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, ctrlseq)); } else if (seq != null) { if (mModAlt) { // send ESC prefix for "Meta" ic.commitText(Character.toString((char) 27), 1); } // send ESC prefix of escape sequence ic.commitText(Character.toString((char) 27), 1); ic.commitText(seq, 1); } else { // send key code, let connectbot handle it sendDownUpKeyEvents(code); } handleModifierKeysUp(false, false); } private final static int asciiToKeyCode[] = new int[127]; private final static int KF_MASK = 0xffff; private final static int KF_SHIFTABLE = 0x10000; private final static int KF_UPPER = 0x20000; private final static int KF_LETTER = 0x40000; { // Include RETURN in this set even though it's not printable. // Most other non-printable keys get handled elsewhere. asciiToKeyCode['\n'] = KeyEvent.KEYCODE_ENTER | KF_SHIFTABLE; // Non-alphanumeric ASCII codes which have their own keys // (on some keyboards) asciiToKeyCode[' '] = KeyEvent.KEYCODE_SPACE | KF_SHIFTABLE; //asciiToKeyCode['!'] = KeyEvent.KEYCODE_; //asciiToKeyCode['"'] = KeyEvent.KEYCODE_; asciiToKeyCode['#'] = KeyEvent.KEYCODE_POUND; //asciiToKeyCode['$'] = KeyEvent.KEYCODE_; //asciiToKeyCode['%'] = KeyEvent.KEYCODE_; //asciiToKeyCode['&'] = KeyEvent.KEYCODE_; asciiToKeyCode['\''] = KeyEvent.KEYCODE_APOSTROPHE; //asciiToKeyCode['('] = KeyEvent.KEYCODE_; //asciiToKeyCode[')'] = KeyEvent.KEYCODE_; asciiToKeyCode['*'] = KeyEvent.KEYCODE_STAR; asciiToKeyCode['+'] = KeyEvent.KEYCODE_PLUS; asciiToKeyCode[','] = KeyEvent.KEYCODE_COMMA; asciiToKeyCode['-'] = KeyEvent.KEYCODE_MINUS; asciiToKeyCode['.'] = KeyEvent.KEYCODE_PERIOD; asciiToKeyCode['/'] = KeyEvent.KEYCODE_SLASH; //asciiToKeyCode[':'] = KeyEvent.KEYCODE_; asciiToKeyCode[';'] = KeyEvent.KEYCODE_SEMICOLON; //asciiToKeyCode['<'] = KeyEvent.KEYCODE_; asciiToKeyCode['='] = KeyEvent.KEYCODE_EQUALS; //asciiToKeyCode['>'] = KeyEvent.KEYCODE_; //asciiToKeyCode['?'] = KeyEvent.KEYCODE_; asciiToKeyCode['@'] = KeyEvent.KEYCODE_AT; asciiToKeyCode['['] = KeyEvent.KEYCODE_LEFT_BRACKET; asciiToKeyCode['\\'] = KeyEvent.KEYCODE_BACKSLASH; asciiToKeyCode[']'] = KeyEvent.KEYCODE_RIGHT_BRACKET; //asciiToKeyCode['^'] = KeyEvent.KEYCODE_; //asciiToKeyCode['_'] = KeyEvent.KEYCODE_; asciiToKeyCode['`'] = KeyEvent.KEYCODE_GRAVE; //asciiToKeyCode['{'] = KeyEvent.KEYCODE_; //asciiToKeyCode['|'] = KeyEvent.KEYCODE_; //asciiToKeyCode['}'] = KeyEvent.KEYCODE_; //asciiToKeyCode['~'] = KeyEvent.KEYCODE_; for (int i = 0; i <= 25; ++i) { asciiToKeyCode['a' + i] = KeyEvent.KEYCODE_A + i | KF_LETTER; asciiToKeyCode['A' + i] = KeyEvent.KEYCODE_A + i | KF_UPPER | KF_LETTER; } for (int i = 0; i <= 9; ++i) { asciiToKeyCode['0' + i] = KeyEvent.KEYCODE_0 + i; } } public void sendModifiableKeyChar(char ch) { // Support modified key events boolean modShift = isShiftMod(); if ((modShift || mModCtrl || mModAlt) && ch > 0 && ch < 127) { InputConnection ic = getCurrentInputConnection(); if (isConnectbot()) { if (mModAlt) { // send ESC prefix ic.commitText(Character.toString((char) 27), 1); } if (mModCtrl) { int code = ch & 31; if (code == 9) { sendTab(); } else { ic.commitText(Character.toString((char) code), 1); } } else { ic.commitText(Character.toString(ch), 1); } handleModifierKeysUp(false, false); return; } // Non-ConnectBot // Restrict Shift modifier to ENTER and SPACE, supporting Shift-Enter etc. // Note that most special keys such as DEL or cursor keys aren't handled // by this charcode-based method. int combinedCode = asciiToKeyCode[ch]; if (combinedCode > 0) { int code = combinedCode & KF_MASK; boolean shiftable = (combinedCode & KF_SHIFTABLE) > 0; boolean upper = (combinedCode & KF_UPPER) > 0; boolean letter = (combinedCode & KF_LETTER) > 0; boolean shifted = modShift && (upper || shiftable); if (letter && !mModCtrl && !mModAlt) { // Try workaround for issue 179 where letters don't get upcased ic.commitText(Character.toString(ch), 1); handleModifierKeysUp(false, false); } else { sendModifiedKeyDownUp(code, shifted); } return; } } if (ch >= '0' && ch <= '9') { //WIP InputConnection ic = getCurrentInputConnection(); ic.clearMetaKeyStates(KeyEvent.META_SHIFT_ON | KeyEvent.META_ALT_ON | KeyEvent.META_SYM_ON); //EditorInfo ei = getCurrentInputEditorInfo(); //Log.i(TAG, "capsmode=" + ic.getCursorCapsMode(ei.inputType)); //sendModifiedKeyDownUp(KeyEvent.KEYCODE_0 + ch - '0'); //return; } // Default handling for anything else, including unmodified ENTER and SPACE. sendKeyChar(ch); } private void sendTab() { InputConnection ic = getCurrentInputConnection(); boolean tabHack = isConnectbot() && mConnectbotTabHack; // FIXME: tab and ^I don't work in connectbot, hackish workaround if (tabHack) { if (mModAlt) { // send ESC prefix ic.commitText(Character.toString((char) 27), 1); } ic.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER)); ic.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER)); ic.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_I)); ic.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_I)); } else { sendModifiedKeyDownUp(KeyEvent.KEYCODE_TAB); } } private void sendEscape() { if (isConnectbot()) { sendKeyChar((char) 27); } else { sendModifiedKeyDownUp(111 /*KeyEvent.KEYCODE_ESCAPE */); } } private boolean processMultiKey(int primaryCode) { if (mDeadAccentBuffer.composeBuffer.length() > 0) { //Log.i(TAG, "processMultiKey: pending DeadAccent, length=" + mDeadAccentBuffer.composeBuffer.length()); mDeadAccentBuffer.execute(primaryCode); mDeadAccentBuffer.clear(); return true; } if (mComposeMode) { mComposeMode = mComposeBuffer.execute(primaryCode); return true; } return false; } // Implementation of KeyboardViewListener public void onKey(int primaryCode, int[] keyCodes, int x, int y) { long when = SystemClock.uptimeMillis(); if (primaryCode != Keyboard.KEYCODE_DELETE || when > mLastKeyTime + QUICK_PRESS) { mDeleteCount = 0; } mLastKeyTime = when; final boolean distinctMultiTouch = mKeyboardSwitcher .hasDistinctMultitouch(); switch (primaryCode) { case Keyboard.KEYCODE_DELETE: if (processMultiKey(primaryCode)) { break; } handleBackspace(); mDeleteCount++; LatinImeLogger.logOnDelete(); break; case Keyboard.KEYCODE_SHIFT: // Shift key is handled in onPress() when device has distinct // multi-touch panel. if (!distinctMultiTouch) handleShift(); break; case Keyboard.KEYCODE_MODE_CHANGE: // Symbol key is handled in onPress() when device has distinct // multi-touch panel. if (!distinctMultiTouch) changeKeyboardMode(); break; case LatinKeyboardView.KEYCODE_CTRL_LEFT: // Ctrl key is handled in onPress() when device has distinct // multi-touch panel. if (!distinctMultiTouch) setModCtrl(!mModCtrl); break; case LatinKeyboardView.KEYCODE_ALT_LEFT: // Alt key is handled in onPress() when device has distinct // multi-touch panel. if (!distinctMultiTouch) setModAlt(!mModAlt); break; case LatinKeyboardView.KEYCODE_FN: if (!distinctMultiTouch) setModFn(!mModFn); break; case Keyboard.KEYCODE_CANCEL: if (!isShowingOptionDialog()) { handleClose(); } break; case LatinKeyboardView.KEYCODE_OPTIONS: onOptionKeyPressed(); break; case LatinKeyboardView.KEYCODE_OPTIONS_LONGPRESS: onOptionKeyLongPressed(); break; case LatinKeyboardView.KEYCODE_COMPOSE: mComposeMode = !mComposeMode; mComposeBuffer.clear(); break; case LatinKeyboardView.KEYCODE_NEXT_LANGUAGE: toggleLanguage(false, true); break; case LatinKeyboardView.KEYCODE_PREV_LANGUAGE: toggleLanguage(false, false); break; case LatinKeyboardView.KEYCODE_VOICE: if (VOICE_INSTALLED) { startListening(false /* was a button press, was not a swipe */); } break; case 9 /* Tab */: if (processMultiKey(primaryCode)) { break; } sendTab(); break; case LatinKeyboardView.KEYCODE_ESCAPE: if (processMultiKey(primaryCode)) { break; } sendEscape(); break; case LatinKeyboardView.KEYCODE_DPAD_UP: case LatinKeyboardView.KEYCODE_DPAD_DOWN: case LatinKeyboardView.KEYCODE_DPAD_LEFT: case LatinKeyboardView.KEYCODE_DPAD_RIGHT: case LatinKeyboardView.KEYCODE_DPAD_CENTER: case LatinKeyboardView.KEYCODE_HOME: case LatinKeyboardView.KEYCODE_END: case LatinKeyboardView.KEYCODE_PAGE_UP: case LatinKeyboardView.KEYCODE_PAGE_DOWN: case LatinKeyboardView.KEYCODE_FKEY_F1: case LatinKeyboardView.KEYCODE_FKEY_F2: case LatinKeyboardView.KEYCODE_FKEY_F3: case LatinKeyboardView.KEYCODE_FKEY_F4: case LatinKeyboardView.KEYCODE_FKEY_F5: case LatinKeyboardView.KEYCODE_FKEY_F6: case LatinKeyboardView.KEYCODE_FKEY_F7: case LatinKeyboardView.KEYCODE_FKEY_F8: case LatinKeyboardView.KEYCODE_FKEY_F9: case LatinKeyboardView.KEYCODE_FKEY_F10: case LatinKeyboardView.KEYCODE_FKEY_F11: case LatinKeyboardView.KEYCODE_FKEY_F12: case LatinKeyboardView.KEYCODE_FORWARD_DEL: case LatinKeyboardView.KEYCODE_INSERT: case LatinKeyboardView.KEYCODE_SYSRQ: case LatinKeyboardView.KEYCODE_BREAK: case LatinKeyboardView.KEYCODE_NUM_LOCK: case LatinKeyboardView.KEYCODE_SCROLL_LOCK: if (processMultiKey(primaryCode)) { break; } // send as plain keys, or as escape sequence if needed sendSpecialKey(-primaryCode); break; default: if (!mComposeMode && mDeadKeysActive && Character.getType(primaryCode) == Character.NON_SPACING_MARK) { //Log.i(TAG, "possible dead character: " + primaryCode); if (!mDeadAccentBuffer.execute(primaryCode)) { //Log.i(TAG, "double dead key"); break; // pressing a dead key twice produces spacing equivalent } updateShiftKeyState(getCurrentInputEditorInfo()); break; } if (processMultiKey(primaryCode)) { break; } if (primaryCode != ASCII_ENTER) { mJustAddedAutoSpace = false; } RingCharBuffer.getInstance().push((char) primaryCode, x, y); LatinImeLogger.logOnInputChar(); if (isWordSeparator(primaryCode)) { handleSeparator(primaryCode); } else { handleCharacter(primaryCode, keyCodes); } // Cancel the just reverted state mJustRevertedSeparator = null; } mKeyboardSwitcher.onKey(primaryCode); // Reset after any single keystroke mEnteredText = null; //mDeadAccentBuffer.clear(); // FIXME } public void onText(CharSequence text) { if (VOICE_INSTALLED && mVoiceInputHighlighted) { commitVoiceInput(); } //mDeadAccentBuffer.clear(); // FIXME InputConnection ic = getCurrentInputConnection(); if (ic == null) return; abortCorrection(false); ic.beginBatchEdit(); if (mPredicting) { commitTyped(ic, true); } maybeRemovePreviousPeriod(text); ic.commitText(text, 1); ic.endBatchEdit(); updateShiftKeyState(getCurrentInputEditorInfo()); mKeyboardSwitcher.onKey(0); // dummy key code. mJustRevertedSeparator = null; mJustAddedAutoSpace = false; mEnteredText = text; } public void onCancel() { // User released a finger outside any key mKeyboardSwitcher.onCancelInput(); } private void handleBackspace() { if (VOICE_INSTALLED && mVoiceInputHighlighted) { mVoiceInput .incrementTextModificationDeleteCount(mVoiceResults.candidates .get(0).toString().length()); revertVoiceInput(); return; } boolean deleteChar = false; InputConnection ic = getCurrentInputConnection(); if (ic == null) return; ic.beginBatchEdit(); if (mAfterVoiceInput) { // Don't log delete if the user is pressing delete at // the beginning of the text box (hence not deleting anything) if (mVoiceInput.getCursorPos() > 0) { // If anything was selected before the delete was pressed, // increment the // delete count by the length of the selection int deleteLen = mVoiceInput.getSelectionSpan() > 0 ? mVoiceInput .getSelectionSpan() : 1; mVoiceInput.incrementTextModificationDeleteCount(deleteLen); } } if (mPredicting) { final int length = mComposing.length(); if (length > 0) { mComposing.delete(length - 1, length); mWord.deleteLast(); ic.setComposingText(mComposing, 1); if (mComposing.length() == 0) { mPredicting = false; } postUpdateSuggestions(); } else { ic.deleteSurroundingText(1, 0); } } else { deleteChar = true; } postUpdateShiftKeyState(); TextEntryState.backspace(); if (TextEntryState.getState() == TextEntryState.State.UNDO_COMMIT) { revertLastWord(deleteChar); ic.endBatchEdit(); return; } else if (mEnteredText != null && sameAsTextBeforeCursor(ic, mEnteredText)) { ic.deleteSurroundingText(mEnteredText.length(), 0); } else if (deleteChar) { if (mCandidateView != null && mCandidateView.dismissAddToDictionaryHint()) { // Go back to the suggestion mode if the user canceled the // "Touch again to save". // NOTE: In gerenal, we don't revert the word when backspacing // from a manual suggestion pick. We deliberately chose a // different behavior only in the case of picking the first // suggestion (typed word). It's intentional to have made this // inconsistent with backspacing after selecting other // suggestions. revertLastWord(deleteChar); } else { sendDownUpKeyEvents(KeyEvent.KEYCODE_DEL); if (mDeleteCount > DELETE_ACCELERATE_AT) { sendDownUpKeyEvents(KeyEvent.KEYCODE_DEL); } } } mJustRevertedSeparator = null; ic.endBatchEdit(); } private void setModCtrl(boolean val) { // Log.i("LatinIME", "setModCtrl "+ mModCtrl + "->" + val + ", momentary=" + mCtrlKeyState.isMomentary()); mKeyboardSwitcher.setCtrlIndicator(val); mModCtrl = val; } private void setModAlt(boolean val) { // Log.i("LatinIME", "setModAlt "+ mModAlt + "->" + val + ", momentary=" + mAltKeyState.isMomentary()); mKeyboardSwitcher.setAltIndicator(val); mModAlt = val; } private void setModFn(boolean val) { //Log.i("LatinIME", "setModFn " + mModFn + "->" + val + ", momentary=" + mFnKeyState.isMomentary()); mModFn = val; mKeyboardSwitcher.setFn(val); mKeyboardSwitcher.setCtrlIndicator(mModCtrl); mKeyboardSwitcher.setAltIndicator(mModAlt); } private void startMultitouchShift() { int newState = Keyboard.SHIFT_ON; if (mKeyboardSwitcher.isAlphabetMode()) { mSavedShiftState = getShiftState(); if (mSavedShiftState == Keyboard.SHIFT_LOCKED) newState = Keyboard.SHIFT_CAPS; } handleShiftInternal(true, newState); } private void commitMultitouchShift() { if (mKeyboardSwitcher.isAlphabetMode()) { int newState = nextShiftState(mSavedShiftState, true); handleShiftInternal(true, newState); } else { // do nothing, keyboard is already flipped } } private void resetMultitouchShift() { int newState = Keyboard.SHIFT_OFF; if (mSavedShiftState == Keyboard.SHIFT_CAPS_LOCKED || mSavedShiftState == Keyboard.SHIFT_LOCKED) { newState = mSavedShiftState; } handleShiftInternal(true, newState); } private void resetShift() { handleShiftInternal(true, Keyboard.SHIFT_OFF); } private void handleShift() { handleShiftInternal(false, -1); } private static int getCapsOrShiftLockState() { return sKeyboardSettings.capsLock ? Keyboard.SHIFT_CAPS_LOCKED : Keyboard.SHIFT_LOCKED; } // Rotate through shift states by successively pressing and releasing the Shift key. private static int nextShiftState(int prevState, boolean allowCapsLock) { if (allowCapsLock) { if (prevState == Keyboard.SHIFT_OFF) { return Keyboard.SHIFT_ON; } else if (prevState == Keyboard.SHIFT_ON) { return getCapsOrShiftLockState(); } else { return Keyboard.SHIFT_OFF; } } else { // currently unused, see toggleShift() if (prevState == Keyboard.SHIFT_OFF) { return Keyboard.SHIFT_ON; } else { return Keyboard.SHIFT_OFF; } } } private void handleShiftInternal(boolean forceState, int newState) { //Log.i(TAG, "handleShiftInternal forceNormal=" + forceNormal); mHandler.removeMessages(MSG_UPDATE_SHIFT_STATE); KeyboardSwitcher switcher = mKeyboardSwitcher; if (switcher.isAlphabetMode()) { if (forceState) { switcher.setShiftState(newState); } else { switcher.setShiftState(nextShiftState(getShiftState(), true)); } } else { switcher.toggleShift(); } } private void abortCorrection(boolean force) { if (force || TextEntryState.isCorrecting()) { getCurrentInputConnection().finishComposingText(); clearSuggestions(); } } private void handleCharacter(int primaryCode, int[] keyCodes) { if (VOICE_INSTALLED && mVoiceInputHighlighted) { commitVoiceInput(); } if (mAfterVoiceInput) { // Assume input length is 1. This assumption fails for smiley face // insertions. mVoiceInput.incrementTextModificationInsertCount(1); } if (mLastSelectionStart == mLastSelectionEnd && TextEntryState.isCorrecting()) { abortCorrection(false); } if (isAlphabet(primaryCode) && isPredictionOn() && !mModCtrl && !mModAlt && !isCursorTouchingWord()) { if (!mPredicting) { mPredicting = true; mComposing.setLength(0); saveWordInHistory(mBestWord); mWord.reset(); } } if (mModCtrl || mModAlt) { commitTyped(getCurrentInputConnection(), true); // sets mPredicting=false } if (mPredicting) { if (isShiftCapsMode() && mKeyboardSwitcher.isAlphabetMode() && mComposing.length() == 0) { // Show suggestions with initial caps if starting out shifted, // could be either auto-caps or manual shift. mWord.setFirstCharCapitalized(true); } mComposing.append((char) primaryCode); mWord.add(primaryCode, keyCodes); InputConnection ic = getCurrentInputConnection(); if (ic != null) { // If it's the first letter, make note of auto-caps state if (mWord.size() == 1) { mWord.setAutoCapitalized(getCursorCapsMode(ic, getCurrentInputEditorInfo()) != 0); } ic.setComposingText(mComposing, 1); } postUpdateSuggestions(); } else { sendModifiableKeyChar((char) primaryCode); } updateShiftKeyState(getCurrentInputEditorInfo()); if (LatinIME.PERF_DEBUG) measureCps(); TextEntryState.typedCharacter((char) primaryCode, isWordSeparator(primaryCode)); } private void handleSeparator(int primaryCode) { if (VOICE_INSTALLED && mVoiceInputHighlighted) { commitVoiceInput(); } if (mAfterVoiceInput) { // Assume input length is 1. This assumption fails for smiley face // insertions. mVoiceInput.incrementTextModificationInsertPunctuationCount(1); } // Should dismiss the "Touch again to save" message when handling // separator if (mCandidateView != null && mCandidateView.dismissAddToDictionaryHint()) { postUpdateSuggestions(); } boolean pickedDefault = false; // Handle separator InputConnection ic = getCurrentInputConnection(); if (ic != null) { ic.beginBatchEdit(); abortCorrection(false); } if (mPredicting) { // In certain languages where single quote is a separator, it's // better // not to auto correct, but accept the typed word. For instance, // in Italian dov' should not be expanded to dove' because the // elision // requires the last vowel to be removed. if (mAutoCorrectOn && primaryCode != '\'' && (mJustRevertedSeparator == null || mJustRevertedSeparator.length() == 0 || mJustRevertedSeparator.charAt(0) != primaryCode)) { pickedDefault = pickDefaultSuggestion(); // Picked the suggestion by the space key. We consider this // as "added an auto space" in autocomplete mode, but as manually // typed space in "quick fixes" mode. if (primaryCode == ASCII_SPACE) { if (mAutoCorrectEnabled) { mJustAddedAutoSpace = true; } else { TextEntryState.manualTyped(""); } } } else { commitTyped(ic, true); } } if (mJustAddedAutoSpace && primaryCode == ASCII_ENTER) { removeTrailingSpace(); mJustAddedAutoSpace = false; } sendModifiableKeyChar((char) primaryCode); // Handle the case of ". ." -> " .." with auto-space if necessary // before changing the TextEntryState. if (TextEntryState.getState() == TextEntryState.State.PUNCTUATION_AFTER_ACCEPTED && primaryCode == ASCII_PERIOD) { reswapPeriodAndSpace(); } TextEntryState.typedCharacter((char) primaryCode, true); if (TextEntryState.getState() == TextEntryState.State.PUNCTUATION_AFTER_ACCEPTED && primaryCode != ASCII_ENTER) { swapPunctuationAndSpace(); } else if (isPredictionOn() && primaryCode == ASCII_SPACE) { doubleSpace(); } if (pickedDefault) { TextEntryState.backToAcceptedDefault(mWord.getTypedWord()); } updateShiftKeyState(getCurrentInputEditorInfo()); if (ic != null) { ic.endBatchEdit(); } } private void handleClose() { commitTyped(getCurrentInputConnection(), true); if (VOICE_INSTALLED & mRecognizing) { mVoiceInput.cancel(); } requestHideSelf(0); if (mKeyboardSwitcher != null) { LatinKeyboardView inputView = mKeyboardSwitcher.getInputView(); if (inputView != null) { inputView.closing(); } } TextEntryState.endSession(); } private void saveWordInHistory(CharSequence result) { if (mWord.size() <= 1) { mWord.reset(); return; } // Skip if result is null. It happens in some edge case. if (TextUtils.isEmpty(result)) { return; } // Make a copy of the CharSequence, since it is/could be a mutable // CharSequence final String resultCopy = result.toString(); TypedWordAlternatives entry = new TypedWordAlternatives(resultCopy, new WordComposer(mWord)); mWordHistory.add(entry); } private void postUpdateSuggestions() { mHandler.removeMessages(MSG_UPDATE_SUGGESTIONS); mHandler.sendMessageDelayed(mHandler .obtainMessage(MSG_UPDATE_SUGGESTIONS), 100); } private void postUpdateOldSuggestions() { mHandler.removeMessages(MSG_UPDATE_OLD_SUGGESTIONS); mHandler.sendMessageDelayed(mHandler .obtainMessage(MSG_UPDATE_OLD_SUGGESTIONS), 300); } private boolean isPredictionOn() { return mPredictionOnForMode && isPredictionWanted(); } private boolean isPredictionWanted() { return (mShowSuggestions || mSuggestionForceOn) && !suggestionsDisabled(); } private boolean isCandidateStripVisible() { return isPredictionOn(); } public void onCancelVoice() { if (mRecognizing) { switchToKeyboardView(); } } private void switchToKeyboardView() { mHandler.post(new Runnable() { public void run() { mRecognizing = false; LatinKeyboardView view = mKeyboardSwitcher.getInputView(); if (view != null) { ViewParent p = view.getParent(); if (p != null && p instanceof ViewGroup) { ((ViewGroup) p).removeView(view); } setInputView(mKeyboardSwitcher.getInputView()); } setCandidatesViewShown(true); updateInputViewShown(); postUpdateSuggestions(); } }); } private void switchToRecognitionStatusView() { final boolean configChanged = mConfigurationChanging; mHandler.post(new Runnable() { public void run() { setCandidatesViewShown(false); mRecognizing = true; View v = mVoiceInput.getView(); ViewParent p = v.getParent(); if (p != null && p instanceof ViewGroup) { ((ViewGroup) v.getParent()).removeView(v); } setInputView(v); updateInputViewShown(); if (configChanged) { mVoiceInput.onConfigurationChanged(); } } }); } private void startListening(boolean swipe) { if (!mHasUsedVoiceInput || (!mLocaleSupportedForVoiceInput && !mHasUsedVoiceInputUnsupportedLocale)) { // Calls reallyStartListening if user clicks OK, does nothing if // user clicks Cancel. showVoiceWarningDialog(swipe); } else { reallyStartListening(swipe); } } private void reallyStartListening(boolean swipe) { if (!mHasUsedVoiceInput) { // The user has started a voice input, so remember that in the // future (so we don't show the warning dialog after the first run). SharedPreferences.Editor editor = PreferenceManager .getDefaultSharedPreferences(this).edit(); editor.putBoolean(PREF_HAS_USED_VOICE_INPUT, true); SharedPreferencesCompat.apply(editor); mHasUsedVoiceInput = true; } if (!mLocaleSupportedForVoiceInput && !mHasUsedVoiceInputUnsupportedLocale) { // The user has started a voice input from an unsupported locale, so // remember that // in the future (so we don't show the warning dialog the next time // they do this). SharedPreferences.Editor editor = PreferenceManager .getDefaultSharedPreferences(this).edit(); editor.putBoolean(PREF_HAS_USED_VOICE_INPUT_UNSUPPORTED_LOCALE, true); SharedPreferencesCompat.apply(editor); mHasUsedVoiceInputUnsupportedLocale = true; } // Clear N-best suggestions clearSuggestions(); FieldContext context = new FieldContext(getCurrentInputConnection(), getCurrentInputEditorInfo(), mLanguageSwitcher .getInputLanguage(), mLanguageSwitcher .getEnabledLanguages()); mVoiceInput.startListening(context, swipe); switchToRecognitionStatusView(); } private void showVoiceWarningDialog(final boolean swipe) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setCancelable(true); builder.setIcon(R.drawable.ic_mic_dialog); builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { mVoiceInput.logKeyboardWarningDialogOk(); reallyStartListening(swipe); } }); builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { mVoiceInput.logKeyboardWarningDialogCancel(); } }); if (mLocaleSupportedForVoiceInput) { String message = getString(R.string.voice_warning_may_not_understand) + "\n\n" + getString(R.string.voice_warning_how_to_turn_off); builder.setMessage(message); } else { String message = getString(R.string.voice_warning_locale_not_supported) + "\n\n" + getString(R.string.voice_warning_may_not_understand) + "\n\n" + getString(R.string.voice_warning_how_to_turn_off); builder.setMessage(message); } builder.setTitle(R.string.voice_warning_title); mVoiceWarningDialog = builder.create(); Window window = mVoiceWarningDialog.getWindow(); WindowManager.LayoutParams lp = window.getAttributes(); lp.token = mKeyboardSwitcher.getInputView().getWindowToken(); lp.type = WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG; window.setAttributes(lp); window.addFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM); mVoiceInput.logKeyboardWarningDialogShown(); mVoiceWarningDialog.show(); } public void onVoiceResults(List<String> candidates, Map<String, List<CharSequence>> alternatives) { if (!mRecognizing) { return; } mVoiceResults.candidates = candidates; mVoiceResults.alternatives = alternatives; mHandler.sendMessage(mHandler.obtainMessage(MSG_VOICE_RESULTS)); } private void handleVoiceResults() { mAfterVoiceInput = true; mImmediatelyAfterVoiceInput = true; InputConnection ic = getCurrentInputConnection(); if (!isFullscreenMode()) { // Start listening for updates to the text from typing, etc. if (ic != null) { ExtractedTextRequest req = new ExtractedTextRequest(); ic.getExtractedText(req, InputConnection.GET_EXTRACTED_TEXT_MONITOR); } } vibrate(); switchToKeyboardView(); final List<CharSequence> nBest = new ArrayList<CharSequence>(); boolean capitalizeFirstWord = preferCapitalization() || (mKeyboardSwitcher.isAlphabetMode() && isShiftCapsMode() ); for (String c : mVoiceResults.candidates) { if (capitalizeFirstWord) { c = c.substring(0,1).toUpperCase(sKeyboardSettings.inputLocale) + c.substring(1, c.length()); } nBest.add(c); } if (nBest.size() == 0) { return; } String bestResult = nBest.get(0).toString(); mVoiceInput.logVoiceInputDelivered(bestResult.length()); mHints.registerVoiceResult(bestResult); if (ic != null) ic.beginBatchEdit(); // To avoid extra updates on committing older // text commitTyped(ic, false); EditingUtil.appendText(ic, bestResult); if (ic != null) ic.endBatchEdit(); mVoiceInputHighlighted = true; mWordToSuggestions.putAll(mVoiceResults.alternatives); } private void clearSuggestions() { setSuggestions(null, false, false, false); } private void setSuggestions(List<CharSequence> suggestions, boolean completions, boolean typedWordValid, boolean haveMinimalSuggestion) { if (mIsShowingHint) { setCandidatesViewShown(true); mIsShowingHint = false; } if (mCandidateView != null) { mCandidateView.setSuggestions(suggestions, completions, typedWordValid, haveMinimalSuggestion); } } private void updateSuggestions() { LatinKeyboardView inputView = mKeyboardSwitcher.getInputView(); ((LatinKeyboard) inputView.getKeyboard()).setPreferredLetters(null); // Check if we have a suggestion engine attached. if ((mSuggest == null || !isPredictionOn()) && !mVoiceInputHighlighted) { return; } if (!mPredicting) { setNextSuggestions(); return; } showSuggestions(mWord); } private List<CharSequence> getTypedSuggestions(WordComposer word) { List<CharSequence> stringList = mSuggest.getSuggestions( mKeyboardSwitcher.getInputView(), word, false, null); return stringList; } private void showCorrections(WordAlternatives alternatives) { List<CharSequence> stringList = alternatives.getAlternatives(); ((LatinKeyboard) mKeyboardSwitcher.getInputView().getKeyboard()) .setPreferredLetters(null); showSuggestions(stringList, alternatives.getOriginalWord(), false, false); } private void showSuggestions(WordComposer word) { // long startTime = System.currentTimeMillis(); // TIME MEASUREMENT! // TODO Maybe need better way of retrieving previous word CharSequence prevWord = EditingUtil.getPreviousWord( getCurrentInputConnection(), mWordSeparators); List<CharSequence> stringList = mSuggest.getSuggestions( mKeyboardSwitcher.getInputView(), word, false, prevWord); // long stopTime = System.currentTimeMillis(); // TIME MEASUREMENT! // Log.d("LatinIME","Suggest Total Time - " + (stopTime - startTime)); int[] nextLettersFrequencies = mSuggest.getNextLettersFrequencies(); ((LatinKeyboard) mKeyboardSwitcher.getInputView().getKeyboard()) .setPreferredLetters(nextLettersFrequencies); boolean correctionAvailable = !mInputTypeNoAutoCorrect && mSuggest.hasMinimalCorrection(); // || mCorrectionMode == mSuggest.CORRECTION_FULL; CharSequence typedWord = word.getTypedWord(); // If we're in basic correct boolean typedWordValid = mSuggest.isValidWord(typedWord) || (preferCapitalization() && mSuggest.isValidWord(typedWord .toString().toLowerCase())); if (mCorrectionMode == Suggest.CORRECTION_FULL || mCorrectionMode == Suggest.CORRECTION_FULL_BIGRAM) { correctionAvailable |= typedWordValid; } // Don't auto-correct words with multiple capital letter correctionAvailable &= !word.isMostlyCaps(); correctionAvailable &= !TextEntryState.isCorrecting(); showSuggestions(stringList, typedWord, typedWordValid, correctionAvailable); } private void showSuggestions(List<CharSequence> stringList, CharSequence typedWord, boolean typedWordValid, boolean correctionAvailable) { setSuggestions(stringList, false, typedWordValid, correctionAvailable); if (stringList.size() > 0) { if (correctionAvailable && !typedWordValid && stringList.size() > 1) { mBestWord = stringList.get(1); } else { mBestWord = typedWord; } } else { mBestWord = null; } setCandidatesViewShown(isCandidateStripVisible() || mCompletionOn); } private boolean pickDefaultSuggestion() { // Complete any pending candidate query first if (mHandler.hasMessages(MSG_UPDATE_SUGGESTIONS)) { mHandler.removeMessages(MSG_UPDATE_SUGGESTIONS); updateSuggestions(); } if (mBestWord != null && mBestWord.length() > 0) { TextEntryState.acceptedDefault(mWord.getTypedWord(), mBestWord); mJustAccepted = true; pickSuggestion(mBestWord, false); // Add the word to the auto dictionary if it's not a known word addToDictionaries(mBestWord, AutoDictionary.FREQUENCY_FOR_TYPED); return true; } return false; } public void pickSuggestionManually(int index, CharSequence suggestion) { List<CharSequence> suggestions = mCandidateView.getSuggestions(); if (mAfterVoiceInput && mShowingVoiceSuggestions) { mVoiceInput.flushAllTextModificationCounters(); // send this intent AFTER logging any prior aggregated edits. mVoiceInput.logTextModifiedByChooseSuggestion( suggestion.toString(), index, mWordSeparators, getCurrentInputConnection()); } final boolean correcting = TextEntryState.isCorrecting(); InputConnection ic = getCurrentInputConnection(); if (ic != null) { ic.beginBatchEdit(); } if (mCompletionOn && mCompletions != null && index >= 0 && index < mCompletions.length) { CompletionInfo ci = mCompletions[index]; if (ic != null) { ic.commitCompletion(ci); } mCommittedLength = suggestion.length(); if (mCandidateView != null) { mCandidateView.clear(); } updateShiftKeyState(getCurrentInputEditorInfo()); if (ic != null) { ic.endBatchEdit(); } return; } // If this is a punctuation, apply it through the normal key press if (suggestion.length() == 1 && (isWordSeparator(suggestion.charAt(0)) || isSuggestedPunctuation(suggestion .charAt(0)))) { // Word separators are suggested before the user inputs something. // So, LatinImeLogger logs "" as a user's input. LatinImeLogger.logOnManualSuggestion("", suggestion.toString(), index, suggestions); final char primaryCode = suggestion.charAt(0); onKey(primaryCode, new int[] { primaryCode }, LatinKeyboardBaseView.NOT_A_TOUCH_COORDINATE, LatinKeyboardBaseView.NOT_A_TOUCH_COORDINATE); if (ic != null) { ic.endBatchEdit(); } return; } mJustAccepted = true; pickSuggestion(suggestion, correcting); // Add the word to the auto dictionary if it's not a known word if (index == 0) { addToDictionaries(suggestion, AutoDictionary.FREQUENCY_FOR_PICKED); } else { addToBigramDictionary(suggestion, 1); } LatinImeLogger.logOnManualSuggestion(mComposing.toString(), suggestion .toString(), index, suggestions); TextEntryState.acceptedSuggestion(mComposing.toString(), suggestion); // Follow it with a space if (mAutoSpace && !correcting) { sendSpace(); mJustAddedAutoSpace = true; } final boolean showingAddToDictionaryHint = index == 0 && mCorrectionMode > 0 && !mSuggest.isValidWord(suggestion) && !mSuggest.isValidWord(suggestion.toString().toLowerCase()); if (!correcting) { // Fool the state watcher so that a subsequent backspace will not do // a revert, unless // we just did a correction, in which case we need to stay in // TextEntryState.State.PICKED_SUGGESTION state. TextEntryState.typedCharacter((char) ASCII_SPACE, true); setNextSuggestions(); } else if (!showingAddToDictionaryHint) { // If we're not showing the "Touch again to save", then show // corrections again. // In case the cursor position doesn't change, make sure we show the // suggestions again. clearSuggestions(); postUpdateOldSuggestions(); } if (showingAddToDictionaryHint) { mCandidateView.showAddToDictionaryHint(suggestion); } if (ic != null) { ic.endBatchEdit(); } } private void rememberReplacedWord(CharSequence suggestion) { if (mShowingVoiceSuggestions) { // Retain the replaced word in the alternatives array. EditingUtil.Range range = new EditingUtil.Range(); String wordToBeReplaced = EditingUtil.getWordAtCursor( getCurrentInputConnection(), mWordSeparators, range); if (!mWordToSuggestions.containsKey(wordToBeReplaced)) { wordToBeReplaced = wordToBeReplaced.toLowerCase(); } if (mWordToSuggestions.containsKey(wordToBeReplaced)) { List<CharSequence> suggestions = mWordToSuggestions .get(wordToBeReplaced); if (suggestions.contains(suggestion)) { suggestions.remove(suggestion); } suggestions.add(wordToBeReplaced); mWordToSuggestions.remove(wordToBeReplaced); mWordToSuggestions.put(suggestion.toString(), suggestions); } } } /** * Commits the chosen word to the text field and saves it for later * retrieval. * * @param suggestion * the suggestion picked by the user to be committed to the text * field * @param correcting * whether this is due to a correction of an existing word. */ private void pickSuggestion(CharSequence suggestion, boolean correcting) { LatinKeyboardView inputView = mKeyboardSwitcher.getInputView(); int shiftState = getShiftState(); if (shiftState == Keyboard.SHIFT_LOCKED || shiftState == Keyboard.SHIFT_CAPS_LOCKED) { suggestion = suggestion.toString().toUpperCase(); // all UPPERCASE } InputConnection ic = getCurrentInputConnection(); if (ic != null) { rememberReplacedWord(suggestion); ic.commitText(suggestion, 1); } saveWordInHistory(suggestion); mPredicting = false; mCommittedLength = suggestion.length(); ((LatinKeyboard) inputView.getKeyboard()).setPreferredLetters(null); // If we just corrected a word, then don't show punctuations if (!correcting) { setNextSuggestions(); } updateShiftKeyState(getCurrentInputEditorInfo()); } /** * Tries to apply any voice alternatives for the word if this was a spoken * word and there are voice alternatives. * * @param touching * The word that the cursor is touching, with position * information * @return true if an alternative was found, false otherwise. */ private boolean applyVoiceAlternatives(EditingUtil.SelectedWord touching) { // Search for result in spoken word alternatives String selectedWord = touching.word.toString().trim(); if (!mWordToSuggestions.containsKey(selectedWord)) { selectedWord = selectedWord.toLowerCase(); } if (mWordToSuggestions.containsKey(selectedWord)) { mShowingVoiceSuggestions = true; List<CharSequence> suggestions = mWordToSuggestions .get(selectedWord); // If the first letter of touching is capitalized, make all the // suggestions // start with a capital letter. if (Character.isUpperCase(touching.word.charAt(0))) { for (int i = 0; i < suggestions.size(); i++) { String origSugg = (String) suggestions.get(i); String capsSugg = origSugg.toUpperCase().charAt(0) + origSugg.subSequence(1, origSugg.length()) .toString(); suggestions.set(i, capsSugg); } } setSuggestions(suggestions, false, true, true); setCandidatesViewShown(true); return true; } return false; } /** * Tries to apply any typed alternatives for the word if we have any cached * alternatives, otherwise tries to find new corrections and completions for * the word. * * @param touching * The word that the cursor is touching, with position * information * @return true if an alternative was found, false otherwise. */ private boolean applyTypedAlternatives(EditingUtil.SelectedWord touching) { // If we didn't find a match, search for result in typed word history WordComposer foundWord = null; WordAlternatives alternatives = null; for (WordAlternatives entry : mWordHistory) { if (TextUtils.equals(entry.getChosenWord(), touching.word)) { if (entry instanceof TypedWordAlternatives) { foundWord = ((TypedWordAlternatives) entry).word; } alternatives = entry; break; } } // If we didn't find a match, at least suggest completions if (foundWord == null && (mSuggest.isValidWord(touching.word) || mSuggest .isValidWord(touching.word.toString().toLowerCase()))) { foundWord = new WordComposer(); for (int i = 0; i < touching.word.length(); i++) { foundWord.add(touching.word.charAt(i), new int[] { touching.word.charAt(i) }); } foundWord.setFirstCharCapitalized(Character .isUpperCase(touching.word.charAt(0))); } // Found a match, show suggestions if (foundWord != null || alternatives != null) { if (alternatives == null) { alternatives = new TypedWordAlternatives(touching.word, foundWord); } showCorrections(alternatives); if (foundWord != null) { mWord = new WordComposer(foundWord); } else { mWord.reset(); } return true; } return false; } private void setOldSuggestions() { mShowingVoiceSuggestions = false; if (mCandidateView != null && mCandidateView.isShowingAddToDictionaryHint()) { return; } InputConnection ic = getCurrentInputConnection(); if (ic == null) return; if (!mPredicting) { // Extract the selected or touching text EditingUtil.SelectedWord touching = EditingUtil .getWordAtCursorOrSelection(ic, mLastSelectionStart, mLastSelectionEnd, mWordSeparators); if (touching != null && touching.word.length() > 1) { ic.beginBatchEdit(); if (!applyVoiceAlternatives(touching) && !applyTypedAlternatives(touching)) { abortCorrection(true); } else { TextEntryState.selectedForCorrection(); EditingUtil.underlineWord(ic, touching); } ic.endBatchEdit(); } else { abortCorrection(true); setNextSuggestions(); // Show the punctuation suggestions list } } else { abortCorrection(true); } } private void setNextSuggestions() { setSuggestions(mSuggestPuncList, false, false, false); } private void addToDictionaries(CharSequence suggestion, int frequencyDelta) { checkAddToDictionary(suggestion, frequencyDelta, false); } private void addToBigramDictionary(CharSequence suggestion, int frequencyDelta) { checkAddToDictionary(suggestion, frequencyDelta, true); } /** * Adds to the UserBigramDictionary and/or AutoDictionary * * @param addToBigramDictionary * true if it should be added to bigram dictionary if possible */ private void checkAddToDictionary(CharSequence suggestion, int frequencyDelta, boolean addToBigramDictionary) { if (suggestion == null || suggestion.length() < 1) return; // Only auto-add to dictionary if auto-correct is ON. Otherwise we'll be // adding words in situations where the user or application really // didn't // want corrections enabled or learned. if (!(mCorrectionMode == Suggest.CORRECTION_FULL || mCorrectionMode == Suggest.CORRECTION_FULL_BIGRAM)) { return; } if (suggestion != null) { if (!addToBigramDictionary && mAutoDictionary.isValidWord(suggestion) || (!mSuggest.isValidWord(suggestion.toString()) && !mSuggest .isValidWord(suggestion.toString().toLowerCase()))) { mAutoDictionary.addWord(suggestion.toString(), frequencyDelta); } if (mUserBigramDictionary != null) { CharSequence prevWord = EditingUtil.getPreviousWord( getCurrentInputConnection(), mSentenceSeparators); if (!TextUtils.isEmpty(prevWord)) { mUserBigramDictionary.addBigrams(prevWord.toString(), suggestion.toString()); } } } } private boolean isCursorTouchingWord() { InputConnection ic = getCurrentInputConnection(); if (ic == null) return false; CharSequence toLeft = ic.getTextBeforeCursor(1, 0); CharSequence toRight = ic.getTextAfterCursor(1, 0); if (!TextUtils.isEmpty(toLeft) && !isWordSeparator(toLeft.charAt(0)) && !isSuggestedPunctuation(toLeft.charAt(0))) { return true; } if (!TextUtils.isEmpty(toRight) && !isWordSeparator(toRight.charAt(0)) && !isSuggestedPunctuation(toRight.charAt(0))) { return true; } return false; } private boolean sameAsTextBeforeCursor(InputConnection ic, CharSequence text) { CharSequence beforeText = ic.getTextBeforeCursor(text.length(), 0); return TextUtils.equals(text, beforeText); } public void revertLastWord(boolean deleteChar) { final int length = mComposing.length(); if (!mPredicting && length > 0) { final InputConnection ic = getCurrentInputConnection(); mPredicting = true; mJustRevertedSeparator = ic.getTextBeforeCursor(1, 0); if (deleteChar) ic.deleteSurroundingText(1, 0); int toDelete = mCommittedLength; CharSequence toTheLeft = ic .getTextBeforeCursor(mCommittedLength, 0); if (toTheLeft != null && toTheLeft.length() > 0 && isWordSeparator(toTheLeft.charAt(0))) { toDelete--; } ic.deleteSurroundingText(toDelete, 0); ic.setComposingText(mComposing, 1); TextEntryState.backspace(); postUpdateSuggestions(); } else { sendDownUpKeyEvents(KeyEvent.KEYCODE_DEL); mJustRevertedSeparator = null; } } protected String getWordSeparators() { return mWordSeparators; } public boolean isWordSeparator(int code) { String separators = getWordSeparators(); return separators.contains(String.valueOf((char) code)); } private boolean isSentenceSeparator(int code) { return mSentenceSeparators.contains(String.valueOf((char) code)); } private void sendSpace() { sendModifiableKeyChar((char) ASCII_SPACE); updateShiftKeyState(getCurrentInputEditorInfo()); // onKey(KEY_SPACE[0], KEY_SPACE); } public boolean preferCapitalization() { return mWord.isFirstCharCapitalized(); } void toggleLanguage(boolean reset, boolean next) { if (reset) { mLanguageSwitcher.reset(); } else { if (next) { mLanguageSwitcher.next(); } else { mLanguageSwitcher.prev(); } } int currentKeyboardMode = mKeyboardSwitcher.getKeyboardMode(); reloadKeyboards(); mKeyboardSwitcher.makeKeyboards(true); mKeyboardSwitcher.setKeyboardMode(currentKeyboardMode, 0, mEnableVoiceButton && mEnableVoice); initSuggest(mLanguageSwitcher.getInputLanguage()); mLanguageSwitcher.persist(); mAutoCapActive = mAutoCapPref && mLanguageSwitcher.allowAutoCap(); mDeadKeysActive = mLanguageSwitcher.allowDeadKeys(); updateShiftKeyState(getCurrentInputEditorInfo()); setCandidatesViewShown(isPredictionOn()); } public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { Log.i("PCKeyboard", "onSharedPreferenceChanged()"); boolean needReload = false; Resources res = getResources(); // Apply globally handled shared prefs sKeyboardSettings.sharedPreferenceChanged(sharedPreferences, key); if (sKeyboardSettings.hasFlag(GlobalKeyboardSettings.FLAG_PREF_NEED_RELOAD)) { needReload = true; } if (sKeyboardSettings.hasFlag(GlobalKeyboardSettings.FLAG_PREF_NEW_PUNC_LIST)) { initSuggestPuncList(); } if (sKeyboardSettings.hasFlag(GlobalKeyboardSettings.FLAG_PREF_RECREATE_INPUT_VIEW)) { mKeyboardSwitcher.recreateInputView(); } if (sKeyboardSettings.hasFlag(GlobalKeyboardSettings.FLAG_PREF_RESET_MODE_OVERRIDE)) { mKeyboardModeOverrideLandscape = 0; mKeyboardModeOverridePortrait = 0; } if (sKeyboardSettings.hasFlag(GlobalKeyboardSettings.FLAG_PREF_RESET_KEYBOARDS)) { toggleLanguage(true, true); } int unhandledFlags = sKeyboardSettings.unhandledFlags(); if (unhandledFlags != GlobalKeyboardSettings.FLAG_PREF_NONE) { Log.w(TAG, "Not all flag settings handled, remaining=" + unhandledFlags); } if (PREF_SELECTED_LANGUAGES.equals(key)) { mLanguageSwitcher.loadLocales(sharedPreferences); mRefreshKeyboardRequired = true; } else if (PREF_RECORRECTION_ENABLED.equals(key)) { mReCorrectionEnabled = sharedPreferences.getBoolean( PREF_RECORRECTION_ENABLED, res .getBoolean(R.bool.default_recorrection_enabled)); if (mReCorrectionEnabled) { // It doesn't work right on pre-Gingerbread phones. Toast.makeText(getApplicationContext(), res.getString(R.string.recorrect_warning), Toast.LENGTH_LONG) .show(); } } else if (PREF_CONNECTBOT_TAB_HACK.equals(key)) { mConnectbotTabHack = sharedPreferences.getBoolean( PREF_CONNECTBOT_TAB_HACK, res .getBoolean(R.bool.default_connectbot_tab_hack)); } else if (PREF_FULLSCREEN_OVERRIDE.equals(key)) { mFullscreenOverride = sharedPreferences.getBoolean( PREF_FULLSCREEN_OVERRIDE, res .getBoolean(R.bool.default_fullscreen_override)); needReload = true; } else if (PREF_FORCE_KEYBOARD_ON.equals(key)) { mForceKeyboardOn = sharedPreferences.getBoolean( PREF_FORCE_KEYBOARD_ON, res .getBoolean(R.bool.default_force_keyboard_on)); needReload = true; } else if (PREF_KEYBOARD_NOTIFICATION.equals(key)) { mKeyboardNotification = sharedPreferences.getBoolean( PREF_KEYBOARD_NOTIFICATION, res .getBoolean(R.bool.default_keyboard_notification)); setNotification(mKeyboardNotification); } else if (PREF_SUGGESTIONS_IN_LANDSCAPE.equals(key)) { mSuggestionsInLandscape = sharedPreferences.getBoolean( PREF_SUGGESTIONS_IN_LANDSCAPE, res .getBoolean(R.bool.default_suggestions_in_landscape)); // Respect the suggestion settings in legacy Gingerbread mode, // in portrait mode, or if suggestions in landscape enabled. mSuggestionForceOff = false; mSuggestionForceOn = false; setCandidatesViewShown(isPredictionOn()); } else if (PREF_SHOW_SUGGESTIONS.equals(key)) { mShowSuggestions = sharedPreferences.getBoolean( PREF_SHOW_SUGGESTIONS, res.getBoolean(R.bool.default_suggestions)); mSuggestionForceOff = false; mSuggestionForceOn = false; needReload = true; } else if (PREF_HEIGHT_PORTRAIT.equals(key)) { mHeightPortrait = getHeight(sharedPreferences, PREF_HEIGHT_PORTRAIT, res.getString(R.string.default_height_portrait)); needReload = true; } else if (PREF_HEIGHT_LANDSCAPE.equals(key)) { mHeightLandscape = getHeight(sharedPreferences, PREF_HEIGHT_LANDSCAPE, res.getString(R.string.default_height_landscape)); needReload = true; } else if (PREF_HINT_MODE.equals(key)) { LatinIME.sKeyboardSettings.hintMode = Integer.parseInt(sharedPreferences.getString(PREF_HINT_MODE, res.getString(R.string.default_hint_mode))); needReload = true; } else if (PREF_LONGPRESS_TIMEOUT.equals(key)) { LatinIME.sKeyboardSettings.longpressTimeout = getPrefInt(sharedPreferences, PREF_LONGPRESS_TIMEOUT, res.getString(R.string.default_long_press_duration)); } else if (PREF_RENDER_MODE.equals(key)) { LatinIME.sKeyboardSettings.renderMode = getPrefInt(sharedPreferences, PREF_RENDER_MODE, res.getString(R.string.default_render_mode)); needReload = true; } else if (PREF_SWIPE_UP.equals(key)) { mSwipeUpAction = sharedPreferences.getString(PREF_SWIPE_UP, res.getString(R.string.default_swipe_up)); } else if (PREF_SWIPE_DOWN.equals(key)) { mSwipeDownAction = sharedPreferences.getString(PREF_SWIPE_DOWN, res.getString(R.string.default_swipe_down)); } else if (PREF_SWIPE_LEFT.equals(key)) { mSwipeLeftAction = sharedPreferences.getString(PREF_SWIPE_LEFT, res.getString(R.string.default_swipe_left)); } else if (PREF_SWIPE_RIGHT.equals(key)) { mSwipeRightAction = sharedPreferences.getString(PREF_SWIPE_RIGHT, res.getString(R.string.default_swipe_right)); } else if (PREF_VOL_UP.equals(key)) { mVolUpAction = sharedPreferences.getString(PREF_VOL_UP, res.getString(R.string.default_vol_up)); } else if (PREF_VOL_DOWN.equals(key)) { mVolDownAction = sharedPreferences.getString(PREF_VOL_DOWN, res.getString(R.string.default_vol_down)); } else if (PREF_VIBRATE_LEN.equals(key)) { mVibrateLen = getPrefInt(sharedPreferences, PREF_VIBRATE_LEN, getResources().getString(R.string.vibrate_duration_ms)); vibrate(); // test setting } updateKeyboardOptions(); if (needReload) { mKeyboardSwitcher.makeKeyboards(true); } } private boolean doSwipeAction(String action) { //Log.i(TAG, "doSwipeAction + " + action); if (action == null || action.equals("") || action.equals("none")) { return false; } else if (action.equals("close")) { handleClose(); } else if (action.equals("settings")) { launchSettings(); } else if (action.equals("suggestions")) { if (mSuggestionForceOn) { mSuggestionForceOn = false; mSuggestionForceOff = true; } else if (mSuggestionForceOff) { mSuggestionForceOn = true; mSuggestionForceOff = false; } else if (isPredictionWanted()) { mSuggestionForceOff = true; } else { mSuggestionForceOn = true; } setCandidatesViewShown(isPredictionOn()); } else if (action.equals("lang_prev")) { toggleLanguage(false, false); } else if (action.equals("lang_next")) { toggleLanguage(false, true); } else if (action.equals("debug_auto_play")) { if (LatinKeyboardView.DEBUG_AUTO_PLAY) { ClipboardManager cm = ((ClipboardManager) getSystemService(CLIPBOARD_SERVICE)); CharSequence text = cm.getText(); if (!TextUtils.isEmpty(text)) { mKeyboardSwitcher.getInputView().startPlaying(text.toString()); } } } else if (action.equals("voice_input")) { if (VOICE_INSTALLED) { startListening(false /* was a button press, was not a swipe */); } else { Toast.makeText(getApplicationContext(), getResources().getString(R.string.voice_not_enabled_warning), Toast.LENGTH_LONG) .show(); } } else if (action.equals("full_mode")) { if (isPortrait()) { mKeyboardModeOverridePortrait = (mKeyboardModeOverridePortrait + 1) % mNumKeyboardModes; } else { mKeyboardModeOverrideLandscape = (mKeyboardModeOverrideLandscape + 1) % mNumKeyboardModes; } toggleLanguage(true, true); } else if (action.equals("extension")) { sKeyboardSettings.useExtension = !sKeyboardSettings.useExtension; reloadKeyboards(); } else if (action.equals("height_up")) { if (isPortrait()) { mHeightPortrait += 5; if (mHeightPortrait > 70) mHeightPortrait = 70; } else { mHeightLandscape += 5; if (mHeightLandscape > 70) mHeightLandscape = 70; } toggleLanguage(true, true); } else if (action.equals("height_down")) { if (isPortrait()) { mHeightPortrait -= 5; if (mHeightPortrait < 15) mHeightPortrait = 15; } else { mHeightLandscape -= 5; if (mHeightLandscape < 15) mHeightLandscape = 15; } toggleLanguage(true, true); } else { Log.i(TAG, "Unsupported swipe action config: " + action); } return true; } public boolean swipeRight() { return doSwipeAction(mSwipeRightAction); } public boolean swipeLeft() { return doSwipeAction(mSwipeLeftAction); } public boolean swipeDown() { return doSwipeAction(mSwipeDownAction); } public boolean swipeUp() { return doSwipeAction(mSwipeUpAction); } public void onPress(int primaryCode) { InputConnection ic = getCurrentInputConnection(); if (mKeyboardSwitcher.isVibrateAndSoundFeedbackRequired()) { vibrate(); playKeyClick(primaryCode); } final boolean distinctMultiTouch = mKeyboardSwitcher .hasDistinctMultitouch(); if (distinctMultiTouch && primaryCode == Keyboard.KEYCODE_SHIFT) { mShiftKeyState.onPress(); startMultitouchShift(); } else if (distinctMultiTouch && primaryCode == Keyboard.KEYCODE_MODE_CHANGE) { changeKeyboardMode(); mSymbolKeyState.onPress(); mKeyboardSwitcher.setAutoModeSwitchStateMomentary(); } else if (distinctMultiTouch && primaryCode == LatinKeyboardView.KEYCODE_CTRL_LEFT) { setModCtrl(!mModCtrl); mCtrlKeyState.onPress(); sendCtrlKey(ic, true, true); } else if (distinctMultiTouch && primaryCode == LatinKeyboardView.KEYCODE_ALT_LEFT) { setModAlt(!mModAlt); mAltKeyState.onPress(); sendAltKey(ic, true, true); } else if (distinctMultiTouch && primaryCode == LatinKeyboardView.KEYCODE_FN) { setModFn(!mModFn); mFnKeyState.onPress(); } else { mShiftKeyState.onOtherKeyPressed(); mSymbolKeyState.onOtherKeyPressed(); mCtrlKeyState.onOtherKeyPressed(); mAltKeyState.onOtherKeyPressed(); mFnKeyState.onOtherKeyPressed(); } } public void onRelease(int primaryCode) { // Reset any drag flags in the keyboard ((LatinKeyboard) mKeyboardSwitcher.getInputView().getKeyboard()) .keyReleased(); // vibrate(); final boolean distinctMultiTouch = mKeyboardSwitcher .hasDistinctMultitouch(); InputConnection ic = getCurrentInputConnection(); if (distinctMultiTouch && primaryCode == Keyboard.KEYCODE_SHIFT) { if (mShiftKeyState.isMomentary()) { resetMultitouchShift(); } else { commitMultitouchShift(); } mShiftKeyState.onRelease(); } else if (distinctMultiTouch && primaryCode == Keyboard.KEYCODE_MODE_CHANGE) { // Snap back to the previous keyboard mode if the user chords the // mode change key and // other key, then released the mode change key. if (mKeyboardSwitcher.isInChordingAutoModeSwitchState()) changeKeyboardMode(); mSymbolKeyState.onRelease(); } else if (distinctMultiTouch && primaryCode == LatinKeyboardView.KEYCODE_CTRL_LEFT) { if (mCtrlKeyState.isMomentary()) { setModCtrl(false); } sendCtrlKey(ic, false, true); mCtrlKeyState.onRelease(); } else if (distinctMultiTouch && primaryCode == LatinKeyboardView.KEYCODE_ALT_LEFT) { if (mAltKeyState.isMomentary()) { setModAlt(false); } sendAltKey(ic, false, true); mAltKeyState.onRelease(); } else if (distinctMultiTouch && primaryCode == LatinKeyboardView.KEYCODE_FN) { if (mFnKeyState.isMomentary()) { setModFn(false); } mFnKeyState.onRelease(); } } private FieldContext makeFieldContext() { return new FieldContext(getCurrentInputConnection(), getCurrentInputEditorInfo(), mLanguageSwitcher .getInputLanguage(), mLanguageSwitcher .getEnabledLanguages()); } private boolean fieldCanDoVoice(FieldContext fieldContext) { return !mPasswordText && mVoiceInput != null && !mVoiceInput.isBlacklistedField(fieldContext); } private boolean shouldShowVoiceButton(FieldContext fieldContext, EditorInfo attribute) { return ENABLE_VOICE_BUTTON && fieldCanDoVoice(fieldContext) && !(attribute != null && IME_OPTION_NO_MICROPHONE .equals(attribute.privateImeOptions)) && SpeechRecognizer.isRecognitionAvailable(this); } // receive ringer mode changes to detect silent mode private BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { updateRingerMode(); } }; // update flags for silent mode private void updateRingerMode() { if (mAudioManager == null) { mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); } if (mAudioManager != null) { mSilentMode = (mAudioManager.getRingerMode() != AudioManager.RINGER_MODE_NORMAL); } } private float getKeyClickVolume() { if (mAudioManager == null) return 0.0f; // shouldn't happen // The volume calculations are poorly documented, this is the closest I could // find for explaining volume conversions: // http://developer.android.com/reference/android/media/MediaPlayer.html#setAuxEffectSendLevel(float) // // Note that the passed level value is a raw scalar. UI controls should be scaled logarithmically: // the gain applied by audio framework ranges from -72dB to 0dB, so an appropriate conversion // from linear UI input x to level is: x == 0 -> level = 0 0 < x <= R -> level = 10^(72*(x-R)/20/R) int method = sKeyboardSettings.keyClickMethod; // See click_method_values in strings.xml if (method == 0) return FX_VOLUME; float targetVol = sKeyboardSettings.keyClickVolume; if (method > 1) { // TODO(klausw): on some devices the media volume controls the click volume? // If that's the case, try to set a relative target volume. int mediaMax = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC); int mediaVol = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC); //Log.i(TAG, "getKeyClickVolume relative, media vol=" + mediaVol + "/" + mediaMax); float channelVol = (float) mediaVol / mediaMax; if (method == 2) { targetVol *= channelVol; } else if (method == 3) { if (channelVol == 0) return 0.0f; // Channel is silent, won't get audio targetVol = Math.min(targetVol / channelVol, 1.0f); // Cap at 1.0 } } // Set absolute volume, treating the percentage as a logarithmic control float vol = (float) Math.pow(10.0, FX_VOLUME_RANGE_DB * (targetVol - 1) / 20); //Log.i(TAG, "getKeyClickVolume absolute, target=" + targetVol + " amp=" + vol); return vol; } private void playKeyClick(int primaryCode) { // if mAudioManager is null, we don't have the ringer state yet // mAudioManager will be set by updateRingerMode if (mAudioManager == null) { if (mKeyboardSwitcher.getInputView() != null) { updateRingerMode(); } } if (mSoundOn && !mSilentMode) { // FIXME: Volume and enable should come from UI settings // FIXME: These should be triggered after auto-repeat logic int sound = AudioManager.FX_KEYPRESS_STANDARD; switch (primaryCode) { case Keyboard.KEYCODE_DELETE: sound = AudioManager.FX_KEYPRESS_DELETE; break; case ASCII_ENTER: sound = AudioManager.FX_KEYPRESS_RETURN; break; case ASCII_SPACE: sound = AudioManager.FX_KEYPRESS_SPACEBAR; break; } mAudioManager.playSoundEffect(sound, getKeyClickVolume()); } } private void vibrate() { if (!mVibrateOn) { return; } Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); if (v != null) { v.vibrate(mVibrateLen); return; } if (mKeyboardSwitcher.getInputView() != null) { mKeyboardSwitcher.getInputView().performHapticFeedback( HapticFeedbackConstants.KEYBOARD_TAP, HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING); } } private void checkTutorial(String privateImeOptions) { if (privateImeOptions == null) return; if (privateImeOptions.equals("com.android.setupwizard:ShowTutorial")) { if (mTutorial == null) startTutorial(); } else if (privateImeOptions .equals("com.android.setupwizard:HideTutorial")) { if (mTutorial != null) { if (mTutorial.close()) { mTutorial = null; } } } } private void startTutorial() { mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_START_TUTORIAL), 500); } /* package */void tutorialDone() { mTutorial = null; } /* package */void promoteToUserDictionary(String word, int frequency) { if (mUserDictionary.isValidWord(word)) return; mUserDictionary.addWord(word, frequency); } /* package */WordComposer getCurrentWord() { return mWord; } /* package */boolean getPopupOn() { return mPopupOn; } private void updateCorrectionMode() { mHasDictionary = mSuggest != null ? mSuggest.hasMainDictionary() : false; mAutoCorrectOn = (mAutoCorrectEnabled || mQuickFixes) && !mInputTypeNoAutoCorrect && mHasDictionary; mCorrectionMode = (mAutoCorrectOn && mAutoCorrectEnabled) ? Suggest.CORRECTION_FULL : (mAutoCorrectOn ? Suggest.CORRECTION_BASIC : Suggest.CORRECTION_NONE); mCorrectionMode = (mBigramSuggestionEnabled && mAutoCorrectOn && mAutoCorrectEnabled) ? Suggest.CORRECTION_FULL_BIGRAM : mCorrectionMode; if (suggestionsDisabled()) { mAutoCorrectOn = false; mCorrectionMode = Suggest.CORRECTION_NONE; } if (mSuggest != null) { mSuggest.setCorrectionMode(mCorrectionMode); } } private void updateAutoTextEnabled(Locale systemLocale) { if (mSuggest == null) return; boolean different = !systemLocale.getLanguage().equalsIgnoreCase( mInputLocale.substring(0, 2)); mSuggest.setAutoTextEnabled(!different && mQuickFixes); } protected void launchSettings() { launchSettings(LatinIMESettings.class); } public void launchDebugSettings() { launchSettings(LatinIMEDebugSettings.class); } protected void launchSettings( Class<? extends PreferenceActivity> settingsClass) { handleClose(); Intent intent = new Intent(); intent.setClass(LatinIME.this, settingsClass); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } private void loadSettings() { // Get the settings preferences SharedPreferences sp = PreferenceManager .getDefaultSharedPreferences(this); mVibrateOn = sp.getBoolean(PREF_VIBRATE_ON, false); mVibrateLen = getPrefInt(sp, PREF_VIBRATE_LEN, getResources().getString(R.string.vibrate_duration_ms)); mSoundOn = sp.getBoolean(PREF_SOUND_ON, false); mPopupOn = sp.getBoolean(PREF_POPUP_ON, mResources .getBoolean(R.bool.default_popup_preview)); mAutoCapPref = sp.getBoolean(PREF_AUTO_CAP, getResources().getBoolean( R.bool.default_auto_cap)); mQuickFixes = sp.getBoolean(PREF_QUICK_FIXES, true); mHasUsedVoiceInput = sp.getBoolean(PREF_HAS_USED_VOICE_INPUT, false); mHasUsedVoiceInputUnsupportedLocale = sp.getBoolean( PREF_HAS_USED_VOICE_INPUT_UNSUPPORTED_LOCALE, false); // Get the current list of supported locales and check the current // locale against that // list. We cache this value so as not to check it every time the user // starts a voice // input. Because this method is called by onStartInputView, this should // mean that as // long as the locale doesn't change while the user is keeping the IME // open, the // value should never be stale. String supportedLocalesString = SettingsUtil.getSettingsString( getContentResolver(), SettingsUtil.LATIN_IME_VOICE_INPUT_SUPPORTED_LOCALES, DEFAULT_VOICE_INPUT_SUPPORTED_LOCALES); ArrayList<String> voiceInputSupportedLocales = newArrayList(supportedLocalesString .split("\\s+")); mLocaleSupportedForVoiceInput = voiceInputSupportedLocales.contains(mInputLocale) || voiceInputSupportedLocales.contains(mInputLocale.substring(0, Math.min(2, mInputLocale.length()))); mShowSuggestions = sp.getBoolean(PREF_SHOW_SUGGESTIONS, mResources .getBoolean(R.bool.default_suggestions)); if (VOICE_INSTALLED) { final String voiceMode = sp.getString(PREF_VOICE_MODE, getString(R.string.voice_mode_main)); boolean enableVoice = !voiceMode .equals(getString(R.string.voice_mode_off)) && mEnableVoiceButton; boolean voiceOnPrimary = voiceMode .equals(getString(R.string.voice_mode_main)); if (mKeyboardSwitcher != null && (enableVoice != mEnableVoice || voiceOnPrimary != mVoiceOnPrimary)) { mKeyboardSwitcher.setVoiceMode(enableVoice, voiceOnPrimary); } mEnableVoice = enableVoice; mVoiceOnPrimary = voiceOnPrimary; } mAutoCorrectEnabled = sp.getBoolean(PREF_AUTO_COMPLETE, mResources .getBoolean(R.bool.enable_autocorrect)) & mShowSuggestions; // mBigramSuggestionEnabled = sp.getBoolean( // PREF_BIGRAM_SUGGESTIONS, true) & mShowSuggestions; updateCorrectionMode(); updateAutoTextEnabled(mResources.getConfiguration().locale); mLanguageSwitcher.loadLocales(sp); mAutoCapActive = mAutoCapPref && mLanguageSwitcher.allowAutoCap(); mDeadKeysActive = mLanguageSwitcher.allowDeadKeys(); } private void initSuggestPuncList() { mSuggestPuncList = new ArrayList<CharSequence>(); String suggestPuncs = sKeyboardSettings.suggestedPunctuation; String defaultPuncs = getResources().getString(R.string.suggested_punctuations_default); if (suggestPuncs.equals(defaultPuncs) || suggestPuncs.equals("")) { // Not user-configured, load the language-specific default. suggestPuncs = getResources().getString(R.string.suggested_punctuations); } if (suggestPuncs != null) { for (int i = 0; i < suggestPuncs.length(); i++) { mSuggestPuncList.add(suggestPuncs.subSequence(i, i + 1)); } } setNextSuggestions(); } private boolean isSuggestedPunctuation(int code) { return sKeyboardSettings.suggestedPunctuation.contains(String.valueOf((char) code)); } private void showOptionsMenu() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setCancelable(true); builder.setIcon(R.drawable.ic_dialog_keyboard); builder.setNegativeButton(android.R.string.cancel, null); CharSequence itemSettings = getString(R.string.english_ime_settings); CharSequence itemInputMethod = getString(R.string.selectInputMethod); builder.setItems(new CharSequence[] { itemInputMethod, itemSettings }, new DialogInterface.OnClickListener() { public void onClick(DialogInterface di, int position) { di.dismiss(); switch (position) { case POS_SETTINGS: launchSettings(); break; case POS_METHOD: ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)) .showInputMethodPicker(); break; } } }); builder.setTitle(mResources .getString(R.string.english_ime_input_options)); mOptionsDialog = builder.create(); Window window = mOptionsDialog.getWindow(); WindowManager.LayoutParams lp = window.getAttributes(); lp.token = mKeyboardSwitcher.getInputView().getWindowToken(); lp.type = WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG; window.setAttributes(lp); window.addFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM); mOptionsDialog.show(); } public void changeKeyboardMode() { KeyboardSwitcher switcher = mKeyboardSwitcher; if (switcher.isAlphabetMode()) { mSavedShiftState = getShiftState(); } switcher.toggleSymbols(); if (switcher.isAlphabetMode()) { switcher.setShiftState(mSavedShiftState); } updateShiftKeyState(getCurrentInputEditorInfo()); } public static <E> ArrayList<E> newArrayList(E... elements) { int capacity = (elements.length * 110) / 100 + 5; ArrayList<E> list = new ArrayList<E>(capacity); Collections.addAll(list, elements); return list; } @Override protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) { super.dump(fd, fout, args); final Printer p = new PrintWriterPrinter(fout); p.println("LatinIME state :"); p.println(" Keyboard mode = " + mKeyboardSwitcher.getKeyboardMode()); p.println(" mComposing=" + mComposing.toString()); p.println(" mPredictionOnForMode=" + mPredictionOnForMode); p.println(" mCorrectionMode=" + mCorrectionMode); p.println(" mPredicting=" + mPredicting); p.println(" mAutoCorrectOn=" + mAutoCorrectOn); p.println(" mAutoSpace=" + mAutoSpace); p.println(" mCompletionOn=" + mCompletionOn); p.println(" TextEntryState.state=" + TextEntryState.getState()); p.println(" mSoundOn=" + mSoundOn); p.println(" mVibrateOn=" + mVibrateOn); p.println(" mPopupOn=" + mPopupOn); } // Characters per second measurement private long mLastCpsTime; private static final int CPS_BUFFER_SIZE = 16; private long[] mCpsIntervals = new long[CPS_BUFFER_SIZE]; private int mCpsIndex; private static Pattern NUMBER_RE = Pattern.compile("(\\d+).*"); private void measureCps() { long now = System.currentTimeMillis(); if (mLastCpsTime == 0) mLastCpsTime = now - 100; // Initial mCpsIntervals[mCpsIndex] = now - mLastCpsTime; mLastCpsTime = now; mCpsIndex = (mCpsIndex + 1) % CPS_BUFFER_SIZE; long total = 0; for (int i = 0; i < CPS_BUFFER_SIZE; i++) total += mCpsIntervals[i]; System.out.println("CPS = " + ((CPS_BUFFER_SIZE * 1000f) / total)); } public void onAutoCompletionStateChanged(boolean isAutoCompletion) { mKeyboardSwitcher.onAutoCompletionStateChanged(isAutoCompletion); } static int getIntFromString(String val, int defVal) { Matcher num = NUMBER_RE.matcher(val); if (!num.matches()) return defVal; return Integer.parseInt(num.group(1)); } static int getPrefInt(SharedPreferences prefs, String prefName, int defVal) { String prefVal = prefs.getString(prefName, Integer.toString(defVal)); //Log.i("PCKeyboard", "getPrefInt " + prefName + " = " + prefVal + ", default " + defVal); return getIntFromString(prefVal, defVal); } static int getPrefInt(SharedPreferences prefs, String prefName, String defStr) { int defVal = getIntFromString(defStr, 0); return getPrefInt(prefs, prefName, defVal); } static int getHeight(SharedPreferences prefs, String prefName, String defVal) { int val = getPrefInt(prefs, prefName, defVal); if (val < 15) val = 15; if (val > 75) val = 75; return val; } }
Java
/* * Copyright (C) 2008-2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.pocketworkstation.pckeyboard; import java.text.Collator; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Set; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.res.Configuration; import android.content.res.Resources; import android.os.Bundle; import android.preference.CheckBoxPreference; import android.preference.PreferenceActivity; import android.preference.PreferenceGroup; import android.preference.PreferenceManager; import android.text.TextUtils; import android.util.Log; public class InputLanguageSelection extends PreferenceActivity { private static final String TAG = "PCKeyboardILS"; private ArrayList<Loc> mAvailableLanguages = new ArrayList<Loc>(); private static final String[] BLACKLIST_LANGUAGES = { "ko", "ja", "zh" }; // Languages for which auto-caps should be disabled public static final Set<String> NOCAPS_LANGUAGES = new HashSet<String>(); static { NOCAPS_LANGUAGES.add("ar"); NOCAPS_LANGUAGES.add("iw"); NOCAPS_LANGUAGES.add("th"); } // Languages which should not use dead key logic. The modifier is entered after the base character. public static final Set<String> NODEADKEY_LANGUAGES = new HashSet<String>(); static { NODEADKEY_LANGUAGES.add("ar"); NODEADKEY_LANGUAGES.add("iw"); // TODO: currently no niqqud in the keymap? NODEADKEY_LANGUAGES.add("th"); } // Languages which should not auto-add space after completions public static final Set<String> NOAUTOSPACE_LANGUAGES = new HashSet<String>(); static { NOAUTOSPACE_LANGUAGES.add("th"); } // Run the GetLanguages.sh script to update the following lists based on // the available keyboard resources and dictionaries. private static final String[] KBD_LOCALIZATIONS = { "ar", "bg", "ca", "cs", "cs_QY", "da", "de", "el", "en", "en_DV", "en_GB", "es", "es_US", "fa", "fi", "fr", "fr_CA", "he", "hr", "hu", "hy", "in", "it", "iw", "ja", "ka", "ko", "lo", "lt", "lv", "nb", "nl", "pl", "pt", "pt_PT", "rm", "ro", "ru", "ru_PH", "si", "sk", "sk_QY", "sl", "sr", "sv", "th", "tl", "tr", "uk", "vi", "zh_CN", "zh_TW" }; private static final String[] KBD_5_ROW = { "ar", "bg", "cs", "cs_QY", "da", "de", "el", "en", "en_DV", "en_GB", "es", "fa", "fi", "fr", "fr_CA", "he", "hr", "hy", "it", "iw", "lo", "nb", "pt_PT", "ro", "ru", "ru_PH", "si", "sk", "sk_QY", "sl", "sr", "sv", "th", "tr", "uk" }; private static final String[] KBD_4_ROW = { "ar", "bg", "cs", "cs_QY", "da", "de", "el", "en", "en_DV", "fa", "fr", "fr_CA", "he", "hr", "iw", "nb", "ru", "ru_PH", "sk", "sk_QY", "sl", "sr", "sv", "tr", "uk" }; private static String getLocaleName(Locale l) { String lang = l.getLanguage(); String country = l.getCountry(); if (lang.equals("en") && country.equals("DV")) { return "English (Dvorak)"; } else if (lang.equals("en") && country.equals("EX")) { return "English (4x11)"; } else if (lang.equals("cs") && country.equals("QY")) { return "Čeština (QWERTY)"; } else if (lang.equals("sk") && country.equals("QY")) { return "Slovenčina (QWERTY)"; } else if (lang.equals("ru") && country.equals("PH")) { return "Русский (Phonetic)"; } else { return LanguageSwitcher.toTitleCase(l.getDisplayName(l)); } } private static class Loc implements Comparable<Object> { static Collator sCollator = Collator.getInstance(); String label; Locale locale; public Loc(String label, Locale locale) { this.label = label; this.locale = locale; } @Override public String toString() { return this.label; } public int compareTo(Object o) { return sCollator.compare(this.label, ((Loc) o).label); } } @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); addPreferencesFromResource(R.xml.language_prefs); // Get the settings preferences SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); String selectedLanguagePref = sp.getString(LatinIME.PREF_SELECTED_LANGUAGES, ""); Log.i(TAG, "selected languages: " + selectedLanguagePref); String[] languageList = selectedLanguagePref.split(","); mAvailableLanguages = getUniqueLocales(); // Compatibility hack for v1.22 and older - if a selected language 5-code isn't // found in the current list of available languages, try adding the 2-letter // language code. For example, "en_US" is no longer listed, so use "en" instead. Set<String> availableLanguages = new HashSet<String>(); for (int i = 0; i < mAvailableLanguages.size(); i++) { Locale locale = mAvailableLanguages.get(i).locale; availableLanguages.add(get5Code(locale)); } Set<String> languageSelections = new HashSet<String>(); for (int i = 0; i < languageList.length; ++i) { String spec = languageList[i]; if (availableLanguages.contains(spec)) { languageSelections.add(spec); } else if (spec.length() > 2) { String lang = spec.substring(0, 2); if (availableLanguages.contains(lang)) languageSelections.add(lang); } } PreferenceGroup parent = getPreferenceScreen(); for (int i = 0; i < mAvailableLanguages.size(); i++) { CheckBoxPreference pref = new CheckBoxPreference(this); Locale locale = mAvailableLanguages.get(i).locale; pref.setTitle(mAvailableLanguages.get(i).label + " [" + locale.toString() + "]"); String fivecode = get5Code(locale); String language = locale.getLanguage(); boolean checked = languageSelections.contains(fivecode); pref.setChecked(checked); boolean has4Row = arrayContains(KBD_4_ROW, fivecode) || arrayContains(KBD_4_ROW, language); boolean has5Row = arrayContains(KBD_5_ROW, fivecode) || arrayContains(KBD_5_ROW, language); List<String> summaries = new ArrayList<String>(3); if (has5Row) summaries.add("5-row"); if (has4Row) summaries.add("4-row"); if (hasDictionary(locale)) { summaries.add(getResources().getString(R.string.has_dictionary)); } if (!summaries.isEmpty()) { StringBuilder summary = new StringBuilder(); for (int j = 0; j < summaries.size(); ++j) { if (j > 0) summary.append(", "); summary.append(summaries.get(j)); } pref.setSummary(summary.toString()); } parent.addPreference(pref); } } private boolean hasDictionary(Locale locale) { Resources res = getResources(); Configuration conf = res.getConfiguration(); Locale saveLocale = conf.locale; boolean haveDictionary = false; conf.locale = locale; res.updateConfiguration(conf, res.getDisplayMetrics()); int[] dictionaries = LatinIME.getDictionary(res); BinaryDictionary bd = new BinaryDictionary(this, dictionaries, Suggest.DIC_MAIN); // Is the dictionary larger than a placeholder? Arbitrarily chose a lower limit of // 4000-5000 words, whereas the LARGE_DICTIONARY is about 20000+ words. if (bd.getSize() > Suggest.LARGE_DICTIONARY_THRESHOLD / 4) { haveDictionary = true; } else { BinaryDictionary plug = PluginManager.getDictionary(getApplicationContext(), locale.getLanguage()); if (plug != null) { bd.close(); bd = plug; haveDictionary = true; } } bd.close(); conf.locale = saveLocale; res.updateConfiguration(conf, res.getDisplayMetrics()); return haveDictionary; } private String get5Code(Locale locale) { String country = locale.getCountry(); return locale.getLanguage() + (TextUtils.isEmpty(country) ? "" : "_" + country); } @Override protected void onResume() { super.onResume(); } @Override protected void onPause() { super.onPause(); // Save the selected languages String checkedLanguages = ""; PreferenceGroup parent = getPreferenceScreen(); int count = parent.getPreferenceCount(); for (int i = 0; i < count; i++) { CheckBoxPreference pref = (CheckBoxPreference) parent.getPreference(i); if (pref.isChecked()) { Locale locale = mAvailableLanguages.get(i).locale; checkedLanguages += get5Code(locale) + ","; } } if (checkedLanguages.length() < 1) checkedLanguages = null; // Save null SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); Editor editor = sp.edit(); editor.putString(LatinIME.PREF_SELECTED_LANGUAGES, checkedLanguages); SharedPreferencesCompat.apply(editor); } private static String asString(Set<String> set) { StringBuilder out = new StringBuilder(); out.append("set("); String[] parts = new String[set.size()]; parts = set.toArray(parts); Arrays.sort(parts); for (int i = 0; i < parts.length; ++i) { if (i > 0) out.append(", "); out.append(parts[i]); } out.append(")"); return out.toString(); } ArrayList<Loc> getUniqueLocales() { Set<String> localeSet = new HashSet<String>(); Set<String> langSet = new HashSet<String>(); // Ignore the system (asset) locale list, it's inconsistent and incomplete // String[] sysLocales = getAssets().getLocales(); // // // First, add zz_ZZ style full language+country locales // for (int i = 0; i < sysLocales.length; ++i) { // String sl = sysLocales[i]; // if (sl.length() != 5) continue; // localeSet.add(sl); // langSet.add(sl.substring(0, 2)); // } // // // Add entries for system languages without country, but only if there's // // no full locale for that language yet. // for (int i = 0; i < sysLocales.length; ++i) { // String sl = sysLocales[i]; // if (sl.length() != 2 || langSet.contains(sl)) continue; // localeSet.add(sl); // } // Add entries for additional languages supported by the keyboard. for (int i = 0; i < KBD_LOCALIZATIONS.length; ++i) { String kl = KBD_LOCALIZATIONS[i]; if (kl.length() == 2 && langSet.contains(kl)) continue; // replace zz_rYY with zz_YY if (kl.length() == 6) kl = kl.substring(0, 2) + "_" + kl.substring(4, 6); localeSet.add(kl); } Log.i(TAG, "localeSet=" + asString(localeSet)); Log.i(TAG, "langSet=" + asString(langSet)); // Now build the locale list for display String[] locales = new String[localeSet.size()]; locales = localeSet.toArray(locales); Arrays.sort(locales); ArrayList<Loc> uniqueLocales = new ArrayList<Loc>(); final int origSize = locales.length; Loc[] preprocess = new Loc[origSize]; int finalSize = 0; for (int i = 0 ; i < origSize; i++ ) { String s = locales[i]; int len = s.length(); if (len == 2 || len == 5 || len == 6) { String language = s.substring(0, 2); Locale l; if (len == 5) { // zz_YY String country = s.substring(3, 5); l = new Locale(language, country); } else if (len == 6) { // zz_rYY l = new Locale(language, s.substring(4, 6)); } else { l = new Locale(language); } // Exclude languages that are not relevant to LatinIME if (arrayContains(BLACKLIST_LANGUAGES, language)) continue; if (finalSize == 0) { preprocess[finalSize++] = new Loc(LanguageSwitcher.toTitleCase(l.getDisplayName(l)), l); } else { // check previous entry: // same lang and a country -> upgrade to full name and // insert ours with full name // diff lang -> insert ours with lang-only name if (preprocess[finalSize-1].locale.getLanguage().equals( language)) { preprocess[finalSize-1].label = getLocaleName(preprocess[finalSize-1].locale); preprocess[finalSize++] = new Loc(getLocaleName(l), l); } else { String displayName; if (s.equals("zz_ZZ")) { } else { displayName = getLocaleName(l); preprocess[finalSize++] = new Loc(displayName, l); } } } } } for (int i = 0; i < finalSize ; i++) { uniqueLocales.add(preprocess[i]); } return uniqueLocales; } private boolean arrayContains(String[] array, String value) { for (int i = 0; i < array.length; i++) { if (array[i].equalsIgnoreCase(value)) return true; } return false; } }
Java
/* * Copyright (C) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.pocketworkstation.pckeyboard; import org.pocketworkstation.pckeyboard.Keyboard.Key; import java.util.Arrays; class ProximityKeyDetector extends KeyDetector { private static final int MAX_NEARBY_KEYS = 12; // working area private int[] mDistances = new int[MAX_NEARBY_KEYS]; @Override protected int getMaxNearbyKeys() { return MAX_NEARBY_KEYS; } @Override public int getKeyIndexAndNearbyCodes(int x, int y, int[] allKeys) { final Key[] keys = getKeys(); final int touchX = getTouchX(x); final int touchY = getTouchY(y); int primaryIndex = LatinKeyboardBaseView.NOT_A_KEY; int closestKey = LatinKeyboardBaseView.NOT_A_KEY; int closestKeyDist = mProximityThresholdSquare + 1; int[] distances = mDistances; Arrays.fill(distances, Integer.MAX_VALUE); int [] nearestKeyIndices = mKeyboard.getNearestKeys(touchX, touchY); final int keyCount = nearestKeyIndices.length; for (int i = 0; i < keyCount; i++) { final Key key = keys[nearestKeyIndices[i]]; int dist = 0; boolean isInside = key.isInside(touchX, touchY); if (isInside) { primaryIndex = nearestKeyIndices[i]; } if (((mProximityCorrectOn && (dist = key.squaredDistanceFrom(touchX, touchY)) < mProximityThresholdSquare) || isInside) && key.codes[0] > 32) { // Find insertion point final int nCodes = key.codes.length; if (dist < closestKeyDist) { closestKeyDist = dist; closestKey = nearestKeyIndices[i]; } if (allKeys == null) continue; for (int j = 0; j < distances.length; j++) { if (distances[j] > dist) { // Make space for nCodes codes System.arraycopy(distances, j, distances, j + nCodes, distances.length - j - nCodes); System.arraycopy(allKeys, j, allKeys, j + nCodes, allKeys.length - j - nCodes); System.arraycopy(key.codes, 0, allKeys, j, nCodes); Arrays.fill(distances, j, j + nCodes, dist); break; } } } } if (primaryIndex == LatinKeyboardBaseView.NOT_A_KEY) { primaryIndex = closestKey; } return primaryIndex; } }
Java
/* * Copyright (C) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.pocketworkstation.pckeyboard; import org.pocketworkstation.pckeyboard.Keyboard.Key; class MiniKeyboardKeyDetector extends KeyDetector { private static final int MAX_NEARBY_KEYS = 1; private final int mSlideAllowanceSquare; private final int mSlideAllowanceSquareTop; public MiniKeyboardKeyDetector(float slideAllowance) { super(); mSlideAllowanceSquare = (int)(slideAllowance * slideAllowance); // Top slide allowance is slightly longer (sqrt(2) times) than other edges. mSlideAllowanceSquareTop = mSlideAllowanceSquare * 2; } @Override protected int getMaxNearbyKeys() { return MAX_NEARBY_KEYS; } @Override public int getKeyIndexAndNearbyCodes(int x, int y, int[] allKeys) { final Key[] keys = getKeys(); final int touchX = getTouchX(x); final int touchY = getTouchY(y); int closestKeyIndex = LatinKeyboardBaseView.NOT_A_KEY; int closestKeyDist = (y < 0) ? mSlideAllowanceSquareTop : mSlideAllowanceSquare; final int keyCount = keys.length; for (int i = 0; i < keyCount; i++) { final Key key = keys[i]; int dist = key.squaredDistanceFrom(touchX, touchY); if (dist < closestKeyDist) { closestKeyIndex = i; closestKeyDist = dist; } } if (allKeys != null && closestKeyIndex != LatinKeyboardBaseView.NOT_A_KEY) allKeys[0] = keys[closestKeyIndex].getPrimaryCode(); return closestKeyIndex; } }
Java
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.pocketworkstation.pckeyboard; import android.content.Context; import android.content.pm.PackageManager; import android.content.res.Resources; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.BlurMaskFilter; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.ColorFilter; import android.graphics.Paint; import android.graphics.PorterDuffColorFilter; import android.graphics.Paint.Align; import android.graphics.PorterDuff; import android.graphics.Rect; import android.graphics.Region.Op; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.graphics.drawable.StateListDrawable; import org.pocketworkstation.pckeyboard.Keyboard.Key; import android.os.Handler; import android.os.Message; import android.os.SystemClock; import android.util.AttributeSet; import android.util.Log; import android.util.TypedValue; import android.view.GestureDetector; import android.view.Gravity; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.widget.PopupWindow; import android.widget.TextView; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.text.Normalizer; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.WeakHashMap; /** * A view that renders a virtual {@link LatinKeyboard}. It handles rendering of keys and * detecting key presses and touch movements. * * TODO: References to LatinKeyboard in this class should be replaced with ones to its base class. * * @attr ref R.styleable#LatinKeyboardBaseView_keyBackground * @attr ref R.styleable#LatinKeyboardBaseView_keyPreviewLayout * @attr ref R.styleable#LatinKeyboardBaseView_keyPreviewOffset * @attr ref R.styleable#LatinKeyboardBaseView_labelTextSize * @attr ref R.styleable#LatinKeyboardBaseView_keyTextSize * @attr ref R.styleable#LatinKeyboardBaseView_keyTextColor * @attr ref R.styleable#LatinKeyboardBaseView_verticalCorrection * @attr ref R.styleable#LatinKeyboardBaseView_popupLayout */ public class LatinKeyboardBaseView extends View implements PointerTracker.UIProxy { private static final String TAG = "HK/LatinKeyboardBaseView"; private static final boolean DEBUG = false; public static final int NOT_A_TOUCH_COORDINATE = -1; public interface OnKeyboardActionListener { /** * Called when the user presses a key. This is sent before the * {@link #onKey} is called. For keys that repeat, this is only * called once. * * @param primaryCode * the unicode of the key being pressed. If the touch is * not on a valid key, the value will be zero. */ void onPress(int primaryCode); /** * Called when the user releases a key. This is sent after the * {@link #onKey} is called. For keys that repeat, this is only * called once. * * @param primaryCode * the code of the key that was released */ void onRelease(int primaryCode); /** * Send a key press to the listener. * * @param primaryCode * this is the key that was pressed * @param keyCodes * the codes for all the possible alternative keys with * the primary code being the first. If the primary key * code is a single character such as an alphabet or * number or symbol, the alternatives will include other * characters that may be on the same key or adjacent * keys. These codes are useful to correct for * accidental presses of a key adjacent to the intended * key. * @param x * x-coordinate pixel of touched event. If onKey is not called by onTouchEvent, * the value should be NOT_A_TOUCH_COORDINATE. * @param y * y-coordinate pixel of touched event. If onKey is not called by onTouchEvent, * the value should be NOT_A_TOUCH_COORDINATE. */ void onKey(int primaryCode, int[] keyCodes, int x, int y); /** * Sends a sequence of characters to the listener. * * @param text * the sequence of characters to be displayed. */ void onText(CharSequence text); /** * Called when user released a finger outside any key. */ void onCancel(); /** * Called when the user quickly moves the finger from right to * left. */ boolean swipeLeft(); /** * Called when the user quickly moves the finger from left to * right. */ boolean swipeRight(); /** * Called when the user quickly moves the finger from up to down. */ boolean swipeDown(); /** * Called when the user quickly moves the finger from down to up. */ boolean swipeUp(); } // Timing constants private final int mKeyRepeatInterval; // Miscellaneous constants /* package */ static final int NOT_A_KEY = -1; private static final int NUMBER_HINT_VERTICAL_ADJUSTMENT_PIXEL = -1; // XML attribute private float mKeyTextSize; private float mLabelScale = 1.0f; private int mKeyTextColor; private int mKeyHintColor; private int mKeyCursorColor; private boolean mRecolorSymbols; private Typeface mKeyTextStyle = Typeface.DEFAULT; private float mLabelTextSize; private int mSymbolColorScheme = 0; private int mShadowColor; private float mShadowRadius; private Drawable mKeyBackground; private int mBackgroundAlpha; private float mBackgroundDimAmount; private float mKeyHysteresisDistance; private float mVerticalCorrection; protected int mPreviewOffset; protected int mPreviewHeight; protected int mPopupLayout; // Main keyboard private Keyboard mKeyboard; private Key[] mKeys; // TODO this attribute should be gotten from Keyboard. private int mKeyboardVerticalGap; // Key preview popup protected TextView mPreviewText; protected PopupWindow mPreviewPopup; protected int mPreviewTextSizeLarge; protected int[] mOffsetInWindow; protected int mOldPreviewKeyIndex = NOT_A_KEY; protected boolean mShowPreview = true; protected boolean mShowTouchPoints = true; protected int mPopupPreviewOffsetX; protected int mPopupPreviewOffsetY; protected int mWindowY; protected int mPopupPreviewDisplayedY; protected final int mDelayBeforePreview; protected final int mDelayBeforeSpacePreview; protected final int mDelayAfterPreview; // Popup mini keyboard protected PopupWindow mMiniKeyboardPopup; protected LatinKeyboardBaseView mMiniKeyboard; protected View mMiniKeyboardContainer; protected View mMiniKeyboardParent; protected boolean mMiniKeyboardVisible; protected final WeakHashMap<Key, Keyboard> mMiniKeyboardCacheMain = new WeakHashMap<Key, Keyboard>(); protected final WeakHashMap<Key, Keyboard> mMiniKeyboardCacheShift = new WeakHashMap<Key, Keyboard>(); protected final WeakHashMap<Key, Keyboard> mMiniKeyboardCacheCaps = new WeakHashMap<Key, Keyboard>(); protected int mMiniKeyboardOriginX; protected int mMiniKeyboardOriginY; protected long mMiniKeyboardPopupTime; protected int[] mWindowOffset; protected final float mMiniKeyboardSlideAllowance; protected int mMiniKeyboardTrackerId; /** Listener for {@link OnKeyboardActionListener}. */ private OnKeyboardActionListener mKeyboardActionListener; private final ArrayList<PointerTracker> mPointerTrackers = new ArrayList<PointerTracker>(); private boolean mIgnoreMove = false; // TODO: Let the PointerTracker class manage this pointer queue private final PointerQueue mPointerQueue = new PointerQueue(); private final boolean mHasDistinctMultitouch; private int mOldPointerCount = 1; protected KeyDetector mKeyDetector = new ProximityKeyDetector(); // Swipe gesture detector private GestureDetector mGestureDetector; private final SwipeTracker mSwipeTracker = new SwipeTracker(); private final int mSwipeThreshold; private final boolean mDisambiguateSwipe; // Drawing /** Whether the keyboard bitmap needs to be redrawn before it's blitted. **/ private boolean mDrawPending; /** The dirty region in the keyboard bitmap */ private final Rect mDirtyRect = new Rect(); /** The keyboard bitmap for faster updates */ private Bitmap mBuffer; /** Notes if the keyboard just changed, so that we could possibly reallocate the mBuffer. */ private boolean mKeyboardChanged; private Key mInvalidatedKey; /** The canvas for the above mutable keyboard bitmap */ private Canvas mCanvas; private final Paint mPaint; private final Paint mPaintHint; private final Rect mPadding; private final Rect mClipRegion = new Rect(0, 0, 0, 0); private int mViewWidth; // This map caches key label text height in pixel as value and key label text size as map key. private final HashMap<Integer, Integer> mTextHeightCache = new HashMap<Integer, Integer>(); // Distance from horizontal center of the key, proportional to key label text height. private final float KEY_LABEL_VERTICAL_ADJUSTMENT_FACTOR = 0.55f; private final String KEY_LABEL_HEIGHT_REFERENCE_CHAR = "H"; /* package */ static Method sSetRenderMode; private static int sPrevRenderMode = -1; private final UIHandler mHandler = new UIHandler(); class UIHandler extends Handler { private static final int MSG_POPUP_PREVIEW = 1; private static final int MSG_DISMISS_PREVIEW = 2; private static final int MSG_REPEAT_KEY = 3; private static final int MSG_LONGPRESS_KEY = 4; private boolean mInKeyRepeat; @Override public void handleMessage(Message msg) { switch (msg.what) { case MSG_POPUP_PREVIEW: showKey(msg.arg1, (PointerTracker)msg.obj); break; case MSG_DISMISS_PREVIEW: mPreviewPopup.dismiss(); break; case MSG_REPEAT_KEY: { final PointerTracker tracker = (PointerTracker)msg.obj; tracker.repeatKey(msg.arg1); startKeyRepeatTimer(mKeyRepeatInterval, msg.arg1, tracker); break; } case MSG_LONGPRESS_KEY: { final PointerTracker tracker = (PointerTracker)msg.obj; openPopupIfRequired(msg.arg1, tracker); break; } } } public void popupPreview(long delay, int keyIndex, PointerTracker tracker) { removeMessages(MSG_POPUP_PREVIEW); if (mPreviewPopup.isShowing() && mPreviewText.getVisibility() == VISIBLE) { // Show right away, if it's already visible and finger is moving around showKey(keyIndex, tracker); } else { sendMessageDelayed(obtainMessage(MSG_POPUP_PREVIEW, keyIndex, 0, tracker), delay); } } public void cancelPopupPreview() { removeMessages(MSG_POPUP_PREVIEW); } public void dismissPreview(long delay) { if (mPreviewPopup.isShowing()) { sendMessageDelayed(obtainMessage(MSG_DISMISS_PREVIEW), delay); } } public void cancelDismissPreview() { removeMessages(MSG_DISMISS_PREVIEW); } public void startKeyRepeatTimer(long delay, int keyIndex, PointerTracker tracker) { mInKeyRepeat = true; sendMessageDelayed(obtainMessage(MSG_REPEAT_KEY, keyIndex, 0, tracker), delay); } public void cancelKeyRepeatTimer() { mInKeyRepeat = false; removeMessages(MSG_REPEAT_KEY); } public boolean isInKeyRepeat() { return mInKeyRepeat; } public void startLongPressTimer(long delay, int keyIndex, PointerTracker tracker) { removeMessages(MSG_LONGPRESS_KEY); sendMessageDelayed(obtainMessage(MSG_LONGPRESS_KEY, keyIndex, 0, tracker), delay); } public void cancelLongPressTimer() { removeMessages(MSG_LONGPRESS_KEY); } public void cancelKeyTimers() { cancelKeyRepeatTimer(); cancelLongPressTimer(); } public void cancelAllMessages() { cancelKeyTimers(); cancelPopupPreview(); cancelDismissPreview(); } } static class PointerQueue { private LinkedList<PointerTracker> mQueue = new LinkedList<PointerTracker>(); public void add(PointerTracker tracker) { mQueue.add(tracker); } public int lastIndexOf(PointerTracker tracker) { LinkedList<PointerTracker> queue = mQueue; for (int index = queue.size() - 1; index >= 0; index--) { PointerTracker t = queue.get(index); if (t == tracker) return index; } return -1; } public void releaseAllPointersOlderThan(PointerTracker tracker, long eventTime) { LinkedList<PointerTracker> queue = mQueue; int oldestPos = 0; for (PointerTracker t = queue.get(oldestPos); t != tracker; t = queue.get(oldestPos)) { if (t.isModifier()) { oldestPos++; } else { t.onUpEvent(t.getLastX(), t.getLastY(), eventTime); t.setAlreadyProcessed(); queue.remove(oldestPos); } } } public void releaseAllPointersExcept(PointerTracker tracker, long eventTime) { for (PointerTracker t : mQueue) { if (t == tracker) continue; t.onUpEvent(t.getLastX(), t.getLastY(), eventTime); t.setAlreadyProcessed(); } mQueue.clear(); if (tracker != null) mQueue.add(tracker); } public void remove(PointerTracker tracker) { mQueue.remove(tracker); } public boolean isInSlidingKeyInput() { for (final PointerTracker tracker : mQueue) { if (tracker.isInSlidingKeyInput()) return true; } return false; } } static { initCompatibility(); } static void initCompatibility() { try { sSetRenderMode = View.class.getMethod("setLayerType", int.class, Paint.class); Log.i(TAG, "setRenderMode is supported"); } catch (SecurityException e) { Log.w(TAG, "unexpected SecurityException", e); } catch (NoSuchMethodException e) { // ignore, not supported by API level pre-Honeycomb Log.i(TAG, "ignoring render mode, not supported"); } } private void setRenderModeIfPossible(int mode) { if (sSetRenderMode != null && mode != sPrevRenderMode) { try { sSetRenderMode.invoke(this, mode, null); sPrevRenderMode = mode; Log.i(TAG, "render mode set to " + LatinIME.sKeyboardSettings.renderMode); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } } public LatinKeyboardBaseView(Context context, AttributeSet attrs) { this(context, attrs, R.attr.keyboardViewStyle); } public LatinKeyboardBaseView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); Log.i(TAG, "Creating new LatinKeyboardBaseView " + this); setRenderModeIfPossible(LatinIME.sKeyboardSettings.renderMode); TypedArray a = context.obtainStyledAttributes( attrs, R.styleable.LatinKeyboardBaseView, defStyle, R.style.LatinKeyboardBaseView); int n = a.getIndexCount(); for (int i = 0; i < n; i++) { int attr = a.getIndex(i); switch (attr) { case R.styleable.LatinKeyboardBaseView_keyBackground: mKeyBackground = a.getDrawable(attr); break; case R.styleable.LatinKeyboardBaseView_keyHysteresisDistance: mKeyHysteresisDistance = a.getDimensionPixelOffset(attr, 0); break; case R.styleable.LatinKeyboardBaseView_verticalCorrection: mVerticalCorrection = a.getDimensionPixelOffset(attr, 0); break; case R.styleable.LatinKeyboardBaseView_keyTextSize: mKeyTextSize = a.getDimensionPixelSize(attr, 18); break; case R.styleable.LatinKeyboardBaseView_keyTextColor: mKeyTextColor = a.getColor(attr, 0xFF000000); break; case R.styleable.LatinKeyboardBaseView_keyHintColor: mKeyHintColor = a.getColor(attr, 0xFFBBBBBB); break; case R.styleable.LatinKeyboardBaseView_keyCursorColor: mKeyCursorColor = a.getColor(attr, 0xFF000000); break; case R.styleable.LatinKeyboardBaseView_recolorSymbols: mRecolorSymbols = a.getBoolean(attr, false); break; case R.styleable.LatinKeyboardBaseView_labelTextSize: mLabelTextSize = a.getDimensionPixelSize(attr, 14); break; case R.styleable.LatinKeyboardBaseView_shadowColor: mShadowColor = a.getColor(attr, 0); break; case R.styleable.LatinKeyboardBaseView_shadowRadius: mShadowRadius = a.getFloat(attr, 0f); break; // TODO: Use Theme (android.R.styleable.Theme_backgroundDimAmount) case R.styleable.LatinKeyboardBaseView_backgroundDimAmount: mBackgroundDimAmount = a.getFloat(attr, 0.5f); break; case R.styleable.LatinKeyboardBaseView_backgroundAlpha: mBackgroundAlpha = a.getInteger(attr, 255); break; //case android.R.styleable. case R.styleable.LatinKeyboardBaseView_keyTextStyle: int textStyle = a.getInt(attr, 0); switch (textStyle) { case 0: mKeyTextStyle = Typeface.DEFAULT; break; case 1: mKeyTextStyle = Typeface.DEFAULT_BOLD; break; default: mKeyTextStyle = Typeface.defaultFromStyle(textStyle); break; } break; case R.styleable.LatinKeyboardBaseView_symbolColorScheme: mSymbolColorScheme = a.getInt(attr, 0); break; } } final Resources res = getResources(); mShowPreview = false; mDelayBeforePreview = res.getInteger(R.integer.config_delay_before_preview); mDelayBeforeSpacePreview = res.getInteger(R.integer.config_delay_before_space_preview); mDelayAfterPreview = res.getInteger(R.integer.config_delay_after_preview); mPopupLayout = 0; mPaint = new Paint(); mPaint.setAntiAlias(true); mPaint.setTextAlign(Align.CENTER); mPaint.setAlpha(255); mPaintHint = new Paint(); mPaintHint.setAntiAlias(true); mPaintHint.setTextAlign(Align.RIGHT); mPaintHint.setAlpha(255); mPaintHint.setTypeface(Typeface.DEFAULT_BOLD); mPadding = new Rect(0, 0, 0, 0); mKeyBackground.getPadding(mPadding); mSwipeThreshold = (int) (300 * res.getDisplayMetrics().density); // TODO: Refer frameworks/base/core/res/res/values/config.xml // TODO(klausw): turn off mDisambiguateSwipe if no swipe actions are set? mDisambiguateSwipe = res.getBoolean(R.bool.config_swipeDisambiguation); mMiniKeyboardSlideAllowance = res.getDimension(R.dimen.mini_keyboard_slide_allowance); GestureDetector.SimpleOnGestureListener listener = new GestureDetector.SimpleOnGestureListener() { @Override public boolean onFling(MotionEvent me1, MotionEvent me2, float velocityX, float velocityY) { final float absX = Math.abs(velocityX); final float absY = Math.abs(velocityY); float deltaX = me2.getX() - me1.getX(); float deltaY = me2.getY() - me1.getY(); mSwipeTracker.computeCurrentVelocity(1000); final float endingVelocityX = mSwipeTracker.getXVelocity(); final float endingVelocityY = mSwipeTracker.getYVelocity(); // Calculate swipe distance threshold based on screen width & height, // taking the smaller distance. int travelX = getWidth() / 3; int travelY = getHeight() / 3; int travelMin = Math.min(travelX, travelY); // Log.i(TAG, "onFling vX=" + velocityX + " vY=" + velocityY + " threshold=" + mSwipeThreshold // + " dX=" + deltaX + " dy=" + deltaY + " min=" + travelMin); if (velocityX > mSwipeThreshold && absY < absX && deltaX > travelMin) { if (mDisambiguateSwipe && endingVelocityX >= velocityX / 4) { if (swipeRight()) return true; } } else if (velocityX < -mSwipeThreshold && absY < absX && deltaX < -travelMin) { if (mDisambiguateSwipe && endingVelocityX <= velocityX / 4) { if (swipeLeft()) return true; } } else if (velocityY < -mSwipeThreshold && absX < absY && deltaY < -travelMin) { if (mDisambiguateSwipe && endingVelocityY <= velocityY / 4) { if (swipeUp()) return true; } } else if (velocityY > mSwipeThreshold && absX < absY / 2 && deltaY > travelMin) { if (mDisambiguateSwipe && endingVelocityY >= velocityY / 4) { if (swipeDown()) return true; } } return false; } }; final boolean ignoreMultitouch = true; mGestureDetector = new GestureDetector(getContext(), listener, null, ignoreMultitouch); mGestureDetector.setIsLongpressEnabled(false); mHasDistinctMultitouch = context.getPackageManager() .hasSystemFeature(PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH_DISTINCT); mKeyRepeatInterval = res.getInteger(R.integer.config_key_repeat_interval); } private boolean showHints7Bit() { return LatinIME.sKeyboardSettings.hintMode >= 1; } private boolean showHintsAll() { return LatinIME.sKeyboardSettings.hintMode >= 2; } public void setOnKeyboardActionListener(OnKeyboardActionListener listener) { mKeyboardActionListener = listener; for (PointerTracker tracker : mPointerTrackers) { tracker.setOnKeyboardActionListener(listener); } } /** * Returns the {@link OnKeyboardActionListener} object. * @return the listener attached to this keyboard */ protected OnKeyboardActionListener getOnKeyboardActionListener() { return mKeyboardActionListener; } /** * Attaches a keyboard to this view. The keyboard can be switched at any time and the * view will re-layout itself to accommodate the keyboard. * @see Keyboard * @see #getKeyboard() * @param keyboard the keyboard to display in this view */ public void setKeyboard(Keyboard keyboard) { if (mKeyboard != null) { dismissKeyPreview(); } //Log.i(TAG, "setKeyboard(" + keyboard + ") for " + this); // Remove any pending messages, except dismissing preview mHandler.cancelKeyTimers(); mHandler.cancelPopupPreview(); mKeyboard = keyboard; LatinImeLogger.onSetKeyboard(keyboard); mKeys = mKeyDetector.setKeyboard(keyboard, -getPaddingLeft(), -getPaddingTop() + mVerticalCorrection); mKeyboardVerticalGap = (int)getResources().getDimension(R.dimen.key_bottom_gap); for (PointerTracker tracker : mPointerTrackers) { tracker.setKeyboard(mKeys, mKeyHysteresisDistance); } mLabelScale = LatinIME.sKeyboardSettings.labelScalePref; if (keyboard.mLayoutRows >= 4) mLabelScale *= 5.0f / keyboard.mLayoutRows; requestLayout(); // Hint to reallocate the buffer if the size changed mKeyboardChanged = true; invalidateAllKeys(); computeProximityThreshold(keyboard); mMiniKeyboardCacheMain.clear(); mMiniKeyboardCacheShift.clear(); mMiniKeyboardCacheCaps.clear(); setRenderModeIfPossible(LatinIME.sKeyboardSettings.renderMode); mIgnoreMove = true; } /** * Returns the current keyboard being displayed by this view. * @return the currently attached keyboard * @see #setKeyboard(Keyboard) */ public Keyboard getKeyboard() { return mKeyboard; } /** * Return whether the device has distinct multi-touch panel. * @return true if the device has distinct multi-touch panel. */ public boolean hasDistinctMultitouch() { return mHasDistinctMultitouch; } /** * Sets the state of the shift key of the keyboard, if any. * @param shifted whether or not to enable the state of the shift key * @return true if the shift key state changed, false if there was no change */ public boolean setShiftState(int shiftState) { //Log.i(TAG, "setShifted " + shiftState); if (mKeyboard != null) { if (mKeyboard.setShiftState(shiftState)) { // The whole keyboard probably needs to be redrawn invalidateAllKeys(); return true; } } return false; } public void setCtrlIndicator(boolean active) { if (mKeyboard != null) { invalidateKey(mKeyboard.setCtrlIndicator(active)); } } public void setAltIndicator(boolean active) { if (mKeyboard != null) { invalidateKey(mKeyboard.setAltIndicator(active)); } } /** * Returns the state of the shift key of the keyboard, if any. * @return true if the shift is in a pressed state, false otherwise. If there is * no shift key on the keyboard or there is no keyboard attached, it returns false. */ public int getShiftState() { if (mKeyboard != null) { return mKeyboard.getShiftState(); } return Keyboard.SHIFT_OFF; } public boolean isShiftCaps() { return getShiftState() != Keyboard.SHIFT_OFF; } public boolean isShiftAll() { int state = getShiftState(); if (LatinIME.sKeyboardSettings.shiftLockModifiers) { return state == Keyboard.SHIFT_ON || state == Keyboard.SHIFT_LOCKED; } else { return state == Keyboard.SHIFT_ON; } } /** * Enables or disables the key feedback popup. This is a popup that shows a magnified * version of the depressed key. By default the preview is enabled. * @param previewEnabled whether or not to enable the key feedback popup * @see #isPreviewEnabled() */ public void setPreviewEnabled(boolean previewEnabled) { mShowPreview = previewEnabled; } /** * Returns the enabled state of the key feedback popup. * @return whether or not the key feedback popup is enabled * @see #setPreviewEnabled(boolean) */ public boolean isPreviewEnabled() { return mShowPreview; } private boolean isBlackSym() { return mSymbolColorScheme == 1; } public void setPopupParent(View v) { mMiniKeyboardParent = v; } public void setPopupOffset(int x, int y) { mPopupPreviewOffsetX = x; mPopupPreviewOffsetY = y; if (mPreviewPopup != null) mPreviewPopup.dismiss(); } /** * When enabled, calls to {@link OnKeyboardActionListener#onKey} will include key * codes for adjacent keys. When disabled, only the primary key code will be * reported. * @param enabled whether or not the proximity correction is enabled */ public void setProximityCorrectionEnabled(boolean enabled) { mKeyDetector.setProximityCorrectionEnabled(enabled); } /** * Returns true if proximity correction is enabled. */ public boolean isProximityCorrectionEnabled() { return mKeyDetector.isProximityCorrectionEnabled(); } @Override public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // Round up a little if (mKeyboard == null) { setMeasuredDimension( getPaddingLeft() + getPaddingRight(), getPaddingTop() + getPaddingBottom()); } else { int width = mKeyboard.getMinWidth() + getPaddingLeft() + getPaddingRight(); if (MeasureSpec.getSize(widthMeasureSpec) < width + 10) { width = MeasureSpec.getSize(widthMeasureSpec); } setMeasuredDimension( width, mKeyboard.getHeight() + getPaddingTop() + getPaddingBottom()); } } /** * Compute the average distance between adjacent keys (horizontally and vertically) * and square it to get the proximity threshold. We use a square here and in computing * the touch distance from a key's center to avoid taking a square root. * @param keyboard */ private void computeProximityThreshold(Keyboard keyboard) { if (keyboard == null) return; final Key[] keys = mKeys; if (keys == null) return; int length = keys.length; int dimensionSum = 0; for (int i = 0; i < length; i++) { Key key = keys[i]; dimensionSum += Math.min(key.width, key.height + mKeyboardVerticalGap) + key.gap; } if (dimensionSum < 0 || length == 0) return; mKeyDetector.setProximityThreshold((int) (dimensionSum * 1.4f / length)); } @Override public void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); mViewWidth = w; // Release the buffer, if any and it will be reallocated on the next draw mBuffer = null; } @Override public void onDraw(Canvas canvas) { super.onDraw(canvas); //Log.i(TAG, "onDraw called " + canvas.getClipBounds()); mCanvas = canvas; if (mDrawPending || mBuffer == null || mKeyboardChanged) { onBufferDraw(canvas); } if (mBuffer != null) canvas.drawBitmap(mBuffer, 0, 0, null); } private void drawDeadKeyLabel(Canvas canvas, String hint, int x, float baseline, Paint paint) { char c = hint.charAt(0); String accent = DeadAccentSequence.getSpacing(c); canvas.drawText(Keyboard.DEAD_KEY_PLACEHOLDER_STRING, x, baseline, paint); canvas.drawText(accent, x, baseline, paint); } private int getLabelHeight(Paint paint, int labelSize) { Integer labelHeightValue = mTextHeightCache.get(labelSize); if (labelHeightValue != null) { return labelHeightValue; } else { Rect textBounds = new Rect(); paint.getTextBounds(KEY_LABEL_HEIGHT_REFERENCE_CHAR, 0, 1, textBounds); int labelHeight = textBounds.height(); mTextHeightCache.put(labelSize, labelHeight); return labelHeight; } } private void onBufferDraw(Canvas canvas) { //Log.i(TAG, "onBufferDraw called"); if (/*mBuffer == null ||*/ mKeyboardChanged) { mKeyboard.setKeyboardWidth(mViewWidth); // if (mBuffer == null || mKeyboardChanged && // (mBuffer.getWidth() != getWidth() || mBuffer.getHeight() != getHeight())) { // // Make sure our bitmap is at least 1x1 // final int width = Math.max(1, getWidth()); // final int height = Math.max(1, getHeight()); // mBuffer = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); // mCanvas = new Canvas(mBuffer); // } invalidateAllKeys(); mKeyboardChanged = false; } //final Canvas canvas = mCanvas; //canvas.clipRect(mDirtyRect, Op.REPLACE); canvas.getClipBounds(mDirtyRect); //canvas.drawColor(Color.BLACK); if (mKeyboard == null) return; final Paint paint = mPaint; final Paint paintHint = mPaintHint; paintHint.setColor(mKeyHintColor); final Drawable keyBackground = mKeyBackground; final Rect clipRegion = mClipRegion; final Rect padding = mPadding; final int kbdPaddingLeft = getPaddingLeft(); final int kbdPaddingTop = getPaddingTop(); final Key[] keys = mKeys; final Key invalidKey = mInvalidatedKey; ColorFilter iconColorFilter = null; ColorFilter shadowColorFilter = null; if (mRecolorSymbols) { // TODO: cache these? iconColorFilter = new PorterDuffColorFilter( mKeyTextColor, PorterDuff.Mode.SRC_ATOP); shadowColorFilter = new PorterDuffColorFilter( mShadowColor, PorterDuff.Mode.SRC_ATOP); } boolean drawSingleKey = false; if (invalidKey != null && canvas.getClipBounds(clipRegion)) { // TODO we should use Rect.inset and Rect.contains here. // Is clipRegion completely contained within the invalidated key? if (invalidKey.x + kbdPaddingLeft - 1 <= clipRegion.left && invalidKey.y + kbdPaddingTop - 1 <= clipRegion.top && invalidKey.x + invalidKey.width + kbdPaddingLeft + 1 >= clipRegion.right && invalidKey.y + invalidKey.height + kbdPaddingTop + 1 >= clipRegion.bottom) { drawSingleKey = true; } } //canvas.drawColor(0x00000000, PorterDuff.Mode.CLEAR); final int keyCount = keys.length; int keysDrawn = 0; for (int i = 0; i < keyCount; i++) { final Key key = keys[i]; if (drawSingleKey && invalidKey != key) { continue; } if (!mDirtyRect.intersects( key.x + kbdPaddingLeft, key.y + kbdPaddingTop, key.x + key.width + kbdPaddingLeft, key.y + key.height + kbdPaddingTop)) { continue; } keysDrawn++; paint.setColor(key.isCursor ? mKeyCursorColor : mKeyTextColor); int[] drawableState = key.getCurrentDrawableState(); keyBackground.setState(drawableState); // Switch the character to uppercase if shift is pressed String label = key.getCaseLabel(); float yscale = 1.0f; final Rect bounds = keyBackground.getBounds(); if (key.width != bounds.right || key.height != bounds.bottom) { int minHeight = keyBackground.getMinimumHeight(); if (minHeight > key.height) { yscale = (float) key.height / minHeight; keyBackground.setBounds(0, 0, key.width, minHeight); } else { keyBackground.setBounds(0, 0, key.width, key.height); } } canvas.translate(key.x + kbdPaddingLeft, key.y + kbdPaddingTop); if (yscale != 1.0f) { canvas.save(); canvas.scale(1.0f, yscale); } if (mBackgroundAlpha != 255) { keyBackground.setAlpha(mBackgroundAlpha); } keyBackground.draw(canvas); if (yscale != 1.0f) canvas.restore(); boolean shouldDrawIcon = true; if (label != null) { // For characters, use large font. For labels like "Done", use small font. final int labelSize; if (label.length() > 1 && key.codes.length < 2) { //Log.i(TAG, "mLabelTextSize=" + mLabelTextSize + " LatinIME.sKeyboardSettings.labelScale=" + LatinIME.sKeyboardSettings.labelScale); labelSize = (int)(mLabelTextSize * mLabelScale); paint.setTypeface(Typeface.DEFAULT); } else { labelSize = (int)(mKeyTextSize * mLabelScale); paint.setTypeface(mKeyTextStyle); } paint.setFakeBoldText(key.isCursor); paint.setTextSize(labelSize); final int labelHeight = getLabelHeight(paint, labelSize); // Draw a drop shadow for the text paint.setShadowLayer(mShadowRadius, 0, 0, mShadowColor); // Draw hint label (if present) behind the main key String hint = key.getHintLabel(showHints7Bit(), showHintsAll()); if (!hint.equals("") && !(key.isShifted() && key.shiftLabel != null && hint.charAt(0) == key.shiftLabel.charAt(0))) { int hintTextSize = (int)(mKeyTextSize * 0.6 * mLabelScale); paintHint.setTextSize(hintTextSize); final int hintLabelHeight = getLabelHeight(paintHint, hintTextSize); int x = key.width - padding.right; int baseline = padding.top + hintLabelHeight * 12/10; if (Character.getType(hint.charAt(0)) == Character.NON_SPACING_MARK) { drawDeadKeyLabel(canvas, hint, x, baseline, paintHint); } else { canvas.drawText(hint, x, baseline, paintHint); } } // Draw alternate hint label (if present) behind the main key String altHint = key.getAltHintLabel(showHints7Bit(), showHintsAll()); if (!altHint.equals("")) { int hintTextSize = (int)(mKeyTextSize * 0.6 * mLabelScale); paintHint.setTextSize(hintTextSize); final int hintLabelHeight = getLabelHeight(paintHint, hintTextSize); int x = key.width - padding.right; int baseline = padding.top + hintLabelHeight * (hint.equals("") ? 12 : 26)/10; if (Character.getType(altHint.charAt(0)) == Character.NON_SPACING_MARK) { drawDeadKeyLabel(canvas, altHint, x, baseline, paintHint); } else { canvas.drawText(altHint, x, baseline, paintHint); } } // Draw main key label final int centerX = (key.width + padding.left - padding.right) / 2; final int centerY = (key.height + padding.top - padding.bottom) / 2; final float baseline = centerY + labelHeight * KEY_LABEL_VERTICAL_ADJUSTMENT_FACTOR; if (key.isDeadKey()) { drawDeadKeyLabel(canvas, label, centerX, baseline, paint); } else { canvas.drawText(label, centerX, baseline, paint); } if (key.isCursor) { // poor man's bold - FIXME // Turn off drop shadow paint.setShadowLayer(0, 0, 0, 0); canvas.drawText(label, centerX+0.5f, baseline, paint); canvas.drawText(label, centerX-0.5f, baseline, paint); canvas.drawText(label, centerX, baseline+0.5f, paint); canvas.drawText(label, centerX, baseline-0.5f, paint); } // Turn off drop shadow paint.setShadowLayer(0, 0, 0, 0); // Usually don't draw icon if label is not null, but we draw icon for the number // hint and popup hint. shouldDrawIcon = shouldDrawLabelAndIcon(key); } Drawable icon = key.icon; if (icon != null && shouldDrawIcon) { // Special handing for the upper-right number hint icons final int drawableWidth; final int drawableHeight; final int drawableX; final int drawableY; if (shouldDrawIconFully(key)) { drawableWidth = key.width; drawableHeight = key.height; drawableX = 0; drawableY = NUMBER_HINT_VERTICAL_ADJUSTMENT_PIXEL; } else { drawableWidth = icon.getIntrinsicWidth(); drawableHeight = icon.getIntrinsicHeight(); drawableX = (key.width + padding.left - padding.right - drawableWidth) / 2; drawableY = (key.height + padding.top - padding.bottom - drawableHeight) / 2; } canvas.translate(drawableX, drawableY); icon.setBounds(0, 0, drawableWidth, drawableHeight); if (shadowColorFilter != null && iconColorFilter != null) { // Re-color the icon to match the theme, and draw a shadow for it manually. // // This doesn't seem to look quite right, possibly a problem with using // premultiplied icon images? // Try EmbossMaskFilter, and/or offset? Configurable? BlurMaskFilter shadowBlur = new BlurMaskFilter(mShadowRadius, BlurMaskFilter.Blur.OUTER); Paint blurPaint = new Paint(); blurPaint.setMaskFilter(shadowBlur); Bitmap tmpIcon = Bitmap.createBitmap(key.width, key.height, Bitmap.Config.ARGB_8888); Canvas tmpCanvas = new Canvas(tmpIcon); icon.draw(tmpCanvas); int[] offsets = new int[2]; Bitmap shadowBitmap = tmpIcon.extractAlpha(blurPaint, offsets); Paint shadowPaint = new Paint(); shadowPaint.setColorFilter(shadowColorFilter); canvas.drawBitmap(shadowBitmap, offsets[0], offsets[1], shadowPaint); icon.setColorFilter(iconColorFilter); icon.draw(canvas); icon.setColorFilter(null); } else { icon.draw(canvas); } canvas.translate(-drawableX, -drawableY); } canvas.translate(-key.x - kbdPaddingLeft, -key.y - kbdPaddingTop); } //Log.i(TAG, "keysDrawn=" + keysDrawn); mInvalidatedKey = null; // Overlay a dark rectangle to dim the keyboard if (mMiniKeyboardVisible) { paint.setColor((int) (mBackgroundDimAmount * 0xFF) << 24); canvas.drawRect(0, 0, getWidth(), getHeight(), paint); } if (LatinIME.sKeyboardSettings.showTouchPos || DEBUG) { if (LatinIME.sKeyboardSettings.showTouchPos || mShowTouchPoints) { for (PointerTracker tracker : mPointerTrackers) { int startX = tracker.getStartX(); int startY = tracker.getStartY(); int lastX = tracker.getLastX(); int lastY = tracker.getLastY(); paint.setAlpha(128); paint.setColor(0xFFFF0000); canvas.drawCircle(startX, startY, 3, paint); canvas.drawLine(startX, startY, lastX, lastY, paint); paint.setColor(0xFF0000FF); canvas.drawCircle(lastX, lastY, 3, paint); paint.setColor(0xFF00FF00); canvas.drawCircle((startX + lastX) / 2, (startY + lastY) / 2, 2, paint); } } } mDrawPending = false; mDirtyRect.setEmpty(); } // TODO: clean up this method. private void dismissKeyPreview() { for (PointerTracker tracker : mPointerTrackers) tracker.updateKey(NOT_A_KEY); //Log.i(TAG, "dismissKeyPreview() for " + this); showPreview(NOT_A_KEY, null); } public void showPreview(int keyIndex, PointerTracker tracker) { int oldKeyIndex = mOldPreviewKeyIndex; mOldPreviewKeyIndex = keyIndex; final boolean isLanguageSwitchEnabled = (mKeyboard instanceof LatinKeyboard) && ((LatinKeyboard)mKeyboard).isLanguageSwitchEnabled(); // We should re-draw popup preview when 1) we need to hide the preview, 2) we will show // the space key preview and 3) pointer moves off the space key to other letter key, we // should hide the preview of the previous key. final boolean hidePreviewOrShowSpaceKeyPreview = (tracker == null) || tracker.isSpaceKey(keyIndex) || tracker.isSpaceKey(oldKeyIndex); // If key changed and preview is on or the key is space (language switch is enabled) if (oldKeyIndex != keyIndex && (mShowPreview || (hidePreviewOrShowSpaceKeyPreview && isLanguageSwitchEnabled))) { if (keyIndex == NOT_A_KEY) { mHandler.cancelPopupPreview(); mHandler.dismissPreview(mDelayAfterPreview); } else if (tracker != null) { int delay = mShowPreview ? mDelayBeforePreview : mDelayBeforeSpacePreview; mHandler.popupPreview(delay, keyIndex, tracker); } } } private void showKey(final int keyIndex, PointerTracker tracker) { Key key = tracker.getKey(keyIndex); if (key == null) return; //Log.i(TAG, "showKey() for " + this); // Should not draw hint icon in key preview Drawable icon = key.icon; if (icon != null && !shouldDrawLabelAndIcon(key)) { mPreviewText.setCompoundDrawables(null, null, null, key.iconPreview != null ? key.iconPreview : icon); mPreviewText.setText(null); } else { mPreviewText.setCompoundDrawables(null, null, null, null); mPreviewText.setText(key.getCaseLabel()); if (key.label.length() > 1 && key.codes.length < 2) { mPreviewText.setTextSize(TypedValue.COMPLEX_UNIT_PX, mKeyTextSize); mPreviewText.setTypeface(Typeface.DEFAULT_BOLD); } else { mPreviewText.setTextSize(TypedValue.COMPLEX_UNIT_PX, mPreviewTextSizeLarge); mPreviewText.setTypeface(mKeyTextStyle); } } mPreviewText.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)); int popupWidth = Math.max(mPreviewText.getMeasuredWidth(), key.width + mPreviewText.getPaddingLeft() + mPreviewText.getPaddingRight()); final int popupHeight = mPreviewHeight; LayoutParams lp = mPreviewText.getLayoutParams(); if (lp != null) { lp.width = popupWidth; lp.height = popupHeight; } int popupPreviewX = key.x - (popupWidth - key.width) / 2; int popupPreviewY = key.y - popupHeight + mPreviewOffset; mHandler.cancelDismissPreview(); if (mOffsetInWindow == null) { mOffsetInWindow = new int[2]; getLocationInWindow(mOffsetInWindow); mOffsetInWindow[0] += mPopupPreviewOffsetX; // Offset may be zero mOffsetInWindow[1] += mPopupPreviewOffsetY; // Offset may be zero int[] windowLocation = new int[2]; getLocationOnScreen(windowLocation); mWindowY = windowLocation[1]; } // Set the preview background state. // Retrieve and cache the popup keyboard if any. boolean hasPopup = (getLongPressKeyboard(key) != null); // Set background manually, the StateListDrawable doesn't work. mPreviewText.setBackgroundDrawable(getResources().getDrawable(hasPopup ? R.drawable.keyboard_key_feedback_more_background : R.drawable.keyboard_key_feedback_background)); popupPreviewX += mOffsetInWindow[0]; popupPreviewY += mOffsetInWindow[1]; // If the popup cannot be shown above the key, put it on the side if (popupPreviewY + mWindowY < 0) { // If the key you're pressing is on the left side of the keyboard, show the popup on // the right, offset by enough to see at least one key to the left/right. if (key.x + key.width <= getWidth() / 2) { popupPreviewX += (int) (key.width * 2.5); } else { popupPreviewX -= (int) (key.width * 2.5); } popupPreviewY += popupHeight; } if (mPreviewPopup.isShowing()) { mPreviewPopup.update(popupPreviewX, popupPreviewY, popupWidth, popupHeight); } else { mPreviewPopup.setWidth(popupWidth); mPreviewPopup.setHeight(popupHeight); mPreviewPopup.showAtLocation(mMiniKeyboardParent, Gravity.NO_GRAVITY, popupPreviewX, popupPreviewY); } // Record popup preview position to display mini-keyboard later at the same positon mPopupPreviewDisplayedY = popupPreviewY; mPreviewText.setVisibility(VISIBLE); } /** * Requests a redraw of the entire keyboard. Calling {@link #invalidate} is not sufficient * because the keyboard renders the keys to an off-screen buffer and an invalidate() only * draws the cached buffer. * @see #invalidateKey(Key) */ public void invalidateAllKeys() { mDirtyRect.union(0, 0, getWidth(), getHeight()); mDrawPending = true; invalidate(); } /** * Invalidates a key so that it will be redrawn on the next repaint. Use this method if only * one key is changing it's content. Any changes that affect the position or size of the key * may not be honored. * @param key key in the attached {@link Keyboard}. * @see #invalidateAllKeys */ public void invalidateKey(Key key) { if (key == null) return; mInvalidatedKey = key; // TODO we should clean up this and record key's region to use in onBufferDraw. mDirtyRect.union(key.x + getPaddingLeft(), key.y + getPaddingTop(), key.x + key.width + getPaddingLeft(), key.y + key.height + getPaddingTop()); //onBufferDraw(); invalidate(key.x + getPaddingLeft(), key.y + getPaddingTop(), key.x + key.width + getPaddingLeft(), key.y + key.height + getPaddingTop()); } private boolean openPopupIfRequired(int keyIndex, PointerTracker tracker) { // Check if we have a popup layout specified first. if (mPopupLayout == 0) { return false; } Key popupKey = tracker.getKey(keyIndex); if (popupKey == null) return false; if (tracker.isInSlidingKeyInput()) return false; boolean result = onLongPress(popupKey); if (result) { dismissKeyPreview(); mMiniKeyboardTrackerId = tracker.mPointerId; // Mark this tracker "already processed" and remove it from the pointer queue tracker.setAlreadyProcessed(); mPointerQueue.remove(tracker); } return result; } private void inflateMiniKeyboardContainer() { //Log.i(TAG, "inflateMiniKeyboardContainer(), mPopupLayout=" + mPopupLayout + " from " + this); LayoutInflater inflater = (LayoutInflater)getContext().getSystemService( Context.LAYOUT_INFLATER_SERVICE); View container = inflater.inflate(mPopupLayout, null); mMiniKeyboard = (LatinKeyboardBaseView)container.findViewById(R.id.LatinKeyboardBaseView); mMiniKeyboard.setOnKeyboardActionListener(new OnKeyboardActionListener() { public void onKey(int primaryCode, int[] keyCodes, int x, int y) { mKeyboardActionListener.onKey(primaryCode, keyCodes, x, y); dismissPopupKeyboard(); } public void onText(CharSequence text) { mKeyboardActionListener.onText(text); dismissPopupKeyboard(); } public void onCancel() { mKeyboardActionListener.onCancel(); dismissPopupKeyboard(); } public boolean swipeLeft() { return false; } public boolean swipeRight() { return false; } public boolean swipeUp() { return false; } public boolean swipeDown() { return false; } public void onPress(int primaryCode) { mKeyboardActionListener.onPress(primaryCode); } public void onRelease(int primaryCode) { mKeyboardActionListener.onRelease(primaryCode); } }); // Override default ProximityKeyDetector. mMiniKeyboard.mKeyDetector = new MiniKeyboardKeyDetector(mMiniKeyboardSlideAllowance); // Remove gesture detector on mini-keyboard mMiniKeyboard.mGestureDetector = null; mMiniKeyboard.setPopupParent(this); mMiniKeyboardContainer = container; } private static boolean isOneRowKeys(List<Key> keys) { if (keys.size() == 0) return false; final int edgeFlags = keys.get(0).edgeFlags; // HACK: The first key of mini keyboard which was inflated from xml and has multiple rows, // does not have both top and bottom edge flags on at the same time. On the other hand, // the first key of mini keyboard that was created with popupCharacters must have both top // and bottom edge flags on. // When you want to use one row mini-keyboard from xml file, make sure that the row has // both top and bottom edge flags set. return (edgeFlags & Keyboard.EDGE_TOP) != 0 && (edgeFlags & Keyboard.EDGE_BOTTOM) != 0; } private Keyboard getLongPressKeyboard(Key popupKey) { final WeakHashMap<Key, Keyboard> cache; if (popupKey.isDistinctCaps()) { cache = mMiniKeyboardCacheCaps; } else if (popupKey.isShifted()) { cache = mMiniKeyboardCacheShift; } else { cache = mMiniKeyboardCacheMain; } Keyboard kbd = cache.get(popupKey); if (kbd == null) { kbd = popupKey.getPopupKeyboard(getContext(), getPaddingLeft() + getPaddingRight()); if (kbd != null) cache.put(popupKey, kbd); } //Log.i(TAG, "getLongPressKeyboard returns " + kbd + " for " + popupKey); return kbd; } /** * Called when a key is long pressed. By default this will open any popup keyboard associated * with this key through the attributes popupLayout and popupCharacters. * @param popupKey the key that was long pressed * @return true if the long press is handled, false otherwise. Subclasses should call the * method on the base class if the subclass doesn't wish to handle the call. */ protected boolean onLongPress(Key popupKey) { // TODO if popupKey.popupCharacters has only one letter, send it as key without opening // mini keyboard. if (mPopupLayout == 0) return false; // No popups wanted Keyboard kbd = getLongPressKeyboard(popupKey); //Log.i(TAG, "onLongPress, kbd=" + kbd); if (kbd == null) return false; if (mMiniKeyboardContainer == null) { inflateMiniKeyboardContainer(); } if (mMiniKeyboard == null) return false; mMiniKeyboard.setKeyboard(kbd); mMiniKeyboardContainer.measure(MeasureSpec.makeMeasureSpec(getWidth(), MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(getHeight(), MeasureSpec.AT_MOST)); if (mWindowOffset == null) { mWindowOffset = new int[2]; getLocationInWindow(mWindowOffset); } // Get width of a key in the mini popup keyboard = "miniKeyWidth". // On the other hand, "popupKey.width" is width of the pressed key on the main keyboard. // We adjust the position of mini popup keyboard with the edge key in it: // a) When we have the leftmost key in popup keyboard directly above the pressed key // Right edges of both keys should be aligned for consistent default selection // b) When we have the rightmost key in popup keyboard directly above the pressed key // Left edges of both keys should be aligned for consistent default selection final List<Key> miniKeys = mMiniKeyboard.getKeyboard().getKeys(); final int miniKeyWidth = miniKeys.size() > 0 ? miniKeys.get(0).width : 0; int popupX = popupKey.x + mWindowOffset[0]; popupX += getPaddingLeft(); if (shouldAlignLeftmost(popupKey)) { popupX += popupKey.width - miniKeyWidth; // adjustment for a) described above popupX -= mMiniKeyboardContainer.getPaddingLeft(); } else { popupX += miniKeyWidth; // adjustment for b) described above popupX -= mMiniKeyboardContainer.getMeasuredWidth(); popupX += mMiniKeyboardContainer.getPaddingRight(); } int popupY = popupKey.y + mWindowOffset[1]; popupY += getPaddingTop(); popupY -= mMiniKeyboardContainer.getMeasuredHeight(); popupY += mMiniKeyboardContainer.getPaddingBottom(); final int x = popupX; final int y = mShowPreview && isOneRowKeys(miniKeys) ? mPopupPreviewDisplayedY : popupY; int adjustedX = x; if (x < 0) { adjustedX = 0; } else if (x > (getMeasuredWidth() - mMiniKeyboardContainer.getMeasuredWidth())) { adjustedX = getMeasuredWidth() - mMiniKeyboardContainer.getMeasuredWidth(); } mMiniKeyboardOriginX = adjustedX + mMiniKeyboardContainer.getPaddingLeft() - mWindowOffset[0]; mMiniKeyboardOriginY = y + mMiniKeyboardContainer.getPaddingTop() - mWindowOffset[1]; mMiniKeyboard.setPopupOffset(adjustedX, y); mMiniKeyboard.setShiftState(getShiftState()); // Mini keyboard needs no pop-up key preview displayed. mMiniKeyboard.setPreviewEnabled(false); mMiniKeyboardPopup.setContentView(mMiniKeyboardContainer); mMiniKeyboardPopup.setWidth(mMiniKeyboardContainer.getMeasuredWidth()); mMiniKeyboardPopup.setHeight(mMiniKeyboardContainer.getMeasuredHeight()); //Log.i(TAG, "About to show popup " + mMiniKeyboardPopup + " from " + this); mMiniKeyboardPopup.showAtLocation(this, Gravity.NO_GRAVITY, x, y); mMiniKeyboardVisible = true; // Inject down event on the key to mini keyboard. long eventTime = SystemClock.uptimeMillis(); mMiniKeyboardPopupTime = eventTime; MotionEvent downEvent = generateMiniKeyboardMotionEvent(MotionEvent.ACTION_DOWN, popupKey.x + popupKey.width / 2, popupKey.y + popupKey.height / 2, eventTime); mMiniKeyboard.onTouchEvent(downEvent); downEvent.recycle(); invalidateAllKeys(); return true; } private boolean shouldDrawIconFully(Key key) { return isNumberAtEdgeOfPopupChars(key) || isLatinF1Key(key) || LatinKeyboard.hasPuncOrSmileysPopup(key); } private boolean shouldDrawLabelAndIcon(Key key) { // isNumberAtEdgeOfPopupChars(key) || return isNonMicLatinF1Key(key) || LatinKeyboard.hasPuncOrSmileysPopup(key); } private boolean shouldAlignLeftmost(Key key) { return !key.popupReversed; } private boolean isLatinF1Key(Key key) { return (mKeyboard instanceof LatinKeyboard) && ((LatinKeyboard)mKeyboard).isF1Key(key); } private boolean isNonMicLatinF1Key(Key key) { return isLatinF1Key(key) && key.label != null; } private static boolean isNumberAtEdgeOfPopupChars(Key key) { return isNumberAtLeftmostPopupChar(key) || isNumberAtRightmostPopupChar(key); } /* package */ static boolean isNumberAtLeftmostPopupChar(Key key) { if (key.popupCharacters != null && key.popupCharacters.length() > 0 && isAsciiDigit(key.popupCharacters.charAt(0))) { return true; } return false; } /* package */ static boolean isNumberAtRightmostPopupChar(Key key) { if (key.popupCharacters != null && key.popupCharacters.length() > 0 && isAsciiDigit(key.popupCharacters.charAt(key.popupCharacters.length() - 1))) { return true; } return false; } private static boolean isAsciiDigit(char c) { return (c < 0x80) && Character.isDigit(c); } private MotionEvent generateMiniKeyboardMotionEvent(int action, int x, int y, long eventTime) { return MotionEvent.obtain(mMiniKeyboardPopupTime, eventTime, action, x - mMiniKeyboardOriginX, y - mMiniKeyboardOriginY, 0); } /*package*/ boolean enableSlideKeyHack() { return false; } private PointerTracker getPointerTracker(final int id) { final ArrayList<PointerTracker> pointers = mPointerTrackers; final Key[] keys = mKeys; final OnKeyboardActionListener listener = mKeyboardActionListener; // Create pointer trackers until we can get 'id+1'-th tracker, if needed. for (int i = pointers.size(); i <= id; i++) { final PointerTracker tracker = new PointerTracker(i, mHandler, mKeyDetector, this, getResources(), enableSlideKeyHack()); if (keys != null) tracker.setKeyboard(keys, mKeyHysteresisDistance); if (listener != null) tracker.setOnKeyboardActionListener(listener); pointers.add(tracker); } return pointers.get(id); } public boolean isInSlidingKeyInput() { if (mMiniKeyboardVisible) { return mMiniKeyboard.isInSlidingKeyInput(); } else { return mPointerQueue.isInSlidingKeyInput(); } } public int getPointerCount() { return mOldPointerCount; } @Override public boolean onTouchEvent(MotionEvent me) { return onTouchEvent(me, false); } public boolean onTouchEvent(MotionEvent me, boolean continuing) { final int action = me.getActionMasked(); final int pointerCount = me.getPointerCount(); final int oldPointerCount = mOldPointerCount; mOldPointerCount = pointerCount; // TODO: cleanup this code into a multi-touch to single-touch event converter class? // If the device does not have distinct multi-touch support panel, ignore all multi-touch // events except a transition from/to single-touch. if (!mHasDistinctMultitouch && pointerCount > 1 && oldPointerCount > 1) { return true; } // Track the last few movements to look for spurious swipes. mSwipeTracker.addMovement(me); // Gesture detector must be enabled only when mini-keyboard is not on the screen. if (!mMiniKeyboardVisible && mGestureDetector != null && mGestureDetector.onTouchEvent(me)) { dismissKeyPreview(); mHandler.cancelKeyTimers(); return true; } final long eventTime = me.getEventTime(); final int index = me.getActionIndex(); final int id = me.getPointerId(index); final int x = (int)me.getX(index); final int y = (int)me.getY(index); // Needs to be called after the gesture detector gets a turn, as it may have // displayed the mini keyboard if (mMiniKeyboardVisible) { final int miniKeyboardPointerIndex = me.findPointerIndex(mMiniKeyboardTrackerId); if (miniKeyboardPointerIndex >= 0 && miniKeyboardPointerIndex < pointerCount) { final int miniKeyboardX = (int)me.getX(miniKeyboardPointerIndex); final int miniKeyboardY = (int)me.getY(miniKeyboardPointerIndex); MotionEvent translated = generateMiniKeyboardMotionEvent(action, miniKeyboardX, miniKeyboardY, eventTime); mMiniKeyboard.onTouchEvent(translated); translated.recycle(); } return true; } if (mHandler.isInKeyRepeat()) { // It will keep being in the key repeating mode while the key is being pressed. if (action == MotionEvent.ACTION_MOVE) { return true; } final PointerTracker tracker = getPointerTracker(id); // Key repeating timer will be canceled if 2 or more keys are in action, and current // event (UP or DOWN) is non-modifier key. if (pointerCount > 1 && !tracker.isModifier()) { mHandler.cancelKeyRepeatTimer(); } // Up event will pass through. } // TODO: cleanup this code into a multi-touch to single-touch event converter class? // Translate mutli-touch event to single-touch events on the device that has no distinct // multi-touch panel. if (!mHasDistinctMultitouch) { // Use only main (id=0) pointer tracker. PointerTracker tracker = getPointerTracker(0); if (pointerCount == 1 && oldPointerCount == 2) { // Multi-touch to single touch transition. // Send a down event for the latest pointer. tracker.onDownEvent(x, y, eventTime); } else if (pointerCount == 2 && oldPointerCount == 1) { // Single-touch to multi-touch transition. // Send an up event for the last pointer. tracker.onUpEvent(tracker.getLastX(), tracker.getLastY(), eventTime); } else if (pointerCount == 1 && oldPointerCount == 1) { tracker.onTouchEvent(action, x, y, eventTime); } else { Log.w(TAG, "Unknown touch panel behavior: pointer count is " + pointerCount + " (old " + oldPointerCount + ")"); } if (continuing) tracker.setSlidingKeyInputState(true); return true; } if (action == MotionEvent.ACTION_MOVE) { if (!mIgnoreMove) { for (int i = 0; i < pointerCount; i++) { PointerTracker tracker = getPointerTracker(me.getPointerId(i)); tracker.onMoveEvent((int)me.getX(i), (int)me.getY(i), eventTime); } } } else { PointerTracker tracker = getPointerTracker(id); switch (action) { case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_POINTER_DOWN: mIgnoreMove = false; onDownEvent(tracker, x, y, eventTime); break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_POINTER_UP: mIgnoreMove = false; onUpEvent(tracker, x, y, eventTime); break; case MotionEvent.ACTION_CANCEL: onCancelEvent(tracker, x, y, eventTime); break; } if (continuing) tracker.setSlidingKeyInputState(true); } return true; } private void onDownEvent(PointerTracker tracker, int x, int y, long eventTime) { if (tracker.isOnModifierKey(x, y)) { // Before processing a down event of modifier key, all pointers already being tracked // should be released. mPointerQueue.releaseAllPointersExcept(null, eventTime); } tracker.onDownEvent(x, y, eventTime); mPointerQueue.add(tracker); } private void onUpEvent(PointerTracker tracker, int x, int y, long eventTime) { if (tracker.isModifier()) { // Before processing an up event of modifier key, all pointers already being tracked // should be released. mPointerQueue.releaseAllPointersExcept(tracker, eventTime); } else { int index = mPointerQueue.lastIndexOf(tracker); if (index >= 0) { mPointerQueue.releaseAllPointersOlderThan(tracker, eventTime); } else { Log.w(TAG, "onUpEvent: corresponding down event not found for pointer " + tracker.mPointerId); } } tracker.onUpEvent(x, y, eventTime); mPointerQueue.remove(tracker); } private void onCancelEvent(PointerTracker tracker, int x, int y, long eventTime) { tracker.onCancelEvent(x, y, eventTime); mPointerQueue.remove(tracker); } protected boolean swipeRight() { return mKeyboardActionListener.swipeRight(); } protected boolean swipeLeft() { return mKeyboardActionListener.swipeLeft(); } /*package*/ boolean swipeUp() { return mKeyboardActionListener.swipeUp(); } protected boolean swipeDown() { return mKeyboardActionListener.swipeDown(); } public void closing() { Log.i(TAG, "closing " + this); if (mPreviewPopup != null) mPreviewPopup.dismiss(); mHandler.cancelAllMessages(); dismissPopupKeyboard(); //mMiniKeyboardContainer = null; // TODO: destroy/recycle the views? //mMiniKeyboard = null; // TODO(klausw): use a global bitmap repository, keeping two bitmaps permanently - // one for main and one for popup. // // Allow having the backup bitmap be bigger than the canvas needed, only shrinking in rare cases - // for example if reducing the size of the main keyboard. //mBuffer = null; //mCanvas = null; mMiniKeyboardCacheMain.clear(); mMiniKeyboardCacheShift.clear(); mMiniKeyboardCacheCaps.clear(); } @Override public void onDetachedFromWindow() { super.onDetachedFromWindow(); //Log.i(TAG, "onDetachedFromWindow() for " + this); closing(); } protected boolean popupKeyboardIsShowing() { return mMiniKeyboardPopup != null && mMiniKeyboardPopup.isShowing(); } protected void dismissPopupKeyboard() { if (mMiniKeyboardPopup != null) { //Log.i(TAG, "dismissPopupKeyboard() " + mMiniKeyboardPopup + " showing=" + mMiniKeyboardPopup.isShowing()); if (mMiniKeyboardPopup.isShowing()) { mMiniKeyboardPopup.dismiss(); } mMiniKeyboardVisible = false; invalidateAllKeys(); } } public boolean handleBack() { if (mMiniKeyboardPopup != null && mMiniKeyboardPopup.isShowing()) { dismissPopupKeyboard(); return true; } return false; } }
Java
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.pocketworkstation.pckeyboard; import android.content.SharedPreferences; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * Reflection utils to call SharedPreferences$Editor.apply when possible, * falling back to commit when apply isn't available. */ public class SharedPreferencesCompat { private static final Method sApplyMethod = findApplyMethod(); private static Method findApplyMethod() { try { return SharedPreferences.Editor.class.getMethod("apply"); } catch (NoSuchMethodException unused) { // fall through } return null; } public static void apply(SharedPreferences.Editor editor) { if (sApplyMethod != null) { try { sApplyMethod.invoke(editor); return; } catch (InvocationTargetException unused) { // fall through } catch (IllegalAccessException unused) { // fall through } } editor.commit(); } }
Java
package org.pocketworkstation.pckeyboard; import android.content.Context; import android.content.res.TypedArray; import android.preference.DialogPreference; import android.util.AttributeSet; import android.view.View; import android.widget.SeekBar; import android.widget.TextView; /** * SeekBarPreference provides a dialog for editing float-valued preferences with a slider. */ public class SeekBarPreference extends DialogPreference { private TextView mMinText; private TextView mMaxText; private TextView mValText; private SeekBar mSeek; private float mMin; private float mMax; private float mVal; private float mPrevVal; private float mStep; private boolean mAsPercent; private boolean mLogScale; private String mDisplayFormat; public SeekBarPreference(Context context, AttributeSet attrs) { super(context, attrs); init(context, attrs); } protected void init(Context context, AttributeSet attrs) { setDialogLayoutResource(R.layout.seek_bar_dialog); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SeekBarPreference); mMin = a.getFloat(R.styleable.SeekBarPreference_minValue, 0.0f); mMax = a.getFloat(R.styleable.SeekBarPreference_maxValue, 100.0f); mStep = a.getFloat(R.styleable.SeekBarPreference_step, 0.0f); mAsPercent = a.getBoolean(R.styleable.SeekBarPreference_asPercent, false); mLogScale = a.getBoolean(R.styleable.SeekBarPreference_logScale, false); mDisplayFormat = a.getString(R.styleable.SeekBarPreference_displayFormat); } @Override protected Float onGetDefaultValue(TypedArray a, int index) { return a.getFloat(index, 0.0f); } @Override protected void onSetInitialValue(boolean restorePersistedValue, Object defaultValue) { if (restorePersistedValue) { setVal(getPersistedFloat(0.0f)); } else { setVal((Float) defaultValue); } savePrevVal(); } private String formatFloatDisplay(Float val) { // Use current locale for format, this is for display only. if (mAsPercent) { return String.format("%d%%", (int) (val * 100)); } if (mDisplayFormat != null) { return String.format(mDisplayFormat, val); } else { return Float.toString(val); } } private void showVal() { mValText.setText(formatFloatDisplay(mVal)); } protected void setVal(Float val) { mVal = val; } protected void savePrevVal() { mPrevVal = mVal; } protected void restoreVal() { mVal = mPrevVal; } protected String getValString() { return Float.toString(mVal); } private float percentToSteppedVal(int percent, float min, float max, float step, boolean logScale) { float val; if (logScale) { val = (float) Math.exp(percentToSteppedVal(percent, (float) Math.log(min), (float) Math.log(max), step, false)); } else { float delta = percent * (max - min) / 100; if (step != 0.0f) { delta = Math.round(delta / step) * step; } val = min + delta; } // Hack: Round number to 2 significant digits so that it looks nicer. val = Float.valueOf(String.format("%.2g", val)); return val; } private int getPercent(float val, float min, float max) { return (int) (100 * (val - min) / (max - min)); } private int getProgressVal() { if (mLogScale) { return getPercent((float) Math.log(mVal), (float) Math.log(mMin), (float) Math.log(mMax)); } else { return getPercent(mVal, mMin, mMax); } } @Override protected void onBindDialogView(View view) { mSeek = (SeekBar) view.findViewById(R.id.seekBarPref); mMinText = (TextView) view.findViewById(R.id.seekMin); mMaxText = (TextView) view.findViewById(R.id.seekMax); mValText = (TextView) view.findViewById(R.id.seekVal); showVal(); mMinText.setText(formatFloatDisplay(mMin)); mMaxText.setText(formatFloatDisplay(mMax)); mSeek.setProgress(getProgressVal()); mSeek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { public void onStopTrackingTouch(SeekBar seekBar) {} public void onStartTrackingTouch(SeekBar seekBar) {} public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if (fromUser) { setVal(percentToSteppedVal(progress, mMin, mMax, mStep, mLogScale)); mSeek.setProgress(getProgressVal()); } showVal(); } }); super.onBindDialogView(view); } @Override public CharSequence getSummary() { return formatFloatDisplay(mVal); } @Override protected void onDialogClosed(boolean positiveResult) { if (!positiveResult) { restoreVal(); return; } if (shouldPersist()) { persistFloat(mVal); savePrevVal(); } notifyChanged(); } }
Java
/* * Copyright (C) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.pocketworkstation.pckeyboard; import android.view.MotionEvent; class SwipeTracker { private static final int NUM_PAST = 4; private static final int LONGEST_PAST_TIME = 200; final EventRingBuffer mBuffer = new EventRingBuffer(NUM_PAST); private float mYVelocity; private float mXVelocity; public void addMovement(MotionEvent ev) { if (ev.getAction() == MotionEvent.ACTION_DOWN) { mBuffer.clear(); return; } long time = ev.getEventTime(); final int count = ev.getHistorySize(); for (int i = 0; i < count; i++) { addPoint(ev.getHistoricalX(i), ev.getHistoricalY(i), ev.getHistoricalEventTime(i)); } addPoint(ev.getX(), ev.getY(), time); } private void addPoint(float x, float y, long time) { final EventRingBuffer buffer = mBuffer; while (buffer.size() > 0) { long lastT = buffer.getTime(0); if (lastT >= time - LONGEST_PAST_TIME) break; buffer.dropOldest(); } buffer.add(x, y, time); } public void computeCurrentVelocity(int units) { computeCurrentVelocity(units, Float.MAX_VALUE); } public void computeCurrentVelocity(int units, float maxVelocity) { final EventRingBuffer buffer = mBuffer; final float oldestX = buffer.getX(0); final float oldestY = buffer.getY(0); final long oldestTime = buffer.getTime(0); float accumX = 0; float accumY = 0; final int count = buffer.size(); for (int pos = 1; pos < count; pos++) { final int dur = (int)(buffer.getTime(pos) - oldestTime); if (dur == 0) continue; float dist = buffer.getX(pos) - oldestX; float vel = (dist / dur) * units; // pixels/frame. if (accumX == 0) accumX = vel; else accumX = (accumX + vel) * .5f; dist = buffer.getY(pos) - oldestY; vel = (dist / dur) * units; // pixels/frame. if (accumY == 0) accumY = vel; else accumY = (accumY + vel) * .5f; } mXVelocity = accumX < 0.0f ? Math.max(accumX, -maxVelocity) : Math.min(accumX, maxVelocity); mYVelocity = accumY < 0.0f ? Math.max(accumY, -maxVelocity) : Math.min(accumY, maxVelocity); } public float getXVelocity() { return mXVelocity; } public float getYVelocity() { return mYVelocity; } static class EventRingBuffer { private final int bufSize; private final float xBuf[]; private final float yBuf[]; private final long timeBuf[]; private int top; // points new event private int end; // points oldest event private int count; // the number of valid data public EventRingBuffer(int max) { this.bufSize = max; xBuf = new float[max]; yBuf = new float[max]; timeBuf = new long[max]; clear(); } public void clear() { top = end = count = 0; } public int size() { return count; } // Position 0 points oldest event private int index(int pos) { return (end + pos) % bufSize; } private int advance(int index) { return (index + 1) % bufSize; } public void add(float x, float y, long time) { xBuf[top] = x; yBuf[top] = y; timeBuf[top] = time; top = advance(top); if (count < bufSize) { count++; } else { end = advance(end); } } public float getX(int pos) { return xBuf[index(pos)]; } public float getY(int pos) { return yBuf[index(pos)]; } public long getTime(int pos) { return timeBuf[index(pos)]; } public void dropOldest() { count--; end = advance(end); } } }
Java
/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.pocketworkstation.pckeyboard; import android.app.backup.BackupManager; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.ListPreference; import android.preference.PreferenceActivity; public class PrefScreenView extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener { private ListPreference mRenderModePreference; @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); addPreferencesFromResource(R.xml.prefs_view); SharedPreferences prefs = getPreferenceManager().getSharedPreferences(); prefs.registerOnSharedPreferenceChangeListener(this); mRenderModePreference = (ListPreference) findPreference(LatinIME.PREF_RENDER_MODE); } @Override protected void onDestroy() { getPreferenceManager().getSharedPreferences().unregisterOnSharedPreferenceChangeListener( this); super.onDestroy(); } public void onSharedPreferenceChanged(SharedPreferences prefs, String key) { (new BackupManager(this)).dataChanged(); } @Override protected void onResume() { super.onResume(); if (LatinKeyboardBaseView.sSetRenderMode == null) { mRenderModePreference.setEnabled(false); mRenderModePreference.setSummary(R.string.render_mode_unavailable); } } }
Java
/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.pocketworkstation.pckeyboard; import android.content.SharedPreferences; import android.content.res.Configuration; import android.content.res.Resources; import android.preference.PreferenceManager; import android.util.Log; import android.view.InflateException; import java.lang.ref.SoftReference; import java.util.Arrays; import java.util.HashMap; import java.util.Locale; public class KeyboardSwitcher implements SharedPreferences.OnSharedPreferenceChangeListener { private static String TAG = "PCKeyboardKbSw"; public static final int MODE_NONE = 0; public static final int MODE_TEXT = 1; public static final int MODE_SYMBOLS = 2; public static final int MODE_PHONE = 3; public static final int MODE_URL = 4; public static final int MODE_EMAIL = 5; public static final int MODE_IM = 6; public static final int MODE_WEB = 7; // Main keyboard layouts without the settings key public static final int KEYBOARDMODE_NORMAL = R.id.mode_normal; public static final int KEYBOARDMODE_URL = R.id.mode_url; public static final int KEYBOARDMODE_EMAIL = R.id.mode_email; public static final int KEYBOARDMODE_IM = R.id.mode_im; public static final int KEYBOARDMODE_WEB = R.id.mode_webentry; // Main keyboard layouts with the settings key public static final int KEYBOARDMODE_NORMAL_WITH_SETTINGS_KEY = R.id.mode_normal_with_settings_key; public static final int KEYBOARDMODE_URL_WITH_SETTINGS_KEY = R.id.mode_url_with_settings_key; public static final int KEYBOARDMODE_EMAIL_WITH_SETTINGS_KEY = R.id.mode_email_with_settings_key; public static final int KEYBOARDMODE_IM_WITH_SETTINGS_KEY = R.id.mode_im_with_settings_key; public static final int KEYBOARDMODE_WEB_WITH_SETTINGS_KEY = R.id.mode_webentry_with_settings_key; // Symbols keyboard layout without the settings key public static final int KEYBOARDMODE_SYMBOLS = R.id.mode_symbols; // Symbols keyboard layout with the settings key public static final int KEYBOARDMODE_SYMBOLS_WITH_SETTINGS_KEY = R.id.mode_symbols_with_settings_key; public static final String DEFAULT_LAYOUT_ID = "0"; public static final String PREF_KEYBOARD_LAYOUT = "pref_keyboard_layout"; private static final int[] THEMES = new int[] { R.layout.input_ics, R.layout.input_gingerbread, R.layout.input_stone_bold, R.layout.input_trans_neon, }; // Tables which contains resource ids for each character theme color private static final int KBD_PHONE = R.xml.kbd_phone; private static final int KBD_PHONE_SYMBOLS = R.xml.kbd_phone_symbols; private static final int KBD_SYMBOLS = R.xml.kbd_symbols; private static final int KBD_SYMBOLS_SHIFT = R.xml.kbd_symbols_shift; private static final int KBD_QWERTY = R.xml.kbd_qwerty; private static final int KBD_FULL = R.xml.kbd_full; private static final int KBD_FULL_FN = R.xml.kbd_full_fn; private static final int KBD_COMPACT = R.xml.kbd_compact; private static final int KBD_COMPACT_FN = R.xml.kbd_compact_fn; private LatinKeyboardView mInputView; private static final int[] ALPHABET_MODES = { KEYBOARDMODE_NORMAL, KEYBOARDMODE_URL, KEYBOARDMODE_EMAIL, KEYBOARDMODE_IM, KEYBOARDMODE_WEB, KEYBOARDMODE_NORMAL_WITH_SETTINGS_KEY, KEYBOARDMODE_URL_WITH_SETTINGS_KEY, KEYBOARDMODE_EMAIL_WITH_SETTINGS_KEY, KEYBOARDMODE_IM_WITH_SETTINGS_KEY, KEYBOARDMODE_WEB_WITH_SETTINGS_KEY }; private LatinIME mInputMethodService; private KeyboardId mSymbolsId; private KeyboardId mSymbolsShiftedId; private KeyboardId mCurrentId; private final HashMap<KeyboardId, SoftReference<LatinKeyboard>> mKeyboards = new HashMap<KeyboardId, SoftReference<LatinKeyboard>>(); private int mMode = MODE_NONE; /** One of the MODE_XXX values */ private int mImeOptions; private boolean mIsSymbols; private int mFullMode; /** * mIsAutoCompletionActive indicates that auto completed word will be input * instead of what user actually typed. */ private boolean mIsAutoCompletionActive; private boolean mHasVoice; private boolean mVoiceOnPrimary; private boolean mPreferSymbols; private static final int AUTO_MODE_SWITCH_STATE_ALPHA = 0; private static final int AUTO_MODE_SWITCH_STATE_SYMBOL_BEGIN = 1; private static final int AUTO_MODE_SWITCH_STATE_SYMBOL = 2; // The following states are used only on the distinct multi-touch panel // devices. private static final int AUTO_MODE_SWITCH_STATE_MOMENTARY = 3; private static final int AUTO_MODE_SWITCH_STATE_CHORDING = 4; private int mAutoModeSwitchState = AUTO_MODE_SWITCH_STATE_ALPHA; // Indicates whether or not we have the settings key private boolean mHasSettingsKey; private static final int SETTINGS_KEY_MODE_AUTO = R.string.settings_key_mode_auto; private static final int SETTINGS_KEY_MODE_ALWAYS_SHOW = R.string.settings_key_mode_always_show; // NOTE: No need to have SETTINGS_KEY_MODE_ALWAYS_HIDE here because it's not // being referred to // in the source code now. // Default is SETTINGS_KEY_MODE_AUTO. private static final int DEFAULT_SETTINGS_KEY_MODE = SETTINGS_KEY_MODE_AUTO; private int mLastDisplayWidth; private LanguageSwitcher mLanguageSwitcher; private int mLayoutId; private static final KeyboardSwitcher sInstance = new KeyboardSwitcher(); public static KeyboardSwitcher getInstance() { return sInstance; } private KeyboardSwitcher() { // Intentional empty constructor for singleton. } public static void init(LatinIME ims) { sInstance.mInputMethodService = ims; final SharedPreferences prefs = PreferenceManager .getDefaultSharedPreferences(ims); sInstance.mLayoutId = Integer.valueOf(prefs.getString( PREF_KEYBOARD_LAYOUT, DEFAULT_LAYOUT_ID)); sInstance.updateSettingsKeyState(prefs); prefs.registerOnSharedPreferenceChangeListener(sInstance); sInstance.mSymbolsId = sInstance.makeSymbolsId(false); sInstance.mSymbolsShiftedId = sInstance.makeSymbolsShiftedId(false); } /** * Sets the input locale, when there are multiple locales for input. If no * locale switching is required, then the locale should be set to null. * * @param locale * the current input locale, or null for default locale with no * locale button. */ public void setLanguageSwitcher(LanguageSwitcher languageSwitcher) { mLanguageSwitcher = languageSwitcher; languageSwitcher.getInputLocale(); // for side effect } private KeyboardId makeSymbolsId(boolean hasVoice) { if (mFullMode == 1) { return new KeyboardId(KBD_COMPACT_FN, KEYBOARDMODE_SYMBOLS, true, hasVoice); } else if (mFullMode == 2) { return new KeyboardId(KBD_FULL_FN, KEYBOARDMODE_SYMBOLS, true, hasVoice); } return new KeyboardId(KBD_SYMBOLS, mHasSettingsKey ? KEYBOARDMODE_SYMBOLS_WITH_SETTINGS_KEY : KEYBOARDMODE_SYMBOLS, false, hasVoice); } private KeyboardId makeSymbolsShiftedId(boolean hasVoice) { if (mFullMode > 0) return null; return new KeyboardId(KBD_SYMBOLS_SHIFT, mHasSettingsKey ? KEYBOARDMODE_SYMBOLS_WITH_SETTINGS_KEY : KEYBOARDMODE_SYMBOLS, false, hasVoice); } public void makeKeyboards(boolean forceCreate) { mFullMode = LatinIME.sKeyboardSettings.keyboardMode; mSymbolsId = makeSymbolsId(mHasVoice && !mVoiceOnPrimary); mSymbolsShiftedId = makeSymbolsShiftedId(mHasVoice && !mVoiceOnPrimary); if (forceCreate) mKeyboards.clear(); // Configuration change is coming after the keyboard gets recreated. So // don't rely on that. // If keyboards have already been made, check if we have a screen width // change and // create the keyboard layouts again at the correct orientation int displayWidth = mInputMethodService.getMaxWidth(); if (displayWidth == mLastDisplayWidth) return; mLastDisplayWidth = displayWidth; if (!forceCreate) mKeyboards.clear(); } /** * Represents the parameters necessary to construct a new LatinKeyboard, * which also serve as a unique identifier for each keyboard type. */ private static class KeyboardId { // TODO: should have locale and portrait/landscape orientation? public final int mXml; public final int mKeyboardMode; /** A KEYBOARDMODE_XXX value */ public final boolean mEnableShiftLock; public final boolean mHasVoice; public final float mKeyboardHeightPercent; public final boolean mUsingExtension; private final int mHashCode; public KeyboardId(int xml, int mode, boolean enableShiftLock, boolean hasVoice) { this.mXml = xml; this.mKeyboardMode = mode; this.mEnableShiftLock = enableShiftLock; this.mHasVoice = hasVoice; this.mKeyboardHeightPercent = LatinIME.sKeyboardSettings.keyboardHeightPercent; this.mUsingExtension = LatinIME.sKeyboardSettings.useExtension; this.mHashCode = Arrays.hashCode(new Object[] { xml, mode, enableShiftLock, hasVoice }); } @Override public boolean equals(Object other) { return other instanceof KeyboardId && equals((KeyboardId) other); } private boolean equals(KeyboardId other) { return other != null && other.mXml == this.mXml && other.mKeyboardMode == this.mKeyboardMode && other.mUsingExtension == this.mUsingExtension && other.mEnableShiftLock == this.mEnableShiftLock && other.mHasVoice == this.mHasVoice; } @Override public int hashCode() { return mHashCode; } } public void setVoiceMode(boolean enableVoice, boolean voiceOnPrimary) { if (enableVoice != mHasVoice || voiceOnPrimary != mVoiceOnPrimary) { mKeyboards.clear(); } mHasVoice = enableVoice; mVoiceOnPrimary = voiceOnPrimary; setKeyboardMode(mMode, mImeOptions, mHasVoice, mIsSymbols); } private boolean hasVoiceButton(boolean isSymbols) { return mHasVoice && (isSymbols != mVoiceOnPrimary); } public void setKeyboardMode(int mode, int imeOptions, boolean enableVoice) { mAutoModeSwitchState = AUTO_MODE_SWITCH_STATE_ALPHA; mPreferSymbols = mode == MODE_SYMBOLS; if (mode == MODE_SYMBOLS) { mode = MODE_TEXT; } try { setKeyboardMode(mode, imeOptions, enableVoice, mPreferSymbols); } catch (RuntimeException e) { LatinImeLogger.logOnException(mode + "," + imeOptions + "," + mPreferSymbols, e); } } private void setKeyboardMode(int mode, int imeOptions, boolean enableVoice, boolean isSymbols) { if (mInputView == null) return; mMode = mode; mImeOptions = imeOptions; if (enableVoice != mHasVoice) { // TODO clean up this unnecessary recursive call. setVoiceMode(enableVoice, mVoiceOnPrimary); } mIsSymbols = isSymbols; mInputView.setPreviewEnabled(mInputMethodService.getPopupOn()); KeyboardId id = getKeyboardId(mode, imeOptions, isSymbols); LatinKeyboard keyboard = null; keyboard = getKeyboard(id); if (mode == MODE_PHONE) { mInputView.setPhoneKeyboard(keyboard); } mCurrentId = id; mInputView.setKeyboard(keyboard); keyboard.setShiftState(Keyboard.SHIFT_OFF); keyboard.setImeOptions(mInputMethodService.getResources(), mMode, imeOptions); keyboard.updateSymbolIcons(mIsAutoCompletionActive); } private LatinKeyboard getKeyboard(KeyboardId id) { SoftReference<LatinKeyboard> ref = mKeyboards.get(id); LatinKeyboard keyboard = (ref == null) ? null : ref.get(); if (keyboard == null) { Resources orig = mInputMethodService.getResources(); Configuration conf = orig.getConfiguration(); Locale saveLocale = conf.locale; conf.locale = LatinIME.sKeyboardSettings.inputLocale; orig.updateConfiguration(conf, null); keyboard = new LatinKeyboard(mInputMethodService, id.mXml, id.mKeyboardMode, id.mKeyboardHeightPercent); keyboard.setVoiceMode(hasVoiceButton(id.mXml == R.xml.kbd_symbols), mHasVoice); keyboard.setLanguageSwitcher(mLanguageSwitcher, mIsAutoCompletionActive); // if (isFullMode()) { // keyboard.setExtension(new LatinKeyboard(mInputMethodService, // R.xml.kbd_extension_full, 0, id.mRowHeightPercent)); // } else if (isAlphabetMode()) { // TODO: not in full keyboard mode? Per-mode extension kbd? // keyboard.setExtension(new LatinKeyboard(mInputMethodService, // R.xml.kbd_extension, 0, id.mRowHeightPercent)); // } if (id.mEnableShiftLock) { keyboard.enableShiftLock(); } mKeyboards.put(id, new SoftReference<LatinKeyboard>(keyboard)); conf.locale = saveLocale; orig.updateConfiguration(conf, null); } return keyboard; } public boolean isFullMode() { return mFullMode > 0; } private KeyboardId getKeyboardId(int mode, int imeOptions, boolean isSymbols) { boolean hasVoice = hasVoiceButton(isSymbols); if (mFullMode > 0) { switch (mode) { case MODE_TEXT: case MODE_URL: case MODE_EMAIL: case MODE_IM: case MODE_WEB: return new KeyboardId(mFullMode == 1 ? KBD_COMPACT : KBD_FULL, KEYBOARDMODE_NORMAL, true, hasVoice); } } // TODO: generalize for any KeyboardId int keyboardRowsResId = KBD_QWERTY; if (isSymbols) { if (mode == MODE_PHONE) { return new KeyboardId(KBD_PHONE_SYMBOLS, 0, false, hasVoice); } else { return new KeyboardId( KBD_SYMBOLS, mHasSettingsKey ? KEYBOARDMODE_SYMBOLS_WITH_SETTINGS_KEY : KEYBOARDMODE_SYMBOLS, false, hasVoice); } } switch (mode) { case MODE_NONE: LatinImeLogger.logOnWarning("getKeyboardId:" + mode + "," + imeOptions + "," + isSymbols); /* fall through */ case MODE_TEXT: return new KeyboardId(keyboardRowsResId, mHasSettingsKey ? KEYBOARDMODE_NORMAL_WITH_SETTINGS_KEY : KEYBOARDMODE_NORMAL, true, hasVoice); case MODE_SYMBOLS: return new KeyboardId(KBD_SYMBOLS, mHasSettingsKey ? KEYBOARDMODE_SYMBOLS_WITH_SETTINGS_KEY : KEYBOARDMODE_SYMBOLS, false, hasVoice); case MODE_PHONE: return new KeyboardId(KBD_PHONE, 0, false, hasVoice); case MODE_URL: return new KeyboardId(keyboardRowsResId, mHasSettingsKey ? KEYBOARDMODE_URL_WITH_SETTINGS_KEY : KEYBOARDMODE_URL, true, hasVoice); case MODE_EMAIL: return new KeyboardId(keyboardRowsResId, mHasSettingsKey ? KEYBOARDMODE_EMAIL_WITH_SETTINGS_KEY : KEYBOARDMODE_EMAIL, true, hasVoice); case MODE_IM: return new KeyboardId(keyboardRowsResId, mHasSettingsKey ? KEYBOARDMODE_IM_WITH_SETTINGS_KEY : KEYBOARDMODE_IM, true, hasVoice); case MODE_WEB: return new KeyboardId(keyboardRowsResId, mHasSettingsKey ? KEYBOARDMODE_WEB_WITH_SETTINGS_KEY : KEYBOARDMODE_WEB, true, hasVoice); } return null; } public int getKeyboardMode() { return mMode; } public boolean isAlphabetMode() { if (mCurrentId == null) { return false; } int currentMode = mCurrentId.mKeyboardMode; if (mFullMode > 0 && currentMode == KEYBOARDMODE_NORMAL) return true; for (Integer mode : ALPHABET_MODES) { if (currentMode == mode) { return true; } } return false; } public void setShiftState(int shiftState) { if (mInputView != null) { mInputView.setShiftState(shiftState); } } public void setFn(boolean useFn) { if (mInputView == null) return; int oldShiftState = mInputView.getShiftState(); if (useFn) { LatinKeyboard kbd = getKeyboard(mSymbolsId); kbd.enableShiftLock(); mCurrentId = mSymbolsId; mInputView.setKeyboard(kbd); mInputView.setShiftState(oldShiftState); } else { // Return to default keyboard state setKeyboardMode(mMode, mImeOptions, mHasVoice, false); mInputView.setShiftState(oldShiftState); } } public void setCtrlIndicator(boolean active) { if (mInputView == null) return; mInputView.setCtrlIndicator(active); } public void setAltIndicator(boolean active) { if (mInputView == null) return; mInputView.setAltIndicator(active); } public void toggleShift() { //Log.i(TAG, "toggleShift isAlphabetMode=" + isAlphabetMode() + " mSettings.fullMode=" + mSettings.fullMode); if (isAlphabetMode()) return; if (mFullMode > 0) { boolean shifted = mInputView.isShiftAll(); mInputView.setShiftState(shifted ? Keyboard.SHIFT_OFF : Keyboard.SHIFT_ON); return; } if (mCurrentId.equals(mSymbolsId) || !mCurrentId.equals(mSymbolsShiftedId)) { LatinKeyboard symbolsShiftedKeyboard = getKeyboard(mSymbolsShiftedId); mCurrentId = mSymbolsShiftedId; mInputView.setKeyboard(symbolsShiftedKeyboard); // Symbol shifted keyboard has a ALT_SYM key that has a caps lock style indicator. // To enable the indicator, we need to set the shift state appropriately. symbolsShiftedKeyboard.enableShiftLock(); symbolsShiftedKeyboard.setShiftState(Keyboard.SHIFT_LOCKED); symbolsShiftedKeyboard.setImeOptions(mInputMethodService .getResources(), mMode, mImeOptions); } else { LatinKeyboard symbolsKeyboard = getKeyboard(mSymbolsId); mCurrentId = mSymbolsId; mInputView.setKeyboard(symbolsKeyboard); symbolsKeyboard.enableShiftLock(); symbolsKeyboard.setShiftState(Keyboard.SHIFT_OFF); symbolsKeyboard.setImeOptions(mInputMethodService.getResources(), mMode, mImeOptions); } } public void onCancelInput() { // Snap back to the previous keyboard mode if the user cancels sliding // input. if (mAutoModeSwitchState == AUTO_MODE_SWITCH_STATE_MOMENTARY && getPointerCount() == 1) mInputMethodService.changeKeyboardMode(); } public void toggleSymbols() { setKeyboardMode(mMode, mImeOptions, mHasVoice, !mIsSymbols); if (mIsSymbols && !mPreferSymbols) { mAutoModeSwitchState = AUTO_MODE_SWITCH_STATE_SYMBOL_BEGIN; } else { mAutoModeSwitchState = AUTO_MODE_SWITCH_STATE_ALPHA; } } public boolean hasDistinctMultitouch() { return mInputView != null && mInputView.hasDistinctMultitouch(); } public void setAutoModeSwitchStateMomentary() { mAutoModeSwitchState = AUTO_MODE_SWITCH_STATE_MOMENTARY; } public boolean isInMomentaryAutoModeSwitchState() { return mAutoModeSwitchState == AUTO_MODE_SWITCH_STATE_MOMENTARY; } public boolean isInChordingAutoModeSwitchState() { return mAutoModeSwitchState == AUTO_MODE_SWITCH_STATE_CHORDING; } public boolean isVibrateAndSoundFeedbackRequired() { return mInputView != null && !mInputView.isInSlidingKeyInput(); } private int getPointerCount() { return mInputView == null ? 0 : mInputView.getPointerCount(); } /** * Updates state machine to figure out when to automatically snap back to * the previous mode. */ public void onKey(int key) { // Switch back to alpha mode if user types one or more non-space/enter // characters // followed by a space/enter switch (mAutoModeSwitchState) { case AUTO_MODE_SWITCH_STATE_MOMENTARY: // Only distinct multi touch devices can be in this state. // On non-distinct multi touch devices, mode change key is handled // by {@link onKey}, // not by {@link onPress} and {@link onRelease}. So, on such // devices, // {@link mAutoModeSwitchState} starts from {@link // AUTO_MODE_SWITCH_STATE_SYMBOL_BEGIN}, // or {@link AUTO_MODE_SWITCH_STATE_ALPHA}, not from // {@link AUTO_MODE_SWITCH_STATE_MOMENTARY}. if (key == LatinKeyboard.KEYCODE_MODE_CHANGE) { // Detected only the mode change key has been pressed, and then // released. if (mIsSymbols) { mAutoModeSwitchState = AUTO_MODE_SWITCH_STATE_SYMBOL_BEGIN; } else { mAutoModeSwitchState = AUTO_MODE_SWITCH_STATE_ALPHA; } } else if (getPointerCount() == 1) { // Snap back to the previous keyboard mode if the user pressed // the mode change key // and slid to other key, then released the finger. // If the user cancels the sliding input, snapping back to the // previous keyboard // mode is handled by {@link #onCancelInput}. mInputMethodService.changeKeyboardMode(); } else { // Chording input is being started. The keyboard mode will be // snapped back to the // previous mode in {@link onReleaseSymbol} when the mode change // key is released. mAutoModeSwitchState = AUTO_MODE_SWITCH_STATE_CHORDING; } break; case AUTO_MODE_SWITCH_STATE_SYMBOL_BEGIN: if (key != LatinIME.ASCII_SPACE && key != LatinIME.ASCII_ENTER && key >= 0) { mAutoModeSwitchState = AUTO_MODE_SWITCH_STATE_SYMBOL; } break; case AUTO_MODE_SWITCH_STATE_SYMBOL: // Snap back to alpha keyboard mode if user types one or more // non-space/enter // characters followed by a space/enter. if (key == LatinIME.ASCII_ENTER || key == LatinIME.ASCII_SPACE) { mInputMethodService.changeKeyboardMode(); } break; } } public LatinKeyboardView getInputView() { return mInputView; } public void recreateInputView() { changeLatinKeyboardView(mLayoutId, true); } private void changeLatinKeyboardView(int newLayout, boolean forceReset) { if (mLayoutId != newLayout || mInputView == null || forceReset) { if (mInputView != null) { mInputView.closing(); } if (THEMES.length <= newLayout) { newLayout = Integer.valueOf(DEFAULT_LAYOUT_ID); } LatinIMEUtil.GCUtils.getInstance().reset(); boolean tryGC = true; for (int i = 0; i < LatinIMEUtil.GCUtils.GC_TRY_LOOP_MAX && tryGC; ++i) { try { mInputView = (LatinKeyboardView) mInputMethodService .getLayoutInflater().inflate(THEMES[newLayout], null); tryGC = false; } catch (OutOfMemoryError e) { tryGC = LatinIMEUtil.GCUtils.getInstance().tryGCOrWait( mLayoutId + "," + newLayout, e); } catch (InflateException e) { tryGC = LatinIMEUtil.GCUtils.getInstance().tryGCOrWait( mLayoutId + "," + newLayout, e); } } mInputView.setExtensionLayoutResId(THEMES[newLayout]); mInputView.setOnKeyboardActionListener(mInputMethodService); mInputView.setPadding(0, 0, 0, 0); mLayoutId = newLayout; } mInputMethodService.mHandler.post(new Runnable() { public void run() { if (mInputView != null) { mInputMethodService.setInputView(mInputView); } mInputMethodService.updateInputViewShown(); } }); } public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (PREF_KEYBOARD_LAYOUT.equals(key)) { changeLatinKeyboardView(Integer.valueOf(sharedPreferences .getString(key, DEFAULT_LAYOUT_ID)), true); } else if (LatinIMESettings.PREF_SETTINGS_KEY.equals(key)) { updateSettingsKeyState(sharedPreferences); recreateInputView(); } } public void onAutoCompletionStateChanged(boolean isAutoCompletion) { if (isAutoCompletion != mIsAutoCompletionActive) { LatinKeyboardView keyboardView = getInputView(); mIsAutoCompletionActive = isAutoCompletion; keyboardView.invalidateKey(((LatinKeyboard) keyboardView .getKeyboard()) .onAutoCompletionStateChanged(isAutoCompletion)); } } private void updateSettingsKeyState(SharedPreferences prefs) { Resources resources = mInputMethodService.getResources(); final String settingsKeyMode = prefs.getString( LatinIMESettings.PREF_SETTINGS_KEY, resources .getString(DEFAULT_SETTINGS_KEY_MODE)); // We show the settings key when 1) SETTINGS_KEY_MODE_ALWAYS_SHOW or // 2) SETTINGS_KEY_MODE_AUTO and there are two or more enabled IMEs on // the system if (settingsKeyMode.equals(resources .getString(SETTINGS_KEY_MODE_ALWAYS_SHOW)) || (settingsKeyMode.equals(resources .getString(SETTINGS_KEY_MODE_AUTO)))) { mHasSettingsKey = true; } else { mHasSettingsKey = false; } } }
Java
/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.pocketworkstation.pckeyboard; import android.app.backup.BackupAgentHelper; import android.app.backup.SharedPreferencesBackupHelper; /** * Backs up the Latin IME shared preferences. */ public class LatinIMEBackupAgent extends BackupAgentHelper { @Override public void onCreate() { addHelper("shared_pref", new SharedPreferencesBackupHelper(this, getPackageName() + "_preferences")); } }
Java
/** * */ package org.pocketworkstation.pckeyboard; import android.content.Context; import android.preference.ListPreference; import android.util.AttributeSet; import android.util.Log; public class AutoSummaryListPreference extends ListPreference { private static final String TAG = "HK/AutoSummaryListPreference"; public AutoSummaryListPreference(Context context) { super(context); } public AutoSummaryListPreference(Context context, AttributeSet attrs) { super(context, attrs); } private void trySetSummary() { CharSequence entry = null; try { entry = getEntry(); } catch (ArrayIndexOutOfBoundsException e) { Log.i(TAG, "Malfunctioning ListPreference, can't get entry"); } if (entry != null) { //String percent = getResources().getString(R.string.percent); String percent = "percent"; setSummary(entry.toString().replace("%", " " + percent)); } } @Override public void setEntries(CharSequence[] entries) { super.setEntries(entries); trySetSummary(); } @Override public void setEntryValues(CharSequence[] entryValues) { super.setEntryValues(entryValues); trySetSummary(); } @Override public void setValue(String value) { super.setValue(value); trySetSummary(); } }
Java
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.pocketworkstation.pckeyboard; import java.util.LinkedList; import android.content.Context; import android.os.AsyncTask; /** * Base class for an in-memory dictionary that can grow dynamically and can * be searched for suggestions and valid words. */ public class ExpandableDictionary extends Dictionary { /** * There is difference between what java and native code can handle. * It uses 32 because Java stack overflows when greater value is used. */ protected static final int MAX_WORD_LENGTH = 32; private Context mContext; private char[] mWordBuilder = new char[MAX_WORD_LENGTH]; private int mDicTypeId; private int mMaxDepth; private int mInputLength; private int[] mNextLettersFrequencies; private StringBuilder sb = new StringBuilder(MAX_WORD_LENGTH); private static final char QUOTE = '\''; private boolean mRequiresReload; private boolean mUpdatingDictionary; // Use this lock before touching mUpdatingDictionary & mRequiresDownload private Object mUpdatingLock = new Object(); static class Node { char code; int frequency; boolean terminal; Node parent; NodeArray children; LinkedList<NextWord> ngrams; // Supports ngram } static class NodeArray { Node[] data; int length = 0; private static final int INCREMENT = 2; NodeArray() { data = new Node[INCREMENT]; } void add(Node n) { if (length + 1 > data.length) { Node[] tempData = new Node[length + INCREMENT]; if (length > 0) { System.arraycopy(data, 0, tempData, 0, length); } data = tempData; } data[length++] = n; } } static class NextWord { Node word; NextWord nextWord; int frequency; NextWord(Node word, int frequency) { this.word = word; this.frequency = frequency; } } private NodeArray mRoots; private int[][] mCodes; ExpandableDictionary(Context context, int dicTypeId) { mContext = context; clearDictionary(); mCodes = new int[MAX_WORD_LENGTH][]; mDicTypeId = dicTypeId; } public void loadDictionary() { synchronized (mUpdatingLock) { startDictionaryLoadingTaskLocked(); } } public void startDictionaryLoadingTaskLocked() { if (!mUpdatingDictionary) { mUpdatingDictionary = true; mRequiresReload = false; new LoadDictionaryTask().execute(); } } public void setRequiresReload(boolean reload) { synchronized (mUpdatingLock) { mRequiresReload = reload; } } public boolean getRequiresReload() { return mRequiresReload; } /** Override to load your dictionary here, on a background thread. */ public void loadDictionaryAsync() { } Context getContext() { return mContext; } int getMaxWordLength() { return MAX_WORD_LENGTH; } public void addWord(String word, int frequency) { addWordRec(mRoots, word, 0, frequency, null); } private void addWordRec(NodeArray children, final String word, final int depth, final int frequency, Node parentNode) { final int wordLength = word.length(); final char c = word.charAt(depth); // Does children have the current character? final int childrenLength = children.length; Node childNode = null; boolean found = false; for (int i = 0; i < childrenLength; i++) { childNode = children.data[i]; if (childNode.code == c) { found = true; break; } } if (!found) { childNode = new Node(); childNode.code = c; childNode.parent = parentNode; children.add(childNode); } if (wordLength == depth + 1) { // Terminate this word childNode.terminal = true; childNode.frequency = Math.max(frequency, childNode.frequency); if (childNode.frequency > 255) childNode.frequency = 255; return; } if (childNode.children == null) { childNode.children = new NodeArray(); } addWordRec(childNode.children, word, depth + 1, frequency, childNode); } @Override public void getWords(final WordComposer codes, final WordCallback callback, int[] nextLettersFrequencies) { synchronized (mUpdatingLock) { // If we need to update, start off a background task if (mRequiresReload) startDictionaryLoadingTaskLocked(); // Currently updating contacts, don't return any results. if (mUpdatingDictionary) return; } mInputLength = codes.size(); mNextLettersFrequencies = nextLettersFrequencies; if (mCodes.length < mInputLength) mCodes = new int[mInputLength][]; // Cache the codes so that we don't have to lookup an array list for (int i = 0; i < mInputLength; i++) { mCodes[i] = codes.getCodesAt(i); } mMaxDepth = mInputLength * 3; getWordsRec(mRoots, codes, mWordBuilder, 0, false, 1, 0, -1, callback); for (int i = 0; i < mInputLength; i++) { getWordsRec(mRoots, codes, mWordBuilder, 0, false, 1, 0, i, callback); } } @Override public synchronized boolean isValidWord(CharSequence word) { synchronized (mUpdatingLock) { // If we need to update, start off a background task if (mRequiresReload) startDictionaryLoadingTaskLocked(); if (mUpdatingDictionary) return false; } final int freq = getWordFrequency(word); return freq > -1; } /** * Returns the word's frequency or -1 if not found */ public int getWordFrequency(CharSequence word) { Node node = searchNode(mRoots, word, 0, word.length()); return (node == null) ? -1 : node.frequency; } /** * Recursively traverse the tree for words that match the input. Input consists of * a list of arrays. Each item in the list is one input character position. An input * character is actually an array of multiple possible candidates. This function is not * optimized for speed, assuming that the user dictionary will only be a few hundred words in * size. * @param roots node whose children have to be search for matches * @param codes the input character codes * @param word the word being composed as a possible match * @param depth the depth of traversal - the length of the word being composed thus far * @param completion whether the traversal is now in completion mode - meaning that we've * exhausted the input and we're looking for all possible suffixes. * @param snr current weight of the word being formed * @param inputIndex position in the input characters. This can be off from the depth in * case we skip over some punctuations such as apostrophe in the traversal. That is, if you type * "wouldve", it could be matching "would've", so the depth will be one more than the * inputIndex * @param callback the callback class for adding a word */ protected void getWordsRec(NodeArray roots, final WordComposer codes, final char[] word, final int depth, boolean completion, int snr, int inputIndex, int skipPos, WordCallback callback) { final int count = roots.length; final int codeSize = mInputLength; // Optimization: Prune out words that are too long compared to how much was typed. if (depth > mMaxDepth) { return; } int[] currentChars = null; if (codeSize <= inputIndex) { completion = true; } else { currentChars = mCodes[inputIndex]; } for (int i = 0; i < count; i++) { final Node node = roots.data[i]; final char c = node.code; final char lowerC = toLowerCase(c); final boolean terminal = node.terminal; final NodeArray children = node.children; final int freq = node.frequency; if (completion) { word[depth] = c; if (terminal) { if (!callback.addWord(word, 0, depth + 1, freq * snr, mDicTypeId, DataType.UNIGRAM)) { return; } // Add to frequency of next letters for predictive correction if (mNextLettersFrequencies != null && depth >= inputIndex && skipPos < 0 && mNextLettersFrequencies.length > word[inputIndex]) { mNextLettersFrequencies[word[inputIndex]]++; } } if (children != null) { getWordsRec(children, codes, word, depth + 1, completion, snr, inputIndex, skipPos, callback); } } else if ((c == QUOTE && currentChars[0] != QUOTE) || depth == skipPos) { // Skip the ' and continue deeper word[depth] = c; if (children != null) { getWordsRec(children, codes, word, depth + 1, completion, snr, inputIndex, skipPos, callback); } } else { // Don't use alternatives if we're looking for missing characters final int alternativesSize = skipPos >= 0? 1 : currentChars.length; for (int j = 0; j < alternativesSize; j++) { final int addedAttenuation = (j > 0 ? 1 : 2); final int currentChar = currentChars[j]; if (currentChar == -1) { break; } if (currentChar == lowerC || currentChar == c) { word[depth] = c; if (codeSize == inputIndex + 1) { if (terminal) { if (INCLUDE_TYPED_WORD_IF_VALID || !same(word, depth + 1, codes.getTypedWord())) { int finalFreq = freq * snr * addedAttenuation; if (skipPos < 0) finalFreq *= FULL_WORD_FREQ_MULTIPLIER; callback.addWord(word, 0, depth + 1, finalFreq, mDicTypeId, DataType.UNIGRAM); } } if (children != null) { getWordsRec(children, codes, word, depth + 1, true, snr * addedAttenuation, inputIndex + 1, skipPos, callback); } } else if (children != null) { getWordsRec(children, codes, word, depth + 1, false, snr * addedAttenuation, inputIndex + 1, skipPos, callback); } } } } } } protected int setBigram(String word1, String word2, int frequency) { return addOrSetBigram(word1, word2, frequency, false); } protected int addBigram(String word1, String word2, int frequency) { return addOrSetBigram(word1, word2, frequency, true); } /** * Adds bigrams to the in-memory trie structure that is being used to retrieve any word * @param frequency frequency for this bigrams * @param addFrequency if true, it adds to current frequency * @return returns the final frequency */ private int addOrSetBigram(String word1, String word2, int frequency, boolean addFrequency) { Node firstWord = searchWord(mRoots, word1, 0, null); Node secondWord = searchWord(mRoots, word2, 0, null); LinkedList<NextWord> bigram = firstWord.ngrams; if (bigram == null || bigram.size() == 0) { firstWord.ngrams = new LinkedList<NextWord>(); bigram = firstWord.ngrams; } else { for (NextWord nw : bigram) { if (nw.word == secondWord) { if (addFrequency) { nw.frequency += frequency; } else { nw.frequency = frequency; } return nw.frequency; } } } NextWord nw = new NextWord(secondWord, frequency); firstWord.ngrams.add(nw); return frequency; } /** * Searches for the word and add the word if it does not exist. * @return Returns the terminal node of the word we are searching for. */ private Node searchWord(NodeArray children, String word, int depth, Node parentNode) { final int wordLength = word.length(); final char c = word.charAt(depth); // Does children have the current character? final int childrenLength = children.length; Node childNode = null; boolean found = false; for (int i = 0; i < childrenLength; i++) { childNode = children.data[i]; if (childNode.code == c) { found = true; break; } } if (!found) { childNode = new Node(); childNode.code = c; childNode.parent = parentNode; children.add(childNode); } if (wordLength == depth + 1) { // Terminate this word childNode.terminal = true; return childNode; } if (childNode.children == null) { childNode.children = new NodeArray(); } return searchWord(childNode.children, word, depth + 1, childNode); } // @VisibleForTesting boolean reloadDictionaryIfRequired() { synchronized (mUpdatingLock) { // If we need to update, start off a background task if (mRequiresReload) startDictionaryLoadingTaskLocked(); // Currently updating contacts, don't return any results. return mUpdatingDictionary; } } private void runReverseLookUp(final CharSequence previousWord, final WordCallback callback) { Node prevWord = searchNode(mRoots, previousWord, 0, previousWord.length()); if (prevWord != null && prevWord.ngrams != null) { reverseLookUp(prevWord.ngrams, callback); } } @Override public void getBigrams(final WordComposer codes, final CharSequence previousWord, final WordCallback callback, int[] nextLettersFrequencies) { if (!reloadDictionaryIfRequired()) { runReverseLookUp(previousWord, callback); } } /** * Used only for testing purposes * This function will wait for loading from database to be done */ void waitForDictionaryLoading() { while (mUpdatingDictionary) { try { Thread.sleep(100); } catch (InterruptedException e) { } } } /** * reverseLookUp retrieves the full word given a list of terminal nodes and adds those words * through callback. * @param terminalNodes list of terminal nodes we want to add */ private void reverseLookUp(LinkedList<NextWord> terminalNodes, final WordCallback callback) { Node node; int freq; for (NextWord nextWord : terminalNodes) { node = nextWord.word; freq = nextWord.frequency; // TODO Not the best way to limit suggestion threshold if (freq >= UserBigramDictionary.SUGGEST_THRESHOLD) { sb.setLength(0); do { sb.insert(0, node.code); node = node.parent; } while(node != null); // TODO better way to feed char array? callback.addWord(sb.toString().toCharArray(), 0, sb.length(), freq, mDicTypeId, DataType.BIGRAM); } } } /** * Search for the terminal node of the word * @return Returns the terminal node of the word if the word exists */ private Node searchNode(final NodeArray children, final CharSequence word, final int offset, final int length) { // TODO Consider combining with addWordRec final int count = children.length; char currentChar = word.charAt(offset); for (int j = 0; j < count; j++) { final Node node = children.data[j]; if (node.code == currentChar) { if (offset == length - 1) { if (node.terminal) { return node; } } else { if (node.children != null) { Node returnNode = searchNode(node.children, word, offset + 1, length); if (returnNode != null) return returnNode; } } } } return null; } protected void clearDictionary() { mRoots = new NodeArray(); } private class LoadDictionaryTask extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... v) { loadDictionaryAsync(); synchronized (mUpdatingLock) { mUpdatingDictionary = false; } return null; } } static char toLowerCase(char c) { if (c < BASE_CHARS.length) { c = BASE_CHARS[c]; } if (c >= 'A' && c <= 'Z') { c = (char) (c | 32); } else if (c > 127) { c = Character.toLowerCase(c); } return c; } /** * Table mapping most combined Latin, Greek, and Cyrillic characters * to their base characters. If c is in range, BASE_CHARS[c] == c * if c is not a combined character, or the base character if it * is combined. */ static final char BASE_CHARS[] = { 0x0000, 0x0001, 0x0002, 0x0003, 0x0004, 0x0005, 0x0006, 0x0007, 0x0008, 0x0009, 0x000a, 0x000b, 0x000c, 0x000d, 0x000e, 0x000f, 0x0010, 0x0011, 0x0012, 0x0013, 0x0014, 0x0015, 0x0016, 0x0017, 0x0018, 0x0019, 0x001a, 0x001b, 0x001c, 0x001d, 0x001e, 0x001f, 0x0020, 0x0021, 0x0022, 0x0023, 0x0024, 0x0025, 0x0026, 0x0027, 0x0028, 0x0029, 0x002a, 0x002b, 0x002c, 0x002d, 0x002e, 0x002f, 0x0030, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, 0x0036, 0x0037, 0x0038, 0x0039, 0x003a, 0x003b, 0x003c, 0x003d, 0x003e, 0x003f, 0x0040, 0x0041, 0x0042, 0x0043, 0x0044, 0x0045, 0x0046, 0x0047, 0x0048, 0x0049, 0x004a, 0x004b, 0x004c, 0x004d, 0x004e, 0x004f, 0x0050, 0x0051, 0x0052, 0x0053, 0x0054, 0x0055, 0x0056, 0x0057, 0x0058, 0x0059, 0x005a, 0x005b, 0x005c, 0x005d, 0x005e, 0x005f, 0x0060, 0x0061, 0x0062, 0x0063, 0x0064, 0x0065, 0x0066, 0x0067, 0x0068, 0x0069, 0x006a, 0x006b, 0x006c, 0x006d, 0x006e, 0x006f, 0x0070, 0x0071, 0x0072, 0x0073, 0x0074, 0x0075, 0x0076, 0x0077, 0x0078, 0x0079, 0x007a, 0x007b, 0x007c, 0x007d, 0x007e, 0x007f, 0x0080, 0x0081, 0x0082, 0x0083, 0x0084, 0x0085, 0x0086, 0x0087, 0x0088, 0x0089, 0x008a, 0x008b, 0x008c, 0x008d, 0x008e, 0x008f, 0x0090, 0x0091, 0x0092, 0x0093, 0x0094, 0x0095, 0x0096, 0x0097, 0x0098, 0x0099, 0x009a, 0x009b, 0x009c, 0x009d, 0x009e, 0x009f, 0x0020, 0x00a1, 0x00a2, 0x00a3, 0x00a4, 0x00a5, 0x00a6, 0x00a7, 0x0020, 0x00a9, 0x0061, 0x00ab, 0x00ac, 0x00ad, 0x00ae, 0x0020, 0x00b0, 0x00b1, 0x0032, 0x0033, 0x0020, 0x03bc, 0x00b6, 0x00b7, 0x0020, 0x0031, 0x006f, 0x00bb, 0x0031, 0x0031, 0x0033, 0x00bf, 0x0041, 0x0041, 0x0041, 0x0041, 0x0041, 0x0041, 0x00c6, 0x0043, 0x0045, 0x0045, 0x0045, 0x0045, 0x0049, 0x0049, 0x0049, 0x0049, 0x00d0, 0x004e, 0x004f, 0x004f, 0x004f, 0x004f, 0x004f, 0x00d7, 0x004f, 0x0055, 0x0055, 0x0055, 0x0055, 0x0059, 0x00de, 0x0073, // Manually changed d8 to 4f // Manually changed df to 73 0x0061, 0x0061, 0x0061, 0x0061, 0x0061, 0x0061, 0x00e6, 0x0063, 0x0065, 0x0065, 0x0065, 0x0065, 0x0069, 0x0069, 0x0069, 0x0069, 0x00f0, 0x006e, 0x006f, 0x006f, 0x006f, 0x006f, 0x006f, 0x00f7, 0x006f, 0x0075, 0x0075, 0x0075, 0x0075, 0x0079, 0x00fe, 0x0079, // Manually changed f8 to 6f 0x0041, 0x0061, 0x0041, 0x0061, 0x0041, 0x0061, 0x0043, 0x0063, 0x0043, 0x0063, 0x0043, 0x0063, 0x0043, 0x0063, 0x0044, 0x0064, 0x0110, 0x0111, 0x0045, 0x0065, 0x0045, 0x0065, 0x0045, 0x0065, 0x0045, 0x0065, 0x0045, 0x0065, 0x0047, 0x0067, 0x0047, 0x0067, 0x0047, 0x0067, 0x0047, 0x0067, 0x0048, 0x0068, 0x0126, 0x0127, 0x0049, 0x0069, 0x0049, 0x0069, 0x0049, 0x0069, 0x0049, 0x0069, 0x0049, 0x0131, 0x0049, 0x0069, 0x004a, 0x006a, 0x004b, 0x006b, 0x0138, 0x004c, 0x006c, 0x004c, 0x006c, 0x004c, 0x006c, 0x004c, 0x006c, 0x0141, 0x0142, 0x004e, 0x006e, 0x004e, 0x006e, 0x004e, 0x006e, 0x02bc, 0x014a, 0x014b, 0x004f, 0x006f, 0x004f, 0x006f, 0x004f, 0x006f, 0x0152, 0x0153, 0x0052, 0x0072, 0x0052, 0x0072, 0x0052, 0x0072, 0x0053, 0x0073, 0x0053, 0x0073, 0x0053, 0x0073, 0x0053, 0x0073, 0x0054, 0x0074, 0x0054, 0x0074, 0x0166, 0x0167, 0x0055, 0x0075, 0x0055, 0x0075, 0x0055, 0x0075, 0x0055, 0x0075, 0x0055, 0x0075, 0x0055, 0x0075, 0x0057, 0x0077, 0x0059, 0x0079, 0x0059, 0x005a, 0x007a, 0x005a, 0x007a, 0x005a, 0x007a, 0x0073, 0x0180, 0x0181, 0x0182, 0x0183, 0x0184, 0x0185, 0x0186, 0x0187, 0x0188, 0x0189, 0x018a, 0x018b, 0x018c, 0x018d, 0x018e, 0x018f, 0x0190, 0x0191, 0x0192, 0x0193, 0x0194, 0x0195, 0x0196, 0x0197, 0x0198, 0x0199, 0x019a, 0x019b, 0x019c, 0x019d, 0x019e, 0x019f, 0x004f, 0x006f, 0x01a2, 0x01a3, 0x01a4, 0x01a5, 0x01a6, 0x01a7, 0x01a8, 0x01a9, 0x01aa, 0x01ab, 0x01ac, 0x01ad, 0x01ae, 0x0055, 0x0075, 0x01b1, 0x01b2, 0x01b3, 0x01b4, 0x01b5, 0x01b6, 0x01b7, 0x01b8, 0x01b9, 0x01ba, 0x01bb, 0x01bc, 0x01bd, 0x01be, 0x01bf, 0x01c0, 0x01c1, 0x01c2, 0x01c3, 0x0044, 0x0044, 0x0064, 0x004c, 0x004c, 0x006c, 0x004e, 0x004e, 0x006e, 0x0041, 0x0061, 0x0049, 0x0069, 0x004f, 0x006f, 0x0055, 0x0075, 0x00dc, 0x00fc, 0x00dc, 0x00fc, 0x00dc, 0x00fc, 0x00dc, 0x00fc, 0x01dd, 0x00c4, 0x00e4, 0x0226, 0x0227, 0x00c6, 0x00e6, 0x01e4, 0x01e5, 0x0047, 0x0067, 0x004b, 0x006b, 0x004f, 0x006f, 0x01ea, 0x01eb, 0x01b7, 0x0292, 0x006a, 0x0044, 0x0044, 0x0064, 0x0047, 0x0067, 0x01f6, 0x01f7, 0x004e, 0x006e, 0x00c5, 0x00e5, 0x00c6, 0x00e6, 0x00d8, 0x00f8, 0x0041, 0x0061, 0x0041, 0x0061, 0x0045, 0x0065, 0x0045, 0x0065, 0x0049, 0x0069, 0x0049, 0x0069, 0x004f, 0x006f, 0x004f, 0x006f, 0x0052, 0x0072, 0x0052, 0x0072, 0x0055, 0x0075, 0x0055, 0x0075, 0x0053, 0x0073, 0x0054, 0x0074, 0x021c, 0x021d, 0x0048, 0x0068, 0x0220, 0x0221, 0x0222, 0x0223, 0x0224, 0x0225, 0x0041, 0x0061, 0x0045, 0x0065, 0x00d6, 0x00f6, 0x00d5, 0x00f5, 0x004f, 0x006f, 0x022e, 0x022f, 0x0059, 0x0079, 0x0234, 0x0235, 0x0236, 0x0237, 0x0238, 0x0239, 0x023a, 0x023b, 0x023c, 0x023d, 0x023e, 0x023f, 0x0240, 0x0241, 0x0242, 0x0243, 0x0244, 0x0245, 0x0246, 0x0247, 0x0248, 0x0249, 0x024a, 0x024b, 0x024c, 0x024d, 0x024e, 0x024f, 0x0250, 0x0251, 0x0252, 0x0253, 0x0254, 0x0255, 0x0256, 0x0257, 0x0258, 0x0259, 0x025a, 0x025b, 0x025c, 0x025d, 0x025e, 0x025f, 0x0260, 0x0261, 0x0262, 0x0263, 0x0264, 0x0265, 0x0266, 0x0267, 0x0268, 0x0269, 0x026a, 0x026b, 0x026c, 0x026d, 0x026e, 0x026f, 0x0270, 0x0271, 0x0272, 0x0273, 0x0274, 0x0275, 0x0276, 0x0277, 0x0278, 0x0279, 0x027a, 0x027b, 0x027c, 0x027d, 0x027e, 0x027f, 0x0280, 0x0281, 0x0282, 0x0283, 0x0284, 0x0285, 0x0286, 0x0287, 0x0288, 0x0289, 0x028a, 0x028b, 0x028c, 0x028d, 0x028e, 0x028f, 0x0290, 0x0291, 0x0292, 0x0293, 0x0294, 0x0295, 0x0296, 0x0297, 0x0298, 0x0299, 0x029a, 0x029b, 0x029c, 0x029d, 0x029e, 0x029f, 0x02a0, 0x02a1, 0x02a2, 0x02a3, 0x02a4, 0x02a5, 0x02a6, 0x02a7, 0x02a8, 0x02a9, 0x02aa, 0x02ab, 0x02ac, 0x02ad, 0x02ae, 0x02af, 0x0068, 0x0266, 0x006a, 0x0072, 0x0279, 0x027b, 0x0281, 0x0077, 0x0079, 0x02b9, 0x02ba, 0x02bb, 0x02bc, 0x02bd, 0x02be, 0x02bf, 0x02c0, 0x02c1, 0x02c2, 0x02c3, 0x02c4, 0x02c5, 0x02c6, 0x02c7, 0x02c8, 0x02c9, 0x02ca, 0x02cb, 0x02cc, 0x02cd, 0x02ce, 0x02cf, 0x02d0, 0x02d1, 0x02d2, 0x02d3, 0x02d4, 0x02d5, 0x02d6, 0x02d7, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x02de, 0x02df, 0x0263, 0x006c, 0x0073, 0x0078, 0x0295, 0x02e5, 0x02e6, 0x02e7, 0x02e8, 0x02e9, 0x02ea, 0x02eb, 0x02ec, 0x02ed, 0x02ee, 0x02ef, 0x02f0, 0x02f1, 0x02f2, 0x02f3, 0x02f4, 0x02f5, 0x02f6, 0x02f7, 0x02f8, 0x02f9, 0x02fa, 0x02fb, 0x02fc, 0x02fd, 0x02fe, 0x02ff, 0x0300, 0x0301, 0x0302, 0x0303, 0x0304, 0x0305, 0x0306, 0x0307, 0x0308, 0x0309, 0x030a, 0x030b, 0x030c, 0x030d, 0x030e, 0x030f, 0x0310, 0x0311, 0x0312, 0x0313, 0x0314, 0x0315, 0x0316, 0x0317, 0x0318, 0x0319, 0x031a, 0x031b, 0x031c, 0x031d, 0x031e, 0x031f, 0x0320, 0x0321, 0x0322, 0x0323, 0x0324, 0x0325, 0x0326, 0x0327, 0x0328, 0x0329, 0x032a, 0x032b, 0x032c, 0x032d, 0x032e, 0x032f, 0x0330, 0x0331, 0x0332, 0x0333, 0x0334, 0x0335, 0x0336, 0x0337, 0x0338, 0x0339, 0x033a, 0x033b, 0x033c, 0x033d, 0x033e, 0x033f, 0x0300, 0x0301, 0x0342, 0x0313, 0x0308, 0x0345, 0x0346, 0x0347, 0x0348, 0x0349, 0x034a, 0x034b, 0x034c, 0x034d, 0x034e, 0x034f, 0x0350, 0x0351, 0x0352, 0x0353, 0x0354, 0x0355, 0x0356, 0x0357, 0x0358, 0x0359, 0x035a, 0x035b, 0x035c, 0x035d, 0x035e, 0x035f, 0x0360, 0x0361, 0x0362, 0x0363, 0x0364, 0x0365, 0x0366, 0x0367, 0x0368, 0x0369, 0x036a, 0x036b, 0x036c, 0x036d, 0x036e, 0x036f, 0x0370, 0x0371, 0x0372, 0x0373, 0x02b9, 0x0375, 0x0376, 0x0377, 0x0378, 0x0379, 0x0020, 0x037b, 0x037c, 0x037d, 0x003b, 0x037f, 0x0380, 0x0381, 0x0382, 0x0383, 0x0020, 0x00a8, 0x0391, 0x00b7, 0x0395, 0x0397, 0x0399, 0x038b, 0x039f, 0x038d, 0x03a5, 0x03a9, 0x03ca, 0x0391, 0x0392, 0x0393, 0x0394, 0x0395, 0x0396, 0x0397, 0x0398, 0x0399, 0x039a, 0x039b, 0x039c, 0x039d, 0x039e, 0x039f, 0x03a0, 0x03a1, 0x03a2, 0x03a3, 0x03a4, 0x03a5, 0x03a6, 0x03a7, 0x03a8, 0x03a9, 0x0399, 0x03a5, 0x03b1, 0x03b5, 0x03b7, 0x03b9, 0x03cb, 0x03b1, 0x03b2, 0x03b3, 0x03b4, 0x03b5, 0x03b6, 0x03b7, 0x03b8, 0x03b9, 0x03ba, 0x03bb, 0x03bc, 0x03bd, 0x03be, 0x03bf, 0x03c0, 0x03c1, 0x03c2, 0x03c3, 0x03c4, 0x03c5, 0x03c6, 0x03c7, 0x03c8, 0x03c9, 0x03b9, 0x03c5, 0x03bf, 0x03c5, 0x03c9, 0x03cf, 0x03b2, 0x03b8, 0x03a5, 0x03d2, 0x03d2, 0x03c6, 0x03c0, 0x03d7, 0x03d8, 0x03d9, 0x03da, 0x03db, 0x03dc, 0x03dd, 0x03de, 0x03df, 0x03e0, 0x03e1, 0x03e2, 0x03e3, 0x03e4, 0x03e5, 0x03e6, 0x03e7, 0x03e8, 0x03e9, 0x03ea, 0x03eb, 0x03ec, 0x03ed, 0x03ee, 0x03ef, 0x03ba, 0x03c1, 0x03c2, 0x03f3, 0x0398, 0x03b5, 0x03f6, 0x03f7, 0x03f8, 0x03a3, 0x03fa, 0x03fb, 0x03fc, 0x03fd, 0x03fe, 0x03ff, 0x0415, 0x0415, 0x0402, 0x0413, 0x0404, 0x0405, 0x0406, 0x0406, 0x0408, 0x0409, 0x040a, 0x040b, 0x041a, 0x0418, 0x0423, 0x040f, 0x0410, 0x0411, 0x0412, 0x0413, 0x0414, 0x0415, 0x0416, 0x0417, 0x0418, 0x0418, 0x041a, 0x041b, 0x041c, 0x041d, 0x041e, 0x041f, 0x0420, 0x0421, 0x0422, 0x0423, 0x0424, 0x0425, 0x0426, 0x0427, 0x0428, 0x0429, 0x042a, 0x042b, 0x042c, 0x042d, 0x042e, 0x042f, 0x0430, 0x0431, 0x0432, 0x0433, 0x0434, 0x0435, 0x0436, 0x0437, 0x0438, 0x0438, 0x043a, 0x043b, 0x043c, 0x043d, 0x043e, 0x043f, 0x0440, 0x0441, 0x0442, 0x0443, 0x0444, 0x0445, 0x0446, 0x0447, 0x0448, 0x0449, 0x044a, 0x044b, 0x044c, 0x044d, 0x044e, 0x044f, 0x0435, 0x0435, 0x0452, 0x0433, 0x0454, 0x0455, 0x0456, 0x0456, 0x0458, 0x0459, 0x045a, 0x045b, 0x043a, 0x0438, 0x0443, 0x045f, 0x0460, 0x0461, 0x0462, 0x0463, 0x0464, 0x0465, 0x0466, 0x0467, 0x0468, 0x0469, 0x046a, 0x046b, 0x046c, 0x046d, 0x046e, 0x046f, 0x0470, 0x0471, 0x0472, 0x0473, 0x0474, 0x0475, 0x0474, 0x0475, 0x0478, 0x0479, 0x047a, 0x047b, 0x047c, 0x047d, 0x047e, 0x047f, 0x0480, 0x0481, 0x0482, 0x0483, 0x0484, 0x0485, 0x0486, 0x0487, 0x0488, 0x0489, 0x048a, 0x048b, 0x048c, 0x048d, 0x048e, 0x048f, 0x0490, 0x0491, 0x0492, 0x0493, 0x0494, 0x0495, 0x0496, 0x0497, 0x0498, 0x0499, 0x049a, 0x049b, 0x049c, 0x049d, 0x049e, 0x049f, 0x04a0, 0x04a1, 0x04a2, 0x04a3, 0x04a4, 0x04a5, 0x04a6, 0x04a7, 0x04a8, 0x04a9, 0x04aa, 0x04ab, 0x04ac, 0x04ad, 0x04ae, 0x04af, 0x04b0, 0x04b1, 0x04b2, 0x04b3, 0x04b4, 0x04b5, 0x04b6, 0x04b7, 0x04b8, 0x04b9, 0x04ba, 0x04bb, 0x04bc, 0x04bd, 0x04be, 0x04bf, 0x04c0, 0x0416, 0x0436, 0x04c3, 0x04c4, 0x04c5, 0x04c6, 0x04c7, 0x04c8, 0x04c9, 0x04ca, 0x04cb, 0x04cc, 0x04cd, 0x04ce, 0x04cf, 0x0410, 0x0430, 0x0410, 0x0430, 0x04d4, 0x04d5, 0x0415, 0x0435, 0x04d8, 0x04d9, 0x04d8, 0x04d9, 0x0416, 0x0436, 0x0417, 0x0437, 0x04e0, 0x04e1, 0x0418, 0x0438, 0x0418, 0x0438, 0x041e, 0x043e, 0x04e8, 0x04e9, 0x04e8, 0x04e9, 0x042d, 0x044d, 0x0423, 0x0443, 0x0423, 0x0443, 0x0423, 0x0443, 0x0427, 0x0447, 0x04f6, 0x04f7, 0x042b, 0x044b, 0x04fa, 0x04fb, 0x04fc, 0x04fd, 0x04fe, 0x04ff, }; // generated with: // cat UnicodeData.txt | perl -e 'while (<>) { @foo = split(/;/); $foo[5] =~ s/<.*> //; $base[hex($foo[0])] = hex($foo[5]);} for ($i = 0; $i < 0x500; $i += 8) { for ($j = $i; $j < $i + 8; $j++) { printf("0x%04x, ", $base[$j] ? $base[$j] : $j)}; print "\n"; }' }
Java
package org.pocketworkstation.pckeyboard; import android.content.Context; import android.preference.EditTextPreference; import android.util.AttributeSet; public class AutoSummaryEditTextPreference extends EditTextPreference { public AutoSummaryEditTextPreference(Context context) { super(context); } public AutoSummaryEditTextPreference(Context context, AttributeSet attrs) { super(context, attrs); } public AutoSummaryEditTextPreference(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override public void setText(String text) { super.setText(text); setSummary(text); } }
Java
/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.pocketworkstation.pckeyboard; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Locale; import android.content.Context; import android.text.AutoText; import android.text.TextUtils; import android.util.Log; import android.view.View; /** * This class loads a dictionary and provides a list of suggestions for a given sequence of * characters. This includes corrections and completions. * @hide pending API Council Approval */ public class Suggest implements Dictionary.WordCallback { private static String TAG = "PCKeyboard"; public static final int APPROX_MAX_WORD_LENGTH = 32; public static final int CORRECTION_NONE = 0; public static final int CORRECTION_BASIC = 1; public static final int CORRECTION_FULL = 2; public static final int CORRECTION_FULL_BIGRAM = 3; /** * Words that appear in both bigram and unigram data gets multiplier ranging from * BIGRAM_MULTIPLIER_MIN to BIGRAM_MULTIPLIER_MAX depending on the frequency score from * bigram data. */ public static final double BIGRAM_MULTIPLIER_MIN = 1.2; public static final double BIGRAM_MULTIPLIER_MAX = 1.5; /** * Maximum possible bigram frequency. Will depend on how many bits are being used in data * structure. Maximum bigram freqeuncy will get the BIGRAM_MULTIPLIER_MAX as the multiplier. */ public static final int MAXIMUM_BIGRAM_FREQUENCY = 127; public static final int DIC_USER_TYPED = 0; public static final int DIC_MAIN = 1; public static final int DIC_USER = 2; public static final int DIC_AUTO = 3; public static final int DIC_CONTACTS = 4; // If you add a type of dictionary, increment DIC_TYPE_LAST_ID public static final int DIC_TYPE_LAST_ID = 4; static final int LARGE_DICTIONARY_THRESHOLD = 200 * 1000; private BinaryDictionary mMainDict; private Dictionary mUserDictionary; private Dictionary mAutoDictionary; private Dictionary mContactsDictionary; private Dictionary mUserBigramDictionary; private int mPrefMaxSuggestions = 12; private static final int PREF_MAX_BIGRAMS = 60; private boolean mAutoTextEnabled; private int[] mPriorities = new int[mPrefMaxSuggestions]; private int[] mBigramPriorities = new int[PREF_MAX_BIGRAMS]; // Handle predictive correction for only the first 1280 characters for performance reasons // If we support scripts that need latin characters beyond that, we should probably use some // kind of a sparse array or language specific list with a mapping lookup table. // 1280 is the size of the BASE_CHARS array in ExpandableDictionary, which is a basic set of // latin characters. private int[] mNextLettersFrequencies = new int[1280]; private ArrayList<CharSequence> mSuggestions = new ArrayList<CharSequence>(); ArrayList<CharSequence> mBigramSuggestions = new ArrayList<CharSequence>(); private ArrayList<CharSequence> mStringPool = new ArrayList<CharSequence>(); private boolean mHaveCorrection; private CharSequence mOriginalWord; private String mLowerOriginalWord; // TODO: Remove these member variables by passing more context to addWord() callback method private boolean mIsFirstCharCapitalized; private boolean mIsAllUpperCase; private int mCorrectionMode = CORRECTION_BASIC; public Suggest(Context context, int[] dictionaryResId) { mMainDict = new BinaryDictionary(context, dictionaryResId, DIC_MAIN); if (!hasMainDictionary()) { Locale locale = context.getResources().getConfiguration().locale; BinaryDictionary plug = PluginManager.getDictionary(context, locale.getLanguage()); if (plug != null) { mMainDict.close(); mMainDict = plug; } } initPool(); } public Suggest(Context context, ByteBuffer byteBuffer) { mMainDict = new BinaryDictionary(context, byteBuffer, DIC_MAIN); initPool(); } private void initPool() { for (int i = 0; i < mPrefMaxSuggestions; i++) { StringBuilder sb = new StringBuilder(getApproxMaxWordLength()); mStringPool.add(sb); } } public void setAutoTextEnabled(boolean enabled) { mAutoTextEnabled = enabled; } public int getCorrectionMode() { return mCorrectionMode; } public void setCorrectionMode(int mode) { mCorrectionMode = mode; } public boolean hasMainDictionary() { return mMainDict.getSize() > LARGE_DICTIONARY_THRESHOLD; } public int getApproxMaxWordLength() { return APPROX_MAX_WORD_LENGTH; } /** * Sets an optional user dictionary resource to be loaded. The user dictionary is consulted * before the main dictionary, if set. */ public void setUserDictionary(Dictionary userDictionary) { mUserDictionary = userDictionary; } /** * Sets an optional contacts dictionary resource to be loaded. */ public void setContactsDictionary(Dictionary userDictionary) { mContactsDictionary = userDictionary; } public void setAutoDictionary(Dictionary autoDictionary) { mAutoDictionary = autoDictionary; } public void setUserBigramDictionary(Dictionary userBigramDictionary) { mUserBigramDictionary = userBigramDictionary; } /** * Number of suggestions to generate from the input key sequence. This has * to be a number between 1 and 100 (inclusive). * @param maxSuggestions * @throws IllegalArgumentException if the number is out of range */ public void setMaxSuggestions(int maxSuggestions) { if (maxSuggestions < 1 || maxSuggestions > 100) { throw new IllegalArgumentException("maxSuggestions must be between 1 and 100"); } mPrefMaxSuggestions = maxSuggestions; mPriorities = new int[mPrefMaxSuggestions]; mBigramPriorities = new int[PREF_MAX_BIGRAMS]; collectGarbage(mSuggestions, mPrefMaxSuggestions); while (mStringPool.size() < mPrefMaxSuggestions) { StringBuilder sb = new StringBuilder(getApproxMaxWordLength()); mStringPool.add(sb); } } private boolean haveSufficientCommonality(String original, CharSequence suggestion) { final int originalLength = original.length(); final int suggestionLength = suggestion.length(); final int minLength = Math.min(originalLength, suggestionLength); if (minLength <= 2) return true; int matching = 0; int lessMatching = 0; // Count matches if we skip one character int i; for (i = 0; i < minLength; i++) { final char origChar = ExpandableDictionary.toLowerCase(original.charAt(i)); if (origChar == ExpandableDictionary.toLowerCase(suggestion.charAt(i))) { matching++; lessMatching++; } else if (i + 1 < suggestionLength && origChar == ExpandableDictionary.toLowerCase(suggestion.charAt(i + 1))) { lessMatching++; } } matching = Math.max(matching, lessMatching); if (minLength <= 4) { return matching >= 2; } else { return matching > minLength / 2; } } /** * Returns a list of words that match the list of character codes passed in. * This list will be overwritten the next time this function is called. * @param view a view for retrieving the context for AutoText * @param wordComposer contains what is currently being typed * @param prevWordForBigram previous word (used only for bigram) * @return list of suggestions. */ public List<CharSequence> getSuggestions(View view, WordComposer wordComposer, boolean includeTypedWordIfValid, CharSequence prevWordForBigram) { LatinImeLogger.onStartSuggestion(prevWordForBigram); mHaveCorrection = false; mIsFirstCharCapitalized = wordComposer.isFirstCharCapitalized(); mIsAllUpperCase = wordComposer.isAllUpperCase(); collectGarbage(mSuggestions, mPrefMaxSuggestions); Arrays.fill(mPriorities, 0); Arrays.fill(mNextLettersFrequencies, 0); // Save a lowercase version of the original word mOriginalWord = wordComposer.getTypedWord(); if (mOriginalWord != null) { final String mOriginalWordString = mOriginalWord.toString(); mOriginalWord = mOriginalWordString; mLowerOriginalWord = mOriginalWordString.toLowerCase(); // Treating USER_TYPED as UNIGRAM suggestion for logging now. LatinImeLogger.onAddSuggestedWord(mOriginalWordString, Suggest.DIC_USER_TYPED, Dictionary.DataType.UNIGRAM); } else { mLowerOriginalWord = ""; } if (wordComposer.size() == 1 && (mCorrectionMode == CORRECTION_FULL_BIGRAM || mCorrectionMode == CORRECTION_BASIC)) { // At first character typed, search only the bigrams Arrays.fill(mBigramPriorities, 0); collectGarbage(mBigramSuggestions, PREF_MAX_BIGRAMS); if (!TextUtils.isEmpty(prevWordForBigram)) { CharSequence lowerPrevWord = prevWordForBigram.toString().toLowerCase(); if (mMainDict.isValidWord(lowerPrevWord)) { prevWordForBigram = lowerPrevWord; } if (mUserBigramDictionary != null) { mUserBigramDictionary.getBigrams(wordComposer, prevWordForBigram, this, mNextLettersFrequencies); } if (mContactsDictionary != null) { mContactsDictionary.getBigrams(wordComposer, prevWordForBigram, this, mNextLettersFrequencies); } if (mMainDict != null) { mMainDict.getBigrams(wordComposer, prevWordForBigram, this, mNextLettersFrequencies); } char currentChar = wordComposer.getTypedWord().charAt(0); char currentCharUpper = Character.toUpperCase(currentChar); int count = 0; int bigramSuggestionSize = mBigramSuggestions.size(); for (int i = 0; i < bigramSuggestionSize; i++) { if (mBigramSuggestions.get(i).charAt(0) == currentChar || mBigramSuggestions.get(i).charAt(0) == currentCharUpper) { int poolSize = mStringPool.size(); StringBuilder sb = poolSize > 0 ? (StringBuilder) mStringPool.remove(poolSize - 1) : new StringBuilder(getApproxMaxWordLength()); sb.setLength(0); sb.append(mBigramSuggestions.get(i)); mSuggestions.add(count++, sb); if (count > mPrefMaxSuggestions) break; } } } } else if (wordComposer.size() > 1) { // At second character typed, search the unigrams (scores being affected by bigrams) if (mUserDictionary != null || mContactsDictionary != null) { if (mUserDictionary != null) { mUserDictionary.getWords(wordComposer, this, mNextLettersFrequencies); } if (mContactsDictionary != null) { mContactsDictionary.getWords(wordComposer, this, mNextLettersFrequencies); } if (mSuggestions.size() > 0 && isValidWord(mOriginalWord) && (mCorrectionMode == CORRECTION_FULL || mCorrectionMode == CORRECTION_FULL_BIGRAM)) { mHaveCorrection = true; } } mMainDict.getWords(wordComposer, this, mNextLettersFrequencies); if ((mCorrectionMode == CORRECTION_FULL || mCorrectionMode == CORRECTION_FULL_BIGRAM) && mSuggestions.size() > 0) { mHaveCorrection = true; } } if (mOriginalWord != null) { mSuggestions.add(0, mOriginalWord.toString()); } // Check if the first suggestion has a minimum number of characters in common if (wordComposer.size() > 1 && mSuggestions.size() > 1 && (mCorrectionMode == CORRECTION_FULL || mCorrectionMode == CORRECTION_FULL_BIGRAM)) { if (!haveSufficientCommonality(mLowerOriginalWord, mSuggestions.get(1))) { mHaveCorrection = false; } } if (mAutoTextEnabled) { int i = 0; int max = 6; // Don't autotext the suggestions from the dictionaries if (mCorrectionMode == CORRECTION_BASIC) max = 1; while (i < mSuggestions.size() && i < max) { String suggestedWord = mSuggestions.get(i).toString().toLowerCase(); CharSequence autoText = AutoText.get(suggestedWord, 0, suggestedWord.length(), view); // Is there an AutoText correction? boolean canAdd = autoText != null; // Is that correction already the current prediction (or original word)? canAdd &= !TextUtils.equals(autoText, mSuggestions.get(i)); // Is that correction already the next predicted word? if (canAdd && i + 1 < mSuggestions.size() && mCorrectionMode != CORRECTION_BASIC) { canAdd &= !TextUtils.equals(autoText, mSuggestions.get(i + 1)); } if (canAdd) { mHaveCorrection = true; mSuggestions.add(i + 1, autoText); i++; } i++; } } removeDupes(); return mSuggestions; } public int[] getNextLettersFrequencies() { return mNextLettersFrequencies; } private void removeDupes() { final ArrayList<CharSequence> suggestions = mSuggestions; if (suggestions.size() < 2) return; int i = 1; // Don't cache suggestions.size(), since we may be removing items while (i < suggestions.size()) { final CharSequence cur = suggestions.get(i); // Compare each candidate with each previous candidate for (int j = 0; j < i; j++) { CharSequence previous = suggestions.get(j); if (TextUtils.equals(cur, previous)) { removeFromSuggestions(i); i--; break; } } i++; } } private void removeFromSuggestions(int index) { CharSequence garbage = mSuggestions.remove(index); if (garbage != null && garbage instanceof StringBuilder) { mStringPool.add(garbage); } } public boolean hasMinimalCorrection() { return mHaveCorrection; } private boolean compareCaseInsensitive(final String mLowerOriginalWord, final char[] word, final int offset, final int length) { final int originalLength = mLowerOriginalWord.length(); if (originalLength == length && Character.isUpperCase(word[offset])) { for (int i = 0; i < originalLength; i++) { if (mLowerOriginalWord.charAt(i) != Character.toLowerCase(word[offset+i])) { return false; } } return true; } return false; } public boolean addWord(final char[] word, final int offset, final int length, int freq, final int dicTypeId, final Dictionary.DataType dataType) { Dictionary.DataType dataTypeForLog = dataType; ArrayList<CharSequence> suggestions; int[] priorities; int prefMaxSuggestions; if(dataType == Dictionary.DataType.BIGRAM) { suggestions = mBigramSuggestions; priorities = mBigramPriorities; prefMaxSuggestions = PREF_MAX_BIGRAMS; } else { suggestions = mSuggestions; priorities = mPriorities; prefMaxSuggestions = mPrefMaxSuggestions; } int pos = 0; // Check if it's the same word, only caps are different if (compareCaseInsensitive(mLowerOriginalWord, word, offset, length)) { pos = 0; } else { if (dataType == Dictionary.DataType.UNIGRAM) { // Check if the word was already added before (by bigram data) int bigramSuggestion = searchBigramSuggestion(word,offset,length); if(bigramSuggestion >= 0) { dataTypeForLog = Dictionary.DataType.BIGRAM; // turn freq from bigram into multiplier specified above double multiplier = (((double) mBigramPriorities[bigramSuggestion]) / MAXIMUM_BIGRAM_FREQUENCY) * (BIGRAM_MULTIPLIER_MAX - BIGRAM_MULTIPLIER_MIN) + BIGRAM_MULTIPLIER_MIN; /* Log.d(TAG,"bigram num: " + bigramSuggestion + " wordB: " + mBigramSuggestions.get(bigramSuggestion).toString() + " currentPriority: " + freq + " bigramPriority: " + mBigramPriorities[bigramSuggestion] + " multiplier: " + multiplier); */ freq = (int)Math.round((freq * multiplier)); } } // Check the last one's priority and bail if (priorities[prefMaxSuggestions - 1] >= freq) return true; while (pos < prefMaxSuggestions) { if (priorities[pos] < freq || (priorities[pos] == freq && length < suggestions.get(pos).length())) { break; } pos++; } } if (pos >= prefMaxSuggestions) { return true; } System.arraycopy(priorities, pos, priorities, pos + 1, prefMaxSuggestions - pos - 1); priorities[pos] = freq; int poolSize = mStringPool.size(); StringBuilder sb = poolSize > 0 ? (StringBuilder) mStringPool.remove(poolSize - 1) : new StringBuilder(getApproxMaxWordLength()); sb.setLength(0); if (mIsAllUpperCase) { sb.append(new String(word, offset, length).toUpperCase()); } else if (mIsFirstCharCapitalized) { sb.append(Character.toUpperCase(word[offset])); if (length > 1) { sb.append(word, offset + 1, length - 1); } } else { sb.append(word, offset, length); } suggestions.add(pos, sb); if (suggestions.size() > prefMaxSuggestions) { CharSequence garbage = suggestions.remove(prefMaxSuggestions); if (garbage instanceof StringBuilder) { mStringPool.add(garbage); } } else { LatinImeLogger.onAddSuggestedWord(sb.toString(), dicTypeId, dataTypeForLog); } return true; } private int searchBigramSuggestion(final char[] word, final int offset, final int length) { // TODO This is almost O(n^2). Might need fix. // search whether the word appeared in bigram data int bigramSuggestSize = mBigramSuggestions.size(); for(int i = 0; i < bigramSuggestSize; i++) { if(mBigramSuggestions.get(i).length() == length) { boolean chk = true; for(int j = 0; j < length; j++) { if(mBigramSuggestions.get(i).charAt(j) != word[offset+j]) { chk = false; break; } } if(chk) return i; } } return -1; } public boolean isValidWord(final CharSequence word) { if (word == null || word.length() == 0) { return false; } return mMainDict.isValidWord(word) || (mUserDictionary != null && mUserDictionary.isValidWord(word)) || (mAutoDictionary != null && mAutoDictionary.isValidWord(word)) || (mContactsDictionary != null && mContactsDictionary.isValidWord(word)); } private void collectGarbage(ArrayList<CharSequence> suggestions, int prefMaxSuggestions) { int poolSize = mStringPool.size(); int garbageSize = suggestions.size(); while (poolSize < prefMaxSuggestions && garbageSize > 0) { CharSequence garbage = suggestions.get(garbageSize - 1); if (garbage != null && garbage instanceof StringBuilder) { mStringPool.add(garbage); poolSize++; } garbageSize--; } if (poolSize == prefMaxSuggestions + 1) { Log.w("Suggest", "String pool got too big: " + poolSize); } suggestions.clear(); } public void close() { if (mMainDict != null) { mMainDict.close(); } } }
Java
/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.pocketworkstation.pckeyboard; import android.content.Context; import android.content.res.Resources; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Paint.Align; import android.graphics.Rect; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.view.GestureDetector; import android.view.Gravity; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.widget.PopupWindow; import android.widget.TextView; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class CandidateView extends View { private static final int OUT_OF_BOUNDS_WORD_INDEX = -1; private static final int OUT_OF_BOUNDS_X_COORD = -1; private LatinIME mService; private final ArrayList<CharSequence> mSuggestions = new ArrayList<CharSequence>(); private boolean mShowingCompletions; private CharSequence mSelectedString; private int mSelectedIndex; private int mTouchX = OUT_OF_BOUNDS_X_COORD; private final Drawable mSelectionHighlight; private boolean mTypedWordValid; private boolean mHaveMinimalSuggestion; private Rect mBgPadding; private final TextView mPreviewText; private final PopupWindow mPreviewPopup; private int mCurrentWordIndex; private Drawable mDivider; private static final int MAX_SUGGESTIONS = 32; private static final int SCROLL_PIXELS = 20; private final int[] mWordWidth = new int[MAX_SUGGESTIONS]; private final int[] mWordX = new int[MAX_SUGGESTIONS]; private int mPopupPreviewX; private int mPopupPreviewY; private static final int X_GAP = 10; private final int mColorNormal; private final int mColorRecommended; private final int mColorOther; private final Paint mPaint; private final int mDescent; private boolean mScrolled; private boolean mShowingAddToDictionary; private CharSequence mAddToDictionaryHint; private int mTargetScrollX; private final int mMinTouchableWidth; private int mTotalWidth; private final GestureDetector mGestureDetector; /** * Construct a CandidateView for showing suggested words for completion. * @param context * @param attrs */ public CandidateView(Context context, AttributeSet attrs) { super(context, attrs); mSelectionHighlight = context.getResources().getDrawable( R.drawable.list_selector_background_pressed); LayoutInflater inflate = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); Resources res = context.getResources(); mPreviewPopup = new PopupWindow(context); mPreviewText = (TextView) inflate.inflate(R.layout.candidate_preview, null); mPreviewPopup.setWindowLayoutMode(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); mPreviewPopup.setContentView(mPreviewText); mPreviewPopup.setBackgroundDrawable(null); mPreviewPopup.setAnimationStyle(R.style.KeyPreviewAnimation); mColorNormal = res.getColor(R.color.candidate_normal); mColorRecommended = res.getColor(R.color.candidate_recommended); mColorOther = res.getColor(R.color.candidate_other); mDivider = res.getDrawable(R.drawable.keyboard_suggest_strip_divider); mAddToDictionaryHint = res.getString(R.string.hint_add_to_dictionary); mPaint = new Paint(); mPaint.setColor(mColorNormal); mPaint.setAntiAlias(true); mPaint.setTextSize(mPreviewText.getTextSize() * LatinIME.sKeyboardSettings.candidateScalePref); mPaint.setStrokeWidth(0); mPaint.setTextAlign(Align.CENTER); mDescent = (int) mPaint.descent(); mMinTouchableWidth = (int)res.getDimension(R.dimen.candidate_min_touchable_width); mGestureDetector = new GestureDetector( new CandidateStripGestureListener(mMinTouchableWidth)); setWillNotDraw(false); setHorizontalScrollBarEnabled(false); setVerticalScrollBarEnabled(false); scrollTo(0, getScrollY()); } private class CandidateStripGestureListener extends GestureDetector.SimpleOnGestureListener { private final int mTouchSlopSquare; public CandidateStripGestureListener(int touchSlop) { // Slightly reluctant to scroll to be able to easily choose the suggestion mTouchSlopSquare = touchSlop * touchSlop; } @Override public void onLongPress(MotionEvent me) { if (mSuggestions.size() > 0) { if (me.getX() + getScrollX() < mWordWidth[0] && getScrollX() < 10) { longPressFirstWord(); } } } @Override public boolean onDown(MotionEvent e) { mScrolled = false; return false; } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { if (!mScrolled) { // This is applied only when we recognize that scrolling is starting. final int deltaX = (int) (e2.getX() - e1.getX()); final int deltaY = (int) (e2.getY() - e1.getY()); final int distance = (deltaX * deltaX) + (deltaY * deltaY); if (distance < mTouchSlopSquare) { return true; } mScrolled = true; } final int width = getWidth(); mScrolled = true; int scrollX = getScrollX(); scrollX += (int) distanceX; if (scrollX < 0) { scrollX = 0; } if (distanceX > 0 && scrollX + width > mTotalWidth) { scrollX -= (int) distanceX; } mTargetScrollX = scrollX; scrollTo(scrollX, getScrollY()); hidePreview(); invalidate(); return true; } } /** * A connection back to the service to communicate with the text field * @param listener */ public void setService(LatinIME listener) { mService = listener; } @Override public int computeHorizontalScrollRange() { return mTotalWidth; } /** * If the canvas is null, then only touch calculations are performed to pick the target * candidate. */ @Override protected void onDraw(Canvas canvas) { if (canvas != null) { super.onDraw(canvas); } mTotalWidth = 0; final int height = getHeight(); if (mBgPadding == null) { mBgPadding = new Rect(0, 0, 0, 0); if (getBackground() != null) { getBackground().getPadding(mBgPadding); } mDivider.setBounds(0, 0, mDivider.getIntrinsicWidth(), mDivider.getIntrinsicHeight()); } final int count = mSuggestions.size(); final Rect bgPadding = mBgPadding; final Paint paint = mPaint; final int touchX = mTouchX; final int scrollX = getScrollX(); final boolean scrolled = mScrolled; final boolean typedWordValid = mTypedWordValid; final int y = (int) (height + mPaint.getTextSize() - mDescent) / 2; boolean existsAutoCompletion = false; int x = 0; for (int i = 0; i < count; i++) { CharSequence suggestion = mSuggestions.get(i); if (suggestion == null) continue; final int wordLength = suggestion.length(); paint.setColor(mColorNormal); if (mHaveMinimalSuggestion && ((i == 1 && !typedWordValid) || (i == 0 && typedWordValid))) { paint.setTypeface(Typeface.DEFAULT_BOLD); paint.setColor(mColorRecommended); existsAutoCompletion = true; } else if (i != 0 || (wordLength == 1 && count > 1)) { // HACK: even if i == 0, we use mColorOther when this suggestion's length is 1 and // there are multiple suggestions, such as the default punctuation list. paint.setColor(mColorOther); } int wordWidth; if ((wordWidth = mWordWidth[i]) == 0) { float textWidth = paint.measureText(suggestion, 0, wordLength); wordWidth = Math.max(mMinTouchableWidth, (int) textWidth + X_GAP * 2); mWordWidth[i] = wordWidth; } mWordX[i] = x; if (touchX != OUT_OF_BOUNDS_X_COORD && !scrolled && touchX + scrollX >= x && touchX + scrollX < x + wordWidth) { if (canvas != null && !mShowingAddToDictionary) { canvas.translate(x, 0); mSelectionHighlight.setBounds(0, bgPadding.top, wordWidth, height); mSelectionHighlight.draw(canvas); canvas.translate(-x, 0); } mSelectedString = suggestion; mSelectedIndex = i; } if (canvas != null) { canvas.drawText(suggestion, 0, wordLength, x + wordWidth / 2, y, paint); paint.setColor(mColorOther); canvas.translate(x + wordWidth, 0); // Draw a divider unless it's after the hint if (!(mShowingAddToDictionary && i == 1)) { mDivider.draw(canvas); } canvas.translate(-x - wordWidth, 0); } paint.setTypeface(Typeface.DEFAULT); x += wordWidth; } mService.onAutoCompletionStateChanged(existsAutoCompletion); mTotalWidth = x; if (mTargetScrollX != scrollX) { scrollToTarget(); } } private void scrollToTarget() { int scrollX = getScrollX(); if (mTargetScrollX > scrollX) { scrollX += SCROLL_PIXELS; if (scrollX >= mTargetScrollX) { scrollX = mTargetScrollX; scrollTo(scrollX, getScrollY()); requestLayout(); } else { scrollTo(scrollX, getScrollY()); } } else { scrollX -= SCROLL_PIXELS; if (scrollX <= mTargetScrollX) { scrollX = mTargetScrollX; scrollTo(scrollX, getScrollY()); requestLayout(); } else { scrollTo(scrollX, getScrollY()); } } invalidate(); } public void setSuggestions(List<CharSequence> suggestions, boolean completions, boolean typedWordValid, boolean haveMinimalSuggestion) { clear(); if (suggestions != null) { int insertCount = Math.min(suggestions.size(), MAX_SUGGESTIONS); for (CharSequence suggestion : suggestions) { mSuggestions.add(suggestion); if (--insertCount == 0) break; } } mShowingCompletions = completions; mTypedWordValid = typedWordValid; scrollTo(0, getScrollY()); mTargetScrollX = 0; mHaveMinimalSuggestion = haveMinimalSuggestion; // Compute the total width onDraw(null); invalidate(); requestLayout(); } public boolean isShowingAddToDictionaryHint() { return mShowingAddToDictionary; } public void showAddToDictionaryHint(CharSequence word) { ArrayList<CharSequence> suggestions = new ArrayList<CharSequence>(); suggestions.add(word); suggestions.add(mAddToDictionaryHint); setSuggestions(suggestions, false, false, false); mShowingAddToDictionary = true; } public boolean dismissAddToDictionaryHint() { if (!mShowingAddToDictionary) return false; clear(); return true; } /* package */ List<CharSequence> getSuggestions() { return mSuggestions; } public void clear() { // Don't call mSuggestions.clear() because it's being used for logging // in LatinIME.pickSuggestionManually(). mSuggestions.clear(); mTouchX = OUT_OF_BOUNDS_X_COORD; mSelectedString = null; mSelectedIndex = -1; mShowingAddToDictionary = false; invalidate(); Arrays.fill(mWordWidth, 0); Arrays.fill(mWordX, 0); } @Override public boolean onTouchEvent(MotionEvent me) { if (mGestureDetector.onTouchEvent(me)) { return true; } int action = me.getAction(); int x = (int) me.getX(); int y = (int) me.getY(); mTouchX = x; switch (action) { case MotionEvent.ACTION_DOWN: invalidate(); break; case MotionEvent.ACTION_MOVE: if (y <= 0) { // Fling up!? if (mSelectedString != null) { // If there are completions from the application, we don't change the state to // STATE_PICKED_SUGGESTION if (!mShowingCompletions) { // This "acceptedSuggestion" will not be counted as a word because // it will be counted in pickSuggestion instead. //TextEntryState.acceptedSuggestion(mSuggestions.get(0), mSelectedString); //TextEntryState.manualTyped(mSelectedString); } mService.pickSuggestionManually(mSelectedIndex, mSelectedString); mSelectedString = null; mSelectedIndex = -1; } } break; case MotionEvent.ACTION_UP: if (!mScrolled) { if (mSelectedString != null) { if (mShowingAddToDictionary) { longPressFirstWord(); clear(); } else { if (!mShowingCompletions) { //TextEntryState.acceptedSuggestion(mSuggestions.get(0), mSelectedString); //TextEntryState.manualTyped(mSelectedString); } mService.pickSuggestionManually(mSelectedIndex, mSelectedString); } } } mSelectedString = null; mSelectedIndex = -1; requestLayout(); hidePreview(); invalidate(); break; } return true; } private void hidePreview() { mTouchX = OUT_OF_BOUNDS_X_COORD; mCurrentWordIndex = OUT_OF_BOUNDS_WORD_INDEX; mPreviewPopup.dismiss(); } private void showPreview(int wordIndex, String altText) { int oldWordIndex = mCurrentWordIndex; mCurrentWordIndex = wordIndex; // If index changed or changing text if (oldWordIndex != mCurrentWordIndex || altText != null) { if (wordIndex == OUT_OF_BOUNDS_WORD_INDEX) { hidePreview(); } else { CharSequence word = altText != null? altText : mSuggestions.get(wordIndex); mPreviewText.setText(word); mPreviewText.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)); int wordWidth = (int) (mPaint.measureText(word, 0, word.length()) + X_GAP * 2); final int popupWidth = wordWidth + mPreviewText.getPaddingLeft() + mPreviewText.getPaddingRight(); final int popupHeight = mPreviewText.getMeasuredHeight(); //mPreviewText.setVisibility(INVISIBLE); mPopupPreviewX = mWordX[wordIndex] - mPreviewText.getPaddingLeft() - getScrollX() + (mWordWidth[wordIndex] - wordWidth) / 2; mPopupPreviewY = - popupHeight; int [] offsetInWindow = new int[2]; getLocationInWindow(offsetInWindow); if (mPreviewPopup.isShowing()) { mPreviewPopup.update(mPopupPreviewX, mPopupPreviewY + offsetInWindow[1], popupWidth, popupHeight); } else { mPreviewPopup.setWidth(popupWidth); mPreviewPopup.setHeight(popupHeight); mPreviewPopup.showAtLocation(this, Gravity.NO_GRAVITY, mPopupPreviewX, mPopupPreviewY + offsetInWindow[1]); } mPreviewText.setVisibility(VISIBLE); } } } private void longPressFirstWord() { CharSequence word = mSuggestions.get(0); if (word.length() < 2) return; if (mService.addWordToDictionary(word.toString())) { showPreview(0, getContext().getResources().getString(R.string.added_word, word)); } } @Override public void onDetachedFromWindow() { super.onDetachedFromWindow(); hidePreview(); } }
Java
/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.pocketworkstation.pckeyboard; import java.util.List; import android.content.Context; import android.content.res.Resources; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Paint; import org.pocketworkstation.pckeyboard.Keyboard.Key; import android.os.Handler; import android.os.Message; import android.os.SystemClock; import android.text.TextUtils; import android.util.AttributeSet; import android.util.Log; import android.view.LayoutInflater; import android.view.MotionEvent; import android.widget.PopupWindow; import android.widget.TextView; public class LatinKeyboardView extends LatinKeyboardBaseView { static final String TAG = "HK/LatinKeyboardView"; // The keycode list needs to stay in sync with the // res/values/keycodes.xml file. // FIXME: The following keycodes should really be renumbered // since they conflict with existing KeyEvent keycodes. static final int KEYCODE_OPTIONS = -100; static final int KEYCODE_OPTIONS_LONGPRESS = -101; static final int KEYCODE_VOICE = -102; static final int KEYCODE_F1 = -103; static final int KEYCODE_NEXT_LANGUAGE = -104; static final int KEYCODE_PREV_LANGUAGE = -105; static final int KEYCODE_COMPOSE = -10024; // The following keycodes match (negative) KeyEvent keycodes. // Would be better to use the real KeyEvent values, but many // don't exist prior to the Honeycomb API (level 11). static final int KEYCODE_DPAD_UP = -19; static final int KEYCODE_DPAD_DOWN = -20; static final int KEYCODE_DPAD_LEFT = -21; static final int KEYCODE_DPAD_RIGHT = -22; static final int KEYCODE_DPAD_CENTER = -23; static final int KEYCODE_ALT_LEFT = -57; static final int KEYCODE_PAGE_UP = -92; static final int KEYCODE_PAGE_DOWN = -93; static final int KEYCODE_ESCAPE = -111; static final int KEYCODE_FORWARD_DEL = -112; static final int KEYCODE_CTRL_LEFT = -113; static final int KEYCODE_CAPS_LOCK = -115; static final int KEYCODE_SCROLL_LOCK = -116; static final int KEYCODE_FN = -119; static final int KEYCODE_SYSRQ = -120; static final int KEYCODE_BREAK = -121; static final int KEYCODE_HOME = -122; static final int KEYCODE_END = -123; static final int KEYCODE_INSERT = -124; static final int KEYCODE_FKEY_F1 = -131; static final int KEYCODE_FKEY_F2 = -132; static final int KEYCODE_FKEY_F3 = -133; static final int KEYCODE_FKEY_F4 = -134; static final int KEYCODE_FKEY_F5 = -135; static final int KEYCODE_FKEY_F6 = -136; static final int KEYCODE_FKEY_F7 = -137; static final int KEYCODE_FKEY_F8 = -138; static final int KEYCODE_FKEY_F9 = -139; static final int KEYCODE_FKEY_F10 = -140; static final int KEYCODE_FKEY_F11 = -141; static final int KEYCODE_FKEY_F12 = -142; static final int KEYCODE_NUM_LOCK = -143; private Keyboard mPhoneKeyboard; /** Whether the extension of this keyboard is visible */ private boolean mExtensionVisible; /** The view that is shown as an extension of this keyboard view */ private LatinKeyboardView mExtension; /** The popup window that contains the extension of this keyboard */ private PopupWindow mExtensionPopup; /** Whether this view is an extension of another keyboard */ private boolean mIsExtensionType; private boolean mFirstEvent; /** Whether we've started dropping move events because we found a big jump */ private boolean mDroppingEvents; /** * Whether multi-touch disambiguation needs to be disabled for any reason. There are 2 reasons * for this to happen - (1) if a real multi-touch event has occured and (2) we've opened an * extension keyboard. */ private boolean mDisableDisambiguation; /** The distance threshold at which we start treating the touch session as a multi-touch */ private int mJumpThresholdSquare = Integer.MAX_VALUE; /** The y coordinate of the last row */ private int mLastRowY; private int mExtensionLayoutResId = 0; private LatinKeyboard mExtensionKeyboard; public LatinKeyboardView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public LatinKeyboardView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); // TODO(klausw): migrate attribute styles to LatinKeyboardView? TypedArray a = context.obtainStyledAttributes( attrs, R.styleable.LatinKeyboardBaseView, defStyle, R.style.LatinKeyboardBaseView); LayoutInflater inflate = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); int previewLayout = 0; int n = a.getIndexCount(); for (int i = 0; i < n; i++) { int attr = a.getIndex(i); switch (attr) { case R.styleable.LatinKeyboardBaseView_keyPreviewLayout: previewLayout = a.getResourceId(attr, 0); if (previewLayout == R.layout.null_layout) previewLayout = 0; break; case R.styleable.LatinKeyboardBaseView_keyPreviewOffset: mPreviewOffset = a.getDimensionPixelOffset(attr, 0); break; case R.styleable.LatinKeyboardBaseView_keyPreviewHeight: mPreviewHeight = a.getDimensionPixelSize(attr, 80); break; case R.styleable.LatinKeyboardBaseView_popupLayout: mPopupLayout = a.getResourceId(attr, 0); if (mPopupLayout == R.layout.null_layout) mPopupLayout = 0; break; } } final Resources res = getResources(); if (previewLayout != 0) { mPreviewPopup = new PopupWindow(context); Log.i(TAG, "new mPreviewPopup " + mPreviewPopup + " from " + this); mPreviewText = (TextView) inflate.inflate(previewLayout, null); mPreviewTextSizeLarge = (int) res.getDimension(R.dimen.key_preview_text_size_large); mPreviewPopup.setContentView(mPreviewText); mPreviewPopup.setBackgroundDrawable(null); mPreviewPopup.setTouchable(false); mPreviewPopup.setAnimationStyle(R.style.KeyPreviewAnimation); } else { mShowPreview = false; } if (mPopupLayout != 0) { mMiniKeyboardParent = this; mMiniKeyboardPopup = new PopupWindow(context); Log.i(TAG, "new mMiniKeyboardPopup " + mMiniKeyboardPopup + " from " + this); mMiniKeyboardPopup.setBackgroundDrawable(null); mMiniKeyboardPopup.setAnimationStyle(R.style.MiniKeyboardAnimation); mMiniKeyboardVisible = false; } } public void setPhoneKeyboard(Keyboard phoneKeyboard) { mPhoneKeyboard = phoneKeyboard; } public void setExtensionLayoutResId (int id) { mExtensionLayoutResId = id; } @Override public void setPreviewEnabled(boolean previewEnabled) { if (getKeyboard() == mPhoneKeyboard) { // Phone keyboard never shows popup preview (except language switch). super.setPreviewEnabled(false); } else { super.setPreviewEnabled(previewEnabled); } } @Override public void setKeyboard(Keyboard newKeyboard) { final Keyboard oldKeyboard = getKeyboard(); if (oldKeyboard instanceof LatinKeyboard) { // Reset old keyboard state before switching to new keyboard. ((LatinKeyboard)oldKeyboard).keyReleased(); } super.setKeyboard(newKeyboard); // One-seventh of the keyboard width seems like a reasonable threshold mJumpThresholdSquare = newKeyboard.getMinWidth() / 7; mJumpThresholdSquare *= mJumpThresholdSquare; // Get Y coordinate of the last row based on the row count, assuming equal height int numRows = newKeyboard.mRowCount; mLastRowY = (newKeyboard.getHeight() * (numRows - 1)) / numRows; mExtensionKeyboard = ((LatinKeyboard) newKeyboard).getExtension(); if (mExtensionKeyboard != null && mExtension != null) mExtension.setKeyboard(mExtensionKeyboard); setKeyboardLocal(newKeyboard); } @Override /*package*/ boolean enableSlideKeyHack() { return true; } @Override protected boolean onLongPress(Key key) { PointerTracker.clearSlideKeys(); int primaryCode = key.codes[0]; if (primaryCode == KEYCODE_OPTIONS) { return invokeOnKey(KEYCODE_OPTIONS_LONGPRESS); } else if (primaryCode == KEYCODE_DPAD_CENTER) { return invokeOnKey(KEYCODE_COMPOSE); } else if (primaryCode == '0' && getKeyboard() == mPhoneKeyboard) { // Long pressing on 0 in phone number keypad gives you a '+'. return invokeOnKey('+'); } else { return super.onLongPress(key); } } private boolean invokeOnKey(int primaryCode) { getOnKeyboardActionListener().onKey(primaryCode, null, LatinKeyboardBaseView.NOT_A_TOUCH_COORDINATE, LatinKeyboardBaseView.NOT_A_TOUCH_COORDINATE); return true; } /** * This function checks to see if we need to handle any sudden jumps in the pointer location * that could be due to a multi-touch being treated as a move by the firmware or hardware. * Once a sudden jump is detected, all subsequent move events are discarded * until an UP is received.<P> * When a sudden jump is detected, an UP event is simulated at the last position and when * the sudden moves subside, a DOWN event is simulated for the second key. * @param me the motion event * @return true if the event was consumed, so that it doesn't continue to be handled by * KeyboardView. */ private boolean handleSuddenJump(MotionEvent me) { final int action = me.getAction(); final int x = (int) me.getX(); final int y = (int) me.getY(); boolean result = false; // Real multi-touch event? Stop looking for sudden jumps if (me.getPointerCount() > 1) { mDisableDisambiguation = true; } if (mDisableDisambiguation) { // If UP, reset the multi-touch flag if (action == MotionEvent.ACTION_UP) mDisableDisambiguation = false; return false; } switch (action) { case MotionEvent.ACTION_DOWN: // Reset the "session" mDroppingEvents = false; mDisableDisambiguation = false; break; case MotionEvent.ACTION_MOVE: // Is this a big jump? final int distanceSquare = (mLastX - x) * (mLastX - x) + (mLastY - y) * (mLastY - y); // Check the distance and also if the move is not entirely within the bottom row // If it's only in the bottom row, it might be an intentional slide gesture // for language switching if (distanceSquare > mJumpThresholdSquare && (mLastY < mLastRowY || y < mLastRowY)) { // If we're not yet dropping events, start dropping and send an UP event if (!mDroppingEvents) { mDroppingEvents = true; // Send an up event MotionEvent translated = MotionEvent.obtain(me.getEventTime(), me.getEventTime(), MotionEvent.ACTION_UP, mLastX, mLastY, me.getMetaState()); super.onTouchEvent(translated); translated.recycle(); } result = true; } else if (mDroppingEvents) { // If moves are small and we're already dropping events, continue dropping result = true; } break; case MotionEvent.ACTION_UP: if (mDroppingEvents) { // Send a down event first, as we dropped a bunch of sudden jumps and assume that // the user is releasing the touch on the second key. MotionEvent translated = MotionEvent.obtain(me.getEventTime(), me.getEventTime(), MotionEvent.ACTION_DOWN, x, y, me.getMetaState()); super.onTouchEvent(translated); translated.recycle(); mDroppingEvents = false; // Let the up event get processed as well, result = false } break; } // Track the previous coordinate mLastX = x; mLastY = y; return result; } @Override public boolean onTouchEvent(MotionEvent me) { LatinKeyboard keyboard = (LatinKeyboard) getKeyboard(); if (LatinIME.sKeyboardSettings.showTouchPos || DEBUG_LINE) { mLastX = (int) me.getX(); mLastY = (int) me.getY(); invalidate(); } // If an extension keyboard is visible or this is an extension keyboard, don't look // for sudden jumps. Otherwise, if there was a sudden jump, return without processing the // actual motion event. if (!mExtensionVisible && !mIsExtensionType && handleSuddenJump(me)) return true; // Reset any bounding box controls in the keyboard if (me.getAction() == MotionEvent.ACTION_DOWN) { keyboard.keyReleased(); } if (me.getAction() == MotionEvent.ACTION_UP) { int languageDirection = keyboard.getLanguageChangeDirection(); if (languageDirection != 0) { getOnKeyboardActionListener().onKey( languageDirection == 1 ? KEYCODE_NEXT_LANGUAGE : KEYCODE_PREV_LANGUAGE, null, mLastX, mLastY); me.setAction(MotionEvent.ACTION_CANCEL); keyboard.keyReleased(); return super.onTouchEvent(me); } } // If we don't have an extension keyboard, don't go any further. if (keyboard.getExtension() == null) { return super.onTouchEvent(me); } // If the motion event is above the keyboard and it's not an UP event coming // even before the first MOVE event into the extension area if (me.getY() < 0 && (mExtensionVisible || me.getAction() != MotionEvent.ACTION_UP)) { if (mExtensionVisible) { int action = me.getAction(); if (mFirstEvent) action = MotionEvent.ACTION_DOWN; mFirstEvent = false; MotionEvent translated = MotionEvent.obtain(me.getEventTime(), me.getEventTime(), action, me.getX(), me.getY() + mExtension.getHeight(), me.getMetaState()); if (me.getActionIndex() > 0) return true; // ignore second touches to avoid "pointerIndex out of range" boolean result = mExtension.onTouchEvent(translated); translated.recycle(); if (me.getAction() == MotionEvent.ACTION_UP || me.getAction() == MotionEvent.ACTION_CANCEL) { closeExtension(); } return result; } else { if (swipeUp()) { return true; } else if (openExtension()) { MotionEvent cancel = MotionEvent.obtain(me.getDownTime(), me.getEventTime(), MotionEvent.ACTION_CANCEL, me.getX() - 100, me.getY() - 100, 0); super.onTouchEvent(cancel); cancel.recycle(); if (mExtension.getHeight() > 0) { MotionEvent translated = MotionEvent.obtain(me.getEventTime(), me.getEventTime(), MotionEvent.ACTION_DOWN, me.getX(), me.getY() + mExtension.getHeight(), me.getMetaState()); mExtension.onTouchEvent(translated); translated.recycle(); } else { mFirstEvent = true; } // Stop processing multi-touch errors mDisableDisambiguation = true; } return true; } } else if (mExtensionVisible) { closeExtension(); // Send a down event into the main keyboard first MotionEvent down = MotionEvent.obtain(me.getEventTime(), me.getEventTime(), MotionEvent.ACTION_DOWN, me.getX(), me.getY(), me.getMetaState()); super.onTouchEvent(down, true); down.recycle(); // Send the actual event return super.onTouchEvent(me); } else { return super.onTouchEvent(me); } } private void setExtensionType(boolean isExtensionType) { mIsExtensionType = isExtensionType; } private boolean openExtension() { // If the current keyboard is not visible, or if the mini keyboard is active, don't show the popup if (!isShown() || popupKeyboardIsShowing()) { return false; } PointerTracker.clearSlideKeys(); if (((LatinKeyboard) getKeyboard()).getExtension() == null) return false; makePopupWindow(); mExtensionVisible = true; return true; } private void makePopupWindow() { dismissPopupKeyboard(); if (mExtensionPopup == null) { int[] windowLocation = new int[2]; mExtensionPopup = new PopupWindow(getContext()); mExtensionPopup.setBackgroundDrawable(null); LayoutInflater li = (LayoutInflater) getContext().getSystemService( Context.LAYOUT_INFLATER_SERVICE); mExtension = (LatinKeyboardView) li.inflate(mExtensionLayoutResId == 0 ? R.layout.input_trans : mExtensionLayoutResId, null); Keyboard keyboard = mExtensionKeyboard; mExtension.setKeyboard(keyboard); mExtension.setExtensionType(true); mExtension.setPadding(0, 0, 0, 0); mExtension.setOnKeyboardActionListener( new ExtensionKeyboardListener(getOnKeyboardActionListener())); mExtension.setPopupParent(this); mExtension.setPopupOffset(0, -windowLocation[1]); mExtensionPopup.setContentView(mExtension); mExtensionPopup.setWidth(getWidth()); mExtensionPopup.setHeight(keyboard.getHeight()); mExtensionPopup.setAnimationStyle(-1); getLocationInWindow(windowLocation); // TODO: Fix the "- 30". mExtension.setPopupOffset(0, -windowLocation[1] - 30); mExtensionPopup.showAtLocation(this, 0, 0, -keyboard.getHeight() + windowLocation[1] + this.getPaddingTop()); } else { mExtension.setVisibility(VISIBLE); } mExtension.setShiftState(getShiftState()); // propagate shift state } @Override public void closing() { super.closing(); if (mExtensionPopup != null && mExtensionPopup.isShowing()) { mExtensionPopup.dismiss(); mExtensionPopup = null; } } private void closeExtension() { mExtension.closing(); mExtension.setVisibility(INVISIBLE); mExtensionVisible = false; } private static class ExtensionKeyboardListener implements OnKeyboardActionListener { private OnKeyboardActionListener mTarget; ExtensionKeyboardListener(OnKeyboardActionListener target) { mTarget = target; } public void onKey(int primaryCode, int[] keyCodes, int x, int y) { mTarget.onKey(primaryCode, keyCodes, x, y); } public void onPress(int primaryCode) { mTarget.onPress(primaryCode); } public void onRelease(int primaryCode) { mTarget.onRelease(primaryCode); } public void onText(CharSequence text) { mTarget.onText(text); } public void onCancel() { mTarget.onCancel(); } public boolean swipeDown() { // Don't pass through return true; } public boolean swipeLeft() { // Don't pass through return true; } public boolean swipeRight() { // Don't pass through return true; } public boolean swipeUp() { // Don't pass through return true; } } /**************************** INSTRUMENTATION *******************************/ static final boolean DEBUG_AUTO_PLAY = false; static final boolean DEBUG_LINE = false; private static final int MSG_TOUCH_DOWN = 1; private static final int MSG_TOUCH_UP = 2; Handler mHandler2; private String mStringToPlay; private int mStringIndex; private boolean mDownDelivered; private Key[] mAsciiKeys = new Key[256]; private boolean mPlaying; private int mLastX; private int mLastY; private Paint mPaint; private void setKeyboardLocal(Keyboard k) { if (DEBUG_AUTO_PLAY) { findKeys(); if (mHandler2 == null) { mHandler2 = new Handler() { @Override public void handleMessage(Message msg) { removeMessages(MSG_TOUCH_DOWN); removeMessages(MSG_TOUCH_UP); if (mPlaying == false) return; switch (msg.what) { case MSG_TOUCH_DOWN: if (mStringIndex >= mStringToPlay.length()) { mPlaying = false; return; } char c = mStringToPlay.charAt(mStringIndex); while (c > 255 || mAsciiKeys[c] == null) { mStringIndex++; if (mStringIndex >= mStringToPlay.length()) { mPlaying = false; return; } c = mStringToPlay.charAt(mStringIndex); } int x = mAsciiKeys[c].x + 10; int y = mAsciiKeys[c].y + 26; MotionEvent me = MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN, x, y, 0); LatinKeyboardView.this.dispatchTouchEvent(me); me.recycle(); sendEmptyMessageDelayed(MSG_TOUCH_UP, 500); // Deliver up in 500ms if nothing else // happens mDownDelivered = true; break; case MSG_TOUCH_UP: char cUp = mStringToPlay.charAt(mStringIndex); int x2 = mAsciiKeys[cUp].x + 10; int y2 = mAsciiKeys[cUp].y + 26; mStringIndex++; MotionEvent me2 = MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_UP, x2, y2, 0); LatinKeyboardView.this.dispatchTouchEvent(me2); me2.recycle(); sendEmptyMessageDelayed(MSG_TOUCH_DOWN, 500); // Deliver up in 500ms if nothing else // happens mDownDelivered = false; break; } } }; } } } private void findKeys() { List<Key> keys = getKeyboard().getKeys(); // Get the keys on this keyboard for (int i = 0; i < keys.size(); i++) { int code = keys.get(i).codes[0]; if (code >= 0 && code <= 255) { mAsciiKeys[code] = keys.get(i); } } } public void startPlaying(String s) { if (DEBUG_AUTO_PLAY) { if (s == null) return; mStringToPlay = s.toLowerCase(); mPlaying = true; mDownDelivered = false; mStringIndex = 0; mHandler2.sendEmptyMessageDelayed(MSG_TOUCH_DOWN, 10); } } @Override public void draw(Canvas c) { LatinIMEUtil.GCUtils.getInstance().reset(); boolean tryGC = true; for (int i = 0; i < LatinIMEUtil.GCUtils.GC_TRY_LOOP_MAX && tryGC; ++i) { try { super.draw(c); tryGC = false; } catch (OutOfMemoryError e) { tryGC = LatinIMEUtil.GCUtils.getInstance().tryGCOrWait("LatinKeyboardView", e); } } if (DEBUG_AUTO_PLAY) { if (mPlaying) { mHandler2.removeMessages(MSG_TOUCH_DOWN); mHandler2.removeMessages(MSG_TOUCH_UP); if (mDownDelivered) { mHandler2.sendEmptyMessageDelayed(MSG_TOUCH_UP, 20); } else { mHandler2.sendEmptyMessageDelayed(MSG_TOUCH_DOWN, 20); } } } if (LatinIME.sKeyboardSettings.showTouchPos || DEBUG_LINE) { if (mPaint == null) { mPaint = new Paint(); mPaint.setColor(0x80FFFFFF); mPaint.setAntiAlias(false); } c.drawLine(mLastX, 0, mLastX, getHeight(), mPaint); c.drawLine(0, mLastY, getWidth(), mLastY, mPaint); } } }
Java
/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.pocketworkstation.pckeyboard; import java.util.ArrayList; import java.util.HashMap; import java.util.Locale; import java.util.Map; import android.app.AlertDialog; import android.app.Dialog; import android.app.backup.BackupManager; import android.content.DialogInterface; import android.content.SharedPreferences; import android.content.res.Resources; import android.os.Bundle; import android.preference.CheckBoxPreference; import android.preference.ListPreference; import android.preference.Preference; import android.preference.PreferenceActivity; import android.preference.PreferenceGroup; import android.speech.SpeechRecognizer; import android.text.AutoText; import android.text.InputType; import android.util.Log; import com.android.inputmethod.voice.SettingsUtil; import com.android.inputmethod.voice.VoiceInputLogger; public class LatinIMESettings extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener, DialogInterface.OnDismissListener { private static final String QUICK_FIXES_KEY = "quick_fixes"; private static final String PREDICTION_SETTINGS_KEY = "prediction_settings"; private static final String VOICE_SETTINGS_KEY = "voice_mode"; /* package */ static final String PREF_SETTINGS_KEY = "settings_key"; static final String INPUT_CONNECTION_INFO = "input_connection_info"; private static final String TAG = "LatinIMESettings"; // Dialog ids private static final int VOICE_INPUT_CONFIRM_DIALOG = 0; private CheckBoxPreference mQuickFixes; private ListPreference mVoicePreference; private ListPreference mSettingsKeyPreference; private ListPreference mKeyboardModePortraitPreference; private ListPreference mKeyboardModeLandscapePreference; private Preference mInputConnectionInfo; private boolean mVoiceOn; private VoiceInputLogger mLogger; private boolean mOkClicked = false; private String mVoiceModeOff; @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); addPreferencesFromResource(R.xml.prefs); mQuickFixes = (CheckBoxPreference) findPreference(QUICK_FIXES_KEY); mVoicePreference = (ListPreference) findPreference(VOICE_SETTINGS_KEY); mSettingsKeyPreference = (ListPreference) findPreference(PREF_SETTINGS_KEY); mInputConnectionInfo = (Preference) findPreference(INPUT_CONNECTION_INFO); // TODO(klausw): remove these when no longer needed mKeyboardModePortraitPreference = (ListPreference) findPreference("pref_keyboard_mode_portrait"); mKeyboardModeLandscapePreference = (ListPreference) findPreference("pref_keyboard_mode_landscape"); SharedPreferences prefs = getPreferenceManager().getSharedPreferences(); prefs.registerOnSharedPreferenceChangeListener(this); mVoiceModeOff = getString(R.string.voice_mode_off); mVoiceOn = !(prefs.getString(VOICE_SETTINGS_KEY, mVoiceModeOff).equals(mVoiceModeOff)); mLogger = VoiceInputLogger.getLogger(this); } @Override protected void onResume() { super.onResume(); int autoTextSize = AutoText.getSize(getListView()); if (autoTextSize < 1) { ((PreferenceGroup) findPreference(PREDICTION_SETTINGS_KEY)) .removePreference(mQuickFixes); } if (!LatinIME.VOICE_INSTALLED || !SpeechRecognizer.isRecognitionAvailable(this)) { getPreferenceScreen().removePreference(mVoicePreference); } else { updateVoiceModeSummary(); } Log.i(TAG, "compactModeEnabled=" + LatinIME.sKeyboardSettings.compactModeEnabled); if (!LatinIME.sKeyboardSettings.compactModeEnabled) { CharSequence[] oldEntries = mKeyboardModePortraitPreference.getEntries(); CharSequence[] oldValues = mKeyboardModePortraitPreference.getEntryValues(); if (oldEntries.length > 2) { CharSequence[] newEntries = new CharSequence[] { oldEntries[0], oldEntries[2] }; CharSequence[] newValues = new CharSequence[] { oldValues[0], oldValues[2] }; mKeyboardModePortraitPreference.setEntries(newEntries); mKeyboardModePortraitPreference.setEntryValues(newValues); mKeyboardModeLandscapePreference.setEntries(newEntries); mKeyboardModeLandscapePreference.setEntryValues(newValues); } } updateSummaries(); } @Override protected void onDestroy() { getPreferenceManager().getSharedPreferences().unregisterOnSharedPreferenceChangeListener( this); super.onDestroy(); } public void onSharedPreferenceChanged(SharedPreferences prefs, String key) { (new BackupManager(this)).dataChanged(); // If turning on voice input, show dialog if (key.equals(VOICE_SETTINGS_KEY) && !mVoiceOn) { if (!prefs.getString(VOICE_SETTINGS_KEY, mVoiceModeOff) .equals(mVoiceModeOff)) { showVoiceConfirmation(); } } mVoiceOn = !(prefs.getString(VOICE_SETTINGS_KEY, mVoiceModeOff).equals(mVoiceModeOff)); updateVoiceModeSummary(); updateSummaries(); } static Map<Integer, String> INPUT_CLASSES = new HashMap<Integer, String>(); static Map<Integer, String> DATETIME_VARIATIONS = new HashMap<Integer, String>(); static Map<Integer, String> TEXT_VARIATIONS = new HashMap<Integer, String>(); static Map<Integer, String> NUMBER_VARIATIONS = new HashMap<Integer, String>(); static { INPUT_CLASSES.put(0x00000004, "DATETIME"); INPUT_CLASSES.put(0x00000002, "NUMBER"); INPUT_CLASSES.put(0x00000003, "PHONE"); INPUT_CLASSES.put(0x00000001, "TEXT"); INPUT_CLASSES.put(0x00000000, "NULL"); DATETIME_VARIATIONS.put(0x00000010, "DATE"); DATETIME_VARIATIONS.put(0x00000020, "TIME"); NUMBER_VARIATIONS.put(0x00000010, "PASSWORD"); TEXT_VARIATIONS.put(0x00000020, "EMAIL_ADDRESS"); TEXT_VARIATIONS.put(0x00000030, "EMAIL_SUBJECT"); TEXT_VARIATIONS.put(0x000000b0, "FILTER"); TEXT_VARIATIONS.put(0x00000050, "LONG_MESSAGE"); TEXT_VARIATIONS.put(0x00000080, "PASSWORD"); TEXT_VARIATIONS.put(0x00000060, "PERSON_NAME"); TEXT_VARIATIONS.put(0x000000c0, "PHONETIC"); TEXT_VARIATIONS.put(0x00000070, "POSTAL_ADDRESS"); TEXT_VARIATIONS.put(0x00000040, "SHORT_MESSAGE"); TEXT_VARIATIONS.put(0x00000010, "URI"); TEXT_VARIATIONS.put(0x00000090, "VISIBLE_PASSWORD"); TEXT_VARIATIONS.put(0x000000a0, "WEB_EDIT_TEXT"); TEXT_VARIATIONS.put(0x000000d0, "WEB_EMAIL_ADDRESS"); TEXT_VARIATIONS.put(0x000000e0, "WEB_PASSWORD"); } private static void addBit(StringBuffer buf, int bit, String str) { if (bit != 0) { buf.append("|"); buf.append(str); } } private static String inputTypeDesc(int type) { int cls = type & 0x0000000f; // MASK_CLASS int flags = type & 0x00fff000; // MASK_FLAGS int var = type & 0x00000ff0; // MASK_VARIATION StringBuffer out = new StringBuffer(); String clsName = INPUT_CLASSES.get(cls); out.append(clsName != null ? clsName : "?"); if (cls == InputType.TYPE_CLASS_TEXT) { String varName = TEXT_VARIATIONS.get(var); if (varName != null) { out.append("."); out.append(varName); } addBit(out, flags & 0x00010000, "AUTO_COMPLETE"); addBit(out, flags & 0x00008000, "AUTO_CORRECT"); addBit(out, flags & 0x00001000, "CAP_CHARACTERS"); addBit(out, flags & 0x00004000, "CAP_SENTENCES"); addBit(out, flags & 0x00002000, "CAP_WORDS"); addBit(out, flags & 0x00040000, "IME_MULTI_LINE"); addBit(out, flags & 0x00020000, "MULTI_LINE"); addBit(out, flags & 0x00080000, "NO_SUGGESTIONS"); } else if (cls == InputType.TYPE_CLASS_NUMBER) { String varName = NUMBER_VARIATIONS.get(var); if (varName != null) { out.append("."); out.append(varName); } addBit(out, flags & 0x00002000, "DECIMAL"); addBit(out, flags & 0x00001000, "SIGNED"); } else if (cls == InputType.TYPE_CLASS_DATETIME) { String varName = DATETIME_VARIATIONS.get(var); if (varName != null) { out.append("."); out.append(varName); } } return out.toString(); } private void updateSummaries() { Resources res = getResources(); mSettingsKeyPreference.setSummary( res.getStringArray(R.array.settings_key_modes) [mSettingsKeyPreference.findIndexOfValue(mSettingsKeyPreference.getValue())]); mInputConnectionInfo.setSummary(String.format("%s type=%s", LatinIME.sKeyboardSettings.editorPackageName, inputTypeDesc(LatinIME.sKeyboardSettings.editorInputType) )); } private void showVoiceConfirmation() { mOkClicked = false; showDialog(VOICE_INPUT_CONFIRM_DIALOG); } private void updateVoiceModeSummary() { mVoicePreference.setSummary( getResources().getStringArray(R.array.voice_input_modes_summary) [mVoicePreference.findIndexOfValue(mVoicePreference.getValue())]); } @Override protected Dialog onCreateDialog(int id) { switch (id) { case VOICE_INPUT_CONFIRM_DIALOG: DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { if (whichButton == DialogInterface.BUTTON_NEGATIVE) { mVoicePreference.setValue(mVoiceModeOff); mLogger.settingsWarningDialogCancel(); } else if (whichButton == DialogInterface.BUTTON_POSITIVE) { mOkClicked = true; mLogger.settingsWarningDialogOk(); } updateVoicePreference(); } }; AlertDialog.Builder builder = new AlertDialog.Builder(this) .setTitle(R.string.voice_warning_title) .setPositiveButton(android.R.string.ok, listener) .setNegativeButton(android.R.string.cancel, listener); // Get the current list of supported locales and check the current locale against // that list, to decide whether to put a warning that voice input will not work in // the current language as part of the pop-up confirmation dialog. String supportedLocalesString = SettingsUtil.getSettingsString( getContentResolver(), SettingsUtil.LATIN_IME_VOICE_INPUT_SUPPORTED_LOCALES, LatinIME.DEFAULT_VOICE_INPUT_SUPPORTED_LOCALES); ArrayList<String> voiceInputSupportedLocales = LatinIME.newArrayList(supportedLocalesString.split("\\s+")); boolean localeSupported = voiceInputSupportedLocales.contains(Locale.getDefault().toString()) || voiceInputSupportedLocales.contains(Locale.getDefault().getLanguage()); if (localeSupported) { String message = getString(R.string.voice_warning_may_not_understand) + "\n\n" + getString(R.string.voice_hint_dialog_message); builder.setMessage(message); } else { String message = getString(R.string.voice_warning_locale_not_supported) + "\n\n" + getString(R.string.voice_warning_may_not_understand) + "\n\n" + getString(R.string.voice_hint_dialog_message); builder.setMessage(message); } AlertDialog dialog = builder.create(); dialog.setOnDismissListener(this); mLogger.settingsWarningDialogShown(); return dialog; default: Log.e(TAG, "unknown dialog " + id); return null; } } public void onDismiss(DialogInterface dialog) { mLogger.settingsWarningDialogDismissed(); if (!mOkClicked) { // This assumes that onPreferenceClick gets called first, and this if the user // agreed after the warning, we set the mOkClicked value to true. mVoicePreference.setValue(mVoiceModeOff); } } private void updateVoicePreference() { boolean isChecked = !mVoicePreference.getValue().equals(mVoiceModeOff); if (isChecked) { mLogger.voiceInputSettingEnabled(); } else { mLogger.voiceInputSettingDisabled(); } } }
Java
/* * Copyright (C) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.pocketworkstation.pckeyboard; import com.android.inputmethod.voice.SettingsUtil; import android.content.ContentResolver; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.view.inputmethod.InputConnection; import java.util.Calendar; import java.util.HashMap; import java.util.Map; /** * Logic to determine when to display hints on usage to the user. */ public class Hints { public interface Display { public void showHint(int viewResource); } private static final String PREF_VOICE_HINT_NUM_UNIQUE_DAYS_SHOWN = "voice_hint_num_unique_days_shown"; private static final String PREF_VOICE_HINT_LAST_TIME_SHOWN = "voice_hint_last_time_shown"; private static final String PREF_VOICE_INPUT_LAST_TIME_USED = "voice_input_last_time_used"; private static final String PREF_VOICE_PUNCTUATION_HINT_VIEW_COUNT = "voice_punctuation_hint_view_count"; private static final int DEFAULT_SWIPE_HINT_MAX_DAYS_TO_SHOW = 7; private static final int DEFAULT_PUNCTUATION_HINT_MAX_DISPLAYS = 7; private Context mContext; private Display mDisplay; private boolean mVoiceResultContainedPunctuation; private int mSwipeHintMaxDaysToShow; private int mPunctuationHintMaxDisplays; // Only show punctuation hint if voice result did not contain punctuation. static final Map<CharSequence, String> SPEAKABLE_PUNCTUATION = new HashMap<CharSequence, String>(); static { SPEAKABLE_PUNCTUATION.put(",", "comma"); SPEAKABLE_PUNCTUATION.put(".", "period"); SPEAKABLE_PUNCTUATION.put("?", "question mark"); } public Hints(Context context, Display display) { mContext = context; mDisplay = display; ContentResolver cr = mContext.getContentResolver(); mSwipeHintMaxDaysToShow = SettingsUtil.getSettingsInt( cr, SettingsUtil.LATIN_IME_VOICE_INPUT_SWIPE_HINT_MAX_DAYS, DEFAULT_SWIPE_HINT_MAX_DAYS_TO_SHOW); mPunctuationHintMaxDisplays = SettingsUtil.getSettingsInt( cr, SettingsUtil.LATIN_IME_VOICE_INPUT_PUNCTUATION_HINT_MAX_DISPLAYS, DEFAULT_PUNCTUATION_HINT_MAX_DISPLAYS); } public boolean showSwipeHintIfNecessary(boolean fieldRecommended) { if (fieldRecommended && shouldShowSwipeHint()) { showHint(R.layout.voice_swipe_hint); return true; } return false; } public boolean showPunctuationHintIfNecessary(InputConnection ic) { if (!mVoiceResultContainedPunctuation && ic != null && getAndIncrementPref(PREF_VOICE_PUNCTUATION_HINT_VIEW_COUNT) < mPunctuationHintMaxDisplays) { CharSequence charBeforeCursor = ic.getTextBeforeCursor(1, 0); if (SPEAKABLE_PUNCTUATION.containsKey(charBeforeCursor)) { showHint(R.layout.voice_punctuation_hint); return true; } } return false; } public void registerVoiceResult(String text) { // Update the current time as the last time voice input was used. SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(mContext).edit(); editor.putLong(PREF_VOICE_INPUT_LAST_TIME_USED, System.currentTimeMillis()); SharedPreferencesCompat.apply(editor); mVoiceResultContainedPunctuation = false; for (CharSequence s : SPEAKABLE_PUNCTUATION.keySet()) { if (text.indexOf(s.toString()) >= 0) { mVoiceResultContainedPunctuation = true; break; } } } private boolean shouldShowSwipeHint() { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(mContext); int numUniqueDaysShown = sp.getInt(PREF_VOICE_HINT_NUM_UNIQUE_DAYS_SHOWN, 0); // If we've already shown the hint for enough days, we'll return false. if (numUniqueDaysShown < mSwipeHintMaxDaysToShow) { long lastTimeVoiceWasUsed = sp.getLong(PREF_VOICE_INPUT_LAST_TIME_USED, 0); // If the user has used voice today, we'll return false. (We don't show the hint on // any day that the user has already used voice.) if (!isFromToday(lastTimeVoiceWasUsed)) { return true; } } return false; } /** * Determines whether the provided time is from some time today (i.e., this day, month, * and year). */ private boolean isFromToday(long timeInMillis) { if (timeInMillis == 0) return false; Calendar today = Calendar.getInstance(); today.setTimeInMillis(System.currentTimeMillis()); Calendar timestamp = Calendar.getInstance(); timestamp.setTimeInMillis(timeInMillis); return (today.get(Calendar.YEAR) == timestamp.get(Calendar.YEAR) && today.get(Calendar.DAY_OF_MONTH) == timestamp.get(Calendar.DAY_OF_MONTH) && today.get(Calendar.MONTH) == timestamp.get(Calendar.MONTH)); } private void showHint(int hintViewResource) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(mContext); int numUniqueDaysShown = sp.getInt(PREF_VOICE_HINT_NUM_UNIQUE_DAYS_SHOWN, 0); long lastTimeHintWasShown = sp.getLong(PREF_VOICE_HINT_LAST_TIME_SHOWN, 0); // If this is the first time the hint is being shown today, increase the saved values // to represent that. We don't need to increase the last time the hint was shown unless // it is a different day from the current value. if (!isFromToday(lastTimeHintWasShown)) { SharedPreferences.Editor editor = sp.edit(); editor.putInt(PREF_VOICE_HINT_NUM_UNIQUE_DAYS_SHOWN, numUniqueDaysShown + 1); editor.putLong(PREF_VOICE_HINT_LAST_TIME_SHOWN, System.currentTimeMillis()); SharedPreferencesCompat.apply(editor); } if (mDisplay != null) { mDisplay.showHint(hintViewResource); } } private int getAndIncrementPref(String pref) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(mContext); int value = sp.getInt(pref, 0); SharedPreferences.Editor editor = sp.edit(); editor.putInt(pref, value + 1); SharedPreferencesCompat.apply(editor); return value; } }
Java
/* * Copyright (C) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.pocketworkstation.pckeyboard; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteQueryBuilder; import android.os.AsyncTask; import android.provider.BaseColumns; import android.util.Log; /** * Stores all the pairs user types in databases. Prune the database if the size * gets too big. Unlike AutoDictionary, it even stores the pairs that are already * in the dictionary. */ public class UserBigramDictionary extends ExpandableDictionary { private static final String TAG = "UserBigramDictionary"; /** Any pair being typed or picked */ private static final int FREQUENCY_FOR_TYPED = 2; /** Maximum frequency for all pairs */ private static final int FREQUENCY_MAX = 127; /** * If this pair is typed 6 times, it would be suggested. * Should be smaller than ContactsDictionary.FREQUENCY_FOR_CONTACTS_BIGRAM */ protected static final int SUGGEST_THRESHOLD = 6 * FREQUENCY_FOR_TYPED; /** Maximum number of pairs. Pruning will start when databases goes above this number. */ private static int sMaxUserBigrams = 10000; /** * When it hits maximum bigram pair, it will delete until you are left with * only (sMaxUserBigrams - sDeleteUserBigrams) pairs. * Do not keep this number small to avoid deleting too often. */ private static int sDeleteUserBigrams = 1000; /** * Database version should increase if the database structure changes */ private static final int DATABASE_VERSION = 1; private static final String DATABASE_NAME = "userbigram_dict.db"; /** Name of the words table in the database */ private static final String MAIN_TABLE_NAME = "main"; // TODO: Consume less space by using a unique id for locale instead of the whole // 2-5 character string. (Same TODO from AutoDictionary) private static final String MAIN_COLUMN_ID = BaseColumns._ID; private static final String MAIN_COLUMN_WORD1 = "word1"; private static final String MAIN_COLUMN_WORD2 = "word2"; private static final String MAIN_COLUMN_LOCALE = "locale"; /** Name of the frequency table in the database */ private static final String FREQ_TABLE_NAME = "frequency"; private static final String FREQ_COLUMN_ID = BaseColumns._ID; private static final String FREQ_COLUMN_PAIR_ID = "pair_id"; private static final String FREQ_COLUMN_FREQUENCY = "freq"; private final LatinIME mIme; /** Locale for which this auto dictionary is storing words */ private String mLocale; private HashSet<Bigram> mPendingWrites = new HashSet<Bigram>(); private final Object mPendingWritesLock = new Object(); private static volatile boolean sUpdatingDB = false; private final static HashMap<String, String> sDictProjectionMap; static { sDictProjectionMap = new HashMap<String, String>(); sDictProjectionMap.put(MAIN_COLUMN_ID, MAIN_COLUMN_ID); sDictProjectionMap.put(MAIN_COLUMN_WORD1, MAIN_COLUMN_WORD1); sDictProjectionMap.put(MAIN_COLUMN_WORD2, MAIN_COLUMN_WORD2); sDictProjectionMap.put(MAIN_COLUMN_LOCALE, MAIN_COLUMN_LOCALE); sDictProjectionMap.put(FREQ_COLUMN_ID, FREQ_COLUMN_ID); sDictProjectionMap.put(FREQ_COLUMN_PAIR_ID, FREQ_COLUMN_PAIR_ID); sDictProjectionMap.put(FREQ_COLUMN_FREQUENCY, FREQ_COLUMN_FREQUENCY); } private static DatabaseHelper sOpenHelper = null; private static class Bigram { String word1; String word2; int frequency; Bigram(String word1, String word2, int frequency) { this.word1 = word1; this.word2 = word2; this.frequency = frequency; } @Override public boolean equals(Object bigram) { Bigram bigram2 = (Bigram) bigram; return (word1.equals(bigram2.word1) && word2.equals(bigram2.word2)); } @Override public int hashCode() { return (word1 + " " + word2).hashCode(); } } public void setDatabaseMax(int maxUserBigram) { sMaxUserBigrams = maxUserBigram; } public void setDatabaseDelete(int deleteUserBigram) { sDeleteUserBigrams = deleteUserBigram; } public UserBigramDictionary(Context context, LatinIME ime, String locale, int dicTypeId) { super(context, dicTypeId); mIme = ime; mLocale = locale; if (sOpenHelper == null) { sOpenHelper = new DatabaseHelper(getContext()); } if (mLocale != null && mLocale.length() > 1) { loadDictionary(); } } @Override public void close() { flushPendingWrites(); // Don't close the database as locale changes will require it to be reopened anyway // Also, the database is written to somewhat frequently, so it needs to be kept alive // throughout the life of the process. // mOpenHelper.close(); super.close(); } /** * Pair will be added to the userbigram database. */ public int addBigrams(String word1, String word2) { // remove caps if (mIme != null && mIme.getCurrentWord().isAutoCapitalized()) { word2 = Character.toLowerCase(word2.charAt(0)) + word2.substring(1); } int freq = super.addBigram(word1, word2, FREQUENCY_FOR_TYPED); if (freq > FREQUENCY_MAX) freq = FREQUENCY_MAX; synchronized (mPendingWritesLock) { if (freq == FREQUENCY_FOR_TYPED || mPendingWrites.isEmpty()) { mPendingWrites.add(new Bigram(word1, word2, freq)); } else { Bigram bi = new Bigram(word1, word2, freq); mPendingWrites.remove(bi); mPendingWrites.add(bi); } } return freq; } /** * Schedules a background thread to write any pending words to the database. */ public void flushPendingWrites() { synchronized (mPendingWritesLock) { // Nothing pending? Return if (mPendingWrites.isEmpty()) return; // Create a background thread to write the pending entries new UpdateDbTask(getContext(), sOpenHelper, mPendingWrites, mLocale).execute(); // Create a new map for writing new entries into while the old one is written to db mPendingWrites = new HashSet<Bigram>(); } } /** Used for testing purpose **/ void waitUntilUpdateDBDone() { synchronized (mPendingWritesLock) { while (sUpdatingDB) { try { Thread.sleep(100); } catch (InterruptedException e) { } } return; } } @Override public void loadDictionaryAsync() { // Load the words that correspond to the current input locale Cursor cursor = query(MAIN_COLUMN_LOCALE + "=?", new String[] { mLocale }); try { if (cursor.moveToFirst()) { int word1Index = cursor.getColumnIndex(MAIN_COLUMN_WORD1); int word2Index = cursor.getColumnIndex(MAIN_COLUMN_WORD2); int frequencyIndex = cursor.getColumnIndex(FREQ_COLUMN_FREQUENCY); while (!cursor.isAfterLast()) { String word1 = cursor.getString(word1Index); String word2 = cursor.getString(word2Index); int frequency = cursor.getInt(frequencyIndex); // Safeguard against adding really long words. Stack may overflow due // to recursive lookup if (word1.length() < MAX_WORD_LENGTH && word2.length() < MAX_WORD_LENGTH) { super.setBigram(word1, word2, frequency); } cursor.moveToNext(); } } } finally { cursor.close(); } } /** * Query the database */ private Cursor query(String selection, String[] selectionArgs) { SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); // main INNER JOIN frequency ON (main._id=freq.pair_id) qb.setTables(MAIN_TABLE_NAME + " INNER JOIN " + FREQ_TABLE_NAME + " ON (" + MAIN_TABLE_NAME + "." + MAIN_COLUMN_ID + "=" + FREQ_TABLE_NAME + "." + FREQ_COLUMN_PAIR_ID +")"); qb.setProjectionMap(sDictProjectionMap); // Get the database and run the query SQLiteDatabase db = sOpenHelper.getReadableDatabase(); Cursor c = qb.query(db, new String[] { MAIN_COLUMN_WORD1, MAIN_COLUMN_WORD2, FREQ_COLUMN_FREQUENCY }, selection, selectionArgs, null, null, null); return c; } /** * This class helps open, create, and upgrade the database file. */ private static class DatabaseHelper extends SQLiteOpenHelper { DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("PRAGMA foreign_keys = ON;"); db.execSQL("CREATE TABLE " + MAIN_TABLE_NAME + " (" + MAIN_COLUMN_ID + " INTEGER PRIMARY KEY," + MAIN_COLUMN_WORD1 + " TEXT," + MAIN_COLUMN_WORD2 + " TEXT," + MAIN_COLUMN_LOCALE + " TEXT" + ");"); db.execSQL("CREATE TABLE " + FREQ_TABLE_NAME + " (" + FREQ_COLUMN_ID + " INTEGER PRIMARY KEY," + FREQ_COLUMN_PAIR_ID + " INTEGER," + FREQ_COLUMN_FREQUENCY + " INTEGER," + "FOREIGN KEY(" + FREQ_COLUMN_PAIR_ID + ") REFERENCES " + MAIN_TABLE_NAME + "(" + MAIN_COLUMN_ID + ")" + " ON DELETE CASCADE" + ");"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); db.execSQL("DROP TABLE IF EXISTS " + MAIN_TABLE_NAME); db.execSQL("DROP TABLE IF EXISTS " + FREQ_TABLE_NAME); onCreate(db); } } /** * Async task to write pending words to the database so that it stays in sync with * the in-memory trie. */ private static class UpdateDbTask extends AsyncTask<Void, Void, Void> { private final HashSet<Bigram> mMap; private final DatabaseHelper mDbHelper; private final String mLocale; public UpdateDbTask(Context context, DatabaseHelper openHelper, HashSet<Bigram> pendingWrites, String locale) { mMap = pendingWrites; mLocale = locale; mDbHelper = openHelper; } /** Prune any old data if the database is getting too big. */ private void checkPruneData(SQLiteDatabase db) { db.execSQL("PRAGMA foreign_keys = ON;"); Cursor c = db.query(FREQ_TABLE_NAME, new String[] { FREQ_COLUMN_PAIR_ID }, null, null, null, null, null); try { int totalRowCount = c.getCount(); // prune out old data if we have too much data if (totalRowCount > sMaxUserBigrams) { int numDeleteRows = (totalRowCount - sMaxUserBigrams) + sDeleteUserBigrams; int pairIdColumnId = c.getColumnIndex(FREQ_COLUMN_PAIR_ID); c.moveToFirst(); int count = 0; while (count < numDeleteRows && !c.isAfterLast()) { String pairId = c.getString(pairIdColumnId); // Deleting from MAIN table will delete the frequencies // due to FOREIGN KEY .. ON DELETE CASCADE db.delete(MAIN_TABLE_NAME, MAIN_COLUMN_ID + "=?", new String[] { pairId }); c.moveToNext(); count++; } } } finally { c.close(); } } @Override protected void onPreExecute() { sUpdatingDB = true; } @Override protected Void doInBackground(Void... v) { SQLiteDatabase db = mDbHelper.getWritableDatabase(); db.execSQL("PRAGMA foreign_keys = ON;"); // Write all the entries to the db Iterator<Bigram> iterator = mMap.iterator(); while (iterator.hasNext()) { Bigram bi = iterator.next(); // find pair id Cursor c = db.query(MAIN_TABLE_NAME, new String[] { MAIN_COLUMN_ID }, MAIN_COLUMN_WORD1 + "=? AND " + MAIN_COLUMN_WORD2 + "=? AND " + MAIN_COLUMN_LOCALE + "=?", new String[] { bi.word1, bi.word2, mLocale }, null, null, null); int pairId; if (c.moveToFirst()) { // existing pair pairId = c.getInt(c.getColumnIndex(MAIN_COLUMN_ID)); db.delete(FREQ_TABLE_NAME, FREQ_COLUMN_PAIR_ID + "=?", new String[] { Integer.toString(pairId) }); } else { // new pair Long pairIdLong = db.insert(MAIN_TABLE_NAME, null, getContentValues(bi.word1, bi.word2, mLocale)); pairId = pairIdLong.intValue(); } c.close(); // insert new frequency db.insert(FREQ_TABLE_NAME, null, getFrequencyContentValues(pairId, bi.frequency)); } checkPruneData(db); sUpdatingDB = false; return null; } private ContentValues getContentValues(String word1, String word2, String locale) { ContentValues values = new ContentValues(3); values.put(MAIN_COLUMN_WORD1, word1); values.put(MAIN_COLUMN_WORD2, word2); values.put(MAIN_COLUMN_LOCALE, locale); return values; } private ContentValues getFrequencyContentValues(int pairId, int frequency) { ContentValues values = new ContentValues(2); values.put(FREQ_COLUMN_PAIR_ID, pairId); values.put(FREQ_COLUMN_FREQUENCY, frequency); return values; } } }
Java
/* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.pocketworkstation.pckeyboard; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.text.Html; import android.text.Spanned; import android.text.method.LinkMovementMethod; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import android.widget.TextView.BufferType; public class Main extends Activity { private final static String MARKET_URI = "market://search?q=pub:\"Klaus Weidner\""; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); String html = getString(R.string.main_body); html += "<p><i>Version: " + getString(R.string.auto_version) + "</i></p>"; Spanned content = Html.fromHtml(html); TextView description = (TextView) findViewById(R.id.main_description); description.setMovementMethod(LinkMovementMethod.getInstance()); description.setText(content, BufferType.SPANNABLE); final Button setup1 = (Button) findViewById(R.id.main_setup_btn_configure_imes); setup1.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { startActivityForResult(new Intent(android.provider.Settings.ACTION_INPUT_METHOD_SETTINGS), 0); } }); final Button setup2 = (Button) findViewById(R.id.main_setup_btn_set_ime); setup2.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); mgr.showInputMethodPicker(); } }); final Activity that = this; final Button setup4 = (Button) findViewById(R.id.main_setup_btn_input_lang); setup4.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { startActivityForResult(new Intent(that, InputLanguageSelection.class), 0); } }); final Button setup3 = (Button) findViewById(R.id.main_setup_btn_get_dicts); setup3.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent it = new Intent(Intent.ACTION_VIEW, Uri.parse(MARKET_URI)); try { startActivity(it); } catch (ActivityNotFoundException e) { Toast.makeText(getApplicationContext(), getResources().getString( R.string.no_market_warning), Toast.LENGTH_LONG) .show(); } } }); // PluginManager.getPluginDictionaries(getApplicationContext()); // why? } }
Java
/* * Copyright (C) 2008-2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.pocketworkstation.pckeyboard; import org.xmlpull.v1.XmlPullParserException; import android.content.Context; import android.content.res.Resources; import android.content.res.TypedArray; import android.content.res.XmlResourceParser; import android.graphics.drawable.Drawable; import android.text.TextUtils; import android.util.Log; import android.util.TypedValue; import android.util.Xml; import android.util.DisplayMetrics; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Set; import java.util.StringTokenizer; /** * Loads an XML description of a keyboard and stores the attributes of the keys. A keyboard * consists of rows of keys. * <p>The layout file for a keyboard contains XML that looks like the following snippet:</p> * <pre> * &lt;Keyboard * android:keyWidth="%10p" * android:keyHeight="50px" * android:horizontalGap="2px" * android:verticalGap="2px" &gt; * &lt;Row android:keyWidth="32px" &gt; * &lt;Key android:keyLabel="A" /&gt; * ... * &lt;/Row&gt; * ... * &lt;/Keyboard&gt; * </pre> * @attr ref android.R.styleable#Keyboard_keyWidth * @attr ref android.R.styleable#Keyboard_keyHeight * @attr ref android.R.styleable#Keyboard_horizontalGap * @attr ref android.R.styleable#Keyboard_verticalGap */ public class Keyboard { static final String TAG = "Keyboard"; public final static char DEAD_KEY_PLACEHOLDER = 0x25cc; // dotted small circle public final static String DEAD_KEY_PLACEHOLDER_STRING = Character.toString(DEAD_KEY_PLACEHOLDER); // Keyboard XML Tags private static final String TAG_KEYBOARD = "Keyboard"; private static final String TAG_ROW = "Row"; private static final String TAG_KEY = "Key"; public static final int EDGE_LEFT = 0x01; public static final int EDGE_RIGHT = 0x02; public static final int EDGE_TOP = 0x04; public static final int EDGE_BOTTOM = 0x08; public static final int KEYCODE_SHIFT = -1; public static final int KEYCODE_MODE_CHANGE = -2; public static final int KEYCODE_CANCEL = -3; public static final int KEYCODE_DONE = -4; public static final int KEYCODE_DELETE = -5; public static final int KEYCODE_ALT_SYM = -6; // Backwards compatible setting to avoid having to change all the kbd_qwerty files public static final int DEFAULT_LAYOUT_ROWS = 4; public static final int DEFAULT_LAYOUT_COLUMNS = 10; // Flag values for popup key contents. Keep in sync with strings.xml values. public static final int POPUP_ADD_SHIFT = 1; public static final int POPUP_ADD_CASE = 2; public static final int POPUP_ADD_SELF = 4; public static final int POPUP_DISABLE = 256; public static final int POPUP_AUTOREPEAT = 512; /** Horizontal gap default for all rows */ private float mDefaultHorizontalGap; private float mHorizontalPad; private float mVerticalPad; /** Default key width */ private float mDefaultWidth; /** Default key height */ private int mDefaultHeight; /** Default gap between rows */ private int mDefaultVerticalGap; public static final int SHIFT_OFF = 0; public static final int SHIFT_ON = 1; public static final int SHIFT_LOCKED = 2; public static final int SHIFT_CAPS = 3; public static final int SHIFT_CAPS_LOCKED = 4; /** Is the keyboard in the shifted state */ private int mShiftState = SHIFT_OFF; /** Key instance for the shift key, if present */ private Key mShiftKey; private Key mAltKey; private Key mCtrlKey; /** Key index for the shift key, if present */ private int mShiftKeyIndex = -1; /** Total height of the keyboard, including the padding and keys */ private int mTotalHeight; /** * Total width of the keyboard, including left side gaps and keys, but not any gaps on the * right side. */ private int mTotalWidth; /** List of keys in this keyboard */ private List<Key> mKeys; /** List of modifier keys such as Shift & Alt, if any */ private List<Key> mModifierKeys; /** Width of the screen available to fit the keyboard */ private int mDisplayWidth; /** Height of the screen and keyboard */ private int mDisplayHeight; private int mKeyboardHeight; /** Keyboard mode, or zero, if none. */ private int mKeyboardMode; private boolean mUseExtension; public int mLayoutRows; public int mLayoutColumns; public int mRowCount = 1; public int mExtensionRowCount = 0; // Variables for pre-computing nearest keys. private int mCellWidth; private int mCellHeight; private int[][] mGridNeighbors; private int mProximityThreshold; /** Number of key widths from current touch point to search for nearest keys. */ private static float SEARCH_DISTANCE = 1.8f; /** * Container for keys in the keyboard. All keys in a row are at the same Y-coordinate. * Some of the key size defaults can be overridden per row from what the {@link Keyboard} * defines. * @attr ref android.R.styleable#Keyboard_keyWidth * @attr ref android.R.styleable#Keyboard_keyHeight * @attr ref android.R.styleable#Keyboard_horizontalGap * @attr ref android.R.styleable#Keyboard_verticalGap * @attr ref android.R.styleable#Keyboard_Row_keyboardMode */ public static class Row { /** Default width of a key in this row. */ public float defaultWidth; /** Default height of a key in this row. */ public int defaultHeight; /** Default horizontal gap between keys in this row. */ public float defaultHorizontalGap; /** Vertical gap following this row. */ public int verticalGap; /** The keyboard mode for this row */ public int mode; public boolean extension; private Keyboard parent; public Row(Keyboard parent) { this.parent = parent; } public Row(Resources res, Keyboard parent, XmlResourceParser parser) { this.parent = parent; TypedArray a = res.obtainAttributes(Xml.asAttributeSet(parser), R.styleable.Keyboard); defaultWidth = getDimensionOrFraction(a, R.styleable.Keyboard_keyWidth, parent.mDisplayWidth, parent.mDefaultWidth); defaultHeight = Math.round(getDimensionOrFraction(a, R.styleable.Keyboard_keyHeight, parent.mDisplayHeight, parent.mDefaultHeight)); defaultHorizontalGap = getDimensionOrFraction(a, R.styleable.Keyboard_horizontalGap, parent.mDisplayWidth, parent.mDefaultHorizontalGap); verticalGap = Math.round(getDimensionOrFraction(a, R.styleable.Keyboard_verticalGap, parent.mDisplayHeight, parent.mDefaultVerticalGap)); a.recycle(); a = res.obtainAttributes(Xml.asAttributeSet(parser), R.styleable.Keyboard_Row); mode = a.getResourceId(R.styleable.Keyboard_Row_keyboardMode, 0); extension = a.getBoolean(R.styleable.Keyboard_Row_extension, false); if (parent.mLayoutRows >= 5) { boolean isTop = (extension || parent.mRowCount - parent.mExtensionRowCount <= 0); float topScale = LatinIME.sKeyboardSettings.topRowScale; float scale = isTop ? topScale : 1.0f + (1.0f - topScale) / (parent.mLayoutRows - 1); defaultHeight = Math.round(defaultHeight * scale); } a.recycle(); } } /** * Class for describing the position and characteristics of a single key in the keyboard. * * @attr ref android.R.styleable#Keyboard_keyWidth * @attr ref android.R.styleable#Keyboard_keyHeight * @attr ref android.R.styleable#Keyboard_horizontalGap * @attr ref android.R.styleable#Keyboard_Key_codes * @attr ref android.R.styleable#Keyboard_Key_keyIcon * @attr ref android.R.styleable#Keyboard_Key_keyLabel * @attr ref android.R.styleable#Keyboard_Key_iconPreview * @attr ref android.R.styleable#Keyboard_Key_isSticky * @attr ref android.R.styleable#Keyboard_Key_isRepeatable * @attr ref android.R.styleable#Keyboard_Key_isModifier * @attr ref android.R.styleable#Keyboard_Key_popupKeyboard * @attr ref android.R.styleable#Keyboard_Key_popupCharacters * @attr ref android.R.styleable#Keyboard_Key_keyOutputText */ public static class Key { /** * All the key codes (unicode or custom code) that this key could generate, zero'th * being the most important. */ public int[] codes; /** Label to display */ public CharSequence label; public CharSequence shiftLabel; public CharSequence capsLabel; /** Icon to display instead of a label. Icon takes precedence over a label */ public Drawable icon; /** Preview version of the icon, for the preview popup */ public Drawable iconPreview; /** Width of the key, not including the gap */ public int width; /** Height of the key, not including the gap */ private float realWidth; public int height; /** The horizontal gap before this key */ public int gap; private float realGap; /** Whether this key is sticky, i.e., a toggle key */ public boolean sticky; /** X coordinate of the key in the keyboard layout */ public int x; private float realX; /** Y coordinate of the key in the keyboard layout */ public int y; /** The current pressed state of this key */ public boolean pressed; /** If this is a sticky key, is it on or locked? */ public boolean on; public boolean locked; /** Text to output when pressed. This can be multiple characters, like ".com" */ public CharSequence text; /** Popup characters */ public CharSequence popupCharacters; public boolean popupReversed; public boolean isCursor; public String hint; // Set by LatinKeyboardBaseView public String altHint; // Set by LatinKeyboardBaseView /** * Flags that specify the anchoring to edges of the keyboard for detecting touch events * that are just out of the boundary of the key. This is a bit mask of * {@link Keyboard#EDGE_LEFT}, {@link Keyboard#EDGE_RIGHT}, {@link Keyboard#EDGE_TOP} and * {@link Keyboard#EDGE_BOTTOM}. */ public int edgeFlags; /** Whether this is a modifier key, such as Shift or Alt */ public boolean modifier; /** The keyboard that this key belongs to */ private Keyboard keyboard; /** * If this key pops up a mini keyboard, this is the resource id for the XML layout for that * keyboard. */ public int popupResId; /** Whether this key repeats itself when held down */ public boolean repeatable; /** Is the shifted character the uppercase equivalent of the unshifted one? */ private boolean isSimpleUppercase; /** Is the shifted character a distinct uppercase char that's different from the shifted char? */ private boolean isDistinctUppercase; private final static int[] KEY_STATE_NORMAL_ON = { android.R.attr.state_checkable, android.R.attr.state_checked }; private final static int[] KEY_STATE_PRESSED_ON = { android.R.attr.state_pressed, android.R.attr.state_checkable, android.R.attr.state_checked }; private final static int[] KEY_STATE_NORMAL_LOCK = { android.R.attr.state_active, android.R.attr.state_checkable, android.R.attr.state_checked }; private final static int[] KEY_STATE_PRESSED_LOCK = { android.R.attr.state_active, android.R.attr.state_pressed, android.R.attr.state_checkable, android.R.attr.state_checked }; private final static int[] KEY_STATE_NORMAL_OFF = { android.R.attr.state_checkable }; private final static int[] KEY_STATE_PRESSED_OFF = { android.R.attr.state_pressed, android.R.attr.state_checkable }; private final static int[] KEY_STATE_NORMAL = { }; private final static int[] KEY_STATE_PRESSED = { android.R.attr.state_pressed }; /** Create an empty key with no attributes. */ public Key(Row parent) { keyboard = parent.parent; height = parent.defaultHeight; width = Math.round(parent.defaultWidth); realWidth = parent.defaultWidth; gap = Math.round(parent.defaultHorizontalGap); realGap = parent.defaultHorizontalGap; } /** Create a key with the given top-left coordinate and extract its attributes from * the XML parser. * @param res resources associated with the caller's context * @param parent the row that this key belongs to. The row must already be attached to * a {@link Keyboard}. * @param x the x coordinate of the top-left * @param y the y coordinate of the top-left * @param parser the XML parser containing the attributes for this key */ public Key(Resources res, Row parent, int x, int y, XmlResourceParser parser) { this(parent); this.x = x; this.y = y; TypedArray a = res.obtainAttributes(Xml.asAttributeSet(parser), R.styleable.Keyboard); realWidth = getDimensionOrFraction(a, R.styleable.Keyboard_keyWidth, keyboard.mDisplayWidth, parent.defaultWidth); float realHeight = getDimensionOrFraction(a, R.styleable.Keyboard_keyHeight, keyboard.mDisplayHeight, parent.defaultHeight); realHeight -= parent.parent.mVerticalPad; height = Math.round(realHeight); this.y += parent.parent.mVerticalPad / 2; realGap = getDimensionOrFraction(a, R.styleable.Keyboard_horizontalGap, keyboard.mDisplayWidth, parent.defaultHorizontalGap); realGap += parent.parent.mHorizontalPad; realWidth -= parent.parent.mHorizontalPad; width = Math.round(realWidth); gap = Math.round(realGap); a.recycle(); a = res.obtainAttributes(Xml.asAttributeSet(parser), R.styleable.Keyboard_Key); this.realX = this.x + realGap - parent.parent.mHorizontalPad / 2; this.x = Math.round(this.realX); TypedValue codesValue = new TypedValue(); a.getValue(R.styleable.Keyboard_Key_codes, codesValue); if (codesValue.type == TypedValue.TYPE_INT_DEC || codesValue.type == TypedValue.TYPE_INT_HEX) { codes = new int[] { codesValue.data }; } else if (codesValue.type == TypedValue.TYPE_STRING) { codes = parseCSV(codesValue.string.toString()); } iconPreview = a.getDrawable(R.styleable.Keyboard_Key_iconPreview); if (iconPreview != null) { iconPreview.setBounds(0, 0, iconPreview.getIntrinsicWidth(), iconPreview.getIntrinsicHeight()); } popupCharacters = a.getText( R.styleable.Keyboard_Key_popupCharacters); popupResId = a.getResourceId( R.styleable.Keyboard_Key_popupKeyboard, 0); repeatable = a.getBoolean( R.styleable.Keyboard_Key_isRepeatable, false); modifier = a.getBoolean( R.styleable.Keyboard_Key_isModifier, false); sticky = a.getBoolean( R.styleable.Keyboard_Key_isSticky, false); isCursor = a.getBoolean( R.styleable.Keyboard_Key_isCursor, false); icon = a.getDrawable( R.styleable.Keyboard_Key_keyIcon); if (icon != null) { icon.setBounds(0, 0, icon.getIntrinsicWidth(), icon.getIntrinsicHeight()); } label = a.getText(R.styleable.Keyboard_Key_keyLabel); shiftLabel = a.getText(R.styleable.Keyboard_Key_shiftLabel); if (shiftLabel != null && shiftLabel.length() == 0) shiftLabel = null; capsLabel = a.getText(R.styleable.Keyboard_Key_capsLabel); if (capsLabel != null && capsLabel.length() == 0) capsLabel = null; text = a.getText(R.styleable.Keyboard_Key_keyOutputText); if (codes == null && !TextUtils.isEmpty(label)) { codes = getFromString(label); if (codes != null && codes.length == 1) { final Locale locale = LatinIME.sKeyboardSettings.inputLocale; String upperLabel = label.toString().toUpperCase(locale); if (shiftLabel == null) { // No shiftLabel supplied, auto-set to uppercase if possible. if (!upperLabel.equals(label.toString()) && upperLabel.length() == 1) { shiftLabel = upperLabel; isSimpleUppercase = true; } } else { // Both label and shiftLabel supplied. Check if // the shiftLabel is the uppercased normal label. // If not, treat it as a distinct uppercase variant. if (capsLabel != null) { isDistinctUppercase = true; } else if (upperLabel.equals(shiftLabel.toString())) { isSimpleUppercase = true; } else if (upperLabel.length() == 1) { capsLabel = upperLabel; isDistinctUppercase = true; } } } if ((LatinIME.sKeyboardSettings.popupKeyboardFlags & POPUP_DISABLE) != 0) { popupCharacters = null; popupResId = 0; } if ((LatinIME.sKeyboardSettings.popupKeyboardFlags & POPUP_AUTOREPEAT) != 0) { // Assume POPUP_DISABLED is set too, otherwise things may get weird. repeatable = true; } } //Log.i(TAG, "added key definition: " + this); a.recycle(); } public boolean isDistinctCaps() { return isDistinctUppercase && keyboard.isShiftCaps(); } public boolean isShifted() { boolean shifted = keyboard.isShifted(isSimpleUppercase); //Log.i(TAG, "FIXME isShifted=" + shifted + " for " + this); return shifted; } public int getPrimaryCode(boolean isShiftCaps, boolean isShifted) { if (isDistinctUppercase && isShiftCaps) { return capsLabel.charAt(0); } //Log.i(TAG, "getPrimaryCode(), shifted=" + shifted); if (isShifted && shiftLabel != null) { if (shiftLabel.charAt(0) == DEAD_KEY_PLACEHOLDER && shiftLabel.length() >= 2) { return shiftLabel.charAt(1); } else { return shiftLabel.charAt(0); } } else { return codes[0]; } } public int getPrimaryCode() { return getPrimaryCode(keyboard.isShiftCaps(), keyboard.isShifted(isSimpleUppercase)); } public boolean isDeadKey() { if (codes == null || codes.length < 1) return false; return Character.getType(codes[0]) == Character.NON_SPACING_MARK; } public int[] getFromString(CharSequence str) { if (str.length() > 1) { if (str.charAt(0) == DEAD_KEY_PLACEHOLDER && str.length() >= 2) { return new int[] { str.charAt(1) }; // FIXME: >1 length? } else { text = str; // TODO: add space? return new int[] { 0 }; } } else { char c = str.charAt(0); return new int[] { c }; } } public String getCaseLabel() { if (isDistinctUppercase && keyboard.isShiftCaps()) { return capsLabel.toString(); } boolean isShifted = keyboard.isShifted(isSimpleUppercase); if (isShifted && shiftLabel != null) { return shiftLabel.toString(); } else { return label != null ? label.toString() : null; } } private String getPopupKeyboardContent(boolean isShiftCaps, boolean isShifted, boolean addExtra) { int mainChar = getPrimaryCode(false, false); int shiftChar = getPrimaryCode(false, true); int capsChar = getPrimaryCode(true, true); // Remove duplicates if (shiftChar == mainChar) shiftChar = 0; if (capsChar == shiftChar || capsChar == mainChar) capsChar = 0; int popupLen = (popupCharacters == null) ? 0 : popupCharacters.length(); StringBuilder popup = new StringBuilder(popupLen); for (int i = 0; i < popupLen; ++i) { char c = popupCharacters.charAt(i); if (isShifted || isShiftCaps) { String upper = Character.toString(c).toUpperCase(LatinIME.sKeyboardSettings.inputLocale); if (upper.length() == 1) c = upper.charAt(0); } if (c == mainChar || c == shiftChar || c == capsChar) continue; popup.append(c); } if (addExtra) { StringBuilder extra = new StringBuilder(3 + popup.length()); int flags = LatinIME.sKeyboardSettings.popupKeyboardFlags; if ((flags & POPUP_ADD_SELF) != 0) { // if shifted, add unshifted key to extra, and vice versa if (isDistinctUppercase && isShiftCaps) { if (capsChar > 0) { extra.append((char) capsChar); capsChar = 0; } } else if (isShifted) { if (shiftChar > 0) { extra.append((char) shiftChar); shiftChar = 0; } } else { if (mainChar > 0) { extra.append((char) mainChar); mainChar = 0; } } } if ((flags & POPUP_ADD_CASE) != 0) { // if shifted, add unshifted key to popup, and vice versa if (isDistinctUppercase && isShiftCaps) { if (mainChar > 0) { extra.append((char) mainChar); mainChar = 0; } if (shiftChar > 0) { extra.append((char) shiftChar); shiftChar = 0; } } else if (isShifted) { if (mainChar > 0) { extra.append((char) mainChar); mainChar = 0; } if (capsChar > 0) { extra.append((char) capsChar); capsChar = 0; } } else { if (shiftChar > 0) { extra.append((char) shiftChar); shiftChar = 0; } if (capsChar > 0) { extra.append((char) capsChar); capsChar = 0; } } } if (!isSimpleUppercase && (flags & POPUP_ADD_SHIFT) != 0) { // if shifted, add unshifted key to popup, and vice versa if (isShifted) { if (mainChar > 0) { extra.append((char) mainChar); mainChar = 0; } } else { if (shiftChar > 0) { extra.append((char) shiftChar); shiftChar = 0; } } } extra.append(popup); return extra.toString(); } return popup.toString(); } public Keyboard getPopupKeyboard(Context context, int padding) { if (popupCharacters == null) { if (popupResId != 0) { return new Keyboard(context, keyboard.mDefaultHeight, popupResId); } else { if (modifier) return null; // Space, Return etc. } } if ((LatinIME.sKeyboardSettings.popupKeyboardFlags & POPUP_DISABLE) != 0) return null; String popup = getPopupKeyboardContent(keyboard.isShiftCaps(), keyboard.isShifted(isSimpleUppercase), true); //Log.i(TAG, "getPopupKeyboard: popup='" + popup + "' for " + this); if (popup.length() > 0) { int resId = popupResId; if (resId == 0) resId = R.xml.kbd_popup_template; return new Keyboard(context, keyboard.mDefaultHeight, resId, popup, popupReversed, -1, padding); } else { return null; } } public String getHintLabel(boolean wantAscii, boolean wantAll) { if (hint == null) { hint = ""; if (shiftLabel != null && !isSimpleUppercase) { char c = shiftLabel.charAt(0); if (wantAll || wantAscii && is7BitAscii(c)) { hint = Character.toString(c); } } } return hint; } public String getAltHintLabel(boolean wantAscii, boolean wantAll) { if (altHint == null) { altHint = ""; String popup = getPopupKeyboardContent(false, false, false); if (popup.length() > 0) { char c = popup.charAt(0); if (wantAll || wantAscii && is7BitAscii(c)) { altHint = Character.toString(c); } } } return altHint; } private static boolean is7BitAscii(char c) { if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')) return false; return c >= 32 && c < 127; } /** * Informs the key that it has been pressed, in case it needs to change its appearance or * state. * @see #onReleased(boolean) */ public void onPressed() { pressed = !pressed; } /** * Changes the pressed state of the key. Sticky key indicators are handled explicitly elsewhere. * @param inside whether the finger was released inside the key * @see #onPressed() */ public void onReleased(boolean inside) { pressed = !pressed; } int[] parseCSV(String value) { int count = 0; int lastIndex = 0; if (value.length() > 0) { count++; while ((lastIndex = value.indexOf(",", lastIndex + 1)) > 0) { count++; } } int[] values = new int[count]; count = 0; StringTokenizer st = new StringTokenizer(value, ","); while (st.hasMoreTokens()) { try { values[count++] = Integer.parseInt(st.nextToken()); } catch (NumberFormatException nfe) { Log.e(TAG, "Error parsing keycodes " + value); } } return values; } /** * Detects if a point falls inside this key. * @param x the x-coordinate of the point * @param y the y-coordinate of the point * @return whether or not the point falls inside the key. If the key is attached to an edge, * it will assume that all points between the key and the edge are considered to be inside * the key. */ public boolean isInside(int x, int y) { boolean leftEdge = (edgeFlags & EDGE_LEFT) > 0; boolean rightEdge = (edgeFlags & EDGE_RIGHT) > 0; boolean topEdge = (edgeFlags & EDGE_TOP) > 0; boolean bottomEdge = (edgeFlags & EDGE_BOTTOM) > 0; if ((x >= this.x || (leftEdge && x <= this.x + this.width)) && (x < this.x + this.width || (rightEdge && x >= this.x)) && (y >= this.y || (topEdge && y <= this.y + this.height)) && (y < this.y + this.height || (bottomEdge && y >= this.y))) { return true; } else { return false; } } /** * Returns the square of the distance between the center of the key and the given point. * @param x the x-coordinate of the point * @param y the y-coordinate of the point * @return the square of the distance of the point from the center of the key */ public int squaredDistanceFrom(int x, int y) { int xDist = this.x + width / 2 - x; int yDist = this.y + height / 2 - y; return xDist * xDist + yDist * yDist; } /** * Returns the drawable state for the key, based on the current state and type of the key. * @return the drawable state of the key. * @see android.graphics.drawable.StateListDrawable#setState(int[]) */ public int[] getCurrentDrawableState() { int[] states = KEY_STATE_NORMAL; if (locked) { if (pressed) { states = KEY_STATE_PRESSED_LOCK; } else { states = KEY_STATE_NORMAL_LOCK; } } else if (on) { if (pressed) { states = KEY_STATE_PRESSED_ON; } else { states = KEY_STATE_NORMAL_ON; } } else { if (sticky) { if (pressed) { states = KEY_STATE_PRESSED_OFF; } else { states = KEY_STATE_NORMAL_OFF; } } else { if (pressed) { states = KEY_STATE_PRESSED; } } } return states; } public String toString() { int code = (codes != null && codes.length > 0) ? codes[0] : 0; String edges = ( ((edgeFlags & Keyboard.EDGE_LEFT) != 0 ? "L" : "-") + ((edgeFlags & Keyboard.EDGE_RIGHT) != 0 ? "R" : "-") + ((edgeFlags & Keyboard.EDGE_TOP) != 0 ? "T" : "-") + ((edgeFlags & Keyboard.EDGE_BOTTOM) != 0 ? "B" : "-")); return "KeyDebugFIXME(label=" + label + (shiftLabel != null ? " shift=" + shiftLabel : "") + (capsLabel != null ? " caps=" + capsLabel : "") + (text != null ? " text=" + text : "" ) + " code=" + code + (code <= 0 || Character.isWhitespace(code) ? "" : ":'" + (char)code + "'" ) + " x=" + x + ".." + (x+width) + " y=" + y + ".." + (y+height) + " edgeFlags=" + edges + (popupCharacters != null ? " pop=" + popupCharacters : "" ) + " res=" + popupResId + ")"; } } /** * Creates a keyboard from the given xml key layout file. * @param context the application or service context * @param xmlLayoutResId the resource file that contains the keyboard layout and keys. */ public Keyboard(Context context, int defaultHeight, int xmlLayoutResId) { this(context, defaultHeight, xmlLayoutResId, 0); } public Keyboard(Context context, int defaultHeight, int xmlLayoutResId, int modeId) { this(context, defaultHeight, xmlLayoutResId, modeId, 0); } /** * Creates a keyboard from the given xml key layout file. Weeds out rows * that have a keyboard mode defined but don't match the specified mode. * @param context the application or service context * @param xmlLayoutResId the resource file that contains the keyboard layout and keys. * @param modeId keyboard mode identifier * @param rowHeightPercent height of each row as percentage of screen height */ public Keyboard(Context context, int defaultHeight, int xmlLayoutResId, int modeId, float kbHeightPercent) { DisplayMetrics dm = context.getResources().getDisplayMetrics(); mDisplayWidth = dm.widthPixels; mDisplayHeight = dm.heightPixels; //Log.v(TAG, "keyboard's display metrics:" + dm); mDefaultHorizontalGap = 0; mDefaultWidth = mDisplayWidth / 10; mDefaultVerticalGap = 0; mDefaultHeight = defaultHeight; // may be zero, to be adjusted below mKeyboardHeight = Math.round(mDisplayHeight * kbHeightPercent / 100); //Log.i("PCKeyboard", "mDefaultHeight=" + mDefaultHeight + "(arg=" + defaultHeight + ")" + " kbHeight=" + mKeyboardHeight + " displayHeight="+mDisplayHeight+")"); mKeys = new ArrayList<Key>(); mModifierKeys = new ArrayList<Key>(); mKeyboardMode = modeId; mUseExtension = LatinIME.sKeyboardSettings.useExtension; loadKeyboard(context, context.getResources().getXml(xmlLayoutResId)); setEdgeFlags(); fixAltChars(LatinIME.sKeyboardSettings.inputLocale); } /** * <p>Creates a blank keyboard from the given resource file and populates it with the specified * characters in left-to-right, top-to-bottom fashion, using the specified number of columns. * </p> * <p>If the specified number of columns is -1, then the keyboard will fit as many keys as * possible in each row.</p> * @param context the application or service context * @param layoutTemplateResId the layout template file, containing no keys. * @param characters the list of characters to display on the keyboard. One key will be created * for each character. * @param columns the number of columns of keys to display. If this number is greater than the * number of keys that can fit in a row, it will be ignored. If this number is -1, the * keyboard will fit as many keys as possible in each row. */ private Keyboard(Context context, int defaultHeight, int layoutTemplateResId, CharSequence characters, boolean reversed, int columns, int horizontalPadding) { this(context, defaultHeight, layoutTemplateResId); int x = 0; int y = 0; int column = 0; mTotalWidth = 0; Row row = new Row(this); row.defaultHeight = mDefaultHeight; row.defaultWidth = mDefaultWidth; row.defaultHorizontalGap = mDefaultHorizontalGap; row.verticalGap = mDefaultVerticalGap; final int maxColumns = columns == -1 ? Integer.MAX_VALUE : columns; mLayoutRows = 1; int start = reversed ? characters.length()-1 : 0; int end = reversed ? -1 : characters.length(); int step = reversed ? -1 : 1; for (int i = start; i != end; i+=step) { char c = characters.charAt(i); if (column >= maxColumns || x + mDefaultWidth + horizontalPadding > mDisplayWidth) { x = 0; y += mDefaultVerticalGap + mDefaultHeight; column = 0; ++mLayoutRows; } final Key key = new Key(row); key.x = x; key.realX = x; key.y = y; key.label = String.valueOf(c); key.codes = key.getFromString(key.label); column++; x += key.width + key.gap; mKeys.add(key); if (x > mTotalWidth) { mTotalWidth = x; } } mTotalHeight = y + mDefaultHeight; mLayoutColumns = columns == -1 ? column : maxColumns; setEdgeFlags(); } private void setEdgeFlags() { if (mRowCount == 0) mRowCount = 1; // Assume one row if not set int row = 0; Key prevKey = null; int rowFlags = 0; for (Key key : mKeys) { int keyFlags = 0; if (prevKey == null || key.x <= prevKey.x) { // Start new row. if (prevKey != null) { // Add "right edge" to rightmost key of previous row. // Need to do the last key separately below. prevKey.edgeFlags |= Keyboard.EDGE_RIGHT; } // Set the row flags for the current row. rowFlags = 0; if (row == 0) rowFlags |= Keyboard.EDGE_TOP; if (row == mRowCount - 1) rowFlags |= Keyboard.EDGE_BOTTOM; ++row; // Mark current key as "left edge" keyFlags |= Keyboard.EDGE_LEFT; } key.edgeFlags = rowFlags | keyFlags; prevKey = key; } // Fix up the last key if (prevKey != null) prevKey.edgeFlags |= Keyboard.EDGE_RIGHT; // Log.i(TAG, "setEdgeFlags() done:"); // for (Key key : mKeys) { // Log.i(TAG, "key=" + key); // } } private void fixAltChars(Locale locale) { if (locale == null) locale = Locale.getDefault(); Set<Character> mainKeys = new HashSet<Character>(); for (Key key : mKeys) { // Remember characters on the main keyboard so that they can be removed from popups. // This makes it easy to share popup char maps between the normal and shifted // keyboards. if (key.label != null && !key.modifier && key.label.length() == 1) { char c = key.label.charAt(0); mainKeys.add(c); } } for (Key key : mKeys) { if (key.popupCharacters == null) continue; int popupLen = key.popupCharacters.length(); if (popupLen == 0) { continue; } if (key.x >= mTotalWidth / 2) { key.popupReversed = true; } // Uppercase the alt chars if the main key is uppercase boolean needUpcase = key.label != null && key.label.length() == 1 && Character.isUpperCase(key.label.charAt(0)); if (needUpcase) { key.popupCharacters = key.popupCharacters.toString().toUpperCase(); popupLen = key.popupCharacters.length(); } StringBuilder newPopup = new StringBuilder(popupLen); for (int i = 0; i < popupLen; ++i) { char c = key.popupCharacters.charAt(i); if (Character.isDigit(c) && mainKeys.contains(c)) continue; // already present elsewhere // Skip extra digit alt keys on 5-row keyboards if ((key.edgeFlags & EDGE_TOP) == 0 && Character.isDigit(c)) continue; newPopup.append(c); } //Log.i("PCKeyboard", "popup for " + key.label + " '" + key.popupCharacters + "' => '"+ newPopup + "' length " + newPopup.length()); key.popupCharacters = newPopup.toString(); } } public List<Key> getKeys() { return mKeys; } public List<Key> getModifierKeys() { return mModifierKeys; } protected int getHorizontalGap() { return Math.round(mDefaultHorizontalGap); } protected void setHorizontalGap(int gap) { mDefaultHorizontalGap = gap; } protected int getVerticalGap() { return mDefaultVerticalGap; } protected void setVerticalGap(int gap) { mDefaultVerticalGap = gap; } protected int getKeyHeight() { return mDefaultHeight; } protected void setKeyHeight(int height) { mDefaultHeight = height; } protected int getKeyWidth() { return Math.round(mDefaultWidth); } protected void setKeyWidth(int width) { mDefaultWidth = width; } /** * Returns the total height of the keyboard * @return the total height of the keyboard */ public int getHeight() { return mTotalHeight; } public int getScreenHeight() { return mDisplayHeight; } public int getMinWidth() { return mTotalWidth; } public boolean setShiftState(int shiftState, boolean updateKey) { //Log.i(TAG, "setShiftState " + mShiftState + " -> " + shiftState); if (updateKey && mShiftKey != null) { mShiftKey.on = (shiftState != SHIFT_OFF); } if (mShiftState != shiftState) { mShiftState = shiftState; return true; } return false; } public boolean setShiftState(int shiftState) { return setShiftState(shiftState, true); } public Key setCtrlIndicator(boolean active) { //Log.i(TAG, "setCtrlIndicator " + active + " ctrlKey=" + mCtrlKey); if (mCtrlKey != null) mCtrlKey.on = active; return mCtrlKey; } public Key setAltIndicator(boolean active) { if (mAltKey != null) mAltKey.on = active; return mAltKey; } public boolean isShiftCaps() { return mShiftState == SHIFT_CAPS || mShiftState == SHIFT_CAPS_LOCKED; } public boolean isShifted(boolean applyCaps) { if (applyCaps) { return mShiftState != SHIFT_OFF; } else { return mShiftState == SHIFT_ON || mShiftState == SHIFT_LOCKED; } } public int getShiftState() { return mShiftState; } public int getShiftKeyIndex() { return mShiftKeyIndex; } private void computeNearestNeighbors() { // Round-up so we don't have any pixels outside the grid mCellWidth = (getMinWidth() + mLayoutColumns - 1) / mLayoutColumns; mCellHeight = (getHeight() + mLayoutRows - 1) / mLayoutRows; mGridNeighbors = new int[mLayoutColumns * mLayoutRows][]; int[] indices = new int[mKeys.size()]; final int gridWidth = mLayoutColumns * mCellWidth; final int gridHeight = mLayoutRows * mCellHeight; for (int x = 0; x < gridWidth; x += mCellWidth) { for (int y = 0; y < gridHeight; y += mCellHeight) { int count = 0; for (int i = 0; i < mKeys.size(); i++) { final Key key = mKeys.get(i); boolean isSpace = key.codes != null && key.codes.length > 0 && key.codes[0] == LatinIME.ASCII_SPACE; if (key.squaredDistanceFrom(x, y) < mProximityThreshold || key.squaredDistanceFrom(x + mCellWidth - 1, y) < mProximityThreshold || key.squaredDistanceFrom(x + mCellWidth - 1, y + mCellHeight - 1) < mProximityThreshold || key.squaredDistanceFrom(x, y + mCellHeight - 1) < mProximityThreshold || isSpace && !( x + mCellWidth - 1 < key.x || x > key.x + key.width || y + mCellHeight - 1 < key.y || y > key.y + key.height)) { //if (isSpace) Log.i(TAG, "space at grid" + x + "," + y); indices[count++] = i; } } int [] cell = new int[count]; System.arraycopy(indices, 0, cell, 0, count); mGridNeighbors[(y / mCellHeight) * mLayoutColumns + (x / mCellWidth)] = cell; } } } /** * Returns the indices of the keys that are closest to the given point. * @param x the x-coordinate of the point * @param y the y-coordinate of the point * @return the array of integer indices for the nearest keys to the given point. If the given * point is out of range, then an array of size zero is returned. */ public int[] getNearestKeys(int x, int y) { if (mGridNeighbors == null) computeNearestNeighbors(); if (x >= 0 && x < getMinWidth() && y >= 0 && y < getHeight()) { int index = (y / mCellHeight) * mLayoutColumns + (x / mCellWidth); if (index < mLayoutRows * mLayoutColumns) { return mGridNeighbors[index]; } } return new int[0]; } protected Row createRowFromXml(Resources res, XmlResourceParser parser) { return new Row(res, this, parser); } protected Key createKeyFromXml(Resources res, Row parent, int x, int y, XmlResourceParser parser) { return new Key(res, parent, x, y, parser); } private void loadKeyboard(Context context, XmlResourceParser parser) { boolean inKey = false; boolean inRow = false; float x = 0; int y = 0; Key key = null; Row currentRow = null; Resources res = context.getResources(); boolean skipRow = false; mRowCount = 0; try { int event; Key prevKey = null; while ((event = parser.next()) != XmlResourceParser.END_DOCUMENT) { if (event == XmlResourceParser.START_TAG) { String tag = parser.getName(); if (TAG_ROW.equals(tag)) { inRow = true; x = 0; currentRow = createRowFromXml(res, parser); skipRow = currentRow.mode != 0 && currentRow.mode != mKeyboardMode; if (currentRow.extension) { if (mUseExtension) { ++mExtensionRowCount; } else { skipRow = true; } } if (skipRow) { skipToEndOfRow(parser); inRow = false; } } else if (TAG_KEY.equals(tag)) { inKey = true; key = createKeyFromXml(res, currentRow, Math.round(x), y, parser); key.realX = x; if (key.codes == null) { // skip this key, adding its width to the previous one if (prevKey != null) { prevKey.width += key.width; } } else { mKeys.add(key); prevKey = key; if (key.codes[0] == KEYCODE_SHIFT) { if (mShiftKeyIndex == -1) { mShiftKey = key; mShiftKeyIndex = mKeys.size()-1; } mModifierKeys.add(key); } else if (key.codes[0] == KEYCODE_ALT_SYM) { mModifierKeys.add(key); } else if (key.codes[0] == LatinKeyboardView.KEYCODE_CTRL_LEFT) { mCtrlKey = key; } else if (key.codes[0] == LatinKeyboardView.KEYCODE_ALT_LEFT) { mAltKey = key; } } } else if (TAG_KEYBOARD.equals(tag)) { parseKeyboardAttributes(res, parser); } } else if (event == XmlResourceParser.END_TAG) { if (inKey) { inKey = false; x += key.realGap + key.realWidth; if (x > mTotalWidth) { mTotalWidth = Math.round(x); } } else if (inRow) { inRow = false; y += currentRow.verticalGap; y += currentRow.defaultHeight; mRowCount++; } else { // TODO: error or extend? } } } } catch (Exception e) { Log.e(TAG, "Parse error:" + e); e.printStackTrace(); } mTotalHeight = y - mDefaultVerticalGap; } public void setKeyboardWidth(int newWidth) { if (newWidth <= 0) return; // view not initialized? if (mTotalWidth <= newWidth) return; // it already fits float scale = (float) newWidth / mDisplayWidth; //Log.i("PCKeyboard", "Rescaling keyboard: " + mTotalWidth + " => " + newWidth); for (Key key : mKeys) { key.x = Math.round(key.realX * scale); } mTotalWidth = newWidth; } private void skipToEndOfRow(XmlResourceParser parser) throws XmlPullParserException, IOException { int event; while ((event = parser.next()) != XmlResourceParser.END_DOCUMENT) { if (event == XmlResourceParser.END_TAG && parser.getName().equals(TAG_ROW)) { break; } } } private void parseKeyboardAttributes(Resources res, XmlResourceParser parser) { TypedArray a = res.obtainAttributes(Xml.asAttributeSet(parser), R.styleable.Keyboard); mDefaultWidth = getDimensionOrFraction(a, R.styleable.Keyboard_keyWidth, mDisplayWidth, mDisplayWidth / 10); mDefaultHeight = Math.round(getDimensionOrFraction(a, R.styleable.Keyboard_keyHeight, mDisplayHeight, mDefaultHeight)); mDefaultHorizontalGap = getDimensionOrFraction(a, R.styleable.Keyboard_horizontalGap, mDisplayWidth, 0); mDefaultVerticalGap = Math.round(getDimensionOrFraction(a, R.styleable.Keyboard_verticalGap, mDisplayHeight, 0)); mHorizontalPad = getDimensionOrFraction(a, R.styleable.Keyboard_horizontalPad, mDisplayWidth, res.getDimension(R.dimen.key_horizontal_pad)); mVerticalPad = getDimensionOrFraction(a, R.styleable.Keyboard_verticalPad, mDisplayHeight, res.getDimension(R.dimen.key_vertical_pad)); mLayoutRows = a.getInteger(R.styleable.Keyboard_layoutRows, DEFAULT_LAYOUT_ROWS); mLayoutColumns = a.getInteger(R.styleable.Keyboard_layoutColumns, DEFAULT_LAYOUT_COLUMNS); if (mDefaultHeight == 0 && mKeyboardHeight > 0 && mLayoutRows > 0) { mDefaultHeight = mKeyboardHeight / mLayoutRows; //Log.i(TAG, "got mLayoutRows=" + mLayoutRows + ", mDefaultHeight=" + mDefaultHeight); } mProximityThreshold = (int) (mDefaultWidth * SEARCH_DISTANCE); mProximityThreshold = mProximityThreshold * mProximityThreshold; // Square it for comparison a.recycle(); } static float getDimensionOrFraction(TypedArray a, int index, int base, float defValue) { TypedValue value = a.peekValue(index); if (value == null) return defValue; if (value.type == TypedValue.TYPE_DIMENSION) { return a.getDimensionPixelOffset(index, Math.round(defValue)); } else if (value.type == TypedValue.TYPE_FRACTION) { // Round it to avoid values like 47.9999 from getting truncated //return Math.round(a.getFraction(index, base, base, defValue)); return a.getFraction(index, base, base, defValue); } return defValue; } @Override public String toString() { return "Keyboard(" + mLayoutColumns + "x" + mLayoutRows + " keys=" + mKeys.size() + " rowCount=" + mRowCount + " mode=" + mKeyboardMode + " size=" + mTotalWidth + "x" + mTotalHeight + ")"; } }
Java
/* * Copyright (C) 2011 Darren Salt * * Licensed under the Apache License, Version 2.0 (the "Licence"); you may * not use this file except in compliance with the Licence. You may obtain * a copy of the Licence at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the Licence is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * Licence for the specific language governing permissions and limitations * under the Licence. */ package org.pocketworkstation.pckeyboard; import android.inputmethodservice.InputMethodService; import android.util.Log; import android.view.inputmethod.EditorInfo; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; interface ComposeSequencing { public void onText(CharSequence text); public void updateShiftKeyState(EditorInfo attr); public EditorInfo getCurrentInputEditorInfo(); } public abstract class ComposeBase { private static final String TAG = "HK/ComposeBase"; protected static final Map<String, String> mMap = new HashMap<String, String>(); protected static final Set<String> mPrefixes = new HashSet<String>(); protected static String get(String key) { if (key == null || key.length() == 0) { return null; } //Log.i(TAG, "ComposeBase get, key=" + showString(key) + " result=" + mMap.get(key)); return mMap.get(key); } private static String showString(String in) { // TODO Auto-generated method stub StringBuilder out = new StringBuilder(in); out.append("{"); for (int i = 0; i < in.length(); ++i) { if (i > 0) out.append(","); out.append((int) in.charAt(i)); } out.append("}"); return out.toString(); } private static boolean isValid(String partialKey) { if (partialKey == null || partialKey.length() == 0) { return false; } return mPrefixes.contains(partialKey); } protected static void put(String key, String value) { mMap.put(key, value); for (int i = 1; i < key.length(); ++i) { mPrefixes.add(key.substring(0, i)); } } protected StringBuilder composeBuffer = new StringBuilder(10); protected ComposeSequencing composeUser; protected void init(ComposeSequencing user) { clear(); composeUser = user; } public void clear() { composeBuffer.setLength(0); } public void bufferKey(char code) { composeBuffer.append(code); //Log.i(TAG, "bufferKey code=" + (int) code + " => " + showString(composeBuffer.toString())); } // returns true if the compose sequence is valid but incomplete public String executeToString(int code) { KeyboardSwitcher ks = KeyboardSwitcher.getInstance(); if (ks.getInputView().isShiftCaps() && ks.isAlphabetMode() && Character.isLowerCase(code)) { code = Character.toUpperCase(code); } bufferKey((char) code); composeUser.updateShiftKeyState(composeUser.getCurrentInputEditorInfo()); String composed = get(composeBuffer.toString()); if (composed != null) { // If we get here, we have a complete compose sequence return composed; } else if (!isValid(composeBuffer.toString())) { // If we get here, then the sequence typed isn't recognised return ""; } return null; } public boolean execute(int code) { String composed = executeToString(code); if (composed != null) { clear(); composeUser.onText(composed); return false; } return true; } public boolean execute(CharSequence sequence) { int i, len = sequence.length(); boolean result = true; for (i = 0; i < len; ++i) { result = execute(sequence.charAt(i)); } return result; // only last one matters } }
Java
/* * Copyright (C) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.pocketworkstation.pckeyboard; import java.util.HashMap; import java.util.Set; import java.util.Map.Entry; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteQueryBuilder; import android.os.AsyncTask; import android.provider.BaseColumns; import android.util.Log; /** * Stores new words temporarily until they are promoted to the user dictionary * for longevity. Words in the auto dictionary are used to determine if it's ok * to accept a word that's not in the main or user dictionary. Using a new word * repeatedly will promote it to the user dictionary. */ public class AutoDictionary extends ExpandableDictionary { // Weight added to a user picking a new word from the suggestion strip static final int FREQUENCY_FOR_PICKED = 3; // Weight added to a user typing a new word that doesn't get corrected (or is reverted) static final int FREQUENCY_FOR_TYPED = 1; // A word that is frequently typed and gets promoted to the user dictionary, uses this // frequency. static final int FREQUENCY_FOR_AUTO_ADD = 250; // If the user touches a typed word 2 times or more, it will become valid. private static final int VALIDITY_THRESHOLD = 2 * FREQUENCY_FOR_PICKED; // If the user touches a typed word 4 times or more, it will be added to the user dict. private static final int PROMOTION_THRESHOLD = 4 * FREQUENCY_FOR_PICKED; private LatinIME mIme; // Locale for which this auto dictionary is storing words private String mLocale; private HashMap<String,Integer> mPendingWrites = new HashMap<String,Integer>(); private final Object mPendingWritesLock = new Object(); private static final String DATABASE_NAME = "auto_dict.db"; private static final int DATABASE_VERSION = 1; // These are the columns in the dictionary // TODO: Consume less space by using a unique id for locale instead of the whole // 2-5 character string. private static final String COLUMN_ID = BaseColumns._ID; private static final String COLUMN_WORD = "word"; private static final String COLUMN_FREQUENCY = "freq"; private static final String COLUMN_LOCALE = "locale"; /** Sort by descending order of frequency. */ public static final String DEFAULT_SORT_ORDER = COLUMN_FREQUENCY + " DESC"; /** Name of the words table in the auto_dict.db */ private static final String AUTODICT_TABLE_NAME = "words"; private static HashMap<String, String> sDictProjectionMap; static { sDictProjectionMap = new HashMap<String, String>(); sDictProjectionMap.put(COLUMN_ID, COLUMN_ID); sDictProjectionMap.put(COLUMN_WORD, COLUMN_WORD); sDictProjectionMap.put(COLUMN_FREQUENCY, COLUMN_FREQUENCY); sDictProjectionMap.put(COLUMN_LOCALE, COLUMN_LOCALE); } private static DatabaseHelper sOpenHelper = null; public AutoDictionary(Context context, LatinIME ime, String locale, int dicTypeId) { super(context, dicTypeId); mIme = ime; mLocale = locale; if (sOpenHelper == null) { sOpenHelper = new DatabaseHelper(getContext()); } if (mLocale != null && mLocale.length() > 1) { loadDictionary(); } } @Override public boolean isValidWord(CharSequence word) { final int frequency = getWordFrequency(word); return frequency >= VALIDITY_THRESHOLD; } @Override public void close() { flushPendingWrites(); // Don't close the database as locale changes will require it to be reopened anyway // Also, the database is written to somewhat frequently, so it needs to be kept alive // throughout the life of the process. // mOpenHelper.close(); super.close(); } @Override public void loadDictionaryAsync() { // Load the words that correspond to the current input locale Cursor cursor = query(COLUMN_LOCALE + "=?", new String[] { mLocale }); try { if (cursor.moveToFirst()) { int wordIndex = cursor.getColumnIndex(COLUMN_WORD); int frequencyIndex = cursor.getColumnIndex(COLUMN_FREQUENCY); while (!cursor.isAfterLast()) { String word = cursor.getString(wordIndex); int frequency = cursor.getInt(frequencyIndex); // Safeguard against adding really long words. Stack may overflow due // to recursive lookup if (word.length() < getMaxWordLength()) { super.addWord(word, frequency); } cursor.moveToNext(); } } } finally { cursor.close(); } } @Override public void addWord(String word, int addFrequency) { final int length = word.length(); // Don't add very short or very long words. if (length < 2 || length > getMaxWordLength()) return; if (mIme.getCurrentWord().isAutoCapitalized()) { // Remove caps before adding word = Character.toLowerCase(word.charAt(0)) + word.substring(1); } int freq = getWordFrequency(word); freq = freq < 0 ? addFrequency : freq + addFrequency; super.addWord(word, freq); if (freq >= PROMOTION_THRESHOLD) { mIme.promoteToUserDictionary(word, FREQUENCY_FOR_AUTO_ADD); freq = 0; } synchronized (mPendingWritesLock) { // Write a null frequency if it is to be deleted from the db mPendingWrites.put(word, freq == 0 ? null : new Integer(freq)); } } /** * Schedules a background thread to write any pending words to the database. */ public void flushPendingWrites() { synchronized (mPendingWritesLock) { // Nothing pending? Return if (mPendingWrites.isEmpty()) return; // Create a background thread to write the pending entries new UpdateDbTask(getContext(), sOpenHelper, mPendingWrites, mLocale).execute(); // Create a new map for writing new entries into while the old one is written to db mPendingWrites = new HashMap<String, Integer>(); } } /** * This class helps open, create, and upgrade the database file. */ private static class DatabaseHelper extends SQLiteOpenHelper { DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE " + AUTODICT_TABLE_NAME + " (" + COLUMN_ID + " INTEGER PRIMARY KEY," + COLUMN_WORD + " TEXT," + COLUMN_FREQUENCY + " INTEGER," + COLUMN_LOCALE + " TEXT" + ");"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w("AutoDictionary", "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); db.execSQL("DROP TABLE IF EXISTS " + AUTODICT_TABLE_NAME); onCreate(db); } } private Cursor query(String selection, String[] selectionArgs) { SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); qb.setTables(AUTODICT_TABLE_NAME); qb.setProjectionMap(sDictProjectionMap); // Get the database and run the query SQLiteDatabase db = sOpenHelper.getReadableDatabase(); Cursor c = qb.query(db, null, selection, selectionArgs, null, null, DEFAULT_SORT_ORDER); return c; } /** * Async task to write pending words to the database so that it stays in sync with * the in-memory trie. */ private static class UpdateDbTask extends AsyncTask<Void, Void, Void> { private final HashMap<String, Integer> mMap; private final DatabaseHelper mDbHelper; private final String mLocale; public UpdateDbTask(Context context, DatabaseHelper openHelper, HashMap<String, Integer> pendingWrites, String locale) { mMap = pendingWrites; mLocale = locale; mDbHelper = openHelper; } @Override protected Void doInBackground(Void... v) { SQLiteDatabase db = mDbHelper.getWritableDatabase(); // Write all the entries to the db Set<Entry<String,Integer>> mEntries = mMap.entrySet(); for (Entry<String,Integer> entry : mEntries) { Integer freq = entry.getValue(); db.delete(AUTODICT_TABLE_NAME, COLUMN_WORD + "=? AND " + COLUMN_LOCALE + "=?", new String[] { entry.getKey(), mLocale }); if (freq != null) { db.insert(AUTODICT_TABLE_NAME, null, getContentValues(entry.getKey(), freq, mLocale)); } } return null; } private ContentValues getContentValues(String word, int frequency, String locale) { ContentValues values = new ContentValues(4); values.put(COLUMN_WORD, word); values.put(COLUMN_FREQUENCY, frequency); values.put(COLUMN_LOCALE, locale); return values; } } }
Java
package org.pocketworkstation.pckeyboard; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.xmlpull.v1.XmlPullParserException; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.content.res.Resources; import android.content.res.XmlResourceParser; import android.util.Log; public class PluginManager extends BroadcastReceiver { private static String TAG = "PCKeyboard"; private static String HK_INTENT_DICT = "org.pocketworkstation.DICT"; private static String SOFTKEYBOARD_INTENT_DICT = "com.menny.android.anysoftkeyboard.DICTIONARY"; private LatinIME mIME; // Apparently anysoftkeyboard doesn't use ISO 639-1 language codes for its locales? // Add exceptions as needed. private static Map<String, String> SOFTKEYBOARD_LANG_MAP = new HashMap<String, String>(); static { SOFTKEYBOARD_LANG_MAP.put("dk", "da"); } PluginManager(LatinIME ime) { super(); mIME = ime; } private static Map<String, DictPluginSpec> mPluginDicts = new HashMap<String, DictPluginSpec>(); static interface DictPluginSpec { BinaryDictionary getDict(Context context); } static private abstract class DictPluginSpecBase implements DictPluginSpec { String mPackageName; Resources getResources(Context context) { PackageManager packageManager = context.getPackageManager(); Resources res = null; try { ApplicationInfo appInfo = packageManager.getApplicationInfo(mPackageName, 0); res = packageManager.getResourcesForApplication(appInfo); } catch (NameNotFoundException e) { Log.i(TAG, "couldn't get resources"); } return res; } abstract InputStream[] getStreams(Resources res); public BinaryDictionary getDict(Context context) { Resources res = getResources(context); if (res == null) return null; InputStream[] dicts = getStreams(res); if (dicts == null) return null; BinaryDictionary dict = new BinaryDictionary( context, dicts, Suggest.DIC_MAIN); if (dict.getSize() == 0) return null; //Log.i(TAG, "dict size=" + dict.getSize()); return dict; } } static private class DictPluginSpecHK extends DictPluginSpecBase { int[] mRawIds; public DictPluginSpecHK(String pkg, int[] ids) { mPackageName = pkg; mRawIds = ids; } @Override InputStream[] getStreams(Resources res) { if (mRawIds == null || mRawIds.length == 0) return null; InputStream[] streams = new InputStream[mRawIds.length]; for (int i = 0; i < mRawIds.length; ++i) { streams[i] = res.openRawResource(mRawIds[i]); } return streams; } } static private class DictPluginSpecSoftKeyboard extends DictPluginSpecBase { String mAssetName; public DictPluginSpecSoftKeyboard(String pkg, String asset) { mPackageName = pkg; mAssetName = asset; } @Override InputStream[] getStreams(Resources res) { if (mAssetName == null) return null; try { InputStream in = res.getAssets().open(mAssetName); return new InputStream[] {in}; } catch (IOException e) { Log.e(TAG, "Dictionary asset loading failure"); return null; } } } @Override public void onReceive(Context context, Intent intent) { Log.i(TAG, "Package information changed, updating dictionaries."); getPluginDictionaries(context); Log.i(TAG, "Finished updating dictionaries."); mIME.toggleLanguage(true, true); } static void getSoftKeyboardDictionaries(PackageManager packageManager) { Intent dictIntent = new Intent(SOFTKEYBOARD_INTENT_DICT); List<ResolveInfo> dictPacks = packageManager.queryBroadcastReceivers( dictIntent, PackageManager.GET_RECEIVERS); for (ResolveInfo ri : dictPacks) { ApplicationInfo appInfo = ri.activityInfo.applicationInfo; String pkgName = appInfo.packageName; boolean success = false; try { Resources res = packageManager.getResourcesForApplication(appInfo); //Log.i(TAG, "Found dictionary plugin package: " + pkgName); int dictId = res.getIdentifier("dictionaries", "xml", pkgName); if (dictId == 0) continue; XmlResourceParser xrp = res.getXml(dictId); String assetName = null; String lang = null; try { int current = xrp.getEventType(); while (current != XmlResourceParser.END_DOCUMENT) { if (current == XmlResourceParser.START_TAG) { String tag = xrp.getName(); if (tag != null) { if (tag.equals("Dictionary")) { lang = xrp.getAttributeValue(null, "locale"); String convLang = SOFTKEYBOARD_LANG_MAP.get(lang); if (convLang != null) lang = convLang; String type = xrp.getAttributeValue(null, "type"); if (type == null || type.equals("raw") || type.equals("binary")) { assetName = xrp.getAttributeValue(null, "dictionaryAssertName"); // sic } else { Log.w(TAG, "Unsupported AnySoftKeyboard dict type " + type); } //Log.i(TAG, "asset=" + assetName + " lang=" + lang); } } } xrp.next(); current = xrp.getEventType(); } } catch (XmlPullParserException e) { Log.e(TAG, "Dictionary XML parsing failure"); } catch (IOException e) { Log.e(TAG, "Dictionary XML IOException"); } if (assetName == null || lang == null) continue; DictPluginSpec spec = new DictPluginSpecSoftKeyboard(pkgName, assetName); mPluginDicts.put(lang, spec); Log.i(TAG, "Found plugin dictionary: lang=" + lang + ", pkg=" + pkgName); success = true; } catch (NameNotFoundException e) { Log.i(TAG, "bad"); } finally { if (!success) { Log.i(TAG, "failed to load plugin dictionary spec from " + pkgName); } } } } static void getHKDictionaries(PackageManager packageManager) { Intent dictIntent = new Intent(HK_INTENT_DICT); List<ResolveInfo> dictPacks = packageManager.queryIntentActivities(dictIntent, 0); for (ResolveInfo ri : dictPacks) { ApplicationInfo appInfo = ri.activityInfo.applicationInfo; String pkgName = appInfo.packageName; boolean success = false; try { Resources res = packageManager.getResourcesForApplication(appInfo); //Log.i(TAG, "Found dictionary plugin package: " + pkgName); int langId = res.getIdentifier("dict_language", "string", pkgName); if (langId == 0) continue; String lang = res.getString(langId); int[] rawIds = null; // Try single-file version first int rawId = res.getIdentifier("main", "raw", pkgName); if (rawId != 0) { rawIds = new int[] { rawId }; } else { // try multi-part version int parts = 0; List<Integer> ids = new ArrayList<Integer>(); while (true) { int id = res.getIdentifier("main" + parts, "raw", pkgName); if (id == 0) break; ids.add(id); ++parts; } if (parts == 0) continue; // no parts found rawIds = new int[parts]; for (int i = 0; i < parts; ++i) rawIds[i] = ids.get(i); } DictPluginSpec spec = new DictPluginSpecHK(pkgName, rawIds); mPluginDicts.put(lang, spec); Log.i(TAG, "Found plugin dictionary: lang=" + lang + ", pkg=" + pkgName); success = true; } catch (NameNotFoundException e) { Log.i(TAG, "bad"); } finally { if (!success) { Log.i(TAG, "failed to load plugin dictionary spec from " + pkgName); } } } } static void getPluginDictionaries(Context context) { mPluginDicts.clear(); PackageManager packageManager = context.getPackageManager(); getSoftKeyboardDictionaries(packageManager); getHKDictionaries(packageManager); } static BinaryDictionary getDictionary(Context context, String lang) { //Log.i(TAG, "Looking for plugin dictionary for lang=" + lang); DictPluginSpec spec = mPluginDicts.get(lang); if (spec == null) spec = mPluginDicts.get(lang.substring(0, 2)); if (spec == null) { //Log.i(TAG, "No plugin found."); return null; } BinaryDictionary dict = spec.getDict(context); Log.i(TAG, "Found plugin dictionary for " + lang + (dict == null ? " is null" : ", size=" + dict.getSize())); return dict; } }
Java
/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.pocketworkstation.pckeyboard; /** * Abstract base class for a dictionary that can do a fuzzy search for words based on a set of key * strokes. */ abstract public class Dictionary { /** * Whether or not to replicate the typed word in the suggested list, even if it's valid. */ protected static final boolean INCLUDE_TYPED_WORD_IF_VALID = false; /** * The weight to give to a word if it's length is the same as the number of typed characters. */ protected static final int FULL_WORD_FREQ_MULTIPLIER = 2; public static enum DataType { UNIGRAM, BIGRAM } /** * Interface to be implemented by classes requesting words to be fetched from the dictionary. * @see #getWords(WordComposer, WordCallback) */ public interface WordCallback { /** * Adds a word to a list of suggestions. The word is expected to be ordered based on * the provided frequency. * @param word the character array containing the word * @param wordOffset starting offset of the word in the character array * @param wordLength length of valid characters in the character array * @param frequency the frequency of occurence. This is normalized between 1 and 255, but * can exceed those limits * @param dicTypeId of the dictionary where word was from * @param dataType tells type of this data * @return true if the word was added, false if no more words are required */ boolean addWord(char[] word, int wordOffset, int wordLength, int frequency, int dicTypeId, DataType dataType); } /** * Searches for words in the dictionary that match the characters in the composer. Matched * words are added through the callback object. * @param composer the key sequence to match * @param callback the callback object to send matched words to as possible candidates * @param nextLettersFrequencies array of frequencies of next letters that could follow the * word so far. For instance, "bracke" can be followed by "t", so array['t'] will have * a non-zero value on returning from this method. * Pass in null if you don't want the dictionary to look up next letters. * @see WordCallback#addWord(char[], int, int) */ abstract public void getWords(final WordComposer composer, final WordCallback callback, int[] nextLettersFrequencies); /** * Searches for pairs in the bigram dictionary that matches the previous word and all the * possible words following are added through the callback object. * @param composer the key sequence to match * @param callback the callback object to send possible word following previous word * @param nextLettersFrequencies array of frequencies of next letters that could follow the * word so far. For instance, "bracke" can be followed by "t", so array['t'] will have * a non-zero value on returning from this method. * Pass in null if you don't want the dictionary to look up next letters. */ public void getBigrams(final WordComposer composer, final CharSequence previousWord, final WordCallback callback, int[] nextLettersFrequencies) { // empty base implementation } /** * Checks if the given word occurs in the dictionary * @param word the word to search for. The search should be case-insensitive. * @return true if the word exists, false otherwise */ abstract public boolean isValidWord(CharSequence word); /** * Compares the contents of the character array with the typed word and returns true if they * are the same. * @param word the array of characters that make up the word * @param length the number of valid characters in the character array * @param typedWord the word to compare with * @return true if they are the same, false otherwise. */ protected boolean same(final char[] word, final int length, final CharSequence typedWord) { if (typedWord.length() != length) { return false; } for (int i = 0; i < length; i++) { if (word[i] != typedWord.charAt(i)) { return false; } } return true; } /** * Override to clean up any resources. */ public void close() { } }
Java
/* * Copyright (C) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.android.inputmethod.voice; import org.pocketworkstation.pckeyboard.EditingUtil; import org.pocketworkstation.pckeyboard.R; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.Parcelable; import android.speech.RecognitionListener; import android.speech.SpeechRecognizer; import android.speech.RecognizerIntent; import android.util.Log; import android.view.inputmethod.InputConnection; import android.view.View; import android.view.View.OnClickListener; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; /** * Speech recognition input, including both user interface and a background * process to stream audio to the network recognizer. This class supplies a * View (getView()), which it updates as recognition occurs. The user of this * class is responsible for making the view visible to the user, as well as * handling various events returned through UiListener. */ public class VoiceInput implements OnClickListener { private static final String TAG = "VoiceInput"; private static final String EXTRA_RECOGNITION_CONTEXT = "android.speech.extras.RECOGNITION_CONTEXT"; private static final String EXTRA_CALLING_PACKAGE = "calling_package"; private static final String EXTRA_ALTERNATES = "android.speech.extra.ALTERNATES"; private static final int MAX_ALT_LIST_LENGTH = 6; private static final String DEFAULT_RECOMMENDED_PACKAGES = "com.android.mms " + "com.google.android.gm " + "com.google.android.talk " + "com.google.android.apps.googlevoice " + "com.android.email " + "com.android.browser "; // WARNING! Before enabling this, fix the problem with calling getExtractedText() in // landscape view. It causes Extracted text updates to be rejected due to a token mismatch public static boolean ENABLE_WORD_CORRECTIONS = true; // Dummy word suggestion which means "delete current word" public static final String DELETE_SYMBOL = " \u00D7 "; // times symbol private Whitelist mRecommendedList; private Whitelist mBlacklist; private VoiceInputLogger mLogger; // Names of a few extras defined in VoiceSearch's RecognitionController // Note, the version of voicesearch that shipped in Froyo returns the raw // RecognitionClientAlternates protocol buffer under the key "alternates", // so a VS market update must be installed on Froyo devices in order to see // alternatives. private static final String ALTERNATES_BUNDLE = "alternates_bundle"; // This is copied from the VoiceSearch app. private static final class AlternatesBundleKeys { public static final String ALTERNATES = "alternates"; public static final String CONFIDENCE = "confidence"; public static final String LENGTH = "length"; public static final String MAX_SPAN_LENGTH = "max_span_length"; public static final String SPANS = "spans"; public static final String SPAN_KEY_DELIMITER = ":"; public static final String START = "start"; public static final String TEXT = "text"; } // Names of a few intent extras defined in VoiceSearch's RecognitionService. // These let us tweak the endpointer parameters. private static final String EXTRA_SPEECH_MINIMUM_LENGTH_MILLIS = "android.speech.extras.SPEECH_INPUT_MINIMUM_LENGTH_MILLIS"; private static final String EXTRA_SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS = "android.speech.extras.SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS"; private static final String EXTRA_SPEECH_INPUT_POSSIBLY_COMPLETE_SILENCE_LENGTH_MILLIS = "android.speech.extras.SPEECH_INPUT_POSSIBLY_COMPLETE_SILENCE_LENGTH_MILLIS"; // The usual endpointer default value for input complete silence length is 0.5 seconds, // but that's used for things like voice search. For dictation-like voice input like this, // we go with a more liberal value of 1 second. This value will only be used if a value // is not provided from Gservices. private static final String INPUT_COMPLETE_SILENCE_LENGTH_DEFAULT_VALUE_MILLIS = "1000"; // Used to record part of that state for logging purposes. public static final int DEFAULT = 0; public static final int LISTENING = 1; public static final int WORKING = 2; public static final int ERROR = 3; private int mAfterVoiceInputDeleteCount = 0; private int mAfterVoiceInputInsertCount = 0; private int mAfterVoiceInputInsertPunctuationCount = 0; private int mAfterVoiceInputCursorPos = 0; private int mAfterVoiceInputSelectionSpan = 0; private int mState = DEFAULT; private final static int MSG_CLOSE_ERROR_DIALOG = 1; private final Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { if (msg.what == MSG_CLOSE_ERROR_DIALOG) { mState = DEFAULT; mRecognitionView.finish(); mUiListener.onCancelVoice(); } } }; /** * Events relating to the recognition UI. You must implement these. */ public interface UiListener { /** * @param recognitionResults a set of transcripts for what the user * spoke, sorted by likelihood. */ public void onVoiceResults( List<String> recognitionResults, Map<String, List<CharSequence>> alternatives); /** * Called when the user cancels speech recognition. */ public void onCancelVoice(); } private SpeechRecognizer mSpeechRecognizer; private RecognitionListener mRecognitionListener; private RecognitionView mRecognitionView; private UiListener mUiListener; private Context mContext; /** * @param context the service or activity in which we're running. * @param uiHandler object to receive events from VoiceInput. */ public VoiceInput(Context context, UiListener uiHandler) { mLogger = VoiceInputLogger.getLogger(context); mRecognitionListener = new ImeRecognitionListener(); mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(context); mSpeechRecognizer.setRecognitionListener(mRecognitionListener); mUiListener = uiHandler; mContext = context; newView(); String recommendedPackages = SettingsUtil.getSettingsString( context.getContentResolver(), SettingsUtil.LATIN_IME_VOICE_INPUT_RECOMMENDED_PACKAGES, DEFAULT_RECOMMENDED_PACKAGES); mRecommendedList = new Whitelist(); for (String recommendedPackage : recommendedPackages.split("\\s+")) { mRecommendedList.addApp(recommendedPackage); } mBlacklist = new Whitelist(); mBlacklist.addApp("com.android.setupwizard"); } public void setCursorPos(int pos) { mAfterVoiceInputCursorPos = pos; } public int getCursorPos() { return mAfterVoiceInputCursorPos; } public void setSelectionSpan(int span) { mAfterVoiceInputSelectionSpan = span; } public int getSelectionSpan() { return mAfterVoiceInputSelectionSpan; } public void incrementTextModificationDeleteCount(int count){ mAfterVoiceInputDeleteCount += count; // Send up intents for other text modification types if (mAfterVoiceInputInsertCount > 0) { logTextModifiedByTypingInsertion(mAfterVoiceInputInsertCount); mAfterVoiceInputInsertCount = 0; } if (mAfterVoiceInputInsertPunctuationCount > 0) { logTextModifiedByTypingInsertionPunctuation(mAfterVoiceInputInsertPunctuationCount); mAfterVoiceInputInsertPunctuationCount = 0; } } public void incrementTextModificationInsertCount(int count){ mAfterVoiceInputInsertCount += count; if (mAfterVoiceInputSelectionSpan > 0) { // If text was highlighted before inserting the char, count this as // a delete. mAfterVoiceInputDeleteCount += mAfterVoiceInputSelectionSpan; } // Send up intents for other text modification types if (mAfterVoiceInputDeleteCount > 0) { logTextModifiedByTypingDeletion(mAfterVoiceInputDeleteCount); mAfterVoiceInputDeleteCount = 0; } if (mAfterVoiceInputInsertPunctuationCount > 0) { logTextModifiedByTypingInsertionPunctuation(mAfterVoiceInputInsertPunctuationCount); mAfterVoiceInputInsertPunctuationCount = 0; } } public void incrementTextModificationInsertPunctuationCount(int count){ mAfterVoiceInputInsertPunctuationCount += 1; if (mAfterVoiceInputSelectionSpan > 0) { // If text was highlighted before inserting the char, count this as // a delete. mAfterVoiceInputDeleteCount += mAfterVoiceInputSelectionSpan; } // Send up intents for aggregated non-punctuation insertions if (mAfterVoiceInputDeleteCount > 0) { logTextModifiedByTypingDeletion(mAfterVoiceInputDeleteCount); mAfterVoiceInputDeleteCount = 0; } if (mAfterVoiceInputInsertCount > 0) { logTextModifiedByTypingInsertion(mAfterVoiceInputInsertCount); mAfterVoiceInputInsertCount = 0; } } public void flushAllTextModificationCounters() { if (mAfterVoiceInputInsertCount > 0) { logTextModifiedByTypingInsertion(mAfterVoiceInputInsertCount); mAfterVoiceInputInsertCount = 0; } if (mAfterVoiceInputDeleteCount > 0) { logTextModifiedByTypingDeletion(mAfterVoiceInputDeleteCount); mAfterVoiceInputDeleteCount = 0; } if (mAfterVoiceInputInsertPunctuationCount > 0) { logTextModifiedByTypingInsertionPunctuation(mAfterVoiceInputInsertPunctuationCount); mAfterVoiceInputInsertPunctuationCount = 0; } } /** * The configuration of the IME changed and may have caused the views to be layed out * again. Restore the state of the recognition view. */ public void onConfigurationChanged() { mRecognitionView.restoreState(); } /** * @return true if field is blacklisted for voice */ public boolean isBlacklistedField(FieldContext context) { return mBlacklist.matches(context); } /** * Used to decide whether to show voice input hints for this field, etc. * * @return true if field is recommended for voice */ public boolean isRecommendedField(FieldContext context) { return mRecommendedList.matches(context); } /** * Start listening for speech from the user. This will grab the microphone * and start updating the view provided by getView(). It is the caller's * responsibility to ensure that the view is visible to the user at this stage. * * @param context the same FieldContext supplied to voiceIsEnabled() * @param swipe whether this voice input was started by swipe, for logging purposes */ public void startListening(FieldContext context, boolean swipe) { mState = DEFAULT; Locale locale = Locale.getDefault(); String localeString = locale.getLanguage() + "-" + locale.getCountry(); mLogger.start(localeString, swipe); mState = LISTENING; mRecognitionView.showInitializing(); startListeningAfterInitialization(context); } /** * Called only when the recognition manager's initialization completed * * @param context context with which {@link #startListening(FieldContext, boolean)} was executed */ private void startListeningAfterInitialization(FieldContext context) { Intent intent = makeIntent(); intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, ""); intent.putExtra(EXTRA_RECOGNITION_CONTEXT, context.getBundle()); intent.putExtra(EXTRA_CALLING_PACKAGE, "VoiceIME"); intent.putExtra(EXTRA_ALTERNATES, true); intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, SettingsUtil.getSettingsInt( mContext.getContentResolver(), SettingsUtil.LATIN_IME_MAX_VOICE_RESULTS, 1)); // Get endpointer params from Gservices. // TODO: Consider caching these values for improved performance on slower devices. final ContentResolver cr = mContext.getContentResolver(); putEndpointerExtra( cr, intent, SettingsUtil.LATIN_IME_SPEECH_MINIMUM_LENGTH_MILLIS, EXTRA_SPEECH_MINIMUM_LENGTH_MILLIS, null /* rely on endpointer default */); putEndpointerExtra( cr, intent, SettingsUtil.LATIN_IME_SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS, EXTRA_SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS, INPUT_COMPLETE_SILENCE_LENGTH_DEFAULT_VALUE_MILLIS /* our default value is different from the endpointer's */); putEndpointerExtra( cr, intent, SettingsUtil. LATIN_IME_SPEECH_INPUT_POSSIBLY_COMPLETE_SILENCE_LENGTH_MILLIS, EXTRA_SPEECH_INPUT_POSSIBLY_COMPLETE_SILENCE_LENGTH_MILLIS, null /* rely on endpointer default */); mSpeechRecognizer.startListening(intent); } /** * Gets the value of the provided Gservices key, attempts to parse it into a long, * and if successful, puts the long value as an extra in the provided intent. */ private void putEndpointerExtra(ContentResolver cr, Intent i, String gservicesKey, String intentExtraKey, String defaultValue) { long l = -1; String s = SettingsUtil.getSettingsString(cr, gservicesKey, defaultValue); if (s != null) { try { l = Long.valueOf(s); } catch (NumberFormatException e) { Log.e(TAG, "could not parse value for " + gservicesKey + ": " + s); } } if (l != -1) i.putExtra(intentExtraKey, l); } public void destroy() { mSpeechRecognizer.destroy(); } /** * Creates a new instance of the view that is returned by {@link #getView()} * Clients should use this when a previously returned view is stuck in a * layout that is being thrown away and a new one is need to show to the * user. */ public void newView() { mRecognitionView = new RecognitionView(mContext, this); } /** * @return a view that shows the recognition flow--e.g., "Speak now" and * "working" dialogs. */ public View getView() { return mRecognitionView.getView(); } /** * Handle the cancel button. */ public void onClick(View view) { switch(view.getId()) { case R.id.button: cancel(); break; } } public void logTextModifiedByTypingInsertion(int length) { mLogger.textModifiedByTypingInsertion(length); } public void logTextModifiedByTypingInsertionPunctuation(int length) { mLogger.textModifiedByTypingInsertionPunctuation(length); } public void logTextModifiedByTypingDeletion(int length) { mLogger.textModifiedByTypingDeletion(length); } public void logTextModifiedByChooseSuggestion(String suggestion, int index, String wordSeparators, InputConnection ic) { EditingUtil.Range range = new EditingUtil.Range(); String wordToBeReplaced = EditingUtil.getWordAtCursor(ic, wordSeparators, range); // If we enable phrase-based alternatives, only send up the first word // in suggestion and wordToBeReplaced. mLogger.textModifiedByChooseSuggestion(suggestion.length(), wordToBeReplaced.length(), index, wordToBeReplaced, suggestion); } public void logKeyboardWarningDialogShown() { mLogger.keyboardWarningDialogShown(); } public void logKeyboardWarningDialogDismissed() { mLogger.keyboardWarningDialogDismissed(); } public void logKeyboardWarningDialogOk() { mLogger.keyboardWarningDialogOk(); } public void logKeyboardWarningDialogCancel() { mLogger.keyboardWarningDialogCancel(); } public void logSwipeHintDisplayed() { mLogger.swipeHintDisplayed(); } public void logPunctuationHintDisplayed() { mLogger.punctuationHintDisplayed(); } public void logVoiceInputDelivered(int length) { mLogger.voiceInputDelivered(length); } public void logInputEnded() { mLogger.inputEnded(); } public void flushLogs() { mLogger.flush(); } private static Intent makeIntent() { Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); // On Cupcake, use VoiceIMEHelper since VoiceSearch doesn't support. // On Donut, always use VoiceSearch, since VoiceIMEHelper and // VoiceSearch may conflict. if (Build.VERSION.RELEASE.equals("1.5")) { intent = intent.setClassName( "com.google.android.voiceservice", "com.google.android.voiceservice.IMERecognitionService"); } else { intent = intent.setClassName( "com.google.android.voicesearch", "com.google.android.voicesearch.RecognitionService"); } return intent; } /** * Cancel in-progress speech recognition. */ public void cancel() { switch (mState) { case LISTENING: mLogger.cancelDuringListening(); break; case WORKING: mLogger.cancelDuringWorking(); break; case ERROR: mLogger.cancelDuringError(); break; } mState = DEFAULT; // Remove all pending tasks (e.g., timers to cancel voice input) mHandler.removeMessages(MSG_CLOSE_ERROR_DIALOG); mSpeechRecognizer.cancel(); mUiListener.onCancelVoice(); mRecognitionView.finish(); } private int getErrorStringId(int errorType, boolean endpointed) { switch (errorType) { // We use CLIENT_ERROR to signify that voice search is not available on the device. case SpeechRecognizer.ERROR_CLIENT: return R.string.voice_not_installed; case SpeechRecognizer.ERROR_NETWORK: return R.string.voice_network_error; case SpeechRecognizer.ERROR_NETWORK_TIMEOUT: return endpointed ? R.string.voice_network_error : R.string.voice_too_much_speech; case SpeechRecognizer.ERROR_AUDIO: return R.string.voice_audio_error; case SpeechRecognizer.ERROR_SERVER: return R.string.voice_server_error; case SpeechRecognizer.ERROR_SPEECH_TIMEOUT: return R.string.voice_speech_timeout; case SpeechRecognizer.ERROR_NO_MATCH: return R.string.voice_no_match; default: return R.string.voice_error; } } private void onError(int errorType, boolean endpointed) { Log.i(TAG, "error " + errorType); mLogger.error(errorType); onError(mContext.getString(getErrorStringId(errorType, endpointed))); } private void onError(String error) { mState = ERROR; mRecognitionView.showError(error); // Wait a couple seconds and then automatically dismiss message. mHandler.sendMessageDelayed(Message.obtain(mHandler, MSG_CLOSE_ERROR_DIALOG), 2000); } private class ImeRecognitionListener implements RecognitionListener { // Waveform data final ByteArrayOutputStream mWaveBuffer = new ByteArrayOutputStream(); int mSpeechStart; private boolean mEndpointed = false; public void onReadyForSpeech(Bundle noiseParams) { mRecognitionView.showListening(); } public void onBeginningOfSpeech() { mEndpointed = false; mSpeechStart = mWaveBuffer.size(); } public void onRmsChanged(float rmsdB) { mRecognitionView.updateVoiceMeter(rmsdB); } public void onBufferReceived(byte[] buf) { try { mWaveBuffer.write(buf); } catch (IOException e) {} } public void onEndOfSpeech() { mEndpointed = true; mState = WORKING; mRecognitionView.showWorking(mWaveBuffer, mSpeechStart, mWaveBuffer.size()); } public void onError(int errorType) { mState = ERROR; VoiceInput.this.onError(errorType, mEndpointed); } public void onResults(Bundle resultsBundle) { List<String> results = resultsBundle .getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION); // VS Market update is needed for IME froyo clients to access the alternatesBundle // TODO: verify this. Bundle alternatesBundle = resultsBundle.getBundle(ALTERNATES_BUNDLE); mState = DEFAULT; final Map<String, List<CharSequence>> alternatives = new HashMap<String, List<CharSequence>>(); if (ENABLE_WORD_CORRECTIONS && alternatesBundle != null && results.size() > 0) { // Use the top recognition result to map each alternative's start:length to a word. String[] words = results.get(0).split(" "); Bundle spansBundle = alternatesBundle.getBundle(AlternatesBundleKeys.SPANS); for (String key : spansBundle.keySet()) { // Get the word for which these alternates correspond to. Bundle spanBundle = spansBundle.getBundle(key); int start = spanBundle.getInt(AlternatesBundleKeys.START); int length = spanBundle.getInt(AlternatesBundleKeys.LENGTH); // Only keep single-word based alternatives. if (length == 1 && start < words.length) { // Get the alternatives associated with the span. // If a word appears twice in a recognition result, // concatenate the alternatives for the word. List<CharSequence> altList = alternatives.get(words[start]); if (altList == null) { altList = new ArrayList<CharSequence>(); alternatives.put(words[start], altList); } Parcelable[] alternatesArr = spanBundle .getParcelableArray(AlternatesBundleKeys.ALTERNATES); for (int j = 0; j < alternatesArr.length && altList.size() < MAX_ALT_LIST_LENGTH; j++) { Bundle alternateBundle = (Bundle) alternatesArr[j]; String alternate = alternateBundle.getString(AlternatesBundleKeys.TEXT); // Don't allow duplicates in the alternates list. if (!altList.contains(alternate)) { altList.add(alternate); } } } } } if (results.size() > 5) { results = results.subList(0, 5); } mUiListener.onVoiceResults(results, alternatives); mRecognitionView.finish(); } public void onPartialResults(final Bundle partialResults) { // currently - do nothing } public void onEvent(int eventType, Bundle params) { // do nothing - reserved for events that might be added in the future } } }
Java
/* * Copyright (C) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.android.inputmethod.voice; import android.os.Bundle; import android.util.Log; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.ExtractedText; import android.view.inputmethod.ExtractedTextRequest; import android.view.inputmethod.InputConnection; /** * Represents information about a given text field, which can be passed * to the speech recognizer as context information. */ public class FieldContext { private static final boolean DBG = false; static final String LABEL = "label"; static final String HINT = "hint"; static final String PACKAGE_NAME = "packageName"; static final String FIELD_ID = "fieldId"; static final String FIELD_NAME = "fieldName"; static final String SINGLE_LINE = "singleLine"; static final String INPUT_TYPE = "inputType"; static final String IME_OPTIONS = "imeOptions"; static final String SELECTED_LANGUAGE = "selectedLanguage"; static final String ENABLED_LANGUAGES = "enabledLanguages"; Bundle mFieldInfo; public FieldContext(InputConnection conn, EditorInfo info, String selectedLanguage, String[] enabledLanguages) { mFieldInfo = new Bundle(); addEditorInfoToBundle(info, mFieldInfo); addInputConnectionToBundle(conn, mFieldInfo); addLanguageInfoToBundle(selectedLanguage, enabledLanguages, mFieldInfo); if (DBG) Log.i("FieldContext", "Bundle = " + mFieldInfo.toString()); } private static String safeToString(Object o) { if (o == null) { return ""; } return o.toString(); } private static void addEditorInfoToBundle(EditorInfo info, Bundle bundle) { if (info == null) { return; } bundle.putString(LABEL, safeToString(info.label)); bundle.putString(HINT, safeToString(info.hintText)); bundle.putString(PACKAGE_NAME, safeToString(info.packageName)); bundle.putInt(FIELD_ID, info.fieldId); bundle.putString(FIELD_NAME, safeToString(info.fieldName)); bundle.putInt(INPUT_TYPE, info.inputType); bundle.putInt(IME_OPTIONS, info.imeOptions); } private static void addInputConnectionToBundle( InputConnection conn, Bundle bundle) { if (conn == null) { return; } ExtractedText et = conn.getExtractedText(new ExtractedTextRequest(), 0); if (et == null) { return; } bundle.putBoolean(SINGLE_LINE, (et.flags & et.FLAG_SINGLE_LINE) > 0); } private static void addLanguageInfoToBundle( String selectedLanguage, String[] enabledLanguages, Bundle bundle) { bundle.putString(SELECTED_LANGUAGE, selectedLanguage); bundle.putStringArray(ENABLED_LANGUAGES, enabledLanguages); } public Bundle getBundle() { return mFieldInfo; } public String toString() { return mFieldInfo.toString(); } }
Java
/* * Copyright (C) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.android.inputmethod.voice; import android.os.Bundle; import java.util.ArrayList; import java.util.List; /** * A set of text fields where speech has been explicitly enabled. */ public class Whitelist { private List<Bundle> mConditions; public Whitelist() { mConditions = new ArrayList<Bundle>(); } public Whitelist(List<Bundle> conditions) { this.mConditions = conditions; } public void addApp(String app) { Bundle bundle = new Bundle(); bundle.putString("packageName", app); mConditions.add(bundle); } /** * @return true if the field is a member of the whitelist. */ public boolean matches(FieldContext context) { for (Bundle condition : mConditions) { if (matches(condition, context.getBundle())) { return true; } } return false; } /** * @return true of all values in condition are matched by a value * in target. */ private boolean matches(Bundle condition, Bundle target) { for (String key : condition.keySet()) { if (!condition.getString(key).equals(target.getString(key))) { return false; } } return true; } }
Java
/* * Copyright (C) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.android.inputmethod.voice; import android.content.ContentResolver; import android.database.Cursor; import android.net.Uri; import android.provider.Settings; import android.util.Log; /** * Utility for retrieving settings from Settings.Secure. */ public class SettingsUtil { /** * A whitespace-separated list of supported locales for voice input from the keyboard. */ public static final String LATIN_IME_VOICE_INPUT_SUPPORTED_LOCALES = "latin_ime_voice_input_supported_locales"; /** * A whitespace-separated list of recommended app packages for voice input from the * keyboard. */ public static final String LATIN_IME_VOICE_INPUT_RECOMMENDED_PACKAGES = "latin_ime_voice_input_recommended_packages"; /** * The maximum number of unique days to show the swipe hint for voice input. */ public static final String LATIN_IME_VOICE_INPUT_SWIPE_HINT_MAX_DAYS = "latin_ime_voice_input_swipe_hint_max_days"; /** * The maximum number of times to show the punctuation hint for voice input. */ public static final String LATIN_IME_VOICE_INPUT_PUNCTUATION_HINT_MAX_DISPLAYS = "latin_ime_voice_input_punctuation_hint_max_displays"; /** * Endpointer parameters for voice input from the keyboard. */ public static final String LATIN_IME_SPEECH_MINIMUM_LENGTH_MILLIS = "latin_ime_speech_minimum_length_millis"; public static final String LATIN_IME_SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS = "latin_ime_speech_input_complete_silence_length_millis"; public static final String LATIN_IME_SPEECH_INPUT_POSSIBLY_COMPLETE_SILENCE_LENGTH_MILLIS = "latin_ime_speech_input_possibly_complete_silence_length_millis"; /** * Min and max volume levels that can be displayed on the "speak now" screen. */ public static final String LATIN_IME_MIN_MICROPHONE_LEVEL = "latin_ime_min_microphone_level"; public static final String LATIN_IME_MAX_MICROPHONE_LEVEL = "latin_ime_max_microphone_level"; /** * The number of sentence-level alternates to request of the server. */ public static final String LATIN_IME_MAX_VOICE_RESULTS = "latin_ime_max_voice_results"; /** * Get a string-valued setting. * * @param cr The content resolver to use * @param key The setting to look up * @param defaultValue The default value to use if none can be found * @return The value of the setting, or defaultValue if it couldn't be found */ public static String getSettingsString(ContentResolver cr, String key, String defaultValue) { String result = Settings.Secure.getString(cr, key); return (result == null) ? defaultValue : result; } /** * Get an int-valued setting. * * @param cr The content resolver to use * @param key The setting to look up * @param defaultValue The default value to use if the setting couldn't be found or parsed * @return The value of the setting, or defaultValue if it couldn't be found or parsed */ public static int getSettingsInt(ContentResolver cr, String key, int defaultValue) { return Settings.Secure.getInt(cr, key, defaultValue); } /** * Get a float-valued setting. * * @param cr The content resolver to use * @param key The setting to look up * @param defaultValue The default value to use if the setting couldn't be found or parsed * @return The value of the setting, or defaultValue if it couldn't be found or parsed */ public static float getSettingsFloat(ContentResolver cr, String key, float defaultValue) { return Settings.Secure.getFloat(cr, key, defaultValue); } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.android.inputmethod.voice; import android.content.Context; /** * Provides the logging facility for voice input events. This fires broadcasts back to * the voice search app which then logs on our behalf. * * Note that debug console logging does not occur in this class. If you want to * see console output of these logging events, there is a boolean switch to turn * on on the VoiceSearch side. */ public class VoiceInputLogger { private static VoiceInputLogger sVoiceInputLogger; // The base intent used to form all broadcast intents to the logger // in VoiceSearch. // This flag is used to indicate when there are voice events that // need to be flushed. /** * Returns the singleton of the logger. * * @param contextHint a hint context used when creating the logger instance. * Ignored if the singleton instance already exists. */ public static synchronized VoiceInputLogger getLogger(Context contextHint) { if (sVoiceInputLogger == null) { sVoiceInputLogger = new VoiceInputLogger(contextHint); } return sVoiceInputLogger; } public VoiceInputLogger(Context context) { } public void flush() { } public void keyboardWarningDialogShown() { } public void keyboardWarningDialogDismissed() { } public void keyboardWarningDialogOk() { } public void keyboardWarningDialogCancel() { } public void settingsWarningDialogShown() { } public void settingsWarningDialogDismissed() { } public void settingsWarningDialogOk() { } public void settingsWarningDialogCancel() { } public void swipeHintDisplayed() { } public void cancelDuringListening() { } public void cancelDuringWorking() { } public void cancelDuringError() { } public void punctuationHintDisplayed() { } public void error(int code) { } public void start(String locale, boolean swipe) { } public void voiceInputDelivered(int length) { } public void textModifiedByTypingInsertion(int length) { } public void textModifiedByTypingInsertionPunctuation(int length) { } public void textModifiedByTypingDeletion(int length) { } public void textModifiedByChooseSuggestion(int suggestionLength, int replacedPhraseLength, int index, String before, String after) { } public void inputEnded() { } public void voiceInputSettingEnabled() { } public void voiceInputSettingDisabled() { } }
Java
/* * Copyright (C) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.android.inputmethod.voice; import java.io.ByteArrayOutputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.ShortBuffer; import java.util.ArrayList; import java.util.List; import android.content.ContentResolver; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.CornerPathEffect; import android.graphics.Paint; import android.graphics.Path; import android.graphics.PathEffect; import android.graphics.drawable.Drawable; import android.os.Handler; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup.MarginLayoutParams; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import org.pocketworkstation.pckeyboard.R; /** * The user interface for the "Speak now" and "working" states. * Displays a recognition dialog (with waveform, voice meter, etc.), * plays beeps, shows errors, etc. */ public class RecognitionView { private static final String TAG = "RecognitionView"; private Handler mUiHandler; // Reference to UI thread private View mView; private Context mContext; private ImageView mImage; private TextView mText; private View mButton; private TextView mButtonText; private View mProgress; private Drawable mInitializing; private Drawable mError; private List<Drawable> mSpeakNow; private float mVolume = 0.0f; private int mLevel = 0; private enum State {LISTENING, WORKING, READY} private State mState = State.READY; private float mMinMicrophoneLevel; private float mMaxMicrophoneLevel; /** Updates the microphone icon to show user their volume.*/ private Runnable mUpdateVolumeRunnable = new Runnable() { public void run() { if (mState != State.LISTENING) { return; } final float min = mMinMicrophoneLevel; final float max = mMaxMicrophoneLevel; final int maxLevel = mSpeakNow.size() - 1; int index = (int) ((mVolume - min) / (max - min) * maxLevel); final int level = Math.min(Math.max(0, index), maxLevel); if (level != mLevel) { mImage.setImageDrawable(mSpeakNow.get(level)); mLevel = level; } mUiHandler.postDelayed(mUpdateVolumeRunnable, 50); } }; public RecognitionView(Context context, OnClickListener clickListener) { mUiHandler = new Handler(); LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE); mView = inflater.inflate(R.layout.recognition_status, null); ContentResolver cr = context.getContentResolver(); mMinMicrophoneLevel = SettingsUtil.getSettingsFloat( cr, SettingsUtil.LATIN_IME_MIN_MICROPHONE_LEVEL, 15.f); mMaxMicrophoneLevel = SettingsUtil.getSettingsFloat( cr, SettingsUtil.LATIN_IME_MAX_MICROPHONE_LEVEL, 30.f); // Pre-load volume level images Resources r = context.getResources(); mSpeakNow = new ArrayList<Drawable>(); mSpeakNow.add(r.getDrawable(R.drawable.speak_now_level0)); mSpeakNow.add(r.getDrawable(R.drawable.speak_now_level1)); mSpeakNow.add(r.getDrawable(R.drawable.speak_now_level2)); mSpeakNow.add(r.getDrawable(R.drawable.speak_now_level3)); mSpeakNow.add(r.getDrawable(R.drawable.speak_now_level4)); mSpeakNow.add(r.getDrawable(R.drawable.speak_now_level5)); mSpeakNow.add(r.getDrawable(R.drawable.speak_now_level6)); mInitializing = r.getDrawable(R.drawable.mic_slash); mError = r.getDrawable(R.drawable.caution); mImage = (ImageView) mView.findViewById(R.id.image); mButton = mView.findViewById(R.id.button); mButton.setOnClickListener(clickListener); mText = (TextView) mView.findViewById(R.id.text); mButtonText = (TextView) mView.findViewById(R.id.button_text); mProgress = mView.findViewById(R.id.progress); mContext = context; } public View getView() { return mView; } public void restoreState() { mUiHandler.post(new Runnable() { public void run() { // Restart the spinner if (mState == State.WORKING) { ((ProgressBar)mProgress).setIndeterminate(false); ((ProgressBar)mProgress).setIndeterminate(true); } } }); } public void showInitializing() { mUiHandler.post(new Runnable() { public void run() { prepareDialog(false, mContext.getText(R.string.voice_initializing), mInitializing, mContext.getText(R.string.cancel)); } }); } public void showListening() { mUiHandler.post(new Runnable() { public void run() { mState = State.LISTENING; prepareDialog(false, mContext.getText(R.string.voice_listening), mSpeakNow.get(0), mContext.getText(R.string.cancel)); } }); mUiHandler.postDelayed(mUpdateVolumeRunnable, 50); } public void updateVoiceMeter(final float rmsdB) { mVolume = rmsdB; } public void showError(final String message) { mUiHandler.post(new Runnable() { public void run() { mState = State.READY; prepareDialog(false, message, mError, mContext.getText(R.string.ok)); } }); } public void showWorking( final ByteArrayOutputStream waveBuffer, final int speechStartPosition, final int speechEndPosition) { mUiHandler.post(new Runnable() { public void run() { mState = State.WORKING; prepareDialog(true, mContext.getText(R.string.voice_working), null, mContext .getText(R.string.cancel)); final ShortBuffer buf = ByteBuffer.wrap(waveBuffer.toByteArray()).order( ByteOrder.nativeOrder()).asShortBuffer(); buf.position(0); waveBuffer.reset(); showWave(buf, speechStartPosition / 2, speechEndPosition / 2); } }); } private void prepareDialog(boolean spinVisible, CharSequence text, Drawable image, CharSequence btnTxt) { if (spinVisible) { mProgress.setVisibility(View.VISIBLE); mImage.setVisibility(View.GONE); } else { mProgress.setVisibility(View.GONE); mImage.setImageDrawable(image); mImage.setVisibility(View.VISIBLE); } mText.setText(text); mButtonText.setText(btnTxt); } /** * @return an average abs of the specified buffer. */ private static int getAverageAbs(ShortBuffer buffer, int start, int i, int npw) { int from = start + i * npw; int end = from + npw; int total = 0; for (int x = from; x < end; x++) { total += Math.abs(buffer.get(x)); } return total / npw; } /** * Shows waveform of input audio. * * Copied from version in VoiceSearch's RecognitionActivity. * * TODO: adjust stroke width based on the size of data. * TODO: use dip rather than pixels. */ private void showWave(ShortBuffer waveBuffer, int startPosition, int endPosition) { final int w = ((View) mImage.getParent()).getWidth(); final int h = mImage.getHeight(); if (w <= 0 || h <= 0) { // view is not visible this time. Skip drawing. return; } final Bitmap b = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); final Canvas c = new Canvas(b); final Paint paint = new Paint(); paint.setColor(0xFFFFFFFF); // 0xAARRGGBB paint.setAntiAlias(true); paint.setStyle(Paint.Style.STROKE); paint.setAlpha(0x90); final PathEffect effect = new CornerPathEffect(3); paint.setPathEffect(effect); final int numSamples = waveBuffer.remaining(); int endIndex; if (endPosition == 0) { endIndex = numSamples; } else { endIndex = Math.min(endPosition, numSamples); } int startIndex = startPosition - 2000; // include 250ms before speech if (startIndex < 0) { startIndex = 0; } final int numSamplePerWave = 200; // 8KHz 25ms = 200 samples final float scale = 10.0f / 65536.0f; final int count = (endIndex - startIndex) / numSamplePerWave; final float deltaX = 1.0f * w / count; int yMax = h / 2 - 8; Path path = new Path(); c.translate(0, yMax); float x = 0; path.moveTo(x, 0); for (int i = 0; i < count; i++) { final int avabs = getAverageAbs(waveBuffer, startIndex, i , numSamplePerWave); int sign = ( (i & 01) == 0) ? -1 : 1; final float y = Math.min(yMax, avabs * h * scale) * sign; path.lineTo(x, y); x += deltaX; path.lineTo(x, y); } if (deltaX > 4) { paint.setStrokeWidth(3); } else { paint.setStrokeWidth(Math.max(1, (int) (deltaX -.05))); } c.drawPath(path, paint); mImage.setImageBitmap(b); mImage.setVisibility(View.VISIBLE); MarginLayoutParams mProgressParams = (MarginLayoutParams)mProgress.getLayoutParams(); mProgressParams.topMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, -h , mContext.getResources().getDisplayMetrics()); // Tweak the padding manually to fill out the whole view horizontally. // TODO: Do this in the xml layout instead. ((View) mImage.getParent()).setPadding(4, ((View) mImage.getParent()).getPaddingTop(), 3, ((View) mImage.getParent()).getPaddingBottom()); mProgress.setLayoutParams(mProgressParams); } public void finish() { mUiHandler.post(new Runnable() { public void run() { mState = State.READY; exitWorking(); } }); } private void exitWorking() { mProgress.setVisibility(View.GONE); mImage.setVisibility(View.VISIBLE); } }
Java
/* * Copyright (C) 2008-2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.android.inputmethod.voice; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import java.io.ByteArrayOutputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.ShortBuffer; /** * Utility class to draw a waveform into a bitmap, given a byte array * that represents the waveform as a sequence of 16-bit integers. * Adapted from RecognitionActivity.java. */ public class WaveformImage { private static final int SAMPLING_RATE = 8000; private WaveformImage() {} public static Bitmap drawWaveform( ByteArrayOutputStream waveBuffer, int w, int h, int start, int end) { final Bitmap b = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); final Canvas c = new Canvas(b); final Paint paint = new Paint(); paint.setColor(0xFFFFFFFF); // 0xRRGGBBAA paint.setAntiAlias(true); paint.setStrokeWidth(0); final ShortBuffer buf = ByteBuffer .wrap(waveBuffer.toByteArray()) .order(ByteOrder.nativeOrder()) .asShortBuffer(); buf.position(0); final int numSamples = waveBuffer.size() / 2; final int delay = (SAMPLING_RATE * 100 / 1000); int endIndex = end / 2 + delay; if (end == 0 || endIndex >= numSamples) { endIndex = numSamples; } int index = start / 2 - delay; if (index < 0) { index = 0; } final int size = endIndex - index; int numSamplePerPixel = 32; int delta = size / (numSamplePerPixel * w); if (delta == 0) { numSamplePerPixel = size / w; delta = 1; } final float scale = 3.5f / 65536.0f; // do one less column to make sure we won't read past // the buffer. try { for (int i = 0; i < w - 1 ; i++) { final float x = i; for (int j = 0; j < numSamplePerPixel; j++) { final short s = buf.get(index); final float y = (h / 2) - (s * h * scale); c.drawPoint(x, y, paint); index += delta; } } } catch (IndexOutOfBoundsException e) { // this can happen, but we don't care } return b; } }
Java
package mypackage.forfun; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ViewFlipper; public class flipActivity extends Activity { ViewFlipper flipper; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.flipper); flipper = (ViewFlipper) findViewById(R.id.details); Button btn = (Button) findViewById(R.id.flip_me); btn.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { flipper.showNext(); } }); } }
Java
package mypackage.forfun; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Iterator; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.webkit.WebView; import android.widget.Button; public class WebkitDemo extends Activity { WebView browser; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); browser = (WebView) findViewById(R.id.webview); browser.loadUrl("http://www2.leboncoin.fr/ar/form/0?ca=15_s&id=328084729"); // not working.... // browser.loadDataWithBaseURL("file:///android_asset/page.html", // null,"text/html", "utf-8", null); /* try { String textFromCSS=getTextFromRessourceId(R.raw.css); HashMap<String, String> map=new HashMap<String, String>(); map.put("style", textFromCSS); String textFromPage=getTextFromRessourceWithValues(R.raw.page,map); browser.getSettings().setJavaScriptEnabled(true); String textFromPage = getTextFromRessourceId(R.raw.form); browser.loadData(textFromPage, "text/html", "UTF-8"); } catch (IOException e1) { e1.printStackTrace(); } */ } public String getTextFromRessourceWithValues(int idRessource, HashMap<String, String> map) throws IOException { return replaceValuesFromMapAndText(getTextFromRessourceId(idRessource), map); } public String replaceValuesFromMapAndText(String sources, HashMap<String, String> map) { Iterator<String> keys = map.keySet().iterator(); String key = ""; while (keys.hasNext()) { key = keys.next(); sources = sources.replace("${" + key + "}", map.get(key)); } return sources; } public String getTextFromRessourceId(int idRessource) throws IOException { InputStream inputStream = getResources().openRawResource(idRessource); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); int i = inputStream.read(); while (i != -1) { byteArrayOutputStream.write(i); i = inputStream.read(); } inputStream.close(); return byteArrayOutputStream.toString(); } public void push(View view) { browser.loadUrl("javascript:submitform()"); } }
Java
package mypackage.forfun; import android.app.Activity; import android.os.Bundle; import android.widget.TabHost; public class tabhost extends Activity { @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.tabhost); TabHost tabs = (TabHost) findViewById(R.id.tabhost); tabs.setup(); TabHost.TabSpec spec = tabs.newTabSpec("tag1"); spec.setContent(R.id.tab1); spec.setIndicator("Horloge"); tabs.addTab(spec); spec = tabs.newTabSpec("tag2"); spec.setContent(R.id.tab2); spec.setIndicator("Bouton"); tabs.addTab(spec); spec = tabs.newTabSpec("tag3"); spec.setContent(R.id.tab3); spec.setIndicator("Bouton 2"); tabs.addTab(spec); tabs.setCurrentTab(0); } }
Java
package mypackage.forfun; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.ViewFlipper; public class AndroidFunActivity extends Activity { private TextView textview=null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.playwithmenu); textview = (TextView) findViewById(R.id.textView1); } @Override public boolean onCreateOptionsMenu(Menu menu) { new MenuInflater(getApplication()).inflate(R.menu.testmenu, menu); return (super.onCreateOptionsMenu(menu)); } @Override public boolean onOptionsItemSelected(MenuItem item) { textview.setText(item.getTitle().toString()); return (super.onOptionsItemSelected(item)); } }
Java
package mypackage.forfun; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.AnalogClock; import android.widget.Button; import android.widget.TabHost; public class tabHostDynamic extends Activity { @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.tabdynamic); final TabHost tabs = (TabHost) findViewById(R.id.tabhost); tabs.setup(); TabHost.TabSpec spec = tabs.newTabSpec("buttontab"); spec.setContent(R.id.buttontab); spec.setIndicator("Bouton"); tabs.addTab(spec); Button btn = (Button) tabs.getCurrentView() .findViewById(R.id.buttontab); btn.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { TabHost.TabSpec spec = tabs.newTabSpec("tag1"); spec.setContent(new TabHost.TabContentFactory() { public View createTabContent(String tag) { return (new AnalogClock(tabHostDynamic.this)); } }); spec.setIndicator("Horloge"); tabs.addTab(spec); } }); } }
Java
/** Automatically generated file. DO NOT MODIFY */ package mypackage.forfun; public final class BuildConfig { public final static boolean DEBUG = true; }
Java
package org.mines.douai.j2ee.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import org.apache.cxf.interceptor.LoggingInInterceptor; import org.apache.cxf.interceptor.LoggingOutInterceptor; import org.apache.cxf.jaxws.JaxWsProxyFactoryBean; import org.mines.douai.j2ee.webservices.WeatherWebService; @WebServlet(name = "SimpleWeather", urlPatterns = { "/SimpleWeather" }) public class SimpleWeatherServlet extends HttpServlet { public void service (ServletRequest request, ServletResponse response) throws IOException,ServletException { //Get the temperature value from the webservice JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean(); factory.getInInterceptors().add(new LoggingInInterceptor()); factory.getOutFaultInterceptors().add(new LoggingOutInterceptor()); factory.setServiceClass(WeatherWebService.class); factory.setAddress("http://localhost:9000/TpWebService/services/WeatherWebServiceImplPort"); WeatherWebService client = (WeatherWebService) factory.create(); String usa = client.getWeatherValue("us"); String france = client.getWeatherValue("fr"); String angleterre = client.getWeatherValue("en"); // generation of the view response.setContentType("text/html");// Type MIME java.io.PrintWriter out = response.getWriter(); out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"><html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"fr\" lang=\"fr\">" + "<head>" + "<title>Tp servlet 1</title>" + "</head>" + "<body>"); out.println("<p>Aux Etats-Unis il fait "+usa+"</p>"); out.println("<p>En France il fait "+france+"</p>"); out.println("<p>En Angleterre il fait "+angleterre+"</p>"); out.println("</body>"); out.println("</html>"); } }
Java
package org.mines.douai.j2ee.webservices; import javax.jws.WebParam; import javax.jws.WebService; @WebService public interface WeatherWebService { public String getWeatherValue(@WebParam(name="country")String country); }
Java
package org.mines.douai.j2ee.webservices; import javax.xml.ws.Endpoint; public class Server { protected Server() throws Exception { // START SNIPPET: publish System.out.println("Starting Server"); WeatherWebServiceImpl implementor = new WeatherWebServiceImpl(); String address = "http://localhost:9090/weatherWebService"; Endpoint.publish(address, implementor); // END SNIPPET: publish } public static void main(String args[]) throws Exception { new Server(); System.out.println("Server ready..."); Thread.sleep(5 * 60 * 1000); System.out.println("Server exiting"); System.exit(0); } }
Java
package org.mines.douai.j2ee.webservices; import org.apache.cxf.interceptor.LoggingInInterceptor; import org.apache.cxf.interceptor.LoggingOutInterceptor; import org.apache.cxf.jaxws.JaxWsProxyFactoryBean; public class WeatherWebServiceConsumer { public static void main(String[] args) { JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean(); factory.getInInterceptors().add(new LoggingInInterceptor()); factory.getOutFaultInterceptors().add(new LoggingOutInterceptor()); factory.setServiceClass(WeatherWebService.class); factory.setAddress("http://localhost:9090/weatherWebService"); WeatherWebService client = (WeatherWebService) factory.create(); String reply = client.getWeatherValue("us"); System.out.println("Server said: " + reply); System.exit(0); } }
Java
package org.mines.douai.j2ee.cxf; import org.apache.cxf.interceptor.LoggingInInterceptor; import org.apache.cxf.interceptor.LoggingOutInterceptor; import org.apache.cxf.jaxws.JaxWsProxyFactoryBean; public class HelloWorldConsumer { public static void main(String[] args) { JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean(); factory.getInInterceptors().add(new LoggingInInterceptor()); factory.getOutFaultInterceptors().add(new LoggingOutInterceptor()); factory.setServiceClass(HelloWorld.class); //factory.setAddress("http://localhost:8080/TpWebService/services/HelloWorldImplPort"); factory.setAddress("http://localhost:54218/WCFService1/Service.svc"); HelloWorld client = (HelloWorld) factory.create(); String reply = client.sayHi("ifbfqibfqi"); System.out.println("Server said: " + reply); System.exit(0); } }
Java
package org.mines.douai.j2ee.cxf; import javax.xml.ws.Endpoint; public class HelloWorldPublisher { public static void main(String[] args) { System.out.println("Starting Server"); HelloWorldImpl implementor= new HelloWorldImpl(); String address="http://localhost:9999/helloWorld"; Endpoint.publish(address, implementor); } }
Java
package org.mines.douai.j2ee.cxf; import javax.jws.WebService; @WebService(endpointInterface="org.mines.douai.j2ee.cxf.HelloWorld",serviceName="HelloWorld") public class HelloWorldImpl implements HelloWorld{ @Override public String sayHi(String text) { System.out.println("sayHi called"); return "Hello " + text; } }
Java
package org.mines.douai.j2ee.cxf; import javax.jws.WebParam; import javax.jws.WebService; @WebService public interface HelloWorld{ String sayHi(@WebParam(name="text")String text); }
Java
package parse; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URI; import java.util.ArrayList; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; public class CustomHttpClient { /** The time it takes for our client to timeout */ public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds /** Single instance of our HttpClient */ private static HttpClient mHttpClient; /** * Get our single instance of our HttpClient object. * * @return an HttpClient object with connection parameters set */ private static HttpClient getHttpClient() { if (mHttpClient == null) { mHttpClient = new DefaultHttpClient(); final HttpParams params = mHttpClient.getParams(); HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT); HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT); } return mHttpClient; } /** * Performs an HTTP Post request to the specified url with the specified * parameters. * * @param url * The web address to post the request to * @param postParameters * The parameters to send via the request * @return The result of the request * @throws Exception */ public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception { BufferedReader in = null; try { HttpClient client = getHttpClient(); HttpPost request = new HttpPost(url); UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity( postParameters); request.setEntity(formEntity); HttpResponse response = client.execute(request); in = new BufferedReader(new InputStreamReader(response.getEntity() .getContent())); StringBuffer sb = new StringBuffer(""); String line = ""; String NL = System.getProperty("line.separator"); while ((line = in.readLine()) != null) { sb.append(line + NL); } in.close(); String result = sb.toString(); return result; } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } } /** * Performs an HTTP GET request to the specified url. * * @param url * The web address to post the request to * @return The result of the request * @throws Exception */ public static String executeHttpGet(String url) throws Exception { BufferedReader in = null; try { HttpClient client = getHttpClient(); HttpGet request = new HttpGet(); request.setURI(new URI(url)); HttpResponse response = client.execute(request); in = new BufferedReader(new InputStreamReader(response.getEntity() .getContent())); StringBuffer sb = new StringBuffer(""); String line = ""; String NL = System.getProperty("line.separator"); while ((line = in.readLine()) != null) { sb.append(line + NL); } in.close(); String result = sb.toString(); return result; } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
Java
//package parse; // //import java.io.IOException; //import java.net.MalformedURLException; // //import android.content.Context; //import android.graphics.drawable.Drawable; //import android.os.Handler; //import android.os.Handler.Callback; //import android.os.Message; //import android.util.AttributeSet; //import android.view.View; //import android.widget.ImageView; //import android.widget.LinearLayout; //import android.widget.ProgressBar; // ///** // * Free for anyone to use, just say thanks and share :-) // * @author Blundell // * // */ //public class LoaderImageView extends LinearLayout{ // // private static final int COMPLETE = 0; // private static final int FAILED = 1; // // private Context mContext; // private Drawable mDrawable; // private ProgressBar mSpinner; // private ImageView mImage; // // /** // * This is used when creating the view in XML // * To have an image load in XML use the tag 'image="http://developer.android.com/images/dialog_buttons.png"' // * Replacing the url with your desired image // * Once you have instantiated the XML view you can call // * setImageDrawable(url) to change the image // * @param context // * @param attrSet // */ // public LoaderImageView(final Context context, final AttributeSet attrSet) { // super(context, attrSet); // final String url = attrSet.getAttributeValue(null, "image"); // if(url != null){ // instantiate(context, url); // } else { // instantiate(context, null); // } // } // // /** // * This is used when creating the view programatically // * Once you have instantiated the view you can call // * setImageDrawable(url) to change the image // * @param context the Activity context // * @param imageUrl the Image URL you wish to load // */ // public LoaderImageView(final Context context, final String imageUrl) { // super(context); // instantiate(context, imageUrl); // } // // /** // * First time loading of the LoaderImageView // * Sets up the LayoutParams of the view, you can change these to // * get the required effects you want // */ // private void instantiate(final Context context, final String imageUrl) { // mContext = context; // // mImage = new ImageView(mContext); // mImage.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); // // mSpinner = new ProgressBar(mContext); // mSpinner.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); // // mSpinner.setIndeterminate(true); // // addView(mSpinner); // addView(mImage); // // if(imageUrl != null){ // setImageDrawable(imageUrl); // } // } // // /** // * Set's the view's drawable, this uses the internet to retrieve the image // * don't forget to add the correct permissions to your manifest // * @param imageUrl the url of the image you wish to load // */ // public void setImageDrawable(final String imageUrl) { // mDrawable = null; // mSpinner.setVisibility(View.VISIBLE); // mImage.setVisibility(View.GONE); // new Thread(){ // public void run() { // try { // mDrawable = getDrawableFromUrl(imageUrl); // imageLoadedHandler.sendEmptyMessage(COMPLETE); // } catch (MalformedURLException e) { // imageLoadedHandler.sendEmptyMessage(FAILED); // } catch (IOException e) { // imageLoadedHandler.sendEmptyMessage(FAILED); // } // }; // }.start(); // } // // /** // * Callback that is received once the image has been downloaded // */ // private final Handler imageLoadedHandler = new Handler(new Callback() { // @Override // public boolean handleMessage(Message msg) { // switch (msg.what) { // case COMPLETE: // mImage.setImageDrawable(mDrawable); // mImage.setVisibility(View.VISIBLE); // mSpinner.setVisibility(View.GONE); // break; // case FAILED: // default: // // Could change image here to a 'failed' image // // otherwise will just keep on spinning // break; // } // return true; // } // }); // // /** // * Pass in an image url to get a drawable object // * @return a drawable object // * @throws IOException // * @throws MalformedURLException // */ // private static Drawable getDrawableFromUrl(final String url) throws IOException, MalformedURLException { // return Drawable.createFromStream(((java.io.InputStream)new java.net.URL(url).getContent()), "name"); // } // //}
Java
//package parse; // //import android.app.Activity; //import android.os.Bundle; //import android.view.Gravity; //import android.view.View; //import android.widget.Button; //import android.widget.LinearLayout; //import android.widget.LinearLayout.LayoutParams; // //public class ImageExample extends Activity { // // private final String images[] = {"http://developer.android.com/images/dialog_custom.png", "http://developer.android.com/images/dialog_progress_bar.png"}; // private int i = 0; // // /** Called when the activity is first created. */ // @Override // public void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // final LinearLayout main = new LinearLayout(this); // main.setOrientation(LinearLayout.VERTICAL); // main.setGravity(Gravity.CENTER); // main.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); // // final Button loadImage = new Button(this); // loadImage.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); // loadImage.setText("Load Image"); // // main.addView(loadImage); // // final LoaderImageView image = new LoaderImageView(this, getAnImageUrl()); // image.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); // // main.addView(image); // // loadImage.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // image.setImageDrawable(getAnImageUrl()); // } // }); // // setContentView(main); // } // // private String getAnImageUrl() { // i++; // if(i >= images.length){ // i = 0; // } // return images[i]; // } //}
Java
package model.domain; public class Owner { private String name; private PhoneNumber phoneNumber; public String getName() { return name; } public void setName(String name) { this.name = name; } public PhoneNumber getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(PhoneNumber phoneNumber) { this.phoneNumber = phoneNumber; } }
Java
package model.domain; import java.util.ArrayList; import java.util.List; public class Category { public Category(String name, List<Category> child, boolean isRoot) { super(); this.name = name; this.child = child; this.isRoot = isRoot; } private String name; private List<Category> child = new ArrayList<Category>(); private Boolean isRoot; private List<Integer> listPrices = new ArrayList<Integer>(); public List<Integer> getListPrices() { return listPrices; } public void setListPrices(List<Integer> listPrices) { this.listPrices = listPrices; } public Boolean isRoot() { return isRoot; } public void setIsRoot(Boolean isRoot) { this.isRoot = isRoot; } public List<Category> getChild() { return child; } public void setChild(List<Category> child) { this.child = child; } public void setName(String name) { this.name = name; } public String getName() { return name; } }
Java
package model.domain; public class PhoneNumber { private String phoneNumber; public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public boolean isImage() { return isImage; } public void setImage(boolean isImage) { this.isImage = isImage; } private boolean isImage; @Override public String toString() { return phoneNumber; } }
Java
package model.domain; import java.util.ArrayList; import java.util.List; public class Region implements Comparable<Region> { public Region(String name, List<Department> departments) { super(); this.name = name; this.departments = departments; } public Region(String name) { this.setName(name); } private String name; private List<Department> departments = new ArrayList<Department>(); public void setName(String name) { this.name = name; } public String getName() { return name; } public void setDepartments(List<Department> departments) { this.departments = departments; } public List<Department> getDepartments() { return departments; } public void addDepartment(Department depart) { this.getDepartments().add(depart); } @Override public int compareTo(Region o) { return this.getName().compareTo(o.getName()); } }
Java
package model.domain; public class Department { public Department(String name, int number, Region region) { super(); this.name = name; this.number = number; this.region = region; } private Region region; private String name; private int number; public void setName(String name) { this.name = name; } public String getName() { return name; } public void setNumber(int number) { this.number = number; } public int getNumber() { return number; } public void setRegion(Region region) { this.region = region; } public Region getRegion() { return region; } }
Java
package model.domain; import java.util.ArrayList; import java.util.List; public class Country { public Country() { } public Country(String name) { this.setName(name); } private String name; private List<Region> regions = new ArrayList<Region>(); public List<Region> getRegions() { return regions; } public void setRegions(List<Region> regions) { this.regions = regions; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
Java
package model.domain; import java.util.List; import model.advertisers.Advertiser; public class Advert { private double id; private String date; private String name; private String price; private String currency; private String category; private String town; private String postalCode; private String department; private String hyperlinkDetail; private String hyperlinkPicture; private String hyperlinkPictureHD; private String detail; private Owner owner; private String urlContact; private Advertiser advertiser; public String toString() { String result = "advertiser: " + this.getAdvertiser() + "\nid: " + this.getId() + "\ndate: " + this.getDate() + "\nname: " + this.getName() + "\nhyperlinkPicture: " + this.getHyperlinkPicture() + "\nhyperlink: " + this.getHyperlinkDetail() + "\nPrix: " + this.getPrice() + "\nDepart: " + this.getDepartment() + "\nVille: " + this.getTown() + "\nCategory: " + this.getCategory(); if (getDetail() != null) { String detail = this.getDetail(); String postalCode = this.getPostalCode(); String ownerName = this.getOwner().getName(); String urlContact = this.getUrlContact(); String pictureHD = this.getHyperlinkPictureHD(); String phoneNumber = null; if (this.getOwner().getPhoneNumber() != null) { phoneNumber = this.getOwner().getPhoneNumber().toString(); } result = result + "\npostalCode: " + postalCode + "\nownerName: " + ownerName + "\nphoneNumber: " + phoneNumber + "\nurlContact: " + urlContact + "\npictureHD: " + pictureHD + " \ndetail: " + detail; } result = result + "\n--------------------------------------------------------"; return result; } public void reparseAllAtributes() { this.setName(this.getAdvertiser().reparse(this.getName())); this.setDepartment(this.getAdvertiser().reparse(this.getDepartment())); this.setTown(this.getAdvertiser().reparse(this.getTown())); this.setCategory(this.getAdvertiser().reparse(this.getCategory())); } public static Advert findById(List<Advert> adverts, double id) { for (Advert advert : adverts) { if (advert.getId() == id) { return advert; } } return null; } public double getId() { return id; } public void setId(double id) { this.id = id; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public void setName(String name) { this.name = name; } public String getName() { return name; } public void setCurrency(String currency) { this.currency = currency; } public String getCurrency() { return currency; } public void setHyperlinkDetail(String hyperlinkDetail) { this.hyperlinkDetail = hyperlinkDetail; } public String getHyperlinkDetail() { return hyperlinkDetail; } public void setHyperlinkPicture(String hyperlinkPicture) { this.hyperlinkPicture = hyperlinkPicture; } public String getHyperlinkPicture() { return hyperlinkPicture; } public void setDepartment(String department) { this.department = department; } public String getDepartment() { return department; } public void setTown(String town) { this.town = town; } public String getTown() { return town; } public void setCategory(String category) { this.category = category; } public String getCategory() { return category; } public void setPrice(String price) { this.price = price; } public String getPrice() { return price; } public Advertiser getAdvertiser() { return advertiser; } public void setAdvertiser(Advertiser advertiser) { this.advertiser = advertiser; } public Advert getMoreDetail() { return this.getAdvertiser().findDetails(this); } public String getDetail() { return detail; } public void setDetail(String detail) { this.detail = detail; } public Owner getOwner() { return owner; } public void setOwner(Owner owner) { this.owner = owner; } public String getUrlContact() { return urlContact; } public void setUrlContact(String urlContact) { this.urlContact = urlContact; } public String getPostalCode() { return postalCode; } public void setPostalCode(String postalCode) { this.postalCode = postalCode; } public String getHyperlinkPictureHD() { return hyperlinkPictureHD; } public void setHyperlinkPictureHD(String hyperlinkPictureHD) { this.hyperlinkPictureHD = hyperlinkPictureHD; } }
Java
package model.advertisers; import java.util.List; import model.advertisers.reference.AdvertiserReference; import model.domain.Advert; public abstract class Advertiser { private AdvertiserReference advertiserReference; private int currentPage; private String location; private String kind; private String category; private String keyWord; // todo price Min and Max private Integer min; private Integer max; private boolean lastPageReached; private String name; private String pathPicture; public Advertiser() { } public void setName(String name) { this.name = name; } public String getName() { return name; } public void setPathPicture(String pathPicture) { this.pathPicture = pathPicture; } public String getPathPicture() { return pathPicture; } public abstract String getUrlRoot(); public abstract String getUrlResearch(); public abstract String findContentForOnePage(); public abstract List<Advert> findAdvertsForOnePage(String allTheContent); public abstract List<Advert> findMoreAdverts(); public abstract List<Advert> findAdverts(); public abstract Advert findDetails(Advert advert); public abstract boolean isLastPage(char[] allChar); public abstract String reparse(String source); public abstract String sendMail(Advert advert, String nameSender, String mailSender, String message); public int getCurrentPage() { return currentPage; } public void setCurrentPage(int currentPage) { this.currentPage = currentPage; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getKind() { return kind; } public void setKind(String kind) { this.kind = kind; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public String getKeyWord() { return keyWord; } public void setKeyWord(String keyWord) { this.keyWord = keyWord; } public boolean isLastPageReached() { return lastPageReached; } public void setLastPageReached(boolean lastPageReached) { this.lastPageReached = lastPageReached; } public AdvertiserReference getAdvertiserReference() { return this.advertiserReference; } public void setAdvertiserReference(AdvertiserReference advertiserReference) { this.advertiserReference = advertiserReference; } public Integer getMin() { return min; } public void setMin(Integer min) { this.min = min; } public Integer getMax() { return max; } public void setMax(Integer max) { this.max = max; } }
Java
package model.advertisers.reference; import model.reference.Categories; import model.reference.Departments; import model.reference.Regions; public class LeboncoinReference extends AdvertiserReference { public LeboncoinReference() { this.getCategories().put(Categories.ALL.getName(), ""); this.getCategories().put(Categories.CAR.getName(), "voitures"); this.getCategories().put(Categories.MOTORBIKE.getName(), "motos"); this.getCategories().put(Categories.CARAVAN.getName(), "caravaning"); this.getCategories().put(Categories.BOATING.getName(), "nautisme"); this.getCategories().put(Categories.ALL_CAR.getName(), "_vehicules_"); this.getCategories().put(Categories.HOUSE.getName(), "_maison_"); this.getCategories().put(Categories.COMPUTER.getName(), "informatique"); this.getCategories().put(Categories.GAME.getName(), "consoles_jeux_video"); this.getCategories().put(Categories.PHONE.getName(), "telephonie"); this.getCategories().put(Categories.ALL_MULTIMEDIA.getName(), "_multimedia_"); this.getCategories().put(Categories.ANIMALS.getName(), "animaux"); this.getCategories().put(Categories.WINE.getName(), "vins_gastronomie"); this.getCategories().put(Categories.MUSICAL_INSTRUMENT.getName(), "instruments_de_musique"); this.getCategories().put(Categories.GAME_TOY.getName(), "jeux_jouets"); this.getCategories().put(Categories.HOBBIES.getName(), "_loisirs_"); this.getCategories() .put(Categories.JOBS.getName(), "_emploi_services_"); this.getCategories().put(Categories.LESSONS.getName(), "cours_particuliers"); this.getCategories().put(Categories.BUILDING_SALES.getName(), "ventes_immobilieres"); this.getCategories().put(Categories.BUILDING_RENT.getName(), "locations"); this.getCategories().put(Categories.BUILDING_COLOCATION.getName(), "colocations"); this.getCategories().put(Categories.BUILDING_HOLIDAY_RENT.getName(), "locations_de_vacances"); this.getCategories().put(Categories.BUILDING.getName(), "_immobilier_"); this.getLocalisation().put(Regions.ALL.getName(), ""); this.getLocalisation().put(Regions.ALSACE.getName(), "alsace"); this.getLocalisation().put(Regions.AQUITAINE.getName(), "aquitaine"); this.getLocalisation().put(Regions.AUVERGNE.getName(), "auvergne"); this.getLocalisation().put(Regions.BASSE_NORMANDIE.getName(), "basse_normandie"); this.getLocalisation().put(Regions.BOURGOGNE.getName(), "bourgogne"); this.getLocalisation().put(Regions.BRETAGNE.getName(), "bretagne"); this.getLocalisation().put(Regions.CENTRE.getName(), "centre"); this.getLocalisation().put(Regions.CHAMPAGNE_ARDENNE.getName(), "champagne_ardenne"); this.getLocalisation().put(Regions.CORSE.getName(), "corse"); this.getLocalisation().put(Regions.FRANCHE_COMTE.getName(), "franche_comte"); this.getLocalisation().put(Regions.HAUTE_NORMANDIE.getName(), "haute_normandie"); this.getLocalisation().put(Regions.ILE_DE_FRANCE.getName(), "ile_de_france"); this.getLocalisation().put(Regions.LANGUEDOC_ROUSSILLON.getName(), "languedoc_roussillon"); this.getLocalisation().put(Regions.LIMOUSIN.getName(), "limousin"); this.getLocalisation().put(Regions.LORRAINE.getName(), "lorraine"); this.getLocalisation().put(Regions.MIDI_PYRENEES.getName(), "midi_pyrenees"); this.getLocalisation().put(Regions.NORD_PAS_DE_CALAIS.getName(), "nord_pas_de_calais"); this.getLocalisation().put(Regions.PAYS_DE_LA_LOIRE.getName(), "pays_de_la_loire"); this.getLocalisation().put(Regions.PICARDIE.getName(), "picardie"); this.getLocalisation().put(Regions.POITOU_CHARENTES.getName(), "poitou_charentes"); this.getLocalisation().put( Regions.PROVENCE_ALPES_COTE_D_AZUR.getName(), "provence_alpes_cote_d_azur"); this.getLocalisation() .put(Regions.RHONE_ALPES.getName(), "rhone_alpes"); this.getLocalisation().put(Regions.GUADELOUPE.getName(), "guadeloupe"); this.getLocalisation().put(Regions.MARTINIQUE.getName(), "martinique"); this.getLocalisation().put(Regions.GUYANE.getName(), "guyane"); this.getLocalisation().put(Regions.REUNION.getName(), "reunion"); this.getLocalisation().put(Departments.AIN.getName(), "ain"); this.getLocalisation().put(Departments.AISNE.getName(), "aisne"); this.getLocalisation().put(Departments.ALLIER.getName(), "allier"); this.getLocalisation().put( Departments.ALPES_DE_HAUTES_PROVENCE.getName(), "alpes_de_hautes_provence"); this.getLocalisation().put(Departments.HAUTES_ALPES.getName(), "hautes_alpes"); this.getLocalisation().put(Departments.ALPES_MARITIMES.getName(), "alpes_maritimes"); this.getLocalisation().put(Departments.ARDECHE.getName(), "ardeche"); this.getLocalisation().put(Departments.ARDENNES.getName(), "ardennes"); this.getLocalisation().put(Departments.ARIEGE.getName(), "ariege"); this.getLocalisation().put(Departments.AUBE.getName(), "aube"); this.getLocalisation().put(Departments.AUDE.getName(), "aude"); this.getLocalisation().put(Departments.AVEYRON.getName(), "aveyron"); this.getLocalisation().put(Departments.BOUCHES_DU_RHONE.getName(), "bouches_du_rhone"); this.getLocalisation().put(Departments.CALVADOS.getName(), "calvados"); this.getLocalisation().put(Departments.CANTAL.getName(), "cantal"); this.getLocalisation().put(Departments.CHARENTE.getName(), "charente"); this.getLocalisation().put(Departments.CHARENTE_MARITIME.getName(), "charente_maritime"); this.getLocalisation().put(Departments.CHER.getName(), "cher"); this.getLocalisation().put(Departments.CORREZE.getName(), "correze"); this.getLocalisation().put(Departments.CORSE_DU_SUD.getName(), "corse_du_sud"); this.getLocalisation().put(Departments.HAUTE_CORSE.getName(), "haute_corse"); this.getLocalisation() .put(Departments.COTE_D_OR.getName(), "cote_d_or"); this.getLocalisation().put(Departments.COTES_D_ARMOR.getName(), "cotes_d_armor"); this.getLocalisation().put(Departments.CREUSE.getName(), "creuse"); this.getLocalisation().put(Departments.DORDOGNE.getName(), "dordogne"); this.getLocalisation().put(Departments.DOUBS.getName(), "doubs"); this.getLocalisation().put(Departments.DROME.getName(), "drome"); this.getLocalisation().put(Departments.EURE.getName(), "eure"); this.getLocalisation().put(Departments.EURE_ET_LOIR.getName(), "eure_et_loir"); this.getLocalisation() .put(Departments.FINISTERE.getName(), "finistere"); this.getLocalisation().put(Departments.GARD.getName(), "gard"); this.getLocalisation().put(Departments.HAUTE_GARONNE.getName(), "haute_garonne"); this.getLocalisation().put(Departments.GERS.getName(), "gers"); this.getLocalisation().put(Departments.GIRONDE.getName(), "gironde"); this.getLocalisation().put(Departments.HERAULT.getName(), "herault"); this.getLocalisation().put(Departments.ILLE_ET_VILAINE.getName(), "ille_et_vilaine"); this.getLocalisation().put(Departments.INDRE.getName(), "indre"); this.getLocalisation().put(Departments.INDRE_ET_LOIRE.getName(), "indre_et_loire"); this.getLocalisation().put(Departments.ISERE.getName(), "isere"); this.getLocalisation().put(Departments.JURA.getName(), "jura"); this.getLocalisation().put(Departments.LANDES.getName(), "landes"); this.getLocalisation().put(Departments.LOIR_ET_CHER.getName(), "loir_et_cher"); this.getLocalisation().put(Departments.LOIRE.getName(), "loire"); this.getLocalisation().put(Departments.HAUTE_LOIRE.getName(), "haute_loire"); this.getLocalisation().put(Departments.LOIRE_ATLANTIQUE.getName(), "loire_atlantique"); this.getLocalisation().put(Departments.LOIRET.getName(), "loiret"); this.getLocalisation().put(Departments.LOT.getName(), "lot"); this.getLocalisation().put(Departments.LOT_ET_GARONNE.getName(), "lot_et_garonne"); this.getLocalisation().put(Departments.LOZERE.getName(), "lozere"); this.getLocalisation().put(Departments.MAINE_ET_LOIRE.getName(), "maine_et_loire"); this.getLocalisation().put(Departments.MANCHE.getName(), "manche"); this.getLocalisation().put(Departments.MARNE.getName(), "marne"); this.getLocalisation().put(Departments.HAUTE_MARNE.getName(), "haute_marne"); this.getLocalisation().put(Departments.MAYENNE.getName(), "mayenne"); this.getLocalisation().put(Departments.MEURTHE_ET_MOSELLE.getName(), "meurthe_et_moselle"); this.getLocalisation().put(Departments.MEUSE.getName(), "meuse"); this.getLocalisation().put(Departments.MORBIHAN.getName(), "morbihan"); this.getLocalisation().put(Departments.MOSELLE.getName(), "moselle"); this.getLocalisation().put(Departments.NIEVRE.getName(), "nievre"); this.getLocalisation().put(Departments.NORD.getName(), "nord"); this.getLocalisation().put(Departments.OISE.getName(), "oise"); this.getLocalisation().put(Departments.ORNE.getName(), "orne"); this.getLocalisation().put(Departments.PAS_DE_CALAIS.getName(), "pas_de_calais"); this.getLocalisation().put(Departments.PUY_DE_DOME.getName(), "puy_de_dome"); this.getLocalisation().put(Departments.PYRENEES_ATLANTIQUES.getName(), "pyrenees_atlantiques"); this.getLocalisation().put(Departments.HAUTES_PYRENEES.getName(), "hautes_pyrenees"); this.getLocalisation().put(Departments.PYRENEES_ORIENTALES.getName(), "pyrenees_orientales"); this.getLocalisation().put(Departments.BAS_RHIN.getName(), "bas_rhin"); this.getLocalisation() .put(Departments.HAUT_RHIN.getName(), "haut_rhin"); this.getLocalisation().put(Departments.RHONE.getName(), "rhone"); this.getLocalisation().put(Departments.HAUTE_SAONE.getName(), "haute_saone"); this.getLocalisation().put(Departments.SAONE_ET_LOIRE.getName(), "saone_et_loire"); this.getLocalisation().put(Departments.SARTHE.getName(), "sarthe"); this.getLocalisation().put(Departments.SAVOIE.getName(), "savoie"); this.getLocalisation().put(Departments.HAUTE_SAVOIE.getName(), "haute_savoie"); this.getLocalisation().put(Departments.PARIS.getName(), "paris"); this.getLocalisation().put(Departments.SEINE_MARITIME.getName(), "seine_maritime"); this.getLocalisation().put(Departments.SEINE_ET_MARNE.getName(), "seine_et_marne"); this.getLocalisation().put(Departments.YVELINES.getName(), "yvelines"); this.getLocalisation().put(Departments.DEUX_SEVRES.getName(), "deux_sevres"); this.getLocalisation().put(Departments.SOMME.getName(), "somme"); this.getLocalisation().put(Departments.TARN.getName(), "tarn"); this.getLocalisation().put(Departments.TARN_ET_GARONNE.getName(), "tarn_et_garonne"); this.getLocalisation().put(Departments.VAR.getName(), "var"); this.getLocalisation().put(Departments.VAUCLUSE.getName(), "vaucluse"); this.getLocalisation().put(Departments.VENDEE.getName(), "vendee"); this.getLocalisation().put(Departments.VIENNE.getName(), "vienne"); this.getLocalisation().put(Departments.HAUTE_VIENNE.getName(), "haute_vienne"); this.getLocalisation().put(Departments.VOSGES.getName(), "vosges"); this.getLocalisation().put(Departments.YONNE.getName(), "yonne"); this.getLocalisation().put(Departments.TERRITOIRE_DE_BELFORT.getName(), "territoire_de_belfort"); this.getLocalisation().put(Departments.ESSONNE.getName(), "essonne"); this.getLocalisation().put(Departments.HAUTS_DE_SEINE.getName(), "hauts_de_seine"); this.getLocalisation().put(Departments.SEINE_SAINT_DENIS.getName(), "seine_saint_denis"); this.getLocalisation().put(Departments.VAL_DE_MARNE.getName(), "val_de_marne"); this.getLocalisation().put(Departments.VAL_D_OISE.getName(), "val_d_oise"); } }
Java
package model.advertisers.reference; import java.util.HashMap; import java.util.Map; public abstract class AdvertiserReference { private Map<String, String> localisations = new HashMap<String, String>(); private Map<String, String> categories = new HashMap<String, String>(); private Map<String, String> prices = new HashMap<String, String>(); public Map<String, String> getPrices() { return prices; } public void setPrices(Map<String, String> prices) { this.prices = prices; } public Map<String, String> getCategories() { return categories; } public void setCategories(Map<String, String> categories) { this.categories = categories; } public Map<String, String> getLocalisation() { return localisations; } public void setLocalisation(Map<String, String> localisation) { this.localisations = localisation; } }
Java
package model.advertisers.reference; import model.reference.Categories; import model.reference.Departments; import model.reference.Regions; public class VivastreetReference extends AdvertiserReference { public VivastreetReference() { // TODO put all categories (just empty result for the search) this.getCategories().put(Categories.ALL.getName(), "search.vivastreet.com/"); this.getCategories().put(Categories.CAR.getName(), "annonces-voiture-occasion"); this.getCategories().put(Categories.MOTORBIKE.getName(), "annonce-moto-occasion"); this.getCategories() .put(Categories.CARAVAN.getName(), "annonces-caravane-camping-car"); this.getCategories().put(Categories.BOATING.getName(), "annonces-bateau-occasion"); this.getCategories().put(Categories.ALL_CAR.getName(), "annonces-voiture-occasion"); this.getCategories() .put(Categories.HOUSE.getName(), "annonces-achat-vente-appartement"); this.getCategories().put(Categories.COMPUTER.getName(), "informatique-pda"); this.getCategories().put(Categories.GAME.getName(), "consoles-jeux"); this.getCategories().put(Categories.PHONE.getName(), "achat-vente-portables"); this.getCategories().put(Categories.ALL_MULTIMEDIA.getName(), "multimedia"); this.getCategories().put(Categories.ANIMALS.getName(), "chien-chat"); this.getCategories().put(Categories.WINE.getName(), "produit-terroir"); this.getCategories().put(Categories.MUSICAL_INSTRUMENT.getName(), "vente-instruments-musique"); this.getCategories().put(Categories.GAME_TOY.getName(), "figurines"); this.getCategories().put(Categories.HOBBIES.getName(), "loisirs"); this.getCategories().put(Categories.JOBS.getName(), "annonces-emploi"); this.getCategories().put(Categories.LESSONS.getName(), "soutien-scolaire"); this.getCategories().put(Categories.BUILDING_SALES.getName(), "a-vendre"); this.getCategories() .put(Categories.BUILDING_RENT.getName(), "annonces-location-appartement"); this.getCategories().put(Categories.BUILDING_COLOCATION.getName(), "annonces-colocation"); this.getCategories().put(Categories.BUILDING_HOLIDAY_RENT.getName(), "annonces-location-vacances"); this.getCategories().put(Categories.BUILDING.getName(), "logement-neuf"); this.getLocalisation().put(Regions.ALL.getName(), ""); this.getLocalisation().put(Regions.ALSACE.getName(), "alsace/&searchGeoId=17292"); this.getLocalisation().put(Regions.AQUITAINE.getName(), "aquitaine/&searchGeoId=5622"); this.getLocalisation().put(Regions.AUVERGNE.getName(), "auvergne/&searchGeoId=18322"); this.getLocalisation().put(Regions.BASSE_NORMANDIE.getName(), "basse_normandie/&searchGeoId=31787"); this.getLocalisation().put(Regions.BOURGOGNE.getName(), "bourgogne/&searchGeoId=19683"); this.getLocalisation().put(Regions.BRETAGNE.getName(), "bretagne/&searchGeoId=12751"); this.getLocalisation().put(Regions.CENTRE.getName(), "centre/&searchGeoId=21841"); this.getLocalisation().put(Regions.CHAMPAGNE_ARDENNE.getName(), "champagne-ardenne/&searchGeoId=23765"); this.getLocalisation().put(Regions.CORSE.getName(), "corse/&searchGeoId=26017"); this.getLocalisation().put(Regions.FRANCHE_COMTE.getName(), "franche-comte/&searchGeoId=26444"); this.getLocalisation().put(Regions.HAUTE_NORMANDIE.getName(), "haute-normandie/&searchGeoId=33720"); this.getLocalisation().put(Regions.ILE_DE_FRANCE.getName(), "ile-de-france/&searchGeoId=2"); this.getLocalisation().put(Regions.LANGUEDOC_ROUSSILLON.getName(), "languedoc-roussillon/&searchGeoId=11131"); this.getLocalisation().put(Regions.LIMOUSIN.getName(), "limousin/&searchGeoId=28418"); this.getLocalisation().put(Regions.LORRAINE.getName(), "lorraine/&searchGeoId=29203"); this.getLocalisation().put(Regions.MIDI_PYRENEES.getName(), "midi-pyrenees/&searchGeoId=8015"); this.getLocalisation().put(Regions.NORD_PAS_DE_CALAIS.getName(), "nord-pas-de-calais/&searchGeoId=15699"); this.getLocalisation().put(Regions.PAYS_DE_LA_LOIRE.getName(), "pays-de-la-loire/&searchGeoId=14097"); this.getLocalisation().put(Regions.PICARDIE.getName(), "picardie/&searchGeoId=35221"); this.getLocalisation().put(Regions.POITOU_CHARENTES.getName(), "poitou-charentes/&searchGeoId=37604"); this.getLocalisation().put( Regions.PROVENCE_ALPES_COTE_D_AZUR.getName(), "paca/&searchGeoId=4523"); this.getLocalisation() .put(Regions.RHONE_ALPES.getName(), "rhone-alpes/&searchGeoId=1377"); this.getLocalisation().put(Regions.GUADELOUPE.getName(), "dom-tom/&searchGeoId=39211"); this.getLocalisation().put(Regions.MARTINIQUE.getName(), "dom-tom/&searchGeoId=39211"); this.getLocalisation().put(Regions.GUYANE.getName(), "dom-tom/&searchGeoId=39211"); this.getLocalisation().put(Regions.REUNION.getName(), "dom-tom/&searchGeoId=39211"); this.getLocalisation().put(Departments.AIN.getName(), "ain"); this.getLocalisation().put(Departments.AISNE.getName(), "aisne"); this.getLocalisation().put(Departments.ALLIER.getName(), "allier"); this.getLocalisation().put( Departments.ALPES_DE_HAUTES_PROVENCE.getName(), "alpes-de-hautes-provence"); this.getLocalisation().put(Departments.HAUTES_ALPES.getName(), "hautes-alpes"); this.getLocalisation().put(Departments.ALPES_MARITIMES.getName(), "alpes-maritimes"); this.getLocalisation().put(Departments.ARDECHE.getName(), "ardeche"); this.getLocalisation().put(Departments.ARDENNES.getName(), "ardennes"); this.getLocalisation().put(Departments.ARIEGE.getName(), "ariege"); this.getLocalisation().put(Departments.AUBE.getName(), "aube"); this.getLocalisation().put(Departments.AUDE.getName(), "aude"); this.getLocalisation().put(Departments.AVEYRON.getName(), "aveyron"); this.getLocalisation().put(Departments.BOUCHES_DU_RHONE.getName(), "bouches-du-rhone"); this.getLocalisation().put(Departments.CALVADOS.getName(), "calvados"); this.getLocalisation().put(Departments.CANTAL.getName(), "cantal"); this.getLocalisation().put(Departments.CHARENTE.getName(), "charente"); this.getLocalisation().put(Departments.CHARENTE_MARITIME.getName(), "charente-maritime"); this.getLocalisation().put(Departments.CHER.getName(), "cher"); this.getLocalisation().put(Departments.CORREZE.getName(), "correze"); this.getLocalisation().put(Departments.CORSE_DU_SUD.getName(), "corse-du-sud"); this.getLocalisation().put(Departments.HAUTE_CORSE.getName(), "haute-corse"); this.getLocalisation() .put(Departments.COTE_D_OR.getName(), "cote-d-or"); this.getLocalisation().put(Departments.COTES_D_ARMOR.getName(), "cotes-d-armor"); this.getLocalisation().put(Departments.CREUSE.getName(), "creuse"); this.getLocalisation().put(Departments.DORDOGNE.getName(), "dordogne"); this.getLocalisation().put(Departments.DOUBS.getName(), "doubs"); this.getLocalisation().put(Departments.DROME.getName(), "drome"); this.getLocalisation().put(Departments.EURE.getName(), "eure"); this.getLocalisation().put(Departments.EURE_ET_LOIR.getName(), "eure-et-loir"); this.getLocalisation() .put(Departments.FINISTERE.getName(), "finistere"); this.getLocalisation().put(Departments.GARD.getName(), "gard"); this.getLocalisation().put(Departments.HAUTE_GARONNE.getName(), "haute-garonne"); this.getLocalisation().put(Departments.GERS.getName(), "gers"); this.getLocalisation().put(Departments.GIRONDE.getName(), "gironde"); this.getLocalisation().put(Departments.HERAULT.getName(), "herault"); this.getLocalisation().put(Departments.ILLE_ET_VILAINE.getName(), "ille-et-vilaine"); this.getLocalisation().put(Departments.INDRE.getName(), "indre"); this.getLocalisation().put(Departments.INDRE_ET_LOIRE.getName(), "indre-et-loire"); this.getLocalisation().put(Departments.ISERE.getName(), "isere"); this.getLocalisation().put(Departments.JURA.getName(), "jura"); this.getLocalisation().put(Departments.LANDES.getName(), "landes"); this.getLocalisation().put(Departments.LOIR_ET_CHER.getName(), "loir-et-cher"); this.getLocalisation().put(Departments.LOIRE.getName(), "loire"); this.getLocalisation().put(Departments.HAUTE_LOIRE.getName(), "haute-loire"); this.getLocalisation().put(Departments.LOIRE_ATLANTIQUE.getName(), "loire-atlantique"); this.getLocalisation().put(Departments.LOIRET.getName(), "loiret"); this.getLocalisation().put(Departments.LOT.getName(), "lot"); this.getLocalisation().put(Departments.LOT_ET_GARONNE.getName(), "lot-et-garonne"); this.getLocalisation().put(Departments.LOZERE.getName(), "lozere"); this.getLocalisation().put(Departments.MAINE_ET_LOIRE.getName(), "maine-et-loire"); this.getLocalisation().put(Departments.MANCHE.getName(), "manche"); this.getLocalisation().put(Departments.MARNE.getName(), "marne"); this.getLocalisation().put(Departments.HAUTE_MARNE.getName(), "haute-marne"); this.getLocalisation().put(Departments.MAYENNE.getName(), "mayenne"); this.getLocalisation().put(Departments.MEURTHE_ET_MOSELLE.getName(), "meurthe-et-moselle"); this.getLocalisation().put(Departments.MEUSE.getName(), "meuse"); this.getLocalisation().put(Departments.MORBIHAN.getName(), "morbihan"); this.getLocalisation().put(Departments.MOSELLE.getName(), "moselle"); this.getLocalisation().put(Departments.NIEVRE.getName(), "nievre"); this.getLocalisation().put(Departments.NORD.getName(), "nord"); this.getLocalisation().put(Departments.OISE.getName(), "oise"); this.getLocalisation().put(Departments.ORNE.getName(), "orne"); this.getLocalisation().put(Departments.PAS_DE_CALAIS.getName(), "pas-de-calais"); this.getLocalisation().put(Departments.PUY_DE_DOME.getName(), "puy-de-dome"); this.getLocalisation().put(Departments.PYRENEES_ATLANTIQUES.getName(), "pyrenees-atlantiques"); this.getLocalisation().put(Departments.HAUTES_PYRENEES.getName(), "hautes-pyrenees"); this.getLocalisation().put(Departments.PYRENEES_ORIENTALES.getName(), "pyrenees-orientales"); this.getLocalisation().put(Departments.BAS_RHIN.getName(), "bas-rhin"); this.getLocalisation() .put(Departments.HAUT_RHIN.getName(), "haut-rhin"); this.getLocalisation().put(Departments.RHONE.getName(), "rhone"); this.getLocalisation().put(Departments.HAUTE_SAONE.getName(), "haute-saone"); this.getLocalisation().put(Departments.SAONE_ET_LOIRE.getName(), "saone-et-loire"); this.getLocalisation().put(Departments.SARTHE.getName(), "sarthe"); this.getLocalisation().put(Departments.SAVOIE.getName(), "savoie"); this.getLocalisation().put(Departments.HAUTE_SAVOIE.getName(), "haute-savoie"); this.getLocalisation().put(Departments.PARIS.getName(), "paris"); this.getLocalisation().put(Departments.SEINE_MARITIME.getName(), "seine-maritime"); this.getLocalisation().put(Departments.SEINE_ET_MARNE.getName(), "seine-et-marne"); this.getLocalisation().put(Departments.YVELINES.getName(), "yvelines"); this.getLocalisation().put(Departments.DEUX_SEVRES.getName(), "deux-sevres"); this.getLocalisation().put(Departments.SOMME.getName(), "somme"); this.getLocalisation().put(Departments.TARN.getName(), "tarn"); this.getLocalisation().put(Departments.TARN_ET_GARONNE.getName(), "tarn-et-garonne"); this.getLocalisation().put(Departments.VAR.getName(), "var"); this.getLocalisation().put(Departments.VAUCLUSE.getName(), "vaucluse"); this.getLocalisation().put(Departments.VENDEE.getName(), "vendee"); this.getLocalisation().put(Departments.VIENNE.getName(), "vienne"); this.getLocalisation().put(Departments.HAUTE_VIENNE.getName(), "haute-vienne"); this.getLocalisation().put(Departments.VOSGES.getName(), "vosges"); this.getLocalisation().put(Departments.YONNE.getName(), "yonne"); this.getLocalisation().put(Departments.TERRITOIRE_DE_BELFORT.getName(), "territoire-de-belfort"); this.getLocalisation().put(Departments.ESSONNE.getName(), "essonne"); this.getLocalisation().put(Departments.HAUTS_DE_SEINE.getName(), "hauts-de-seine"); this.getLocalisation().put(Departments.SEINE_SAINT_DENIS.getName(), "seine-saint-denis"); this.getLocalisation().put(Departments.VAL_DE_MARNE.getName(), "val-de-marne"); this.getLocalisation().put(Departments.VAL_D_OISE.getName(), "val-d-oise"); } }
Java
package model.reference.price; import java.util.ArrayList; import java.util.List; public class Prices { public List<String> PRICES_LIST = new ArrayList<String>(); }
Java
package model.reference.price; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class CarPrices { // take care about 0 and + public static final List<Integer> CAR_PRICES_LIST = new ArrayList<Integer>( Arrays.asList(500, 1000, 1500, 2000, 2500, 3000, 4000, 5000, 7500, 10000, 15000, 20000, 30000, 50000)); }
Java
package model.reference; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import model.domain.Category; public class Categories { // ALL public final static Category ALL = new Category("Toutes", null, true); // Vehicules public final static Category CAR = new Category("Voitures", null, false); public final static Category MOTORBIKE = new Category("Motos", null, false); public final static Category CARAVAN = new Category("Caravanes", null, false); public final static Category BOATING = new Category("Nautisme", null, false); public final static Category ALL_CAR = new Category("Vehicules", new ArrayList<Category>(Arrays.asList(CAR, MOTORBIKE, CARAVAN, BOATING)), true); // House public final static Category HOUSE = new Category("Maison", null, true); // Multimedia public final static Category COMPUTER = new Category("Informatique", null, false); public final static Category GAME = new Category("JeuxVideo", null, false); public final static Category PHONE = new Category("Telephonie", null, false); public final static Category ALL_MULTIMEDIA = new Category("Multimedia", new ArrayList<Category>(Arrays.asList(COMPUTER, GAME, PHONE)), true); // Hobbies public final static Category ANIMALS = new Category("Animaux", null, false); public final static Category WINE = new Category("Vin & Gastronomie", null, false); public final static Category MUSICAL_INSTRUMENT = new Category( "Instrument de musique", null, false); public final static Category GAME_TOY = new Category("Jeux & Jouets", null, false); public final static Category HOBBIES = new Category("Loisirs", new ArrayList<Category>(Arrays.asList(ANIMALS, WINE, MUSICAL_INSTRUMENT, GAME_TOY)), true); // Jobs public final static Category JOBS = new Category("Emploi", null, true); // Lessons public final static Category LESSONS = new Category("Cours", null, true); // Building public final static Category BUILDING_SALES = new Category("Ventes", null, false); public final static Category BUILDING_RENT = new Category("Locations", null, false); public final static Category BUILDING_COLOCATION = new Category( "Colocations", null, false); public final static Category BUILDING_HOLIDAY_RENT = new Category( "Locations Vacance", null, false); public final static Category BUILDING = new Category( "Immobilier", new ArrayList<Category>(Arrays.asList(BUILDING_SALES, BUILDING_RENT, BUILDING_COLOCATION, BUILDING_HOLIDAY_RENT)), true); // public static final List<Category> CATEGORIES_LIST = new ArrayList<Category>( Arrays.asList(ALL, CAR, MOTORBIKE, CARAVAN, BOATING, ALL_CAR, HOUSE, COMPUTER, GAME, PHONE, ALL_MULTIMEDIA, ANIMALS, WINE, MUSICAL_INSTRUMENT, GAME_TOY, HOBBIES, JOBS, LESSONS, BUILDING_SALES, BUILDING_RENT, BUILDING_COLOCATION, BUILDING_HOLIDAY_RENT, BUILDING)); }
Java
package activities.sample; import model.advertisers.Advertiser; import model.advertisers.Leboncoin; import model.domain.Advert; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.widget.TextView; public class SendToHyperlink extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // setContentView(R.layout.main); } public void myClickHandler(View view) { String url = "http://www.google.fr"; Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(url)); startActivity(i); } }
Java
package activities.sample; import android.app.Activity; import android.objects.LoaderImageView; import android.os.Bundle; import android.view.Gravity; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; public class ImageExample extends Activity { private final String images[] = {"http://developer.android.com/images/dialog_custom.png", "http://developer.android.com/images/dialog_progress_bar.png"}; private int i = 0; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final LinearLayout main = new LinearLayout(this); main.setOrientation(LinearLayout.VERTICAL); main.setGravity(Gravity.CENTER); main.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); final Button loadImage = new Button(this); loadImage.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); loadImage.setText("Load Image"); main.addView(loadImage); final LoaderImageView image = new LoaderImageView(this, getAnImageUrl()); image.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); main.addView(image); loadImage.setOnClickListener(new View.OnClickListener() { //@Override public void onClick(View v) { image.setImageDrawable(getAnImageUrl()); } }); setContentView(main); } private String getAnImageUrl() { i++; if(i >= images.length){ i = 0; } return images[i]; } }
Java
package android.objects; import java.io.IOException; import java.net.MalformedURLException; import android.content.Context; import android.graphics.drawable.Drawable; import android.os.Handler; import android.os.Handler.Callback; import android.os.Message; import android.util.AttributeSet; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; /** * Free for anyone to use, just say thanks and share :-) * @author Blundell * */ public class LoaderImageView extends LinearLayout{ private static final int COMPLETE = 0; private static final int FAILED = 1; private Context mContext; private Drawable mDrawable; private ProgressBar mSpinner; private ImageView mImage; /** * This is used when creating the view in XML * To have an image load in XML use the tag 'image="http://developer.android.com/images/dialog_buttons.png"' * Replacing the url with your desired image * Once you have instantiated the XML view you can call * setImageDrawable(url) to change the image * @param context * @param attrSet */ public LoaderImageView(final Context context, final AttributeSet attrSet) { super(context, attrSet); final String url = attrSet.getAttributeValue(null, "image"); if(url != null){ instantiate(context, url); } else { instantiate(context, null); } } /** * This is used when creating the view programatically * Once you have instantiated the view you can call * setImageDrawable(url) to change the image * @param context the Activity context * @param imageUrl the Image URL you wish to load */ public LoaderImageView(final Context context, final String imageUrl) { super(context); instantiate(context, imageUrl); } /** * First time loading of the LoaderImageView * Sets up the LayoutParams of the view, you can change these to * get the required effects you want */ private void instantiate(final Context context, final String imageUrl) { mContext = context; mImage = new ImageView(mContext); mImage.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); mSpinner = new ProgressBar(mContext); mSpinner.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); mSpinner.setIndeterminate(true); addView(mSpinner); addView(mImage); if(imageUrl != null){ setImageDrawable(imageUrl); } } /** * Set's the view's drawable, this uses the internet to retrieve the image * don't forget to add the correct permissions to your manifest * @param imageUrl the url of the image you wish to load */ public void setImageDrawable(final String imageUrl) { mDrawable = null; mSpinner.setVisibility(View.VISIBLE); mImage.setVisibility(View.GONE); new Thread(){ public void run() { try { mDrawable = getDrawableFromUrl(imageUrl); imageLoadedHandler.sendEmptyMessage(COMPLETE); } catch (MalformedURLException e) { imageLoadedHandler.sendEmptyMessage(FAILED); } catch (IOException e) { imageLoadedHandler.sendEmptyMessage(FAILED); } }; }.start(); } /** * Callback that is received once the image has been downloaded */ private final Handler imageLoadedHandler = new Handler(new Callback() { public boolean handleMessage(Message msg) { switch (msg.what) { case COMPLETE: mImage.setImageDrawable(mDrawable); mImage.setVisibility(View.VISIBLE); mSpinner.setVisibility(View.GONE); break; case FAILED: default: // Could change image here to a 'failed' image // otherwise will just keep on spinning break; } return true; } }); /** * Pass in an image url to get a drawable object * @return a drawable object * @throws IOException * @throws MalformedURLException */ private static Drawable getDrawableFromUrl(final String url) throws IOException, MalformedURLException { return Drawable.createFromStream(((java.io.InputStream)new java.net.URL(url).getContent()), "name"); } }
Java
package android.objects; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Picture; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.Region; import android.graphics.RegionIterator; import android.graphics.drawable.Drawable; import android.graphics.drawable.PictureDrawable; import android.view.View; public class SampleView extends View { private final Paint mPaint = new Paint(); private final Rect mRect1 = new Rect(); private final Rect mRect2 = new Rect(); public SampleView(Context context) { super(context); setFocusable(true); mPaint.setAntiAlias(true); mPaint.setTextSize(16); mPaint.setTextAlign(Paint.Align.CENTER); mRect1.set(10, 10, 100, 80); mRect2.set(50, 50, 130, 110); } private void drawOriginalRects(Canvas canvas, int alpha) { mPaint.setStyle(Paint.Style.STROKE); mPaint.setColor(Color.RED); mPaint.setAlpha(alpha); drawCentered(canvas, mRect1, mPaint); mPaint.setColor(Color.BLUE); mPaint.setAlpha(alpha); drawCentered(canvas, mRect2, mPaint); // restore style mPaint.setStyle(Paint.Style.FILL); } private void drawRgn(Canvas canvas, int color, String str, Region.Op op) { if (str != null) { mPaint.setColor(Color.BLACK); canvas.drawText(str, 80, 24, mPaint); } Region rgn = new Region(); rgn.set(mRect1); rgn.op(mRect2, op); mPaint.setColor(color); RegionIterator iter = new RegionIterator(rgn); Rect r = new Rect(); canvas.translate(0, 30); mPaint.setColor(color); while (iter.next(r)) { canvas.drawRect(r, mPaint); } drawOriginalRects(canvas, 0x80); } private static void drawCentered(Canvas c, Rect r, Paint p) { float inset = p.getStrokeWidth() * 0.5f; if (inset == 0) { // catch hairlines inset = 0.5f; } c.drawRect(r.left + inset, r.top + inset, r.right - inset, r.bottom - inset, p); } @Override protected void onDraw(Canvas canvas) { canvas.drawColor(Color.GRAY); canvas.save(); canvas.translate(80, 5); drawOriginalRects(canvas, 0xFF); canvas.restore(); mPaint.setStyle(Paint.Style.FILL); canvas.save(); canvas.translate(0, 140); drawRgn(canvas, Color.RED, "Union", Region.Op.UNION); canvas.restore(); canvas.save(); canvas.translate(0, 280); drawRgn(canvas, Color.BLUE, "Xor", Region.Op.XOR); canvas.restore(); canvas.save(); canvas.translate(160, 140); drawRgn(canvas, Color.GREEN, "Difference", Region.Op.DIFFERENCE); canvas.restore(); canvas.save(); canvas.translate(160, 280); drawRgn(canvas, Color.WHITE, "Intersect", Region.Op.INTERSECT); canvas.restore(); } }
Java