aboutsummaryrefslogtreecommitdiff
path: root/vendor
diff options
context:
space:
mode:
authorPaul Mundt <paul.mundt@adaptant.io>2016-05-12 13:15:33 +0000
committerFelix Hanley <felix@userspace.com.au>2016-05-12 13:15:33 +0000
commitbb8476ffe78210d1a4c0b4bbee6da99da1bc15c5 (patch)
tree5a70f855509889e02ea6df60d0b0fac208ee6f49 /vendor
parenta3a77dbd4ec45c17687d3e42dab551db59c93ca3 (diff)
downloadgo-dict2rest-bb8476ffe78210d1a4c0b4bbee6da99da1bc15c5.tar.gz
go-dict2rest-bb8476ffe78210d1a4c0b4bbee6da99da1bc15c5.tar.bz2
Inhibit repeated handling of requests through context-aware middleware chains (#3)
* Squashed 'vendor/src/github.com/alexedwards/stack/' content from commit a4c0268 git-subtree-dir: vendor/src/github.com/alexedwards/stack git-subtree-split: a4c0268505f12934376d6d8fdca232416861e271 * Use context-aware handler chains to limit repeated handling Presently each middleware must advance through the handler chain to reach the router endpoint. In the case of multiple compressors (gzip, deflate) we need to be able to walk through the chain without additional processing of already handled requests. This implements some simple iteration logic based on request context that we pass down the chain. Signed-off-by: Paul Mundt <paul.mundt@adaptant.io>
Diffstat (limited to 'vendor')
-rw-r--r--vendor/src/github.com/alexedwards/stack/.travis.yml8
-rw-r--r--vendor/src/github.com/alexedwards/stack/LICENSE20
-rw-r--r--vendor/src/github.com/alexedwards/stack/README.md187
-rw-r--r--vendor/src/github.com/alexedwards/stack/context.go55
-rw-r--r--vendor/src/github.com/alexedwards/stack/context_test.go48
-rw-r--r--vendor/src/github.com/alexedwards/stack/stack.go94
-rw-r--r--vendor/src/github.com/alexedwards/stack/stack_test.go126
7 files changed, 538 insertions, 0 deletions
diff --git a/vendor/src/github.com/alexedwards/stack/.travis.yml b/vendor/src/github.com/alexedwards/stack/.travis.yml
new file mode 100644
index 0000000..70eed36
--- /dev/null
+++ b/vendor/src/github.com/alexedwards/stack/.travis.yml
@@ -0,0 +1,8 @@
+sudo: false
+language: go
+go:
+ - 1.1
+ - 1.2
+ - 1.3
+ - 1.4
+ - tip \ No newline at end of file
diff --git a/vendor/src/github.com/alexedwards/stack/LICENSE b/vendor/src/github.com/alexedwards/stack/LICENSE
new file mode 100644
index 0000000..f25a33b
--- /dev/null
+++ b/vendor/src/github.com/alexedwards/stack/LICENSE
@@ -0,0 +1,20 @@
+The MIT License (MIT)
+
+Copyright (c) 2014 Alex Edwards
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software is furnished to do so,
+subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
+COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
+IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/vendor/src/github.com/alexedwards/stack/README.md b/vendor/src/github.com/alexedwards/stack/README.md
new file mode 100644
index 0000000..ba689f6
--- /dev/null
+++ b/vendor/src/github.com/alexedwards/stack/README.md
@@ -0,0 +1,187 @@
+# Stack <br> [![Build Status](https://travis-ci.org/alexedwards/stack.svg?branch=master)](https://travis-ci.org/alexedwards/stack) [![Coverage](http://gocover.io/_badge/github.com/alexedwards/stack?0)](http://gocover.io/github.com/alexedwards/stack) [![GoDoc](http://godoc.org/github.com/alexedwards/stack?status.png)](http://godoc.org/github.com/alexedwards/stack)
+
+Stack provides an easy way to chain your HTTP middleware and handlers together and to pass request-scoped context between them. It's essentially a context-aware version of [Alice](https://github.com/justinas/alice).
+
+[Skip to the example &rsaquo;](#example)
+
+### Usage
+
+#### Making a chain
+
+Middleware chains are constructed with [`stack.New()`](http://godoc.org/github.com/alexedwards/stack#New):
+
+```go
+stack.New(middlewareOne, middlewareTwo, middlewareThree)
+```
+
+You can also store middleware chains as variables, and then [`Append()`](http://godoc.org/github.com/alexedwards/stack#Chain.Append) to them:
+
+```go
+stdStack := stack.New(middlewareOne, middlewareTwo)
+extStack := stdStack.Append(middlewareThree, middlewareFour)
+```
+
+Your middleware should have the signature `func(*stack.Context, http.Handler) http.Handler`. For example:
+
+```go
+func middlewareOne(ctx *stack.Context, next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ // do something middleware-ish, accessing ctx
+ next.ServeHTTP(w, r)
+ })
+}
+```
+
+You can also use middleware with the signature `func(http.Handler) http.Handler` by adapting it with [`stack.Adapt()`](http://godoc.org/github.com/alexedwards/stack#Adapt). For example, if you had the middleware:
+
+```go
+func middlewareTwo(next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ // do something else middleware-ish
+ next.ServeHTTP(w, r)
+ })
+}
+```
+
+You can add it to a chain like this:
+
+```go
+stack.New(middlewareOne, stack.Adapt(middlewareTwo), middlewareThree)
+```
+
+See the [codes samples](#code-samples) for real-life use of third-party middleware with Stack.
+
+#### Adding an application handler
+
+Application handlers should have the signature `func(*stack.Context, http.ResponseWriter, *http.Request)`. You add them to the end of a middleware chain with the [`Then()`](http://godoc.org/github.com/alexedwards/stack#Chain.Then) method.
+
+So an application handler like this:
+
+```go
+func appHandler(ctx *stack.Context, w http.ResponseWriter, r *http.Request) {
+ // do something handler-ish, accessing ctx
+}
+```
+
+Is added to the end of a middleware chain like this:
+
+```go
+stack.New(middlewareOne, middlewareTwo).Then(appHandler)
+```
+
+For convenience [`ThenHandler()`](http://godoc.org/github.com/alexedwards/stack#Chain.ThenHandler) and [`ThenHandlerFunc()`](http://godoc.org/github.com/alexedwards/stack#Chain.ThenHandlerFunc) methods are also provided. These allow you to finish a chain with a standard `http.Handler` or `http.HandlerFunc` respectively.
+
+For example, you could use a standard `http.FileServer` as the application handler:
+
+```go
+fs := http.FileServer(http.Dir("./static/"))
+http.Handle("/", stack.New(middlewareOne, middlewareTwo).ThenHandler(fs))
+```
+
+Once a chain is 'closed' with any of these methods it is converted into a [`HandlerChain`](http://godoc.org/github.com/alexedwards/stack#HandlerChain) object which satisfies the `http.Handler` interface, and can be used with the `http.DefaultServeMux` and many other routers.
+
+#### Using context
+
+Request-scoped data (or *context*) can be passed through the chain by storing it in `stack.Context`. This is implemented as a pointer to a `map[string]interface{}` and scoped to the goroutine executing the current HTTP request. Operations on `stack.Context` are protected by a mutex, so if you need to pass the context pointer to another goroutine (say for logging or completing a background process) it is safe for concurrent use.
+
+Data is added with [`Context.Put()`](http://godoc.org/github.com/alexedwards/stack#Context.Put). The first parameter is a string (which acts as a key) and the second is the value you need to store. For example:
+
+```go
+func middlewareOne(ctx *stack.Context, next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ ctx.Put("token", "c9e452805dee5044ba520198628abcaa")
+ next.ServeHTTP(w, r)
+ })
+}
+```
+
+You retrieve data with [`Context.Get()`](http://godoc.org/github.com/alexedwards/stack#Context.Get). Remember to type assert the returned value into the type you're expecting.
+
+```go
+func appHandler(ctx *stack.Context, w http.ResponseWriter, r *http.Request) {
+ token, ok := ctx.Get("token").(string)
+ if !ok {
+ http.Error(w, http.StatusText(500), 500)
+ return
+ }
+ fmt.Fprintf(w, "Token is: %s", token)
+}
+```
+
+Note that `Context.Get()` will return `nil` if a key does not exist. If you need to tell the difference between a key having a `nil` value and it explicitly not existing, please check with [`Context.Exists()`](http://godoc.org/github.com/alexedwards/stack#Context.Exists).
+
+Keys (and their values) can be deleted with [`Context.Delete()`](http://godoc.org/github.com/alexedwards/stack#Context.Delete).
+
+#### Injecting context
+
+It's possible to inject values into `stack.Context` during a request cycle but *before* the chain starts to be executed. This is useful if you need to inject parameters from a router into the context.
+
+The [`Inject()`](http://godoc.org/github.com/alexedwards/stack#Inject) function returns a new copy of the chain containing the injected context. You should make sure that you use this new copy &ndash; not the original &ndash; for subsequent processing.
+
+Here's an example of a wrapper for injecting [httprouter](https://github.com/julienschmidt/httprouter) params into the context:
+
+```go
+func InjectParams(hc stack.HandlerChain) httprouter.Handle {
+ return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
+ newHandlerChain := stack.Inject(hc, "params", ps)
+ newHandlerChain.ServeHTTP(w, r)
+ }
+}
+```
+
+A full example is available in the [code samples](#code-samples).
+
+### Example
+
+```go
+package main
+
+import (
+ "net/http"
+ "github.com/alexedwards/stack"
+ "fmt"
+)
+
+func main() {
+ stk := stack.New(token, stack.Adapt(language))
+
+ http.Handle("/", stk.Then(final))
+
+ http.ListenAndServe(":3000", nil)
+}
+
+func token(ctx *stack.Context, next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ ctx.Put("token", "c9e452805dee5044ba520198628abcaa")
+ next.ServeHTTP(w, r)
+ })
+}
+
+func language(next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Language", "en-gb")
+ next.ServeHTTP(w, r)
+ })
+}
+
+func final(ctx *stack.Context, w http.ResponseWriter, r *http.Request) {
+ token, ok := ctx.Get("token").(string)
+ if !ok {
+ http.Error(w, http.StatusText(500), 500)
+ return
+ }
+ fmt.Fprintf(w, "Token is: %s", token)
+}
+```
+
+### Code samples
+
+* [Integrating with httprouter](https://gist.github.com/alexedwards/4d20c505f389597c3360)
+* *More to follow*
+
+### TODO
+
+- Add more code samples (using 3rd party middleware)
+- Make a `chain.Merge()` method
+- Mirror master in v1 branch (and mention gopkg.in in README)
+- Add benchmarks
diff --git a/vendor/src/github.com/alexedwards/stack/context.go b/vendor/src/github.com/alexedwards/stack/context.go
new file mode 100644
index 0000000..07afe21
--- /dev/null
+++ b/vendor/src/github.com/alexedwards/stack/context.go
@@ -0,0 +1,55 @@
+package stack
+
+import (
+ "sync"
+)
+
+type Context struct {
+ mu sync.RWMutex
+ m map[string]interface{}
+}
+
+func NewContext() *Context {
+ m := make(map[string]interface{})
+ return &Context{m: m}
+}
+
+func (c *Context) Get(key string) interface{} {
+ if !c.Exists(key) {
+ return nil
+ }
+ c.mu.RLock()
+ defer c.mu.RUnlock()
+ return c.m[key]
+}
+
+func (c *Context) Put(key string, val interface{}) *Context {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ c.m[key] = val
+ return c
+}
+
+func (c *Context) Delete(key string) *Context {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ delete(c.m, key)
+ return c
+}
+
+func (c *Context) Exists(key string) bool {
+ c.mu.RLock()
+ defer c.mu.RUnlock()
+ _, ok := c.m[key]
+ return ok
+}
+
+func (c *Context) copy() *Context {
+ nc := NewContext()
+ c.mu.RLock()
+ defer c.mu.RUnlock()
+ for k, v := range c.m {
+ nc.m[k] = v
+ }
+ return nc
+}
diff --git a/vendor/src/github.com/alexedwards/stack/context_test.go b/vendor/src/github.com/alexedwards/stack/context_test.go
new file mode 100644
index 0000000..469200e
--- /dev/null
+++ b/vendor/src/github.com/alexedwards/stack/context_test.go
@@ -0,0 +1,48 @@
+package stack
+
+import "testing"
+
+func TestGet(t *testing.T) {
+ ctx := NewContext()
+ ctx.m["flip"] = "flop"
+ ctx.m["bish"] = nil
+
+ val := ctx.Get("flip")
+ assertEquals(t, "flop", val)
+
+ val = ctx.Get("bish")
+ assertEquals(t, nil, val)
+}
+
+func TestPut(t *testing.T) {
+ ctx := NewContext()
+
+ ctx.Put("bish", "bash")
+ assertEquals(t, "bash", ctx.m["bish"])
+}
+
+func TestDelete(t *testing.T) {
+ ctx := NewContext()
+ ctx.m["flip"] = "flop"
+
+ ctx.Delete("flip")
+ assertEquals(t, nil, ctx.m["flip"])
+}
+
+func TestCopy(t *testing.T) {
+ ctx := NewContext()
+ ctx.m["flip"] = "flop"
+
+ ctx2 := ctx.copy()
+ ctx2.m["bish"] = "bash"
+ assertEquals(t, nil, ctx.m["bish"])
+ assertEquals(t, "bash", ctx2.m["bish"])
+}
+
+func TestExists(t *testing.T) {
+ ctx := NewContext()
+ ctx.m["flip"] = "flop"
+
+ assertEquals(t, true, ctx.Exists("flip"))
+ assertEquals(t, false, ctx.Exists("bash"))
+}
diff --git a/vendor/src/github.com/alexedwards/stack/stack.go b/vendor/src/github.com/alexedwards/stack/stack.go
new file mode 100644
index 0000000..47c42b2
--- /dev/null
+++ b/vendor/src/github.com/alexedwards/stack/stack.go
@@ -0,0 +1,94 @@
+package stack
+
+import "net/http"
+
+type chainHandler func(*Context) http.Handler
+type chainMiddleware func(*Context, http.Handler) http.Handler
+
+type Chain struct {
+ mws []chainMiddleware
+ h chainHandler
+}
+
+func New(mws ...chainMiddleware) Chain {
+ return Chain{mws: mws}
+}
+
+func (c Chain) Append(mws ...chainMiddleware) Chain {
+ newMws := make([]chainMiddleware, len(c.mws)+len(mws))
+ copy(newMws[:len(c.mws)], c.mws)
+ copy(newMws[len(c.mws):], mws)
+ c.mws = newMws
+ return c
+}
+
+func (c Chain) Then(chf func(ctx *Context, w http.ResponseWriter, r *http.Request)) HandlerChain {
+ c.h = adaptContextHandlerFunc(chf)
+ return newHandlerChain(c)
+}
+
+func (c Chain) ThenHandler(h http.Handler) HandlerChain {
+ c.h = adaptHandler(h)
+ return newHandlerChain(c)
+}
+
+func (c Chain) ThenHandlerFunc(fn func(http.ResponseWriter, *http.Request)) HandlerChain {
+ c.h = adaptHandlerFunc(fn)
+ return newHandlerChain(c)
+}
+
+type HandlerChain struct {
+ context *Context
+ Chain
+}
+
+func newHandlerChain(c Chain) HandlerChain {
+ return HandlerChain{context: NewContext(), Chain: c}
+}
+
+func (hc HandlerChain) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ // Always take a copy of context (i.e. pointing to a brand new memory location)
+ ctx := hc.context.copy()
+
+ final := hc.h(ctx)
+ for i := len(hc.mws) - 1; i >= 0; i-- {
+ final = hc.mws[i](ctx, final)
+ }
+ final.ServeHTTP(w, r)
+}
+
+func Inject(hc HandlerChain, key string, val interface{}) HandlerChain {
+ hc.context = hc.context.copy().Put(key, val)
+ return hc
+}
+
+// Adapt third party middleware with the signature
+// func(http.Handler) http.Handler into chainMiddleware
+func Adapt(fn func(http.Handler) http.Handler) chainMiddleware {
+ return func(ctx *Context, h http.Handler) http.Handler {
+ return fn(h)
+ }
+}
+
+// Adapt http.Handler into a chainHandler
+func adaptHandler(h http.Handler) chainHandler {
+ return func(ctx *Context) http.Handler {
+ return h
+ }
+}
+
+// Adapt a function with the signature
+// func(http.ResponseWriter, *http.Request) into a chainHandler
+func adaptHandlerFunc(fn func(w http.ResponseWriter, r *http.Request)) chainHandler {
+ return adaptHandler(http.HandlerFunc(fn))
+}
+
+// Adapt a function with the signature
+// func(Context, http.ResponseWriter, *http.Request) into a chainHandler
+func adaptContextHandlerFunc(fn func(ctx *Context, w http.ResponseWriter, r *http.Request)) chainHandler {
+ return func(ctx *Context) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ fn(ctx, w, r)
+ })
+ }
+}
diff --git a/vendor/src/github.com/alexedwards/stack/stack_test.go b/vendor/src/github.com/alexedwards/stack/stack_test.go
new file mode 100644
index 0000000..28aa0ae
--- /dev/null
+++ b/vendor/src/github.com/alexedwards/stack/stack_test.go
@@ -0,0 +1,126 @@
+package stack
+
+import (
+ "fmt"
+ "io/ioutil"
+ "log"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+)
+
+func assertEquals(t *testing.T, e interface{}, o interface{}) {
+ if e != o {
+ t.Errorf("\n...expected = %v\n...obtained = %v", e, o)
+ }
+}
+
+func serveAndRequest(h http.Handler) string {
+ ts := httptest.NewServer(h)
+ defer ts.Close()
+ res, err := http.Get(ts.URL)
+ if err != nil {
+ log.Fatal(err)
+ }
+ resBody, err := ioutil.ReadAll(res.Body)
+ res.Body.Close()
+ if err != nil {
+ log.Fatal(err)
+ }
+ return string(resBody)
+}
+
+func bishMiddleware(ctx *Context, next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ ctx.Put("bish", "bash")
+ fmt.Fprintf(w, "bishMiddleware>")
+ next.ServeHTTP(w, r)
+ })
+}
+
+func flipMiddleware(ctx *Context, next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ fmt.Fprintf(w, "flipMiddleware>")
+ next.ServeHTTP(w, r)
+ })
+}
+
+func wobbleMiddleware(next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ fmt.Fprintf(w, "wobbleMiddleware>")
+ next.ServeHTTP(w, r)
+ })
+}
+
+func bishHandler(ctx *Context, w http.ResponseWriter, r *http.Request) {
+ val := ctx.Get("bish")
+ fmt.Fprintf(w, "bishHandler [bish=%v]", val)
+}
+
+func flipHandler(ctx *Context, w http.ResponseWriter, r *http.Request) {
+ valb := ctx.Get("bish")
+ valf := ctx.Get("flip")
+ fmt.Fprintf(w, "flipHandler [bish=%v,flip=%v]", valb, valf)
+}
+
+func TestNew(t *testing.T) {
+ st := New(bishMiddleware, flipMiddleware).Then(bishHandler)
+ res := serveAndRequest(st)
+ assertEquals(t, "bishMiddleware>flipMiddleware>bishHandler [bish=bash]", res)
+}
+
+func TestAppend(t *testing.T) {
+ st := New(bishMiddleware).Append(flipMiddleware, flipMiddleware).Then(bishHandler)
+ res := serveAndRequest(st)
+ assertEquals(t, "bishMiddleware>flipMiddleware>flipMiddleware>bishHandler [bish=bash]", res)
+}
+
+func TestAppendDoesNotMutate(t *testing.T) {
+ st1 := New(bishMiddleware, flipMiddleware)
+ st2 := st1.Append(flipMiddleware, flipMiddleware)
+ res := serveAndRequest(st1.Then(bishHandler))
+ assertEquals(t, "bishMiddleware>flipMiddleware>bishHandler [bish=bash]", res)
+ res = serveAndRequest(st2.Then(bishHandler))
+ assertEquals(t, "bishMiddleware>flipMiddleware>flipMiddleware>flipMiddleware>bishHandler [bish=bash]", res)
+}
+
+func TestThen(t *testing.T) {
+ chf := func(ctx *Context, w http.ResponseWriter, r *http.Request) {
+ fmt.Fprint(w, "An anonymous ContextHandlerFunc")
+ }
+ st := New().Then(chf)
+ res := serveAndRequest(st)
+ assertEquals(t, "An anonymous ContextHandlerFunc", res)
+}
+
+func TestThenHandler(t *testing.T) {
+ st := New().ThenHandler(http.NotFoundHandler())
+ res := serveAndRequest(st)
+ assertEquals(t, "404 page not found\n", res)
+}
+
+func TestThenHandlerFunc(t *testing.T) {
+ hf := func(w http.ResponseWriter, r *http.Request) {
+ fmt.Fprint(w, "An anonymous HandlerFunc")
+ }
+ st := New().ThenHandlerFunc(hf)
+ res := serveAndRequest(st)
+ assertEquals(t, "An anonymous HandlerFunc", res)
+}
+
+func TestMixedMiddleware(t *testing.T) {
+ st := New(bishMiddleware, Adapt(wobbleMiddleware), flipMiddleware).Then(bishHandler)
+ res := serveAndRequest(st)
+ assertEquals(t, "bishMiddleware>wobbleMiddleware>flipMiddleware>bishHandler [bish=bash]", res)
+}
+
+func TestInject(t *testing.T) {
+ st := New(flipMiddleware).Then(flipHandler)
+ st2 := Inject(st, "bish", "boop")
+
+ res := serveAndRequest(st2)
+ assertEquals(t, "flipMiddleware>flipHandler [bish=boop,flip=<nil>]", res)
+
+ res = serveAndRequest(st)
+ assertEquals(t, "flipMiddleware>flipHandler [bish=<nil>,flip=<nil>]", res)
+}
13 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351
/*
 * Copyright (c) 2015 Menny Even-Danan
 *
 * 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.anysoftkeyboard;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.inputmethodservice.InputMethodService;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.SystemClock;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
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.ImageView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.anysoftkeyboard.LayoutSwitchAnimationListener.AnimationType;
import com.anysoftkeyboard.api.KeyCodes;
import com.anysoftkeyboard.devicespecific.Clipboard;
import com.anysoftkeyboard.dictionaries.DictionaryAddOnAndBuilder;
import com.anysoftkeyboard.dictionaries.EditableDictionary;
import com.anysoftkeyboard.dictionaries.ExternalDictionaryFactory;
import com.anysoftkeyboard.dictionaries.Suggest;
import com.anysoftkeyboard.dictionaries.TextEntryState;
import com.anysoftkeyboard.dictionaries.TextEntryState.State;
import com.anysoftkeyboard.dictionaries.sqlite.AutoDictionary;
import com.anysoftkeyboard.keyboards.AnyKeyboard;
import com.anysoftkeyboard.keyboards.AnyKeyboard.AnyKey;
import com.anysoftkeyboard.keyboards.AnyKeyboard.HardKeyboardTranslator;
import com.anysoftkeyboard.keyboards.CondenseType;
import com.anysoftkeyboard.keyboards.GenericKeyboard;
import com.anysoftkeyboard.keyboards.Keyboard.Key;
import com.anysoftkeyboard.keyboards.KeyboardAddOnAndBuilder;
import com.anysoftkeyboard.keyboards.KeyboardSwitcher;
import com.anysoftkeyboard.keyboards.KeyboardSwitcher.NextKeyboardType;
import com.anysoftkeyboard.keyboards.physical.HardKeyboardActionImpl;
import com.anysoftkeyboard.keyboards.physical.MyMetaKeyKeyListener;
import com.anysoftkeyboard.keyboards.views.AnyKeyboardView;
import com.anysoftkeyboard.keyboards.views.CandidateView;
import com.anysoftkeyboard.keyboards.views.OnKeyboardActionListener;
import com.anysoftkeyboard.quicktextkeys.QuickTextKey;
import com.anysoftkeyboard.quicktextkeys.QuickTextKeyFactory;
import com.anysoftkeyboard.receivers.PackagesChangedReceiver;
import com.anysoftkeyboard.receivers.SoundPreferencesChangedReceiver;
import com.anysoftkeyboard.receivers.SoundPreferencesChangedReceiver.SoundPreferencesChangedListener;
import com.anysoftkeyboard.theme.KeyboardTheme;
import com.anysoftkeyboard.theme.KeyboardThemeFactory;
import com.anysoftkeyboard.ui.VoiceInputNotInstalledActivity;
import com.anysoftkeyboard.ui.dev.DeveloperUtils;
import com.anysoftkeyboard.ui.settings.MainSettingsActivity;
import com.anysoftkeyboard.ui.tutorials.TipLayoutsSupport;
import com.anysoftkeyboard.ui.tutorials.TutorialsProvider;
import com.anysoftkeyboard.utils.IMEUtil.GCUtils;
import com.anysoftkeyboard.utils.IMEUtil.GCUtils.MemRelatedOperation;
import com.anysoftkeyboard.utils.Log;
import com.anysoftkeyboard.utils.ModifierKeyState;
import com.anysoftkeyboard.utils.Workarounds;
import com.google.android.voiceime.VoiceRecognitionTrigger;
import com.menny.android.anysoftkeyboard.AnyApplication;
import com.menny.android.anysoftkeyboard.BuildConfig;
import com.menny.android.anysoftkeyboard.FeaturesSet;
import com.menny.android.anysoftkeyboard.R;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

/**
 * Input method implementation for Qwerty'ish keyboard.
 */
public class AnySoftKeyboard extends InputMethodService implements
		OnKeyboardActionListener, OnSharedPreferenceChangeListener,
		AnyKeyboardContextProvider, SoundPreferencesChangedListener {

	private final static String TAG = "ASK";
	// private View mRestartSuggestionsView;
	private static final long MINIMUM_REFRESH_TIME_FOR_DICTIONARIES = 30 * 1000;
	private static final String SMILEY_PLUGIN_ID = "0077b34d-770f-4083-83e4-081957e06c27";
	private static final String KEYBOARD_NOTIFICATION_ALWAYS = "1";
	private static final String KEYBOARD_NOTIFICATION_ON_PHYSICAL = "2";
	private static final String KEYBOARD_NOTIFICATION_NEVER = "3";
	//Arrays.asList((CharSequence) ".", ",", "?", "!", ":", "'", "\"", "@", "#", "&", "()");
	private static final List<CharSequence> msEmptyNextSuggestions = Arrays.asList(/*empty for now*/);
	private static final long ONE_FRAME_DELAY = 1000l / 60l;
	private static final long HALF_FRAME_DELAY = ONE_FRAME_DELAY / 2l;
	private final AskPrefs mAskPrefs;
	private final ModifierKeyState mShiftKeyState = new ModifierKeyState(true/*supports locked state*/);
	private final ModifierKeyState mControlKeyState = new ModifierKeyState(false/*does not support locked state*/);
	private final HardKeyboardActionImpl mHardKeyboardAction = new HardKeyboardActionImpl();
	private final Handler mHandler = new KeyboardUIStateHandler(this);

	// receive ringer mode changes to detect silent mode
	private final SoundPreferencesChangedReceiver mSoundPreferencesChangedReceiver = new SoundPreferencesChangedReceiver(this);
	private final PackagesChangedReceiver mPackagesChangedReceiver = new PackagesChangedReceiver(this);
	protected IBinder mImeToken = null;
	KeyboardSwitcher mKeyboardSwitcher;
	/*package*/ TextView mCandidateCloseText;
	private SharedPreferences mPrefs;
	private LayoutSwitchAnimationListener mSwitchAnimator;
	private boolean mDistinctMultiTouch = true;
	private AnyKeyboardView mInputView;
	private View mCandidatesParent;
	private CandidateView mCandidateView;
	private long mLastDictionaryRefresh = -1;
	private int mMinimumWordCorrectionLength = 2;
	private Suggest mSuggest;
	private CompletionInfo[] mCompletions;
	private AlertDialog mOptionsDialog;
	private AlertDialog mQuickTextKeyDialog;
	private long mMetaState;
	private HashSet<Character> mSentenceSeparators = new HashSet<>();
	// private BTreeDictionary mContactsDictionary;
	private EditableDictionary mUserDictionary;
	private AutoDictionary mAutoDictionary;
	private WordComposer mWord = new WordComposer();
	private int mOrientation = Configuration.ORIENTATION_PORTRAIT;
	private int mCommittedLength;
	/*
	 * Do we do prediction now
	 */
	private boolean mPredicting;
	/*
	 * is prediction needed for the current input connection
	 */
	private boolean mPredictionOn;
	/*
	 * is out-side completions needed
	 */
	private boolean mCompletionOn;
	private boolean mAutoSpace;
	private boolean mAutoCorrectOn;
	private boolean mAllowSuggestionsRestart = true;
	private boolean mCurrentlyAllowSuggestionRestart = true;
	private boolean mJustAutoAddedWord = false;
	private boolean mSmileyOnShortPress;
	private String mOverrideQuickTextText = null;
	private boolean mAutoCap;
	private boolean mQuickFixes;
	/*
	 * Configuration flag. Should we support dictionary suggestions
	 */
	private boolean mShowSuggestions = false;
	private boolean mAutoComplete;
	// private int mCorrectionMode;
	private String mKeyboardChangeNotificationType;
	/*
	 * This will help us find out if UNDO_COMMIT is still possible to be done
	 */
	private int mUndoCommitCursorPosition = -2;
	private AudioManager mAudioManager;
	private boolean mSilentMode;
	private boolean mSoundOn;
	// between 0..100. This is the custom volume
	private int mSoundVolume;
	private Vibrator mVibrator;
	private int mVibrationDuration;
	private CondenseType mKeyboardInCondensedMode = CondenseType.None;
	private boolean mJustAddedAutoSpace;
	private CharSequence mJustAddOnText = null;
	private boolean mLastCharacterWasShifted = false;
	private InputMethodManager mInputMethodManager;
	private VoiceRecognitionTrigger mVoiceRecognitionTrigger;

	public AnySoftKeyboard() {
		mAskPrefs = AnyApplication.getConfig();
	}

	private static int getCursorPosition(InputConnection connection) {
		if (connection == null)
			return 0;
		ExtractedText extracted = connection.getExtractedText(new ExtractedTextRequest(), 0);
		if (extracted == null)
			return 0;
		return extracted.startOffset + extracted.selectionStart;
	}

	private static boolean isBackWordStopChar(int c) {
		return !Character.isLetter(c);
	}

	private static String getDictionaryOverrideKey(AnyKeyboard currentKeyboard) {
		return currentKeyboard.getKeyboardPrefId() + "_override_dictionary";
	}

	@Override
	@NonNull
	public AbstractInputMethodImpl onCreateInputMethodInterface() {
		return new InputMethodImpl() {
			@Override
			public void attachToken(IBinder token) {
				super.attachToken(token);
				mImeToken = token;
			}
		};
	}

	@Override
	public void onCreate() {
		super.onCreate();
		mPrefs = PreferenceManager
				.getDefaultSharedPreferences(getApplicationContext());
		if (DeveloperUtils.hasTracingRequested(getApplicationContext())) {
			try {
				DeveloperUtils.startTracing();
				Toast.makeText(getApplicationContext(),
						R.string.debug_tracing_starting, Toast.LENGTH_SHORT).show();
			} catch (Exception e) {
				//see issue https://github.com/AnySoftKeyboard/AnySoftKeyboard/issues/105
				//I might get a "Permission denied" error.
				e.printStackTrace();
				Toast.makeText(getApplicationContext(),
						R.string.debug_tracing_starting_failed, Toast.LENGTH_LONG).show();
			}
		}
		Log.i(TAG, "****** AnySoftKeyboard v%s (%d) service started.", BuildConfig.VERSION_NAME, BuildConfig.VERSION_CODE);
		if (!BuildConfig.DEBUG && BuildConfig.VERSION_NAME.endsWith("-SNAPSHOT"))
			throw new RuntimeException("You can not run a 'RELEASE' build with a SNAPSHOT postfix!");

		if (mAskPrefs.getAnimationsLevel() != AskPrefs.AnimationsLevel.None) {
			final int fancyAnimation = getResources().getIdentifier("Animation_InputMethodFancy", "style", "android");
			if (fancyAnimation != 0) {
				Log.i(TAG, "Found Animation_InputMethodFancy as %d, so I'll use this", fancyAnimation);
				getWindow().getWindow().setWindowAnimations(fancyAnimation);
			} else {
				Log.w(TAG, "Could not find Animation_InputMethodFancy, using default animation");
				getWindow().getWindow().setWindowAnimations(android.R.style.Animation_InputMethod);
			}
		}

		mInputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
		mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
		updateRingerMode();
		// register to receive ringer mode changes for silent mode
		registerReceiver(mSoundPreferencesChangedReceiver,
				mSoundPreferencesChangedReceiver.createFilterToRegisterOn());
		// register to receive packages changes
		registerReceiver(mPackagesChangedReceiver,
				mPackagesChangedReceiver.createFilterToRegisterOn());
		mVibrator = ((Vibrator) getSystemService(Context.VIBRATOR_SERVICE));
		loadSettings();
		mAskPrefs.addChangedListener(this);
		mKeyboardSwitcher = new KeyboardSwitcher(this);

		mOrientation = getResources().getConfiguration().orientation;

		mSentenceSeparators = getCurrentKeyboard().getSentenceSeparators();

		if (mSuggest == null) {
			initSuggest();
		}

		if (mKeyboardChangeNotificationType
				.equals(KEYBOARD_NOTIFICATION_ALWAYS)) {
			notifyKeyboardChangeIfNeeded();
		}

		mVoiceRecognitionTrigger = new VoiceRecognitionTrigger(this);

		mSwitchAnimator = new LayoutSwitchAnimationListener(this);
	}

	private void initSuggest() {
		mSuggest = new Suggest(this);
		mSuggest.setCorrectionMode(mQuickFixes, mShowSuggestions);
		mSuggest.setMinimumWordLengthForCorrection(mMinimumWordCorrectionLength);
		setDictionariesForCurrentKeyboard();
	}

	@Override
	public void onDestroy() {
		Log.i(TAG, "AnySoftKeyboard has been destroyed! Cleaning resources..");

		mSwitchAnimator.onDestory();

		mAskPrefs.removeChangedListener(this);

		unregisterReceiver(mSoundPreferencesChangedReceiver);
		unregisterReceiver(mPackagesChangedReceiver);

		mInputMethodManager.hideStatusIcon(mImeToken);

		if (mInputView != null)
			mInputView.onViewNotRequired();
		mInputView = null;

		mKeyboardSwitcher.setInputView(null);

		mSuggest.setAutoDictionary(null);
		mSuggest.setContactsDictionary(getApplicationContext(), false);
		mSuggest.setMainDictionary(getApplicationContext(), null);
		mSuggest.setUserDictionary(null);

		if (DeveloperUtils.hasTracingStarted()) {
			DeveloperUtils.stopTracing();
			Toast.makeText(
					getApplicationContext(),
					getString(R.string.debug_tracing_finished,
							DeveloperUtils.getTraceFile()), Toast.LENGTH_SHORT)
					.show();
		}

		super.onDestroy();
	}

	@Override
	public void onFinishInputView(boolean finishingInput) {
		super.onFinishInputView(finishingInput);

		if (!mKeyboardChangeNotificationType
				.equals(KEYBOARD_NOTIFICATION_ALWAYS)) {
			mInputMethodManager.hideStatusIcon(mImeToken);
		}
		// Remove pending messages related to update suggestions
		abortCorrection(true, false);
	}

	AnyKeyboardView getInputView() {
		return mInputView;
	}

	@Override
	public void setInputView(@NonNull View view) {
		super.setInputView(view);
		ViewParent parent = view.getParent();
		if (parent instanceof View) {
			// this is required for animations, so the background will be
			// consist.
			((View) parent).setBackgroundResource(R.drawable.ask_wallpaper);
		} else {
			Log.w(TAG,
					"*** It seams that the InputView parent is not a View!! This is very strange.");
		}
	}

	@Override
	public View onCreateInputView() {
		if (mInputView != null)
			mInputView.onViewNotRequired();
		mInputView = null;

		GCUtils.getInstance().performOperationWithMemRetry(TAG,
				new MemRelatedOperation() {
					public void operation() {
						mInputView = (AnyKeyboardView) getLayoutInflater().inflate(R.layout.main_keyboard_layout, null);
					}
				}, true);
		// resetting token users
		mOptionsDialog = null;
		mQuickTextKeyDialog = null;

		mKeyboardSwitcher.setInputView(mInputView);
		mInputView.setOnKeyboardActionListener(this);

		mDistinctMultiTouch = mInputView.hasDistinctMultitouch();

		return mInputView;
	}

	@Override
	public View onCreateCandidatesView() {
		mKeyboardSwitcher.makeKeyboards(false);
		final ViewGroup candidateViewContainer = (ViewGroup) getLayoutInflater().inflate(R.layout.candidates, null);
		mCandidatesParent = null;
		mCandidateView = (CandidateView) candidateViewContainer.findViewById(R.id.candidates);
		mCandidateView.setService(this);
		setCandidatesViewShown(false);

		final KeyboardTheme theme = KeyboardThemeFactory
				.getCurrentKeyboardTheme(getApplicationContext());
		final TypedArray a = theme.getPackageContext().obtainStyledAttributes(
				null, R.styleable.AnyKeyboardViewTheme, 0,
				theme.getThemeResId());
		int closeTextColor = getResources().getColor(R.color.candidate_other);
		float fontSizePixel = getResources().getDimensionPixelSize(
				R.dimen.candidate_font_height);
		try {
			closeTextColor = a.getColor(
					R.styleable.AnyKeyboardViewTheme_suggestionOthersTextColor,
					closeTextColor);
			fontSizePixel = a.getDimension(
					R.styleable.AnyKeyboardViewTheme_suggestionTextSize,
					fontSizePixel);
		} catch (Exception e) {
			e.printStackTrace();
		}
		a.recycle();

		mCandidateCloseText = (TextView) candidateViewContainer
				.findViewById(R.id.close_suggestions_strip_text);
		View closeIcon = candidateViewContainer
				.findViewById(R.id.close_suggestions_strip_icon);

		if (mCandidateCloseText != null && closeIcon != null) {// why? In API3
			// it is not
			// supported
			closeIcon.setOnClickListener(new OnClickListener() {
				// two seconds is enough.
				private final static long DOUBLE_TAP_TIMEOUT = 2 * 1000;

				public void onClick(View v) {
					mHandler.removeMessages(KeyboardUIStateHandler.MSG_REMOVE_CLOSE_SUGGESTIONS_HINT);
					mCandidateCloseText.setVisibility(View.VISIBLE);
					mCandidateCloseText.startAnimation(AnimationUtils.loadAnimation(getApplicationContext(), R.anim.close_candidates_hint_in));
					mHandler.sendMessageDelayed(mHandler.obtainMessage(KeyboardUIStateHandler.MSG_REMOVE_CLOSE_SUGGESTIONS_HINT), DOUBLE_TAP_TIMEOUT - 50);
				}
			});

			mCandidateCloseText.setTextColor(closeTextColor);
			mCandidateCloseText.setTextSize(TypedValue.COMPLEX_UNIT_PX,
					fontSizePixel);
			mCandidateCloseText.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					mHandler.removeMessages(KeyboardUIStateHandler.MSG_REMOVE_CLOSE_SUGGESTIONS_HINT);
					mCandidateCloseText.setVisibility(View.GONE);
					abortCorrection(true, true);
				}
			});
		}

		final TextView tipsNotification = (TextView) candidateViewContainer
				.findViewById(R.id.tips_notification_on_candidates);
		if (tipsNotification != null) {// why? in API 3 it is not supported
			if (mAskPrefs.getShowTipsNotification()
					&& TutorialsProvider.shouldShowTips(getApplicationContext())) {

				final String TIPS_NOTIFICATION_KEY = "TIPS_NOTIFICATION_KEY";
				TipLayoutsSupport.addTipToCandidate(getApplicationContext(), tipsNotification, TIPS_NOTIFICATION_KEY, new OnClickListener() {
					@Override
					public void onClick(View v) {
						TutorialsProvider.showTips(getApplicationContext());
					}
				});
			}
		}

		return candidateViewContainer;
	}

	@Override
	public void onStartInput(EditorInfo attribute, boolean restarting) {
		Log.d(TAG, "onStartInput(EditorInfo:" + attribute.imeOptions + ","
				+ attribute.inputType + ", restarting:" + restarting + ")");

		super.onStartInput(attribute, restarting);

		abortCorrection(true, false);

		if (!restarting) {
			TextEntryState.newSession(this);
			// Clear shift states.
			mMetaState = 0;
			mCurrentlyAllowSuggestionRestart = mAllowSuggestionsRestart;
		} else {
			// something very fishy happening here...
			// this is the only way I can get around it.
			// it seems that when a onStartInput is called with restarting ==
			// true
			// suggestions restart fails :(
			// see Browser when editing multiline textbox
			mCurrentlyAllowSuggestionRestart = false;
		}
	}

	@Override
	public void onStartInputView(final EditorInfo attribute,
	                             final boolean restarting) {
		Log.d(TAG, "onStartInputView(EditorInfo{imeOptions %d, inputType %d}, restarting %s",
				attribute.imeOptions, attribute.inputType, restarting);

		super.onStartInputView(attribute, restarting);
		if (mVoiceRecognitionTrigger != null) {
			mVoiceRecognitionTrigger.onStartInputView();
		}

		if (mInputView == null) {
			return;
		}

		mInputView.setKeyboardActionType(attribute.imeOptions);
		mKeyboardSwitcher.makeKeyboards(false);

		mPredictionOn = false;
		mCompletionOn = false;
		mCompletions = null;

		switch (attribute.inputType & EditorInfo.TYPE_MASK_CLASS) {
			case EditorInfo.TYPE_CLASS_DATETIME:
				Log.d(TAG, "Setting MODE_DATETIME as keyboard due to a TYPE_CLASS_DATETIME input.");
				mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_DATETIME, attribute, restarting);
				break;
			case EditorInfo.TYPE_CLASS_NUMBER:
				Log.d(TAG, "Setting MODE_NUMBERS as keyboard due to a TYPE_CLASS_NUMBER input.");
				mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_NUMBERS, attribute, restarting);
				break;
			case EditorInfo.TYPE_CLASS_PHONE:
				Log.d(TAG, "Setting MODE_PHONE as keyboard due to a TYPE_CLASS_PHONE input.");
				mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_PHONE, attribute, restarting);
				break;
			case EditorInfo.TYPE_CLASS_TEXT:
				Log.d(TAG, "A TYPE_CLASS_TEXT input.");
				final int variation = attribute.inputType & EditorInfo.TYPE_MASK_VARIATION;
				switch (variation) {
					case EditorInfo.TYPE_TEXT_VARIATION_PASSWORD:
					case EditorInfo.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD:
					case EditorInfo.TYPE_TEXT_VARIATION_WEB_PASSWORD:
						Log.d(TAG, "A password TYPE_CLASS_TEXT input with no prediction");
						mPredictionOn = false;
						break;
					default:
						mPredictionOn = true;
				}

				if (mAskPrefs.getInsertSpaceAfterCandidatePick()) {
					switch (variation) {
						case EditorInfo.TYPE_TEXT_VARIATION_EMAIL_ADDRESS:
						case EditorInfo.TYPE_TEXT_VARIATION_URI:
						case EditorInfo.TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS:
							mAutoSpace = false;
							break;
						default:
							mAutoSpace = true;
					}
				} else {
					// some users don't want auto-space
					mAutoSpace = false;
				}

				switch (variation) {
					case EditorInfo.TYPE_TEXT_VARIATION_EMAIL_ADDRESS:
					case EditorInfo.TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS:
						Log.d(TAG, "Setting MODE_EMAIL as keyboard due to a TYPE_TEXT_VARIATION_EMAIL_ADDRESS input.");
						mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_EMAIL, attribute, restarting);
						mPredictionOn = false;
						break;
					case EditorInfo.TYPE_TEXT_VARIATION_URI:
						Log.d(TAG, "Setting MODE_URL as keyboard due to a TYPE_TEXT_VARIATION_URI input.");
						mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_URL, attribute, restarting);
						mPredictionOn = false;
						break;
					case EditorInfo.TYPE_TEXT_VARIATION_SHORT_MESSAGE:
						Log.d(TAG, "Setting MODE_IM as keyboard due to a TYPE_TEXT_VARIATION_SHORT_MESSAGE input.");
						mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_IM, attribute, restarting);
						break;
					default:
						Log.d(TAG, "Setting MODE_TEXT as keyboard due to a default input.");
						mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_TEXT, attribute, restarting);
				}

				final int textFlag = attribute.inputType & EditorInfo.TYPE_MASK_FLAGS;
				switch (textFlag) {
					case EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS:
					case EditorInfo.TYPE_TEXT_FLAG_AUTO_COMPLETE:
						Log.d(TAG, "Input requested NO_SUGGESTIONS, or it is AUTO_COMPLETE by itself.");
						mPredictionOn = false;
						break;
					default:
						// we'll keep the previous mPredictionOn value
				}

				break;
			default:
				Log.d(TAG, "Setting MODE_TEXT as keyboard due to a default input.");
				// No class. Probably a console window, or no GUI input connection
				mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_TEXT, attribute, restarting);
				mPredictionOn = false;
				mAutoSpace = true;
		}

		mPredicting = false;
		mJustAddedAutoSpace = false;
		setCandidatesViewShown(false);

		if (mSuggest != null) {
			mSuggest.setCorrectionMode(mQuickFixes, mShowSuggestions);
		}

		mPredictionOn = mPredictionOn && (mShowSuggestions/* || mQuickFixes */);

		setSuggestions(null, false, false, false);

		if (mPredictionOn) {
			if ((SystemClock.elapsedRealtime() - mLastDictionaryRefresh) > MINIMUM_REFRESH_TIME_FOR_DICTIONARIES)
				setDictionariesForCurrentKeyboard();
		} else {
			// this will release memory
			setDictionariesForCurrentKeyboard();
		}

		updateShiftStateNow();
	}

	@Override
	public void hideWindow() {
		if (mOptionsDialog != null && mOptionsDialog.isShowing()) {
			mOptionsDialog.dismiss();
			mOptionsDialog = null;
		}
		if (mQuickTextKeyDialog != null && mQuickTextKeyDialog.isShowing()) {
			mQuickTextKeyDialog.dismiss();
			mQuickTextKeyDialog = null;
		}

		super.hideWindow();

		TextEntryState.endSession();
	}

	@Override
	public void onFinishInput() {
		Log.d(TAG, "onFinishInput()");
		super.onFinishInput();

		if (mInputView != null) {
			mInputView.closing();
		}

		if (!mKeyboardChangeNotificationType
				.equals(KEYBOARD_NOTIFICATION_ALWAYS)) {
			mInputMethodManager.hideStatusIcon(mImeToken);
		}
	}

	/*
	 * this function is called EVERY TIME them selection is changed. This also
	 * includes the underlined suggestions.
	 */
	@Override
	public void onUpdateSelection(int oldSelStart, int oldSelEnd,
	                              int newSelStart, int newSelEnd, int candidatesStart,
	                              int candidatesEnd) {
		super.onUpdateSelection(oldSelStart, oldSelEnd, newSelStart, newSelEnd, candidatesStart, candidatesEnd);

		Log.d(TAG, "onUpdateSelection: oss=" + oldSelStart + ", ose="
				+ oldSelEnd + ", nss=" + newSelStart + ", nse=" + newSelEnd
				+ ", cs=" + candidatesStart + ", ce=" + candidatesEnd);
		//next UI thread loop, please recalculate the shift state

		updateShiftStateNow();

		mWord.setGlobalCursorPosition(newSelEnd);

		if (!isPredictionOn()) {
			return;// not relevant if no prediction is needed.
		}

		final InputConnection ic = getCurrentInputConnection();
		if (ic == null)
			return;// well, I can't do anything without this connection

		Log.d(TAG, "onUpdateSelection: ok, let's see what can be done");

		if (newSelStart != newSelEnd) {
			// text selection. can't predict in this mode
			Log.d(TAG, "onUpdateSelection: text selection.");
			abortCorrection(true, false);
		} else {
			// we have the following options (we are in an input which requires
			// predicting (mPredictionOn == true):
			// 1) predicting and moved inside the word
			// 2) predicting and moved outside the word
			// 2.1) to a new word
			// 2.2) to no word land
			// 3) not predicting
			// 3.1) to a new word
			// 3.2) to no word land

			// so, 1 and 2 requires that predicting is currently done, and the
			// cursor moved
			if (mPredicting) {
				if (newSelStart >= candidatesStart && newSelStart <= candidatesEnd) {
					// 1) predicting and moved inside the word - just update the
					// cursor position and shift state
					// inside the currently selected word
					int cursorPosition = newSelEnd - candidatesStart;
					if (mWord.setCursorPostion(cursorPosition)) {
						Log.d(TAG, "onUpdateSelection: cursor moving inside the predicting word");
					}
				} else {
					Log.d(TAG, "onUpdateSelection: cursor moving outside the currently predicting word");
					abortCorrection(true, false);
					// ask user whether to restart
					postRestartWordSuggestion();
				}
			} else {
				Log.d(TAG,
						"onUpdateSelection: not predicting at this moment, maybe the cursor is now at a new word?");
				if (TextEntryState.getState() == State.ACCEPTED_DEFAULT) {
					if (mUndoCommitCursorPosition == oldSelStart && mUndoCommitCursorPosition != newSelStart) {
						Log.d(TAG, "onUpdateSelection: I am in ACCEPTED_DEFAULT state, but the user moved the cursor, so it is not possible to undo_commit now.");
						abortCorrection(true, false);
					} else if (mUndoCommitCursorPosition == -2) {
						Log.d(TAG, "onUpdateSelection: I am in ACCEPTED_DEFAULT state, time to store the position - I can only undo-commit from here.");
						mUndoCommitCursorPosition = newSelStart;
					}
				}
				postRestartWordSuggestion();
			}
		}
	}

	private void postRestartWordSuggestion() {
		mHandler.removeMessages(KeyboardUIStateHandler.MSG_RESTART_NEW_WORD_SUGGESTIONS);

		mHandler.sendMessageDelayed(mHandler.obtainMessage(KeyboardUIStateHandler.MSG_RESTART_NEW_WORD_SUGGESTIONS), 10 * ONE_FRAME_DELAY);
	}

	private boolean canRestartWordSuggestion() {
		if (mPredicting || !isPredictionOn() || !mAllowSuggestionsRestart
				|| !mCurrentlyAllowSuggestionRestart || mInputView == null
				|| !mInputView.isShown()) {
			// why?
			// mPredicting - if I'm predicting a word, I can not restart it..
			// right? I'm inside that word!
			// isPredictionOn() - this is obvious.
			// mAllowSuggestionsRestart - config settings
			// mCurrentlyAllowSuggestionRestart - workaround for
			// onInputStart(restarting == true)
			// mInputView == null - obvious, no?
			Log.d(TAG, "performRestartWordSuggestion: no need to restart: mPredicting=%s, isPredictionOn=%s, mAllowSuggestionsRestart=%s, mCurrentlyAllowSuggestionRestart=%s"
					, mPredicting, isPredictionOn(), mAllowSuggestionsRestart, mCurrentlyAllowSuggestionRestart);
			return false;
		} else if (!isCursorTouchingWord()) {
			Log.d(TAG, "User moved cursor to no-man land. Bye bye.");
			return false;
		}

		return true;
	}

	public void performRestartWordSuggestion(final InputConnection ic) {
		// I assume ASK DOES NOT predict at this moment!

		// 2) predicting and moved outside the word - abort predicting, update
		// shift state
		// 2.1) to a new word - restart predicting on the new word
		// 2.2) to no word land - nothing else

		// this means that the new cursor position is outside the candidates
		// underline
		// this can be either because the cursor is really outside the
		// previously underlined (suggested)
		// or nothing was suggested.
		// in this case, we would like to reset the prediction and restart
		// if the user clicked inside a different word
		// restart required?
		if (canRestartWordSuggestion()) {// 2.1
			ic.beginBatchEdit();// don't want any events till I finish handling
			// this touch
			Log.d(TAG,
					"User moved cursor to a word. Should I restart predition?");
			abortCorrection(true, false);

			// locating the word
			CharSequence toLeft = "";
			CharSequence toRight = "";
			while (true) {
				Log.d(TAG, "Checking left offset " + toLeft.length()
						+ ". Currently have '" + toLeft + "'");
				CharSequence newToLeft = ic.getTextBeforeCursor(
						toLeft.length() + 1, 0);
				if (TextUtils.isEmpty(newToLeft)
						|| isWordSeparator(newToLeft.charAt(0))
						|| newToLeft.length() == toLeft.length()) {
					break;
				}
				toLeft = newToLeft;
			}
			while (true) {
				Log.d(TAG, "Checking right offset " + toRight.length()
						+ ". Currently have '" + toRight + "'");
				CharSequence newToRight = ic.getTextAfterCursor(
						toRight.length() + 1, 0);
				if (TextUtils.isEmpty(newToRight)
						|| isWordSeparator(newToRight.charAt(newToRight
						.length() - 1))
						|| newToRight.length() == toRight.length()) {
					break;
				}
				toRight = newToRight;
			}
			CharSequence word = toLeft.toString() + toRight.toString();
			Log.d(TAG, "Starting new prediction on word '" + word + "'.");
			mPredicting = word.length() > 0;
			mUndoCommitCursorPosition = -2;// so it will be marked the next time
			mWord.reset();

			final int[] tempNearByKeys = new int[1];

			for (int index = 0; index < word.length(); index++) {
				final char c = word.charAt(index);
				if (index == 0)
					mWord.setFirstCharCapitalized(Character.isUpperCase(c));

				tempNearByKeys[0] = c;
				mWord.add(c, tempNearByKeys);

				TextEntryState.typedCharacter(c, false);
			}
			ic.deleteSurroundingText(toLeft.length(), toRight.length());
			ic.setComposingText(word, 1);
			// repositioning the cursor
			if (toRight.length() > 0) {
				final int cursorPosition = getCursorPosition(ic)
						- toRight.length();
				Log.d(TAG,
						"Repositioning the cursor inside the word to position "
								+ cursorPosition);
				ic.setSelection(cursorPosition, cursorPosition);
			}

			mWord.setCursorPostion(toLeft.length());
			ic.endBatchEdit();
			postUpdateSuggestions();
		} else {
			Log.d(TAG,
					"performRestartWordSuggestion canRestartWordSuggestion == false");
		}
	}

	private void onPhysicalKeyboardKeyPressed() {
		if (mAskPrefs.hideSoftKeyboardWhenPhysicalKeyPressed())
			hideWindow();

		// For all other keys, if we want to do transformations on
		// text being entered with a hard keyboard, we need to process
		// it and do the appropriate action.
		// using physical keyboard is more annoying with candidate view in
		// the way
		// so we disable it.

		// to clear the underline.
		abortCorrection(true, false);
	}

	@Override
	public void onDisplayCompletions(CompletionInfo[] completions) {
		if (FeaturesSet.DEBUG_LOG) {
			Log.d(TAG, "Received completions:");
			for (int i = 0; i < (completions != null ? completions.length : 0); i++) {
				Log.d(TAG, "  #" + i + ": " + completions[i]);
			}
		}

		// completions should be shown if dictionary requires, or if we are in
		// full-screen and have outside completions
		if (mCompletionOn || (isFullscreenMode() && (completions != null))) {
			Log.v(TAG, "Received completions: completion should be shown: "
					+ mCompletionOn + " fullscreen:" + isFullscreenMode());
			mCompletions = completions;
			// we do completions :)

			mCompletionOn = true;
			if (completions == null) {
				Log.v(TAG,
						"Received completions: completion is NULL. Clearing suggestions.");
				setSuggestions(null, false, false, false);
				return;
			}

			List<CharSequence> stringList = new ArrayList<>();
			for (CompletionInfo ci : completions) {
				if (ci != null) stringList.add(ci.getText());
			}
			Log.v(TAG, "Received completions: setting to suggestions view "
					+ stringList.size() + " completions.");
			// CharSequence typedWord = mWord.getTypedWord();
			setSuggestions(stringList, true, true, true);
			mWord.setPreferredWord(null);
			// I mean, if I'm here, it must be shown...
			setCandidatesViewShown(true);
		} else {
			Log.v(TAG, "Received completions: completions should not be shown.");
		}
	}

	@Override
	public void setCandidatesViewShown(boolean shown) {
		// we show predication only in on-screen keyboard
		// (onEvaluateInputViewShown)
		// or if the physical keyboard supports candidates
		// (mPredictionLandscape)
		final boolean shouldShow = shouldCandidatesStripBeShown() && shown;
		final boolean currentlyShown = mCandidatesParent != null
				&& mCandidatesParent.getVisibility() == View.VISIBLE;
		super.setCandidatesViewShown(shouldShow);
		if (shouldShow != currentlyShown) {
			// I believe (can't confirm it) that candidates animation is kinda
			// rare,
			// and it is better to load it on demand, then to keep it in memory
			// always..
			if (shouldShow) {
				mCandidatesParent.setAnimation(AnimationUtils.loadAnimation(
						getApplicationContext(),
						R.anim.candidates_bottom_to_up_enter));
			} else {
				mCandidatesParent.setAnimation(AnimationUtils.loadAnimation(
						getApplicationContext(),
						R.anim.candidates_up_to_bottom_exit));
			}
		}
	}

	@Override
	public void setCandidatesView(@NonNull View view) {
		super.setCandidatesView(view);
		mCandidatesParent = view.getParent() instanceof View ? (View) view
				.getParent() : null;
	}

	private void clearSuggestions() {
		setSuggestions(null, false, false, false);
	}

	private void setSuggestions(List<CharSequence> suggestions,
	                            boolean completions, boolean typedWordValid,
	                            boolean haveMinimalSuggestion) {

		if (mCandidateView != null) {
			mCandidateView.setSuggestions(suggestions, completions,
					typedWordValid, haveMinimalSuggestion && mAutoCorrectOn);
		}
	}

	@Override
	public void onComputeInsets(@NonNull InputMethodService.Insets outInsets) {
		super.onComputeInsets(outInsets);
		if (!isFullscreenMode()) {
			outInsets.contentTopInsets = outInsets.visibleTopInsets;
		}
	}

	@Override
	public boolean onEvaluateFullscreenMode() {
		switch (mOrientation) {
			case Configuration.ORIENTATION_LANDSCAPE:
				return mAskPrefs.getUseFullScreenInputInLandscape();
			default:
				return mAskPrefs.getUseFullScreenInputInPortrait();
		}
	}

	@Override
	public boolean onKeyDown(final int keyCode, @NonNull KeyEvent event) {
		final boolean shouldTranslateSpecialKeys = isInputViewShown();
		Log.d(TAG, "isInputViewShown=%s", shouldTranslateSpecialKeys);

		if (event.isPrintingKey())
			onPhysicalKeyboardKeyPressed();
		mHardKeyboardAction.initializeAction(event, mMetaState);

		InputConnection ic = getCurrentInputConnection();
		Log.d(TAG,
				"Event: Key:"
						+ event.getKeyCode()
						+ " Shift:"
						+ ((event.getMetaState() & KeyEvent.META_SHIFT_ON) != 0)
						+ " ALT:"
						+ ((event.getMetaState() & KeyEvent.META_ALT_ON) != 0)
						+ " Repeats:" + event.getRepeatCount());

		switch (keyCode) {
			/****
			 * SPEACIAL translated HW keys If you add new keys here, do not forget
			 * to add to the
			 */
			case KeyEvent.KEYCODE_CAMERA:
				if (shouldTranslateSpecialKeys
						&& mAskPrefs.useCameraKeyForBackspaceBackword()) {
					handleBackWord(getCurrentInputConnection());
					return true;
				}
				// DO NOT DELAY CAMERA KEY with unneeded checks in default mark
				return super.onKeyDown(keyCode, event);
			case KeyEvent.KEYCODE_FOCUS:
				if (shouldTranslateSpecialKeys
						&& mAskPrefs.useCameraKeyForBackspaceBackword()) {
					handleDeleteLastCharacter(false);
					return true;
				}
				// DO NOT DELAY FOCUS KEY with unneeded checks in default mark
				return super.onKeyDown(keyCode, event);
			case KeyEvent.KEYCODE_VOLUME_UP:
				if (shouldTranslateSpecialKeys
						&& mAskPrefs.useVolumeKeyForLeftRight()) {
					sendDownUpKeyEvents(KeyEvent.KEYCODE_DPAD_LEFT);
					return true;
				}
				// DO NOT DELAY VOLUME UP KEY with unneeded checks in default
				// mark
				return super.onKeyDown(keyCode, event);
			case KeyEvent.KEYCODE_VOLUME_DOWN:
				if (shouldTranslateSpecialKeys
						&& mAskPrefs.useVolumeKeyForLeftRight()) {
					sendDownUpKeyEvents(KeyEvent.KEYCODE_DPAD_RIGHT);
					return true;
				}
				// DO NOT DELAY VOLUME DOWN KEY with unneeded checks in default
				// mark
				return super.onKeyDown(keyCode, event);
			/****
			 * END of SPEACIAL translated HW keys code section
			 */
			case KeyEvent.KEYCODE_BACK:
				if (event.getRepeatCount() == 0 && mInputView != null) {
					if (mInputView.handleBack()) {
						// consuming the meta keys
						if (ic != null) {
							ic.clearMetaKeyStates(Integer.MAX_VALUE);// translated,
							// so we
							// also take
							// care of
							// the
							// metakeys.
						}
						mMetaState = 0;
						return true;
					} /*
				 * else if (mTutorial != null) { mTutorial.close(); mTutorial =
				 * null; }
				 */
				}
				break;
			case 0x000000cc:// API 14: KeyEvent.KEYCODE_LANGUAGE_SWITCH
				switchToNextPhysicalKeyboard(ic);
				return true;
			case KeyEvent.KEYCODE_SHIFT_LEFT:
			case KeyEvent.KEYCODE_SHIFT_RIGHT:
				if (event.isAltPressed()
						&& Workarounds.isAltSpaceLangSwitchNotPossible()) {
					switchToNextPhysicalKeyboard(ic);
					return true;
				}
				// NOTE: letting it fall-through to the other meta-keys
			case KeyEvent.KEYCODE_ALT_LEFT:
			case KeyEvent.KEYCODE_ALT_RIGHT:
			case KeyEvent.KEYCODE_SYM:
				Log.d(TAG + "-meta-key",
						getMetaKeysStates("onKeyDown before handle"));
				mMetaState = MyMetaKeyKeyListener.handleKeyDown(mMetaState,
						keyCode, event);
				Log.d(TAG + "-meta-key",
						getMetaKeysStates("onKeyDown after handle"));
				break;
			case KeyEvent.KEYCODE_SPACE:
				if ((event.isAltPressed() && !Workarounds
						.isAltSpaceLangSwitchNotPossible())
						|| event.isShiftPressed()) {
					switchToNextPhysicalKeyboard(ic);
					return true;
				}
				// NOTE:
				// letting it fall through to the "default"
			default:

				// Fix issue 185, check if we should process key repeat
				if (!mAskPrefs.getUseRepeatingKeys() && event.getRepeatCount() > 0)
					return true;

				if (mKeyboardSwitcher.isCurrentKeyboardPhysical()) {
					// sometimes, the physical keyboard will delete input, and
					// then
					// add some.
					// we'll try to make it nice
					if (ic != null)
						ic.beginBatchEdit();
					try {
						// issue 393, backword on the hw keyboard!
						if (mAskPrefs.useBackword()
								&& keyCode == KeyEvent.KEYCODE_DEL
								&& event.isShiftPressed()) {
							handleBackWord(ic);
							return true;
						} else/* if (event.isPrintingKey()) */ {
							// http://article.gmane.org/gmane.comp.handhelds.openmoko.android-freerunner/629
							AnyKeyboard current = mKeyboardSwitcher
									.getCurrentKeyboard();

							HardKeyboardTranslator keyTranslator = (HardKeyboardTranslator) current;

							if (BuildConfig.DEBUG) {
								final String keyboardName = current
										.getKeyboardName();

								Log.d(TAG, "Asking '" + keyboardName
										+ "' to translate key: " + keyCode);
								Log.v(TAG,
										"Hard Keyboard Action before translation: Shift: "
												+ mHardKeyboardAction
												.isShiftActive()
												+ ", Alt: "
												+ mHardKeyboardAction.isAltActive()
												+ ", Key code: "
												+ mHardKeyboardAction.getKeyCode()
												+ ", changed: "
												+ mHardKeyboardAction
												.getKeyCodeWasChanged());
							}

							keyTranslator.translatePhysicalCharacter(
									mHardKeyboardAction, this);

							Log.v(TAG,
									"Hard Keyboard Action after translation: Key code: "
											+ mHardKeyboardAction.getKeyCode()
											+ ", changed: "
											+ mHardKeyboardAction
											.getKeyCodeWasChanged());
							if (mHardKeyboardAction.getKeyCodeWasChanged()) {
								final int translatedChar = mHardKeyboardAction
										.getKeyCode();
								// typing my own.
								onKey(translatedChar, null, -1,
										new int[]{translatedChar}, true/*
																	 * simualting
																	 * fromUI
																	 */);
								// my handling
								// we are at a regular key press, so we'll
								// update
								// our meta-state member
								mMetaState = MyMetaKeyKeyListener
										.adjustMetaAfterKeypress(mMetaState);
								Log.d(TAG + "-meta-key",
										getMetaKeysStates("onKeyDown after adjust - translated"));
								return true;
							}
						}
					} finally {
						if (ic != null)
							ic.endBatchEdit();
					}
				}
				if (event.isPrintingKey()) {
					// we are at a regular key press, so we'll update our
					// meta-state
					// member
					mMetaState = MyMetaKeyKeyListener
							.adjustMetaAfterKeypress(mMetaState);
					Log.d(TAG + "-meta-key",
							getMetaKeysStates("onKeyDown after adjust"));
				}
		}
		return super.onKeyDown(keyCode, event);
	}

	private void switchToNextPhysicalKeyboard(InputConnection ic) {
		// consuming the meta keys
		if (ic != null) {
			ic.clearMetaKeyStates(Integer.MAX_VALUE);// translated, so
			// we also take
			// care of the
			// metakeys.
		}
		mMetaState = 0;
		// only physical keyboard
		nextKeyboard(getCurrentInputEditorInfo(),
				NextKeyboardType.AlphabetSupportsPhysical);
	}

	private void notifyKeyboardChangeIfNeeded() {
		// Log.d("anySoftKeyboard","notifyKeyboardChangeIfNeeded");
		// Thread.dumpStack();
		if (mKeyboardSwitcher == null)// happens on first onCreate.
			return;

		if ((mKeyboardSwitcher.isAlphabetMode())
				&& !mKeyboardChangeNotificationType
				.equals(KEYBOARD_NOTIFICATION_NEVER)) {
			mInputMethodManager.showStatusIcon(mImeToken, getCurrentKeyboard()
							.getKeyboardContext().getPackageName(),
					getCurrentKeyboard().getKeyboardIconResId());
		}
	}

	public AnyKeyboard getCurrentKeyboard() {
		return mKeyboardSwitcher.getCurrentKeyboard();
	}

	public KeyboardSwitcher getKeyboardSwitcher() {
		return mKeyboardSwitcher;
	}

	@Override
	public boolean onKeyUp(int keyCode, @NonNull KeyEvent event) {
		switch (keyCode) {
			// Issue 248
			case KeyEvent.KEYCODE_VOLUME_DOWN:
			case KeyEvent.KEYCODE_VOLUME_UP:
				if (!isInputViewShown()) {
					return super.onKeyUp(keyCode, event);
				}
				if (mAskPrefs.useVolumeKeyForLeftRight()) {
					// no need of vol up/down sound
					return true;
				}
			case KeyEvent.KEYCODE_DPAD_DOWN:
			case KeyEvent.KEYCODE_DPAD_UP:
			case KeyEvent.KEYCODE_DPAD_LEFT:
			case KeyEvent.KEYCODE_DPAD_RIGHT:
				if (mInputView != null && mInputView.isShown()
						&& mInputView.isShifted()) {
					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_ALT_LEFT:
			case KeyEvent.KEYCODE_ALT_RIGHT:
			case KeyEvent.KEYCODE_SHIFT_LEFT:
			case KeyEvent.KEYCODE_SHIFT_RIGHT:
			case KeyEvent.KEYCODE_SYM:
				mMetaState = MyMetaKeyKeyListener.handleKeyUp(mMetaState, keyCode, event);
				Log.d("AnySoftKeyboard-meta-key", getMetaKeysStates("onKeyUp"));
				setInputConnectionMetaStateAsCurrentMetaKeyKeyListenerState();
				break;
		}
		return super.onKeyUp(keyCode, event);
	}

	private String getMetaKeysStates(String place) {
		final int shiftState = MyMetaKeyKeyListener.getMetaState(mMetaState,
				MyMetaKeyKeyListener.META_SHIFT_ON);
		final int altState = MyMetaKeyKeyListener.getMetaState(mMetaState,
				MyMetaKeyKeyListener.META_ALT_ON);
		final int symState = MyMetaKeyKeyListener.getMetaState(mMetaState,
				MyMetaKeyKeyListener.META_SYM_ON);

		return "Meta keys state at " + place + "- SHIFT:" + shiftState
				+ ", ALT:" + altState + " SYM:" + symState + " bits:"
				+ MyMetaKeyKeyListener.getMetaState(mMetaState) + " state:"
				+ mMetaState;
	}

	private void setInputConnectionMetaStateAsCurrentMetaKeyKeyListenerState() {
		InputConnection ic = getCurrentInputConnection();
		if (ic != null) {
			int clearStatesFlags = 0;
			if (MyMetaKeyKeyListener.getMetaState(mMetaState,
					MyMetaKeyKeyListener.META_ALT_ON) == 0)
				clearStatesFlags += KeyEvent.META_ALT_ON;
			if (MyMetaKeyKeyListener.getMetaState(mMetaState,
					MyMetaKeyKeyListener.META_SHIFT_ON) == 0)
				clearStatesFlags += KeyEvent.META_SHIFT_ON;
			if (MyMetaKeyKeyListener.getMetaState(mMetaState,
					MyMetaKeyKeyListener.META_SYM_ON) == 0)
				clearStatesFlags += KeyEvent.META_SYM_ON;
			Log.d("AnySoftKeyboard-meta-key",
					getMetaKeysStates("setInputConnectionMetaStateAsCurrentMetaKeyKeyListenerState with flags: "
							+ clearStatesFlags));
			ic.clearMetaKeyStates(clearStatesFlags);
		}
	}

	private boolean addToDictionaries(WordComposer suggestion,
	                                  AutoDictionary.AdditionType type) {
		boolean added = checkAddToDictionary(suggestion, type);
		if (added) {
			Log.i(TAG, "Word '" + suggestion
					+ "' was added to the auto-dictionary.");
		}
		return added;
	}

	/**
	 * Adds to the UserBigramDictionary and/or AutoDictionary
	 */
	private boolean checkAddToDictionary(WordComposer suggestion,
	                                     AutoDictionary.AdditionType type/*
							 * , boolean addToBigramDictionary
							 */) {
		if (suggestion == null || suggestion.length() < 1)
			return false;
		// 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 (!mQuickFixes && !mShowSuggestions)
			return false;

		if (mAutoDictionary != null) {
			String suggestionToCheck = suggestion.getTypedWord().toString();
			if (!mSuggest.isValidWord(suggestionToCheck)) {

				final boolean added = mAutoDictionary.addWord(suggestion, type, this);
				if (added && mCandidateView != null) {
					mCandidateView.notifyAboutWordAdded(suggestion.getTypedWord());
				}
				return added;
			}
		}
		return false;
	}

	private void commitTyped(InputConnection inputConnection) {
		if (mPredicting) {
			mPredicting = false;
			if (mWord.length() > 0) {
				if (inputConnection != null) {
					inputConnection.commitText(
							mWord.getTypedWord(), 1);
				}
				mCommittedLength = mWord.length();// mComposing.length();
				TextEntryState
						.acceptedTyped(mWord.getTypedWord());
				addToDictionaries(mWord, AutoDictionary.AdditionType.Typed);
			}
			if (mHandler.hasMessages(KeyboardUIStateHandler.MSG_UPDATE_SUGGESTIONS)) {
				postUpdateSuggestions(-1);
			}
		}
	}

	private void swapPunctuationAndSpace() {
		final InputConnection ic = getCurrentInputConnection();
		if (ic == null)
			return;
		if (!mAskPrefs.shouldswapPunctuationAndSpace())
			return;
		CharSequence lastTwo = ic.getTextBeforeCursor(2, 0);
		if (BuildConfig.DEBUG) {
			String seps = "";
			for (Character c : mSentenceSeparators)
				seps += c;
			Log.d(TAG, "swapPunctuationAndSpace: lastTwo: '" + lastTwo
					+ "', mSentenceSeparators " + mSentenceSeparators.size()
					+ " '" + seps + "'");
		}
		if (lastTwo != null && lastTwo.length() == 2
				&& lastTwo.charAt(0) == KeyCodes.SPACE
				&& mSentenceSeparators.contains(lastTwo.charAt(1))) {
			ic.beginBatchEdit();
			ic.deleteSurroundingText(2, 0);
			ic.commitText(lastTwo.charAt(1) + " ", 1);
			ic.endBatchEdit();
			mJustAddedAutoSpace = true;
			Log.d(TAG, "swapPunctuationAndSpace: YES");
		}
	}

	private void swapPeriodAndSpace() {
		final InputConnection ic = getCurrentInputConnection();
		if (ic == null)
			return;
		CharSequence lastThree = ic.getTextBeforeCursor(3, 0);
		if (lastThree != null && lastThree.length() == 3
				&& lastThree.charAt(0) == '.'
				&& lastThree.charAt(1) == KeyCodes.SPACE
				&& lastThree.charAt(2) == '.') {
			ic.beginBatchEdit();
			ic.deleteSurroundingText(3, 0);
			ic.commitText(".. ", 1);
			ic.endBatchEdit();
		}
	}

	private void doubleSpace() {
		// if (!mAutoPunctuate) return;
		if (!mAskPrefs.isDoubleSpaceChangesToPeriod())
			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) == KeyCodes.SPACE
				&& lastThree.charAt(2) == KeyCodes.SPACE) {
			ic.beginBatchEdit();
			ic.deleteSurroundingText(2, 0);
			ic.commitText(". ", 1);
			ic.endBatchEdit();
			mJustAddedAutoSpace = true;
		}
	}

	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) == KeyCodes.SPACE) {
			ic.deleteSurroundingText(1, 0);
		}
	}

	public boolean addWordToDictionary(String word) {
		if (mUserDictionary != null) {
			boolean added = mUserDictionary.addWord(word, 128);
			if (added && mCandidateView != null)
				mCandidateView.notifyAboutWordAdded(word);
			return added;
		} else {
			return false;
		}
	}

	public void removeFromUserDictionary(String word) {
		if (mUserDictionary != null) {
			mUserDictionary.deleteWord(word);
			abortCorrection(true, false);
			if (mCandidateView != null)
				mCandidateView.notifyAboutRemovedWord(word);
		}
	}

	/**
	 * Helper to determine if a given character code is alphabetic.
	 */
	private boolean isAlphabet(int code) {
		// inner letters have more options: ' in English. " in Hebrew, and more.
		if (mPredicting)
			return getCurrentKeyboard().isInnerWordLetter((char) code);
		else
			return getCurrentKeyboard().isStartOfWordLetter((char) code);
	}

	public void onMultiTapStarted() {
		final InputConnection ic = getCurrentInputConnection();
		if (ic != null)
			ic.beginBatchEdit();
		handleDeleteLastCharacter(true);
		if (mInputView != null)
			mInputView.setShifted(mLastCharacterWasShifted);
	}

	public void onMultiTapEnded() {
		final InputConnection ic = getCurrentInputConnection();
		if (ic != null)
			ic.endBatchEdit();
	}

	public void onKey(int primaryCode, Key key, int multiTapIndex,
	                  int[] nearByKeyCodes, boolean fromUI) {
		Log.d(TAG, "onKey " + primaryCode);
		final InputConnection ic = getCurrentInputConnection();

		switch (primaryCode) {
			case KeyCodes.ENTER:
			case KeyCodes.SPACE:
				//shortcut. Nothing more.
				handleSeparator(primaryCode);
				//should we switch to alphabet keyboard?
				if (!mKeyboardSwitcher.isAlphabetMode()) {
					Log.d(TAG, "SPACE/ENTER while in symbols mode");
					if (mAskPrefs.getSwitchKeyboardOnSpace()) {
						Log.d(TAG, "Switching to Alphabet is required by the user");
						mKeyboardSwitcher.nextKeyboard(getCurrentInputEditorInfo(), NextKeyboardType.Alphabet);
					}
				}
				break;
			case KeyCodes.DELETE_WORD:
				if (ic == null)// if we don't want to do anything, lets check
					// null first.
					break;
				handleBackWord(ic);
				break;
			case KeyCodes.DELETE:
				if (ic == null)// if we don't want to do anything, lets check null first.
					break;
				// we do backword if the shift is pressed while pressing
				// backspace (like in a PC)
				// but this is true ONLY if the device has multitouch, or the
				// user specifically asked for it
				if (mInputView != null
						&& mInputView.isShifted()
						&& !mInputView.getKeyboard().isShiftLocked()
						&& ((mDistinctMultiTouch && mShiftKeyState.isPressed()) || mAskPrefs.useBackword())) {
					handleBackWord(ic);
				} else {
					handleDeleteLastCharacter(false);
				}
				break;
			case KeyCodes.CLEAR_INPUT:
				if (ic != null) {
					ic.beginBatchEdit();
					commitTyped(ic);
					ic.deleteSurroundingText(Integer.MAX_VALUE, Integer.MAX_VALUE);
					ic.endBatchEdit();
				}
				break;
			case KeyCodes.CTRL:
				if ((!mDistinctMultiTouch) || (!fromUI))
					handleControl();
				break;
			case KeyCodes.SHIFT:
				if ((!mDistinctMultiTouch) || (!fromUI))
					handleShift();
				break;
			case KeyCodes.ARROW_LEFT:
				sendDownUpKeyEvents(KeyEvent.KEYCODE_DPAD_LEFT);
				break;
			case KeyCodes.ARROW_RIGHT:
				sendDownUpKeyEvents(KeyEvent.KEYCODE_DPAD_RIGHT);
				break;
			case KeyCodes.ARROW_UP:
				sendDownUpKeyEvents(KeyEvent.KEYCODE_DPAD_UP);
				break;
			case KeyCodes.ARROW_DOWN:
				sendDownUpKeyEvents(KeyEvent.KEYCODE_DPAD_DOWN);
				break;
			case KeyCodes.MOVE_HOME:
				if (Workarounds.getApiLevel() >= 11) {
					sendDownUpKeyEvents(0x0000007a/*
											 * API 11:
											 * KeyEvent.KEYCODE_MOVE_HOME
											 */);
				} else {
					if (ic != null) {
						CharSequence textBefore = ic.getTextBeforeCursor(1024, 0);
						if (!TextUtils.isEmpty(textBefore)) {
							int newPosition = textBefore.length() - 1;
							while (newPosition > 0) {
								char chatAt = textBefore.charAt(newPosition - 1);
								if (chatAt == '\n' || chatAt == '\r') {
									break;
								}
								newPosition--;
							}
							if (newPosition < 0)
								newPosition = 0;
							ic.setSelection(newPosition, newPosition);
						}
					}
				}
				break;
			case KeyCodes.MOVE_END:
				if (Workarounds.getApiLevel() >= 11) {
					//API 11: KeyEvent.KEYCODE_MOVE_END
					sendDownUpKeyEvents(0x0000007b);
				} else {
					if (ic != null) {
						CharSequence textAfter = ic.getTextAfterCursor(1024, 0);
						if (!TextUtils.isEmpty(textAfter)) {
							int newPosition = 1;
							while (newPosition < textAfter.length()) {
								char chatAt = textAfter.charAt(newPosition);
								if (chatAt == '\n' || chatAt == '\r') {
									break;
								}
								newPosition++;
							}
							if (newPosition > textAfter.length())
								newPosition = textAfter.length();
							try {
								CharSequence textBefore = ic.getTextBeforeCursor(Integer.MAX_VALUE, 0);
								if (!TextUtils.isEmpty(textBefore)) {
									newPosition = newPosition + textBefore.length();
								}
								ic.setSelection(newPosition, newPosition);
							} catch (Throwable e/*I'm using Integer.MAX_VALUE, it's scary.*/) {
								Log.w(TAG, "Failed to getTextBeforeCursor.", e);
							}
						}
					}
				}
				break;
			case KeyCodes.VOICE_INPUT:
				if (mVoiceRecognitionTrigger.isInstalled()) {
					mVoiceRecognitionTrigger.startVoiceRecognition(getCurrentKeyboard().getDefaultDictionaryLocale());
				} else {
					Intent voiceInputNotInstalledIntent = new Intent(getApplicationContext(), VoiceInputNotInstalledActivity.class);
					voiceInputNotInstalledIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					startActivity(voiceInputNotInstalledIntent);
				}
				break;
			case KeyCodes.CANCEL:
				if (mOptionsDialog == null || !mOptionsDialog.isShowing()) {
					handleClose();
				}
				break;
			case KeyCodes.SETTINGS:
				showOptionsMenu();
				break;
			case KeyCodes.SPLIT_LAYOUT:
			case KeyCodes.MERGE_LAYOUT:
			case KeyCodes.COMPACT_LAYOUT_TO_RIGHT:
			case KeyCodes.COMPACT_LAYOUT_TO_LEFT:
				if (getCurrentKeyboard() != null && mInputView != null) {
					mKeyboardInCondensedMode = CondenseType.fromKeyCode(primaryCode);
					AnyKeyboard currentKeyboard = getCurrentKeyboard();
					setKeyboardStuffBeforeSetToView(currentKeyboard);
					mInputView.setKeyboard(currentKeyboard);
				}
				break;
			case KeyCodes.DOMAIN:
				onText(mAskPrefs.getDomainText());
				break;
			case KeyCodes.QUICK_TEXT:
				QuickTextKey quickTextKey = QuickTextKeyFactory
						.getCurrentQuickTextKey(this);

				if (mSmileyOnShortPress) {
					if (TextUtils.isEmpty(mOverrideQuickTextText))
						onText(quickTextKey.getKeyOutputText());
					else
						onText(mOverrideQuickTextText);
				} else {
					if (quickTextKey.isPopupKeyboardUsed()) {
						showQuickTextKeyPopupKeyboard(quickTextKey);
					} else {
						showQuickTextKeyPopupList(quickTextKey);
					}
				}
				break;
			case KeyCodes.QUICK_TEXT_POPUP:
				quickTextKey = QuickTextKeyFactory.getCurrentQuickTextKey(this);
				if (quickTextKey.getId().equals(SMILEY_PLUGIN_ID)
						&& !mSmileyOnShortPress) {
					if (TextUtils.isEmpty(mOverrideQuickTextText))
						onText(quickTextKey.getKeyOutputText());
					else
						onText(mOverrideQuickTextText);
				} else {
					if (quickTextKey.isPopupKeyboardUsed()) {
						showQuickTextKeyPopupKeyboard(quickTextKey);
					} else {
						showQuickTextKeyPopupList(quickTextKey);
					}
				}
				break;
			case KeyCodes.MODE_SYMOBLS:
				nextKeyboard(getCurrentInputEditorInfo(), NextKeyboardType.Symbols);
				break;
			case KeyCodes.MODE_ALPHABET:
				if (mKeyboardSwitcher.shouldPopupForLanguageSwitch()) {
					showLanguageSelectionDialog();
				} else
					nextKeyboard(getCurrentInputEditorInfo(),
							NextKeyboardType.Alphabet);
				break;
			case KeyCodes.UTILITY_KEYBOARD:
				mInputView.openUtilityKeyboard();
				break;
			case KeyCodes.MODE_ALPHABET_POPUP:
				showLanguageSelectionDialog();
				break;
			case KeyCodes.ALT:
				nextAlterKeyboard(getCurrentInputEditorInfo());
				break;
			case KeyCodes.KEYBOARD_CYCLE:
				nextKeyboard(getCurrentInputEditorInfo(), NextKeyboardType.Any);
				break;
			case KeyCodes.KEYBOARD_REVERSE_CYCLE:
				nextKeyboard(getCurrentInputEditorInfo(),
						NextKeyboardType.PreviousAny);
				break;
			case KeyCodes.KEYBOARD_CYCLE_INSIDE_MODE:
				nextKeyboard(getCurrentInputEditorInfo(),
						NextKeyboardType.AnyInsideMode);
				break;
			case KeyCodes.KEYBOARD_MODE_CHANGE:
				nextKeyboard(getCurrentInputEditorInfo(),
						NextKeyboardType.OtherMode);
				break;
			case KeyCodes.CLIPBOARD:
				Clipboard cp = AnyApplication.getFrankenRobot().embody(
						new Clipboard.ClipboardDiagram(getApplicationContext()));
				CharSequence clipboardText = cp.getText();
				if (!TextUtils.isEmpty(clipboardText)) {
					onText(clipboardText);
				}
				break;
			case KeyCodes.TAB:
				sendTab();
				break;
			case KeyCodes.ESCAPE:
				sendEscape();
				break;
			default:
				// Issue 146: Right to left langs require reversed parenthesis
				if (mKeyboardSwitcher.isRightToLeftMode()) {
					if (primaryCode == (int) ')')
						primaryCode = (int) '(';
					else if (primaryCode == (int) '(')
						primaryCode = (int) ')';
				}

				if (isWordSeparator(primaryCode)) {
					handleSeparator(primaryCode);
				} else {
					if (mControlKeyState.isActive() && primaryCode >= 32 && primaryCode < 127) {
						// http://en.wikipedia.org/wiki/Control_character#How_control_characters_map_to_keyboards
						int controlCode = primaryCode & 31;
						Log.d(TAG, "CONTROL state: Char was %d and now it is %d", primaryCode, controlCode);
						if (controlCode == 9) {
							sendTab();
						} else {
							ic.commitText(Character.toString((char) controlCode), 1);
						}
					} else {
						handleCharacter(primaryCode, key, multiTapIndex,
								nearByKeyCodes);
					}
					// resetting the mSpaceSent, which is set to true upon selecting candidate
					mJustAddedAutoSpace = false;
				}
				break;
		}
	}

	private boolean isConnectBot() {
		EditorInfo ei = getCurrentInputEditorInfo();
		String pkg = ei.packageName;
		return ((pkg.equalsIgnoreCase("org.connectbot")
				|| pkg.equalsIgnoreCase("org.woltage.irssiconnectbot") || pkg
				.equalsIgnoreCase("com.pslib.connectbot")) && ei.inputType == 0);
	}

	private void sendTab() {
		InputConnection ic = getCurrentInputConnection();
		if (ic == null)
			return;
		boolean tabHack = isConnectBot();

		// Note: tab and ^I don't work in ConnectBot, hackish workaround
		if (tabHack) {
			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 {
			ic.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN,
					KeyEvent.KEYCODE_TAB));
			ic.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_UP,
					KeyEvent.KEYCODE_TAB));
		}
	}

	private void sendEscape() {
		InputConnection ic = getCurrentInputConnection();
		if (ic == null)
			return;
		if (isConnectBot()) {
			sendKeyChar((char) 27);
		} else {
			ic.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, 111 /* KEYCODE_ESCAPE */));
			ic.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, 111 /* KEYCODE_ESCAPE */));
		}
	}

	public void setKeyboardStuffBeforeSetToView(AnyKeyboard currentKeyboard) {
		currentKeyboard.setCondensedKeys(mKeyboardInCondensedMode);
	}

	private void showLanguageSelectionDialog() {
		KeyboardAddOnAndBuilder[] builders = mKeyboardSwitcher
				.getEnabledKeyboardsBuilders();
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setCancelable(true);
		builder.setIcon(R.drawable.ic_launcher);
		builder.setTitle(getResources().getString(
				R.string.select_keyboard_popup_title));
		builder.setNegativeButton(android.R.string.cancel, null);
		ArrayList<CharSequence> keyboardsIds = new ArrayList<>();
		ArrayList<CharSequence> keyboards = new ArrayList<>();
		// going over all enabled keyboards
		for (KeyboardAddOnAndBuilder keyboardBuilder : builders) {
			keyboardsIds.add(keyboardBuilder.getId());
			String name = keyboardBuilder.getName();

			keyboards.add(name);
		}

		final CharSequence[] ids = new CharSequence[keyboardsIds.size()];
		final CharSequence[] items = new CharSequence[keyboards.size()];
		keyboardsIds.toArray(ids);
		keyboards.toArray(items);

		builder.setItems(items, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface di, int position) {
				di.dismiss();

				if ((position < 0) || (position >= items.length)) {
					Log.d(TAG, "Keyboard selection popup canceled");
				} else {
					CharSequence id = ids[position];
					Log.d(TAG, "User selected '%s' with id %s", items[position], id);
					EditorInfo currentEditorInfo = getCurrentInputEditorInfo();
					mKeyboardSwitcher.nextAlphabetKeyboard(currentEditorInfo, id.toString());
					setKeyboardFinalStuff(NextKeyboardType.Alphabet);
				}
			}
		});

		mOptionsDialog = builder.create();
		Window window = mOptionsDialog.getWindow();
		WindowManager.LayoutParams lp = window.getAttributes();
		lp.token = mInputView.getWindowToken();
		lp.type = WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG;
		window.setAttributes(lp);
		window.addFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
		mOptionsDialog.show();
	}

	public void onText(CharSequence text) {
		Log.d(TAG, "onText: '%s'", text);
		InputConnection ic = getCurrentInputConnection();
		if (ic == null)
			return;
		ic.beginBatchEdit();
		if (mPredicting) {
			commitTyped(ic);
		}
		abortCorrection(true, false);
		ic.commitText(text, 1);
		ic.endBatchEdit();

		mJustAddedAutoSpace = false;
		mJustAddOnText = text;
	}

	private boolean performOnTextDeletion(InputConnection ic) {
		if (mJustAddOnText != null && ic != null) {
			final CharSequence onTextText = mJustAddOnText;
			mJustAddOnText = null;
			//just now, the user had cause onText to add text to input.
			//but after that, immediately pressed delete. So I'm guessing deleting the entire text is needed
			final int onTextLength = onTextText.length();
			Log.d(TAG, "Deleting the entire 'onText' input " + onTextText);
			CharSequence cs = ic.getTextBeforeCursor(onTextLength, 0);
			if (onTextText.equals(cs)) {
				ic.deleteSurroundingText(onTextLength, 0);
				return true;
			}
		}

		return false;
	}

	private void handleBackWord(InputConnection ic) {
		if (ic == null) {
			return;
		}

		if (performOnTextDeletion(ic))
			return;

		if (mPredicting) {
			mWord.reset();
			mPredicting = false;
			ic.setComposingText("", 1);
			postUpdateSuggestions();
			return;
		}
		// I will not delete more than 128 characters. Just a safe-guard.
		// this will also allow me do just one call to getTextBeforeCursor!
		// Which is always good. This is a part of issue 951.
		CharSequence cs = ic.getTextBeforeCursor(128, 0);
		if (TextUtils.isEmpty(cs)) {
			return;// nothing to delete
		}
		// TWO OPTIONS
		// 1) Either we do like Linux and Windows (and probably ALL desktop
		// OSes):
		// Delete all the characters till a complete word was deleted:
		/*
		 * What to do: We delete until we find a separator (the function
		 * isBackWordStopChar). Note that we MUST delete a delete a whole word!
		 * So if the back-word starts at separators, we'll delete those, and then
		 * the word before: "test this,       ," -> "test "
		 */
		// Pro: same as desktop
		// Con: when auto-caps is on (the default), this will delete the
		// previous word, which can be annoying..
		// E.g., Writing a sentence, then a period, then ASK will auto-caps,
		// then when the user press backspace (for some reason),
		// the entire previous word deletes.

		// 2) Or we delete all the characters till we encounter a separator, but
		// delete at least one character.
		/*
		 * What to do: We delete until we find a separator (the function
		 * isBackWordStopChar). Note that we MUST delete a delete at least one
		 * character "test this, " -> "test this," -> "test this" -> "test "
		 */
		// Pro: Supports auto-caps, and mostly similar to desktop OSes
		// Con: Not all desktop use-cases are here.

		// For now, I go with option 2, but I'm open for discussion.

		// 2b) "test this, " -> "test this"

		final int inputLength = cs.length();
		int idx = inputLength - 1;// it's OK since we checked whether cs is
		// empty after retrieving it.
		while (idx > 0 && !isBackWordStopChar((int) cs.charAt(idx))) {
			idx--;
		}
		ic.deleteSurroundingText(inputLength - idx, 0);// it is always > 0 !
	}

	private void handleDeleteLastCharacter(boolean forMultiTap) {
		InputConnection ic = getCurrentInputConnection();

		if (!forMultiTap && performOnTextDeletion(ic))
			return;

		boolean deleteChar = false;
		if (mPredicting) {
			final boolean wordManipulation = mWord.length() > 0
					&& mWord.cursorPosition() > 0;
			if (wordManipulation) {
				mWord.deleteLast();
				final int cursorPosition;
				if (mWord.cursorPosition() != mWord.length())
					cursorPosition = getCursorPosition(ic);
				else
					cursorPosition = -1;

				if (cursorPosition >= 0)
					ic.beginBatchEdit();

				ic.setComposingText(mWord.getTypedWord(), 1);
				if (mWord.length() == 0) {
					mPredicting = false;
				} else if (cursorPosition >= 0) {
					ic.setSelection(cursorPosition - 1, cursorPosition - 1);
				}

				if (cursorPosition >= 0)
					ic.endBatchEdit();

				postUpdateSuggestions();
			} else {
				ic.deleteSurroundingText(1, 0);
			}
		} else {
			deleteChar = true;
		}

		TextEntryState.backspace();
		if (TextEntryState.getState() == TextEntryState.State.UNDO_COMMIT) {
			revertLastWord(deleteChar);
		} else if (deleteChar) {
			if (mCandidateView != null
					&& mCandidateView.dismissAddToDictionaryHint()) {
				// Go back to the suggestion mode if the user canceled the
				// "Touch again to save".
				// NOTE: 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(true/*this is a Delete character*/);
			} else {
				if (!forMultiTap) {
					sendDownUpKeyEvents(KeyEvent.KEYCODE_DEL);
				} else {
					// this code tries to delete the text in a different way,
					// because of multi-tap stuff
					// using "deleteSurroundingText" will actually get the input
					// updated faster!
					// but will not handle "delete all selected text" feature,
					// hence the "if (!forMultiTap)" above
					final CharSequence beforeText = ic == null ? null : ic.getTextBeforeCursor(1, 0);
					final int textLengthBeforeDelete = (TextUtils.isEmpty(beforeText)) ? 0 : beforeText.length();
					if (textLengthBeforeDelete > 0)
						ic.deleteSurroundingText(1, 0);
					else
						sendDownUpKeyEvents(KeyEvent.KEYCODE_DEL);
				}
			}
		}
	}

	private void handleControl() {
		if (mInputView != null && mKeyboardSwitcher.isAlphabetMode()) {
			mInputView.setControl(mControlKeyState.isActive());
		}
	}

	private void handleShift() {
		if (mInputView != null) {
			Log.d(TAG, "shift Setting UI active:%s, locked: %s", mShiftKeyState.isActive(), mShiftKeyState.isLocked());
			mInputView.setShifted(mShiftKeyState.isActive());
			mInputView.setShiftLocked(mShiftKeyState.isLocked());
		}
	}

	private void abortCorrection(boolean force, boolean forever) {
		if (force || TextEntryState.isCorrecting()) {
			Log.d(TAG, "abortCorrection will actually abort correct");
			mHandler.removeMessages(KeyboardUIStateHandler.MSG_UPDATE_SUGGESTIONS);
			mHandler.removeMessages(KeyboardUIStateHandler.MSG_RESTART_NEW_WORD_SUGGESTIONS);

			final InputConnection ic = getCurrentInputConnection();
			if (ic != null)
				ic.finishComposingText();

			clearSuggestions();

			TextEntryState.reset();
			mUndoCommitCursorPosition = -2;
			mWord.reset();
			mPredicting = false;
			mJustAddedAutoSpace = false;
			if (forever) {
				Log.d(TAG, "abortCorrection will abort correct forever");
				mPredictionOn = false;
				setCandidatesViewShown(false);
				if (mSuggest != null) {
					mSuggest.setCorrectionMode(false, false);
				}
			}
		}
	}

	private void handleCharacter(final int primaryCode, Key key,
	                             int multiTapIndex, int[] nearByKeyCodes) {
		Log.d(TAG, "handleCharacter: " + primaryCode + ", isPredictionOn:"
				+ isPredictionOn() + ", mPredicting:" + mPredicting);
		if (!mPredicting && isPredictionOn() && isAlphabet(primaryCode)
				&& !isCursorTouchingWord()) {
			mPredicting = true;
			mUndoCommitCursorPosition = -2;// so it will be marked the next time
			mWord.reset();
			mAutoCorrectOn = mAutoComplete;
		}

		mLastCharacterWasShifted = (mInputView != null)
				&& mInputView.isShifted();

		// if (mLastSelectionStart == mLastSelectionEnd &&
		// TextEntryState.isCorrecting()) {
		// abortCorrection(false);
		// }

		final int primaryCodeForShow;
		if (mInputView != null) {
			if (mInputView.isShifted()) {
				if (key != null && key instanceof AnyKey) {
					AnyKey anyKey = (AnyKey) key;
					int[] shiftCodes = anyKey.shiftedCodes;
					primaryCodeForShow = shiftCodes != null
							&& shiftCodes.length > multiTapIndex ? shiftCodes[multiTapIndex]
							: Character.toUpperCase(primaryCode);
				} else {
					primaryCodeForShow = Character.toUpperCase(primaryCode);
				}
			} else {
				primaryCodeForShow = primaryCode;
			}
		} else {
			primaryCodeForShow = primaryCode;
		}

		if (mPredicting) {
			if ((mInputView != null) && mInputView.isShifted()
					&& mWord.cursorPosition() == 0) {
				mWord.setFirstCharCapitalized(true);
			}

			final InputConnection ic = getCurrentInputConnection();
			if (mWord.add(primaryCodeForShow, nearByKeyCodes)) {
				Toast note = Toast
						.makeText(
								getApplicationContext(),
								"Check the logcat for a note from AnySoftKeyboard developers!",
								Toast.LENGTH_LONG);
				note.show();

				Log.i(TAG,
						"*******************"
								+ "\nNICE!!! You found the our easter egg! http://www.dailymotion.com/video/x3zg90_gnarls-barkley-crazy-2006-mtv-star_music\n"
								+ "\nAnySoftKeyboard R&D team would like to thank you for using our keyboard application."
								+ "\nWe hope you enjoying it, we enjoyed making it."
								+ "\nWhile developing this application, we heard Gnarls Barkley's Crazy quite a lot, and would like to share it with you."
								+ "\n"
								+ "\nThanks."
								+ "\nMenny Even Danan, Hezi Cohen, Hugo Lopes, Henrik Andersson, Sami Salonen, and Lado Kumsiashvili."
								+ "\n*******************");

				Intent easterEgg = new Intent(
						Intent.ACTION_VIEW,
						Uri.parse("http://www.dailymotion.com/video/x3zg90_gnarls-barkley-crazy-2006-mtv-star_music"));
				easterEgg.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivity(easterEgg);
			}
			if (ic != null) {
				final int cursorPosition;
				if (mWord.cursorPosition() != mWord.length()) {
					Log.d(TAG,
							"Cursor is not at the end of the word. I'll need to reposition");
					cursorPosition = getCursorPosition(ic);
				} else {
					cursorPosition = -1;
				}

				if (cursorPosition >= 0)
					ic.beginBatchEdit();

				ic.setComposingText(mWord.getTypedWord(), 1);
				if (cursorPosition >= 0) {
					ic.setSelection(cursorPosition + 1, cursorPosition + 1);
					ic.endBatchEdit();
				}
			}
			// this should be done ONLY if the key is a letter, and not a inner
			// character (like ').
			if (Character.isLetter((char) primaryCodeForShow)) {
				postUpdateSuggestions();
			} else {
				// just replace the typed word in the candidates view
				if (mCandidateView != null)
					mCandidateView.replaceTypedWord(mWord.getTypedWord());
			}
		} else {
			sendKeyChar((char) primaryCodeForShow);
		}
		TextEntryState.typedCharacter((char) primaryCodeForShow, false);
	}

	private void handleSeparator(int primaryCode) {
		Log.d(TAG, "handleSeparator: " + primaryCode);

		// 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();
		}
		// this is a special case, when the user presses a separator WHILE
		// inside the predicted word.
		// in this case, I will want to just dump the separator.
		final boolean separatorInsideWord = (mWord.cursorPosition() < mWord.length());

		if (mPredicting && !separatorInsideWord) {
			// 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.
			//Also, ACTION does not invoke default picking. See https://github.com/AnySoftKeyboard/AnySoftKeyboard/issues/198
			if (mAutoCorrectOn && primaryCode != '\'' && primaryCode != KeyCodes.ENTER) {
				pickedDefault = pickDefaultSuggestion();
				// Picked the suggestion by the space key. We consider this
				// as "added an auto space".
				if (primaryCode == KeyCodes.SPACE) {
					mJustAddedAutoSpace = true;
				}
			} else {
				commitTyped(ic);
				abortCorrection(true, false);
			}
		} else if (separatorInsideWord) {
			// when putting a separator in the middle of a word, there is no
			// need to do correction, or keep knowledge
			abortCorrection(true, false);
		}

		if (mJustAddedAutoSpace && primaryCode == KeyCodes.ENTER) {
			removeTrailingSpace();
			mJustAddedAutoSpace = false;
		}

		final EditorInfo ei = getCurrentInputEditorInfo();
		if (primaryCode == KeyCodes.ENTER && mShiftKeyState.isActive() && ic != null && ei != null && (ei.imeOptions & EditorInfo.IME_MASK_ACTION) != EditorInfo.IME_ACTION_NONE) {
			//power-users feature ahead: Shift+Enter
			//getting away from firing the default editor action, by forcing newline
			ic.commitText("\n", 1);
		} else {
			sendKeyChar((char) primaryCode);
		}

		// Handle the case of ". ." -> " .." with auto-space if necessary
		// before changing the TextEntryState.
		if (mJustAddedAutoSpace && primaryCode == '.') {
			swapPeriodAndSpace();
		}

		TextEntryState.typedCharacter((char) primaryCode, true);
		if (TextEntryState.getState() == TextEntryState.State.PUNCTUATION_AFTER_ACCEPTED
				&& primaryCode != KeyCodes.ENTER) {
			swapPunctuationAndSpace();
		} else if (/* isPredictionOn() && */primaryCode == ' ') {
			doubleSpace();
		}
		if (pickedDefault && mWord.getPreferredWord() != null) {
			TextEntryState.acceptedDefault(mWord.getTypedWord(),
					mWord.getPreferredWord());
		}
		if (ic != null) {
			ic.endBatchEdit();
		}
	}

	private void handleClose() {
		boolean closeSelf = true;

		if (mInputView != null)
			closeSelf = mInputView.closing();

		if (closeSelf) {
			commitTyped(getCurrentInputConnection());
			requestHideSelf(0);
			abortCorrection(true, true);
			TextEntryState.endSession();
		}
	}

	private void postUpdateSuggestions() {
		postUpdateSuggestions(5 * ONE_FRAME_DELAY);
	}

	/**
	 * posts an update suggestions request to the messages queue. Removes any previous request.
	 *
	 * @param delay negative value will cause the call to be done now, in this thread.
	 */
	private void postUpdateSuggestions(long delay) {
		mHandler.removeMessages(KeyboardUIStateHandler.MSG_UPDATE_SUGGESTIONS);
		if (delay > 0)
			mHandler.sendMessageDelayed(mHandler.obtainMessage(KeyboardUIStateHandler.MSG_UPDATE_SUGGESTIONS), delay);
		else if (delay == 0)
			mHandler.sendMessage(mHandler.obtainMessage(KeyboardUIStateHandler.MSG_UPDATE_SUGGESTIONS));
		else
			performUpdateSuggestions();
	}

	private boolean isPredictionOn() {
		return mPredictionOn;
	}

	private boolean shouldCandidatesStripBeShown() {
		return mShowSuggestions && onEvaluateInputViewShown();
	}

	/*package*/ void performUpdateSuggestions() {
		Log.d(TAG, "performUpdateSuggestions: has mSuggest:"
				+ (mSuggest != null) + ", isPredictionOn:"
				+ isPredictionOn() + ", mPredicting:" + mPredicting
				+ ", mQuickFixes:" + mQuickFixes + " mShowSuggestions:"
				+ mShowSuggestions);
		// Check if we have a suggestion engine attached.
		if (mSuggest == null) {
			return;
		}

		// final boolean showSuggestions = (mCandidateView != null &&
		// mPredicting
		// && isPredictionOn() && shouldCandidatesStripBeShown());

		if (mCandidateCloseText != null)// in API3 this variable is null
			mCandidateCloseText.setVisibility(View.GONE);

		if (!mPredicting) {
			setSuggestions(null, false, false, false);
			return;
		}

		List<CharSequence> stringList = mSuggest.getSuggestions(/* mInputView, */mWord, false);
		boolean correctionAvailable = mSuggest.hasMinimalCorrection();
		// || mCorrectionMode == mSuggest.CORRECTION_FULL;
		CharSequence typedWord = mWord.getTypedWord();
		// If we're in basic correct
		boolean typedWordValid = mSuggest.isValidWord(typedWord);/*
		        || (preferCapitalization() && mSuggest.isValidWord(typedWord
                .toString().toLowerCase()));*/

		if (mShowSuggestions || mQuickFixes) {
			correctionAvailable |= typedWordValid;
		}

		// Don't auto-correct words with multiple capital letter
		correctionAvailable &= !mWord.isMostlyCaps();
		correctionAvailable &= !TextEntryState.isCorrecting();

		setSuggestions(stringList, false, typedWordValid, correctionAvailable);
		if (stringList.size() > 0) {
			if (correctionAvailable && !typedWordValid && stringList.size() > 1) {
				mWord.setPreferredWord(stringList.get(1));
			} else {
				mWord.setPreferredWord(typedWord);
			}
		} else {
			mWord.setPreferredWord(null);
		}
		setCandidatesViewShown(shouldCandidatesStripBeShown() || mCompletionOn);
	}

	private boolean pickDefaultSuggestion() {

		// Complete any pending candidate query first
		if (mHandler.hasMessages(KeyboardUIStateHandler.MSG_UPDATE_SUGGESTIONS)) {
			postUpdateSuggestions(-1);
		}

		final CharSequence bestWord = mWord.getPreferredWord();
		Log.d(TAG, "pickDefaultSuggestion: bestWord:" + bestWord);

		if (!TextUtils.isEmpty(bestWord)) {
			final CharSequence typedWord = mWord.getTypedWord();
			TextEntryState.acceptedDefault(typedWord, bestWord);
			final boolean fixed = !typedWord.equals(pickSuggestion(bestWord, !bestWord.equals(typedWord)));
			if (!fixed) {//if the word typed was auto-replaced, we should not learn it.
				// Add the word to the auto dictionary if it's not a known word
				addToDictionaries(mWord, AutoDictionary.AdditionType.Typed);
			}
			return true;
		}
		return false;
	}

	public void pickSuggestionManually(int index, CharSequence suggestion) {
		Log.d(TAG, "pickSuggestionManually: index " + index
				+ " suggestion " + suggestion);
		final boolean correcting = TextEntryState.isCorrecting();
		final InputConnection ic = getCurrentInputConnection();
		if (ic != null) {
			ic.beginBatchEdit();
		}
		try {
			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();
				}
				return;
			}
			pickSuggestion(suggestion, correcting);

			TextEntryState.acceptedSuggestion(mWord.getTypedWord(), suggestion);
			// Follow it with a space
			if (mAutoSpace && !correcting) {
				sendSpace();
				mJustAddedAutoSpace = true;
			}
			// Add the word to the auto dictionary if it's not a known word
			mJustAutoAddedWord = false;
			if (index == 0) {
				mJustAutoAddedWord = addToDictionaries(mWord, AutoDictionary.AdditionType.Picked);
			}

			final boolean showingAddToDictionaryHint = !mJustAutoAddedWord
					&& index == 0
					&& (mQuickFixes || mShowSuggestions)
					&& !mSuggest.isValidWord(suggestion)// this is for the case
					// that the word was
					// auto-added upon
					// picking
					&& !mSuggest.isValidWord(suggestion.toString()
					.toLowerCase());

			if (!mJustAutoAddedWord) {
				/*
				 * 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) KeyCodes.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 != null) {
					mCandidateView.showAddToDictionaryHint(suggestion);
				}
			}
		} finally {
			if (ic != null) {
				ic.endBatchEdit();
			}
		}
	}

	/**
	 * 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 CharSequence pickSuggestion(CharSequence suggestion,
	                                    boolean correcting) {
		if (mShiftKeyState.isLocked()) {
			suggestion = suggestion.toString().toUpperCase();
		} else if (preferCapitalization()
				|| (mKeyboardSwitcher.isAlphabetMode() && (mInputView != null) && mInputView
				.isShifted())) {
			suggestion = Character.toUpperCase(suggestion.charAt(0))
					+ suggestion.subSequence(1, suggestion.length()).toString();
		}

		mWord.setPreferredWord(suggestion);
		InputConnection ic = getCurrentInputConnection();
		if (ic != null) {
			if (correcting) {
				AnyApplication.getDeviceSpecific()
						.commitCorrectionToInputConnection(ic, mWord);
				// and drawing popout text
				mInputView.popTextOutOfKey(mWord.getPreferredWord());
			} else {
				ic.commitText(suggestion, 1);
			}
		}
		mPredicting = false;
		mCommittedLength = suggestion.length();
		setSuggestions(null, false, false, false);
		// If we just corrected a word, then don't show punctuations
		if (!correcting) {
			setNextSuggestions();
		}

		return suggestion;
	}

	private boolean isCursorTouchingWord() {
		InputConnection ic = getCurrentInputConnection();
		if (ic == null)
			return false;

		CharSequence toLeft = ic.getTextBeforeCursor(1, 0);
		// It is not exactly clear to me why, but sometimes, although I request
		// 1 character, I get
		// the entire text. This causes me to incorrectly detect restart
		// suggestions...
		if (!TextUtils.isEmpty(toLeft) && toLeft.length() == 1
				&& !isWordSeparator(toLeft.charAt(0))) {
			return true;
		}

		CharSequence toRight = ic.getTextAfterCursor(1, 0);
		return (!TextUtils.isEmpty(toRight)) &&
				(toRight.length() == 1) &&
				(!isWordSeparator(toRight.charAt(0)));
	}

	public void revertLastWord(boolean deleteChar) {
		Log.d(TAG, "revertLastWord deleteChar:" + deleteChar
				+ ", mWord.size:" + mWord.length() + " mPredicting:"
				+ mPredicting + " mCommittedLength" + mCommittedLength);

		final int length = mWord.length();// mComposing.length();
		if (!mPredicting && length > 0) {
			mAutoCorrectOn = false;
			final CharSequence typedWord = mWord.getTypedWord();
			final InputConnection ic = getCurrentInputConnection();
			mPredicting = true;
			mUndoCommitCursorPosition = -2;
			ic.beginBatchEdit();
			// 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(typedWord/* mComposing */, 1);
			TextEntryState.backspace();
			ic.endBatchEdit();
			postUpdateSuggestions(-1);
			if (mJustAutoAddedWord && mUserDictionary != null) {
				// we'll also need to REMOVE the word from the user dictionary
				// now...
				// Since the user revert the committed word, and ASK auto-added
				// that word, this word will need to be removed.
				Log.i(TAG,
						"Since the word '"
								+ typedWord
								+ "' was auto-added to the user-dictionary, it will not be deleted.");
				removeFromUserDictionary(typedWord.toString());
			}
		} else {
			sendDownUpKeyEvents(KeyEvent.KEYCODE_DEL);
			// mJustRevertedSeparator = null;
		}
	}

	private void setNextSuggestions() {
		setSuggestions(
		/* mSuggest.getInitialSuggestions() */msEmptyNextSuggestions, false,
				false, false);
	}

	public boolean isWordSeparator(int code) {
		return (!isAlphabet(code));
	}

	private void sendSpace() {
		sendKeyChar((char) KeyCodes.SPACE);
	}

	public boolean preferCapitalization() {
		return mWord.isFirstCharCapitalized();
	}

	private void nextAlterKeyboard(EditorInfo currentEditorInfo) {
		Log.d(TAG, "nextAlterKeyboard: currentEditorInfo.inputType="
				+ currentEditorInfo.inputType);

		// AnyKeyboard currentKeyboard = mKeyboardSwitcher.getCurrentKeyboard();
		if (getCurrentKeyboard() == null) {
			Log.d(TAG,
					"nextKeyboard: Looking for next keyboard. No current keyboard.");
		} else {
			Log.d(TAG,
					"nextKeyboard: Looking for next keyboard. Current keyboard is:"
							+ getCurrentKeyboard().getKeyboardName());
		}

		mKeyboardSwitcher.nextAlterKeyboard(currentEditorInfo);

		Log.i(TAG, "nextAlterKeyboard: Setting next keyboard to: "
				+ getCurrentKeyboard().getKeyboardName());
	}

	private void nextKeyboard(EditorInfo currentEditorInfo,
	                          KeyboardSwitcher.NextKeyboardType type) {
		Log.d(TAG, "nextKeyboard: currentEditorInfo.inputType="
				+ currentEditorInfo.inputType + " type:" + type);

		// in numeric keyboards, the LANG key will go back to the original
		// alphabet keyboard-
		// so no need to look for the next keyboard, 'mLastSelectedKeyboard'
		// holds the last
		// keyboard used.
		AnyKeyboard keyboard = mKeyboardSwitcher.nextKeyboard(currentEditorInfo, type);

		if (!(keyboard instanceof GenericKeyboard)) {
			mSentenceSeparators = keyboard.getSentenceSeparators();
		}
		setKeyboardFinalStuff(type);
	}

	private void setKeyboardFinalStuff( KeyboardSwitcher.NextKeyboardType type) {
		mShiftKeyState.reset();
		mControlKeyState.reset();
		// changing dictionary
		setDictionariesForCurrentKeyboard();
		// Notifying if needed
		if ((mKeyboardChangeNotificationType.equals(KEYBOARD_NOTIFICATION_ALWAYS))
				|| (mKeyboardChangeNotificationType.equals(KEYBOARD_NOTIFICATION_ON_PHYSICAL) && (type == NextKeyboardType.AlphabetSupportsPhysical))) {
			notifyKeyboardChangeIfNeeded();
		}
		postUpdateSuggestions();
	}

	public void onSwipeRight(boolean onSpaceBar, boolean twoFingersGesture) {
		final int keyCode = mAskPrefs.getGestureSwipeRightKeyCode(onSpaceBar, twoFingersGesture);
		Log.d(TAG, "onSwipeRight " + ((onSpaceBar) ? " + space" : "") + ((twoFingersGesture) ? " + two-fingers" : "")
				+ " => code " + keyCode);
		if (keyCode != 0)
			mSwitchAnimator
					.doSwitchAnimation(AnimationType.SwipeRight, keyCode);
	}

	public void onSwipeLeft(boolean onSpaceBar, boolean twoFingersGesture) {
		final int keyCode = mAskPrefs.getGestureSwipeLeftKeyCode(onSpaceBar, twoFingersGesture);
		Log.d(TAG, "onSwipeLeft " + ((onSpaceBar) ? " + space" : "") + ((twoFingersGesture) ? " + two-fingers" : "")
				+ " => code " + keyCode);
		if (keyCode != 0)
			mSwitchAnimator.doSwitchAnimation(AnimationType.SwipeLeft, keyCode);
	}

	public void onSwipeDown(boolean onSpaceBar) {
		final int keyCode = mAskPrefs.getGestureSwipeDownKeyCode();
		Log.d(TAG, "onSwipeDown " + ((onSpaceBar) ? " + space" : "")
				+ " => code " + keyCode);
		if (keyCode != 0)
			onKey(keyCode, null, -1, new int[]{keyCode}, false);
	}

	public void onSwipeUp(boolean onSpaceBar) {
		final int keyCode = mAskPrefs.getGestureSwipeUpKeyCode(onSpaceBar);
		Log.d(TAG, "onSwipeUp " + ((onSpaceBar) ? " + space" : "")
				+ " => code " + keyCode);
		if (keyCode != 0) {
			onKey(keyCode, null, -1, new int[]{keyCode}, false);
		}
	}

	public void onPinch() {
		final int keyCode = mAskPrefs.getGesturePinchKeyCode();
		Log.d(TAG, "onPinch => code " + keyCode);
		if (keyCode != 0)
			onKey(keyCode, null, -1, new int[]{keyCode}, false);
	}

	public void onSeparate() {
		final int keyCode = mAskPrefs.getGestureSeparateKeyCode();
		Log.d(TAG, "onSeparate => code " + keyCode);
		if (keyCode != 0)
			onKey(keyCode, null, -1, new int[]{keyCode}, false);
	}

	private void sendKeyDown(InputConnection ic, int key) {
		if (ic != null)
			ic.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, key));
	}

	private void sendKeyUp(InputConnection ic, int key) {
		if (ic != null)
			ic.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, key));
	}

	public void onPress(int primaryCode) {
		InputConnection ic = getCurrentInputConnection();
		Log.d(TAG, "onPress:" + primaryCode);
		if (mVibrationDuration > 0 && primaryCode != 0) {
			mVibrator.vibrate(mVibrationDuration);
		}

		if (primaryCode == KeyCodes.SHIFT) {
			mShiftKeyState.onPress();
			handleShift();
		} else {
			mShiftKeyState.onOtherKeyPressed();
		}

		if (primaryCode == KeyCodes.CTRL) {
			mControlKeyState.onPress();
			handleControl();
			sendKeyDown(ic, 113); // KeyEvent.KEYCODE_CTRL_LEFT (API 11 and up)
		} else {
			mControlKeyState.onOtherKeyPressed();
		}

		if (mSoundOn && (!mSilentMode) && primaryCode != 0) {
			final int keyFX;
			switch (primaryCode) {
				case 13:
				case KeyCodes.ENTER:
					keyFX = AudioManager.FX_KEYPRESS_RETURN;
					break;
				case KeyCodes.DELETE:
					keyFX = AudioManager.FX_KEYPRESS_DELETE;
					break;
				case KeyCodes.SPACE:
					keyFX = AudioManager.FX_KEYPRESS_SPACEBAR;
					break;
				default:
					keyFX = AudioManager.FX_KEY_CLICK;
			}
			final float fxVolume;
			// creating scoop to make sure volume and maxVolume
			// are not used
			{
				final int volume;
				final int maxVolume;
				if (mSoundVolume > 0) {
					volume = mSoundVolume;
					maxVolume = 100;
					// pre-eclair
					// volume is between 0..8 (float)
					// eclair
					// volume is between 0..1 (float)
					if (Workarounds.getApiLevel() >= 5) {
						fxVolume = ((float) volume) / ((float) maxVolume);
					} else {
						fxVolume = 8 * ((float) volume) / ((float) maxVolume);
					}
				} else {
					fxVolume = -1.0f;
				}

			}

			Log.d(TAG, "Sound on key-pressed. Sound ID:" + keyFX
					+ " with volume " + fxVolume);

			mAudioManager.playSoundEffect(keyFX, fxVolume);
		}
	}

	public void onRelease(int primaryCode) {
		InputConnection ic = getCurrentInputConnection();
		Log.d(TAG, "onRelease:" + primaryCode);
		if (primaryCode == KeyCodes.SHIFT) {
			mShiftKeyState.onRelease(mAskPrefs.getMultiTapTimeout());
		} else {
			mShiftKeyState.onOtherKeyReleased();
		}
		handleShift();

		if (primaryCode == KeyCodes.CTRL) {
			sendKeyUp(ic, 113); // KeyEvent.KEYCODE_CTRL_LEFT
			mControlKeyState.onRelease(mAskPrefs.getMultiTapTimeout());
		} else {
			mControlKeyState.onOtherKeyReleased();
		}
		handleControl();
	}

	// update flags for silent mode
	public void updateRingerMode() {
		mSilentMode = (mAudioManager.getRingerMode() != AudioManager.RINGER_MODE_NORMAL);
	}

	private void loadSettings() {
		// Get the settings preferences
		SharedPreferences sp = PreferenceManager
				.getDefaultSharedPreferences(this);

		mVibrationDuration = Integer
				.parseInt(sp
						.getString(
								getString(R.string.settings_key_vibrate_on_key_press_duration),
								getString(R.string.settings_default_vibrate_on_key_press_duration)));

		mSoundOn = sp.getBoolean(getString(R.string.settings_key_sound_on),
				getResources().getBoolean(R.bool.settings_default_sound_on));
		if (mSoundOn) {
			Log.i(TAG,
					"Loading sounds effects from AUDIO_SERVICE due to configuration change.");
			mAudioManager.loadSoundEffects();
		}
		// checking the volume
		boolean customVolume = sp.getBoolean("use_custom_sound_volume", false);
		int newVolume;
		if (customVolume) {
			newVolume = sp.getInt("custom_sound_volume", 0) + 1;
			Log.i(TAG, "Custom volume checked: " + newVolume + " out of 100");
		} else {
			Log.i(TAG, "Custom volume un-checked.");
			newVolume = -1;
		}
		mSoundVolume = newVolume;

		// in order to support the old type of configuration
		mKeyboardChangeNotificationType = sp
				.getString(
						getString(R.string.settings_key_physical_keyboard_change_notification_type),
						getString(R.string.settings_default_physical_keyboard_change_notification_type));

		// now clearing the notification, and it will be re-shown if needed
		mInputMethodManager.hideStatusIcon(mImeToken);
		// mNotificationManager.cancel(KEYBOARD_NOTIFICATION_ID);
		// should it be always on?
		if (mKeyboardChangeNotificationType
				.equals(KEYBOARD_NOTIFICATION_ALWAYS))
			notifyKeyboardChangeIfNeeded();

		mAutoCap = sp.getBoolean("auto_caps", true);

		mShowSuggestions = sp.getBoolean("candidates_on", true);

		setDictionariesForCurrentKeyboard();

		mAutoComplete = sp.getBoolean("auto_complete", true)
				&& mShowSuggestions;

		mQuickFixes = sp.getBoolean("quick_fix", true);

		mAllowSuggestionsRestart = sp.getBoolean(
				getString(R.string.settings_key_allow_suggestions_restart),
				getResources().getBoolean(
						R.bool.settings_default_allow_suggestions_restart));

		mAutoCorrectOn = mAutoComplete;

		// mCorrectionMode = mAutoComplete ? 2
		// : (/*mShowSuggestions*/ mQuickFixes ? 1 : 0);

		mSmileyOnShortPress = sp
				.getBoolean(
						getString(R.string.settings_key_emoticon_long_press_opens_popup),
						getResources()
								.getBoolean(
										R.bool.settings_default_emoticon_long_press_opens_popup));
		// mSmileyPopupType =
		// sp.getString(getString(R.string.settings_key_smiley_popup_type),
		// getString(R.string.settings_default_smiley_popup_type));
		mOverrideQuickTextText = sp.getString(
				getString(R.string.settings_key_emoticon_default_text), null);

		mMinimumWordCorrectionLength = sp
				.getInt(getString(R.string.settings_key_min_length_for_word_correction__),
						2);
		if (mSuggest != null)
			mSuggest.setMinimumWordLengthForCorrection(mMinimumWordCorrectionLength);

		setInitialCondensedState(getResources().getConfiguration());
	}

	private void setDictionariesForCurrentKeyboard() {
		if (mSuggest != null) {
			if (!mPredictionOn) {
				Log.d(TAG,
						"No suggestion is required. I'll try to release memory from the dictionary.");
				// DictionaryFactory.getInstance().releaseAllDictionaries();
				mSuggest.setMainDictionary(getApplicationContext(), null);
				mSuggest.setUserDictionary(null);
				mSuggest.setAutoDictionary(null);
				mLastDictionaryRefresh = -1;
			} else {
				mLastDictionaryRefresh = SystemClock.elapsedRealtime();
				// It null at the creation of the application.
				if ((mKeyboardSwitcher != null)
						&& mKeyboardSwitcher.isAlphabetMode()) {
					AnyKeyboard currentKeyobard = mKeyboardSwitcher
							.getCurrentKeyboard();

					// if there is a mapping in the settings, we'll use that,
					// else we'll
					// return the default
					String mappingSettingsKey = getDictionaryOverrideKey(currentKeyobard);
					String defaultDictionary = currentKeyobard
							.getDefaultDictionaryLocale();
					String dictionaryValue = mPrefs.getString(
							mappingSettingsKey, null);

					final DictionaryAddOnAndBuilder dictionaryBuilder;

					if (dictionaryValue == null) {
						dictionaryBuilder = ExternalDictionaryFactory
								.getDictionaryBuilderByLocale(currentKeyobard
												.getDefaultDictionaryLocale(),
										getApplicationContext());
					} else {
						Log.d(TAG, "Default dictionary '%s' for keyboard '%s' has been overridden to '%s'",
								defaultDictionary, currentKeyobard.getKeyboardPrefId(), dictionaryValue);
						dictionaryBuilder =
								ExternalDictionaryFactory.getDictionaryBuilderById(dictionaryValue, getApplicationContext());
					}

					mSuggest.setMainDictionary(getApplicationContext(), dictionaryBuilder);
					String localeForSupportingDictionaries = dictionaryBuilder != null ? dictionaryBuilder
							.getLanguage() : defaultDictionary;
					mUserDictionary = mSuggest.getDictionaryFactory()
							.createUserDictionary(getApplicationContext(),
									localeForSupportingDictionaries);
					mSuggest.setUserDictionary(mUserDictionary);

					mAutoDictionary = mSuggest.getDictionaryFactory().createAutoDictionary(getApplicationContext(), localeForSupportingDictionaries);
					mSuggest.setAutoDictionary(mAutoDictionary);
					mSuggest.setContactsDictionary(getApplicationContext(), mAskPrefs.useContactsDictionary());
				}
			}
		}
	}

	private void launchSettings() {
		handleClose();
		Intent intent = new Intent();
		intent.setClass(AnySoftKeyboard.this, MainSettingsActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(intent);
	}

	private void launchDictionaryOverriding() {
		final String dictionaryOverridingKey = getDictionaryOverrideKey(getCurrentKeyboard());
		final String dictionaryOverrideValue = mPrefs.getString(
				dictionaryOverridingKey, null);
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setCancelable(true);
		builder.setIcon(R.drawable.ic_launcher);
		builder.setTitle(getResources().getString(
				R.string.override_dictionary_title,
				getCurrentKeyboard().getKeyboardName()));
		builder.setNegativeButton(android.R.string.cancel, null);
		ArrayList<CharSequence> dictionaryIds = new ArrayList<>();
		ArrayList<CharSequence> dictionaries = new ArrayList<>();
		// null dictionary is handled as the default for the keyboard
		dictionaryIds.add(null);
		final String SELECTED = "\u2714 ";
		final String NOT_SELECTED = "- ";
		if (dictionaryOverrideValue == null)
			dictionaries.add(SELECTED + getString(R.string.override_dictionary_default));
		else
			dictionaries.add(NOT_SELECTED + getString(R.string.override_dictionary_default));
		// going over all installed dictionaries
		for (DictionaryAddOnAndBuilder dictionaryBuilder : ExternalDictionaryFactory
				.getAllAvailableExternalDictionaries(getApplicationContext())) {
			dictionaryIds.add(dictionaryBuilder.getId());
			String description;
			if (dictionaryOverrideValue != null
					&& dictionaryBuilder.getId()
					.equals(dictionaryOverrideValue))
				description = SELECTED;
			else
				description = NOT_SELECTED;
			description += dictionaryBuilder.getName();
			if (!TextUtils.isEmpty(dictionaryBuilder.getDescription())) {
				description += " (" + dictionaryBuilder.getDescription() + ")";
			}
			dictionaries.add(description);
		}

		final CharSequence[] ids = new CharSequence[dictionaryIds.size()];
		final CharSequence[] items = new CharSequence[dictionaries.size()];
		dictionaries.toArray(items);
		dictionaryIds.toArray(ids);

		builder.setItems(items, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface di, int position) {
				di.dismiss();
				Editor editor = mPrefs.edit();
				switch (position) {
					case 0:
						Log.d(TAG,
								"Dictionary overriden disabled. User selected default.");
						editor.remove(dictionaryOverridingKey);
						showToastMessage(R.string.override_disabled, true);
						break;
					default:
						if ((position < 0) || (position >= items.length)) {
							Log.d(TAG, "Dictionary override dialog canceled.");
						} else {
							CharSequence id = ids[position];
							String selectedDictionaryId = (id == null) ? null : id
									.toString();
							String selectedLanguageString = items[position]
									.toString();
							Log.d(TAG,
									"Dictionary override. User selected "
											+ selectedLanguageString
											+ " which corresponds to id "
											+ ((selectedDictionaryId == null) ? "(null)"
											: selectedDictionaryId));
							editor.putString(dictionaryOverridingKey,
									selectedDictionaryId);
							showToastMessage(
									getString(R.string.override_enabled,
											selectedLanguageString), true);
						}
						break;
				}
				editor.commit();
				setDictionariesForCurrentKeyboard();
			}
		});

		mOptionsDialog = builder.create();
		Window window = mOptionsDialog.getWindow();
		WindowManager.LayoutParams lp = window.getAttributes();
		lp.token = mInputView.getWindowToken();
		lp.type = WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG;
		window.setAttributes(lp);
		window.addFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
		mOptionsDialog.show();
	}

	private void showOptionsMenu() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setCancelable(true);
		builder.setIcon(R.drawable.ic_launcher);
		builder.setNegativeButton(android.R.string.cancel, null);
		CharSequence itemSettings = getString(R.string.ime_settings);
		CharSequence itemOverrideDictionary = getString(R.string.override_dictionary);
		CharSequence itemInputMethod = getString(R.string.change_ime);
		builder.setItems(new CharSequence[]{itemSettings,
						itemOverrideDictionary, itemInputMethod},
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface di, int position) {
						di.dismiss();
						switch (position) {
							case 0:
								launchSettings();
								break;
							case 1:
								launchDictionaryOverriding();
								break;
							case 2:
								((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE))
										.showInputMethodPicker();
								break;
						}
					}
				});
		builder.setTitle(getResources().getString(R.string.ime_name));
		mOptionsDialog = builder.create();
		Window window = mOptionsDialog.getWindow();
		WindowManager.LayoutParams lp = window.getAttributes();
		lp.token = mInputView.getWindowToken();
		lp.type = WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG;
		window.setAttributes(lp);
		window.addFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
		mOptionsDialog.show();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {

		// If orientation changed while predicting, commit the change
		if (newConfig.orientation != mOrientation) {

			setInitialCondensedState(newConfig);

			commitTyped(getCurrentInputConnection());
			mOrientation = newConfig.orientation;

			mKeyboardSwitcher.makeKeyboards(true);
			// new WxH. need new object.
			mSentenceSeparators = getCurrentKeyboard().getSentenceSeparators();

			if (mKeyboardChangeNotificationType
					.equals(KEYBOARD_NOTIFICATION_ALWAYS))// should
				// it
				// be
				// always
				// on?
				notifyKeyboardChangeIfNeeded();
		}

		super.onConfigurationChanged(newConfig);
	}

	private void setInitialCondensedState(Configuration newConfig) {
		final String defaultCondensed = mAskPrefs.getInitialKeyboardCondenseState();
		mKeyboardInCondensedMode = CondenseType.None;
		switch (defaultCondensed) {
			case "split_always":
				mKeyboardInCondensedMode = CondenseType.Split;
				break;
			case "split_in_landscape":
				if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE)
					mKeyboardInCondensedMode = CondenseType.Split;
				else
					mKeyboardInCondensedMode = CondenseType.None;
				break;
			case "compact_right_always":
				mKeyboardInCondensedMode = CondenseType.CompactToRight;
				break;
			case "compact_left_always":
				mKeyboardInCondensedMode = CondenseType.CompactToLeft;
				break;
		}

		Log.d(TAG, "setInitialCondensedState: defaultCondensed is "
				+ defaultCondensed + " and mKeyboardInCondensedMode is "
				+ mKeyboardInCondensedMode);
	}

	public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
	                                      String key) {
		Log.d(TAG, "onSharedPreferenceChanged - key:" + key);
		AnyApplication.requestBackupToCloud();

		boolean isKeyboardKey = key
				.startsWith(KeyboardAddOnAndBuilder.KEYBOARD_PREF_PREFIX);
		boolean isDictionaryKey = key.startsWith("dictionary_");
		boolean isQuickTextKey = key
				.equals(getString(R.string.settings_key_active_quick_text_key));
		if (isKeyboardKey || isDictionaryKey || isQuickTextKey) {
			mKeyboardSwitcher.makeKeyboards(true);
		}

		loadSettings();

		if (isDictionaryKey
				|| key.equals(getString(R.string.settings_key_use_contacts_dictionary))
				|| key.equals(getString(R.string.settings_key_auto_dictionary_threshold))) {
			setDictionariesForCurrentKeyboard();
		} else if (
			// key.equals(getString(R.string.settings_key_top_keyboard_row_id)) ||
				key.equals(getString(R.string.settings_key_ext_kbd_bottom_row_key))
						|| key.equals(getString(R.string.settings_key_ext_kbd_top_row_key))
						|| key.equals(getString(R.string.settings_key_ext_kbd_ext_ketboard_key))
						|| key.equals(getString(R.string.settings_key_ext_kbd_hidden_bottom_row_key))
						|| key.equals(getString(R.string.settings_key_keyboard_theme_key))
						|| key.equals("zoom_factor_keys_in_portrait")
						|| key.equals("zoom_factor_keys_in_landscape")
						|| key.equals(getString(R.string.settings_key_smiley_icon_on_smileys_key))
						|| key.equals(getString(R.string.settings_key_long_press_timeout))
						|| key.equals(getString(R.string.settings_key_multitap_timeout))
						|| key.equals(getString(R.string.settings_key_default_split_state))) {
			// in some cases we do want to force keyboards recreations
			resetKeyboardView(key
					.equals(getString(R.string.settings_key_keyboard_theme_key)));
		}
	}

	/*
	 * public void appendCharactersToInput(CharSequence textToCommit) { if
	 * (DEBUG) Log.d(TAG, "appendCharactersToInput: '"+ textToCommit+"'");
	 * for(int index=0; index<textToCommit.length(); index++) { final char c =
	 * textToCommit.charAt(index); mWord.add(c, new int[]{c}); }
	 * //mComposing.append(textToCommit); if (mPredictionOn)
	 * getCurrentInputConnection().setComposingText(mWord.getTypedWord(),
	 * textToCommit.length()); else commitTyped(getCurrentInputConnection());
	 * updateShiftKeyState(getCurrentInputEditorInfo()); }
	 */
	public void deleteLastCharactersFromInput(int countToDelete) {
		if (countToDelete == 0)
			return;

		final int currentLength = mWord.length();
		boolean shouldDeleteUsingCompletion;
		if (currentLength > 0) {
			shouldDeleteUsingCompletion = true;
			if (currentLength > countToDelete) {
				// mComposing.delete(currentLength - countToDelete,
				// currentLength);

				int deletesLeft = countToDelete;
				while (deletesLeft > 0) {
					mWord.deleteLast();
					deletesLeft--;
				}
			} else {
				// mComposing.setLength(0);
				mWord.reset();
			}
		} else {
			shouldDeleteUsingCompletion = false;
		}
		InputConnection ic = getCurrentInputConnection();
		if (ic != null) {
			if (mPredictionOn && shouldDeleteUsingCompletion) {
				ic.setComposingText(mWord.getTypedWord()/* mComposing */, 1);
				// updateCandidates();
			} else {
				ic.deleteSurroundingText(countToDelete, 0);
			}
		}
	}

	public void showToastMessage(int resId, boolean forShortTime) {
		CharSequence text = getResources().getText(resId);
		showToastMessage(text, forShortTime);
	}

	private void showToastMessage(CharSequence text, boolean forShortTime) {
		int duration = forShortTime ? Toast.LENGTH_SHORT : Toast.LENGTH_LONG;
		Log.v(TAG, "showToastMessage: '" + text + "'. For: "
				+ duration);
		Toast.makeText(this.getApplication(), text, duration).show();
	}

	@Override
	public void onLowMemory() {
		Log.w(TAG,
				"The OS has reported that it is low on memory!. I'll try to clear some cache.");
		mKeyboardSwitcher.onLowMemory();
		// DictionaryFactory.getInstance().onLowMemory(mSuggest.getMainDictionary());
		super.onLowMemory();
	}

	private void showQuickTextKeyPopupKeyboard(QuickTextKey quickTextKey) {
		if (mInputView != null) {
            /*if (quickTextKey.getPackageContext() == getApplicationContext()) {
                mInputView.simulateLongPress(KeyCodes.QUICK_TEXT);
            } else {*/
			mInputView.showQuickTextPopupKeyboard(quickTextKey);
            /*}*/
		}
	}

	private void showQuickTextKeyPopupList(@NonNull final QuickTextKey key) {
		if (mQuickTextKeyDialog == null) {
			String[] names = key.getPopupListNames();
			final String[] texts = key.getPopupListValues();
			int[] icons = key.getPopupListIconResIds();

			final int N = names.length;

			List<Map<String, ?>> entries = new ArrayList<>();
			for (int i = 0; i < N; i++) {
				HashMap<String, Object> entry = new HashMap<>();

				entry.put("name", names[i]);
				entry.put("text", texts[i]);
				if (icons != null)
					entry.put("icons", icons[i]);

				entries.add(entry);
			}

			int layout;
			String[] from;
			int[] to;
			if (icons == null) {
				layout = R.layout.quick_text_key_menu_item_without_icon;
				from = new String[]{"name", "text"};
				to = new int[]{R.id.quick_text_name, R.id.quick_text_output};
			} else {
				layout = R.layout.quick_text_key_menu_item_with_icon;
				from = new String[]{"name", "text", "icons"};
				to = new int[]{R.id.quick_text_name, R.id.quick_text_output,
						R.id.quick_text_icon};
			}
			final SimpleAdapter a = new SimpleAdapter(this, entries, layout,
					from, to);
			SimpleAdapter.ViewBinder viewBinder = new SimpleAdapter.ViewBinder() {
				public boolean setViewValue(View view, Object data,
				                            String textRepresentation) {
					if (view instanceof ImageView) {
						Context packageContext = key.getPackageContext();
						if (packageContext != null) {
							Drawable img = packageContext.getResources().getDrawable((Integer) data);
							((ImageView) view).setImageDrawable(img);
						}
						return true;
					}
					return false;
				}
			};
			a.setViewBinder(viewBinder);

			AlertDialog.Builder b = new AlertDialog.Builder(this);

			b.setTitle(getString(R.string.menu_insert_smiley));

			b.setCancelable(true);
			b.setAdapter(a, new DialogInterface.OnClickListener() {
				@SuppressWarnings("unchecked")
				// I know, I know, it is not safe to cast, but I created the
				// list, and willing to pay the price.
				public final void onClick(DialogInterface dialog, int which) {
					HashMap<String, Object> item = (HashMap<String, Object>) a
							.getItem(which);
					onText((String) item.get("text"));

					dialog.dismiss();
				}
			});

			mQuickTextKeyDialog = b.create();
			Window window = mQuickTextKeyDialog.getWindow();
			WindowManager.LayoutParams lp = window.getAttributes();
			lp.token = mInputView.getWindowToken();
			lp.type = WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG;
			window.setAttributes(lp);
			window.addFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
		}

		mQuickTextKeyDialog.show();
	}

	public boolean promoteToUserDictionary(String word, int frequency) {
		return !mUserDictionary.isValidWord(word) && mUserDictionary.addWord(word, frequency);
	}

	public WordComposer getCurrentWord() {
		return mWord;
	}

	/**
	 * Override this to control when the soft input area should be shown to the
	 * user. The default implementation only shows the input view when there is
	 * no hard keyboard or the keyboard is hidden. If you change what this
	 * returns, you will need to call {@link #updateInputViewShown()} yourself
	 * whenever the returned value may have changed to have it re-evalauted and
	 * applied. This needs to be re-coded for Issue 620
	 */
	@Override
	public boolean onEvaluateInputViewShown() {
		Configuration config = getResources().getConfiguration();
		return config.keyboard == Configuration.KEYBOARD_NOKEYS
				|| config.hardKeyboardHidden == Configuration.KEYBOARDHIDDEN_YES;
	}

	public void onCancel() {
		// don't know what to do here.
	}

	public void resetKeyboardView(boolean recreateView) {
		handleClose();
		if (mKeyboardSwitcher != null)
			mKeyboardSwitcher.makeKeyboards(true);
		if (recreateView) {
			// also recreate keyboard view
			setInputView(onCreateInputView());
			setCandidatesView(onCreateCandidatesView());
			setCandidatesViewShown(false);
		}
	}

	private void updateShiftStateNow() {
		final InputConnection ic = getCurrentInputConnection();
		EditorInfo ei = getCurrentInputEditorInfo();
		final int caps;
		if (mAutoCap && ei != null && ei.inputType != EditorInfo.TYPE_NULL) {
			caps = ic.getCursorCapsMode(ei.inputType);
		} else {
			caps = 0;
		}
		final boolean inputSaysCaps = caps != 0;
		Log.d(TAG, "shift updateShiftStateNow inputSaysCaps=%s", inputSaysCaps);
		mShiftKeyState.setActiveState(inputSaysCaps);
		handleShift();
	}
}