code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231
values | license stringclasses 13
values | size int64 1 2.01M |
|---|---|---|---|---|---|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace GestorDeFlotasDesktop.Listado
{
public partial class Listado : Form
{
public Listado()
{
InitializeComponent();
tb_mes_fin.Enabled = false;
//'2009-01-08 12:00:00.000'
cb_tipo_listado.Items.Add("choferes");
cb_tipo_listado.Items.Add("taxis");
cb_tipo_listado.Items.Add("clientes");
}
private void Listado_Load(object sender, EventArgs e)
{
}
private void cb_tipo_listado_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void aceptar_Click(object sender, EventArgs e)
{
using (SqlConnection con = Modelo.Modelo.createConnection())
{
if (tb_anio_ini.Text != "" && tb_anio_fin.Text != "" && tb_mes_ini.Text != "")
{
if (Int32.Parse(tb_mes_ini.Text) == 1)
{
tb_mes_fin.Text = "04";
}
if (Int32.Parse(tb_mes_ini.Text) == 2)
{
tb_mes_fin.Text = "05";
}
if (Int32.Parse(tb_mes_ini.Text) == 3)
{
tb_mes_fin.Text = "06";
}
if (Int32.Parse(tb_mes_ini.Text) == 4)
{
tb_mes_fin.Text = "07";
}
if (Int32.Parse(tb_mes_ini.Text) == 5)
{
tb_mes_fin.Text = "08";
}
if (Int32.Parse(tb_mes_ini.Text) == 6)
{
tb_mes_fin.Text = "09";
}
if (Int32.Parse(tb_mes_ini.Text) == 7)
{
tb_mes_fin.Text = "10";
}
if (Int32.Parse(tb_mes_ini.Text) == 8)
{
tb_mes_fin.Text = "11";
}
if (Int32.Parse(tb_mes_ini.Text) == 9)
{
tb_mes_fin.Text = "12";
}
if (Int32.Parse(tb_mes_ini.Text) == 10)
{
tb_mes_fin.Text = "01";
}
if (Int32.Parse(tb_mes_ini.Text) == 11)
{
tb_mes_fin.Text = "02";
}
if (Int32.Parse(tb_mes_ini.Text) == 12)
{
tb_mes_fin.Text = "03";
}
string fecha_ini = "'" + tb_anio_ini.Text + "-01-" + tb_mes_ini.Text + "'";
string fecha_fin = "'" + tb_anio_fin.Text + "-01-" + tb_mes_fin.Text + "'";
//===============================================================================================
//0: choferes
//===============================================================================================
if (cb_tipo_listado.SelectedIndex.ToString() == "0")
{
SqlDataAdapter da = new SqlDataAdapter("SELECT TOP (5) Id_Chofer,(SELECT Ch_Dni FROM NUNCA_TAXI.Choferes WHERE (NUNCA_TAXI.Viajes.Id_Chofer = Id_Chofer)) AS DNI,(SELECT Ch_Nombre FROM NUNCA_TAXI.Choferes AS Choferes_2 WHERE (NUNCA_TAXI.Viajes.Id_Chofer = Id_Chofer)) AS NOMBRE,(SELECT Ch_Apellido FROM NUNCA_TAXI.Choferes AS Choferes_1 WHERE (NUNCA_TAXI.Viajes.Id_Chofer = Id_Chofer)) AS APELLIDO, SUM(Vi_Importe) AS GastoTotal FROM NUNCA_TAXI.Viajes WHERE (Vi_Fecha BETWEEN " + fecha_ini + " AND " + fecha_fin + ") GROUP BY Id_Chofer ORDER BY gastototal DESC", con);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
}
//===============================================================================================
//1: taxis
//===============================================================================================
if (cb_tipo_listado.SelectedIndex.ToString() == "1")
{
SqlDataAdapter da = new SqlDataAdapter("SELECT TOP (5) Id_Taxi,(SELECT Ta_Patente FROM NUNCA_TAXI.Taxis WHERE (NUNCA_TAXI.Viajes.Id_Taxi = Id_Taxi)) AS patente,(SELECT Ta_Licencia FROM NUNCA_TAXI.Taxis AS Choferes_2 WHERE (NUNCA_TAXI.Viajes.Id_Taxi = Id_Taxi)) AS licencia,(SELECT Ma_NombreTaxi FROM NUNCA_TAXI.MarcasTaxi WHERE (Id_MarcaTaxi =(SELECT Id_MarcaTaxi FROM NUNCA_TAXI.Taxis AS Taxis_1 WHERE (NUNCA_TAXI.Viajes.Id_Taxi = Id_Taxi)))) AS MARCA, SUM(Vi_Importe) AS GastoTotal FROM NUNCA_TAXI.Viajes WHERE (Vi_Fecha BETWEEN " + fecha_ini + " AND " + fecha_fin + ")GROUP BY Id_Taxi ORDER BY gastototal DESC", con);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
}
//===============================================================================================
//2: clientes
//===============================================================================================
if (cb_tipo_listado.SelectedIndex.ToString() == "2")
{
SqlDataAdapter da = new SqlDataAdapter("SELECT TOP (5) Id_Cliente,(SELECT Cl_Dni FROM NUNCA_TAXI.Clientes WHERE (NUNCA_TAXI.Viajes.Id_Cliente = Id_Cliente)) AS DNI,(SELECT Cl_Nombre FROM NUNCA_TAXI.Clientes AS Clientes_2 WHERE (NUNCA_TAXI.Viajes.Id_Cliente = Id_Cliente)) AS NOMBRE,(SELECT Cl_Apellido FROM NUNCA_TAXI.Clientes AS Clientes_1 WHERE (NUNCA_TAXI.Viajes.Id_Cliente = Id_Cliente)) AS APELLIDO, SUM(Vi_Importe) AS GastoTotal FROM NUNCA_TAXI.Viajes WHERE (Id_Cliente IS NOT NULL) AND (Vi_Fecha BETWEEN " + fecha_ini + " AND " + fecha_fin + ") GROUP BY Id_Cliente ORDER BY gastototal DESC", con);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
}
}
}
}
}
}
| 09066bd9cc483c8928891679d8ad73b5 | trunk/ArchivosEntrega/TP1C2012 K3051 NUNCA_TAXI/src/GestorDeFlotasDesktop/Listado/Listado.cs | C# | asf20 | 7,020 |
# Copyright (C) 2007 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# If you don't need to do a full clean build but would like to touch
# a file or delete some intermediate files, add a clean step to the end
# of the list. These steps will only be run once, if they haven't been
# run before.
#
# E.g.:
# $(call add-clean-step, touch -c external/sqlite/sqlite3.h)
# $(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/STATIC_LIBRARIES/libz_intermediates)
#
# Always use "touch -c" and "rm -f" or "rm -rf" to gracefully deal with
# files that are missing or have been moved.
#
# Use $(PRODUCT_OUT) to get to the "out/target/product/blah/" directory.
# Use $(OUT_DIR) to refer to the "out" directory.
#
# If you need to re-do something that's already mentioned, just copy
# the command and add it to the bottom of the list. E.g., if a change
# that you made last week required touching a file and a change you
# made today requires touching the same file, just copy the old
# touch step and add it to the end of the list.
#
# ************************************************
# NEWER CLEAN STEPS MUST BE AT THE END OF THE LIST
# ************************************************
# For example:
#$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/APPS/AndroidTests_intermediates)
#$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/JAVA_LIBRARIES/core_intermediates)
#$(call add-clean-step, find $(OUT_DIR) -type f -name "IGTalkSession*" -print0 | xargs -0 rm -f)
#$(call add-clean-step, rm -rf $(PRODUCT_OUT)/data/*)
$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/APPS/LatinIME*)
$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/app/LatinIME.apk)
$(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/SHARED_LIBRARIES/libjni_latinime_intermediates)
# ************************************************
# NEWER CLEAN STEPS MUST BE AT THE END OF THE LIST
# ************************************************
| 11beeaosama-descrbvbnvbniption | CleanSpec.mk | Makefile | asf20 | 2,470 |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.android.inputmethod.latin;
import android.test.AndroidTestCase;
import com.android.inputmethod.latin.tests.R;
public class SuggestTests extends AndroidTestCase {
private static final String TAG = "SuggestTests";
private SuggestHelper sh;
@Override
protected void setUp() {
int[] resId = new int[] { R.raw.test };
sh = new SuggestHelper(TAG, getTestContext(), resId);
}
/************************** Tests ************************/
/**
* Tests for simple completions of one character.
*/
public void testCompletion1char() {
assertTrue(sh.isDefaultSuggestion("peopl", "people"));
assertTrue(sh.isDefaultSuggestion("abou", "about"));
assertTrue(sh.isDefaultSuggestion("thei", "their"));
}
/**
* Tests for simple completions of two characters.
*/
public void testCompletion2char() {
assertTrue(sh.isDefaultSuggestion("peop", "people"));
assertTrue(sh.isDefaultSuggestion("calli", "calling"));
assertTrue(sh.isDefaultSuggestion("busine", "business"));
}
/**
* Tests for proximity errors.
*/
public void testProximityPositive() {
assertTrue(sh.isDefaultSuggestion("peiple", "people"));
assertTrue(sh.isDefaultSuggestion("peoole", "people"));
assertTrue(sh.isDefaultSuggestion("pwpple", "people"));
}
/**
* Tests for proximity errors - negative, when the error key is not near.
*/
public void testProximityNegative() {
assertFalse(sh.isDefaultSuggestion("arout", "about"));
assertFalse(sh.isDefaultSuggestion("ire", "are"));
}
/**
* Tests for checking if apostrophes are added automatically.
*/
public void testApostropheInsertion() {
assertTrue(sh.isDefaultSuggestion("im", "I'm"));
assertTrue(sh.isDefaultSuggestion("dont", "don't"));
}
/**
* Test to make sure apostrophed word is not suggested for an apostrophed word.
*/
public void testApostrophe() {
assertFalse(sh.isDefaultSuggestion("don't", "don't"));
}
/**
* Tests for suggestion of capitalized version of a word.
*/
public void testCapitalization() {
assertTrue(sh.isDefaultSuggestion("i'm", "I'm"));
assertTrue(sh.isDefaultSuggestion("sunday", "Sunday"));
assertTrue(sh.isDefaultSuggestion("sundat", "Sunday"));
}
/**
* Tests to see if more than one completion is provided for certain prefixes.
*/
public void testMultipleCompletions() {
assertTrue(sh.isASuggestion("com", "come"));
assertTrue(sh.isASuggestion("com", "company"));
assertTrue(sh.isASuggestion("th", "the"));
assertTrue(sh.isASuggestion("th", "that"));
assertTrue(sh.isASuggestion("th", "this"));
assertTrue(sh.isASuggestion("th", "they"));
}
/**
* Does the suggestion engine recognize zero frequency words as valid words.
*/
public void testZeroFrequencyAccepted() {
assertTrue(sh.isValid("yikes"));
assertFalse(sh.isValid("yike"));
}
/**
* Tests to make sure that zero frequency words are not suggested as completions.
*/
public void testZeroFrequencySuggestionsNegative() {
assertFalse(sh.isASuggestion("yike", "yikes"));
assertFalse(sh.isASuggestion("what", "whatcha"));
}
/**
* Tests to ensure that words with large edit distances are not suggested, in some cases
* and not considered corrections, in some cases.
*/
public void testTooLargeEditDistance() {
assertFalse(sh.isASuggestion("sniyr", "about"));
assertFalse(sh.isDefaultCorrection("rjw", "the"));
}
/**
* Make sure sh.isValid is case-sensitive.
*/
public void testValidityCaseSensitivity() {
assertTrue(sh.isValid("Sunday"));
assertFalse(sh.isValid("sunday"));
}
/**
* Are accented forms of words suggested as corrections?
*/
public void testAccents() {
// ni<LATIN SMALL LETTER N WITH TILDE>o
assertTrue(sh.isDefaultCorrection("nino", "ni\u00F1o"));
// ni<LATIN SMALL LETTER N WITH TILDE>o
assertTrue(sh.isDefaultCorrection("nimo", "ni\u00F1o"));
// Mar<LATIN SMALL LETTER I WITH ACUTE>a
assertTrue(sh.isDefaultCorrection("maria", "Mar\u00EDa"));
}
/**
* Make sure bigrams are showing when first character is typed
* and don't show any when there aren't any
*/
public void testBigramsAtFirstChar() {
assertTrue(sh.isDefaultNextSuggestion("about", "p", "part"));
assertTrue(sh.isDefaultNextSuggestion("I'm", "a", "about"));
assertTrue(sh.isDefaultNextSuggestion("about", "b", "business"));
assertTrue(sh.isASuggestion("about", "b", "being"));
assertFalse(sh.isDefaultNextSuggestion("about", "p", "business"));
}
/**
* Make sure bigrams score affects the original score
*/
public void testBigramsScoreEffect() {
assertTrue(sh.isDefaultCorrection("pa", "page"));
assertTrue(sh.isDefaultNextCorrection("about", "pa", "part"));
assertTrue(sh.isDefaultCorrection("sa", "said"));
assertTrue(sh.isDefaultNextCorrection("from", "sa", "same"));
}
}
| 11beeaosama-descrbvbnvbniption | tests/src/com/android/inputmethod/latin/SuggestTests.java | Java | asf20 | 5,920 |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.android.inputmethod.latin;
import android.test.AndroidTestCase;
import android.util.Log;
import com.android.inputmethod.latin.tests.R;
import java.io.InputStreamReader;
import java.io.InputStream;
import java.io.BufferedReader;
import java.util.StringTokenizer;
public class SuggestPerformanceTests extends AndroidTestCase {
private static final String TAG = "SuggestPerformanceTests";
private String mTestText;
private SuggestHelper sh;
@Override
protected void setUp() {
// TODO Figure out a way to directly using the dictionary rather than copying it over
// For testing with real dictionary, TEMPORARILY COPY main dictionary into test directory.
// DO NOT SUBMIT real dictionary under test directory.
//int[] resId = new int[] { R.raw.main0, R.raw.main1, R.raw.main2 };
int[] resId = new int[] { R.raw.test };
sh = new SuggestHelper(TAG, getTestContext(), resId);
loadString();
}
private void loadString() {
try {
InputStream is = getTestContext().getResources().openRawResource(R.raw.testtext);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = reader.readLine();
while (line != null) {
sb.append(line + " ");
line = reader.readLine();
}
mTestText = sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
}
/************************** Helper functions ************************/
private int lookForSuggestion(String prevWord, String currentWord) {
for (int i = 1; i < currentWord.length(); i++) {
if (i == 1) {
if (sh.isDefaultNextSuggestion(prevWord, currentWord.substring(0, i),
currentWord)) {
return i;
}
} else {
if (sh.isDefaultNextCorrection(prevWord, currentWord.substring(0, i),
currentWord)) {
return i;
}
}
}
return currentWord.length();
}
private double runText(boolean withBigrams) {
StringTokenizer st = new StringTokenizer(mTestText);
String prevWord = null;
int typeCount = 0;
int characterCount = 0; // without space
int wordCount = 0;
while (st.hasMoreTokens()) {
String currentWord = st.nextToken();
boolean endCheck = false;
if (currentWord.matches("[\\w]*[\\.|?|!|*|@|&|/|:|;]")) {
currentWord = currentWord.substring(0, currentWord.length() - 1);
endCheck = true;
}
if (withBigrams && prevWord != null) {
typeCount += lookForSuggestion(prevWord, currentWord);
} else {
typeCount += lookForSuggestion(null, currentWord);
}
characterCount += currentWord.length();
if (!endCheck) prevWord = currentWord;
wordCount++;
}
double result = (double) (characterCount - typeCount) / characterCount * 100;
if (withBigrams) {
Log.i(TAG, "with bigrams -> " + result + " % saved!");
} else {
Log.i(TAG, "without bigrams -> " + result + " % saved!");
}
Log.i(TAG, "\ttotal number of words: " + wordCount);
Log.i(TAG, "\ttotal number of characters: " + mTestText.length());
Log.i(TAG, "\ttotal number of characters without space: " + characterCount);
Log.i(TAG, "\ttotal number of characters typed: " + typeCount);
return result;
}
/************************** Performance Tests ************************/
/**
* Compare the Suggest with and without bigram
* Check the log for detail
*/
public void testSuggestPerformance() {
assertTrue(runText(false) <= runText(true));
}
}
| 11beeaosama-descrbvbnvbniption | tests/src/com/android/inputmethod/latin/SuggestPerformanceTests.java | Java | asf20 | 4,654 |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.android.inputmethod.latin;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import com.android.inputmethod.latin.Suggest;
import com.android.inputmethod.latin.UserBigramDictionary;
import com.android.inputmethod.latin.WordComposer;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.Channels;
import java.util.List;
import java.util.Locale;
import java.util.StringTokenizer;
public class SuggestHelper {
private Suggest mSuggest;
private UserBigramDictionary mUserBigram;
private final String TAG;
/** Uses main dictionary only **/
public SuggestHelper(String tag, Context context, int[] resId) {
TAG = tag;
InputStream[] is = null;
try {
// merging separated dictionary into one if dictionary is separated
int total = 0;
is = new InputStream[resId.length];
for (int i = 0; i < resId.length; i++) {
is[i] = context.getResources().openRawResource(resId[i]);
total += is[i].available();
}
ByteBuffer byteBuffer =
ByteBuffer.allocateDirect(total).order(ByteOrder.nativeOrder());
int got = 0;
for (int i = 0; i < resId.length; i++) {
got += Channels.newChannel(is[i]).read(byteBuffer);
}
if (got != total) {
Log.w(TAG, "Read " + got + " bytes, expected " + total);
} else {
mSuggest = new Suggest(context, byteBuffer);
Log.i(TAG, "Created mSuggest " + total + " bytes");
}
} catch (IOException e) {
Log.w(TAG, "No available memory for binary dictionary");
} finally {
try {
if (is != null) {
for (int i = 0; i < is.length; i++) {
is[i].close();
}
}
} catch (IOException e) {
Log.w(TAG, "Failed to close input stream");
}
}
mSuggest.setAutoTextEnabled(false);
mSuggest.setCorrectionMode(Suggest.CORRECTION_FULL_BIGRAM);
}
/** Uses both main dictionary and user-bigram dictionary **/
public SuggestHelper(String tag, Context context, int[] resId, int userBigramMax,
int userBigramDelete) {
this(tag, context, resId);
mUserBigram = new UserBigramDictionary(context, null, Locale.US.toString(),
Suggest.DIC_USER);
mUserBigram.setDatabaseMax(userBigramMax);
mUserBigram.setDatabaseDelete(userBigramDelete);
mSuggest.setUserBigramDictionary(mUserBigram);
}
void changeUserBigramLocale(Context context, Locale locale) {
if (mUserBigram != null) {
flushUserBigrams();
mUserBigram.close();
mUserBigram = new UserBigramDictionary(context, null, locale.toString(),
Suggest.DIC_USER);
mSuggest.setUserBigramDictionary(mUserBigram);
}
}
private WordComposer createWordComposer(CharSequence s) {
WordComposer word = new WordComposer();
for (int i = 0; i < s.length(); i++) {
final char c = s.charAt(i);
int[] codes;
// If it's not a lowercase letter, don't find adjacent letters
if (c < 'a' || c > 'z') {
codes = new int[] { c };
} else {
codes = adjacents[c - 'a'];
}
word.add(c, codes);
}
return word;
}
private void showList(String title, List<CharSequence> suggestions) {
Log.i(TAG, title);
for (int i = 0; i < suggestions.size(); i++) {
Log.i(title, suggestions.get(i) + ", ");
}
}
private boolean isDefaultSuggestion(List<CharSequence> suggestions, CharSequence word) {
// Check if either the word is what you typed or the first alternative
return suggestions.size() > 0 &&
(/*TextUtils.equals(suggestions.get(0), word) || */
(suggestions.size() > 1 && TextUtils.equals(suggestions.get(1), word)));
}
boolean isDefaultSuggestion(CharSequence typed, CharSequence expected) {
WordComposer word = createWordComposer(typed);
List<CharSequence> suggestions = mSuggest.getSuggestions(null, word, false, null);
return isDefaultSuggestion(suggestions, expected);
}
boolean isDefaultCorrection(CharSequence typed, CharSequence expected) {
WordComposer word = createWordComposer(typed);
List<CharSequence> suggestions = mSuggest.getSuggestions(null, word, false, null);
return isDefaultSuggestion(suggestions, expected) && mSuggest.hasMinimalCorrection();
}
boolean isASuggestion(CharSequence typed, CharSequence expected) {
WordComposer word = createWordComposer(typed);
List<CharSequence> suggestions = mSuggest.getSuggestions(null, word, false, null);
for (int i = 1; i < suggestions.size(); i++) {
if (TextUtils.equals(suggestions.get(i), expected)) return true;
}
return false;
}
private void getBigramSuggestions(CharSequence previous, CharSequence typed) {
if (!TextUtils.isEmpty(previous) && (typed.length() > 1)) {
WordComposer firstChar = createWordComposer(Character.toString(typed.charAt(0)));
mSuggest.getSuggestions(null, firstChar, false, previous);
}
}
boolean isDefaultNextSuggestion(CharSequence previous, CharSequence typed,
CharSequence expected) {
WordComposer word = createWordComposer(typed);
getBigramSuggestions(previous, typed);
List<CharSequence> suggestions = mSuggest.getSuggestions(null, word, false, previous);
return isDefaultSuggestion(suggestions, expected);
}
boolean isDefaultNextCorrection(CharSequence previous, CharSequence typed,
CharSequence expected) {
WordComposer word = createWordComposer(typed);
getBigramSuggestions(previous, typed);
List<CharSequence> suggestions = mSuggest.getSuggestions(null, word, false, previous);
return isDefaultSuggestion(suggestions, expected) && mSuggest.hasMinimalCorrection();
}
boolean isASuggestion(CharSequence previous, CharSequence typed,
CharSequence expected) {
WordComposer word = createWordComposer(typed);
getBigramSuggestions(previous, typed);
List<CharSequence> suggestions = mSuggest.getSuggestions(null, word, false, previous);
for (int i = 1; i < suggestions.size(); i++) {
if (TextUtils.equals(suggestions.get(i), expected)) return true;
}
return false;
}
boolean isValid(CharSequence typed) {
return mSuggest.isValidWord(typed);
}
boolean isUserBigramSuggestion(CharSequence previous, char typed,
CharSequence expected) {
WordComposer word = createWordComposer(Character.toString(typed));
if (mUserBigram == null) return false;
flushUserBigrams();
if (!TextUtils.isEmpty(previous) && !TextUtils.isEmpty(Character.toString(typed))) {
WordComposer firstChar = createWordComposer(Character.toString(typed));
mSuggest.getSuggestions(null, firstChar, false, previous);
boolean reloading = mUserBigram.reloadDictionaryIfRequired();
if (reloading) mUserBigram.waitForDictionaryLoading();
mUserBigram.getBigrams(firstChar, previous, mSuggest, null);
}
List<CharSequence> suggestions = mSuggest.mBigramSuggestions;
for (int i = 0; i < suggestions.size(); i++) {
if (TextUtils.equals(suggestions.get(i), expected)) return true;
}
return false;
}
void addToUserBigram(String sentence) {
StringTokenizer st = new StringTokenizer(sentence);
String previous = null;
while (st.hasMoreTokens()) {
String current = st.nextToken();
if (previous != null) {
addToUserBigram(new String[] {previous, current});
}
previous = current;
}
}
void addToUserBigram(String[] pair) {
if (mUserBigram != null && pair.length == 2) {
mUserBigram.addBigrams(pair[0], pair[1]);
}
}
void flushUserBigrams() {
if (mUserBigram != null) {
mUserBigram.flushPendingWrites();
mUserBigram.waitUntilUpdateDBDone();
}
}
final int[][] adjacents = {
{'a','s','w','q',-1},
{'b','h','v','n','g','j',-1},
{'c','v','f','x','g',},
{'d','f','r','e','s','x',-1},
{'e','w','r','s','d',-1},
{'f','g','d','c','t','r',-1},
{'g','h','f','y','t','v',-1},
{'h','j','u','g','b','y',-1},
{'i','o','u','k',-1},
{'j','k','i','h','u','n',-1},
{'k','l','o','j','i','m',-1},
{'l','k','o','p',-1},
{'m','k','n','l',-1},
{'n','m','j','k','b',-1},
{'o','p','i','l',-1},
{'p','o',-1},
{'q','w',-1},
{'r','t','e','f',-1},
{'s','d','e','w','a','z',-1},
{'t','y','r',-1},
{'u','y','i','h','j',-1},
{'v','b','g','c','h',-1},
{'w','e','q',-1},
{'x','c','d','z','f',-1},
{'y','u','t','h','g',-1},
{'z','s','x','a','d',-1},
};
}
| 11beeaosama-descrbvbnvbniption | tests/src/com/android/inputmethod/latin/SuggestHelper.java | Java | asf20 | 10,798 |
/*
* Copyright (C) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.android.inputmethod.latin;
import com.android.inputmethod.latin.SwipeTracker.EventRingBuffer;
import android.test.AndroidTestCase;
public class EventRingBufferTests extends AndroidTestCase {
@Override
protected void setUp() throws Exception {
super.setUp();
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
}
private static float X_BASE = 1000f;
private static float Y_BASE = 2000f;
private static long TIME_BASE = 3000l;
private static float x(int id) {
return X_BASE + id;
}
private static float y(int id) {
return Y_BASE + id;
}
private static long time(int id) {
return TIME_BASE + id;
}
private static void addEvent(EventRingBuffer buf, int id) {
buf.add(x(id), y(id), time(id));
}
private static void assertEventSize(EventRingBuffer buf, int size) {
assertEquals(size, buf.size());
}
private static void assertEvent(EventRingBuffer buf, int pos, int id) {
assertEquals(x(id), buf.getX(pos), 0f);
assertEquals(y(id), buf.getY(pos), 0f);
assertEquals(time(id), buf.getTime(pos));
}
public void testClearBuffer() {
EventRingBuffer buf = new EventRingBuffer(4);
assertEventSize(buf, 0);
addEvent(buf, 0);
addEvent(buf, 1);
addEvent(buf, 2);
addEvent(buf, 3);
addEvent(buf, 4);
assertEventSize(buf, 4);
buf.clear();
assertEventSize(buf, 0);
}
public void testRingBuffer() {
EventRingBuffer buf = new EventRingBuffer(4);
assertEventSize(buf, 0); // [0]
addEvent(buf, 0);
assertEventSize(buf, 1); // [1] 0
assertEvent(buf, 0, 0);
addEvent(buf, 1);
addEvent(buf, 2);
assertEventSize(buf, 3); // [3] 2 1 0
assertEvent(buf, 0, 0);
assertEvent(buf, 1, 1);
assertEvent(buf, 2, 2);
addEvent(buf, 3);
assertEventSize(buf, 4); // [4] 3 2 1 0
assertEvent(buf, 0, 0);
assertEvent(buf, 1, 1);
assertEvent(buf, 2, 2);
assertEvent(buf, 3, 3);
addEvent(buf, 4);
addEvent(buf, 5);
assertEventSize(buf, 4); // [4] 5 4|3 2(1 0)
assertEvent(buf, 0, 2);
assertEvent(buf, 1, 3);
assertEvent(buf, 2, 4);
assertEvent(buf, 3, 5);
addEvent(buf, 6);
addEvent(buf, 7);
addEvent(buf, 8);
assertEventSize(buf, 4); // [4] 8 7 6 5|(4 3 2)1|0
assertEvent(buf, 0, 5);
assertEvent(buf, 1, 6);
assertEvent(buf, 2, 7);
assertEvent(buf, 3, 8);
}
public void testDropOldest() {
EventRingBuffer buf = new EventRingBuffer(4);
addEvent(buf, 0);
assertEventSize(buf, 1); // [1] 0
assertEvent(buf, 0, 0);
buf.dropOldest();
assertEventSize(buf, 0); // [0] (0)
addEvent(buf, 1);
addEvent(buf, 2);
addEvent(buf, 3);
addEvent(buf, 4);
assertEventSize(buf, 4); // [4] 4|3 2 1(0)
assertEvent(buf, 0, 1);
buf.dropOldest();
assertEventSize(buf, 3); // [3] 4|3 2(1)0
assertEvent(buf, 0, 2);
buf.dropOldest();
assertEventSize(buf, 2); // [2] 4|3(2)10
assertEvent(buf, 0, 3);
buf.dropOldest();
assertEventSize(buf, 1); // [1] 4|(3)210
assertEvent(buf, 0, 4);
buf.dropOldest();
assertEventSize(buf, 0); // [0] (4)|3210
}
}
| 11beeaosama-descrbvbnvbniption | tests/src/com/android/inputmethod/latin/EventRingBufferTests.java | Java | asf20 | 4,141 |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.android.inputmethod.latin;
import android.test.AndroidTestCase;
import com.android.inputmethod.latin.tests.R;
import java.util.Locale;
public class UserBigramTests extends AndroidTestCase {
private static final String TAG = "UserBigramTests";
private static final int SUGGESTION_STARTS = 6;
private static final int MAX_DATA = 20;
private static final int DELETE_DATA = 10;
private SuggestHelper sh;
@Override
protected void setUp() {
int[] resId = new int[] { R.raw.test };
sh = new SuggestHelper(TAG, getTestContext(), resId, MAX_DATA, DELETE_DATA);
}
/************************** Tests ************************/
/**
* Test suggestion started at right time
*/
public void testUserBigram() {
for (int i = 0; i < SUGGESTION_STARTS; i++) sh.addToUserBigram(pair1);
for (int i = 0; i < (SUGGESTION_STARTS - 1); i++) sh.addToUserBigram(pair2);
assertTrue(sh.isUserBigramSuggestion("user", 'b', "bigram"));
assertFalse(sh.isUserBigramSuggestion("android", 'p', "platform"));
}
/**
* Test loading correct (locale) bigrams
*/
public void testOpenAndClose() {
for (int i = 0; i < SUGGESTION_STARTS; i++) sh.addToUserBigram(pair1);
assertTrue(sh.isUserBigramSuggestion("user", 'b', "bigram"));
// change to fr_FR
sh.changeUserBigramLocale(getTestContext(), Locale.FRANCE);
for (int i = 0; i < SUGGESTION_STARTS; i++) sh.addToUserBigram(pair3);
assertTrue(sh.isUserBigramSuggestion("locale", 'f', "france"));
assertFalse(sh.isUserBigramSuggestion("user", 'b', "bigram"));
// change back to en_US
sh.changeUserBigramLocale(getTestContext(), Locale.US);
assertFalse(sh.isUserBigramSuggestion("locale", 'f', "france"));
assertTrue(sh.isUserBigramSuggestion("user", 'b', "bigram"));
}
/**
* Test data gets pruned when it is over maximum
*/
public void testPruningData() {
for (int i = 0; i < SUGGESTION_STARTS; i++) sh.addToUserBigram(sentence0);
sh.flushUserBigrams();
assertTrue(sh.isUserBigramSuggestion("Hello", 'w', "world"));
sh.addToUserBigram(sentence1);
sh.addToUserBigram(sentence2);
assertTrue(sh.isUserBigramSuggestion("Hello", 'w', "world"));
// pruning should happen
sh.addToUserBigram(sentence3);
sh.addToUserBigram(sentence4);
// trying to reopen database to check pruning happened in database
sh.changeUserBigramLocale(getTestContext(), Locale.US);
assertFalse(sh.isUserBigramSuggestion("Hello", 'w', "world"));
}
final String[] pair1 = new String[] {"user", "bigram"};
final String[] pair2 = new String[] {"android","platform"};
final String[] pair3 = new String[] {"locale", "france"};
final String sentence0 = "Hello world";
final String sentence1 = "This is a test for user input based bigram";
final String sentence2 = "It learns phrases that contain both dictionary and nondictionary "
+ "words";
final String sentence3 = "This should give better suggestions than the previous version";
final String sentence4 = "Android stock keyboard is improving";
}
| 11beeaosama-descrbvbnvbniption | tests/src/com/android/inputmethod/latin/UserBigramTests.java | Java | asf20 | 3,884 |
LOCAL_PATH:= $(call my-dir)
include $(CLEAR_VARS)
# We only want this apk build for tests.
LOCAL_MODULE_TAGS := tests
LOCAL_CERTIFICATE := shared
LOCAL_JAVA_LIBRARIES := android.test.runner
# Include all test java files.
LOCAL_SRC_FILES := $(call all-java-files-under, src)
LOCAL_PACKAGE_NAME := LatinIMETests
LOCAL_INSTRUMENTATION_FOR := LatinIME
include $(BUILD_PACKAGE)
| 11beeaosama-descrbvbnvbniption | tests/Android.mk | Makefile | asf20 | 379 |
#!/bin/bash
Res=res/
Alt=donottranslate-altchars.xml
Map=donottranslate-keymap.xml
Out=assets/kbd/
mkdir -p "$Out"
for Dir in res/values res/values-*
do
[ -f $Dir/$Map ] || continue # -o -f $Dir/$Alt ] || continue
Args="$Res/values/$Alt"
[ -f $Dir/$Alt ] && Args="$Args $Dir/$Alt"
Args="$Args $Res/values/$Map"
[ -f $Dir/$Map ] && Args="$Args $Dir/$Map"
if [ -n "$CONVERT_MAPS" ]; then
Loc=$(echo "$Dir" | sed 's/res.values-*//; s/\/$//; s/^$/en/')
perl CheckMap.pl -c $Args > "$Out/map-full-$Loc.txt"
else
echo >&2 -n "$Dir: "
perl CheckMap.pl $Args
fi
done
| 11beeaosama-descrbvbnvbniption | java/CheckMaps.sh | Shell | asf20 | 594 |
#!/usr/bin/perl
binmode(STDOUT, ":utf8");
use Getopt::Std;
getopts('c') || die;
# Character used to display combining diacritics
my $placeholder = "\x{25cc}"; # dotted circle
#my $placeholder = "\x{25ab}"; # very small square
#my $placeholder = " "; # space
my %entities = (
'amp' => '&',
'lt' => '<',
'gt' => '>',
);
sub expand_entity {
my $in = shift;
if ($entities{$in}) {
return $entities{$in};
}
if ($in =~ /^#x(\w+)$/) {
return chr(hex($1));
} elsif ($in =~ /^#(\d+)$/) {
return chr(0+$1);
} else {
return '[???]';
}
}
sub prefix_diacritic {
my $in = shift;
return $in if $in =~ /^[\040-\176]/;
#$in =~ s/^(\p{Diacritic})/$placeholder$1/;
$in =~ s/^(\p{BidiClass:NSM})/$placeholder$1/;
return $in;
}
my @std_map = (
['key_tlde', 'key_ae01', 'key_ae02', 'key_ae03', 'key_ae04', 'key_ae05',
'key_ae06', 'key_ae07', 'key_ae08', 'key_ae09', 'key_ae10', 'key_ae11',
'key_ae12'],
['key_ad01', 'key_ad02', 'key_ad03', 'key_ad04', 'key_ad05', 'key_ad06',
'key_ad07', 'key_ad08', 'key_ad09', 'key_ad10', 'key_ad11', 'key_ad12',
'key_bksl'],
['key_ac01', 'key_ac02', 'key_ac03', 'key_ac04', 'key_ac05', 'key_ac06',
'key_ac07', 'key_ac08', 'key_ac09', 'key_ac10', 'key_ac11'],
['key_lsgt', 'key_ab01', 'key_ab02', 'key_ab03', 'key_ab04', 'key_ab05',
'key_ab06', 'key_ab07', 'key_ab08', 'key_ab09', 'key_ab10'],
);
my %edge = (
'key_ae12' => 1,
'key_bksl' => 1,
'key_ac11' => 1,
);
my %std_col = ();
my %std_row = ();
for (my $i = 0; $i < @std_map; ++$i) {
my @row = @{$std_map[$i]};
for (my $j = 0; $j < @row; ++$j) {
my $key = $row[$j];
$std_row{$key} = $i;
$std_col{$key} = $j;
}
}
sub read_strings {
my ($href, $file) = @_;
open(my $in, '<:utf8', $file) or die;
while (<$in>) {
#print;
if (/string\s+name="(.*)"\s*>(.*)</) {
my $name = $1;
my $chars = $2;
if ($chars =~ /\@string\/(\w+)/) {
$chars = $$href{$1};
} else {
print STDERR "ERROR: trailing backslash for $name; " if $chars =~ /[^\\]\\$/;
$chars =~ s/&(\#?\w+);/expand_entity($1)/eg;
$chars =~ s/\\(.)/$1/g; # Backslashes
}
$$href{$name} = $chars;
}
}
close $in;
}
sub main {
my %res = ();
foreach my $arg (@ARGV) {
read_strings(\%res, $arg);
}
my %found = ();
for (my $c = 33; $c < 127; ++$c) {
$found{chr($c)} = 0;
}
my $missing_digits = '';
my %keys = ();
foreach my $key (sort keys %res) {
next unless $key =~ /^key_/;
$keys{substr($key, 0, length('key_ae01'))} = 1;
my $chars = $res{$key};
## Replace entities
#$chars =~ s/\&(\w+)\;/entities{$1}/eg;
## Unescape backslashes
#$chars =~ s/\\(.)/$1/g;
for (my $i = 0; $i < length($chars); ++$i) {
my $char = substr($chars, $i, 1);
#print "$key $chars: char at $i = $char\n";
++ $found{$char};
}
if ($key =~ /key_ad(\d(\d))_alt/) {
my $keynum = $1;
next if $keynum > 10;
my $digit = $2;
#print "Digit check: key=$key chars=$chars\n";
$missing_digits .= $digit unless $chars =~ /$digit/;
}
}
if ($opt_c) {
my $prev_row = 0;
for my $key (sort {
$std_row{$a} <=> $std_row{$b}
||
$std_col{$a} <=> $std_col{$b}
||
$a cmp $b
} keys %keys) {
my $row = $std_row{$key};
if ($row != $prev_row) {
print "\n";
$prev_row = $row;
}
my $main = $res{$key . '_main'};
my $shift = $res{$key . '_shift'};
my $alt = $res{$key . '_alt'};
$main = prefix_diacritic($main);
$shift = prefix_diacritic($shift);
my @alt_list = split('', $alt);
@alt_list = map { prefix_diacritic($_) } @alt_list;
my $alt_join = join(' ', @alt_list);
print "$key\t$main\t$shift\t$alt_join\n";
}
}
my $missing = '';
if ($missing_digits ne '') {
$missing .= "Digits '$missing_digits', ";
}
foreach my $c (sort keys %found) {
if ($found{$c} == 0) {
$missing .= $c;
}
}
if (length($missing) > 0) {
print STDERR "Missing: $missing\n";
} else {
print STDERR "All present.\n" unless $opt_c;
}
}
&main();
| 11beeaosama-descrbvbnvbniption | java/CheckMap.pl | Raku | asf20 | 4,184 |
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.pocketworkstation.pckeyboard;
import android.content.ContentResolver;
import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.os.SystemClock;
import android.provider.ContactsContract.Contacts;
import android.text.TextUtils;
import android.util.Log;
public class ContactsDictionary extends ExpandableDictionary {
private static final String[] PROJECTION = {
Contacts._ID,
Contacts.DISPLAY_NAME,
};
private static final String TAG = "ContactsDictionary";
/**
* Frequency for contacts information into the dictionary
*/
private static final int FREQUENCY_FOR_CONTACTS = 128;
private static final int FREQUENCY_FOR_CONTACTS_BIGRAM = 90;
private static final int INDEX_NAME = 1;
private ContentObserver mObserver;
private long mLastLoadedContacts;
public ContactsDictionary(Context context, int dicTypeId) {
super(context, dicTypeId);
// Perform a managed query. The Activity will handle closing and requerying the cursor
// when needed.
ContentResolver cres = context.getContentResolver();
cres.registerContentObserver(
Contacts.CONTENT_URI, true,mObserver = new ContentObserver(null) {
@Override
public void onChange(boolean self) {
setRequiresReload(true);
}
});
loadDictionary();
}
@Override
public synchronized void close() {
if (mObserver != null) {
getContext().getContentResolver().unregisterContentObserver(mObserver);
mObserver = null;
}
super.close();
}
@Override
public void startDictionaryLoadingTaskLocked() {
long now = SystemClock.uptimeMillis();
if (mLastLoadedContacts == 0
|| now - mLastLoadedContacts > 30 * 60 * 1000 /* 30 minutes */) {
super.startDictionaryLoadingTaskLocked();
}
}
@Override
public void loadDictionaryAsync() {
try {
Cursor cursor = getContext().getContentResolver()
.query(Contacts.CONTENT_URI, PROJECTION, null, null, null);
if (cursor != null) {
addWords(cursor);
}
} catch(IllegalStateException e) {
Log.e(TAG, "Contacts DB is having problems");
}
mLastLoadedContacts = SystemClock.uptimeMillis();
}
private void addWords(Cursor cursor) {
clearDictionary();
final int maxWordLength = getMaxWordLength();
try {
if (cursor.moveToFirst()) {
while (!cursor.isAfterLast()) {
String name = cursor.getString(INDEX_NAME);
if (name != null) {
int len = name.length();
String prevWord = null;
// TODO: Better tokenization for non-Latin writing systems
for (int i = 0; i < len; i++) {
if (Character.isLetter(name.charAt(i))) {
int j;
for (j = i + 1; j < len; j++) {
char c = name.charAt(j);
if (!(c == '-' || c == '\'' ||
Character.isLetter(c))) {
break;
}
}
String word = name.substring(i, j);
i = j - 1;
// Safeguard against adding really long words. Stack
// may overflow due to recursion
// Also don't add single letter words, possibly confuses
// capitalization of i.
final int wordLen = word.length();
if (wordLen < maxWordLength && wordLen > 1) {
super.addWord(word, FREQUENCY_FOR_CONTACTS);
if (!TextUtils.isEmpty(prevWord)) {
// TODO Do not add email address
// Not so critical
super.setBigram(prevWord, word,
FREQUENCY_FOR_CONTACTS_BIGRAM);
}
prevWord = word;
}
}
}
}
cursor.moveToNext();
}
}
cursor.close();
} catch(IllegalStateException e) {
Log.e(TAG, "Contacts DB is having problems");
}
}
}
| 11beeaosama-descrbvbnvbniption | java/src/org/pocketworkstation/pckeyboard/ContactsDictionary.java | Java | asf20 | 5,606 |
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.text.Layout;
import android.text.SpannableStringBuilder;
import android.text.StaticLayout;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.PopupWindow;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class Tutorial implements OnTouchListener {
private List<Bubble> mBubbles = new ArrayList<Bubble>();
private View mInputView;
private LatinIME mIme;
private int[] mLocation = new int[2];
private static final int MSG_SHOW_BUBBLE = 0;
private int mBubbleIndex;
Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_SHOW_BUBBLE:
Bubble bubba = (Bubble) msg.obj;
bubba.show(mLocation[0], mLocation[1]);
break;
}
}
};
class Bubble {
Drawable bubbleBackground;
int x;
int y;
int width;
int gravity;
CharSequence text;
boolean dismissOnTouch;
boolean dismissOnClose;
PopupWindow window;
TextView textView;
View inputView;
Bubble(Context context, View inputView,
int backgroundResource, int bx, int by, int textResource1, int textResource2) {
bubbleBackground = context.getResources().getDrawable(backgroundResource);
x = bx;
y = by;
width = (int) (inputView.getWidth() * 0.9);
this.gravity = Gravity.TOP | Gravity.LEFT;
text = new SpannableStringBuilder()
.append(context.getResources().getText(textResource1))
.append("\n")
.append(context.getResources().getText(textResource2));
this.dismissOnTouch = true;
this.dismissOnClose = false;
this.inputView = inputView;
window = new PopupWindow(context);
window.setBackgroundDrawable(null);
LayoutInflater inflate =
(LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
textView = (TextView) inflate.inflate(R.layout.bubble_text, null);
textView.setBackgroundDrawable(bubbleBackground);
textView.setText(text);
//textView.setText(textResource1);
window.setContentView(textView);
window.setFocusable(false);
window.setTouchable(true);
window.setOutsideTouchable(false);
}
private int chooseSize(PopupWindow pop, View parentView, CharSequence text, TextView tv) {
int wid = tv.getPaddingLeft() + tv.getPaddingRight();
int ht = tv.getPaddingTop() + tv.getPaddingBottom();
/*
* Figure out how big the text would be if we laid it out to the
* full width of this view minus the border.
*/
int cap = width - wid;
Layout l = new StaticLayout(text, tv.getPaint(), cap,
Layout.Alignment.ALIGN_NORMAL, 1, 0, true);
float max = 0;
for (int i = 0; i < l.getLineCount(); i++) {
max = Math.max(max, l.getLineWidth(i));
}
/*
* Now set the popup size to be big enough for the text plus the border.
*/
pop.setWidth(width);
pop.setHeight(ht + l.getHeight());
return l.getHeight();
}
void show(int offx, int offy) {
int textHeight = chooseSize(window, inputView, text, textView);
offy -= textView.getPaddingTop() + textHeight;
if (inputView.getVisibility() == View.VISIBLE
&& inputView.getWindowVisibility() == View.VISIBLE) {
try {
if ((gravity & Gravity.BOTTOM) == Gravity.BOTTOM) offy -= window.getHeight();
if ((gravity & Gravity.RIGHT) == Gravity.RIGHT) offx -= window.getWidth();
textView.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View view, MotionEvent me) {
Tutorial.this.next();
return true;
}
});
window.showAtLocation(inputView, Gravity.NO_GRAVITY, x + offx, y + offy);
} catch (Exception e) {
// Input view is not valid
}
}
}
void hide() {
if (window.isShowing()) {
textView.setOnTouchListener(null);
window.dismiss();
}
}
boolean isShowing() {
return window.isShowing();
}
}
public Tutorial(LatinIME ime, LatinKeyboardView inputView) {
Context context = inputView.getContext();
mIme = ime;
int inputWidth = inputView.getWidth();
final int x = inputWidth / 20; // Half of 1/10th
Bubble bWelcome = new Bubble(context, inputView,
R.drawable.dialog_bubble_step02, x, 0,
R.string.tip_to_open_keyboard, R.string.touch_to_continue);
mBubbles.add(bWelcome);
Bubble bAccents = new Bubble(context, inputView,
R.drawable.dialog_bubble_step02, x, 0,
R.string.tip_to_view_accents, R.string.touch_to_continue);
mBubbles.add(bAccents);
Bubble b123 = new Bubble(context, inputView,
R.drawable.dialog_bubble_step07, x, 0,
R.string.tip_to_open_symbols, R.string.touch_to_continue);
mBubbles.add(b123);
Bubble bABC = new Bubble(context, inputView,
R.drawable.dialog_bubble_step07, x, 0,
R.string.tip_to_close_symbols, R.string.touch_to_continue);
mBubbles.add(bABC);
Bubble bSettings = new Bubble(context, inputView,
R.drawable.dialog_bubble_step07, x, 0,
R.string.tip_to_launch_settings, R.string.touch_to_continue);
mBubbles.add(bSettings);
Bubble bDone = new Bubble(context, inputView,
R.drawable.dialog_bubble_step02, x, 0,
R.string.tip_to_start_typing, R.string.touch_to_finish);
mBubbles.add(bDone);
mInputView = inputView;
}
void start() {
mInputView.getLocationInWindow(mLocation);
mBubbleIndex = -1;
mInputView.setOnTouchListener(this);
next();
}
boolean next() {
if (mBubbleIndex >= 0) {
// If the bubble is not yet showing, don't move to the next.
if (!mBubbles.get(mBubbleIndex).isShowing()) {
return true;
}
// Hide all previous bubbles as well, as they may have had a delayed show
for (int i = 0; i <= mBubbleIndex; i++) {
mBubbles.get(i).hide();
}
}
mBubbleIndex++;
if (mBubbleIndex >= mBubbles.size()) {
mInputView.setOnTouchListener(null);
mIme.sendDownUpKeyEvents(-1); // Inform the setupwizard that tutorial is in last bubble
mIme.tutorialDone();
return false;
}
if (mBubbleIndex == 3 || mBubbleIndex == 4) {
mIme.mKeyboardSwitcher.toggleSymbols();
}
mHandler.sendMessageDelayed(
mHandler.obtainMessage(MSG_SHOW_BUBBLE, mBubbles.get(mBubbleIndex)), 500);
return true;
}
void hide() {
for (int i = 0; i < mBubbles.size(); i++) {
mBubbles.get(i).hide();
}
mInputView.setOnTouchListener(null);
}
boolean close() {
mHandler.removeMessages(MSG_SHOW_BUBBLE);
hide();
return true;
}
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
next();
}
return true;
}
}
| 11beeaosama-descrbvbnvbniption | java/src/org/pocketworkstation/pckeyboard/Tutorial.java | Java | asf20 | 9,032 |
/*
* Copyright (C) 2011 Darren Salt
*
* Licensed under the Apache License, Version 2.0 (the "Licence"); you may
* not use this file except in compliance with the Licence. You may obtain
* a copy of the Licence at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the Licence is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* Licence for the specific language governing permissions and limitations
* under the Licence.
*/
package org.pocketworkstation.pckeyboard;
public class ComposeSequence extends ComposeBase {
public ComposeSequence(ComposeSequencing user) {
init(user);
}
static {
put("++", "#");
put("' ", "'");
put(" '", "'");
put("AT", "@");
put("((", "[");
put("//", "\\");
put("/<", "\\");
put("</", "\\");
put("))", "]");
put("^ ", "^");
put(" ^", "^");
put("> ", "^");
put(" >", "^");
put("` ", "`");
put(" `", "`");
put(", ", "¸");
put(" ,", "¸");
put("(-", "{");
put("-(", "{");
put("/^", "|");
put("^/", "|");
put("VL", "|");
put("LV", "|");
put("vl", "|");
put("lv", "|");
put(")-", "}");
put("-)", "}");
put("~ ", "~");
put(" ~", "~");
put("- ", "~");
put(" -", "~");
put(" ", " ");
put(" .", " ");
put("oc", "©");
put("oC", "©");
put("Oc", "©");
put("OC", "©");
put("or", "®");
put("oR", "®");
put("Or", "®");
put("OR", "®");
put(".>", "›");
put(".<", "‹");
put("..", "…");
put(".-", "·");
put(".=", "•");
put("!^", "¦");
put("!!", "¡");
put("p!", "¶");
put("P!", "¶");
put("+-", "±");
put("??", "¿");
put("-d", "đ");
put("-D", "Đ");
put("ss", "ß");
put("SS", "ẞ");
put("oe", "œ");
put("OE", "Œ");
put("ae", "æ");
put("AE", "Æ");
put("oo", "°");
put("\"\\", "〝");
put("\"/", "〞");
put("<<", "«");
put(">>", "»");
put("<'", "‘");
put("'<", "‘");
put(">'", "’");
put("'>", "’");
put(",'", "‚");
put("',", "‚");
put("<\"", "“");
put("\"<", "“");
put(">\"", "”");
put("\">", "”");
put(",\"", "„");
put("\",", "„");
put("%o", "‰");
put("CE", "₠");
put("C/", "₡");
put("/C", "₡");
put("Cr", "₢");
put("Fr", "₣");
put("L=", "₤");
put("=L", "₤");
put("m/", "₥");
put("/m", "₥");
put("N=", "₦");
put("=N", "₦");
put("Pt", "₧");
put("Rs", "₨");
put("W=", "₩");
put("=W", "₩");
put("d-", "₫");
put("C=", "€");
put("=C", "€");
put("c=", "€");
put("=c", "€");
put("E=", "€");
put("=E", "€");
put("e=", "€");
put("=e", "€");
put("|c", "¢");
put("c|", "¢");
put("c/", "¢");
put("/c", "¢");
put("L-", "£");
put("-L", "£");
put("Y=", "¥");
put("=Y", "¥");
put("fs", "ſ");
put("fS", "ſ");
put("--.", "–");
put("---", "—");
put("#b", "♭");
put("#f", "♮");
put("##", "♯");
put("so", "§");
put("os", "§");
put("ox", "¤");
put("xo", "¤");
put("PP", "¶");
put("No", "№");
put("NO", "№");
put("?!", "⸘");
put("!?", "‽");
put("CCCP", "☭");
put("OA", "Ⓐ");
put("<3", "♥");
put(":)", "☺");
put(":(", "☹");
put(",-", "¬");
put("-,", "¬");
put("^_a", "ª");
put("^2", "²");
put("^3", "³");
put("mu", "µ");
put("^1", "¹");
put("^_o", "º");
put("14", "¼");
put("12", "½");
put("34", "¾");
put("`A", "À");
put("'A", "Á");
put("^A", "Â");
put("~A", "Ã");
put("\"A", "Ä");
put("oA", "Å");
put(",C", "Ç");
put("`E", "È");
put("'E", "É");
put("^E", "Ê");
put("\"E", "Ë");
put("`I", "Ì");
put("'I", "Í");
put("^I", "Î");
put("\"I", "Ï");
put("DH", "Ð");
put("~N", "Ñ");
put("`O", "Ò");
put("'O", "Ó");
put("^O", "Ô");
put("~O", "Õ");
put("\"O", "Ö");
put("xx", "×");
put("/O", "Ø");
put("`U", "Ù");
put("'U", "Ú");
put("^U", "Û");
put("\"U", "Ü");
put("'Y", "Ý");
put("TH", "Þ");
put("`a", "à");
put("'a", "á");
put("^a", "â");
put("~a", "ã");
put("\"a", "ä");
put("oa", "å");
put(",c", "ç");
put("`e", "è");
put("'e", "é");
put("^e", "ê");
put("\"e", "ë");
put("`i", "ì");
put("'i", "í");
put("^i", "î");
put("\"i", "ï");
put("dh", "ð");
put("~n", "ñ");
put("`o", "ò");
put("'o", "ó");
put("^o", "ô");
put("~o", "õ");
put("\"o", "ö");
put(":-", "÷");
put("-:", "÷");
put("/o", "ø");
put("`u", "ù");
put("'u", "ú");
put("^u", "û");
put("\"u", "ü");
put("'y", "ý");
put("th", "þ");
put("\"y", "ÿ");
put("_A", "Ā");
put("_a", "ā");
put("UA", "Ă");
put("bA", "Ă");
put("Ua", "ă");
put("ba", "ă");
put(";A", "Ą");
put(",A", "Ą");
put(";a", "ą");
put(",a", "ą");
put("'C", "Ć");
put("'c", "ć");
put("^C", "Ĉ");
put("^c", "ĉ");
put(".C", "Ċ");
put(".c", "ċ");
put("cC", "Č");
put("cc", "č");
put("cD", "Ď");
put("cd", "ď");
put("/D", "Đ");
put("/d", "đ");
put("_E", "Ē");
put("_e", "ē");
put("UE", "Ĕ");
put("bE", "Ĕ");
put("Ue", "ĕ");
put("be", "ĕ");
put(".E", "Ė");
put(".e", "ė");
put(";E", "Ę");
put(",E", "Ę");
put(";e", "ę");
put(",e", "ę");
put("cE", "Ě");
put("ce", "ě");
//put("ff", "ff"); // Not usable, interferes with ffi/ffl prefix
put("+f", "ff");
put("f+", "ff");
put("fi", "fi");
put("fl", "fl");
put("ffi", "ffi");
put("ffl", "ffl");
put("^G", "Ĝ");
put("^g", "ĝ");
put("UG", "Ğ");
put("bG", "Ğ");
put("Ug", "ğ");
put("bg", "ğ");
put(".G", "Ġ");
put(".g", "ġ");
put(",G", "Ģ");
put(",g", "ģ");
put("^H", "Ĥ");
put("^h", "ĥ");
put("/H", "Ħ");
put("/h", "ħ");
put("~I", "Ĩ");
put("~i", "ĩ");
put("_I", "Ī");
put("_i", "ī");
put("UI", "Ĭ");
put("bI", "Ĭ");
put("Ui", "ĭ");
put("bi", "ĭ");
put(";I", "Į");
put(",I", "Į");
put(";i", "į");
put(",i", "į");
put(".I", "İ");
put("i.", "ı");
put("^J", "Ĵ");
put("^j", "ĵ");
put(",K", "Ķ");
put(",k", "ķ");
put("kk", "ĸ");
put("'L", "Ĺ");
put("'l", "ĺ");
put(",L", "Ļ");
put(",l", "ļ");
put("cL", "Ľ");
put("cl", "ľ");
put("/L", "Ł");
put("/l", "ł");
put("'N", "Ń");
put("'n", "ń");
put(",N", "Ņ");
put(",n", "ņ");
put("cN", "Ň");
put("cn", "ň");
put("NG", "Ŋ");
put("ng", "ŋ");
put("_O", "Ō");
put("_o", "ō");
put("UO", "Ŏ");
put("bO", "Ŏ");
put("Uo", "ŏ");
put("bo", "ŏ");
put("=O", "Ő");
put("=o", "ő");
put("'R", "Ŕ");
put("'r", "ŕ");
put(",R", "Ŗ");
put(",r", "ŗ");
put("cR", "Ř");
put("cr", "ř");
put("'S", "Ś");
put("'s", "ś");
put("^S", "Ŝ");
put("^s", "ŝ");
put(",S", "Ş");
put(",s", "ş");
put("cS", "Š");
put("cs", "š");
put(",T", "Ţ");
put(",t", "ţ");
put("cT", "Ť");
put("ct", "ť");
put("/T", "Ŧ");
put("/t", "ŧ");
put("~U", "Ũ");
put("~u", "ũ");
put("_U", "Ū");
put("_u", "ū");
put("UU", "Ŭ");
put("bU", "Ŭ");
put("Uu", "ŭ");
put("uu", "ŭ");
put("bu", "ŭ");
put("oU", "Ů");
put("ou", "ů");
put("=U", "Ű");
put("=u", "ű");
put(";U", "Ų");
put(",U", "Ų");
put(";u", "ų");
put(",u", "ų");
put("^W", "Ŵ");
put("^w", "ŵ");
put("^Y", "Ŷ");
put("^y", "ŷ");
put("\"Y", "Ÿ");
put("'Z", "Ź");
put("'z", "ź");
put(".Z", "Ż");
put(".z", "ż");
put("cZ", "Ž");
put("cz", "ž");
put("/b", "ƀ");
put("/I", "Ɨ");
put("+O", "Ơ");
put("+o", "ơ");
put("+U", "Ư");
put("+u", "ư");
put("/Z", "Ƶ");
put("/z", "ƶ");
put("cA", "Ǎ");
put("ca", "ǎ");
put("cI", "Ǐ");
put("ci", "ǐ");
put("cO", "Ǒ");
put("co", "ǒ");
put("cU", "Ǔ");
put("cu", "ǔ");
put("_Ü", "Ǖ");
put("_\"U", "Ǖ");
put("_ü", "ǖ");
put("_\"u", "ǖ");
put("'Ü", "Ǘ");
put("'\"U", "Ǘ");
put("'ü", "ǘ");
put("'\"u", "ǘ");
put("cÜ", "Ǚ");
put("c\"U", "Ǚ");
put("cü", "ǚ");
put("c\"u", "ǚ");
put("`Ü", "Ǜ");
put("`\"U", "Ǜ");
put("`ü", "ǜ");
put("`\"u", "ǜ");
put("_Ä", "Ǟ");
put("_\"A", "Ǟ");
put("_ä", "ǟ");
put("_\"a", "ǟ");
put("_.A", "Ǡ");
put("_.a", "ǡ");
put("_Æ", "Ǣ");
put("_æ", "ǣ");
put("/G", "Ǥ");
put("/g", "ǥ");
put("cG", "Ǧ");
put("cg", "ǧ");
put("cK", "Ǩ");
put("ck", "ǩ");
put(";O", "Ǫ");
put(";o", "ǫ");
put("_;O", "Ǭ");
put("_;o", "ǭ");
put("cj", "ǰ");
put("'G", "Ǵ");
put("'g", "ǵ");
put("`N", "Ǹ");
put("`n", "ǹ");
put("'Å", "Ǻ");
put("o'A", "Ǻ");
put("'å", "ǻ");
put("o'a", "ǻ");
put("'Æ", "Ǽ");
put("'æ", "ǽ");
put("'Ø", "Ǿ");
put("'/O", "Ǿ");
put("'ø", "ǿ");
put("'/o", "ǿ");
put("cH", "Ȟ");
put("ch", "ȟ");
put(".A", "Ȧ");
put(".a", "ȧ");
put("_Ö", "Ȫ");
put("_\"O", "Ȫ");
put("_ö", "ȫ");
put("_\"o", "ȫ");
put("_Õ", "Ȭ");
put("_~O", "Ȭ");
put("_õ", "ȭ");
put("_~o", "ȭ");
put(".O", "Ȯ");
put(".o", "ȯ");
put("_.O", "Ȱ");
put("_.o", "ȱ");
put("_Y", "Ȳ");
put("_y", "ȳ");
put("ee", "ə");
put("/i", "ɨ");
put("^_h", "ʰ");
put("^_j", "ʲ");
put("^_r", "ʳ");
put("^_w", "ʷ");
put("^_y", "ʸ");
put("^_l", "ˡ");
put("^_s", "ˢ");
put("^_x", "ˣ");
put("\"'", "̈́");
put(".B", "Ḃ");
put(".b", "ḃ");
put("!B", "Ḅ");
put("!b", "ḅ");
put("'Ç", "Ḉ");
put("'ç", "ḉ");
put(".D", "Ḋ");
put(".d", "ḋ");
put("!D", "Ḍ");
put("!d", "ḍ");
put(",D", "Ḑ");
put(",d", "ḑ");
put("`Ē", "Ḕ");
put("`_E", "Ḕ");
put("`ē", "ḕ");
put("`_e", "ḕ");
put("'Ē", "Ḗ");
put("'_E", "Ḗ");
put("'ē", "ḗ");
put("'_e", "ḗ");
put("U,E", "Ḝ");
put("b,E", "Ḝ");
put("U,e", "ḝ");
put("b,e", "ḝ");
put(".F", "Ḟ");
put(".f", "ḟ");
put("_G", "Ḡ");
put("_g", "ḡ");
put(".H", "Ḣ");
put(".h", "ḣ");
put("!H", "Ḥ");
put("!h", "ḥ");
put("\"H", "Ḧ");
put("\"h", "ḧ");
put(",H", "Ḩ");
put(",h", "ḩ");
put("'Ï", "Ḯ");
put("'\"I", "Ḯ");
put("'ï", "ḯ");
put("'\"i", "ḯ");
put("'K", "Ḱ");
put("'k", "ḱ");
put("!K", "Ḳ");
put("!k", "ḳ");
put("!L", "Ḷ");
put("!l", "ḷ");
put("_!L", "Ḹ");
put("_!l", "ḹ");
put("'M", "Ḿ");
put("'m", "ḿ");
put(".M", "Ṁ");
put(".m", "ṁ");
put("!M", "Ṃ");
put("!m", "ṃ");
put(".N", "Ṅ");
put(".n", "ṅ");
put("!N", "Ṇ");
put("!n", "ṇ");
put("'Õ", "Ṍ");
put("'~O", "Ṍ");
put("'õ", "ṍ");
put("'~o", "ṍ");
put("\"Õ", "Ṏ");
put("\"~O", "Ṏ");
put("\"õ", "ṏ");
put("\"~o", "ṏ");
put("`Ō", "Ṑ");
put("`_O", "Ṑ");
put("`ō", "ṑ");
put("`_o", "ṑ");
put("'Ō", "Ṓ");
put("'_O", "Ṓ");
put("'ō", "ṓ");
put("'_o", "ṓ");
put("'P", "Ṕ");
put("'p", "ṕ");
put(".P", "Ṗ");
put(".p", "ṗ");
put(".R", "Ṙ");
put(".r", "ṙ");
put("!R", "Ṛ");
put("!r", "ṛ");
put("_!R", "Ṝ");
put("_!r", "ṝ");
put(".S", "Ṡ");
put(".s", "ṡ");
put("!S", "Ṣ");
put("!s", "ṣ");
put(".Ś", "Ṥ");
put(".'S", "Ṥ");
put(".ś", "ṥ");
put(".'s", "ṥ");
put(".Š", "Ṧ");
put(".š", "ṧ");
put(".!S", "Ṩ");
put(".!s", "ṩ");
put(".T", "Ṫ");
put(".t", "ṫ");
put("!T", "Ṭ");
put("!t", "ṭ");
put("'Ũ", "Ṹ");
put("'~U", "Ṹ");
put("'ũ", "ṹ");
put("'~u", "ṹ");
put("\"Ū", "Ṻ");
put("\"_U", "Ṻ");
put("\"ū", "ṻ");
put("\"_u", "ṻ");
put("~V", "Ṽ");
put("~v", "ṽ");
put("!V", "Ṿ");
put("!v", "ṿ");
put("`W", "Ẁ");
put("`w", "ẁ");
put("'W", "Ẃ");
put("'w", "ẃ");
put("\"W", "Ẅ");
put("\"w", "ẅ");
put(".W", "Ẇ");
put(".w", "ẇ");
put("!W", "Ẉ");
put("!w", "ẉ");
put(".X", "Ẋ");
put(".x", "ẋ");
put("\"X", "Ẍ");
put("\"x", "ẍ");
put(".Y", "Ẏ");
put(".y", "ẏ");
put("^Z", "Ẑ");
put("^z", "ẑ");
put("!Z", "Ẓ");
put("!z", "ẓ");
put("\"t", "ẗ");
put("ow", "ẘ");
put("oy", "ẙ");
put("!A", "Ạ");
put("!a", "ạ");
put("?A", "Ả");
put("?a", "ả");
put("'Â", "Ấ");
put("'^A", "Ấ");
put("'â", "ấ");
put("'^a", "ấ");
put("`Â", "Ầ");
put("`^A", "Ầ");
put("`â", "ầ");
put("`^a", "ầ");
put("?Â", "Ẩ");
put("?^A", "Ẩ");
put("?â", "ẩ");
put("?^a", "ẩ");
put("~Â", "Ẫ");
put("~^A", "Ẫ");
put("~â", "ẫ");
put("~^a", "ẫ");
put("^!A", "Ậ");
put("^!a", "ậ");
put("'Ă", "Ắ");
put("'bA", "Ắ");
put("'ă", "ắ");
put("'ba", "ắ");
put("`Ă", "Ằ");
put("`bA", "Ằ");
put("`ă", "ằ");
put("`ba", "ằ");
put("?Ă", "Ẳ");
put("?bA", "Ẳ");
put("?ă", "ẳ");
put("?ba", "ẳ");
put("~Ă", "Ẵ");
put("~bA", "Ẵ");
put("~ă", "ẵ");
put("~ba", "ẵ");
put("U!A", "Ặ");
put("b!A", "Ặ");
put("U!a", "ặ");
put("b!a", "ặ");
put("!E", "Ẹ");
put("!e", "ẹ");
put("?E", "Ẻ");
put("?e", "ẻ");
put("~E", "Ẽ");
put("~e", "ẽ");
put("'Ê", "Ế");
put("'^E", "Ế");
put("'ê", "ế");
put("'^e", "ế");
put("`Ê", "Ề");
put("`^E", "Ề");
put("`ê", "ề");
put("`^e", "ề");
put("?Ê", "Ể");
put("?^E", "Ể");
put("?ê", "ể");
put("?^e", "ể");
put("~Ê", "Ễ");
put("~^E", "Ễ");
put("~ê", "ễ");
put("~^e", "ễ");
put("^!E", "Ệ");
put("^!e", "ệ");
put("?I", "Ỉ");
put("?i", "ỉ");
put("!I", "Ị");
put("!i", "ị");
put("!O", "Ọ");
put("!o", "ọ");
put("?O", "Ỏ");
put("?o", "ỏ");
put("'Ô", "Ố");
put("'^O", "Ố");
put("'ô", "ố");
put("'^o", "ố");
put("`Ô", "Ồ");
put("`^O", "Ồ");
put("`ô", "ồ");
put("`^o", "ồ");
put("?Ô", "Ổ");
put("?^O", "Ổ");
put("?ô", "ổ");
put("?^o", "ổ");
put("~Ô", "Ỗ");
put("~^O", "Ỗ");
put("~ô", "ỗ");
put("~^o", "ỗ");
put("^!O", "Ộ");
put("^!o", "ộ");
put("'Ơ", "Ớ");
put("'+O", "Ớ");
put("'ơ", "ớ");
put("'+o", "ớ");
put("`Ơ", "Ờ");
put("`+O", "Ờ");
put("`ơ", "ờ");
put("`+o", "ờ");
put("?Ơ", "Ở");
put("?+O", "Ở");
put("?ơ", "ở");
put("?+o", "ở");
put("~Ơ", "Ỡ");
put("~+O", "Ỡ");
put("~ơ", "ỡ");
put("~+o", "ỡ");
put("!Ơ", "Ợ");
put("!+O", "Ợ");
put("!ơ", "ợ");
put("!+o", "ợ");
put("!U", "Ụ");
put("!u", "ụ");
put("?U", "Ủ");
put("?u", "ủ");
put("'Ư", "Ứ");
put("'+U", "Ứ");
put("'ư", "ứ");
put("'+u", "ứ");
put("`Ư", "Ừ");
put("`+U", "Ừ");
put("`ư", "ừ");
put("`+u", "ừ");
put("?Ư", "Ử");
put("?+U", "Ử");
put("?ư", "ử");
put("?+u", "ử");
put("~Ư", "Ữ");
put("~+U", "Ữ");
put("~ư", "ữ");
put("~+u", "ữ");
put("!Ư", "Ự");
put("!+U", "Ự");
put("!ư", "ự");
put("!+u", "ự");
put("`Y", "Ỳ");
put("`y", "ỳ");
put("!Y", "Ỵ");
put("!y", "ỵ");
put("?Y", "Ỷ");
put("?y", "ỷ");
put("~Y", "Ỹ");
put("~y", "ỹ");
put("^0", "⁰");
put("^_i", "ⁱ");
put("^4", "⁴");
put("^5", "⁵");
put("^6", "⁶");
put("^7", "⁷");
put("^8", "⁸");
put("^9", "⁹");
put("^+", "⁺");
put("^=", "⁼");
put("^(", "⁽");
put("^)", "⁾");
put("^_n", "ⁿ");
put("_0", "₀");
put("_1", "₁");
put("_2", "₂");
put("_3", "₃");
put("_4", "₄");
put("_5", "₅");
put("_6", "₆");
put("_7", "₇");
put("_8", "₈");
put("_9", "₉");
put("_+", "₊");
put("_=", "₌");
put("_(", "₍");
put("_)", "₎");
put("SM", "℠");
put("sM", "℠");
put("Sm", "℠");
put("sm", "℠");
put("TM", "™");
put("tM", "™");
put("Tm", "™");
put("tm", "™");
put("13", "⅓");
put("23", "⅔");
put("15", "⅕");
put("25", "⅖");
put("35", "⅗");
put("45", "⅘");
put("16", "⅙");
put("56", "⅚");
put("18", "⅛");
put("38", "⅜");
put("58", "⅝");
put("78", "⅞");
put("/←", "↚");
put("/→", "↛");
put("<-", "←");
put("->", "→");
put("/=", "≠");
put("=/", "≠");
put("<=", "≤");
put(">=", "≥");
put("(1)", "①");
put("(2)", "②");
put("(3)", "③");
put("(4)", "④");
put("(5)", "⑤");
put("(6)", "⑥");
put("(7)", "⑦");
put("(8)", "⑧");
put("(9)", "⑨");
put("(10)", "⑩");
put("(11)", "⑪");
put("(12)", "⑫");
put("(13)", "⑬");
put("(14)", "⑭");
put("(15)", "⑮");
put("(16)", "⑯");
put("(17)", "⑰");
put("(18)", "⑱");
put("(19)", "⑲");
put("(20)", "⑳");
put("(A)", "Ⓐ");
put("(B)", "Ⓑ");
put("(C)", "Ⓒ");
put("(D)", "Ⓓ");
put("(E)", "Ⓔ");
put("(F)", "Ⓕ");
put("(G)", "Ⓖ");
put("(H)", "Ⓗ");
put("(I)", "Ⓘ");
put("(J)", "Ⓙ");
put("(K)", "Ⓚ");
put("(L)", "Ⓛ");
put("(M)", "Ⓜ");
put("(N)", "Ⓝ");
put("(O)", "Ⓞ");
put("(P)", "Ⓟ");
put("(Q)", "Ⓠ");
put("(R)", "Ⓡ");
put("(S)", "Ⓢ");
put("(T)", "Ⓣ");
put("(U)", "Ⓤ");
put("(V)", "Ⓥ");
put("(W)", "Ⓦ");
put("(X)", "Ⓧ");
put("(Y)", "Ⓨ");
put("(Z)", "Ⓩ");
put("(a)", "ⓐ");
put("(b)", "ⓑ");
put("(c)", "ⓒ");
put("(d)", "ⓓ");
put("(e)", "ⓔ");
put("(f)", "ⓕ");
put("(g)", "ⓖ");
put("(h)", "ⓗ");
put("(i)", "ⓘ");
put("(j)", "ⓙ");
put("(k)", "ⓚ");
put("(l)", "ⓛ");
put("(m)", "ⓜ");
put("(n)", "ⓝ");
put("(o)", "ⓞ");
put("(p)", "ⓟ");
put("(q)", "ⓠ");
put("(r)", "ⓡ");
put("(s)", "ⓢ");
put("(t)", "ⓣ");
put("(u)", "ⓤ");
put("(v)", "ⓥ");
put("(w)", "ⓦ");
put("(x)", "ⓧ");
put("(y)", "ⓨ");
put("(z)", "ⓩ");
put("(0)", "⓪");
put("(21)", "㉑");
put("(22)", "㉒");
put("(23)", "㉓");
put("(24)", "㉔");
put("(25)", "㉕");
put("(26)", "㉖");
put("(27)", "㉗");
put("(28)", "㉘");
put("(29)", "㉙");
put("(30)", "㉚");
put("(31)", "㉛");
put("(32)", "㉜");
put("(33)", "㉝");
put("(34)", "㉞");
put("(35)", "㉟");
put("(36)", "㊱");
put("(37)", "㊲");
put("(38)", "㊳");
put("(39)", "㊴");
put("(40)", "㊵");
put("(41)", "㊶");
put("(42)", "㊷");
put("(43)", "㊸");
put("(44)", "㊹");
put("(45)", "㊺");
put("(46)", "㊻");
put("(47)", "㊼");
put("(48)", "㊽");
put("(49)", "㊾");
put("(50)", "㊿");
put("\\o/", "🙌");
}
}
| 11beeaosama-descrbvbnvbniption | java/src/org/pocketworkstation/pckeyboard/ComposeSequence.java | Java | asf20 | 27,394 |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.pocketworkstation.pckeyboard;
import android.view.inputmethod.InputMethodManager;
import android.content.Context;
import android.os.AsyncTask;
import android.text.format.DateUtils;
import android.util.Log;
public class LatinIMEUtil {
/**
* Cancel an {@link AsyncTask}.
*
* @param mayInterruptIfRunning <tt>true</tt> if the thread executing this
* task should be interrupted; otherwise, in-progress tasks are allowed
* to complete.
*/
public static void cancelTask(AsyncTask<?, ?, ?> task, boolean mayInterruptIfRunning) {
if (task != null && task.getStatus() != AsyncTask.Status.FINISHED) {
task.cancel(mayInterruptIfRunning);
}
}
public static class GCUtils {
private static final String TAG = "GCUtils";
public static final int GC_TRY_COUNT = 2;
// GC_TRY_LOOP_MAX is used for the hard limit of GC wait,
// GC_TRY_LOOP_MAX should be greater than GC_TRY_COUNT.
public static final int GC_TRY_LOOP_MAX = 5;
private static final long GC_INTERVAL = DateUtils.SECOND_IN_MILLIS;
private static GCUtils sInstance = new GCUtils();
private int mGCTryCount = 0;
public static GCUtils getInstance() {
return sInstance;
}
public void reset() {
mGCTryCount = 0;
}
public boolean tryGCOrWait(String metaData, Throwable t) {
if (mGCTryCount == 0) {
System.gc();
}
if (++mGCTryCount > GC_TRY_COUNT) {
LatinImeLogger.logOnException(metaData, t);
return false;
} else {
try {
Thread.sleep(GC_INTERVAL);
return true;
} catch (InterruptedException e) {
Log.e(TAG, "Sleep was interrupted.");
LatinImeLogger.logOnException(metaData, t);
return false;
}
}
}
}
/* package */ static class RingCharBuffer {
private static RingCharBuffer sRingCharBuffer = new RingCharBuffer();
private static final char PLACEHOLDER_DELIMITER_CHAR = '\uFFFC';
private static final int INVALID_COORDINATE = -2;
/* package */ static final int BUFSIZE = 20;
private Context mContext;
private boolean mEnabled = false;
private int mEnd = 0;
/* package */ int mLength = 0;
private char[] mCharBuf = new char[BUFSIZE];
private int[] mXBuf = new int[BUFSIZE];
private int[] mYBuf = new int[BUFSIZE];
private RingCharBuffer() {
}
public static RingCharBuffer getInstance() {
return sRingCharBuffer;
}
public static RingCharBuffer init(Context context, boolean enabled) {
sRingCharBuffer.mContext = context;
sRingCharBuffer.mEnabled = enabled;
return sRingCharBuffer;
}
private int normalize(int in) {
int ret = in % BUFSIZE;
return ret < 0 ? ret + BUFSIZE : ret;
}
public void push(char c, int x, int y) {
if (!mEnabled) return;
mCharBuf[mEnd] = c;
mXBuf[mEnd] = x;
mYBuf[mEnd] = y;
mEnd = normalize(mEnd + 1);
if (mLength < BUFSIZE) {
++mLength;
}
}
public char pop() {
if (mLength < 1) {
return PLACEHOLDER_DELIMITER_CHAR;
} else {
mEnd = normalize(mEnd - 1);
--mLength;
return mCharBuf[mEnd];
}
}
public char getLastChar() {
if (mLength < 1) {
return PLACEHOLDER_DELIMITER_CHAR;
} else {
return mCharBuf[normalize(mEnd - 1)];
}
}
public int getPreviousX(char c, int back) {
int index = normalize(mEnd - 2 - back);
if (mLength <= back
|| Character.toLowerCase(c) != Character.toLowerCase(mCharBuf[index])) {
return INVALID_COORDINATE;
} else {
return mXBuf[index];
}
}
public int getPreviousY(char c, int back) {
int index = normalize(mEnd - 2 - back);
if (mLength <= back
|| Character.toLowerCase(c) != Character.toLowerCase(mCharBuf[index])) {
return INVALID_COORDINATE;
} else {
return mYBuf[index];
}
}
public String getLastString() {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < mLength; ++i) {
char c = mCharBuf[normalize(mEnd - 1 - i)];
if (!((LatinIME)mContext).isWordSeparator(c)) {
sb.append(c);
} else {
break;
}
}
return sb.reverse().toString();
}
public void reset() {
mLength = 0;
}
}
}
| 11beeaosama-descrbvbnvbniption | java/src/org/pocketworkstation/pckeyboard/LatinIMEUtil.java | Java | asf20 | 5,769 |
/*
* Copyright (C) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import java.util.Locale;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
/**
* Keeps track of list of selected input languages and the current
* input language that the user has selected.
*/
public class LanguageSwitcher {
private static final String TAG = "HK/LanguageSwitcher";
private Locale[] mLocales;
private LatinIME mIme;
private String[] mSelectedLanguageArray;
private String mSelectedLanguages;
private int mCurrentIndex = 0;
private String mDefaultInputLanguage;
private Locale mDefaultInputLocale;
private Locale mSystemLocale;
public LanguageSwitcher(LatinIME ime) {
mIme = ime;
mLocales = new Locale[0];
}
public Locale[] getLocales() {
return mLocales;
}
public int getLocaleCount() {
return mLocales.length;
}
/**
* Loads the currently selected input languages from shared preferences.
* @param sp
* @return whether there was any change
*/
public boolean loadLocales(SharedPreferences sp) {
String selectedLanguages = sp.getString(LatinIME.PREF_SELECTED_LANGUAGES, null);
String currentLanguage = sp.getString(LatinIME.PREF_INPUT_LANGUAGE, null);
if (selectedLanguages == null || selectedLanguages.length() < 1) {
loadDefaults();
if (mLocales.length == 0) {
return false;
}
mLocales = new Locale[0];
return true;
}
if (selectedLanguages.equals(mSelectedLanguages)) {
return false;
}
mSelectedLanguageArray = selectedLanguages.split(",");
mSelectedLanguages = selectedLanguages; // Cache it for comparison later
constructLocales();
mCurrentIndex = 0;
if (currentLanguage != null) {
// Find the index
mCurrentIndex = 0;
for (int i = 0; i < mLocales.length; i++) {
if (mSelectedLanguageArray[i].equals(currentLanguage)) {
mCurrentIndex = i;
break;
}
}
// If we didn't find the index, use the first one
}
return true;
}
private void loadDefaults() {
mDefaultInputLocale = mIme.getResources().getConfiguration().locale;
String country = mDefaultInputLocale.getCountry();
mDefaultInputLanguage = mDefaultInputLocale.getLanguage() +
(TextUtils.isEmpty(country) ? "" : "_" + country);
}
private void constructLocales() {
mLocales = new Locale[mSelectedLanguageArray.length];
for (int i = 0; i < mLocales.length; i++) {
final String lang = mSelectedLanguageArray[i];
mLocales[i] = new Locale(lang.substring(0, 2),
lang.length() > 4 ? lang.substring(3, 5) : "");
}
}
/**
* Returns the currently selected input language code, or the display language code if
* no specific locale was selected for input.
*/
public String getInputLanguage() {
if (getLocaleCount() == 0) return mDefaultInputLanguage;
return mSelectedLanguageArray[mCurrentIndex];
}
public boolean allowAutoCap() {
String lang = getInputLanguage();
if (lang.length() > 2) lang = lang.substring(0, 2);
return !InputLanguageSelection.NOCAPS_LANGUAGES.contains(lang);
}
public boolean allowDeadKeys() {
String lang = getInputLanguage();
if (lang.length() > 2) lang = lang.substring(0, 2);
return !InputLanguageSelection.NODEADKEY_LANGUAGES.contains(lang);
}
public boolean allowAutoSpace() {
String lang = getInputLanguage();
if (lang.length() > 2) lang = lang.substring(0, 2);
return !InputLanguageSelection.NOAUTOSPACE_LANGUAGES.contains(lang);
}
/**
* Returns the list of enabled language codes.
*/
public String[] getEnabledLanguages() {
return mSelectedLanguageArray;
}
/**
* Returns the currently selected input locale, or the display locale if no specific
* locale was selected for input.
* @return
*/
public Locale getInputLocale() {
Locale locale;
if (getLocaleCount() == 0) {
locale = mDefaultInputLocale;
} else {
locale = mLocales[mCurrentIndex];
}
LatinIME.sKeyboardSettings.inputLocale = (locale != null) ? locale : Locale.getDefault();
return locale;
}
/**
* Returns the next input locale in the list. Wraps around to the beginning of the
* list if we're at the end of the list.
* @return
*/
public Locale getNextInputLocale() {
if (getLocaleCount() == 0) return mDefaultInputLocale;
return mLocales[(mCurrentIndex + 1) % mLocales.length];
}
/**
* Sets the system locale (display UI) used for comparing with the input language.
* @param locale the locale of the system
*/
public void setSystemLocale(Locale locale) {
mSystemLocale = locale;
}
/**
* Returns the system locale.
* @return the system locale
*/
public Locale getSystemLocale() {
return mSystemLocale;
}
/**
* Returns the previous input locale in the list. Wraps around to the end of the
* list if we're at the beginning of the list.
* @return
*/
public Locale getPrevInputLocale() {
if (getLocaleCount() == 0) return mDefaultInputLocale;
return mLocales[(mCurrentIndex - 1 + mLocales.length) % mLocales.length];
}
public void reset() {
mCurrentIndex = 0;
mSelectedLanguages = "";
loadLocales(PreferenceManager.getDefaultSharedPreferences(mIme));
}
public void next() {
mCurrentIndex++;
if (mCurrentIndex >= mLocales.length) mCurrentIndex = 0; // Wrap around
}
public void prev() {
mCurrentIndex--;
if (mCurrentIndex < 0) mCurrentIndex = mLocales.length - 1; // Wrap around
}
public void persist() {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(mIme);
Editor editor = sp.edit();
editor.putString(LatinIME.PREF_INPUT_LANGUAGE, getInputLanguage());
SharedPreferencesCompat.apply(editor);
}
static String toTitleCase(String s) {
if (s.length() == 0) {
return s;
}
return Character.toUpperCase(s.charAt(0)) + s.substring(1);
}
}
| 11beeaosama-descrbvbnvbniption | java/src/org/pocketworkstation/pckeyboard/LanguageSwitcher.java | Java | asf20 | 7,332 |
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import java.io.InputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.Channels;
import java.util.Arrays;
import android.content.Context;
import android.util.Log;
/**
* Implements a static, compacted, binary dictionary of standard words.
*/
public class BinaryDictionary extends Dictionary {
/**
* There is difference between what java and native code can handle.
* This value should only be used in BinaryDictionary.java
* It is necessary to keep it at this value because some languages e.g. German have
* really long words.
*/
protected static final int MAX_WORD_LENGTH = 48;
private static final String TAG = "BinaryDictionary";
private static final int MAX_ALTERNATIVES = 16;
private static final int MAX_WORDS = 18;
private static final int MAX_BIGRAMS = 60;
private static final int TYPED_LETTER_MULTIPLIER = 2;
private static final boolean ENABLE_MISSED_CHARACTERS = true;
private int mDicTypeId;
private int mNativeDict;
private int mDictLength;
private int[] mInputCodes = new int[MAX_WORD_LENGTH * MAX_ALTERNATIVES];
private char[] mOutputChars = new char[MAX_WORD_LENGTH * MAX_WORDS];
private char[] mOutputChars_bigrams = new char[MAX_WORD_LENGTH * MAX_BIGRAMS];
private int[] mFrequencies = new int[MAX_WORDS];
private int[] mFrequencies_bigrams = new int[MAX_BIGRAMS];
// Keep a reference to the native dict direct buffer in Java to avoid
// unexpected deallocation of the direct buffer.
private ByteBuffer mNativeDictDirectBuffer;
static {
try {
System.loadLibrary("jni_pckeyboard");
Log.i("PCKeyboard", "loaded jni_pckeyboard");
} catch (UnsatisfiedLinkError ule) {
Log.e("BinaryDictionary", "Could not load native library jni_pckeyboard");
}
}
/**
* Create a dictionary from a raw resource file
* @param context application context for reading resources
* @param resId the resource containing the raw binary dictionary
*/
public BinaryDictionary(Context context, int[] resId, int dicTypeId) {
if (resId != null && resId.length > 0 && resId[0] != 0) {
loadDictionary(context, resId);
}
mDicTypeId = dicTypeId;
}
/**
* Create a dictionary from input streams
* @param context application context for reading resources
* @param streams the resource streams containing the raw binary dictionary
*/
public BinaryDictionary(Context context, InputStream[] streams, int dicTypeId) {
if (streams != null && streams.length > 0) {
loadDictionary(streams);
}
mDicTypeId = dicTypeId;
}
/**
* Create a dictionary from a byte buffer. This is used for testing.
* @param context application context for reading resources
* @param byteBuffer a ByteBuffer containing the binary dictionary
*/
public BinaryDictionary(Context context, ByteBuffer byteBuffer, int dicTypeId) {
if (byteBuffer != null) {
if (byteBuffer.isDirect()) {
mNativeDictDirectBuffer = byteBuffer;
} else {
mNativeDictDirectBuffer = ByteBuffer.allocateDirect(byteBuffer.capacity());
byteBuffer.rewind();
mNativeDictDirectBuffer.put(byteBuffer);
}
mDictLength = byteBuffer.capacity();
mNativeDict = openNative(mNativeDictDirectBuffer,
TYPED_LETTER_MULTIPLIER, FULL_WORD_FREQ_MULTIPLIER, mDictLength);
}
mDicTypeId = dicTypeId;
}
private native int openNative(ByteBuffer bb, int typedLetterMultiplier,
int fullWordMultiplier, int dictSize);
private native void closeNative(int dict);
private native boolean isValidWordNative(int nativeData, char[] word, int wordLength);
private native int getSuggestionsNative(int dict, int[] inputCodes, int codesSize,
char[] outputChars, int[] frequencies, int maxWordLength, int maxWords,
int maxAlternatives, int skipPos, int[] nextLettersFrequencies, int nextLettersSize);
private native int getBigramsNative(int dict, char[] prevWord, int prevWordLength,
int[] inputCodes, int inputCodesLength, char[] outputChars, int[] frequencies,
int maxWordLength, int maxBigrams, int maxAlternatives);
private final void loadDictionary(InputStream[] is) {
try {
// merging separated dictionary into one if dictionary is separated
int total = 0;
for (int i = 0; i < is.length; i++) {
total += is[i].available();
}
mNativeDictDirectBuffer =
ByteBuffer.allocateDirect(total).order(ByteOrder.nativeOrder());
int got = 0;
for (int i = 0; i < is.length; i++) {
got += Channels.newChannel(is[i]).read(mNativeDictDirectBuffer);
}
if (got != total) {
Log.e(TAG, "Read " + got + " bytes, expected " + total);
} else {
mNativeDict = openNative(mNativeDictDirectBuffer,
TYPED_LETTER_MULTIPLIER, FULL_WORD_FREQ_MULTIPLIER, total);
mDictLength = total;
}
if (mDictLength > 10000) Log.i("PCKeyboard", "Loaded dictionary, len=" + mDictLength);
} catch (IOException e) {
Log.w(TAG, "No available memory for binary dictionary");
} catch (UnsatisfiedLinkError e) {
Log.w(TAG, "Failed to load native dictionary", e);
} finally {
try {
if (is != null) {
for (int i = 0; i < is.length; i++) {
is[i].close();
}
}
} catch (IOException e) {
Log.w(TAG, "Failed to close input stream");
}
}
}
private final void loadDictionary(Context context, int[] resId) {
InputStream[] is = null;
is = new InputStream[resId.length];
for (int i = 0; i < resId.length; i++) {
is[i] = context.getResources().openRawResource(resId[i]);
}
loadDictionary(is);
}
@Override
public void getBigrams(final WordComposer codes, final CharSequence previousWord,
final WordCallback callback, int[] nextLettersFrequencies) {
char[] chars = previousWord.toString().toCharArray();
Arrays.fill(mOutputChars_bigrams, (char) 0);
Arrays.fill(mFrequencies_bigrams, 0);
int codesSize = codes.size();
Arrays.fill(mInputCodes, -1);
int[] alternatives = codes.getCodesAt(0);
System.arraycopy(alternatives, 0, mInputCodes, 0,
Math.min(alternatives.length, MAX_ALTERNATIVES));
int count = getBigramsNative(mNativeDict, chars, chars.length, mInputCodes, codesSize,
mOutputChars_bigrams, mFrequencies_bigrams, MAX_WORD_LENGTH, MAX_BIGRAMS,
MAX_ALTERNATIVES);
for (int j = 0; j < count; j++) {
if (mFrequencies_bigrams[j] < 1) break;
int start = j * MAX_WORD_LENGTH;
int len = 0;
while (mOutputChars_bigrams[start + len] != 0) {
len++;
}
if (len > 0) {
callback.addWord(mOutputChars_bigrams, start, len, mFrequencies_bigrams[j],
mDicTypeId, DataType.BIGRAM);
}
}
}
@Override
public void getWords(final WordComposer codes, final WordCallback callback,
int[] nextLettersFrequencies) {
final int codesSize = codes.size();
// Won't deal with really long words.
if (codesSize > MAX_WORD_LENGTH - 1) return;
Arrays.fill(mInputCodes, -1);
for (int i = 0; i < codesSize; i++) {
int[] alternatives = codes.getCodesAt(i);
System.arraycopy(alternatives, 0, mInputCodes, i * MAX_ALTERNATIVES,
Math.min(alternatives.length, MAX_ALTERNATIVES));
}
Arrays.fill(mOutputChars, (char) 0);
Arrays.fill(mFrequencies, 0);
if (mNativeDict == 0)
return;
int count = getSuggestionsNative(mNativeDict, mInputCodes, codesSize,
mOutputChars, mFrequencies,
MAX_WORD_LENGTH, MAX_WORDS, MAX_ALTERNATIVES, -1,
nextLettersFrequencies,
nextLettersFrequencies != null ? nextLettersFrequencies.length : 0);
// If there aren't sufficient suggestions, search for words by allowing wild cards at
// the different character positions. This feature is not ready for prime-time as we need
// to figure out the best ranking for such words compared to proximity corrections and
// completions.
if (ENABLE_MISSED_CHARACTERS && count < 5) {
for (int skip = 0; skip < codesSize; skip++) {
int tempCount = getSuggestionsNative(mNativeDict, mInputCodes, codesSize,
mOutputChars, mFrequencies,
MAX_WORD_LENGTH, MAX_WORDS, MAX_ALTERNATIVES, skip,
null, 0);
count = Math.max(count, tempCount);
if (tempCount > 0) break;
}
}
for (int j = 0; j < count; j++) {
if (mFrequencies[j] < 1) break;
int start = j * MAX_WORD_LENGTH;
int len = 0;
while (mOutputChars[start + len] != 0) {
len++;
}
if (len > 0) {
callback.addWord(mOutputChars, start, len, mFrequencies[j], mDicTypeId,
DataType.UNIGRAM);
}
}
}
@Override
public boolean isValidWord(CharSequence word) {
if (word == null || mNativeDict == 0) return false;
char[] chars = word.toString().toCharArray();
return isValidWordNative(mNativeDict, chars, chars.length);
}
public int getSize() {
return mDictLength; // This value is initialized on the call to openNative()
}
@Override
public synchronized void close() {
if (mNativeDict != 0) {
closeNative(mNativeDict);
mNativeDict = 0;
}
}
@Override
protected void finalize() throws Throwable {
close();
super.finalize();
}
}
| 11beeaosama-descrbvbnvbniption | java/src/org/pocketworkstation/pckeyboard/BinaryDictionary.java | Java | asf20 | 11,174 |
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import android.content.Context;
import org.pocketworkstation.pckeyboard.Keyboard.Key;
import android.text.format.DateFormat;
import android.util.Log;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
public class TextEntryState {
private static final boolean DBG = false;
private static final String TAG = "TextEntryState";
private static boolean LOGGING = false;
private static int sBackspaceCount = 0;
private static int sAutoSuggestCount = 0;
private static int sAutoSuggestUndoneCount = 0;
private static int sManualSuggestCount = 0;
private static int sWordNotInDictionaryCount = 0;
private static int sSessionCount = 0;
private static int sTypedChars;
private static int sActualChars;
public enum State {
UNKNOWN,
START,
IN_WORD,
ACCEPTED_DEFAULT,
PICKED_SUGGESTION,
PUNCTUATION_AFTER_WORD,
PUNCTUATION_AFTER_ACCEPTED,
SPACE_AFTER_ACCEPTED,
SPACE_AFTER_PICKED,
UNDO_COMMIT,
CORRECTING,
PICKED_CORRECTION;
}
private static State sState = State.UNKNOWN;
private static FileOutputStream sKeyLocationFile;
private static FileOutputStream sUserActionFile;
public static void newSession(Context context) {
sSessionCount++;
sAutoSuggestCount = 0;
sBackspaceCount = 0;
sAutoSuggestUndoneCount = 0;
sManualSuggestCount = 0;
sWordNotInDictionaryCount = 0;
sTypedChars = 0;
sActualChars = 0;
sState = State.START;
if (LOGGING) {
try {
sKeyLocationFile = context.openFileOutput("key.txt", Context.MODE_APPEND);
sUserActionFile = context.openFileOutput("action.txt", Context.MODE_APPEND);
} catch (IOException ioe) {
Log.e("TextEntryState", "Couldn't open file for output: " + ioe);
}
}
}
public static void endSession() {
if (sKeyLocationFile == null) {
return;
}
try {
sKeyLocationFile.close();
// Write to log file
// Write timestamp, settings,
String out = DateFormat.format("MM:dd hh:mm:ss", Calendar.getInstance().getTime())
.toString()
+ " BS: " + sBackspaceCount
+ " auto: " + sAutoSuggestCount
+ " manual: " + sManualSuggestCount
+ " typed: " + sWordNotInDictionaryCount
+ " undone: " + sAutoSuggestUndoneCount
+ " saved: " + ((float) (sActualChars - sTypedChars) / sActualChars)
+ "\n";
sUserActionFile.write(out.getBytes());
sUserActionFile.close();
sKeyLocationFile = null;
sUserActionFile = null;
} catch (IOException ioe) {
}
}
public static void acceptedDefault(CharSequence typedWord, CharSequence actualWord) {
if (typedWord == null) return;
if (!typedWord.equals(actualWord)) {
sAutoSuggestCount++;
}
sTypedChars += typedWord.length();
sActualChars += actualWord.length();
sState = State.ACCEPTED_DEFAULT;
LatinImeLogger.logOnAutoSuggestion(typedWord.toString(), actualWord.toString());
displayState();
}
// State.ACCEPTED_DEFAULT will be changed to other sub-states
// (see "case ACCEPTED_DEFAULT" in typedCharacter() below),
// and should be restored back to State.ACCEPTED_DEFAULT after processing for each sub-state.
public static void backToAcceptedDefault(CharSequence typedWord) {
if (typedWord == null) return;
switch (sState) {
case SPACE_AFTER_ACCEPTED:
case PUNCTUATION_AFTER_ACCEPTED:
case IN_WORD:
sState = State.ACCEPTED_DEFAULT;
break;
}
displayState();
}
public static void manualTyped(CharSequence typedWord) {
sState = State.START;
displayState();
}
public static void acceptedTyped(CharSequence typedWord) {
sWordNotInDictionaryCount++;
sState = State.PICKED_SUGGESTION;
displayState();
}
public static void acceptedSuggestion(CharSequence typedWord, CharSequence actualWord) {
sManualSuggestCount++;
State oldState = sState;
if (typedWord.equals(actualWord)) {
acceptedTyped(typedWord);
}
if (oldState == State.CORRECTING || oldState == State.PICKED_CORRECTION) {
sState = State.PICKED_CORRECTION;
} else {
sState = State.PICKED_SUGGESTION;
}
displayState();
}
public static void selectedForCorrection() {
sState = State.CORRECTING;
displayState();
}
public static void typedCharacter(char c, boolean isSeparator) {
boolean isSpace = c == ' ';
switch (sState) {
case IN_WORD:
if (isSpace || isSeparator) {
sState = State.START;
} else {
// State hasn't changed.
}
break;
case ACCEPTED_DEFAULT:
case SPACE_AFTER_PICKED:
if (isSpace) {
sState = State.SPACE_AFTER_ACCEPTED;
} else if (isSeparator) {
sState = State.PUNCTUATION_AFTER_ACCEPTED;
} else {
sState = State.IN_WORD;
}
break;
case PICKED_SUGGESTION:
case PICKED_CORRECTION:
if (isSpace) {
sState = State.SPACE_AFTER_PICKED;
} else if (isSeparator) {
// Swap
sState = State.PUNCTUATION_AFTER_ACCEPTED;
} else {
sState = State.IN_WORD;
}
break;
case START:
case UNKNOWN:
case SPACE_AFTER_ACCEPTED:
case PUNCTUATION_AFTER_ACCEPTED:
case PUNCTUATION_AFTER_WORD:
if (!isSpace && !isSeparator) {
sState = State.IN_WORD;
} else {
sState = State.START;
}
break;
case UNDO_COMMIT:
if (isSpace || isSeparator) {
sState = State.ACCEPTED_DEFAULT;
} else {
sState = State.IN_WORD;
}
break;
case CORRECTING:
sState = State.START;
break;
}
displayState();
}
public static void backspace() {
if (sState == State.ACCEPTED_DEFAULT) {
sState = State.UNDO_COMMIT;
sAutoSuggestUndoneCount++;
LatinImeLogger.logOnAutoSuggestionCanceled();
} else if (sState == State.UNDO_COMMIT) {
sState = State.IN_WORD;
}
sBackspaceCount++;
displayState();
}
public static void reset() {
sState = State.START;
displayState();
}
public static State getState() {
if (DBG) {
Log.d(TAG, "Returning state = " + sState);
}
return sState;
}
public static boolean isCorrecting() {
return sState == State.CORRECTING || sState == State.PICKED_CORRECTION;
}
public static void keyPressedAt(Key key, int x, int y) {
if (LOGGING && sKeyLocationFile != null && key.codes[0] >= 32) {
String out =
"KEY: " + (char) key.codes[0]
+ " X: " + x
+ " Y: " + y
+ " MX: " + (key.x + key.width / 2)
+ " MY: " + (key.y + key.height / 2)
+ "\n";
try {
sKeyLocationFile.write(out.getBytes());
} catch (IOException ioe) {
// TODO: May run out of space
}
}
}
private static void displayState() {
if (DBG) {
//Log.w(TAG, "State = " + sState, new Throwable());
Log.i(TAG, "State = " + sState);
}
}
}
| 11beeaosama-descrbvbnvbniption | java/src/org/pocketworkstation/pckeyboard/TextEntryState.java | Java | asf20 | 9,061 |
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import java.util.ArrayList;
/**
* A place to store the currently composing word with information such as adjacent key codes as well
*/
public class WordComposer {
/**
* The list of unicode values for each keystroke (including surrounding keys)
*/
private final ArrayList<int[]> mCodes;
/**
* The word chosen from the candidate list, until it is committed.
*/
private String mPreferredWord;
private final StringBuilder mTypedWord;
private int mCapsCount;
private boolean mAutoCapitalized;
/**
* Whether the user chose to capitalize the first char of the word.
*/
private boolean mIsFirstCharCapitalized;
public WordComposer() {
mCodes = new ArrayList<int[]>(12);
mTypedWord = new StringBuilder(20);
}
WordComposer(WordComposer copy) {
mCodes = new ArrayList<int[]>(copy.mCodes);
mPreferredWord = copy.mPreferredWord;
mTypedWord = new StringBuilder(copy.mTypedWord);
mCapsCount = copy.mCapsCount;
mAutoCapitalized = copy.mAutoCapitalized;
mIsFirstCharCapitalized = copy.mIsFirstCharCapitalized;
}
/**
* Clear out the keys registered so far.
*/
public void reset() {
mCodes.clear();
mIsFirstCharCapitalized = false;
mPreferredWord = null;
mTypedWord.setLength(0);
mCapsCount = 0;
}
/**
* Number of keystrokes in the composing word.
* @return the number of keystrokes
*/
public int size() {
return mCodes.size();
}
/**
* Returns the codes at a particular position in the word.
* @param index the position in the word
* @return the unicode for the pressed and surrounding keys
*/
public int[] getCodesAt(int index) {
return mCodes.get(index);
}
/**
* Add a new keystroke, with codes[0] containing the pressed key's unicode and the rest of
* the array containing unicode for adjacent keys, sorted by reducing probability/proximity.
* @param codes the array of unicode values
*/
public void add(int primaryCode, int[] codes) {
mTypedWord.append((char) primaryCode);
correctPrimaryJuxtapos(primaryCode, codes);
correctCodesCase(codes);
mCodes.add(codes);
if (Character.isUpperCase((char) primaryCode)) mCapsCount++;
}
/**
* Swaps the first and second values in the codes array if the primary code is not the first
* value in the array but the second. This happens when the preferred key is not the key that
* the user released the finger on.
* @param primaryCode the preferred character
* @param codes array of codes based on distance from touch point
*/
private void correctPrimaryJuxtapos(int primaryCode, int[] codes) {
if (codes.length < 2) return;
if (codes[0] > 0 && codes[1] > 0 && codes[0] != primaryCode && codes[1] == primaryCode) {
codes[1] = codes[0];
codes[0] = primaryCode;
}
}
// Prediction expects the keyKodes to be lowercase
private void correctCodesCase(int[] codes) {
for (int i = 0; i < codes.length; ++i) {
int code = codes[i];
if (code > 0) codes[i] = Character.toLowerCase(code);
}
}
/**
* Delete the last keystroke as a result of hitting backspace.
*/
public void deleteLast() {
final int codesSize = mCodes.size();
if (codesSize > 0) {
mCodes.remove(codesSize - 1);
final int lastPos = mTypedWord.length() - 1;
char last = mTypedWord.charAt(lastPos);
mTypedWord.deleteCharAt(lastPos);
if (Character.isUpperCase(last)) mCapsCount--;
}
}
/**
* Returns the word as it was typed, without any correction applied.
* @return the word that was typed so far
*/
public CharSequence getTypedWord() {
int wordSize = mCodes.size();
if (wordSize == 0) {
return null;
}
return mTypedWord;
}
public void setFirstCharCapitalized(boolean capitalized) {
mIsFirstCharCapitalized = capitalized;
}
/**
* Whether or not the user typed a capital letter as the first letter in the word
* @return capitalization preference
*/
public boolean isFirstCharCapitalized() {
return mIsFirstCharCapitalized;
}
/**
* Whether or not all of the user typed chars are upper case
* @return true if all user typed chars are upper case, false otherwise
*/
public boolean isAllUpperCase() {
return (mCapsCount > 0) && (mCapsCount == size());
}
/**
* Stores the user's selected word, before it is actually committed to the text field.
* @param preferred
*/
public void setPreferredWord(String preferred) {
mPreferredWord = preferred;
}
/**
* Return the word chosen by the user, or the typed word if no other word was chosen.
* @return the preferred word
*/
public CharSequence getPreferredWord() {
return mPreferredWord != null ? mPreferredWord : getTypedWord();
}
/**
* Returns true if more than one character is upper case, otherwise returns false.
*/
public boolean isMostlyCaps() {
return mCapsCount > 1;
}
/**
* Saves the reason why the word is capitalized - whether it was automatic or
* due to the user hitting shift in the middle of a sentence.
* @param auto whether it was an automatic capitalization due to start of sentence
*/
public void setAutoCapitalized(boolean auto) {
mAutoCapitalized = auto;
}
/**
* Returns whether the word was automatically capitalized.
* @return whether the word was automatically capitalized
*/
public boolean isAutoCapitalized() {
return mAutoCapitalized;
}
}
| 11beeaosama-descrbvbnvbniption | java/src/org/pocketworkstation/pckeyboard/WordComposer.java | Java | asf20 | 6,622 |
package org.pocketworkstation.pckeyboard;
import android.content.Context;
import android.util.AttributeSet;
public class VibratePreference extends SeekBarPreferenceString {
public VibratePreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public void onChange(float val) {
LatinIME ime = LatinIME.sInstance;
if (ime != null) ime.vibrate((int) val);
}
} | 11beeaosama-descrbvbnvbniption | java/src/org/pocketworkstation/pckeyboard/VibratePreference.java | Java | asf20 | 436 |
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.pocketworkstation.pckeyboard;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.provider.UserDictionary.Words;
import android.util.Log;
public class UserDictionary extends ExpandableDictionary {
private static final String[] PROJECTION = {
Words._ID,
Words.WORD,
Words.FREQUENCY
};
private static final int INDEX_WORD = 1;
private static final int INDEX_FREQUENCY = 2;
private static final String TAG = "HK/UserDictionary";
private ContentObserver mObserver;
private String mLocale;
public UserDictionary(Context context, String locale) {
super(context, Suggest.DIC_USER);
mLocale = locale;
// Perform a managed query. The Activity will handle closing and requerying the cursor
// when needed.
ContentResolver cres = context.getContentResolver();
cres.registerContentObserver(Words.CONTENT_URI, true, mObserver = new ContentObserver(null) {
@Override
public void onChange(boolean self) {
setRequiresReload(true);
}
});
loadDictionary();
}
@Override
public synchronized void close() {
if (mObserver != null) {
getContext().getContentResolver().unregisterContentObserver(mObserver);
mObserver = null;
}
super.close();
}
@Override
public void loadDictionaryAsync() {
Cursor cursor = getContext().getContentResolver()
.query(Words.CONTENT_URI, PROJECTION, "(locale IS NULL) or (locale=?)",
new String[] { mLocale }, null);
addWords(cursor);
}
/**
* Adds a word to the dictionary and makes it persistent.
* @param word the word to add. If the word is capitalized, then the dictionary will
* recognize it as a capitalized word when searched.
* @param frequency the frequency of occurrence of the word. A frequency of 255 is considered
* the highest.
* @TODO use a higher or float range for frequency
*/
@Override
public synchronized void addWord(String word, int frequency) {
// Force load the dictionary here synchronously
if (getRequiresReload()) loadDictionaryAsync();
// Safeguard against adding long words. Can cause stack overflow.
if (word.length() >= getMaxWordLength()) return;
super.addWord(word, frequency);
// Update the user dictionary provider
final ContentValues values = new ContentValues(5);
values.put(Words.WORD, word);
values.put(Words.FREQUENCY, frequency);
values.put(Words.LOCALE, mLocale);
values.put(Words.APP_ID, 0);
final ContentResolver contentResolver = getContext().getContentResolver();
new Thread("addWord") {
public void run() {
contentResolver.insert(Words.CONTENT_URI, values);
}
}.start();
// In case the above does a synchronous callback of the change observer
setRequiresReload(false);
}
@Override
public synchronized void getWords(final WordComposer codes, final WordCallback callback,
int[] nextLettersFrequencies) {
super.getWords(codes, callback, nextLettersFrequencies);
}
@Override
public synchronized boolean isValidWord(CharSequence word) {
return super.isValidWord(word);
}
private void addWords(Cursor cursor) {
if (cursor == null) {
Log.w(TAG, "Unexpected null cursor in addWords()");
return;
}
clearDictionary();
final int maxWordLength = getMaxWordLength();
if (cursor.moveToFirst()) {
while (!cursor.isAfterLast()) {
String word = cursor.getString(INDEX_WORD);
int frequency = cursor.getInt(INDEX_FREQUENCY);
// Safeguard against adding really long words. Stack may overflow due
// to recursion
if (word.length() < maxWordLength) {
super.addWord(word, frequency);
}
cursor.moveToNext();
}
}
cursor.close();
}
}
| 11beeaosama-descrbvbnvbniption | java/src/org/pocketworkstation/pckeyboard/UserDictionary.java | Java | asf20 | 4,998 |
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import android.app.backup.BackupManager;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceActivity;
public class PrefScreenActions extends PreferenceActivity
implements SharedPreferences.OnSharedPreferenceChangeListener {
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
addPreferencesFromResource(R.xml.prefs_actions);
SharedPreferences prefs = getPreferenceManager().getSharedPreferences();
prefs.registerOnSharedPreferenceChangeListener(this);
}
@Override
protected void onDestroy() {
getPreferenceManager().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(
this);
super.onDestroy();
}
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
(new BackupManager(this)).dataChanged();
}
}
| 11beeaosama-descrbvbnvbniption | java/src/org/pocketworkstation/pckeyboard/PrefScreenActions.java | Java | asf20 | 1,584 |
package org.pocketworkstation.pckeyboard;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.inputmethod.InputMethodManager;
public class NotificationReceiver extends BroadcastReceiver {
static final String TAG = "PCKeyboard/Notification";
private LatinIME mIME;
NotificationReceiver(LatinIME ime) {
super();
mIME = ime;
Log.i(TAG, "NotificationReceiver created, ime=" + mIME);
}
@Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "NotificationReceiver.onReceive called");
InputMethodManager imm = (InputMethodManager)
context.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.showSoftInputFromInputMethod(mIME.mToken, InputMethodManager.SHOW_FORCED);
}
}
}
| 11beeaosama-descrbvbnvbniption | java/src/org/pocketworkstation/pckeyboard/NotificationReceiver.java | Java | asf20 | 856 |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.PreferenceActivity;
import android.util.Log;
public class LatinIMEDebugSettings extends PreferenceActivity
implements SharedPreferences.OnSharedPreferenceChangeListener {
private static final String TAG = "LatinIMEDebugSettings";
private static final String DEBUG_MODE_KEY = "debug_mode";
private CheckBoxPreference mDebugMode;
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
addPreferencesFromResource(R.xml.prefs_for_debug);
SharedPreferences prefs = getPreferenceManager().getSharedPreferences();
prefs.registerOnSharedPreferenceChangeListener(this);
mDebugMode = (CheckBoxPreference) findPreference(DEBUG_MODE_KEY);
updateDebugMode();
}
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
if (key.equals(DEBUG_MODE_KEY)) {
if (mDebugMode != null) {
mDebugMode.setChecked(prefs.getBoolean(DEBUG_MODE_KEY, false));
updateDebugMode();
}
}
}
private void updateDebugMode() {
if (mDebugMode == null) {
return;
}
boolean isDebugMode = mDebugMode.isChecked();
String version = "";
try {
PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), 0);
version = "Version " + info.versionName;
} catch (NameNotFoundException e) {
Log.e(TAG, "Could not find version info.");
}
if (!isDebugMode) {
mDebugMode.setTitle(version);
mDebugMode.setSummary("");
} else {
mDebugMode.setTitle(getResources().getString(R.string.prefs_debug_mode));
mDebugMode.setSummary(version);
}
}
}
| 11beeaosama-descrbvbnvbniption | java/src/org/pocketworkstation/pckeyboard/LatinIMEDebugSettings.java | Java | asf20 | 2,686 |
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import android.app.backup.BackupManager;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.PreferenceActivity;
public class PrefScreenFeedback extends PreferenceActivity
implements SharedPreferences.OnSharedPreferenceChangeListener {
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
addPreferencesFromResource(R.xml.prefs_feedback);
SharedPreferences prefs = getPreferenceManager().getSharedPreferences();
prefs.registerOnSharedPreferenceChangeListener(this);
}
@Override
protected void onDestroy() {
getPreferenceManager().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(
this);
super.onDestroy();
}
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
(new BackupManager(this)).dataChanged();
}
@Override
protected void onResume() {
super.onResume();
}
}
| 11beeaosama-descrbvbnvbniption | java/src/org/pocketworkstation/pckeyboard/PrefScreenFeedback.java | Java | asf20 | 1,711 |
package org.pocketworkstation.pckeyboard;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.util.Log;
/**
* Global current settings for the keyboard.
*
* <p>
* Yes, globals are evil. But the persisted shared preferences are global data
* by definition, and trying to hide this by propagating the current manually
* just adds a lot of complication. This is especially annoying due to Views
* getting constructed in a way that doesn't support adding additional
* constructor arguments, requiring post-construction method calls, which is
* error-prone and fragile.
*
* <p>
* The comments below indicate which class is responsible for updating the
* value, and for recreating keyboards or views as necessary. Other classes
* MUST treat the fields as read-only values, and MUST NOT attempt to save
* these values or results derived from them across re-initializations.
*
* @author klaus.weidner@gmail.com
*/
public final class GlobalKeyboardSettings {
protected static final String TAG = "HK/Globals";
/* Simple prefs updated by this class */
//
// Read by Keyboard
public int popupKeyboardFlags = 0x1;
public float topRowScale = 1.0f;
//
// Read by LatinKeyboardView
public boolean showTouchPos = false;
//
// Read by LatinIME
public String suggestedPunctuation = "!?,.";
public int keyboardModePortrait = 0;
public int keyboardModeLandscape = 2;
public boolean compactModeEnabled = false;
public int chordingCtrlKey = 0;
public int chordingAltKey = 0;
public int chordingMetaKey = 0;
public float keyClickVolume = 0.0f;
public int keyClickMethod = 0;
public boolean capsLock = true;
public boolean shiftLockModifiers = false;
//
// Read by LatinKeyboardBaseView
public float labelScalePref = 1.0f;
//
// Read by CandidateView
public float candidateScalePref = 1.0f;
//
// Read by PointerTracker
public int sendSlideKeys = 0;
/* Updated by LatinIME */
//
// Read by KeyboardSwitcher
public int keyboardMode = 0;
public boolean useExtension = false;
//
// Read by LatinKeyboardView and KeyboardSwitcher
public float keyboardHeightPercent = 40.0f; // percent of screen height
//
// Read by LatinKeyboardBaseView
public int hintMode = 0;
public int renderMode = 1;
//
// Read by PointerTracker
public int longpressTimeout = 400;
//
// Read by LatinIMESettings
// These are cached values for informational display, don't use for other purposes
public String editorPackageName;
public String editorFieldName;
public int editorFieldId;
public int editorInputType;
/* Updated by KeyboardSwitcher */
//
// Used by LatinKeyboardBaseView and LatinIME
/* Updated by LanguageSwitcher */
//
// Used by Keyboard and KeyboardSwitcher
public Locale inputLocale = Locale.getDefault();
// Auto pref implementation follows
private Map<String, BooleanPref> mBoolPrefs = new HashMap<String, BooleanPref>();
private Map<String, StringPref> mStringPrefs = new HashMap<String, StringPref>();
public static final int FLAG_PREF_NONE = 0;
public static final int FLAG_PREF_NEED_RELOAD = 0x1;
public static final int FLAG_PREF_NEW_PUNC_LIST = 0x2;
public static final int FLAG_PREF_RECREATE_INPUT_VIEW = 0x4;
public static final int FLAG_PREF_RESET_KEYBOARDS = 0x8;
public static final int FLAG_PREF_RESET_MODE_OVERRIDE = 0x10;
private int mCurrentFlags = 0;
private interface BooleanPref {
void set(boolean val);
boolean getDefault();
int getFlags();
}
private interface StringPref {
void set(String val);
String getDefault();
int getFlags();
}
public void initPrefs(SharedPreferences prefs, Resources resources) {
final Resources res = resources;
addBooleanPref("pref_compact_mode_enabled", new BooleanPref() {
public void set(boolean val) { compactModeEnabled = val; Log.i(TAG, "Setting compactModeEnabled to " + val); }
public boolean getDefault() { return res.getBoolean(R.bool.default_compact_mode_enabled); }
public int getFlags() { return FLAG_PREF_RESET_MODE_OVERRIDE; }
});
addStringPref("pref_keyboard_mode_portrait", new StringPref() {
public void set(String val) { keyboardModePortrait = Integer.valueOf(val); }
public String getDefault() { return res.getString(R.string.default_keyboard_mode_portrait); }
public int getFlags() { return FLAG_PREF_RESET_KEYBOARDS | FLAG_PREF_RESET_MODE_OVERRIDE; }
});
addStringPref("pref_keyboard_mode_landscape", new StringPref() {
public void set(String val) { keyboardModeLandscape = Integer.valueOf(val); }
public String getDefault() { return res.getString(R.string.default_keyboard_mode_landscape); }
public int getFlags() { return FLAG_PREF_RESET_KEYBOARDS | FLAG_PREF_RESET_MODE_OVERRIDE; }
});
addStringPref("pref_slide_keys_int", new StringPref() {
public void set(String val) { sendSlideKeys = Integer.valueOf(val); }
public String getDefault() { return "0"; }
public int getFlags() { return FLAG_PREF_NONE; }
});
addBooleanPref("pref_touch_pos", new BooleanPref() {
public void set(boolean val) { showTouchPos = val; }
public boolean getDefault() { return false; }
public int getFlags() { return FLAG_PREF_NONE; }
});
addStringPref("pref_popup_content", new StringPref() {
public void set(String val) { popupKeyboardFlags = Integer.valueOf(val); }
public String getDefault() { return res.getString(R.string.default_popup_content); }
public int getFlags() { return FLAG_PREF_RESET_KEYBOARDS; }
});
addStringPref("pref_suggested_punctuation", new StringPref() {
public void set(String val) { suggestedPunctuation = val; }
public String getDefault() { return res.getString(R.string.suggested_punctuations_default); }
public int getFlags() { return FLAG_PREF_NEW_PUNC_LIST; }
});
addStringPref("pref_label_scale", new StringPref() {
public void set(String val) { labelScalePref = Float.valueOf(val); }
public String getDefault() { return "1.0"; }
public int getFlags() { return FLAG_PREF_RECREATE_INPUT_VIEW; }
});
addStringPref("pref_candidate_scale", new StringPref() {
public void set(String val) { candidateScalePref = Float.valueOf(val); }
public String getDefault() { return "1.0"; }
public int getFlags() { return FLAG_PREF_RESET_KEYBOARDS; }
});
addStringPref("pref_top_row_scale", new StringPref() {
public void set(String val) { topRowScale = Float.valueOf(val); }
public String getDefault() { return "1.0"; }
public int getFlags() { return FLAG_PREF_RESET_KEYBOARDS; }
});
addStringPref("pref_chording_ctrl_key", new StringPref() {
public void set(String val) { chordingCtrlKey = Integer.valueOf(val); }
public String getDefault() { return res.getString(R.string.default_chording_ctrl_key); }
public int getFlags() { return FLAG_PREF_RESET_KEYBOARDS; }
});
addStringPref("pref_chording_alt_key", new StringPref() {
public void set(String val) { chordingAltKey = Integer.valueOf(val); }
public String getDefault() { return res.getString(R.string.default_chording_alt_key); }
public int getFlags() { return FLAG_PREF_RESET_KEYBOARDS; }
});
addStringPref("pref_chording_meta_key", new StringPref() {
public void set(String val) { chordingMetaKey = Integer.valueOf(val); }
public String getDefault() { return res.getString(R.string.default_chording_meta_key); }
public int getFlags() { return FLAG_PREF_RESET_KEYBOARDS; }
});
addStringPref("pref_click_volume", new StringPref() {
public void set(String val) { keyClickVolume = Float.valueOf(val); }
public String getDefault() { return res.getString(R.string.default_click_volume); }
public int getFlags() { return FLAG_PREF_NONE; }
});
addStringPref("pref_click_method", new StringPref() {
public void set(String val) { keyClickMethod = Integer.valueOf(val); }
public String getDefault() { return res.getString(R.string.default_click_method); }
public int getFlags() { return FLAG_PREF_NONE; }
});
addBooleanPref("pref_caps_lock", new BooleanPref() {
public void set(boolean val) { capsLock = val; }
public boolean getDefault() { return res.getBoolean(R.bool.default_caps_lock); }
public int getFlags() { return FLAG_PREF_NONE; }
});
addBooleanPref("pref_shift_lock_modifiers", new BooleanPref() {
public void set(boolean val) { shiftLockModifiers = val; }
public boolean getDefault() { return res.getBoolean(R.bool.default_shift_lock_modifiers); }
public int getFlags() { return FLAG_PREF_NONE; }
});
// Set initial values
for (String key : mBoolPrefs.keySet()) {
BooleanPref pref = mBoolPrefs.get(key);
pref.set(prefs.getBoolean(key, pref.getDefault()));
}
for (String key : mStringPrefs.keySet()) {
StringPref pref = mStringPrefs.get(key);
pref.set(prefs.getString(key, pref.getDefault()));
}
}
public void sharedPreferenceChanged(SharedPreferences prefs, String key) {
boolean found = false;
mCurrentFlags = FLAG_PREF_NONE;
BooleanPref bPref = mBoolPrefs.get(key);
if (bPref != null) {
found = true;
bPref.set(prefs.getBoolean(key, bPref.getDefault()));
mCurrentFlags |= bPref.getFlags();
}
StringPref sPref = mStringPrefs.get(key);
if (sPref != null) {
found = true;
sPref.set(prefs.getString(key, sPref.getDefault()));
mCurrentFlags |= sPref.getFlags();
}
//if (!found) Log.i(TAG, "sharedPreferenceChanged: unhandled key=" + key);
}
public boolean hasFlag(int flag) {
if ((mCurrentFlags & flag) != 0) {
mCurrentFlags &= ~flag;
return true;
}
return false;
}
public int unhandledFlags() {
return mCurrentFlags;
}
private void addBooleanPref(String key, BooleanPref setter) {
mBoolPrefs.put(key, setter);
}
private void addStringPref(String key, StringPref setter) {
mStringPrefs.put(key, setter);
}
}
| 11beeaosama-descrbvbnvbniption | java/src/org/pocketworkstation/pckeyboard/GlobalKeyboardSettings.java | Java | asf20 | 11,072 |
/*
* Copyright (C) 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import android.text.TextUtils;
import android.view.inputmethod.ExtractedText;
import android.view.inputmethod.ExtractedTextRequest;
import android.view.inputmethod.InputConnection;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.regex.Pattern;
/**
* Utility methods to deal with editing text through an InputConnection.
*/
public class EditingUtil {
/**
* Number of characters we want to look back in order to identify the previous word
*/
private static final int LOOKBACK_CHARACTER_NUM = 15;
// Cache Method pointers
private static boolean sMethodsInitialized;
private static Method sMethodGetSelectedText;
private static Method sMethodSetComposingRegion;
private EditingUtil() {};
/**
* Append newText to the text field represented by connection.
* The new text becomes selected.
*/
public static void appendText(InputConnection connection, String newText) {
if (connection == null) {
return;
}
// Commit the composing text
connection.finishComposingText();
// Add a space if the field already has text.
CharSequence charBeforeCursor = connection.getTextBeforeCursor(1, 0);
if (charBeforeCursor != null
&& !charBeforeCursor.equals(" ")
&& (charBeforeCursor.length() > 0)) {
newText = " " + newText;
}
connection.setComposingText(newText, 1);
}
private static int getCursorPosition(InputConnection connection) {
ExtractedText extracted = connection.getExtractedText(
new ExtractedTextRequest(), 0);
if (extracted == null) {
return -1;
}
return extracted.startOffset + extracted.selectionStart;
}
/**
* @param connection connection to the current text field.
* @param sep characters which may separate words
* @param range the range object to store the result into
* @return the word that surrounds the cursor, including up to one trailing
* separator. For example, if the field contains "he|llo world", where |
* represents the cursor, then "hello " will be returned.
*/
public static String getWordAtCursor(
InputConnection connection, String separators, Range range) {
Range r = getWordRangeAtCursor(connection, separators, range);
return (r == null) ? null : r.word;
}
/**
* Removes the word surrounding the cursor. Parameters are identical to
* getWordAtCursor.
*/
public static void deleteWordAtCursor(
InputConnection connection, String separators) {
Range range = getWordRangeAtCursor(connection, separators, null);
if (range == null) return;
connection.finishComposingText();
// Move cursor to beginning of word, to avoid crash when cursor is outside
// of valid range after deleting text.
int newCursor = getCursorPosition(connection) - range.charsBefore;
connection.setSelection(newCursor, newCursor);
connection.deleteSurroundingText(0, range.charsBefore + range.charsAfter);
}
/**
* Represents a range of text, relative to the current cursor position.
*/
public static class Range {
/** Characters before selection start */
public int charsBefore;
/**
* Characters after selection start, including one trailing word
* separator.
*/
public int charsAfter;
/** The actual characters that make up a word */
public String word;
public Range() {}
public Range(int charsBefore, int charsAfter, String word) {
if (charsBefore < 0 || charsAfter < 0) {
throw new IndexOutOfBoundsException();
}
this.charsBefore = charsBefore;
this.charsAfter = charsAfter;
this.word = word;
}
}
private static Range getWordRangeAtCursor(
InputConnection connection, String sep, Range range) {
if (connection == null || sep == null) {
return null;
}
CharSequence before = connection.getTextBeforeCursor(1000, 0);
CharSequence after = connection.getTextAfterCursor(1000, 0);
if (before == null || after == null) {
return null;
}
// Find first word separator before the cursor
int start = before.length();
while (start > 0 && !isWhitespace(before.charAt(start - 1), sep)) start--;
// Find last word separator after the cursor
int end = -1;
while (++end < after.length() && !isWhitespace(after.charAt(end), sep));
int cursor = getCursorPosition(connection);
if (start >= 0 && cursor + end <= after.length() + before.length()) {
String word = before.toString().substring(start, before.length())
+ after.toString().substring(0, end);
Range returnRange = range != null? range : new Range();
returnRange.charsBefore = before.length() - start;
returnRange.charsAfter = end;
returnRange.word = word;
return returnRange;
}
return null;
}
private static boolean isWhitespace(int code, String whitespace) {
return whitespace.contains(String.valueOf((char) code));
}
private static final Pattern spaceRegex = Pattern.compile("\\s+");
public static CharSequence getPreviousWord(InputConnection connection,
String sentenceSeperators) {
//TODO: Should fix this. This could be slow!
CharSequence prev = connection.getTextBeforeCursor(LOOKBACK_CHARACTER_NUM, 0);
if (prev == null) {
return null;
}
String[] w = spaceRegex.split(prev);
if (w.length >= 2 && w[w.length-2].length() > 0) {
char lastChar = w[w.length-2].charAt(w[w.length-2].length() -1);
if (sentenceSeperators.contains(String.valueOf(lastChar))) {
return null;
}
return w[w.length-2];
} else {
return null;
}
}
public static class SelectedWord {
public int start;
public int end;
public CharSequence word;
}
/**
* Takes a character sequence with a single character and checks if the character occurs
* in a list of word separators or is empty.
* @param singleChar A CharSequence with null, zero or one character
* @param wordSeparators A String containing the word separators
* @return true if the character is at a word boundary, false otherwise
*/
private static boolean isWordBoundary(CharSequence singleChar, String wordSeparators) {
return TextUtils.isEmpty(singleChar) || wordSeparators.contains(singleChar);
}
/**
* Checks if the cursor is inside a word or the current selection is a whole word.
* @param ic the InputConnection for accessing the text field
* @param selStart the start position of the selection within the text field
* @param selEnd the end position of the selection within the text field. This could be
* the same as selStart, if there's no selection.
* @param wordSeparators the word separator characters for the current language
* @return an object containing the text and coordinates of the selected/touching word,
* null if the selection/cursor is not marking a whole word.
*/
public static SelectedWord getWordAtCursorOrSelection(final InputConnection ic,
int selStart, int selEnd, String wordSeparators) {
if (selStart == selEnd) {
// There is just a cursor, so get the word at the cursor
EditingUtil.Range range = new EditingUtil.Range();
CharSequence touching = getWordAtCursor(ic, wordSeparators, range);
if (!TextUtils.isEmpty(touching)) {
SelectedWord selWord = new SelectedWord();
selWord.word = touching;
selWord.start = selStart - range.charsBefore;
selWord.end = selEnd + range.charsAfter;
return selWord;
}
} else {
// Is the previous character empty or a word separator? If not, return null.
CharSequence charsBefore = ic.getTextBeforeCursor(1, 0);
if (!isWordBoundary(charsBefore, wordSeparators)) {
return null;
}
// Is the next character empty or a word separator? If not, return null.
CharSequence charsAfter = ic.getTextAfterCursor(1, 0);
if (!isWordBoundary(charsAfter, wordSeparators)) {
return null;
}
// Extract the selection alone
CharSequence touching = getSelectedText(ic, selStart, selEnd);
if (TextUtils.isEmpty(touching)) return null;
// Is any part of the selection a separator? If so, return null.
final int length = touching.length();
for (int i = 0; i < length; i++) {
if (wordSeparators.contains(touching.subSequence(i, i + 1))) {
return null;
}
}
// Prepare the selected word
SelectedWord selWord = new SelectedWord();
selWord.start = selStart;
selWord.end = selEnd;
selWord.word = touching;
return selWord;
}
return null;
}
/**
* Cache method pointers for performance
*/
private static void initializeMethodsForReflection() {
try {
// These will either both exist or not, so no need for separate try/catch blocks.
// If other methods are added later, use separate try/catch blocks.
sMethodGetSelectedText = InputConnection.class.getMethod("getSelectedText", int.class);
sMethodSetComposingRegion = InputConnection.class.getMethod("setComposingRegion",
int.class, int.class);
} catch (NoSuchMethodException exc) {
// Ignore
}
sMethodsInitialized = true;
}
/**
* Returns the selected text between the selStart and selEnd positions.
*/
private static CharSequence getSelectedText(InputConnection ic, int selStart, int selEnd) {
// Use reflection, for backward compatibility
CharSequence result = null;
if (!sMethodsInitialized) {
initializeMethodsForReflection();
}
if (sMethodGetSelectedText != null) {
try {
result = (CharSequence) sMethodGetSelectedText.invoke(ic, 0);
return result;
} catch (InvocationTargetException exc) {
// Ignore
} catch (IllegalArgumentException e) {
// Ignore
} catch (IllegalAccessException e) {
// Ignore
}
}
// Reflection didn't work, try it the poor way, by moving the cursor to the start,
// getting the text after the cursor and moving the text back to selected mode.
// TODO: Verify that this works properly in conjunction with
// LatinIME#onUpdateSelection
ic.setSelection(selStart, selEnd);
result = ic.getTextAfterCursor(selEnd - selStart, 0);
ic.setSelection(selStart, selEnd);
return result;
}
/**
* Tries to set the text into composition mode if there is support for it in the framework.
*/
public static void underlineWord(InputConnection ic, SelectedWord word) {
// Use reflection, for backward compatibility
// If method not found, there's nothing we can do. It still works but just wont underline
// the word.
if (!sMethodsInitialized) {
initializeMethodsForReflection();
}
if (sMethodSetComposingRegion != null) {
try {
sMethodSetComposingRegion.invoke(ic, word.start, word.end);
} catch (InvocationTargetException exc) {
// Ignore
} catch (IllegalArgumentException e) {
// Ignore
} catch (IllegalAccessException e) {
// Ignore
}
}
}
}
| 11beeaosama-descrbvbnvbniption | java/src/org/pocketworkstation/pckeyboard/EditingUtil.java | Java | asf20 | 13,010 |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.pocketworkstation.pckeyboard;
import org.pocketworkstation.pckeyboard.Dictionary.DataType;
import android.content.Context;
import android.content.SharedPreferences;
import java.util.List;
public class LatinImeLogger implements SharedPreferences.OnSharedPreferenceChangeListener {
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
}
public static void init(Context context) {
}
public static void commit() {
}
public static void onDestroy() {
}
public static void logOnManualSuggestion(
String before, String after, int position, List<CharSequence> suggestions) {
}
public static void logOnAutoSuggestion(String before, String after) {
}
public static void logOnAutoSuggestionCanceled() {
}
public static void logOnDelete() {
}
public static void logOnInputChar() {
}
public static void logOnException(String metaData, Throwable e) {
}
public static void logOnWarning(String warning) {
}
public static void onStartSuggestion(CharSequence previousWords) {
}
public static void onAddSuggestedWord(String word, int typeId, DataType dataType) {
}
public static void onSetKeyboard(Keyboard kb) {
}
}
| 11beeaosama-descrbvbnvbniption | java/src/org/pocketworkstation/pckeyboard/LatinImeLogger.java | Java | asf20 | 1,907 |
package org.pocketworkstation.pckeyboard;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
/**
* Variant of SeekBarPreference that stores values as string preferences.
*
* This is for compatibility with existing preferences, switching types
* leads to runtime errors when upgrading or downgrading.
*/
public class SeekBarPreferenceString extends SeekBarPreference {
private static Pattern FLOAT_RE = Pattern.compile("(\\d+\\.?\\d*).*");
public SeekBarPreferenceString(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
// Some saved preferences from old versions have " ms" or "%" suffix, remove that.
private float floatFromString(String pref) {
Matcher num = FLOAT_RE.matcher(pref);
if (!num.matches()) return 0.0f;
return Float.valueOf(num.group(1));
}
@Override
protected Float onGetDefaultValue(TypedArray a, int index) {
return floatFromString(a.getString(index));
}
@Override
protected void onSetInitialValue(boolean restorePersistedValue, Object defaultValue) {
if (restorePersistedValue) {
setVal(floatFromString(getPersistedString("0.0")));
} else {
setVal(Float.valueOf((Float) defaultValue));
}
savePrevVal();
}
@Override
protected void onDialogClosed(boolean positiveResult) {
if (!positiveResult) {
restoreVal();
return;
}
if (shouldPersist()) {
savePrevVal();
persistString(getValString());
}
notifyChanged();
}
} | 11beeaosama-descrbvbnvbniption | java/src/org/pocketworkstation/pckeyboard/SeekBarPreferenceString.java | Java | asf20 | 1,758 |
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.content.res.XmlResourceParser;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.text.TextPaint;
import android.util.Log;
import android.view.ViewConfiguration;
import android.view.inputmethod.EditorInfo;
import java.util.List;
import java.util.Locale;
public class LatinKeyboard extends Keyboard {
private static final boolean DEBUG_PREFERRED_LETTER = true;
private static final String TAG = "PCKeyboardLK";
private static final int OPACITY_FULLY_OPAQUE = 255;
private static final int SPACE_LED_LENGTH_PERCENT = 80;
private Drawable mShiftLockIcon;
private Drawable mShiftLockPreviewIcon;
private Drawable mOldShiftIcon;
private Drawable mSpaceIcon;
private Drawable mSpaceAutoCompletionIndicator;
private Drawable mSpacePreviewIcon;
private Drawable mMicIcon;
private Drawable mMicPreviewIcon;
private Drawable mSettingsIcon;
private Drawable mSettingsPreviewIcon;
private Drawable m123MicIcon;
private Drawable m123MicPreviewIcon;
private final Drawable mButtonArrowLeftIcon;
private final Drawable mButtonArrowRightIcon;
private Key mShiftKey;
private Key mEnterKey;
private Key mF1Key;
private final Drawable mHintIcon;
private Key mSpaceKey;
private Key m123Key;
private final int[] mSpaceKeyIndexArray;
private int mSpaceDragStartX;
private int mSpaceDragLastDiff;
private Locale mLocale;
private LanguageSwitcher mLanguageSwitcher;
private final Resources mRes;
private final Context mContext;
private int mMode;
// Whether this keyboard has voice icon on it
private boolean mHasVoiceButton;
// Whether voice icon is enabled at all
private boolean mVoiceEnabled;
private final boolean mIsAlphaKeyboard;
private final boolean mIsAlphaFullKeyboard;
private final boolean mIsFnFullKeyboard;
private CharSequence m123Label;
private boolean mCurrentlyInSpace;
private SlidingLocaleDrawable mSlidingLocaleIcon;
private int[] mPrefLetterFrequencies;
private int mPrefLetter;
private int mPrefLetterX;
private int mPrefLetterY;
private int mPrefDistance;
private int mExtensionResId;
// TODO: remove this attribute when either Keyboard.mDefaultVerticalGap or Key.parent becomes
// non-private.
private final int mVerticalGap;
private LatinKeyboard mExtensionKeyboard;
private static final float SPACEBAR_DRAG_THRESHOLD = 0.51f;
private static final float OVERLAP_PERCENTAGE_LOW_PROB = 0.70f;
private static final float OVERLAP_PERCENTAGE_HIGH_PROB = 0.85f;
// Minimum width of space key preview (proportional to keyboard width)
private static final float SPACEBAR_POPUP_MIN_RATIO = 0.4f;
// Minimum width of space key preview (proportional to screen height)
private static final float SPACEBAR_POPUP_MAX_RATIO = 0.4f;
// Height in space key the language name will be drawn. (proportional to space key height)
private static final float SPACEBAR_LANGUAGE_BASELINE = 0.6f;
// If the full language name needs to be smaller than this value to be drawn on space key,
// its short language name will be used instead.
private static final float MINIMUM_SCALE_OF_LANGUAGE_NAME = 0.8f;
private static int sSpacebarVerticalCorrection;
public LatinKeyboard(Context context, int xmlLayoutResId) {
this(context, xmlLayoutResId, 0, 0);
}
public LatinKeyboard(Context context, int xmlLayoutResId, int mode, float kbHeightPercent) {
super(context, 0, xmlLayoutResId, mode, kbHeightPercent);
final Resources res = context.getResources();
//Log.i("PCKeyboard", "keyHeight=" + this.getKeyHeight());
//this.setKeyHeight(30); // is useless, see http://code.google.com/p/android/issues/detail?id=4532
mContext = context;
mMode = mode;
mRes = res;
mShiftLockIcon = res.getDrawable(R.drawable.sym_keyboard_shift_locked);
mShiftLockPreviewIcon = res.getDrawable(R.drawable.sym_keyboard_feedback_shift_locked);
setDefaultBounds(mShiftLockPreviewIcon);
mSpaceIcon = res.getDrawable(R.drawable.sym_keyboard_space);
mSpaceAutoCompletionIndicator = res.getDrawable(R.drawable.sym_keyboard_space_led);
mSpacePreviewIcon = res.getDrawable(R.drawable.sym_keyboard_feedback_space);
mMicIcon = res.getDrawable(R.drawable.sym_keyboard_mic);
mMicPreviewIcon = res.getDrawable(R.drawable.sym_keyboard_feedback_mic);
mSettingsIcon = res.getDrawable(R.drawable.sym_keyboard_settings);
mSettingsPreviewIcon = res.getDrawable(R.drawable.sym_keyboard_feedback_settings);
setDefaultBounds(mMicPreviewIcon);
mButtonArrowLeftIcon = res.getDrawable(R.drawable.sym_keyboard_language_arrows_left);
mButtonArrowRightIcon = res.getDrawable(R.drawable.sym_keyboard_language_arrows_right);
m123MicIcon = res.getDrawable(R.drawable.sym_keyboard_123_mic);
m123MicPreviewIcon = res.getDrawable(R.drawable.sym_keyboard_feedback_123_mic);
mHintIcon = res.getDrawable(R.drawable.hint_popup);
setDefaultBounds(m123MicPreviewIcon);
sSpacebarVerticalCorrection = res.getDimensionPixelOffset(
R.dimen.spacebar_vertical_correction);
mIsAlphaKeyboard = xmlLayoutResId == R.xml.kbd_qwerty;
mIsAlphaFullKeyboard = xmlLayoutResId == R.xml.kbd_full;
mIsFnFullKeyboard = xmlLayoutResId == R.xml.kbd_full_fn || xmlLayoutResId == R.xml.kbd_compact_fn;
// The index of space key is available only after Keyboard constructor has finished.
mSpaceKeyIndexArray = new int[] { indexOf(LatinIME.ASCII_SPACE) };
// TODO remove this initialization after cleanup
mVerticalGap = super.getVerticalGap();
}
@Override
protected Key createKeyFromXml(Resources res, Row parent, int x, int y,
XmlResourceParser parser) {
Key key = new LatinKey(res, parent, x, y, parser);
if (key.codes == null) return key;
switch (key.codes[0]) {
case LatinIME.ASCII_ENTER:
mEnterKey = key;
break;
case LatinKeyboardView.KEYCODE_F1:
mF1Key = key;
break;
case LatinIME.ASCII_SPACE:
mSpaceKey = key;
break;
case KEYCODE_MODE_CHANGE:
m123Key = key;
m123Label = key.label;
break;
}
return key;
}
void setImeOptions(Resources res, int mode, int options) {
mMode = mode;
// TODO should clean up this method
if (mEnterKey != null) {
// Reset some of the rarely used attributes.
mEnterKey.popupCharacters = null;
mEnterKey.popupResId = 0;
mEnterKey.text = null;
switch (options&(EditorInfo.IME_MASK_ACTION|EditorInfo.IME_FLAG_NO_ENTER_ACTION)) {
case EditorInfo.IME_ACTION_GO:
mEnterKey.iconPreview = null;
mEnterKey.icon = null;
mEnterKey.label = res.getText(R.string.label_go_key);
break;
case EditorInfo.IME_ACTION_NEXT:
mEnterKey.iconPreview = null;
mEnterKey.icon = null;
mEnterKey.label = res.getText(R.string.label_next_key);
break;
case EditorInfo.IME_ACTION_DONE:
mEnterKey.iconPreview = null;
mEnterKey.icon = null;
mEnterKey.label = res.getText(R.string.label_done_key);
break;
case EditorInfo.IME_ACTION_SEARCH:
mEnterKey.iconPreview = res.getDrawable(
R.drawable.sym_keyboard_feedback_search);
mEnterKey.icon = res.getDrawable(R.drawable.sym_keyboard_search);
mEnterKey.label = null;
break;
case EditorInfo.IME_ACTION_SEND:
mEnterKey.iconPreview = null;
mEnterKey.icon = null;
mEnterKey.label = res.getText(R.string.label_send_key);
break;
default:
// Keep Return key in IM mode, we have a dedicated smiley key.
mEnterKey.iconPreview = res.getDrawable(
R.drawable.sym_keyboard_feedback_return);
mEnterKey.icon = res.getDrawable(R.drawable.sym_keyboard_return);
mEnterKey.label = null;
break;
}
// Set the initial size of the preview icon
if (mEnterKey.iconPreview != null) {
setDefaultBounds(mEnterKey.iconPreview);
}
}
}
void enableShiftLock() {
int index = getShiftKeyIndex();
if (index >= 0) {
mShiftKey = getKeys().get(index);
mOldShiftIcon = mShiftKey.icon;
}
}
@Override
public boolean setShiftState(int shiftState) {
if (mShiftKey != null) {
// Tri-state LED tracks "on" and "lock" states, icon shows Caps state.
mShiftKey.on = shiftState == SHIFT_ON || shiftState == SHIFT_LOCKED;
mShiftKey.locked = shiftState == SHIFT_LOCKED || shiftState == SHIFT_CAPS_LOCKED;
mShiftKey.icon = (shiftState == SHIFT_OFF || shiftState == SHIFT_ON || shiftState == SHIFT_LOCKED) ?
mOldShiftIcon : mShiftLockIcon;
return super.setShiftState(shiftState, false);
} else {
return super.setShiftState(shiftState, true);
}
}
/* package */ boolean isAlphaKeyboard() {
return mIsAlphaKeyboard;
}
public void setExtension(LatinKeyboard extKeyboard) {
mExtensionKeyboard = extKeyboard;
}
public LatinKeyboard getExtension() {
return mExtensionKeyboard;
}
public void updateSymbolIcons(boolean isAutoCompletion) {
updateDynamicKeys();
updateSpaceBarForLocale(isAutoCompletion);
}
private void setDefaultBounds(Drawable drawable) {
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
}
public void setVoiceMode(boolean hasVoiceButton, boolean hasVoice) {
mHasVoiceButton = hasVoiceButton;
mVoiceEnabled = hasVoice;
updateDynamicKeys();
}
private void updateDynamicKeys() {
update123Key();
updateF1Key();
}
private void update123Key() {
// Update KEYCODE_MODE_CHANGE key only on alphabet mode, not on symbol mode.
if (m123Key != null && mIsAlphaKeyboard) {
if (mVoiceEnabled && !mHasVoiceButton) {
m123Key.icon = m123MicIcon;
m123Key.iconPreview = m123MicPreviewIcon;
m123Key.label = null;
} else {
m123Key.icon = null;
m123Key.iconPreview = null;
m123Key.label = m123Label;
}
}
}
private void updateF1Key() {
// Update KEYCODE_F1 key. Please note that some keyboard layouts have no F1 key.
if (mF1Key == null)
return;
if (mIsAlphaKeyboard) {
if (mMode == KeyboardSwitcher.MODE_URL) {
setNonMicF1Key(mF1Key, "/", R.xml.popup_slash);
} else if (mMode == KeyboardSwitcher.MODE_EMAIL) {
setNonMicF1Key(mF1Key, "@", R.xml.popup_at);
} else {
if (mVoiceEnabled && mHasVoiceButton) {
setMicF1Key(mF1Key);
} else {
setNonMicF1Key(mF1Key, ",", R.xml.popup_comma);
}
}
} else if (mIsAlphaFullKeyboard) {
if (mVoiceEnabled && mHasVoiceButton) {
setMicF1Key(mF1Key);
} else {
setSettingsF1Key(mF1Key);
}
} else if (mIsFnFullKeyboard) {
setMicF1Key(mF1Key);
} else { // Symbols keyboard
if (mVoiceEnabled && mHasVoiceButton) {
setMicF1Key(mF1Key);
} else {
setNonMicF1Key(mF1Key, ",", R.xml.popup_comma);
}
}
}
private void setMicF1Key(Key key) {
// HACK: draw mMicIcon and mHintIcon at the same time
final Drawable micWithSettingsHintDrawable = new BitmapDrawable(mRes,
drawSynthesizedSettingsHintImage(key.width, key.height, mMicIcon, mHintIcon));
if (key.popupResId == 0) {
key.popupResId = R.xml.popup_mic;
} else {
key.modifier = true;
if (key.label != null) {
key.popupCharacters = (key.popupCharacters == null) ?
key.label + key.shiftLabel.toString() :
key.label + key.shiftLabel.toString() + key.popupCharacters.toString();
}
}
key.label = null;
key.shiftLabel = null;
key.codes = new int[] { LatinKeyboardView.KEYCODE_VOICE };
key.icon = micWithSettingsHintDrawable;
key.iconPreview = mMicPreviewIcon;
}
private void setSettingsF1Key(Key key) {
if (key.shiftLabel != null && key.label != null) {
key.codes = new int[] { key.label.charAt(0) };
return; // leave key otherwise unmodified
}
final Drawable settingsHintDrawable = new BitmapDrawable(mRes,
drawSynthesizedSettingsHintImage(key.width, key.height, mSettingsIcon, mHintIcon));
key.label = null;
key.icon = settingsHintDrawable;
key.codes = new int[] { LatinKeyboardView.KEYCODE_OPTIONS };
key.popupResId = R.xml.popup_mic;
key.iconPreview = mSettingsPreviewIcon;
}
private void setNonMicF1Key(Key key, String label, int popupResId) {
if (key.shiftLabel != null) {
key.codes = new int[] { key.label.charAt(0) };
return; // leave key unmodified
}
key.label = label;
key.codes = new int[] { label.charAt(0) };
key.popupResId = popupResId;
key.icon = mHintIcon;
key.iconPreview = null;
}
public boolean isF1Key(Key key) {
return key == mF1Key;
}
public static boolean hasPuncOrSmileysPopup(Key key) {
return key.popupResId == R.xml.popup_punctuation || key.popupResId == R.xml.popup_smileys;
}
/**
* @return a key which should be invalidated.
*/
public Key onAutoCompletionStateChanged(boolean isAutoCompletion) {
updateSpaceBarForLocale(isAutoCompletion);
return mSpaceKey;
}
public boolean isLanguageSwitchEnabled() {
return mLocale != null;
}
private void updateSpaceBarForLocale(boolean isAutoCompletion) {
if (mSpaceKey == null) return;
// If application locales are explicitly selected.
if (mLocale != null) {
mSpaceKey.icon = new BitmapDrawable(mRes,
drawSpaceBar(OPACITY_FULLY_OPAQUE, isAutoCompletion));
} else {
// sym_keyboard_space_led can be shared with Black and White symbol themes.
if (isAutoCompletion) {
mSpaceKey.icon = new BitmapDrawable(mRes,
drawSpaceBar(OPACITY_FULLY_OPAQUE, isAutoCompletion));
} else {
mSpaceKey.icon = mRes.getDrawable(R.drawable.sym_keyboard_space);
}
}
}
// Compute width of text with specified text size using paint.
private static int getTextWidth(Paint paint, String text, float textSize, Rect bounds) {
paint.setTextSize(textSize);
paint.getTextBounds(text, 0, text.length(), bounds);
return bounds.width();
}
// Overlay two images: mainIcon and hintIcon.
private Bitmap drawSynthesizedSettingsHintImage(
int width, int height, Drawable mainIcon, Drawable hintIcon) {
if (mainIcon == null || hintIcon == null)
return null;
Rect hintIconPadding = new Rect(0, 0, 0, 0);
hintIcon.getPadding(hintIconPadding);
final Bitmap buffer = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
final Canvas canvas = new Canvas(buffer);
canvas.drawColor(mRes.getColor(R.color.latinkeyboard_transparent), PorterDuff.Mode.CLEAR);
// Draw main icon at the center of the key visual
// Assuming the hintIcon shares the same padding with the key's background drawable
final int drawableX = (width + hintIconPadding.left - hintIconPadding.right
- mainIcon.getIntrinsicWidth()) / 2;
final int drawableY = (height + hintIconPadding.top - hintIconPadding.bottom
- mainIcon.getIntrinsicHeight()) / 2;
setDefaultBounds(mainIcon);
canvas.translate(drawableX, drawableY);
mainIcon.draw(canvas);
canvas.translate(-drawableX, -drawableY);
// Draw hint icon fully in the key
hintIcon.setBounds(0, 0, width, height);
hintIcon.draw(canvas);
return buffer;
}
// Layout local language name and left and right arrow on space bar.
private static String layoutSpaceBar(Paint paint, Locale locale, Drawable lArrow,
Drawable rArrow, int width, int height, float origTextSize,
boolean allowVariableTextSize) {
final float arrowWidth = lArrow.getIntrinsicWidth();
final float arrowHeight = lArrow.getIntrinsicHeight();
final float maxTextWidth = width - (arrowWidth + arrowWidth);
final Rect bounds = new Rect();
// Estimate appropriate language name text size to fit in maxTextWidth.
String language = LanguageSwitcher.toTitleCase(locale.getDisplayLanguage(locale));
int textWidth = getTextWidth(paint, language, origTextSize, bounds);
// Assuming text width and text size are proportional to each other.
float textSize = origTextSize * Math.min(maxTextWidth / textWidth, 1.0f);
final boolean useShortName;
if (allowVariableTextSize) {
textWidth = getTextWidth(paint, language, textSize, bounds);
// If text size goes too small or text does not fit, use short name
useShortName = textSize / origTextSize < MINIMUM_SCALE_OF_LANGUAGE_NAME
|| textWidth > maxTextWidth;
} else {
useShortName = textWidth > maxTextWidth;
textSize = origTextSize;
}
if (useShortName) {
language = LanguageSwitcher.toTitleCase(locale.getLanguage());
textWidth = getTextWidth(paint, language, origTextSize, bounds);
textSize = origTextSize * Math.min(maxTextWidth / textWidth, 1.0f);
}
paint.setTextSize(textSize);
// Place left and right arrow just before and after language text.
final float baseline = height * SPACEBAR_LANGUAGE_BASELINE;
final int top = (int)(baseline - arrowHeight);
final float remains = (width - textWidth) / 2;
lArrow.setBounds((int)(remains - arrowWidth), top, (int)remains, (int)baseline);
rArrow.setBounds((int)(remains + textWidth), top, (int)(remains + textWidth + arrowWidth),
(int)baseline);
return language;
}
private Bitmap drawSpaceBar(int opacity, boolean isAutoCompletion) {
final int width = mSpaceKey.width;
final int height = mSpaceIcon.getIntrinsicHeight();
final Bitmap buffer = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
final Canvas canvas = new Canvas(buffer);
canvas.drawColor(mRes.getColor(R.color.latinkeyboard_transparent), PorterDuff.Mode.CLEAR);
// If application locales are explicitly selected.
if (mLocale != null) {
final Paint paint = new Paint();
paint.setAlpha(opacity);
paint.setAntiAlias(true);
paint.setTextAlign(Align.CENTER);
final boolean allowVariableTextSize = true;
Locale locale = mLanguageSwitcher.getInputLocale();
//Log.i("PCKeyboard", "input locale: " + locale);
final String language = layoutSpaceBar(paint, locale,
mButtonArrowLeftIcon, mButtonArrowRightIcon, width, height,
getTextSizeFromTheme(android.R.style.TextAppearance_Small, 14),
allowVariableTextSize);
// Draw language text with shadow
final int shadowColor = mRes.getColor(R.color.latinkeyboard_bar_language_shadow_white);
final float baseline = height * SPACEBAR_LANGUAGE_BASELINE;
final float descent = paint.descent();
paint.setColor(shadowColor);
canvas.drawText(language, width / 2, baseline - descent - 1, paint);
paint.setColor(mRes.getColor(R.color.latinkeyboard_dim_color_white));
canvas.drawText(language, width / 2, baseline - descent, paint);
// Put arrows that are already layed out on either side of the text
if (mLanguageSwitcher.getLocaleCount() > 1) {
mButtonArrowLeftIcon.draw(canvas);
mButtonArrowRightIcon.draw(canvas);
}
}
// Draw the spacebar icon at the bottom
if (isAutoCompletion) {
final int iconWidth = width * SPACE_LED_LENGTH_PERCENT / 100;
final int iconHeight = mSpaceAutoCompletionIndicator.getIntrinsicHeight();
int x = (width - iconWidth) / 2;
int y = height - iconHeight;
mSpaceAutoCompletionIndicator.setBounds(x, y, x + iconWidth, y + iconHeight);
mSpaceAutoCompletionIndicator.draw(canvas);
} else {
final int iconWidth = mSpaceIcon.getIntrinsicWidth();
final int iconHeight = mSpaceIcon.getIntrinsicHeight();
int x = (width - iconWidth) / 2;
int y = height - iconHeight;
mSpaceIcon.setBounds(x, y, x + iconWidth, y + iconHeight);
mSpaceIcon.draw(canvas);
}
return buffer;
}
private int getSpacePreviewWidth() {
final int width = Math.min(
Math.max(mSpaceKey.width, (int)(getMinWidth() * SPACEBAR_POPUP_MIN_RATIO)),
(int)(getScreenHeight() * SPACEBAR_POPUP_MAX_RATIO));
return width;
}
private void updateLocaleDrag(int diff) {
if (mSlidingLocaleIcon == null) {
final int width = getSpacePreviewWidth();
final int height = mSpacePreviewIcon.getIntrinsicHeight();
mSlidingLocaleIcon = new SlidingLocaleDrawable(mSpacePreviewIcon, width, height);
mSlidingLocaleIcon.setBounds(0, 0, width, height);
mSpaceKey.iconPreview = mSlidingLocaleIcon;
}
mSlidingLocaleIcon.setDiff(diff);
if (Math.abs(diff) == Integer.MAX_VALUE) {
mSpaceKey.iconPreview = mSpacePreviewIcon;
} else {
mSpaceKey.iconPreview = mSlidingLocaleIcon;
}
mSpaceKey.iconPreview.invalidateSelf();
}
public int getLanguageChangeDirection() {
if (mSpaceKey == null || mLanguageSwitcher.getLocaleCount() < 2
|| Math.abs(mSpaceDragLastDiff) < getSpacePreviewWidth() * SPACEBAR_DRAG_THRESHOLD) {
return 0; // No change
}
return mSpaceDragLastDiff > 0 ? 1 : -1;
}
public void setLanguageSwitcher(LanguageSwitcher switcher, boolean isAutoCompletion) {
mLanguageSwitcher = switcher;
Locale locale = mLanguageSwitcher.getLocaleCount() > 0
? mLanguageSwitcher.getInputLocale()
: null;
// If the language count is 1 and is the same as the system language, don't show it.
if (locale != null
&& mLanguageSwitcher.getLocaleCount() == 1
&& mLanguageSwitcher.getSystemLocale().getLanguage()
.equalsIgnoreCase(locale.getLanguage())) {
locale = null;
}
mLocale = locale;
updateSymbolIcons(isAutoCompletion);
}
boolean isCurrentlyInSpace() {
return mCurrentlyInSpace;
}
void setPreferredLetters(int[] frequencies) {
mPrefLetterFrequencies = frequencies;
mPrefLetter = 0;
}
void keyReleased() {
mCurrentlyInSpace = false;
mSpaceDragLastDiff = 0;
mPrefLetter = 0;
mPrefLetterX = 0;
mPrefLetterY = 0;
mPrefDistance = Integer.MAX_VALUE;
if (mSpaceKey != null) {
updateLocaleDrag(Integer.MAX_VALUE);
}
}
/**
* Does the magic of locking the touch gesture into the spacebar when
* switching input languages.
*/
boolean isInside(LatinKey key, int x, int y) {
final int code = key.codes[0];
if (code == KEYCODE_SHIFT ||
code == KEYCODE_DELETE) {
// Adjust target area for these keys
y -= key.height / 10;
if (code == KEYCODE_SHIFT) {
if (key.x == 0) {
x += key.width / 6; // left shift
} else {
x -= key.width / 6; // right shift
}
}
if (code == KEYCODE_DELETE) x -= key.width / 6;
} else if (code == LatinIME.ASCII_SPACE) {
y += LatinKeyboard.sSpacebarVerticalCorrection;
if (mLanguageSwitcher.getLocaleCount() > 1) {
if (mCurrentlyInSpace) {
int diff = x - mSpaceDragStartX;
if (Math.abs(diff - mSpaceDragLastDiff) > 0) {
updateLocaleDrag(diff);
}
mSpaceDragLastDiff = diff;
return true;
} else {
boolean insideSpace = key.isInsideSuper(x, y);
if (insideSpace) {
mCurrentlyInSpace = true;
mSpaceDragStartX = x;
updateLocaleDrag(0);
}
return insideSpace;
}
}
} else if (mPrefLetterFrequencies != null) {
// New coordinate? Reset
if (mPrefLetterX != x || mPrefLetterY != y) {
mPrefLetter = 0;
mPrefDistance = Integer.MAX_VALUE;
}
// Handle preferred next letter
final int[] pref = mPrefLetterFrequencies;
if (mPrefLetter > 0) {
if (DEBUG_PREFERRED_LETTER) {
if (mPrefLetter == code && !key.isInsideSuper(x, y)) {
Log.d(TAG, "CORRECTED !!!!!!");
}
}
return mPrefLetter == code;
} else {
final boolean inside = key.isInsideSuper(x, y);
int[] nearby = getNearestKeys(x, y);
List<Key> nearbyKeys = getKeys();
if (inside) {
// If it's a preferred letter
if (inPrefList(code, pref)) {
// Check if its frequency is much lower than a nearby key
mPrefLetter = code;
mPrefLetterX = x;
mPrefLetterY = y;
for (int i = 0; i < nearby.length; i++) {
Key k = nearbyKeys.get(nearby[i]);
if (k != key && inPrefList(k.codes[0], pref)) {
final int dist = distanceFrom(k, x, y);
if (dist < (int) (k.width * OVERLAP_PERCENTAGE_LOW_PROB) &&
(pref[k.codes[0]] > pref[mPrefLetter] * 3)) {
mPrefLetter = k.codes[0];
mPrefDistance = dist;
if (DEBUG_PREFERRED_LETTER) {
Log.d(TAG, "CORRECTED ALTHOUGH PREFERRED !!!!!!");
}
break;
}
}
}
return mPrefLetter == code;
}
}
// Get the surrounding keys and intersect with the preferred list
// For all in the intersection
// if distance from touch point is within a reasonable distance
// make this the pref letter
// If no pref letter
// return inside;
// else return thiskey == prefletter;
for (int i = 0; i < nearby.length; i++) {
Key k = nearbyKeys.get(nearby[i]);
if (inPrefList(k.codes[0], pref)) {
final int dist = distanceFrom(k, x, y);
if (dist < (int) (k.width * OVERLAP_PERCENTAGE_HIGH_PROB)
&& dist < mPrefDistance) {
mPrefLetter = k.codes[0];
mPrefLetterX = x;
mPrefLetterY = y;
mPrefDistance = dist;
}
}
}
// Didn't find any
if (mPrefLetter == 0) {
return inside;
} else {
return mPrefLetter == code;
}
}
}
// Lock into the spacebar
if (mCurrentlyInSpace) return false;
return key.isInsideSuper(x, y);
}
private boolean inPrefList(int code, int[] pref) {
if (code < pref.length && code >= 0) return pref[code] > 0;
return false;
}
private int distanceFrom(Key k, int x, int y) {
if (y > k.y && y < k.y + k.height) {
return Math.abs(k.x + k.width / 2 - x);
} else {
return Integer.MAX_VALUE;
}
}
@Override
public int[] getNearestKeys(int x, int y) {
if (mCurrentlyInSpace) {
return mSpaceKeyIndexArray;
} else {
// Avoid dead pixels at edges of the keyboard
return super.getNearestKeys(Math.max(0, Math.min(x, getMinWidth() - 1)),
Math.max(0, Math.min(y, getHeight() - 1)));
}
}
private int indexOf(int code) {
List<Key> keys = getKeys();
int count = keys.size();
for (int i = 0; i < count; i++) {
if (keys.get(i).codes[0] == code) return i;
}
return -1;
}
private int getTextSizeFromTheme(int style, int defValue) {
TypedArray array = mContext.getTheme().obtainStyledAttributes(
style, new int[] { android.R.attr.textSize });
int resId = array.getResourceId(0, 0);
if (resId >= array.length()) {
Log.i(TAG, "getTextSizeFromTheme error: resId " + resId + " > " + array.length());
return defValue;
}
int textSize = array.getDimensionPixelSize(resId, defValue);
return textSize;
}
// TODO LatinKey could be static class
class LatinKey extends Key {
// functional normal state (with properties)
private final int[] KEY_STATE_FUNCTIONAL_NORMAL = {
android.R.attr.state_single
};
// functional pressed state (with properties)
private final int[] KEY_STATE_FUNCTIONAL_PRESSED = {
android.R.attr.state_single,
android.R.attr.state_pressed
};
public LatinKey(Resources res, Keyboard.Row parent, int x, int y,
XmlResourceParser parser) {
super(res, parent, x, y, parser);
}
// sticky is used for shift key. If a key is not sticky and is modifier,
// the key will be treated as functional.
private boolean isFunctionalKey() {
return !sticky && modifier;
}
/**
* Overriding this method so that we can reduce the target area for certain keys.
*/
@Override
public boolean isInside(int x, int y) {
// TODO This should be done by parent.isInside(this, x, y)
// if Key.parent were protected.
boolean result = LatinKeyboard.this.isInside(this, x, y);
return result;
}
boolean isInsideSuper(int x, int y) {
return super.isInside(x, y);
}
@Override
public int[] getCurrentDrawableState() {
if (isFunctionalKey()) {
if (pressed) {
return KEY_STATE_FUNCTIONAL_PRESSED;
} else {
return KEY_STATE_FUNCTIONAL_NORMAL;
}
}
return super.getCurrentDrawableState();
}
@Override
public int squaredDistanceFrom(int x, int y) {
// We should count vertical gap between rows to calculate the center of this Key.
final int verticalGap = LatinKeyboard.this.mVerticalGap;
final int xDist = this.x + width / 2 - x;
final int yDist = this.y + (height + verticalGap) / 2 - y;
return xDist * xDist + yDist * yDist;
}
}
/**
* Animation to be displayed on the spacebar preview popup when switching
* languages by swiping the spacebar. It draws the current, previous and
* next languages and moves them by the delta of touch movement on the spacebar.
*/
class SlidingLocaleDrawable extends Drawable {
private final int mWidth;
private final int mHeight;
private final Drawable mBackground;
private final TextPaint mTextPaint;
private final int mMiddleX;
private final Drawable mLeftDrawable;
private final Drawable mRightDrawable;
private final int mThreshold;
private int mDiff;
private boolean mHitThreshold;
private String mCurrentLanguage;
private String mNextLanguage;
private String mPrevLanguage;
public SlidingLocaleDrawable(Drawable background, int width, int height) {
mBackground = background;
setDefaultBounds(mBackground);
mWidth = width;
mHeight = height;
mTextPaint = new TextPaint();
mTextPaint.setTextSize(getTextSizeFromTheme(android.R.style.TextAppearance_Medium, 18));
mTextPaint.setColor(mRes.getColor(R.color.latinkeyboard_transparent));
mTextPaint.setTextAlign(Align.CENTER);
mTextPaint.setAlpha(OPACITY_FULLY_OPAQUE);
mTextPaint.setAntiAlias(true);
mMiddleX = (mWidth - mBackground.getIntrinsicWidth()) / 2;
mLeftDrawable =
mRes.getDrawable(R.drawable.sym_keyboard_feedback_language_arrows_left);
mRightDrawable =
mRes.getDrawable(R.drawable.sym_keyboard_feedback_language_arrows_right);
mThreshold = ViewConfiguration.get(mContext).getScaledTouchSlop();
}
private void setDiff(int diff) {
if (diff == Integer.MAX_VALUE) {
mHitThreshold = false;
mCurrentLanguage = null;
return;
}
mDiff = diff;
if (mDiff > mWidth) mDiff = mWidth;
if (mDiff < -mWidth) mDiff = -mWidth;
if (Math.abs(mDiff) > mThreshold) mHitThreshold = true;
invalidateSelf();
}
private String getLanguageName(Locale locale) {
return LanguageSwitcher.toTitleCase(locale.getDisplayLanguage(locale));
}
@Override
public void draw(Canvas canvas) {
canvas.save();
if (mHitThreshold) {
Paint paint = mTextPaint;
final int width = mWidth;
final int height = mHeight;
final int diff = mDiff;
final Drawable lArrow = mLeftDrawable;
final Drawable rArrow = mRightDrawable;
canvas.clipRect(0, 0, width, height);
if (mCurrentLanguage == null) {
final LanguageSwitcher languageSwitcher = mLanguageSwitcher;
mCurrentLanguage = getLanguageName(languageSwitcher.getInputLocale());
mNextLanguage = getLanguageName(languageSwitcher.getNextInputLocale());
mPrevLanguage = getLanguageName(languageSwitcher.getPrevInputLocale());
}
// Draw language text with shadow
final float baseline = mHeight * SPACEBAR_LANGUAGE_BASELINE - paint.descent();
paint.setColor(mRes.getColor(R.color.latinkeyboard_feedback_language_text));
canvas.drawText(mCurrentLanguage, width / 2 + diff, baseline, paint);
canvas.drawText(mNextLanguage, diff - width / 2, baseline, paint);
canvas.drawText(mPrevLanguage, diff + width + width / 2, baseline, paint);
setDefaultBounds(lArrow);
rArrow.setBounds(width - rArrow.getIntrinsicWidth(), 0, width,
rArrow.getIntrinsicHeight());
lArrow.draw(canvas);
rArrow.draw(canvas);
}
if (mBackground != null) {
canvas.translate(mMiddleX, 0);
mBackground.draw(canvas);
}
canvas.restore();
}
@Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
@Override
public void setAlpha(int alpha) {
// Ignore
}
@Override
public void setColorFilter(ColorFilter cf) {
// Ignore
}
@Override
public int getIntrinsicWidth() {
return mWidth;
}
@Override
public int getIntrinsicHeight() {
return mHeight;
}
}
}
| 11beeaosama-descrbvbnvbniption | java/src/org/pocketworkstation/pckeyboard/LatinKeyboard.java | Java | asf20 | 39,247 |
/*
* Copyright (C) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import org.pocketworkstation.pckeyboard.Keyboard.Key;
import java.util.Arrays;
import java.util.List;
abstract class KeyDetector {
protected Keyboard mKeyboard;
private Key[] mKeys;
protected int mCorrectionX;
protected int mCorrectionY;
protected boolean mProximityCorrectOn;
protected int mProximityThresholdSquare;
public Key[] setKeyboard(Keyboard keyboard, float correctionX, float correctionY) {
if (keyboard == null)
throw new NullPointerException();
mCorrectionX = (int)correctionX;
mCorrectionY = (int)correctionY;
mKeyboard = keyboard;
List<Key> keys = mKeyboard.getKeys();
Key[] array = keys.toArray(new Key[keys.size()]);
mKeys = array;
return array;
}
protected int getTouchX(int x) {
return x + mCorrectionX;
}
protected int getTouchY(int y) {
return y + mCorrectionY;
}
protected Key[] getKeys() {
if (mKeys == null)
throw new IllegalStateException("keyboard isn't set");
// mKeyboard is guaranteed not to be null at setKeybaord() method if mKeys is not null
return mKeys;
}
public void setProximityCorrectionEnabled(boolean enabled) {
mProximityCorrectOn = enabled;
}
public boolean isProximityCorrectionEnabled() {
return mProximityCorrectOn;
}
public void setProximityThreshold(int threshold) {
mProximityThresholdSquare = threshold * threshold;
}
/**
* Allocates array that can hold all key indices returned by {@link #getKeyIndexAndNearbyCodes}
* method. The maximum size of the array should be computed by {@link #getMaxNearbyKeys}.
*
* @return Allocates and returns an array that can hold all key indices returned by
* {@link #getKeyIndexAndNearbyCodes} method. All elements in the returned array are
* initialized by {@link org.pocketworkstation.pckeyboard.LatinKeyboardView.NOT_A_KEY}
* value.
*/
public int[] newCodeArray() {
int[] codes = new int[getMaxNearbyKeys()];
Arrays.fill(codes, LatinKeyboardBaseView.NOT_A_KEY);
return codes;
}
/**
* Computes maximum size of the array that can contain all nearby key indices returned by
* {@link #getKeyIndexAndNearbyCodes}.
*
* @return Returns maximum size of the array that can contain all nearby key indices returned
* by {@link #getKeyIndexAndNearbyCodes}.
*/
abstract protected int getMaxNearbyKeys();
/**
* Finds all possible nearby key indices around a touch event point and returns the nearest key
* index. The algorithm to determine the nearby keys depends on the threshold set by
* {@link #setProximityThreshold(int)} and the mode set by
* {@link #setProximityCorrectionEnabled(boolean)}.
*
* @param x The x-coordinate of a touch point
* @param y The y-coordinate of a touch point
* @param allKeys All nearby key indices are returned in this array
* @return The nearest key index
*/
abstract public int getKeyIndexAndNearbyCodes(int x, int y, int[] allKeys);
}
| 11beeaosama-descrbvbnvbniption | java/src/org/pocketworkstation/pckeyboard/KeyDetector.java | Java | asf20 | 3,832 |
/*
* Copyright (C) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
class ModifierKeyState {
private static final int RELEASING = 0;
private static final int PRESSING = 1;
private static final int CHORDING = 2;
private int mState = RELEASING;
public void onPress() {
mState = PRESSING;
}
public void onRelease() {
mState = RELEASING;
}
public void onOtherKeyPressed() {
if (mState == PRESSING)
mState = CHORDING;
}
public boolean isChording() {
return mState == CHORDING;
}
public String toString() {
return "ModifierKeyState:" + mState;
}
}
| 11beeaosama-descrbvbnvbniption | java/src/org/pocketworkstation/pckeyboard/ModifierKeyState.java | Java | asf20 | 1,228 |
/*
* Copyright (C) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import java.util.ArrayList;
import java.util.List;
import org.pocketworkstation.pckeyboard.LatinKeyboardBaseView.OnKeyboardActionListener;
import org.pocketworkstation.pckeyboard.LatinKeyboardBaseView.UIHandler;
import android.content.res.Resources;
import org.pocketworkstation.pckeyboard.Keyboard.Key;
import android.util.Log;
import android.view.MotionEvent;
public class PointerTracker {
private static final String TAG = "PointerTracker";
private static final boolean DEBUG = false;
private static final boolean DEBUG_MOVE = false;
public interface UIProxy {
public void invalidateKey(Key key);
public void showPreview(int keyIndex, PointerTracker tracker);
public boolean hasDistinctMultitouch();
}
public final int mPointerId;
// Timing constants
private final int mDelayBeforeKeyRepeatStart;
private final int mMultiTapKeyTimeout;
// Miscellaneous constants
private static final int NOT_A_KEY = LatinKeyboardBaseView.NOT_A_KEY;
private static final int[] KEY_DELETE = { Keyboard.KEYCODE_DELETE };
private final UIProxy mProxy;
private final UIHandler mHandler;
private final KeyDetector mKeyDetector;
private OnKeyboardActionListener mListener;
private final KeyboardSwitcher mKeyboardSwitcher;
private final boolean mHasDistinctMultitouch;
private Key[] mKeys;
private int mKeyHysteresisDistanceSquared = -1;
private final KeyState mKeyState;
// true if keyboard layout has been changed.
private boolean mKeyboardLayoutHasBeenChanged;
// true if event is already translated to a key action (long press or mini-keyboard)
private boolean mKeyAlreadyProcessed;
// true if this pointer is repeatable key
private boolean mIsRepeatableKey;
// true if this pointer is in sliding key input
private boolean mIsInSlidingKeyInput;
// For multi-tap
private int mLastSentIndex;
private int mTapCount;
private long mLastTapTime;
private boolean mInMultiTap;
private final StringBuilder mPreviewLabel = new StringBuilder(1);
// pressed key
private int mPreviousKey = NOT_A_KEY;
private static boolean sSlideKeyHack;
private static List<Key> sSlideKeys = new ArrayList<Key>(10);
// This class keeps track of a key index and a position where this pointer is.
private static class KeyState {
private final KeyDetector mKeyDetector;
// The position and time at which first down event occurred.
private int mStartX;
private int mStartY;
private long mDownTime;
// The current key index where this pointer is.
private int mKeyIndex = NOT_A_KEY;
// The position where mKeyIndex was recognized for the first time.
private int mKeyX;
private int mKeyY;
// Last pointer position.
private int mLastX;
private int mLastY;
public KeyState(KeyDetector keyDetecor) {
mKeyDetector = keyDetecor;
}
public int getKeyIndex() {
return mKeyIndex;
}
public int getKeyX() {
return mKeyX;
}
public int getKeyY() {
return mKeyY;
}
public int getStartX() {
return mStartX;
}
public int getStartY() {
return mStartY;
}
public long getDownTime() {
return mDownTime;
}
public int getLastX() {
return mLastX;
}
public int getLastY() {
return mLastY;
}
public int onDownKey(int x, int y, long eventTime) {
mStartX = x;
mStartY = y;
mDownTime = eventTime;
return onMoveToNewKey(onMoveKeyInternal(x, y), x, y);
}
private int onMoveKeyInternal(int x, int y) {
mLastX = x;
mLastY = y;
return mKeyDetector.getKeyIndexAndNearbyCodes(x, y, null);
}
public int onMoveKey(int x, int y) {
return onMoveKeyInternal(x, y);
}
public int onMoveToNewKey(int keyIndex, int x, int y) {
mKeyIndex = keyIndex;
mKeyX = x;
mKeyY = y;
return keyIndex;
}
public int onUpKey(int x, int y) {
return onMoveKeyInternal(x, y);
}
}
public PointerTracker(int id, UIHandler handler, KeyDetector keyDetector, UIProxy proxy,
Resources res, boolean slideKeyHack) {
if (proxy == null || handler == null || keyDetector == null)
throw new NullPointerException();
mPointerId = id;
mProxy = proxy;
mHandler = handler;
mKeyDetector = keyDetector;
mKeyboardSwitcher = KeyboardSwitcher.getInstance();
mKeyState = new KeyState(keyDetector);
mHasDistinctMultitouch = proxy.hasDistinctMultitouch();
mDelayBeforeKeyRepeatStart = res.getInteger(R.integer.config_delay_before_key_repeat_start);
mMultiTapKeyTimeout = res.getInteger(R.integer.config_multi_tap_key_timeout);
sSlideKeyHack = slideKeyHack;
resetMultiTap();
}
public void setOnKeyboardActionListener(OnKeyboardActionListener listener) {
mListener = listener;
}
public void setKeyboard(Key[] keys, float keyHysteresisDistance) {
if (keys == null || keyHysteresisDistance < 0)
throw new IllegalArgumentException();
mKeys = keys;
mKeyHysteresisDistanceSquared = (int)(keyHysteresisDistance * keyHysteresisDistance);
// Mark that keyboard layout has been changed.
mKeyboardLayoutHasBeenChanged = true;
}
public boolean isInSlidingKeyInput() {
return mIsInSlidingKeyInput;
}
public void setSlidingKeyInputState(boolean state) {
mIsInSlidingKeyInput = state;
}
private boolean isValidKeyIndex(int keyIndex) {
return keyIndex >= 0 && keyIndex < mKeys.length;
}
public Key getKey(int keyIndex) {
return isValidKeyIndex(keyIndex) ? mKeys[keyIndex] : null;
}
private boolean isModifierInternal(int keyIndex) {
Key key = getKey(keyIndex);
if (key == null || key.codes == null)
return false;
int primaryCode = key.codes[0];
return primaryCode == Keyboard.KEYCODE_SHIFT
|| primaryCode == Keyboard.KEYCODE_MODE_CHANGE
|| primaryCode == LatinKeyboardView.KEYCODE_CTRL_LEFT
|| primaryCode == LatinKeyboardView.KEYCODE_ALT_LEFT
|| primaryCode == LatinKeyboardView.KEYCODE_META_LEFT
|| primaryCode == LatinKeyboardView.KEYCODE_FN;
}
public boolean isModifier() {
return isModifierInternal(mKeyState.getKeyIndex());
}
public boolean isOnModifierKey(int x, int y) {
return isModifierInternal(mKeyDetector.getKeyIndexAndNearbyCodes(x, y, null));
}
public boolean isSpaceKey(int keyIndex) {
Key key = getKey(keyIndex);
return key != null && key.codes != null && key.codes[0] == LatinIME.ASCII_SPACE;
}
public void updateKey(int keyIndex) {
if (mKeyAlreadyProcessed)
return;
int oldKeyIndex = mPreviousKey;
mPreviousKey = keyIndex;
if (keyIndex != oldKeyIndex) {
if (isValidKeyIndex(oldKeyIndex)) {
// if new key index is not a key, old key was just released inside of the key.
final boolean inside = (keyIndex == NOT_A_KEY);
mKeys[oldKeyIndex].onReleased(inside);
mProxy.invalidateKey(mKeys[oldKeyIndex]);
}
if (isValidKeyIndex(keyIndex)) {
mKeys[keyIndex].onPressed();
mProxy.invalidateKey(mKeys[keyIndex]);
}
}
}
public void setAlreadyProcessed() {
mKeyAlreadyProcessed = true;
}
public void onTouchEvent(int action, int x, int y, long eventTime) {
switch (action) {
case MotionEvent.ACTION_MOVE:
onMoveEvent(x, y, eventTime);
break;
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_POINTER_DOWN:
onDownEvent(x, y, eventTime);
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_POINTER_UP:
onUpEvent(x, y, eventTime);
break;
case MotionEvent.ACTION_CANCEL:
onCancelEvent(x, y, eventTime);
break;
}
}
public void onDownEvent(int x, int y, long eventTime) {
if (DEBUG)
debugLog("onDownEvent:", x, y);
int keyIndex = mKeyState.onDownKey(x, y, eventTime);
mKeyboardLayoutHasBeenChanged = false;
mKeyAlreadyProcessed = false;
mIsRepeatableKey = false;
mIsInSlidingKeyInput = false;
checkMultiTap(eventTime, keyIndex);
if (mListener != null) {
if (isValidKeyIndex(keyIndex)) {
Key key = mKeys[keyIndex];
if (key.codes != null) mListener.onPress(key.getPrimaryCode());
// This onPress call may have changed keyboard layout. Those cases are detected at
// {@link #setKeyboard}. In those cases, we should update keyIndex according to the
// new keyboard layout.
if (mKeyboardLayoutHasBeenChanged) {
mKeyboardLayoutHasBeenChanged = false;
keyIndex = mKeyState.onDownKey(x, y, eventTime);
}
}
}
if (isValidKeyIndex(keyIndex)) {
if (mKeys[keyIndex].repeatable) {
repeatKey(keyIndex);
mHandler.startKeyRepeatTimer(mDelayBeforeKeyRepeatStart, keyIndex, this);
mIsRepeatableKey = true;
}
startLongPressTimer(keyIndex);
}
showKeyPreviewAndUpdateKey(keyIndex);
}
private static void addSlideKey(Key key) {
if (!sSlideKeyHack || LatinIME.sKeyboardSettings.sendSlideKeys == 0) return;
if (key == null) return;
if (key.modifier) {
clearSlideKeys();
} else {
sSlideKeys.add(key);
}
}
/*package*/ static void clearSlideKeys() {
sSlideKeys.clear();
}
void sendSlideKeys() {
if (!sSlideKeyHack) return;
int slideMode = LatinIME.sKeyboardSettings.sendSlideKeys;
if ((slideMode & 4) > 0) {
// send all
for (Key key : sSlideKeys) {
detectAndSendKey(key, key.x, key.y, -1);
}
} else {
// Send first and/or last key only.
int n = sSlideKeys.size();
if (n > 0 && (slideMode & 1) > 0) {
Key key = sSlideKeys.get(0);
detectAndSendKey(key, key.x, key.y, -1);
}
if (n > 1 && (slideMode & 2) > 0) {
Key key = sSlideKeys.get(n - 1);
detectAndSendKey(key, key.x, key.y, -1);
}
}
clearSlideKeys();
}
public void onMoveEvent(int x, int y, long eventTime) {
if (DEBUG_MOVE)
debugLog("onMoveEvent:", x, y);
if (mKeyAlreadyProcessed)
return;
final KeyState keyState = mKeyState;
int keyIndex = keyState.onMoveKey(x, y);
final Key oldKey = getKey(keyState.getKeyIndex());
if (isValidKeyIndex(keyIndex)) {
boolean isMinorMoveBounce = isMinorMoveBounce(x, y, keyIndex);
if (DEBUG_MOVE) Log.i(TAG, "isMinorMoveBounce=" +isMinorMoveBounce + " oldKey=" + (oldKey== null ? "null" : oldKey));
if (oldKey == null) {
// The pointer has been slid in to the new key, but the finger was not on any keys.
// In this case, we must call onPress() to notify that the new key is being pressed.
if (mListener != null) {
Key key = getKey(keyIndex);
if (key.codes != null) mListener.onPress(key.getPrimaryCode());
// This onPress call may have changed keyboard layout. Those cases are detected
// at {@link #setKeyboard}. In those cases, we should update keyIndex according
// to the new keyboard layout.
if (mKeyboardLayoutHasBeenChanged) {
mKeyboardLayoutHasBeenChanged = false;
keyIndex = keyState.onMoveKey(x, y);
}
}
keyState.onMoveToNewKey(keyIndex, x, y);
startLongPressTimer(keyIndex);
} else if (!isMinorMoveBounce) {
// The pointer has been slid in to the new key from the previous key, we must call
// onRelease() first to notify that the previous key has been released, then call
// onPress() to notify that the new key is being pressed.
mIsInSlidingKeyInput = true;
if (mListener != null && oldKey.codes != null)
mListener.onRelease(oldKey.getPrimaryCode());
resetMultiTap();
if (mListener != null) {
Key key = getKey(keyIndex);
if (key.codes != null) mListener.onPress(key.getPrimaryCode());
// This onPress call may have changed keyboard layout. Those cases are detected
// at {@link #setKeyboard}. In those cases, we should update keyIndex according
// to the new keyboard layout.
if (mKeyboardLayoutHasBeenChanged) {
mKeyboardLayoutHasBeenChanged = false;
keyIndex = keyState.onMoveKey(x, y);
}
addSlideKey(oldKey);
}
keyState.onMoveToNewKey(keyIndex, x, y);
startLongPressTimer(keyIndex);
}
} else {
if (oldKey != null && !isMinorMoveBounce(x, y, keyIndex)) {
// The pointer has been slid out from the previous key, we must call onRelease() to
// notify that the previous key has been released.
mIsInSlidingKeyInput = true;
if (mListener != null && oldKey.codes != null)
mListener.onRelease(oldKey.getPrimaryCode());
resetMultiTap();
keyState.onMoveToNewKey(keyIndex, x ,y);
mHandler.cancelLongPressTimer();
}
}
showKeyPreviewAndUpdateKey(keyState.getKeyIndex());
}
public void onUpEvent(int x, int y, long eventTime) {
if (DEBUG)
debugLog("onUpEvent :", x, y);
mHandler.cancelKeyTimers();
mHandler.cancelPopupPreview();
showKeyPreviewAndUpdateKey(NOT_A_KEY);
mIsInSlidingKeyInput = false;
sendSlideKeys();
if (mKeyAlreadyProcessed)
return;
int keyIndex = mKeyState.onUpKey(x, y);
if (isMinorMoveBounce(x, y, keyIndex)) {
// Use previous fixed key index and coordinates.
keyIndex = mKeyState.getKeyIndex();
x = mKeyState.getKeyX();
y = mKeyState.getKeyY();
}
if (!mIsRepeatableKey) {
detectAndSendKey(keyIndex, x, y, eventTime);
}
if (isValidKeyIndex(keyIndex))
mProxy.invalidateKey(mKeys[keyIndex]);
}
public void onCancelEvent(int x, int y, long eventTime) {
if (DEBUG)
debugLog("onCancelEvt:", x, y);
mHandler.cancelKeyTimers();
mHandler.cancelPopupPreview();
showKeyPreviewAndUpdateKey(NOT_A_KEY);
mIsInSlidingKeyInput = false;
int keyIndex = mKeyState.getKeyIndex();
if (isValidKeyIndex(keyIndex))
mProxy.invalidateKey(mKeys[keyIndex]);
}
public void repeatKey(int keyIndex) {
Key key = getKey(keyIndex);
if (key != null) {
// While key is repeating, because there is no need to handle multi-tap key, we can
// pass -1 as eventTime argument.
detectAndSendKey(keyIndex, key.x, key.y, -1);
}
}
public int getLastX() {
return mKeyState.getLastX();
}
public int getLastY() {
return mKeyState.getLastY();
}
public long getDownTime() {
return mKeyState.getDownTime();
}
// These package scope methods are only for debugging purpose.
/* package */ int getStartX() {
return mKeyState.getStartX();
}
/* package */ int getStartY() {
return mKeyState.getStartY();
}
private boolean isMinorMoveBounce(int x, int y, int newKey) {
if (mKeys == null || mKeyHysteresisDistanceSquared < 0)
throw new IllegalStateException("keyboard and/or hysteresis not set");
int curKey = mKeyState.getKeyIndex();
if (newKey == curKey) {
return true;
} else if (isValidKeyIndex(curKey)) {
//return false; // TODO(klausw): tweak this?
return getSquareDistanceToKeyEdge(x, y, mKeys[curKey]) < mKeyHysteresisDistanceSquared;
} else {
return false;
}
}
private static int getSquareDistanceToKeyEdge(int x, int y, Key key) {
final int left = key.x;
final int right = key.x + key.width;
final int top = key.y;
final int bottom = key.y + key.height;
final int edgeX = x < left ? left : (x > right ? right : x);
final int edgeY = y < top ? top : (y > bottom ? bottom : y);
final int dx = x - edgeX;
final int dy = y - edgeY;
return dx * dx + dy * dy;
}
private void showKeyPreviewAndUpdateKey(int keyIndex) {
updateKey(keyIndex);
// The modifier key, such as shift key, should not be shown as preview when multi-touch is
// supported. On the other hand, if multi-touch is not supported, the modifier key should
// be shown as preview.
if (mHasDistinctMultitouch && isModifier()) {
mProxy.showPreview(NOT_A_KEY, this);
} else {
mProxy.showPreview(keyIndex, this);
}
}
private void startLongPressTimer(int keyIndex) {
if (mKeyboardSwitcher.isInMomentaryAutoModeSwitchState()) {
// We use longer timeout for sliding finger input started from the symbols mode key.
mHandler.startLongPressTimer(LatinIME.sKeyboardSettings.longpressTimeout * 3, keyIndex, this);
} else {
mHandler.startLongPressTimer(LatinIME.sKeyboardSettings.longpressTimeout, keyIndex, this);
}
}
private void detectAndSendKey(int index, int x, int y, long eventTime) {
detectAndSendKey(getKey(index), x, y, eventTime);
mLastSentIndex = index;
}
private void detectAndSendKey(Key key, int x, int y, long eventTime) {
final OnKeyboardActionListener listener = mListener;
if (key == null) {
if (listener != null)
listener.onCancel();
} else {
if (key.text != null) {
if (listener != null) {
listener.onText(key.text);
listener.onRelease(0); // dummy key code
}
} else {
if (key.codes == null) return;
int code = key.getPrimaryCode();
int[] codes = mKeyDetector.newCodeArray();
mKeyDetector.getKeyIndexAndNearbyCodes(x, y, codes);
// Multi-tap
if (mInMultiTap) {
if (mTapCount != -1) {
mListener.onKey(Keyboard.KEYCODE_DELETE, KEY_DELETE, x, y);
} else {
mTapCount = 0;
}
code = key.codes[mTapCount];
}
/*
* Swap the first and second values in the codes array if the primary code is not
* the first value but the second value in the array. This happens when key
* debouncing is in effect.
*/
if (codes.length >= 2 && codes[0] != code && codes[1] == code) {
codes[1] = codes[0];
codes[0] = code;
}
if (listener != null) {
listener.onKey(code, codes, x, y);
listener.onRelease(code);
}
}
mLastTapTime = eventTime;
}
}
/**
* Handle multi-tap keys by producing the key label for the current multi-tap state.
*/
public CharSequence getPreviewText(Key key) {
if (mInMultiTap) {
// Multi-tap
mPreviewLabel.setLength(0);
mPreviewLabel.append((char) key.codes[mTapCount < 0 ? 0 : mTapCount]);
return mPreviewLabel;
} else {
if (key.isDeadKey()) {
return DeadAccentSequence.normalize(" " + key.label);
} else {
return key.label;
}
}
}
private void resetMultiTap() {
mLastSentIndex = NOT_A_KEY;
mTapCount = 0;
mLastTapTime = -1;
mInMultiTap = false;
}
private void checkMultiTap(long eventTime, int keyIndex) {
Key key = getKey(keyIndex);
if (key == null || key.codes == null)
return;
final boolean isMultiTap =
(eventTime < mLastTapTime + mMultiTapKeyTimeout && keyIndex == mLastSentIndex);
if (key.codes.length > 1) {
mInMultiTap = true;
if (isMultiTap) {
mTapCount = (mTapCount + 1) % key.codes.length;
return;
} else {
mTapCount = -1;
return;
}
}
if (!isMultiTap) {
resetMultiTap();
}
}
private void debugLog(String title, int x, int y) {
int keyIndex = mKeyDetector.getKeyIndexAndNearbyCodes(x, y, null);
Key key = getKey(keyIndex);
final String code;
if (key == null || key.codes == null) {
code = "----";
} else {
int primaryCode = key.codes[0];
code = String.format((primaryCode < 0) ? "%4d" : "0x%02x", primaryCode);
}
Log.d(TAG, String.format("%s%s[%d] %3d,%3d %3d(%s) %s", title,
(mKeyAlreadyProcessed ? "-" : " "), mPointerId, x, y, keyIndex, code,
(isModifier() ? "modifier" : "")));
}
}
| 11beeaosama-descrbvbnvbniption | java/src/org/pocketworkstation/pckeyboard/PointerTracker.java | Java | asf20 | 23,344 |
/*
* Copyright (C) 2011 Darren Salt
*
* Licensed under the Apache License, Version 2.0 (the "Licence"); you may
* not use this file except in compliance with the Licence. You may obtain
* a copy of the Licence at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the Licence is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* Licence for the specific language governing permissions and limitations
* under the Licence.
*/
package org.pocketworkstation.pckeyboard;
import java.text.Normalizer;
import android.util.Log;
public class DeadAccentSequence extends ComposeBase {
private static final String TAG = "HK/DeadAccent";
public DeadAccentSequence(ComposeSequencing user) {
init(user);
}
private static void putAccent(String nonSpacing, String spacing, String ascii) {
if (ascii == null) ascii = spacing;
put("" + nonSpacing + " ", ascii);
put(nonSpacing + nonSpacing, spacing);
put(Keyboard.DEAD_KEY_PLACEHOLDER + nonSpacing, spacing);
}
public static String getSpacing(char nonSpacing) {
String spacing = get("" + Keyboard.DEAD_KEY_PLACEHOLDER + nonSpacing);
if (spacing == null) spacing = DeadAccentSequence.normalize(" " + nonSpacing);
if (spacing == null) return "" + nonSpacing;
return spacing;
}
static {
// space + combining diacritical
// cf. http://unicode.org/charts/PDF/U0300.pdf
putAccent("\u0300", "\u02cb", "`"); // grave
putAccent("\u0301", "\u02ca", "´"); // acute
putAccent("\u0302", "\u02c6", "^"); // circumflex
putAccent("\u0303", "\u02dc", "~"); // small tilde
putAccent("\u0304", "\u02c9", "¯"); // macron
putAccent("\u0305", "\u00af", "¯"); // overline
putAccent("\u0306", "\u02d8", null); // breve
putAccent("\u0307", "\u02d9", null); // dot above
putAccent("\u0308", "\u00a8", "¨"); // diaeresis
putAccent("\u0309", "\u02c0", null); // hook above
putAccent("\u030a", "\u02da", "°"); // ring above
putAccent("\u030b", "\u02dd", "\""); // double acute
putAccent("\u030c", "\u02c7", null); // caron
putAccent("\u030d", "\u02c8", null); // vertical line above
putAccent("\u030e", "\"", "\""); // double vertical line above
putAccent("\u0313", "\u02bc", null); // comma above
putAccent("\u0314", "\u02bd", null); // reversed comma above
put("\u0308\u0301\u03b9", "\u0390"); // Greek Dialytika+Tonos, iota
put("\u0301\u0308\u03b9", "\u0390"); // Greek Dialytika+Tonos, iota
put("\u0301\u03ca", "\u0390"); // Greek Dialytika+Tonos, iota
put("\u0308\u0301\u03c5", "\u03b0"); // Greek Dialytika+Tonos, upsilon
put("\u0301\u0308\u03c5", "\u03b0"); // Greek Dialytika+Tonos, upsilon
put("\u0301\u03cb", "\u03b0"); // Greek Dialytika+Tonos, upsilon
/*
// include?
put("̃ ", "~");
put("̃̃", "~");
put("́ ", "'");
put("́́", "´");
put("̀ ", "`");
put("̀̀", "`");
put("̂ ", "^");
put("̂̂", "^");
put("̊ ", "°");
put("̊̊", "°");
put("̄ ", "¯");
put("̄̄", "¯");
put("̆ ", "˘");
put("̆̆", "˘");
put("̇ ", "˙");
put("̇̇", "˙");
put("̈̈", "¨");
put("̈ ", "\"");
put("̋ ", "˝");
put("̋̋", "˝");
put("̌ ", "ˇ");
put("̌̌", "ˇ");
put("̧ ", "¸");
put("̧̧", "¸");
put("̨ ", "˛");
put("̨̨", "˛");
put("̂2", "²");
put("̂3", "³");
put("̂1", "¹");
// include end?
put("̀A", "À");
put("́A", "Á");
put("̂A", "Â");
put("̃A", "Ã");
put("̈A", "Ä");
put("̊A", "Å");
put("̧C", "Ç");
put("̀E", "È");
put("́E", "É");
put("̂E", "Ê");
put("̈E", "Ë");
put("̀I", "Ì");
put("́I", "Í");
put("̂I", "Î");
put("̈I", "Ï");
put("̃N", "Ñ");
put("̀O", "Ò");
put("́O", "Ó");
put("̂O", "Ô");
put("̃O", "Õ");
put("̈O", "Ö");
put("̀U", "Ù");
put("́U", "Ú");
put("̂U", "Û");
put("̈U", "Ü");
put("́Y", "Ý");
put("̀a", "à");
put("́a", "á");
put("̂a", "â");
put("̃a", "ã");
put("̈a", "ä");
put("̊a", "å");
put("̧c", "ç");
put("̀e", "è");
put("́e", "é");
put("̂e", "ê");
put("̈e", "ë");
put("̀i", "ì");
put("́i", "í");
put("̂i", "î");
put("̈i", "ï");
put("̃n", "ñ");
put("̀o", "ò");
put("́o", "ó");
put("̂o", "ô");
put("̃o", "õ");
put("̈o", "ö");
put("̀u", "ù");
put("́u", "ú");
put("̂u", "û");
put("̈u", "ü");
put("́y", "ý");
put("̈y", "ÿ");
put("̄A", "Ā");
put("̄a", "ā");
put("̆A", "Ă");
put("̆a", "ă");
put("̨A", "Ą");
put("̨a", "ą");
put("́C", "Ć");
put("́c", "ć");
put("̂C", "Ĉ");
put("̂c", "ĉ");
put("̇C", "Ċ");
put("̇c", "ċ");
put("̌C", "Č");
put("̌c", "č");
put("̌D", "Ď");
put("̌d", "ď");
put("̄E", "Ē");
put("̄e", "ē");
put("̆E", "Ĕ");
put("̆e", "ĕ");
put("̇E", "Ė");
put("̇e", "ė");
put("̨E", "Ę");
put("̨e", "ę");
put("̌E", "Ě");
put("̌e", "ě");
put("̂G", "Ĝ");
put("̂g", "ĝ");
put("̆G", "Ğ");
put("̆g", "ğ");
put("̇G", "Ġ");
put("̇g", "ġ");
put("̧G", "Ģ");
put("̧g", "ģ");
put("̂H", "Ĥ");
put("̂h", "ĥ");
put("̃I", "Ĩ");
put("̃i", "ĩ");
put("̄I", "Ī");
put("̄i", "ī");
put("̆I", "Ĭ");
put("̆i", "ĭ");
put("̨I", "Į");
put("̨i", "į");
put("̇I", "İ");
put("̇i", "ı");
put("̂J", "Ĵ");
put("̂j", "ĵ");
put("̧K", "Ķ");
put("̧k", "ķ");
put("́L", "Ĺ");
put("́l", "ĺ");
put("̧L", "Ļ");
put("̧l", "ļ");
put("̌L", "Ľ");
put("̌l", "ľ");
put("́N", "Ń");
put("́n", "ń");
put("̧N", "Ņ");
put("̧n", "ņ");
put("̌N", "Ň");
put("̌n", "ň");
put("̄O", "Ō");
put("̄o", "ō");
put("̆O", "Ŏ");
put("̆o", "ŏ");
put("̋O", "Ő");
put("̋o", "ő");
put("́R", "Ŕ");
put("́r", "ŕ");
put("̧R", "Ŗ");
put("̧r", "ŗ");
put("̌R", "Ř");
put("̌r", "ř");
put("́S", "Ś");
put("́s", "ś");
put("̂S", "Ŝ");
put("̂s", "ŝ");
put("̧S", "Ş");
put("̧s", "ş");
put("̌S", "Š");
put("̌s", "š");
put("̧T", "Ţ");
put("̧t", "ţ");
put("̌T", "Ť");
put("̌t", "ť");
put("̃U", "Ũ");
put("̃u", "ũ");
put("̄U", "Ū");
put("̄u", "ū");
put("̆U", "Ŭ");
put("̆u", "ŭ");
put("̊U", "Ů");
put("̊u", "ů");
put("̋U", "Ű");
put("̋u", "ű");
put("̨U", "Ų");
put("̨u", "ų");
put("̂W", "Ŵ");
put("̂w", "ŵ");
put("̂Y", "Ŷ");
put("̂y", "ŷ");
put("̈Y", "Ÿ");
put("́Z", "Ź");
put("́z", "ź");
put("̇Z", "Ż");
put("̇z", "ż");
put("̌Z", "Ž");
put("̌z", "ž");
put("̛O", "Ơ");
put("̛o", "ơ");
put("̛U", "Ư");
put("̛u", "ư");
put("̌A", "Ǎ");
put("̌a", "ǎ");
put("̌I", "Ǐ");
put("̌i", "ǐ");
put("̌O", "Ǒ");
put("̌o", "ǒ");
put("̌U", "Ǔ");
put("̌u", "ǔ");
put("̄Ü", "Ǖ");
put("̄̈U", "Ǖ");
put("̄ü", "ǖ");
put("̄̈u", "ǖ");
put("́Ü", "Ǘ");
put("́̈U", "Ǘ");
put("́ü", "ǘ");
put("́̈u", "ǘ");
put("̌Ü", "Ǚ");
put("̌̈U", "Ǚ");
put("̌ü", "ǚ");
put("̌̈u", "ǚ");
put("̀Ü", "Ǜ");
put("̀̈U", "Ǜ");
put("̀ü", "ǜ");
put("̀̈u", "ǜ");
put("̄Ä", "Ǟ");
put("̄̈A", "Ǟ");
put("̄ä", "ǟ");
put("̄̈a", "ǟ");
put("̄Ȧ", "Ǡ");
put("̄̇A", "Ǡ");
put("̄ȧ", "ǡ");
put("̄̇a", "ǡ");
put("̄Æ", "Ǣ");
put("̄æ", "ǣ");
put("̌G", "Ǧ");
put("̌g", "ǧ");
put("̌K", "Ǩ");
put("̌k", "ǩ");
put("̨O", "Ǫ");
put("̨o", "ǫ");
put("̄Ǫ", "Ǭ");
put("̨̄O", "Ǭ");
put("̄ǫ", "ǭ");
put("̨̄o", "ǭ");
put("̌Ʒ", "Ǯ");
put("̌ʒ", "ǯ");
put("̌j", "ǰ");
put("́G", "Ǵ");
put("́g", "ǵ");
put("̀N", "Ǹ");
put("̀n", "ǹ");
put("́Å", "Ǻ");
put("́̊A", "Ǻ");
put("́å", "ǻ");
put("́̊a", "ǻ");
put("́Æ", "Ǽ");
put("́æ", "ǽ");
put("́Ø", "Ǿ");
put("́ø", "ǿ");
put("̏A", "Ȁ");
put("̏a", "ȁ");
put("̑A", "Ȃ");
put("̑a", "ȃ");
put("̏E", "Ȅ");
put("̏e", "ȅ");
put("̑E", "Ȇ");
put("̑e", "ȇ");
put("̏I", "Ȉ");
put("̏i", "ȉ");
put("̑I", "Ȋ");
put("̑i", "ȋ");
put("̏O", "Ȍ");
put("̏o", "ȍ");
put("̑O", "Ȏ");
put("̑o", "ȏ");
put("̏R", "Ȑ");
put("̏r", "ȑ");
put("̑R", "Ȓ");
put("̑r", "ȓ");
put("̏U", "Ȕ");
put("̏u", "ȕ");
put("̑U", "Ȗ");
put("̑u", "ȗ");
put("̌H", "Ȟ");
put("̌h", "ȟ");
put("̇A", "Ȧ");
put("̇a", "ȧ");
put("̧E", "Ȩ");
put("̧e", "ȩ");
put("̄Ö", "Ȫ");
put("̄̈O", "Ȫ");
put("̄ö", "ȫ");
put("̄̈o", "ȫ");
put("̄Õ", "Ȭ");
put("̄ ̃O", "Ȭ");
put("̄õ", "ȭ");
put("̄ ̃o", "ȭ");
put("̇O", "Ȯ");
put("̇o", "ȯ");
put("̄Ȯ", "Ȱ");
put("̄̇O", "Ȱ");
put("̄ȯ", "ȱ");
put("̄̇o", "ȱ");
put("̄Y", "Ȳ");
put("̄y", "ȳ");
put("̥A", "Ḁ");
put("̥a", "ḁ");
put("̇B", "Ḃ");
put("̇b", "ḃ");
put("̣B", "Ḅ");
put("̣b", "ḅ");
put("̱B", "Ḇ");
put("̱b", "ḇ");
put("́Ç", "Ḉ");
put("̧́C", "Ḉ");
put("́ç", "ḉ");
put("̧́c", "ḉ");
put("̇D", "Ḋ");
put("̇d", "ḋ");
put("̣D", "Ḍ");
put("̣d", "ḍ");
put("̱D", "Ḏ");
put("̱d", "ḏ");
put("̧D", "Ḑ");
put("̧d", "ḑ");
put("̭D", "Ḓ");
put("̭d", "ḓ");
put("̀Ē", "Ḕ");
put("̀ ̄E", "Ḕ");
put("̀ē", "ḕ");
put("̀ ̄e", "ḕ");
put("́Ē", "Ḗ");
put("́ ̄E", "Ḗ");
put("́ē", "ḗ");
put("́ ̄e", "ḗ");
put("̭E", "Ḙ");
put("̭e", "ḙ");
put("̰E", "Ḛ");
put("̰e", "ḛ");
put("̆Ȩ", "Ḝ");
put("̧̆E", "Ḝ");
put("̆ȩ", "ḝ");
put("̧̆e", "ḝ");
put("̇F", "Ḟ");
put("̇f", "ḟ");
put("̄G", "Ḡ");
put("̄g", "ḡ");
put("̇H", "Ḣ");
put("̇h", "ḣ");
put("̣H", "Ḥ");
put("̣h", "ḥ");
put("̈H", "Ḧ");
put("̈h", "ḧ");
put("̧H", "Ḩ");
put("̧h", "ḩ");
put("̮H", "Ḫ");
put("̮h", "ḫ");
put("̰I", "Ḭ");
put("̰i", "ḭ");
put("́Ï", "Ḯ");
put("́̈I", "Ḯ");
put("́ï", "ḯ");
put("́̈i", "ḯ");
put("́K", "Ḱ");
put("́k", "ḱ");
put("̣K", "Ḳ");
put("̣k", "ḳ");
put("̱K", "Ḵ");
put("̱k", "ḵ");
put("̣L", "Ḷ");
put("̣l", "ḷ");
put("̄Ḷ", "Ḹ");
put("̣̄L", "Ḹ");
put("̄ḷ", "ḹ");
put("̣̄l", "ḹ");
put("̱L", "Ḻ");
put("̱l", "ḻ");
put("̭L", "Ḽ");
put("̭l", "ḽ");
put("́M", "Ḿ");
put("́m", "ḿ");
put("̇M", "Ṁ");
put("̇m", "ṁ");
put("̣M", "Ṃ");
put("̣m", "ṃ");
put("̇N", "Ṅ");
put("̇n", "ṅ");
put("̣N", "Ṇ");
put("̣n", "ṇ");
put("̱N", "Ṉ");
put("̱n", "ṉ");
put("̭N", "Ṋ");
put("̭n", "ṋ");
put("́Õ", "Ṍ");
put("́ ̃O", "Ṍ");
put("́õ", "ṍ");
put("́ ̃o", "ṍ");
put("̈Õ", "Ṏ");
put("̈ ̃O", "Ṏ");
put("̈õ", "ṏ");
put("̈ ̃o", "ṏ");
put("̀Ō", "Ṑ");
put("̀ ̄O", "Ṑ");
put("̀ō", "ṑ");
put("̀ ̄o", "ṑ");
put("́Ō", "Ṓ");
put("́ ̄O", "Ṓ");
put("́ō", "ṓ");
put("́ ̄o", "ṓ");
put("́P", "Ṕ");
put("́p", "ṕ");
put("̇P", "Ṗ");
put("̇p", "ṗ");
put("̇R", "Ṙ");
put("̇r", "ṙ");
put("̣R", "Ṛ");
put("̣r", "ṛ");
put("̄Ṛ", "Ṝ");
put("̣̄R", "Ṝ");
put("̄ṛ", "ṝ");
put("̣̄r", "ṝ");
put("̱R", "Ṟ");
put("̱r", "ṟ");
put("̇S", "Ṡ");
put("̇s", "ṡ");
put("̣S", "Ṣ");
put("̣s", "ṣ");
put("̇Ś", "Ṥ");
put("̇ ́S", "Ṥ");
put("̇ś", "ṥ");
put("̇ ́s", "ṥ");
put("̇Š", "Ṧ");
put("̇̌S", "Ṧ");
put("̇š", "ṧ");
put("̇̌s", "ṧ");
put("̇Ṣ", "Ṩ");
put("̣̇S", "Ṩ");
put("̇ṣ", "ṩ");
put("̣̇s", "ṩ");
put("̇T", "Ṫ");
put("̇t", "ṫ");
put("̣T", "Ṭ");
put("̣t", "ṭ");
put("̱T", "Ṯ");
put("̱t", "ṯ");
put("̭T", "Ṱ");
put("̭t", "ṱ");
put("̤U", "Ṳ");
put("̤u", "ṳ");
put("̰U", "Ṵ");
put("̰u", "ṵ");
put("̭U", "Ṷ");
put("̭u", "ṷ");
put("́Ũ", "Ṹ");
put("́ ̃U", "Ṹ");
put("́ũ", "ṹ");
put("́ ̃u", "ṹ");
put("̈Ū", "Ṻ");
put("̈ ̄U", "Ṻ");
put("̈ū", "ṻ");
put("̈ ̄u", "ṻ");
put("̃V", "Ṽ");
put("̃v", "ṽ");
put("̣V", "Ṿ");
put("̣v", "ṿ");
put("̀W", "Ẁ");
put("̀w", "ẁ");
put("́W", "Ẃ");
put("́w", "ẃ");
put("̈W", "Ẅ");
put("̈w", "ẅ");
put("̇W", "Ẇ");
put("̇w", "ẇ");
put("̣W", "Ẉ");
put("̣w", "ẉ");
put("̇X", "Ẋ");
put("̇x", "ẋ");
put("̈X", "Ẍ");
put("̈x", "ẍ");
put("̇Y", "Ẏ");
put("̇y", "ẏ");
put("̂Z", "Ẑ");
put("̂z", "ẑ");
put("̣Z", "Ẓ");
put("̣z", "ẓ");
put("̱Z", "Ẕ");
put("̱z", "ẕ");
put("̱h", "ẖ");
put("̈t", "ẗ");
put("̊w", "ẘ");
put("̊y", "ẙ");
put("̇ſ", "ẛ");
put("̣A", "Ạ");
put("̣a", "ạ");
put("̉A", "Ả");
put("̉a", "ả");
put("́Â", "Ấ");
put("́ ̂A", "Ấ");
put("́â", "ấ");
put("́ ̂a", "ấ");
put("̀Â", "Ầ");
put("̀ ̂A", "Ầ");
put("̀â", "ầ");
put("̀ ̂a", "ầ");
put("̉Â", "Ẩ");
put("̉ ̂A", "Ẩ");
put("̉â", "ẩ");
put("̉ ̂a", "ẩ");
put("̃Â", "Ẫ");
put("̃ ̂A", "Ẫ");
put("̃â", "ẫ");
put("̃ ̂a", "ẫ");
put("̂Ạ", "Ậ");
put("̣̂A", "Ậ");
put("̣Â", "Ậ");
put("̂ạ", "ậ");
put("̣̂a", "ậ");
put("̣â", "ậ");
put("́Ă", "Ắ");
put("́̆A", "Ắ");
put("́ă", "ắ");
put("́̆a", "ắ");
put("̀Ă", "Ằ");
put("̀̆A", "Ằ");
put("̀ă", "ằ");
put("̀̆a", "ằ");
put("̉Ă", "Ẳ");
put("̉̆A", "Ẳ");
put("̉ă", "ẳ");
put("̉̆a", "ẳ");
put("̃Ă", "Ẵ");
put("̃̆A", "Ẵ");
put("̃ă", "ẵ");
put("̃̆a", "ẵ");
put("̆Ạ", "Ặ");
put("̣̆A", "Ặ");
put("̣Ă", "Ặ");
put("̆ạ", "ặ");
put("̣̆a", "ặ");
put("̣ă", "ặ");
put("̣E", "Ẹ");
put("̣e", "ẹ");
put("̉E", "Ẻ");
put("̉e", "ẻ");
put("̃E", "Ẽ");
put("̃e", "ẽ");
put("́Ê", "Ế");
put("́ ̂E", "Ế");
put("́ê", "ế");
put("́ ̂e", "ế");
put("̀Ê", "Ề");
put("̀ ̂E", "Ề");
put("̀ê", "ề");
put("̀ ̂e", "ề");
put("̉Ê", "Ể");
put("̉ ̂E", "Ể");
put("̉ê", "ể");
put("̉ ̂e", "ể");
put("̃Ê", "Ễ");
put("̃ ̂E", "Ễ");
put("̃ê", "ễ");
put("̃ ̂e", "ễ");
put("̂Ẹ", "Ệ");
put("̣̂E", "Ệ");
put("̣Ê", "Ệ");
put("̂ẹ", "ệ");
put("̣̂e", "ệ");
put("̣ê", "ệ");
put("̉I", "Ỉ");
put("̉i", "ỉ");
put("̣I", "Ị");
put("̣i", "ị");
put("̣O", "Ọ");
put("̣o", "ọ");
put("̉O", "Ỏ");
put("̉o", "ỏ");
put("́Ô", "Ố");
put("́ ̂O", "Ố");
put("́ô", "ố");
put("́ ̂o", "ố");
put("̀Ô", "Ồ");
put("̀ ̂O", "Ồ");
put("̀ô", "ồ");
put("̀ ̂o", "ồ");
put("̉Ô", "Ổ");
put("̉ ̂O", "Ổ");
put("̉ô", "ổ");
put("̉ ̂o", "ổ");
put("̃Ô", "Ỗ");
put("̃ ̂O", "Ỗ");
put("̃ô", "ỗ");
put("̃ ̂o", "ỗ");
put("̂Ọ", "Ộ");
put("̣̂O", "Ộ");
put("̣Ô", "Ộ");
put("̂ọ", "ộ");
put("̣̂o", "ộ");
put("̣ô", "ộ");
put("́Ơ", "Ớ");
put("̛́O", "Ớ");
put("́ơ", "ớ");
put("̛́o", "ớ");
put("̀Ơ", "Ờ");
put("̛̀O", "Ờ");
put("̀ơ", "ờ");
put("̛̀o", "ờ");
put("̉Ơ", "Ở");
put("̛̉O", "Ở");
put("̉ơ", "ở");
put("̛̉o", "ở");
put("̃Ơ", "Ỡ");
put("̛̃O", "Ỡ");
put("̃ơ", "ỡ");
put("̛̃o", "ỡ");
put("̣Ơ", "Ợ");
put("̛̣O", "Ợ");
put("̣ơ", "ợ");
put("̛̣o", "ợ");
put("̣U", "Ụ");
put("̣u", "ụ");
put("̉U", "Ủ");
put("̉u", "ủ");
put("́Ư", "Ứ");
put("̛́U", "Ứ");
put("́ư", "ứ");
put("̛́u", "ứ");
put("̀Ư", "Ừ");
put("̛̀U", "Ừ");
put("̀ư", "ừ");
put("̛̀u", "ừ");
put("̉Ư", "Ử");
put("̛̉U", "Ử");
put("̉ư", "ử");
put("̛̉u", "ử");
put("̃Ư", "Ữ");
put("̛̃U", "Ữ");
put("̃ư", "ữ");
put("̛̃u", "ữ");
put("̣Ư", "Ự");
put("̛̣U", "Ự");
put("̣ư", "ự");
put("̛̣u", "ự");
put("̀Y", "Ỳ");
put("̀y", "ỳ");
put("̣Y", "Ỵ");
put("̣y", "ỵ");
put("̉Y", "Ỷ");
put("̉y", "ỷ");
put("̃Y", "Ỹ");
put("̃y", "ỹ");
// include?
put("̂0", "⁰");
put("̂4", "⁴");
put("̂5", "⁵");
put("̂6", "⁶");
put("̂7", "⁷");
put("̂8", "⁸");
put("̂9", "⁹");
put("̂+", "⁺");
put("̂−", "⁻");
put("̂=", "⁼");
put("̂(", "⁽");
put("̂)", "⁾");
put("̣+", "⨥");
put("̰+", "⨦");
put("̣-", "⨪");
put("̣=", "⩦");
put("̤̈=", "⩷");
put("̤̈=", "⩷");
// include end?
put("̥|", "⫰");
put("̇Ā", "Ǡ");
put("̇ā", "ǡ");
put("̇j", "ȷ");
put("̇L", "Ŀ");
put("̇l", "ŀ");
put("̇Ō", "Ȱ");
put("̇ō", "ȱ");
put("́Ṡ", "Ṥ");
put("́ṡ", "ṥ");
put("́V", "Ǘ");
put("́v", "ǘ");
put("̣Ṡ", "Ṩ");
put("̣ṡ", "ṩ");
put("̣̣", "̣");
put("̣ ", "̣");
put("̆Á", "Ắ");
put("̆À", "Ằ");
put("̆Ả", "Ẳ");
put("̆Ã", "Ẵ");
put("̆a", "ắ");
put("̆à", "ằ");
put("̆ả", "ẳ");
put("̆ã", "ẵ");
// include?
put("̌(", "₍");
put("̌)", "₎");
put("̌+", "₊");
put("̌-", "₋");
put("̌0", "₀");
put("̌1", "₁");
put("̌2", "₂");
put("̌3", "₃");
put("̌4", "₄");
put("̌5", "₅");
put("̌6", "₆");
put("̌7", "₇");
put("̌8", "₈");
put("̌9", "₉");
put("̌=", "₌");
// include end?
put("̌Dz", "Dž");
put("̌Ṡ", "Ṧ");
put("̌ṡ", "ṧ");
put("̌V", "Ǚ");
put("̌v", "ǚ");
put("̧C", "Ḉ");
put("̧c", "ḉ");
put("̧¢", "₵");
put("̧Ĕ", "Ḝ");
put("̧ĕ", "ḝ");
put("̂-", "⁻");
put("̂Á", "Ấ");
put("̂À", "Ầ");
put("̂Ả", "Ẩ");
put("̂Ã", "Ẫ");
put("̂á", "ấ");
put("̂à", "ầ");
put("̂ả", "ẩ");
put("̂ã", "ẫ");
put("̂É", "Ế");
put("̂È", "Ề");
put("̂Ẻ", "Ể");
put("̂Ẽ", "Ễ");
put("̂é", "ế");
put("̂è", "ề");
put("̂ẻ", "ể");
put("̂ẽ", "ễ");
put("̂Ó", "Ố");
put("̂Ò", "Ồ");
put("̂Ỏ", "Ổ");
put("̂Õ", "Ỗ");
put("̂ó", "ố");
put("̂ò", "ồ");
put("̂ỏ", "ổ");
put("̂õ", "ỗ");
put("̦S", "Ș");
put("̦s", "ș");
put("̦T", "Ț");
put("̦t", "ț");
put("̦̦", ",");
put("̦ ", ",");
put("̈Ā", "Ǟ");
put("̈ā", "ǟ");
put("̈Í", "Ḯ");
put("̈í", "ḯ");
put("̈Ō", "Ȫ");
put("̈ō", "ȫ");
put("̈Ú", "Ǘ");
put("̈Ǔ", "Ǚ");
put("̈Ù", "Ǜ");
put("̈ú", "ǘ");
put("̈ǔ", "ǚ");
put("̈ù", "ǜ");
put("̀V", "Ǜ");
put("̀v", "ǜ");
put("̉B", "Ɓ");
put("̉b", "ɓ");
put("̉C", "Ƈ");
put("̉c", "ƈ");
put("̉D", "Ɗ");
put("̉d", "ɗ");
put("̉ɖ", "ᶑ");
put("̉F", "Ƒ");
put("̉f", "ƒ");
put("̉G", "Ɠ");
put("̉g", "ɠ");
put("̉h", "ɦ");
put("̉ɟ", "ʄ");
put("̉K", "Ƙ");
put("̉k", "ƙ");
put("̉M", "Ɱ");
put("̉m", "ɱ");
put("̉N", "Ɲ");
put("̉n", "ɲ");
put("̉P", "Ƥ");
put("̉p", "ƥ");
put("̉q", "ʠ");
put("̉ɜ", "ɝ");
put("̉s", "ʂ");
put("̉ə", "ɚ");
put("̉T", "Ƭ");
put("̉t", "ƭ");
put("̉ɹ", "ɻ");
put("̉V", "Ʋ");
put("̉v", "ʋ");
put("̉W", "Ⱳ");
put("̉w", "ⱳ");
put("̉Z", "Ȥ");
put("̉z", "ȥ");
put("̉̉", "̉");
put("̉ ", "̉");
put("̛Ó", "Ớ");
put("̛O", "Ợ");
put("̛Ò", "Ờ");
put("̛Ỏ", "Ở");
put("̛Õ", "Ỡ");
put("̛ó", "ớ");
put("̛ọ", "ợ");
put("̛ò", "ờ");
put("̛ỏ", "ở");
put("̛õ", "ỡ");
put("̛Ú", "Ứ");
put("̛Ụ", "Ự");
put("̛Ù", "Ừ");
put("̛Ủ", "Ử");
put("̛Ũ", "Ữ");
put("̛ú", "ứ");
put("̛ụ", "ự");
put("̛ù", "ừ");
put("̛ủ", "ử");
put("̛ũ", "ữ");
put("̛̛", "̛");
put("̛ ", "̛");
put("̄É", "Ḗ");
put("̄È", "Ḕ");
put("̄é", "ḗ");
put("̄è", "ḕ");
put("̄Ó", "Ṓ");
put("̄Ò", "Ṑ");
put("̄ó", "ṓ");
put("̄ò", "ṑ");
put("̄V", "Ǖ");
put("̄v", "ǖ");
put("̨Ō", "Ǭ");
put("̨ō", "ǭ");
put("̊Á", "Ǻ");
put("̊á", "ǻ");
put("̃Ó", "Ṍ");
put("̃Ö", "Ṏ");
put("̃Ō", "Ȭ");
put("̃ó", "ṍ");
put("̃ö", "ṏ");
put("̃ō", "ȭ");
put("̃Ú", "Ṹ");
put("̃ú", "ṹ");
put("̃=", "≃");
put("̃<", "≲");
put("̃>", "≳");
put("́̇S", "Ṥ");
put("́̇s", "ṥ");
put("̣̇S", "Ṩ");
put("̣̇s", "ṩ");
put("̌̇S", "Ṧ");
put("̌̇s", "ṧ");
put("̇ ̄A", "Ǡ");
put("̇ ̄a", "ǡ");
put("̇ ̄O", "Ȱ");
put("̇ ̄o", "ȱ");
put("̆ ́A", "Ắ");
put("̆ ́a", "ắ");
put("̧ ́C", "Ḉ");
put("̧ ́c", "ḉ");
put("̂ ́A", "Ấ");
put("̂ ́a", "ấ");
put("̂ ́E", "Ế");
put("̂ ́e", "ế");
put("̂ ́O", "Ố");
put("̂ ́o", "ố");
put("̈ ́I", "Ḯ");
put("̈ ́i", "ḯ");
put("̈ ́U", "Ǘ");
put("̈ ́u", "ǘ");
put("̛ ́O", "Ớ");
put("̛ ́o", "ớ");
put("̛ ́U", "Ứ");
put("̛ ́u", "ứ");
put("̄ ́E", "Ḗ");
put("̄ ́e", "ḗ");
put("̄ ́O", "Ṓ");
put("̄ ́o", "ṓ");
put("̊ ́A", "Ǻ");
put("̊ ́a", "ǻ");
put("̃ ́O", "Ṍ");
put("̃ ́o", "ṍ");
put("̃ ́U", "Ṹ");
put("̃ ́u", "ṹ");
put("̣̆A", "Ặ");
put("̣̆a", "ặ");
put("̣ ̂A", "Ậ");
put("̣ ̂a", "ậ");
put("̣ ̂E", "Ệ");
put("̣ ̂e", "ệ");
put("̣ ̂O", "Ộ");
put("̣ ̂o", "ộ");
put("̛̣O", "Ợ");
put("̛̣o", "ợ");
put("̛̣U", "Ự");
put("̛̣u", "ự");
put("̣ ̄L", "Ḹ");
put("̣ ̄l", "ḹ");
put("̣ ̄R", "Ṝ");
put("̣ ̄r", "ṝ");
put("̧̆E", "Ḝ");
put("̧̆e", "ḝ");
put("̆ ̀A", "Ằ");
put("̆ ̀a", "ằ");
put("̆̉A", "Ẳ");
put("̆̉a", "ẳ");
put("̆ ̃A", "Ẵ");
put("̆ ̃a", "ẵ");
put("̈̌U", "Ǚ");
put("̈̌u", "ǚ");
put("̂ ̀A", "Ầ");
put("̂ ̀a", "ầ");
put("̂ ̀E", "Ề");
put("̂ ̀e", "ề");
put("̂ ̀O", "Ồ");
put("̂ ̀o", "ồ");
put("̂̉A", "Ẩ");
put("̂̉a", "ẩ");
put("̂̉E", "Ể");
put("̂̉e", "ể");
put("̂̉O", "Ổ");
put("̂̉o", "ổ");
put("̂ ̃A", "Ẫ");
put("̂ ̃a", "ẫ");
put("̂ ̃E", "Ễ");
put("̂ ̃e", "ễ");
put("̂ ̃O", "Ỗ");
put("̂ ̃o", "ỗ");
put("̈ ̀U", "Ǜ");
put("̈ ̀u", "ǜ");
put("̈ ̄A", "Ǟ");
put("̈ ̄a", "ǟ");
put("̈ ̄O", "Ȫ");
put("̈ ̄o", "ȫ");
put("̃̈O", "Ṏ");
put("̃̈o", "ṏ");
put("̛ ̀O", "Ờ");
put("̛ ̀o", "ờ");
put("̛ ̀U", "Ừ");
put("̛ ̀u", "ừ");
put("̄ ̀E", "Ḕ");
put("̄ ̀e", "ḕ");
put("̄ ̀O", "Ṑ");
put("̄ ̀o", "ṑ");
put("̛̉O", "Ở");
put("̛̉o", "ở");
put("̛̉U", "Ử");
put("̛̉u", "ử");
put("̛ ̃O", "Ỡ");
put("̛ ̃o", "ỡ");
put("̛ ̃U", "Ữ");
put("̛ ̃u", "ữ");
put("̨ ̄O", "Ǭ");
put("̨ ̄o", "ǭ");
put("̃ ̄O", "Ȭ");
put("̃ ̄o", "ȭ");
*/
}
public static String normalize(String input) {
String lookup = mMap.get(input);
if (lookup != null) return lookup;
return Normalizer.normalize(input, Normalizer.Form.NFC);
}
public boolean execute(int code) {
String composed = executeToString(code);
if (composed != null) {
//Log.i(TAG, "composed=" + composed + " len=" + composed.length());
if (composed.equals("")) {
// Unrecognised - try to use the built-in Java text normalisation
int c = composeBuffer.codePointAt(composeBuffer.length() - 1);
if (Character.getType(c) != Character.NON_SPACING_MARK) {
// Put the combining character(s) at the end, else this won't work
composeBuffer.reverse();
composed = Normalizer.normalize(composeBuffer.toString(), Normalizer.Form.NFC);
if (composed.equals("")) {
return true; // incomplete :-)
}
} else {
return true; // there may be multiple combining accents
}
}
clear();
composeUser.onText(composed);
return false;
}
return true;
}
}
| 11beeaosama-descrbvbnvbniption | java/src/org/pocketworkstation/pckeyboard/DeadAccentSequence.java | Java | asf20 | 30,433 |
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import org.pocketworkstation.pckeyboard.LatinIMEUtil.RingCharBuffer;
import com.google.android.voiceime.VoiceRecognitionTrigger;
import org.xmlpull.v1.XmlPullParserException;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.content.res.XmlResourceParser;
import android.inputmethodservice.InputMethodService;
import android.media.AudioManager;
import android.os.Debug;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.SystemClock;
import android.os.Vibrator;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.speech.SpeechRecognizer;
import android.text.ClipboardManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.PrintWriterPrinter;
import android.util.Printer;
import android.view.HapticFeedbackConstants;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.CompletionInfo;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.ExtractedText;
import android.view.inputmethod.ExtractedTextRequest;
import android.view.inputmethod.InputConnection;
import android.view.inputmethod.InputMethodManager;
import android.widget.LinearLayout;
import android.widget.Toast;
import java.io.FileDescriptor;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
/**
* Input method implementation for Qwerty'ish keyboard.
*/
public class LatinIME extends InputMethodService implements
ComposeSequencing,
LatinKeyboardBaseView.OnKeyboardActionListener,
SharedPreferences.OnSharedPreferenceChangeListener {
private static final String TAG = "PCKeyboardIME";
private static final boolean PERF_DEBUG = false;
static final boolean DEBUG = false;
static final boolean TRACE = false;
static Map<Integer, String> ESC_SEQUENCES;
static Map<Integer, Integer> CTRL_SEQUENCES;
private static final String PREF_VIBRATE_ON = "vibrate_on";
static final String PREF_VIBRATE_LEN = "vibrate_len";
private static final String PREF_SOUND_ON = "sound_on";
private static final String PREF_POPUP_ON = "popup_on";
private static final String PREF_AUTO_CAP = "auto_cap";
private static final String PREF_QUICK_FIXES = "quick_fixes";
private static final String PREF_SHOW_SUGGESTIONS = "show_suggestions";
private static final String PREF_AUTO_COMPLETE = "auto_complete";
// private static final String PREF_BIGRAM_SUGGESTIONS =
// "bigram_suggestion";
private static final String PREF_VOICE_MODE = "voice_mode";
// The private IME option used to indicate that no microphone should be
// shown for a
// given text field. For instance this is specified by the search dialog
// when the
// dialog is already showing a voice search button.
private static final String IME_OPTION_NO_MICROPHONE = "nm";
public static final String PREF_SELECTED_LANGUAGES = "selected_languages";
public static final String PREF_INPUT_LANGUAGE = "input_language";
private static final String PREF_RECORRECTION_ENABLED = "recorrection_enabled";
static final String PREF_FULLSCREEN_OVERRIDE = "fullscreen_override";
static final String PREF_FORCE_KEYBOARD_ON = "force_keyboard_on";
static final String PREF_KEYBOARD_NOTIFICATION = "keyboard_notification";
static final String PREF_CONNECTBOT_TAB_HACK = "connectbot_tab_hack";
static final String PREF_FULL_KEYBOARD_IN_PORTRAIT = "full_keyboard_in_portrait";
static final String PREF_SUGGESTIONS_IN_LANDSCAPE = "suggestions_in_landscape";
static final String PREF_HEIGHT_PORTRAIT = "settings_height_portrait";
static final String PREF_HEIGHT_LANDSCAPE = "settings_height_landscape";
static final String PREF_HINT_MODE = "pref_hint_mode";
static final String PREF_LONGPRESS_TIMEOUT = "pref_long_press_duration";
static final String PREF_RENDER_MODE = "pref_render_mode";
static final String PREF_SWIPE_UP = "pref_swipe_up";
static final String PREF_SWIPE_DOWN = "pref_swipe_down";
static final String PREF_SWIPE_LEFT = "pref_swipe_left";
static final String PREF_SWIPE_RIGHT = "pref_swipe_right";
static final String PREF_VOL_UP = "pref_vol_up";
static final String PREF_VOL_DOWN = "pref_vol_down";
private static final int MSG_UPDATE_SUGGESTIONS = 0;
private static final int MSG_START_TUTORIAL = 1;
private static final int MSG_UPDATE_SHIFT_STATE = 2;
private static final int MSG_VOICE_RESULTS = 3;
private static final int MSG_UPDATE_OLD_SUGGESTIONS = 4;
// How many continuous deletes at which to start deleting at a higher speed.
private static final int DELETE_ACCELERATE_AT = 20;
// Key events coming any faster than this are long-presses.
private static final int QUICK_PRESS = 200;
static final int ASCII_ENTER = '\n';
static final int ASCII_SPACE = ' ';
static final int ASCII_PERIOD = '.';
// Contextual menu positions
private static final int POS_METHOD = 0;
private static final int POS_SETTINGS = 1;
// private LatinKeyboardView mInputView;
private LinearLayout mCandidateViewContainer;
private CandidateView mCandidateView;
private Suggest mSuggest;
private CompletionInfo[] mCompletions;
private AlertDialog mOptionsDialog;
/* package */KeyboardSwitcher mKeyboardSwitcher;
private UserDictionary mUserDictionary;
private UserBigramDictionary mUserBigramDictionary;
//private ContactsDictionary mContactsDictionary;
private AutoDictionary mAutoDictionary;
private Resources mResources;
private String mInputLocale;
private String mSystemLocale;
private LanguageSwitcher mLanguageSwitcher;
private StringBuilder mComposing = new StringBuilder();
private WordComposer mWord = new WordComposer();
private int mCommittedLength;
private boolean mPredicting;
private boolean mEnableVoiceButton;
private CharSequence mBestWord;
private boolean mPredictionOnForMode;
private boolean mPredictionOnPref;
private boolean mCompletionOn;
private boolean mHasDictionary;
private boolean mAutoSpace;
private boolean mJustAddedAutoSpace;
private boolean mAutoCorrectEnabled;
private boolean mReCorrectionEnabled;
// Bigram Suggestion is disabled in this version.
private final boolean mBigramSuggestionEnabled = false;
private boolean mAutoCorrectOn;
// TODO move this state variable outside LatinIME
private boolean mModCtrl;
private boolean mModAlt;
private boolean mModMeta;
private boolean mModFn;
// Saved shift state when leaving alphabet mode, or when applying multitouch shift
private int mSavedShiftState;
private boolean mPasswordText;
private boolean mVibrateOn;
private int mVibrateLen;
private boolean mSoundOn;
private boolean mPopupOn;
private boolean mAutoCapPref;
private boolean mAutoCapActive;
private boolean mDeadKeysActive;
private boolean mQuickFixes;
private boolean mShowSuggestions;
private boolean mIsShowingHint;
private boolean mConnectbotTabHack;
private boolean mFullscreenOverride;
private boolean mForceKeyboardOn;
private boolean mKeyboardNotification;
private boolean mSuggestionsInLandscape;
private boolean mSuggestionForceOn;
private boolean mSuggestionForceOff;
private String mSwipeUpAction;
private String mSwipeDownAction;
private String mSwipeLeftAction;
private String mSwipeRightAction;
private String mVolUpAction;
private String mVolDownAction;
public static final GlobalKeyboardSettings sKeyboardSettings = new GlobalKeyboardSettings();
static LatinIME sInstance;
private int mHeightPortrait;
private int mHeightLandscape;
private int mNumKeyboardModes = 3;
private int mKeyboardModeOverridePortrait;
private int mKeyboardModeOverrideLandscape;
private int mCorrectionMode;
private boolean mEnableVoice = true;
private boolean mVoiceOnPrimary;
private int mOrientation;
private List<CharSequence> mSuggestPuncList;
// Keep track of the last selection range to decide if we need to show word
// alternatives
private int mLastSelectionStart;
private int mLastSelectionEnd;
// Input type is such that we should not auto-correct
private boolean mInputTypeNoAutoCorrect;
// Indicates whether the suggestion strip is to be on in landscape
private boolean mJustAccepted;
private CharSequence mJustRevertedSeparator;
private int mDeleteCount;
private long mLastKeyTime;
// Modifier keys state
private ModifierKeyState mShiftKeyState = new ModifierKeyState();
private ModifierKeyState mSymbolKeyState = new ModifierKeyState();
private ModifierKeyState mCtrlKeyState = new ModifierKeyState();
private ModifierKeyState mAltKeyState = new ModifierKeyState();
private ModifierKeyState mMetaKeyState = new ModifierKeyState();
private ModifierKeyState mFnKeyState = new ModifierKeyState();
// Compose sequence handling
private boolean mComposeMode = false;
private ComposeBase mComposeBuffer = new ComposeSequence(this);
private ComposeBase mDeadAccentBuffer = new DeadAccentSequence(this);
private Tutorial mTutorial;
private AudioManager mAudioManager;
// Align sound effect volume on music volume
private final float FX_VOLUME = -1.0f;
private final float FX_VOLUME_RANGE_DB = 72.0f;
private boolean mSilentMode;
/* package */String mWordSeparators;
private String mSentenceSeparators;
private boolean mConfigurationChanging;
// Keeps track of most recently inserted text (multi-character key) for
// reverting
private CharSequence mEnteredText;
private boolean mRefreshKeyboardRequired;
// For each word, a list of potential replacements, usually from voice.
private Map<String, List<CharSequence>> mWordToSuggestions = new HashMap<String, List<CharSequence>>();
private ArrayList<WordAlternatives> mWordHistory = new ArrayList<WordAlternatives>();
private PluginManager mPluginManager;
private NotificationReceiver mNotificationReceiver;
private VoiceRecognitionTrigger mVoiceRecognitionTrigger;
public abstract static class WordAlternatives {
protected CharSequence mChosenWord;
public WordAlternatives() {
// Nothing
}
public WordAlternatives(CharSequence chosenWord) {
mChosenWord = chosenWord;
}
@Override
public int hashCode() {
return mChosenWord.hashCode();
}
public abstract CharSequence getOriginalWord();
public CharSequence getChosenWord() {
return mChosenWord;
}
public abstract List<CharSequence> getAlternatives();
}
public class TypedWordAlternatives extends WordAlternatives {
private WordComposer word;
public TypedWordAlternatives() {
// Nothing
}
public TypedWordAlternatives(CharSequence chosenWord,
WordComposer wordComposer) {
super(chosenWord);
word = wordComposer;
}
@Override
public CharSequence getOriginalWord() {
return word.getTypedWord();
}
@Override
public List<CharSequence> getAlternatives() {
return getTypedSuggestions(word);
}
}
/* package */Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_UPDATE_SUGGESTIONS:
updateSuggestions();
break;
case MSG_UPDATE_OLD_SUGGESTIONS:
setOldSuggestions();
break;
case MSG_START_TUTORIAL:
if (mTutorial == null) {
if (mKeyboardSwitcher.getInputView().isShown()) {
mTutorial = new Tutorial(LatinIME.this,
mKeyboardSwitcher.getInputView());
mTutorial.start();
} else {
// Try again soon if the view is not yet showing
sendMessageDelayed(obtainMessage(MSG_START_TUTORIAL),
100);
}
}
break;
case MSG_UPDATE_SHIFT_STATE:
updateShiftKeyState(getCurrentInputEditorInfo());
break;
}
}
};
@Override
public void onCreate() {
Log.i("PCKeyboard", "onCreate(), os.version=" + System.getProperty("os.version"));
LatinImeLogger.init(this);
KeyboardSwitcher.init(this);
super.onCreate();
sInstance = this;
// setStatusIcon(R.drawable.ime_qwerty);
mResources = getResources();
final Configuration conf = mResources.getConfiguration();
mOrientation = conf.orientation;
final SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(this);
mLanguageSwitcher = new LanguageSwitcher(this);
mLanguageSwitcher.loadLocales(prefs);
mKeyboardSwitcher = KeyboardSwitcher.getInstance();
mKeyboardSwitcher.setLanguageSwitcher(mLanguageSwitcher);
mSystemLocale = conf.locale.toString();
mLanguageSwitcher.setSystemLocale(conf.locale);
String inputLanguage = mLanguageSwitcher.getInputLanguage();
if (inputLanguage == null) {
inputLanguage = conf.locale.toString();
}
Resources res = getResources();
mReCorrectionEnabled = prefs.getBoolean(PREF_RECORRECTION_ENABLED,
res.getBoolean(R.bool.default_recorrection_enabled));
mConnectbotTabHack = prefs.getBoolean(PREF_CONNECTBOT_TAB_HACK,
res.getBoolean(R.bool.default_connectbot_tab_hack));
mFullscreenOverride = prefs.getBoolean(PREF_FULLSCREEN_OVERRIDE,
res.getBoolean(R.bool.default_fullscreen_override));
mForceKeyboardOn = prefs.getBoolean(PREF_FORCE_KEYBOARD_ON,
res.getBoolean(R.bool.default_force_keyboard_on));
mKeyboardNotification = prefs.getBoolean(PREF_KEYBOARD_NOTIFICATION,
res.getBoolean(R.bool.default_keyboard_notification));
mSuggestionsInLandscape = prefs.getBoolean(PREF_SUGGESTIONS_IN_LANDSCAPE,
res.getBoolean(R.bool.default_suggestions_in_landscape));
mHeightPortrait = getHeight(prefs, PREF_HEIGHT_PORTRAIT, res.getString(R.string.default_height_portrait));
mHeightLandscape = getHeight(prefs, PREF_HEIGHT_LANDSCAPE, res.getString(R.string.default_height_landscape));
LatinIME.sKeyboardSettings.hintMode = Integer.parseInt(prefs.getString(PREF_HINT_MODE, res.getString(R.string.default_hint_mode)));
LatinIME.sKeyboardSettings.longpressTimeout = getPrefInt(prefs, PREF_LONGPRESS_TIMEOUT, res.getString(R.string.default_long_press_duration));
LatinIME.sKeyboardSettings.renderMode = getPrefInt(prefs, PREF_RENDER_MODE, res.getString(R.string.default_render_mode));
mSwipeUpAction = prefs.getString(PREF_SWIPE_UP, res.getString(R.string.default_swipe_up));
mSwipeDownAction = prefs.getString(PREF_SWIPE_DOWN, res.getString(R.string.default_swipe_down));
mSwipeLeftAction = prefs.getString(PREF_SWIPE_LEFT, res.getString(R.string.default_swipe_left));
mSwipeRightAction = prefs.getString(PREF_SWIPE_RIGHT, res.getString(R.string.default_swipe_right));
mVolUpAction = prefs.getString(PREF_VOL_UP, res.getString(R.string.default_vol_up));
mVolDownAction = prefs.getString(PREF_VOL_DOWN, res.getString(R.string.default_vol_down));
sKeyboardSettings.initPrefs(prefs, res);
mVoiceRecognitionTrigger = new VoiceRecognitionTrigger(this);
updateKeyboardOptions();
PluginManager.getPluginDictionaries(getApplicationContext());
mPluginManager = new PluginManager(this);
final IntentFilter pFilter = new IntentFilter();
pFilter.addDataScheme("package");
pFilter.addAction("android.intent.action.PACKAGE_ADDED");
pFilter.addAction("android.intent.action.PACKAGE_REPLACED");
pFilter.addAction("android.intent.action.PACKAGE_REMOVED");
registerReceiver(mPluginManager, pFilter);
LatinIMEUtil.GCUtils.getInstance().reset();
boolean tryGC = true;
for (int i = 0; i < LatinIMEUtil.GCUtils.GC_TRY_LOOP_MAX && tryGC; ++i) {
try {
initSuggest(inputLanguage);
tryGC = false;
} catch (OutOfMemoryError e) {
tryGC = LatinIMEUtil.GCUtils.getInstance().tryGCOrWait(
inputLanguage, e);
}
}
mOrientation = conf.orientation;
// register to receive ringer mode changes for silent mode
IntentFilter filter = new IntentFilter(
AudioManager.RINGER_MODE_CHANGED_ACTION);
registerReceiver(mReceiver, filter);
prefs.registerOnSharedPreferenceChangeListener(this);
setNotification(mKeyboardNotification);
}
private int getKeyboardModeNum(int origMode, int override) {
if (mNumKeyboardModes == 2 && origMode == 2) origMode = 1; // skip "compact". FIXME!
int num = (origMode + override) % mNumKeyboardModes;
if (mNumKeyboardModes == 2 && num == 1) num = 2; // skip "compact". FIXME!
return num;
}
private void updateKeyboardOptions() {
//Log.i(TAG, "setFullKeyboardOptions " + fullInPortrait + " " + heightPercentPortrait + " " + heightPercentLandscape);
boolean isPortrait = isPortrait();
int kbMode;
mNumKeyboardModes = sKeyboardSettings.compactModeEnabled ? 3 : 2; // FIXME!
if (isPortrait) {
kbMode = getKeyboardModeNum(sKeyboardSettings.keyboardModePortrait, mKeyboardModeOverridePortrait);
} else {
kbMode = getKeyboardModeNum(sKeyboardSettings.keyboardModeLandscape, mKeyboardModeOverrideLandscape);
}
// Convert overall keyboard height to per-row percentage
int screenHeightPercent = isPortrait ? mHeightPortrait : mHeightLandscape;
LatinIME.sKeyboardSettings.keyboardMode = kbMode;
LatinIME.sKeyboardSettings.keyboardHeightPercent = (float) screenHeightPercent;
}
private void setNotification(boolean visible) {
final String ACTION = "org.pocketworkstation.pckeyboard.SHOW";
final int ID = 1;
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
if (visible && mNotificationReceiver == null) {
int icon = R.drawable.icon;
CharSequence text = "Keyboard notification enabled.";
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, text, when);
// TODO: clean this up?
mNotificationReceiver = new NotificationReceiver(this);
final IntentFilter pFilter = new IntentFilter(ACTION);
registerReceiver(mNotificationReceiver, pFilter);
Intent notificationIntent = new Intent(ACTION);
PendingIntent contentIntent = PendingIntent.getBroadcast(getApplicationContext(), 1, notificationIntent, 0);
//PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
String title = "Show Hacker's Keyboard";
String body = "Select this to open the keyboard. Disable in settings.";
notification.flags |= Notification.FLAG_ONGOING_EVENT | Notification.FLAG_NO_CLEAR;
notification.setLatestEventInfo(getApplicationContext(), title, body, contentIntent);
mNotificationManager.notify(ID, notification);
} else if (mNotificationReceiver != null) {
mNotificationManager.cancel(ID);
unregisterReceiver(mNotificationReceiver);
mNotificationReceiver = null;
}
}
private boolean isPortrait() {
return (mOrientation == Configuration.ORIENTATION_PORTRAIT);
}
private boolean suggestionsDisabled() {
if (mSuggestionForceOff) return true;
if (mSuggestionForceOn) return false;
return !(mSuggestionsInLandscape || isPortrait());
}
/**
* Loads a dictionary or multiple separated dictionary
*
* @return returns array of dictionary resource ids
*/
/* package */static int[] getDictionary(Resources res) {
String packageName = LatinIME.class.getPackage().getName();
XmlResourceParser xrp = res.getXml(R.xml.dictionary);
ArrayList<Integer> dictionaries = new ArrayList<Integer>();
try {
int current = xrp.getEventType();
while (current != XmlResourceParser.END_DOCUMENT) {
if (current == XmlResourceParser.START_TAG) {
String tag = xrp.getName();
if (tag != null) {
if (tag.equals("part")) {
String dictFileName = xrp.getAttributeValue(null,
"name");
dictionaries.add(res.getIdentifier(dictFileName,
"raw", packageName));
}
}
}
xrp.next();
current = xrp.getEventType();
}
} catch (XmlPullParserException e) {
Log.e(TAG, "Dictionary XML parsing failure");
} catch (IOException e) {
Log.e(TAG, "Dictionary XML IOException");
}
int count = dictionaries.size();
int[] dict = new int[count];
for (int i = 0; i < count; i++) {
dict[i] = dictionaries.get(i);
}
return dict;
}
private void initSuggest(String locale) {
mInputLocale = locale;
Resources orig = getResources();
Configuration conf = orig.getConfiguration();
Locale saveLocale = conf.locale;
conf.locale = new Locale(locale);
orig.updateConfiguration(conf, orig.getDisplayMetrics());
if (mSuggest != null) {
mSuggest.close();
}
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(this);
mQuickFixes = sp.getBoolean(PREF_QUICK_FIXES, getResources()
.getBoolean(R.bool.default_quick_fixes));
int[] dictionaries = getDictionary(orig);
mSuggest = new Suggest(this, dictionaries);
updateAutoTextEnabled(saveLocale);
if (mUserDictionary != null)
mUserDictionary.close();
mUserDictionary = new UserDictionary(this, mInputLocale);
//if (mContactsDictionary == null) {
// mContactsDictionary = new ContactsDictionary(this,
// Suggest.DIC_CONTACTS);
//}
if (mAutoDictionary != null) {
mAutoDictionary.close();
}
mAutoDictionary = new AutoDictionary(this, this, mInputLocale,
Suggest.DIC_AUTO);
if (mUserBigramDictionary != null) {
mUserBigramDictionary.close();
}
mUserBigramDictionary = new UserBigramDictionary(this, this,
mInputLocale, Suggest.DIC_USER);
mSuggest.setUserBigramDictionary(mUserBigramDictionary);
mSuggest.setUserDictionary(mUserDictionary);
//mSuggest.setContactsDictionary(mContactsDictionary);
mSuggest.setAutoDictionary(mAutoDictionary);
updateCorrectionMode();
mWordSeparators = mResources.getString(R.string.word_separators);
mSentenceSeparators = mResources
.getString(R.string.sentence_separators);
initSuggestPuncList();
conf.locale = saveLocale;
orig.updateConfiguration(conf, orig.getDisplayMetrics());
}
@Override
public void onDestroy() {
if (mUserDictionary != null) {
mUserDictionary.close();
}
//if (mContactsDictionary != null) {
// mContactsDictionary.close();
//}
unregisterReceiver(mReceiver);
unregisterReceiver(mPluginManager);
if (mNotificationReceiver != null) {
unregisterReceiver(mNotificationReceiver);
mNotificationReceiver = null;
}
LatinImeLogger.commit();
LatinImeLogger.onDestroy();
super.onDestroy();
}
@Override
public void onConfigurationChanged(Configuration conf) {
Log.i("PCKeyboard", "onConfigurationChanged()");
// If the system locale changes and is different from the saved
// locale (mSystemLocale), then reload the input locale list from the
// latin ime settings (shared prefs) and reset the input locale
// to the first one.
final String systemLocale = conf.locale.toString();
if (!TextUtils.equals(systemLocale, mSystemLocale)) {
mSystemLocale = systemLocale;
if (mLanguageSwitcher != null) {
mLanguageSwitcher.loadLocales(PreferenceManager
.getDefaultSharedPreferences(this));
mLanguageSwitcher.setSystemLocale(conf.locale);
toggleLanguage(true, true);
} else {
reloadKeyboards();
}
}
// If orientation changed while predicting, commit the change
if (conf.orientation != mOrientation) {
InputConnection ic = getCurrentInputConnection();
commitTyped(ic, true);
if (ic != null)
ic.finishComposingText(); // For voice input
mOrientation = conf.orientation;
reloadKeyboards();
removeCandidateViewContainer();
}
mConfigurationChanging = true;
super.onConfigurationChanged(conf);
mConfigurationChanging = false;
}
@Override
public View onCreateInputView() {
setCandidatesViewShown(false); // Workaround for "already has a parent" when reconfiguring
mKeyboardSwitcher.recreateInputView();
mKeyboardSwitcher.makeKeyboards(true);
mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_TEXT, 0,
shouldShowVoiceButton(getCurrentInputEditorInfo()));
return mKeyboardSwitcher.getInputView();
}
@Override
public AbstractInputMethodImpl onCreateInputMethodInterface() {
return new MyInputMethodImpl();
}
IBinder mToken;
public class MyInputMethodImpl extends InputMethodImpl {
@Override
public void attachToken(IBinder token) {
super.attachToken(token);
Log.i(TAG, "attachToken " + token);
if (mToken == null) {
mToken = token;
}
}
}
@Override
public View onCreateCandidatesView() {
//Log.i(TAG, "onCreateCandidatesView(), mCandidateViewContainer=" + mCandidateViewContainer);
//mKeyboardSwitcher.makeKeyboards(true);
if (mCandidateViewContainer == null) {
mCandidateViewContainer = (LinearLayout) getLayoutInflater().inflate(
R.layout.candidates, null);
mCandidateView = (CandidateView) mCandidateViewContainer
.findViewById(R.id.candidates);
mCandidateView.setPadding(0, 0, 0, 0);
mCandidateView.setService(this);
setCandidatesView(mCandidateViewContainer);
}
return mCandidateViewContainer;
}
private void removeCandidateViewContainer() {
//Log.i(TAG, "removeCandidateViewContainer(), mCandidateViewContainer=" + mCandidateViewContainer);
if (mCandidateViewContainer != null) {
mCandidateViewContainer.removeAllViews();
ViewParent parent = mCandidateViewContainer.getParent();
if (parent != null && parent instanceof ViewGroup) {
((ViewGroup) parent).removeView(mCandidateViewContainer);
}
mCandidateViewContainer = null;
mCandidateView = null;
}
resetPrediction();
}
private void resetPrediction() {
mComposing.setLength(0);
mPredicting = false;
mDeleteCount = 0;
mJustAddedAutoSpace = false;
}
@Override
public void onStartInputView(EditorInfo attribute, boolean restarting) {
sKeyboardSettings.editorPackageName = attribute.packageName;
sKeyboardSettings.editorFieldName = attribute.fieldName;
sKeyboardSettings.editorFieldId = attribute.fieldId;
sKeyboardSettings.editorInputType = attribute.inputType;
//Log.i("PCKeyboard", "onStartInputView " + attribute + ", inputType= " + Integer.toHexString(attribute.inputType) + ", restarting=" + restarting);
LatinKeyboardView inputView = mKeyboardSwitcher.getInputView();
// In landscape mode, this method gets called without the input view
// being created.
if (inputView == null) {
return;
}
if (mRefreshKeyboardRequired) {
mRefreshKeyboardRequired = false;
toggleLanguage(true, true);
}
mKeyboardSwitcher.makeKeyboards(false);
TextEntryState.newSession(this);
// Most such things we decide below in the switch statement, but we need to know
// now whether this is a password text field, because we need to know now (before
// the switch statement) whether we want to enable the voice button.
mPasswordText = false;
int variation = attribute.inputType & EditorInfo.TYPE_MASK_VARIATION;
if (variation == EditorInfo.TYPE_TEXT_VARIATION_PASSWORD
|| variation == EditorInfo.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
|| variation == 0xe0 /* EditorInfo.TYPE_TEXT_VARIATION_WEB_PASSWORD */
) {
if ((attribute.inputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_TEXT) {
mPasswordText = true;
}
}
mEnableVoiceButton = shouldShowVoiceButton(attribute);
final boolean enableVoiceButton = mEnableVoiceButton && mEnableVoice;
if (mVoiceRecognitionTrigger != null) {
mVoiceRecognitionTrigger.onStartInputView();
}
mInputTypeNoAutoCorrect = false;
mPredictionOnForMode = false;
mCompletionOn = false;
mCompletions = null;
mModCtrl = false;
mModAlt = false;
mModMeta = false;
mModFn = false;
mEnteredText = null;
mSuggestionForceOn = false;
mSuggestionForceOff = false;
mKeyboardModeOverridePortrait = 0;
mKeyboardModeOverrideLandscape = 0;
sKeyboardSettings.useExtension = false;
switch (attribute.inputType & EditorInfo.TYPE_MASK_CLASS) {
case EditorInfo.TYPE_CLASS_NUMBER:
case EditorInfo.TYPE_CLASS_DATETIME:
// fall through
// NOTE: For now, we use the phone keyboard for NUMBER and DATETIME
// until we get
// a dedicated number entry keypad.
// TODO: Use a dedicated number entry keypad here when we get one.
case EditorInfo.TYPE_CLASS_PHONE:
mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_PHONE,
attribute.imeOptions, enableVoiceButton);
break;
case EditorInfo.TYPE_CLASS_TEXT:
mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_TEXT,
attribute.imeOptions, enableVoiceButton);
// startPrediction();
mPredictionOnForMode = true;
// Make sure that passwords are not displayed in candidate view
if (mPasswordText) {
mPredictionOnForMode = false;
}
if (variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_ADDRESS
|| variation == EditorInfo.TYPE_TEXT_VARIATION_PERSON_NAME
|| !mLanguageSwitcher.allowAutoSpace()) {
mAutoSpace = false;
} else {
mAutoSpace = true;
}
if (variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_ADDRESS) {
mPredictionOnForMode = false;
mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_EMAIL,
attribute.imeOptions, enableVoiceButton);
} else if (variation == EditorInfo.TYPE_TEXT_VARIATION_URI) {
mPredictionOnForMode = false;
mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_URL,
attribute.imeOptions, enableVoiceButton);
} else if (variation == EditorInfo.TYPE_TEXT_VARIATION_SHORT_MESSAGE) {
mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_IM,
attribute.imeOptions, enableVoiceButton);
} else if (variation == EditorInfo.TYPE_TEXT_VARIATION_FILTER) {
mPredictionOnForMode = false;
} else if (variation == EditorInfo.TYPE_TEXT_VARIATION_WEB_EDIT_TEXT) {
mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_WEB,
attribute.imeOptions, enableVoiceButton);
// If it's a browser edit field and auto correct is not ON
// explicitly, then
// disable auto correction, but keep suggestions on.
if ((attribute.inputType & EditorInfo.TYPE_TEXT_FLAG_AUTO_CORRECT) == 0) {
mInputTypeNoAutoCorrect = true;
}
}
// If NO_SUGGESTIONS is set, don't do prediction.
if ((attribute.inputType & EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS) != 0) {
mPredictionOnForMode = false;
mInputTypeNoAutoCorrect = true;
}
// If it's not multiline and the autoCorrect flag is not set, then
// don't correct
if ((attribute.inputType & EditorInfo.TYPE_TEXT_FLAG_AUTO_CORRECT) == 0
&& (attribute.inputType & EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE) == 0) {
mInputTypeNoAutoCorrect = true;
}
if ((attribute.inputType & EditorInfo.TYPE_TEXT_FLAG_AUTO_COMPLETE) != 0) {
mPredictionOnForMode = false;
mCompletionOn = isFullscreenMode();
}
break;
default:
mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_TEXT,
attribute.imeOptions, enableVoiceButton);
}
inputView.closing();
resetPrediction();
loadSettings();
updateShiftKeyState(attribute);
mPredictionOnPref = (mCorrectionMode > 0 || mShowSuggestions);
setCandidatesViewShownInternal(isCandidateStripVisible()
|| mCompletionOn, false /* needsInputViewShown */);
updateSuggestions();
// If the dictionary is not big enough, don't auto correct
mHasDictionary = mSuggest.hasMainDictionary();
updateCorrectionMode();
inputView.setPreviewEnabled(mPopupOn);
inputView.setProximityCorrectionEnabled(true);
// If we just entered a text field, maybe it has some old text that
// requires correction
checkReCorrectionOnStart();
checkTutorial(attribute.privateImeOptions);
if (TRACE)
Debug.startMethodTracing("/data/trace/latinime");
}
private boolean shouldShowVoiceButton(EditorInfo attribute) {
// TODO Auto-generated method stub
return true;
}
private void checkReCorrectionOnStart() {
if (mReCorrectionEnabled && isPredictionOn()) {
// First get the cursor position. This is required by
// setOldSuggestions(), so that
// it can pass the correct range to setComposingRegion(). At this
// point, we don't
// have valid values for mLastSelectionStart/Stop because
// onUpdateSelection() has
// not been called yet.
InputConnection ic = getCurrentInputConnection();
if (ic == null)
return;
ExtractedTextRequest etr = new ExtractedTextRequest();
etr.token = 0; // anything is fine here
ExtractedText et = ic.getExtractedText(etr, 0);
if (et == null)
return;
mLastSelectionStart = et.startOffset + et.selectionStart;
mLastSelectionEnd = et.startOffset + et.selectionEnd;
// Then look for possible corrections in a delayed fashion
if (!TextUtils.isEmpty(et.text) && isCursorTouchingWord()) {
postUpdateOldSuggestions();
}
}
}
@Override
public void onFinishInput() {
super.onFinishInput();
LatinImeLogger.commit();
onAutoCompletionStateChanged(false);
if (mKeyboardSwitcher.getInputView() != null) {
mKeyboardSwitcher.getInputView().closing();
}
if (mAutoDictionary != null)
mAutoDictionary.flushPendingWrites();
if (mUserBigramDictionary != null)
mUserBigramDictionary.flushPendingWrites();
}
@Override
public void onFinishInputView(boolean finishingInput) {
super.onFinishInputView(finishingInput);
// Remove penging messages related to update suggestions
mHandler.removeMessages(MSG_UPDATE_SUGGESTIONS);
mHandler.removeMessages(MSG_UPDATE_OLD_SUGGESTIONS);
}
@Override
public void onUpdateExtractedText(int token, ExtractedText text) {
super.onUpdateExtractedText(token, text);
InputConnection ic = getCurrentInputConnection();
}
@Override
public void onUpdateSelection(int oldSelStart, int oldSelEnd,
int newSelStart, int newSelEnd, int candidatesStart,
int candidatesEnd) {
super.onUpdateSelection(oldSelStart, oldSelEnd, newSelStart, newSelEnd,
candidatesStart, candidatesEnd);
if (DEBUG) {
Log.i(TAG, "onUpdateSelection: oss=" + oldSelStart + ", ose="
+ oldSelEnd + ", nss=" + newSelStart + ", nse=" + newSelEnd
+ ", cs=" + candidatesStart + ", ce=" + candidatesEnd);
}
// If the current selection in the text view changes, we should
// clear whatever candidate text we have.
if ((((mComposing.length() > 0 && mPredicting))
&& (newSelStart != candidatesEnd || newSelEnd != candidatesEnd) && mLastSelectionStart != newSelStart)) {
mComposing.setLength(0);
mPredicting = false;
postUpdateSuggestions();
TextEntryState.reset();
InputConnection ic = getCurrentInputConnection();
if (ic != null) {
ic.finishComposingText();
}
} else if (!mPredicting && !mJustAccepted) {
switch (TextEntryState.getState()) {
case ACCEPTED_DEFAULT:
TextEntryState.reset();
// fall through
case SPACE_AFTER_PICKED:
mJustAddedAutoSpace = false; // The user moved the cursor.
break;
}
}
mJustAccepted = false;
postUpdateShiftKeyState();
// Make a note of the cursor position
mLastSelectionStart = newSelStart;
mLastSelectionEnd = newSelEnd;
if (mReCorrectionEnabled) {
// Don't look for corrections if the keyboard is not visible
if (mKeyboardSwitcher != null
&& mKeyboardSwitcher.getInputView() != null
&& mKeyboardSwitcher.getInputView().isShown()) {
// Check if we should go in or out of correction mode.
if (isPredictionOn()
&& mJustRevertedSeparator == null
&& (candidatesStart == candidatesEnd
|| newSelStart != oldSelStart || TextEntryState
.isCorrecting())
&& (newSelStart < newSelEnd - 1 || (!mPredicting))) {
if (isCursorTouchingWord()
|| mLastSelectionStart < mLastSelectionEnd) {
postUpdateOldSuggestions();
} else {
abortCorrection(false);
// Show the punctuation suggestions list if the current
// one is not
// and if not showing "Touch again to save".
if (mCandidateView != null
&& !mSuggestPuncList.equals(mCandidateView
.getSuggestions())
&& !mCandidateView
.isShowingAddToDictionaryHint()) {
setNextSuggestions();
}
}
}
}
}
}
/**
* This is called when the user has clicked on the extracted text view, when
* running in fullscreen mode. The default implementation hides the
* candidates view when this happens, but only if the extracted text editor
* has a vertical scroll bar because its text doesn't fit. Here we override
* the behavior due to the possibility that a re-correction could cause the
* candidate strip to disappear and re-appear.
*/
@Override
public void onExtractedTextClicked() {
if (mReCorrectionEnabled && isPredictionOn())
return;
super.onExtractedTextClicked();
}
/**
* This is called when the user has performed a cursor movement in the
* extracted text view, when it is running in fullscreen mode. The default
* implementation hides the candidates view when a vertical movement
* happens, but only if the extracted text editor has a vertical scroll bar
* because its text doesn't fit. Here we override the behavior due to the
* possibility that a re-correction could cause the candidate strip to
* disappear and re-appear.
*/
@Override
public void onExtractedCursorMovement(int dx, int dy) {
if (mReCorrectionEnabled && isPredictionOn())
return;
super.onExtractedCursorMovement(dx, dy);
}
@Override
public void hideWindow() {
LatinImeLogger.commit();
onAutoCompletionStateChanged(false);
if (TRACE)
Debug.stopMethodTracing();
if (mOptionsDialog != null && mOptionsDialog.isShowing()) {
mOptionsDialog.dismiss();
mOptionsDialog = null;
}
mWordToSuggestions.clear();
mWordHistory.clear();
super.hideWindow();
TextEntryState.endSession();
}
@Override
public void onDisplayCompletions(CompletionInfo[] completions) {
if (DEBUG) {
Log.i("foo", "Received completions:");
for (int i = 0; i < (completions != null ? completions.length : 0); i++) {
Log.i("foo", " #" + i + ": " + completions[i]);
}
}
if (mCompletionOn) {
mCompletions = completions;
if (completions == null) {
clearSuggestions();
return;
}
List<CharSequence> stringList = new ArrayList<CharSequence>();
for (int i = 0; i < (completions != null ? completions.length : 0); i++) {
CompletionInfo ci = completions[i];
if (ci != null)
stringList.add(ci.getText());
}
// When in fullscreen mode, show completions generated by the
// application
setSuggestions(stringList, true, true, true);
mBestWord = null;
setCandidatesViewShown(true);
}
}
private void setCandidatesViewShownInternal(boolean shown,
boolean needsInputViewShown) {
// Log.i(TAG, "setCandidatesViewShownInternal(" + shown + ", " + needsInputViewShown +
// " mCompletionOn=" + mCompletionOn +
// " mPredictionOnForMode=" + mPredictionOnForMode +
// " mPredictionOnPref=" + mPredictionOnPref +
// " mPredicting=" + mPredicting
// );
// TODO: Remove this if we support candidates with hard keyboard
boolean visible = shown
&& onEvaluateInputViewShown()
&& mKeyboardSwitcher.getInputView() != null
&& isPredictionOn()
&& (needsInputViewShown
? mKeyboardSwitcher.getInputView().isShown()
: true);
if (visible) {
if (mCandidateViewContainer == null) {
onCreateCandidatesView();
setNextSuggestions();
}
} else {
if (mCandidateViewContainer != null) {
removeCandidateViewContainer();
commitTyped(getCurrentInputConnection(), true);
}
}
super.setCandidatesViewShown(visible);
}
@Override
public void onFinishCandidatesView(boolean finishingInput) {
//Log.i(TAG, "onFinishCandidatesView(), mCandidateViewContainer=" + mCandidateViewContainer);
super.onFinishCandidatesView(finishingInput);
if (mCandidateViewContainer != null) {
removeCandidateViewContainer();
}
}
@Override
public boolean onEvaluateInputViewShown() {
boolean parent = super.onEvaluateInputViewShown();
boolean wanted = mForceKeyboardOn || parent;
//Log.i(TAG, "OnEvaluateInputViewShown, parent=" + parent + " + " wanted=" + wanted);
return wanted;
}
@Override
public void setCandidatesViewShown(boolean shown) {
setCandidatesViewShownInternal(shown, true /* needsInputViewShown */);
}
@Override
public void onComputeInsets(InputMethodService.Insets outInsets) {
super.onComputeInsets(outInsets);
if (!isFullscreenMode()) {
outInsets.contentTopInsets = outInsets.visibleTopInsets;
}
}
@Override
public boolean onEvaluateFullscreenMode() {
DisplayMetrics dm = getResources().getDisplayMetrics();
float displayHeight = dm.heightPixels;
// If the display is more than X inches high, don't go to fullscreen
// mode
float dimen = getResources().getDimension(
R.dimen.max_height_for_fullscreen);
if (displayHeight > dimen || mFullscreenOverride || isConnectbot()) {
return false;
} else {
return super.onEvaluateFullscreenMode();
}
}
public boolean isKeyboardVisible() {
return (mKeyboardSwitcher != null
&& mKeyboardSwitcher.getInputView() != null
&& mKeyboardSwitcher.getInputView().isShown());
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (event.getRepeatCount() == 0
&& mKeyboardSwitcher.getInputView() != null) {
if (mKeyboardSwitcher.getInputView().handleBack()) {
return true;
} else if (mTutorial != null) {
mTutorial.close();
mTutorial = null;
}
}
break;
case KeyEvent.KEYCODE_DPAD_DOWN:
case KeyEvent.KEYCODE_DPAD_UP:
case KeyEvent.KEYCODE_DPAD_LEFT:
case KeyEvent.KEYCODE_DPAD_RIGHT:
// If tutorial is visible, don't allow dpad to work
if (mTutorial != null) {
return true;
}
break;
case KeyEvent.KEYCODE_VOLUME_UP:
if (!mVolUpAction.equals("none") && isKeyboardVisible()) {
return true;
}
break;
case KeyEvent.KEYCODE_VOLUME_DOWN:
if (!mVolDownAction.equals("none") && isKeyboardVisible()) {
return true;
}
break;
}
return super.onKeyDown(keyCode, event);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_DOWN:
case KeyEvent.KEYCODE_DPAD_UP:
case KeyEvent.KEYCODE_DPAD_LEFT:
case KeyEvent.KEYCODE_DPAD_RIGHT:
// If tutorial is visible, don't allow dpad to work
if (mTutorial != null) {
return true;
}
LatinKeyboardView inputView = mKeyboardSwitcher.getInputView();
// Enable shift key and DPAD to do selections
if (inputView != null && inputView.isShown()
&& inputView.getShiftState() == Keyboard.SHIFT_ON) {
event = new KeyEvent(event.getDownTime(), event.getEventTime(),
event.getAction(), event.getKeyCode(), event
.getRepeatCount(), event.getDeviceId(), event
.getScanCode(), KeyEvent.META_SHIFT_LEFT_ON
| KeyEvent.META_SHIFT_ON);
InputConnection ic = getCurrentInputConnection();
if (ic != null)
ic.sendKeyEvent(event);
return true;
}
break;
case KeyEvent.KEYCODE_VOLUME_UP:
if (!mVolUpAction.equals("none") && isKeyboardVisible()) {
return doSwipeAction(mVolUpAction);
}
break;
case KeyEvent.KEYCODE_VOLUME_DOWN:
if (!mVolDownAction.equals("none") && isKeyboardVisible()) {
return doSwipeAction(mVolDownAction);
}
break;
}
return super.onKeyUp(keyCode, event);
}
private void reloadKeyboards() {
mKeyboardSwitcher.setLanguageSwitcher(mLanguageSwitcher);
if (mKeyboardSwitcher.getInputView() != null
&& mKeyboardSwitcher.getKeyboardMode() != KeyboardSwitcher.MODE_NONE) {
mKeyboardSwitcher.setVoiceMode(mEnableVoice && mEnableVoiceButton,
mVoiceOnPrimary);
}
updateKeyboardOptions();
mKeyboardSwitcher.makeKeyboards(true);
}
private void commitTyped(InputConnection inputConnection, boolean manual) {
if (mPredicting) {
mPredicting = false;
if (mComposing.length() > 0) {
if (inputConnection != null) {
inputConnection.commitText(mComposing, 1);
}
mCommittedLength = mComposing.length();
if (manual) {
TextEntryState.manualTyped(mComposing);
} else {
TextEntryState.acceptedTyped(mComposing);
}
addToDictionaries(mComposing,
AutoDictionary.FREQUENCY_FOR_TYPED);
}
updateSuggestions();
}
}
private void postUpdateShiftKeyState() {
// TODO(klausw): disabling, I have no idea what this is supposed to accomplish.
// //updateShiftKeyState(getCurrentInputEditorInfo());
//
// // FIXME: why the delay?
// mHandler.removeMessages(MSG_UPDATE_SHIFT_STATE);
// // TODO: Should remove this 300ms delay?
// mHandler.sendMessageDelayed(mHandler
// .obtainMessage(MSG_UPDATE_SHIFT_STATE), 300);
}
public void updateShiftKeyState(EditorInfo attr) {
InputConnection ic = getCurrentInputConnection();
if (ic != null && attr != null && mKeyboardSwitcher.isAlphabetMode()) {
int oldState = getShiftState();
boolean isShifted = mShiftKeyState.isChording();
boolean isCapsLock = (oldState == Keyboard.SHIFT_CAPS_LOCKED || oldState == Keyboard.SHIFT_LOCKED);
boolean isCaps = isCapsLock || getCursorCapsMode(ic, attr) != 0;
//Log.i(TAG, "updateShiftKeyState isShifted=" + isShifted + " isCaps=" + isCaps + " isMomentary=" + mShiftKeyState.isMomentary() + " cursorCaps=" + getCursorCapsMode(ic, attr));
int newState = Keyboard.SHIFT_OFF;
if (isShifted) {
newState = (mSavedShiftState == Keyboard.SHIFT_LOCKED) ? Keyboard.SHIFT_CAPS : Keyboard.SHIFT_ON;
} else if (isCaps) {
newState = isCapsLock ? getCapsOrShiftLockState() : Keyboard.SHIFT_CAPS;
}
//Log.i(TAG, "updateShiftKeyState " + oldState + " -> " + newState);
mKeyboardSwitcher.setShiftState(newState);
}
if (ic != null) {
// Clear modifiers other than shift, to avoid them getting stuck
int states =
KeyEvent.META_FUNCTION_ON
| KeyEvent.META_ALT_MASK
| KeyEvent.META_CTRL_MASK
| KeyEvent.META_META_MASK
| KeyEvent.META_SYM_ON;
ic.clearMetaKeyStates(states);
}
}
private int getShiftState() {
if (mKeyboardSwitcher != null) {
LatinKeyboardView view = mKeyboardSwitcher.getInputView();
if (view != null) {
return view.getShiftState();
}
}
return Keyboard.SHIFT_OFF;
}
private boolean isShiftCapsMode() {
if (mKeyboardSwitcher != null) {
LatinKeyboardView view = mKeyboardSwitcher.getInputView();
if (view != null) {
return view.isShiftCaps();
}
}
return false;
}
private int getCursorCapsMode(InputConnection ic, EditorInfo attr) {
int caps = 0;
EditorInfo ei = getCurrentInputEditorInfo();
if (mAutoCapActive && ei != null && ei.inputType != EditorInfo.TYPE_NULL) {
caps = ic.getCursorCapsMode(attr.inputType);
}
return caps;
}
private void swapPunctuationAndSpace() {
final InputConnection ic = getCurrentInputConnection();
if (ic == null)
return;
CharSequence lastTwo = ic.getTextBeforeCursor(2, 0);
if (lastTwo != null && lastTwo.length() == 2
&& lastTwo.charAt(0) == ASCII_SPACE
&& isSentenceSeparator(lastTwo.charAt(1))) {
ic.beginBatchEdit();
ic.deleteSurroundingText(2, 0);
ic.commitText(lastTwo.charAt(1) + " ", 1);
ic.endBatchEdit();
updateShiftKeyState(getCurrentInputEditorInfo());
mJustAddedAutoSpace = true;
}
}
private void reswapPeriodAndSpace() {
final InputConnection ic = getCurrentInputConnection();
if (ic == null)
return;
CharSequence lastThree = ic.getTextBeforeCursor(3, 0);
if (lastThree != null && lastThree.length() == 3
&& lastThree.charAt(0) == ASCII_PERIOD
&& lastThree.charAt(1) == ASCII_SPACE
&& lastThree.charAt(2) == ASCII_PERIOD) {
ic.beginBatchEdit();
ic.deleteSurroundingText(3, 0);
ic.commitText(" ..", 1);
ic.endBatchEdit();
updateShiftKeyState(getCurrentInputEditorInfo());
}
}
private void doubleSpace() {
// if (!mAutoPunctuate) return;
if (mCorrectionMode == Suggest.CORRECTION_NONE)
return;
final InputConnection ic = getCurrentInputConnection();
if (ic == null)
return;
CharSequence lastThree = ic.getTextBeforeCursor(3, 0);
if (lastThree != null && lastThree.length() == 3
&& Character.isLetterOrDigit(lastThree.charAt(0))
&& lastThree.charAt(1) == ASCII_SPACE
&& lastThree.charAt(2) == ASCII_SPACE) {
ic.beginBatchEdit();
ic.deleteSurroundingText(2, 0);
ic.commitText(". ", 1);
ic.endBatchEdit();
updateShiftKeyState(getCurrentInputEditorInfo());
mJustAddedAutoSpace = true;
}
}
private void maybeRemovePreviousPeriod(CharSequence text) {
final InputConnection ic = getCurrentInputConnection();
if (ic == null || text.length() == 0)
return;
// When the text's first character is '.', remove the previous period
// if there is one.
CharSequence lastOne = ic.getTextBeforeCursor(1, 0);
if (lastOne != null && lastOne.length() == 1
&& lastOne.charAt(0) == ASCII_PERIOD
&& text.charAt(0) == ASCII_PERIOD) {
ic.deleteSurroundingText(1, 0);
}
}
private void removeTrailingSpace() {
final InputConnection ic = getCurrentInputConnection();
if (ic == null)
return;
CharSequence lastOne = ic.getTextBeforeCursor(1, 0);
if (lastOne != null && lastOne.length() == 1
&& lastOne.charAt(0) == ASCII_SPACE) {
ic.deleteSurroundingText(1, 0);
}
}
public boolean addWordToDictionary(String word) {
mUserDictionary.addWord(word, 128);
// Suggestion strip should be updated after the operation of adding word
// to the
// user dictionary
postUpdateSuggestions();
return true;
}
private boolean isAlphabet(int code) {
if (Character.isLetter(code)) {
return true;
} else {
return false;
}
}
private void showInputMethodPicker() {
((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
.showInputMethodPicker();
}
private void onOptionKeyPressed() {
if (!isShowingOptionDialog()) {
showOptionsMenu();
}
}
private void onOptionKeyLongPressed() {
if (!isShowingOptionDialog()) {
showInputMethodPicker();
}
}
private boolean isShowingOptionDialog() {
return mOptionsDialog != null && mOptionsDialog.isShowing();
}
private boolean isConnectbot() {
EditorInfo ei = getCurrentInputEditorInfo();
String pkg = ei.packageName;
if (ei == null || pkg == null) return false;
return ((pkg.equalsIgnoreCase("org.connectbot")
|| pkg.equalsIgnoreCase("org.woltage.irssiconnectbot")
|| pkg.equalsIgnoreCase("com.pslib.connectbot")
|| pkg.equalsIgnoreCase("sk.vx.connectbot")
) && ei.inputType == 0); // FIXME
}
private int getMetaState(boolean shifted) {
int meta = 0;
if (shifted) meta |= KeyEvent.META_SHIFT_ON | KeyEvent.META_SHIFT_LEFT_ON;
if (mModCtrl) meta |= KeyEvent.META_CTRL_ON | KeyEvent.META_CTRL_LEFT_ON;
if (mModAlt) meta |= KeyEvent.META_ALT_ON | KeyEvent.META_ALT_LEFT_ON;
if (mModMeta) meta |= KeyEvent.META_META_ON | KeyEvent.META_META_LEFT_ON;
return meta;
}
private void sendKeyDown(InputConnection ic, int key, int meta) {
long now = System.currentTimeMillis();
if (ic != null) ic.sendKeyEvent(new KeyEvent(
now, now, KeyEvent.ACTION_DOWN, key, 0, meta));
}
private void sendKeyUp(InputConnection ic, int key, int meta) {
long now = System.currentTimeMillis();
if (ic != null) ic.sendKeyEvent(new KeyEvent(
now, now, KeyEvent.ACTION_UP, key, 0, meta));
}
private void sendModifiedKeyDownUp(int key, boolean shifted) {
InputConnection ic = getCurrentInputConnection();
int meta = getMetaState(shifted);
sendModifierKeysDown(shifted);
sendKeyDown(ic, key, meta);
sendKeyUp(ic, key, meta);
sendModifierKeysUp(shifted);
}
private boolean isShiftMod() {
if (mShiftKeyState.isChording()) return true;
if (mKeyboardSwitcher != null) {
LatinKeyboardView kb = mKeyboardSwitcher.getInputView();
if (kb != null) return kb.isShiftAll();
}
return false;
}
private boolean delayChordingCtrlModifier() {
return sKeyboardSettings.chordingCtrlKey == 0;
}
private boolean delayChordingAltModifier() {
return sKeyboardSettings.chordingAltKey == 0;
}
private boolean delayChordingMetaModifier() {
return sKeyboardSettings.chordingMetaKey == 0;
}
private void sendModifiedKeyDownUp(int key) {
sendModifiedKeyDownUp(key, isShiftMod());
}
private void sendShiftKey(InputConnection ic, boolean isDown) {
int key = KeyEvent.KEYCODE_SHIFT_LEFT;
int meta = KeyEvent.META_SHIFT_ON | KeyEvent.META_SHIFT_LEFT_ON;
if (isDown) {
sendKeyDown(ic, key, meta);
} else {
sendKeyUp(ic, key, meta);
}
}
private void sendCtrlKey(InputConnection ic, boolean isDown, boolean chording) {
if (chording && delayChordingCtrlModifier()) return;
int key = sKeyboardSettings.chordingCtrlKey;
if (key == 0) key = KeyEvent.KEYCODE_CTRL_LEFT;
int meta = KeyEvent.META_CTRL_ON | KeyEvent.META_CTRL_LEFT_ON;
if (isDown) {
sendKeyDown(ic, key, meta);
} else {
sendKeyUp(ic, key, meta);
}
}
private void sendAltKey(InputConnection ic, boolean isDown, boolean chording) {
if (chording && delayChordingAltModifier()) return;
int key = sKeyboardSettings.chordingAltKey;
if (key == 0) key = KeyEvent.KEYCODE_ALT_LEFT;
int meta = KeyEvent.META_ALT_ON | KeyEvent.META_ALT_LEFT_ON;
if (isDown) {
sendKeyDown(ic, key, meta);
} else {
sendKeyUp(ic, key, meta);
}
}
private void sendMetaKey(InputConnection ic, boolean isDown, boolean chording) {
if (chording && delayChordingMetaModifier()) return;
int key = sKeyboardSettings.chordingMetaKey;
if (key == 0) key = KeyEvent.KEYCODE_META_LEFT;
int meta = KeyEvent.META_META_ON | KeyEvent.META_META_LEFT_ON;
if (isDown) {
sendKeyDown(ic, key, meta);
} else {
sendKeyUp(ic, key, meta);
}
}
private void sendModifierKeysDown(boolean shifted) {
InputConnection ic = getCurrentInputConnection();
if (shifted) {
//Log.i(TAG, "send SHIFT down");
sendShiftKey(ic, true);
}
if (mModCtrl && (!mCtrlKeyState.isChording() || delayChordingCtrlModifier())) {
sendCtrlKey(ic, true, false);
}
if (mModAlt && (!mAltKeyState.isChording() || delayChordingAltModifier())) {
sendAltKey(ic, true, false);
}
if (mModMeta && (!mMetaKeyState.isChording() || delayChordingMetaModifier())) {
sendMetaKey(ic, true, false);
}
}
private void handleModifierKeysUp(boolean shifted, boolean sendKey) {
InputConnection ic = getCurrentInputConnection();
if (mModMeta && (!mMetaKeyState.isChording() || delayChordingMetaModifier())) {
if (sendKey) sendMetaKey(ic, false, false);
if (!mMetaKeyState.isChording()) setModMeta(false);
}
if (mModAlt && (!mAltKeyState.isChording() || delayChordingAltModifier())) {
if (sendKey) sendAltKey(ic, false, false);
if (!mAltKeyState.isChording()) setModAlt(false);
}
if (mModCtrl && (!mCtrlKeyState.isChording() || delayChordingCtrlModifier())) {
if (sendKey) sendCtrlKey(ic, false, false);
if (!mCtrlKeyState.isChording()) setModCtrl(false);
}
if (shifted) {
//Log.i(TAG, "send SHIFT up");
if (sendKey) sendShiftKey(ic, false);
int shiftState = getShiftState();
if (!(mShiftKeyState.isChording() || shiftState == Keyboard.SHIFT_LOCKED)) {
resetShift();
}
}
}
private void sendModifierKeysUp(boolean shifted) {
handleModifierKeysUp(shifted, true);
}
private void sendSpecialKey(int code) {
if (!isConnectbot()) {
commitTyped(getCurrentInputConnection(), true);
sendModifiedKeyDownUp(code);
return;
}
// TODO(klausw): properly support xterm sequences for Ctrl/Alt modifiers?
// See http://slackware.osuosl.org/slackware-12.0/source/l/ncurses/xterm.terminfo
// and the output of "$ infocmp -1L". Support multiple sets, and optional
// true numpad keys?
if (ESC_SEQUENCES == null) {
ESC_SEQUENCES = new HashMap<Integer, String>();
CTRL_SEQUENCES = new HashMap<Integer, Integer>();
// VT escape sequences without leading Escape
ESC_SEQUENCES.put(-LatinKeyboardView.KEYCODE_HOME, "[1~");
ESC_SEQUENCES.put(-LatinKeyboardView.KEYCODE_END, "[4~");
ESC_SEQUENCES.put(-LatinKeyboardView.KEYCODE_PAGE_UP, "[5~");
ESC_SEQUENCES.put(-LatinKeyboardView.KEYCODE_PAGE_DOWN, "[6~");
ESC_SEQUENCES.put(-LatinKeyboardView.KEYCODE_FKEY_F1, "OP");
ESC_SEQUENCES.put(-LatinKeyboardView.KEYCODE_FKEY_F2, "OQ");
ESC_SEQUENCES.put(-LatinKeyboardView.KEYCODE_FKEY_F3, "OR");
ESC_SEQUENCES.put(-LatinKeyboardView.KEYCODE_FKEY_F4, "OS");
ESC_SEQUENCES.put(-LatinKeyboardView.KEYCODE_FKEY_F5, "[15~");
ESC_SEQUENCES.put(-LatinKeyboardView.KEYCODE_FKEY_F6, "[17~");
ESC_SEQUENCES.put(-LatinKeyboardView.KEYCODE_FKEY_F7, "[18~");
ESC_SEQUENCES.put(-LatinKeyboardView.KEYCODE_FKEY_F8, "[19~");
ESC_SEQUENCES.put(-LatinKeyboardView.KEYCODE_FKEY_F9, "[20~");
ESC_SEQUENCES.put(-LatinKeyboardView.KEYCODE_FKEY_F10, "[21~");
ESC_SEQUENCES.put(-LatinKeyboardView.KEYCODE_FKEY_F11, "[23~");
ESC_SEQUENCES.put(-LatinKeyboardView.KEYCODE_FKEY_F12, "[24~");
ESC_SEQUENCES.put(-LatinKeyboardView.KEYCODE_FORWARD_DEL, "[3~");
ESC_SEQUENCES.put(-LatinKeyboardView.KEYCODE_INSERT, "[2~");
// Special ConnectBot hack: Ctrl-1 to Ctrl-0 for F1-F10.
CTRL_SEQUENCES.put(-LatinKeyboardView.KEYCODE_FKEY_F1, KeyEvent.KEYCODE_1);
CTRL_SEQUENCES.put(-LatinKeyboardView.KEYCODE_FKEY_F2, KeyEvent.KEYCODE_2);
CTRL_SEQUENCES.put(-LatinKeyboardView.KEYCODE_FKEY_F3, KeyEvent.KEYCODE_3);
CTRL_SEQUENCES.put(-LatinKeyboardView.KEYCODE_FKEY_F4, KeyEvent.KEYCODE_4);
CTRL_SEQUENCES.put(-LatinKeyboardView.KEYCODE_FKEY_F5, KeyEvent.KEYCODE_5);
CTRL_SEQUENCES.put(-LatinKeyboardView.KEYCODE_FKEY_F6, KeyEvent.KEYCODE_6);
CTRL_SEQUENCES.put(-LatinKeyboardView.KEYCODE_FKEY_F7, KeyEvent.KEYCODE_7);
CTRL_SEQUENCES.put(-LatinKeyboardView.KEYCODE_FKEY_F8, KeyEvent.KEYCODE_8);
CTRL_SEQUENCES.put(-LatinKeyboardView.KEYCODE_FKEY_F9, KeyEvent.KEYCODE_9);
CTRL_SEQUENCES.put(-LatinKeyboardView.KEYCODE_FKEY_F10, KeyEvent.KEYCODE_0);
// Natively supported by ConnectBot
// ESC_SEQUENCES.put(-LatinKeyboardView.KEYCODE_DPAD_UP, "OA");
// ESC_SEQUENCES.put(-LatinKeyboardView.KEYCODE_DPAD_DOWN, "OB");
// ESC_SEQUENCES.put(-LatinKeyboardView.KEYCODE_DPAD_LEFT, "OD");
// ESC_SEQUENCES.put(-LatinKeyboardView.KEYCODE_DPAD_RIGHT, "OC");
// No VT equivalents?
// ESC_SEQUENCES.put(-LatinKeyboardView.KEYCODE_DPAD_CENTER, "");
// ESC_SEQUENCES.put(-LatinKeyboardView.KEYCODE_SYSRQ, "");
// ESC_SEQUENCES.put(-LatinKeyboardView.KEYCODE_BREAK, "");
// ESC_SEQUENCES.put(-LatinKeyboardView.KEYCODE_NUM_LOCK, "");
// ESC_SEQUENCES.put(-LatinKeyboardView.KEYCODE_SCROLL_LOCK, "");
}
InputConnection ic = getCurrentInputConnection();
Integer ctrlseq = null;
if (mConnectbotTabHack) {
ctrlseq = CTRL_SEQUENCES.get(code);
}
String seq = ESC_SEQUENCES.get(code);
if (ctrlseq != null) {
if (mModAlt) {
// send ESC prefix for "Alt"
ic.commitText(Character.toString((char) 27), 1);
}
ic.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN,
KeyEvent.KEYCODE_DPAD_CENTER));
ic.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_UP,
KeyEvent.KEYCODE_DPAD_CENTER));
ic.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN,
ctrlseq));
ic.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_UP,
ctrlseq));
} else if (seq != null) {
if (mModAlt) {
// send ESC prefix for "Alt"
ic.commitText(Character.toString((char) 27), 1);
}
// send ESC prefix of escape sequence
ic.commitText(Character.toString((char) 27), 1);
ic.commitText(seq, 1);
} else {
// send key code, let connectbot handle it
sendDownUpKeyEvents(code);
}
handleModifierKeysUp(false, false);
}
private final static int asciiToKeyCode[] = new int[127];
private final static int KF_MASK = 0xffff;
private final static int KF_SHIFTABLE = 0x10000;
private final static int KF_UPPER = 0x20000;
private final static int KF_LETTER = 0x40000;
{
// Include RETURN in this set even though it's not printable.
// Most other non-printable keys get handled elsewhere.
asciiToKeyCode['\n'] = KeyEvent.KEYCODE_ENTER | KF_SHIFTABLE;
// Non-alphanumeric ASCII codes which have their own keys
// (on some keyboards)
asciiToKeyCode[' '] = KeyEvent.KEYCODE_SPACE | KF_SHIFTABLE;
//asciiToKeyCode['!'] = KeyEvent.KEYCODE_;
//asciiToKeyCode['"'] = KeyEvent.KEYCODE_;
asciiToKeyCode['#'] = KeyEvent.KEYCODE_POUND;
//asciiToKeyCode['$'] = KeyEvent.KEYCODE_;
//asciiToKeyCode['%'] = KeyEvent.KEYCODE_;
//asciiToKeyCode['&'] = KeyEvent.KEYCODE_;
asciiToKeyCode['\''] = KeyEvent.KEYCODE_APOSTROPHE;
//asciiToKeyCode['('] = KeyEvent.KEYCODE_;
//asciiToKeyCode[')'] = KeyEvent.KEYCODE_;
asciiToKeyCode['*'] = KeyEvent.KEYCODE_STAR;
asciiToKeyCode['+'] = KeyEvent.KEYCODE_PLUS;
asciiToKeyCode[','] = KeyEvent.KEYCODE_COMMA;
asciiToKeyCode['-'] = KeyEvent.KEYCODE_MINUS;
asciiToKeyCode['.'] = KeyEvent.KEYCODE_PERIOD;
asciiToKeyCode['/'] = KeyEvent.KEYCODE_SLASH;
//asciiToKeyCode[':'] = KeyEvent.KEYCODE_;
asciiToKeyCode[';'] = KeyEvent.KEYCODE_SEMICOLON;
//asciiToKeyCode['<'] = KeyEvent.KEYCODE_;
asciiToKeyCode['='] = KeyEvent.KEYCODE_EQUALS;
//asciiToKeyCode['>'] = KeyEvent.KEYCODE_;
//asciiToKeyCode['?'] = KeyEvent.KEYCODE_;
asciiToKeyCode['@'] = KeyEvent.KEYCODE_AT;
asciiToKeyCode['['] = KeyEvent.KEYCODE_LEFT_BRACKET;
asciiToKeyCode['\\'] = KeyEvent.KEYCODE_BACKSLASH;
asciiToKeyCode[']'] = KeyEvent.KEYCODE_RIGHT_BRACKET;
//asciiToKeyCode['^'] = KeyEvent.KEYCODE_;
//asciiToKeyCode['_'] = KeyEvent.KEYCODE_;
asciiToKeyCode['`'] = KeyEvent.KEYCODE_GRAVE;
//asciiToKeyCode['{'] = KeyEvent.KEYCODE_;
//asciiToKeyCode['|'] = KeyEvent.KEYCODE_;
//asciiToKeyCode['}'] = KeyEvent.KEYCODE_;
//asciiToKeyCode['~'] = KeyEvent.KEYCODE_;
for (int i = 0; i <= 25; ++i) {
asciiToKeyCode['a' + i] = KeyEvent.KEYCODE_A + i | KF_LETTER;
asciiToKeyCode['A' + i] = KeyEvent.KEYCODE_A + i | KF_UPPER | KF_LETTER;
}
for (int i = 0; i <= 9; ++i) {
asciiToKeyCode['0' + i] = KeyEvent.KEYCODE_0 + i;
}
}
public void sendModifiableKeyChar(char ch) {
// Support modified key events
boolean modShift = isShiftMod();
if ((modShift || mModCtrl || mModAlt || mModMeta) && ch > 0 && ch < 127) {
InputConnection ic = getCurrentInputConnection();
if (isConnectbot()) {
if (mModAlt) {
// send ESC prefix
ic.commitText(Character.toString((char) 27), 1);
}
if (mModCtrl) {
int code = ch & 31;
if (code == 9) {
sendTab();
} else {
ic.commitText(Character.toString((char) code), 1);
}
} else {
ic.commitText(Character.toString(ch), 1);
}
handleModifierKeysUp(false, false);
return;
}
// Non-ConnectBot
// Restrict Shift modifier to ENTER and SPACE, supporting Shift-Enter etc.
// Note that most special keys such as DEL or cursor keys aren't handled
// by this charcode-based method.
int combinedCode = asciiToKeyCode[ch];
if (combinedCode > 0) {
int code = combinedCode & KF_MASK;
boolean shiftable = (combinedCode & KF_SHIFTABLE) > 0;
boolean upper = (combinedCode & KF_UPPER) > 0;
boolean letter = (combinedCode & KF_LETTER) > 0;
boolean shifted = modShift && (upper || shiftable);
if (letter && !mModCtrl && !mModAlt && !mModMeta) {
// Try workaround for issue 179 where letters don't get upcased
ic.commitText(Character.toString(ch), 1);
handleModifierKeysUp(false, false);
} else {
sendModifiedKeyDownUp(code, shifted);
}
return;
}
}
if (ch >= '0' && ch <= '9') {
//WIP
InputConnection ic = getCurrentInputConnection();
ic.clearMetaKeyStates(KeyEvent.META_SHIFT_ON | KeyEvent.META_ALT_ON | KeyEvent.META_SYM_ON);
//EditorInfo ei = getCurrentInputEditorInfo();
//Log.i(TAG, "capsmode=" + ic.getCursorCapsMode(ei.inputType));
//sendModifiedKeyDownUp(KeyEvent.KEYCODE_0 + ch - '0');
//return;
}
// Default handling for anything else, including unmodified ENTER and SPACE.
sendKeyChar(ch);
}
private void sendTab() {
InputConnection ic = getCurrentInputConnection();
boolean tabHack = isConnectbot() && mConnectbotTabHack;
// FIXME: tab and ^I don't work in connectbot, hackish workaround
if (tabHack) {
if (mModAlt) {
// send ESC prefix
ic.commitText(Character.toString((char) 27), 1);
}
ic.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN,
KeyEvent.KEYCODE_DPAD_CENTER));
ic.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_UP,
KeyEvent.KEYCODE_DPAD_CENTER));
ic.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN,
KeyEvent.KEYCODE_I));
ic.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_UP,
KeyEvent.KEYCODE_I));
} else {
sendModifiedKeyDownUp(KeyEvent.KEYCODE_TAB);
}
}
private void sendEscape() {
if (isConnectbot()) {
sendKeyChar((char) 27);
} else {
sendModifiedKeyDownUp(111 /*KeyEvent.KEYCODE_ESCAPE */);
}
}
private boolean processMultiKey(int primaryCode) {
if (mDeadAccentBuffer.composeBuffer.length() > 0) {
//Log.i(TAG, "processMultiKey: pending DeadAccent, length=" + mDeadAccentBuffer.composeBuffer.length());
mDeadAccentBuffer.execute(primaryCode);
mDeadAccentBuffer.clear();
return true;
}
if (mComposeMode) {
mComposeMode = mComposeBuffer.execute(primaryCode);
return true;
}
return false;
}
// Implementation of KeyboardViewListener
public void onKey(int primaryCode, int[] keyCodes, int x, int y) {
long when = SystemClock.uptimeMillis();
if (primaryCode != Keyboard.KEYCODE_DELETE
|| when > mLastKeyTime + QUICK_PRESS) {
mDeleteCount = 0;
}
mLastKeyTime = when;
final boolean distinctMultiTouch = mKeyboardSwitcher
.hasDistinctMultitouch();
switch (primaryCode) {
case Keyboard.KEYCODE_DELETE:
if (processMultiKey(primaryCode)) {
break;
}
handleBackspace();
mDeleteCount++;
LatinImeLogger.logOnDelete();
break;
case Keyboard.KEYCODE_SHIFT:
// Shift key is handled in onPress() when device has distinct
// multi-touch panel.
if (!distinctMultiTouch)
handleShift();
break;
case Keyboard.KEYCODE_MODE_CHANGE:
// Symbol key is handled in onPress() when device has distinct
// multi-touch panel.
if (!distinctMultiTouch)
changeKeyboardMode();
break;
case LatinKeyboardView.KEYCODE_CTRL_LEFT:
// Ctrl key is handled in onPress() when device has distinct
// multi-touch panel.
if (!distinctMultiTouch)
setModCtrl(!mModCtrl);
break;
case LatinKeyboardView.KEYCODE_ALT_LEFT:
// Alt key is handled in onPress() when device has distinct
// multi-touch panel.
if (!distinctMultiTouch)
setModAlt(!mModAlt);
break;
case LatinKeyboardView.KEYCODE_META_LEFT:
// Meta key is handled in onPress() when device has distinct
// multi-touch panel.
if (!distinctMultiTouch)
setModMeta(!mModMeta);
break;
case LatinKeyboardView.KEYCODE_FN:
if (!distinctMultiTouch)
setModFn(!mModFn);
break;
case Keyboard.KEYCODE_CANCEL:
if (!isShowingOptionDialog()) {
handleClose();
}
break;
case LatinKeyboardView.KEYCODE_OPTIONS:
onOptionKeyPressed();
break;
case LatinKeyboardView.KEYCODE_OPTIONS_LONGPRESS:
onOptionKeyLongPressed();
break;
case LatinKeyboardView.KEYCODE_COMPOSE:
mComposeMode = !mComposeMode;
mComposeBuffer.clear();
break;
case LatinKeyboardView.KEYCODE_NEXT_LANGUAGE:
toggleLanguage(false, true);
break;
case LatinKeyboardView.KEYCODE_PREV_LANGUAGE:
toggleLanguage(false, false);
break;
case LatinKeyboardView.KEYCODE_VOICE:
if (mVoiceRecognitionTrigger.isInstalled()) {
mVoiceRecognitionTrigger.startVoiceRecognition();
}
//startListening(false /* was a button press, was not a swipe */);
break;
case 9 /* Tab */:
if (processMultiKey(primaryCode)) {
break;
}
sendTab();
break;
case LatinKeyboardView.KEYCODE_ESCAPE:
if (processMultiKey(primaryCode)) {
break;
}
sendEscape();
break;
case LatinKeyboardView.KEYCODE_DPAD_UP:
case LatinKeyboardView.KEYCODE_DPAD_DOWN:
case LatinKeyboardView.KEYCODE_DPAD_LEFT:
case LatinKeyboardView.KEYCODE_DPAD_RIGHT:
case LatinKeyboardView.KEYCODE_DPAD_CENTER:
case LatinKeyboardView.KEYCODE_HOME:
case LatinKeyboardView.KEYCODE_END:
case LatinKeyboardView.KEYCODE_PAGE_UP:
case LatinKeyboardView.KEYCODE_PAGE_DOWN:
case LatinKeyboardView.KEYCODE_FKEY_F1:
case LatinKeyboardView.KEYCODE_FKEY_F2:
case LatinKeyboardView.KEYCODE_FKEY_F3:
case LatinKeyboardView.KEYCODE_FKEY_F4:
case LatinKeyboardView.KEYCODE_FKEY_F5:
case LatinKeyboardView.KEYCODE_FKEY_F6:
case LatinKeyboardView.KEYCODE_FKEY_F7:
case LatinKeyboardView.KEYCODE_FKEY_F8:
case LatinKeyboardView.KEYCODE_FKEY_F9:
case LatinKeyboardView.KEYCODE_FKEY_F10:
case LatinKeyboardView.KEYCODE_FKEY_F11:
case LatinKeyboardView.KEYCODE_FKEY_F12:
case LatinKeyboardView.KEYCODE_FORWARD_DEL:
case LatinKeyboardView.KEYCODE_INSERT:
case LatinKeyboardView.KEYCODE_SYSRQ:
case LatinKeyboardView.KEYCODE_BREAK:
case LatinKeyboardView.KEYCODE_NUM_LOCK:
case LatinKeyboardView.KEYCODE_SCROLL_LOCK:
if (processMultiKey(primaryCode)) {
break;
}
// send as plain keys, or as escape sequence if needed
sendSpecialKey(-primaryCode);
break;
default:
if (!mComposeMode && mDeadKeysActive && Character.getType(primaryCode) == Character.NON_SPACING_MARK) {
//Log.i(TAG, "possible dead character: " + primaryCode);
if (!mDeadAccentBuffer.execute(primaryCode)) {
//Log.i(TAG, "double dead key");
break; // pressing a dead key twice produces spacing equivalent
}
updateShiftKeyState(getCurrentInputEditorInfo());
break;
}
if (processMultiKey(primaryCode)) {
break;
}
if (primaryCode != ASCII_ENTER) {
mJustAddedAutoSpace = false;
}
RingCharBuffer.getInstance().push((char) primaryCode, x, y);
LatinImeLogger.logOnInputChar();
if (isWordSeparator(primaryCode)) {
handleSeparator(primaryCode);
} else {
handleCharacter(primaryCode, keyCodes);
}
// Cancel the just reverted state
mJustRevertedSeparator = null;
}
mKeyboardSwitcher.onKey(primaryCode);
// Reset after any single keystroke
mEnteredText = null;
//mDeadAccentBuffer.clear(); // FIXME
}
public void onText(CharSequence text) {
//mDeadAccentBuffer.clear(); // FIXME
InputConnection ic = getCurrentInputConnection();
if (ic == null)
return;
if (mPredicting && text.length() == 1) {
// If adding a single letter, treat it as a regular keystroke so
// that completion works as expected.
int c = text.charAt(0);
if (!isWordSeparator(c)) {
int[] codes = {c};
handleCharacter(c, codes);
return;
}
}
abortCorrection(false);
ic.beginBatchEdit();
if (mPredicting) {
commitTyped(ic, true);
}
maybeRemovePreviousPeriod(text);
ic.commitText(text, 1);
ic.endBatchEdit();
updateShiftKeyState(getCurrentInputEditorInfo());
mKeyboardSwitcher.onKey(0); // dummy key code.
mJustRevertedSeparator = null;
mJustAddedAutoSpace = false;
mEnteredText = text;
}
public void onCancel() {
// User released a finger outside any key
mKeyboardSwitcher.onCancelInput();
}
private void handleBackspace() {
boolean deleteChar = false;
InputConnection ic = getCurrentInputConnection();
if (ic == null)
return;
ic.beginBatchEdit();
if (mPredicting) {
final int length = mComposing.length();
if (length > 0) {
mComposing.delete(length - 1, length);
mWord.deleteLast();
ic.setComposingText(mComposing, 1);
if (mComposing.length() == 0) {
mPredicting = false;
}
postUpdateSuggestions();
} else {
ic.deleteSurroundingText(1, 0);
}
} else {
deleteChar = true;
}
postUpdateShiftKeyState();
TextEntryState.backspace();
if (TextEntryState.getState() == TextEntryState.State.UNDO_COMMIT) {
revertLastWord(deleteChar);
ic.endBatchEdit();
return;
} else if (mEnteredText != null
&& sameAsTextBeforeCursor(ic, mEnteredText)) {
ic.deleteSurroundingText(mEnteredText.length(), 0);
} else if (deleteChar) {
if (mCandidateView != null
&& mCandidateView.dismissAddToDictionaryHint()) {
// Go back to the suggestion mode if the user canceled the
// "Touch again to save".
// NOTE: In gerenal, we don't revert the word when backspacing
// from a manual suggestion pick. We deliberately chose a
// different behavior only in the case of picking the first
// suggestion (typed word). It's intentional to have made this
// inconsistent with backspacing after selecting other
// suggestions.
revertLastWord(deleteChar);
} else {
sendDownUpKeyEvents(KeyEvent.KEYCODE_DEL);
if (mDeleteCount > DELETE_ACCELERATE_AT) {
sendDownUpKeyEvents(KeyEvent.KEYCODE_DEL);
}
}
}
mJustRevertedSeparator = null;
ic.endBatchEdit();
}
private void setModCtrl(boolean val) {
// Log.i("LatinIME", "setModCtrl "+ mModCtrl + "->" + val + ", chording=" + mCtrlKeyState.isChording());
mKeyboardSwitcher.setCtrlIndicator(val);
mModCtrl = val;
}
private void setModAlt(boolean val) {
//Log.i("LatinIME", "setModAlt "+ mModAlt + "->" + val + ", chording=" + mAltKeyState.isChording());
mKeyboardSwitcher.setAltIndicator(val);
mModAlt = val;
}
private void setModMeta(boolean val) {
//Log.i("LatinIME", "setModMeta "+ mModMeta + "->" + val + ", chording=" + mMetaKeyState.isChording());
mKeyboardSwitcher.setMetaIndicator(val);
mModMeta = val;
}
private void setModFn(boolean val) {
//Log.i("LatinIME", "setModFn " + mModFn + "->" + val + ", chording=" + mFnKeyState.isChording());
mModFn = val;
mKeyboardSwitcher.setFn(val);
mKeyboardSwitcher.setCtrlIndicator(mModCtrl);
mKeyboardSwitcher.setAltIndicator(mModAlt);
mKeyboardSwitcher.setMetaIndicator(mModMeta);
}
private void startMultitouchShift() {
int newState = Keyboard.SHIFT_ON;
if (mKeyboardSwitcher.isAlphabetMode()) {
mSavedShiftState = getShiftState();
if (mSavedShiftState == Keyboard.SHIFT_LOCKED) newState = Keyboard.SHIFT_CAPS;
}
handleShiftInternal(true, newState);
}
private void commitMultitouchShift() {
if (mKeyboardSwitcher.isAlphabetMode()) {
int newState = nextShiftState(mSavedShiftState, true);
handleShiftInternal(true, newState);
} else {
// do nothing, keyboard is already flipped
}
}
private void resetMultitouchShift() {
int newState = Keyboard.SHIFT_OFF;
if (mSavedShiftState == Keyboard.SHIFT_CAPS_LOCKED || mSavedShiftState == Keyboard.SHIFT_LOCKED) {
newState = mSavedShiftState;
}
handleShiftInternal(true, newState);
}
private void resetShift() {
handleShiftInternal(true, Keyboard.SHIFT_OFF);
}
private void handleShift() {
handleShiftInternal(false, -1);
}
private static int getCapsOrShiftLockState() {
return sKeyboardSettings.capsLock ? Keyboard.SHIFT_CAPS_LOCKED : Keyboard.SHIFT_LOCKED;
}
// Rotate through shift states by successively pressing and releasing the Shift key.
private static int nextShiftState(int prevState, boolean allowCapsLock) {
if (allowCapsLock) {
if (prevState == Keyboard.SHIFT_OFF) {
return Keyboard.SHIFT_ON;
} else if (prevState == Keyboard.SHIFT_ON) {
return getCapsOrShiftLockState();
} else {
return Keyboard.SHIFT_OFF;
}
} else {
// currently unused, see toggleShift()
if (prevState == Keyboard.SHIFT_OFF) {
return Keyboard.SHIFT_ON;
} else {
return Keyboard.SHIFT_OFF;
}
}
}
private void handleShiftInternal(boolean forceState, int newState) {
//Log.i(TAG, "handleShiftInternal forceNormal=" + forceNormal);
mHandler.removeMessages(MSG_UPDATE_SHIFT_STATE);
KeyboardSwitcher switcher = mKeyboardSwitcher;
if (switcher.isAlphabetMode()) {
if (forceState) {
switcher.setShiftState(newState);
} else {
switcher.setShiftState(nextShiftState(getShiftState(), true));
}
} else {
switcher.toggleShift();
}
}
private void abortCorrection(boolean force) {
if (force || TextEntryState.isCorrecting()) {
getCurrentInputConnection().finishComposingText();
clearSuggestions();
}
}
private void handleCharacter(int primaryCode, int[] keyCodes) {
if (mLastSelectionStart == mLastSelectionEnd
&& TextEntryState.isCorrecting()) {
abortCorrection(false);
}
if (isAlphabet(primaryCode) && isPredictionOn()
&& !mModCtrl && !mModAlt && !mModMeta
&& !isCursorTouchingWord()) {
if (!mPredicting) {
mPredicting = true;
mComposing.setLength(0);
saveWordInHistory(mBestWord);
mWord.reset();
}
}
if (mModCtrl || mModAlt || mModMeta) {
commitTyped(getCurrentInputConnection(), true); // sets mPredicting=false
}
if (mPredicting) {
if (isShiftCapsMode()
&& mKeyboardSwitcher.isAlphabetMode()
&& mComposing.length() == 0) {
// Show suggestions with initial caps if starting out shifted,
// could be either auto-caps or manual shift.
mWord.setFirstCharCapitalized(true);
}
mComposing.append((char) primaryCode);
mWord.add(primaryCode, keyCodes);
InputConnection ic = getCurrentInputConnection();
if (ic != null) {
// If it's the first letter, make note of auto-caps state
if (mWord.size() == 1) {
mWord.setAutoCapitalized(getCursorCapsMode(ic,
getCurrentInputEditorInfo()) != 0);
}
ic.setComposingText(mComposing, 1);
}
postUpdateSuggestions();
} else {
sendModifiableKeyChar((char) primaryCode);
}
updateShiftKeyState(getCurrentInputEditorInfo());
if (LatinIME.PERF_DEBUG)
measureCps();
TextEntryState.typedCharacter((char) primaryCode,
isWordSeparator(primaryCode));
}
private void handleSeparator(int primaryCode) {
// Should dismiss the "Touch again to save" message when handling
// separator
if (mCandidateView != null
&& mCandidateView.dismissAddToDictionaryHint()) {
postUpdateSuggestions();
}
boolean pickedDefault = false;
// Handle separator
InputConnection ic = getCurrentInputConnection();
if (ic != null) {
ic.beginBatchEdit();
abortCorrection(false);
}
if (mPredicting) {
// In certain languages where single quote is a separator, it's
// better
// not to auto correct, but accept the typed word. For instance,
// in Italian dov' should not be expanded to dove' because the
// elision
// requires the last vowel to be removed.
if (mAutoCorrectOn
&& primaryCode != '\''
&& (mJustRevertedSeparator == null
|| mJustRevertedSeparator.length() == 0
|| mJustRevertedSeparator.charAt(0) != primaryCode)) {
pickedDefault = pickDefaultSuggestion();
// Picked the suggestion by the space key. We consider this
// as "added an auto space" in autocomplete mode, but as manually
// typed space in "quick fixes" mode.
if (primaryCode == ASCII_SPACE) {
if (mAutoCorrectEnabled) {
mJustAddedAutoSpace = true;
} else {
TextEntryState.manualTyped("");
}
}
} else {
commitTyped(ic, true);
}
}
if (mJustAddedAutoSpace && primaryCode == ASCII_ENTER) {
removeTrailingSpace();
mJustAddedAutoSpace = false;
}
sendModifiableKeyChar((char) primaryCode);
// Handle the case of ". ." -> " .." with auto-space if necessary
// before changing the TextEntryState.
if (TextEntryState.getState() == TextEntryState.State.PUNCTUATION_AFTER_ACCEPTED
&& primaryCode == ASCII_PERIOD) {
reswapPeriodAndSpace();
}
TextEntryState.typedCharacter((char) primaryCode, true);
if (TextEntryState.getState() == TextEntryState.State.PUNCTUATION_AFTER_ACCEPTED
&& primaryCode != ASCII_ENTER) {
swapPunctuationAndSpace();
} else if (isPredictionOn() && primaryCode == ASCII_SPACE) {
doubleSpace();
}
if (pickedDefault) {
TextEntryState.backToAcceptedDefault(mWord.getTypedWord());
}
updateShiftKeyState(getCurrentInputEditorInfo());
if (ic != null) {
ic.endBatchEdit();
}
}
private void handleClose() {
commitTyped(getCurrentInputConnection(), true);
requestHideSelf(0);
if (mKeyboardSwitcher != null) {
LatinKeyboardView inputView = mKeyboardSwitcher.getInputView();
if (inputView != null) {
inputView.closing();
}
}
TextEntryState.endSession();
}
private void saveWordInHistory(CharSequence result) {
if (mWord.size() <= 1) {
mWord.reset();
return;
}
// Skip if result is null. It happens in some edge case.
if (TextUtils.isEmpty(result)) {
return;
}
// Make a copy of the CharSequence, since it is/could be a mutable
// CharSequence
final String resultCopy = result.toString();
TypedWordAlternatives entry = new TypedWordAlternatives(resultCopy,
new WordComposer(mWord));
mWordHistory.add(entry);
}
private void postUpdateSuggestions() {
mHandler.removeMessages(MSG_UPDATE_SUGGESTIONS);
mHandler.sendMessageDelayed(mHandler
.obtainMessage(MSG_UPDATE_SUGGESTIONS), 100);
}
private void postUpdateOldSuggestions() {
mHandler.removeMessages(MSG_UPDATE_OLD_SUGGESTIONS);
mHandler.sendMessageDelayed(mHandler
.obtainMessage(MSG_UPDATE_OLD_SUGGESTIONS), 300);
}
private boolean isPredictionOn() {
return mPredictionOnForMode && isPredictionWanted();
}
private boolean isPredictionWanted() {
return (mShowSuggestions || mSuggestionForceOn) && !suggestionsDisabled();
}
private boolean isCandidateStripVisible() {
return isPredictionOn();
}
private void switchToKeyboardView() {
mHandler.post(new Runnable() {
public void run() {
LatinKeyboardView view = mKeyboardSwitcher.getInputView();
if (view != null) {
ViewParent p = view.getParent();
if (p != null && p instanceof ViewGroup) {
((ViewGroup) p).removeView(view);
}
setInputView(mKeyboardSwitcher.getInputView());
}
setCandidatesViewShown(true);
updateInputViewShown();
postUpdateSuggestions();
}
});
}
private void clearSuggestions() {
setSuggestions(null, false, false, false);
}
private void setSuggestions(List<CharSequence> suggestions,
boolean completions, boolean typedWordValid,
boolean haveMinimalSuggestion) {
if (mIsShowingHint) {
setCandidatesViewShown(true);
mIsShowingHint = false;
}
if (mCandidateView != null) {
mCandidateView.setSuggestions(suggestions, completions,
typedWordValid, haveMinimalSuggestion);
}
}
private void updateSuggestions() {
LatinKeyboardView inputView = mKeyboardSwitcher.getInputView();
((LatinKeyboard) inputView.getKeyboard()).setPreferredLetters(null);
// Check if we have a suggestion engine attached.
if ((mSuggest == null || !isPredictionOn())) {
return;
}
if (!mPredicting) {
setNextSuggestions();
return;
}
showSuggestions(mWord);
}
private List<CharSequence> getTypedSuggestions(WordComposer word) {
List<CharSequence> stringList = mSuggest.getSuggestions(
mKeyboardSwitcher.getInputView(), word, false, null);
return stringList;
}
private void showCorrections(WordAlternatives alternatives) {
List<CharSequence> stringList = alternatives.getAlternatives();
((LatinKeyboard) mKeyboardSwitcher.getInputView().getKeyboard())
.setPreferredLetters(null);
showSuggestions(stringList, alternatives.getOriginalWord(), false,
false);
}
private void showSuggestions(WordComposer word) {
// long startTime = System.currentTimeMillis(); // TIME MEASUREMENT!
// TODO Maybe need better way of retrieving previous word
CharSequence prevWord = EditingUtil.getPreviousWord(
getCurrentInputConnection(), mWordSeparators);
List<CharSequence> stringList = mSuggest.getSuggestions(
mKeyboardSwitcher.getInputView(), word, false, prevWord);
// long stopTime = System.currentTimeMillis(); // TIME MEASUREMENT!
// Log.d("LatinIME","Suggest Total Time - " + (stopTime - startTime));
int[] nextLettersFrequencies = mSuggest.getNextLettersFrequencies();
((LatinKeyboard) mKeyboardSwitcher.getInputView().getKeyboard())
.setPreferredLetters(nextLettersFrequencies);
boolean correctionAvailable = !mInputTypeNoAutoCorrect
&& mSuggest.hasMinimalCorrection();
// || mCorrectionMode == mSuggest.CORRECTION_FULL;
CharSequence typedWord = word.getTypedWord();
// If we're in basic correct
boolean typedWordValid = mSuggest.isValidWord(typedWord)
|| (preferCapitalization() && mSuggest.isValidWord(typedWord
.toString().toLowerCase()));
if (mCorrectionMode == Suggest.CORRECTION_FULL
|| mCorrectionMode == Suggest.CORRECTION_FULL_BIGRAM) {
correctionAvailable |= typedWordValid;
}
// Don't auto-correct words with multiple capital letter
correctionAvailable &= !word.isMostlyCaps();
correctionAvailable &= !TextEntryState.isCorrecting();
showSuggestions(stringList, typedWord, typedWordValid,
correctionAvailable);
}
private void showSuggestions(List<CharSequence> stringList,
CharSequence typedWord, boolean typedWordValid,
boolean correctionAvailable) {
setSuggestions(stringList, false, typedWordValid, correctionAvailable);
if (stringList.size() > 0) {
if (correctionAvailable && !typedWordValid && stringList.size() > 1) {
mBestWord = stringList.get(1);
} else {
mBestWord = typedWord;
}
} else {
mBestWord = null;
}
setCandidatesViewShown(isCandidateStripVisible() || mCompletionOn);
}
private boolean pickDefaultSuggestion() {
// Complete any pending candidate query first
if (mHandler.hasMessages(MSG_UPDATE_SUGGESTIONS)) {
mHandler.removeMessages(MSG_UPDATE_SUGGESTIONS);
updateSuggestions();
}
if (mBestWord != null && mBestWord.length() > 0) {
TextEntryState.acceptedDefault(mWord.getTypedWord(), mBestWord);
mJustAccepted = true;
pickSuggestion(mBestWord, false);
// Add the word to the auto dictionary if it's not a known word
addToDictionaries(mBestWord, AutoDictionary.FREQUENCY_FOR_TYPED);
return true;
}
return false;
}
public void pickSuggestionManually(int index, CharSequence suggestion) {
List<CharSequence> suggestions = mCandidateView.getSuggestions();
final boolean correcting = TextEntryState.isCorrecting();
InputConnection ic = getCurrentInputConnection();
if (ic != null) {
ic.beginBatchEdit();
}
if (mCompletionOn && mCompletions != null && index >= 0
&& index < mCompletions.length) {
CompletionInfo ci = mCompletions[index];
if (ic != null) {
ic.commitCompletion(ci);
}
mCommittedLength = suggestion.length();
if (mCandidateView != null) {
mCandidateView.clear();
}
updateShiftKeyState(getCurrentInputEditorInfo());
if (ic != null) {
ic.endBatchEdit();
}
return;
}
// If this is a punctuation, apply it through the normal key press
if (suggestion.length() == 1
&& (isWordSeparator(suggestion.charAt(0)) || isSuggestedPunctuation(suggestion
.charAt(0)))) {
// Word separators are suggested before the user inputs something.
// So, LatinImeLogger logs "" as a user's input.
LatinImeLogger.logOnManualSuggestion("", suggestion.toString(),
index, suggestions);
final char primaryCode = suggestion.charAt(0);
onKey(primaryCode, new int[] { primaryCode },
LatinKeyboardBaseView.NOT_A_TOUCH_COORDINATE,
LatinKeyboardBaseView.NOT_A_TOUCH_COORDINATE);
if (ic != null) {
ic.endBatchEdit();
}
return;
}
mJustAccepted = true;
pickSuggestion(suggestion, correcting);
// Add the word to the auto dictionary if it's not a known word
if (index == 0) {
addToDictionaries(suggestion, AutoDictionary.FREQUENCY_FOR_PICKED);
} else {
addToBigramDictionary(suggestion, 1);
}
LatinImeLogger.logOnManualSuggestion(mComposing.toString(), suggestion
.toString(), index, suggestions);
TextEntryState.acceptedSuggestion(mComposing.toString(), suggestion);
// Follow it with a space
if (mAutoSpace && !correcting) {
sendSpace();
mJustAddedAutoSpace = true;
}
final boolean showingAddToDictionaryHint = index == 0
&& mCorrectionMode > 0 && !mSuggest.isValidWord(suggestion)
&& !mSuggest.isValidWord(suggestion.toString().toLowerCase());
if (!correcting) {
// Fool the state watcher so that a subsequent backspace will not do
// a revert, unless
// we just did a correction, in which case we need to stay in
// TextEntryState.State.PICKED_SUGGESTION state.
TextEntryState.typedCharacter((char) ASCII_SPACE, true);
setNextSuggestions();
} else if (!showingAddToDictionaryHint) {
// If we're not showing the "Touch again to save", then show
// corrections again.
// In case the cursor position doesn't change, make sure we show the
// suggestions again.
clearSuggestions();
postUpdateOldSuggestions();
}
if (showingAddToDictionaryHint) {
mCandidateView.showAddToDictionaryHint(suggestion);
}
if (ic != null) {
ic.endBatchEdit();
}
}
private void rememberReplacedWord(CharSequence suggestion) {
}
/**
* Commits the chosen word to the text field and saves it for later
* retrieval.
*
* @param suggestion
* the suggestion picked by the user to be committed to the text
* field
* @param correcting
* whether this is due to a correction of an existing word.
*/
private void pickSuggestion(CharSequence suggestion, boolean correcting) {
LatinKeyboardView inputView = mKeyboardSwitcher.getInputView();
int shiftState = getShiftState();
if (shiftState == Keyboard.SHIFT_LOCKED || shiftState == Keyboard.SHIFT_CAPS_LOCKED) {
suggestion = suggestion.toString().toUpperCase(); // all UPPERCASE
}
InputConnection ic = getCurrentInputConnection();
if (ic != null) {
rememberReplacedWord(suggestion);
ic.commitText(suggestion, 1);
}
saveWordInHistory(suggestion);
mPredicting = false;
mCommittedLength = suggestion.length();
((LatinKeyboard) inputView.getKeyboard()).setPreferredLetters(null);
// If we just corrected a word, then don't show punctuations
if (!correcting) {
setNextSuggestions();
}
updateShiftKeyState(getCurrentInputEditorInfo());
}
/**
* Tries to apply any typed alternatives for the word if we have any cached
* alternatives, otherwise tries to find new corrections and completions for
* the word.
*
* @param touching
* The word that the cursor is touching, with position
* information
* @return true if an alternative was found, false otherwise.
*/
private boolean applyTypedAlternatives(EditingUtil.SelectedWord touching) {
// If we didn't find a match, search for result in typed word history
WordComposer foundWord = null;
WordAlternatives alternatives = null;
for (WordAlternatives entry : mWordHistory) {
if (TextUtils.equals(entry.getChosenWord(), touching.word)) {
if (entry instanceof TypedWordAlternatives) {
foundWord = ((TypedWordAlternatives) entry).word;
}
alternatives = entry;
break;
}
}
// If we didn't find a match, at least suggest completions
if (foundWord == null
&& (mSuggest.isValidWord(touching.word) || mSuggest
.isValidWord(touching.word.toString().toLowerCase()))) {
foundWord = new WordComposer();
for (int i = 0; i < touching.word.length(); i++) {
foundWord.add(touching.word.charAt(i),
new int[] { touching.word.charAt(i) });
}
foundWord.setFirstCharCapitalized(Character
.isUpperCase(touching.word.charAt(0)));
}
// Found a match, show suggestions
if (foundWord != null || alternatives != null) {
if (alternatives == null) {
alternatives = new TypedWordAlternatives(touching.word,
foundWord);
}
showCorrections(alternatives);
if (foundWord != null) {
mWord = new WordComposer(foundWord);
} else {
mWord.reset();
}
return true;
}
return false;
}
private void setOldSuggestions() {
if (mCandidateView != null
&& mCandidateView.isShowingAddToDictionaryHint()) {
return;
}
InputConnection ic = getCurrentInputConnection();
if (ic == null)
return;
if (!mPredicting) {
// Extract the selected or touching text
EditingUtil.SelectedWord touching = EditingUtil
.getWordAtCursorOrSelection(ic, mLastSelectionStart,
mLastSelectionEnd, mWordSeparators);
abortCorrection(true);
setNextSuggestions(); // Show the punctuation suggestions list
} else {
abortCorrection(true);
}
}
private void setNextSuggestions() {
setSuggestions(mSuggestPuncList, false, false, false);
}
private void addToDictionaries(CharSequence suggestion, int frequencyDelta) {
checkAddToDictionary(suggestion, frequencyDelta, false);
}
private void addToBigramDictionary(CharSequence suggestion,
int frequencyDelta) {
checkAddToDictionary(suggestion, frequencyDelta, true);
}
/**
* Adds to the UserBigramDictionary and/or AutoDictionary
*
* @param addToBigramDictionary
* true if it should be added to bigram dictionary if possible
*/
private void checkAddToDictionary(CharSequence suggestion,
int frequencyDelta, boolean addToBigramDictionary) {
if (suggestion == null || suggestion.length() < 1)
return;
// Only auto-add to dictionary if auto-correct is ON. Otherwise we'll be
// adding words in situations where the user or application really
// didn't
// want corrections enabled or learned.
if (!(mCorrectionMode == Suggest.CORRECTION_FULL || mCorrectionMode == Suggest.CORRECTION_FULL_BIGRAM)) {
return;
}
if (suggestion != null) {
if (!addToBigramDictionary
&& mAutoDictionary.isValidWord(suggestion)
|| (!mSuggest.isValidWord(suggestion.toString()) && !mSuggest
.isValidWord(suggestion.toString().toLowerCase()))) {
mAutoDictionary.addWord(suggestion.toString(), frequencyDelta);
}
if (mUserBigramDictionary != null) {
CharSequence prevWord = EditingUtil.getPreviousWord(
getCurrentInputConnection(), mSentenceSeparators);
if (!TextUtils.isEmpty(prevWord)) {
mUserBigramDictionary.addBigrams(prevWord.toString(),
suggestion.toString());
}
}
}
}
private boolean isCursorTouchingWord() {
InputConnection ic = getCurrentInputConnection();
if (ic == null)
return false;
CharSequence toLeft = ic.getTextBeforeCursor(1, 0);
CharSequence toRight = ic.getTextAfterCursor(1, 0);
if (!TextUtils.isEmpty(toLeft) && !isWordSeparator(toLeft.charAt(0))
&& !isSuggestedPunctuation(toLeft.charAt(0))) {
return true;
}
if (!TextUtils.isEmpty(toRight) && !isWordSeparator(toRight.charAt(0))
&& !isSuggestedPunctuation(toRight.charAt(0))) {
return true;
}
return false;
}
private boolean sameAsTextBeforeCursor(InputConnection ic, CharSequence text) {
CharSequence beforeText = ic.getTextBeforeCursor(text.length(), 0);
return TextUtils.equals(text, beforeText);
}
public void revertLastWord(boolean deleteChar) {
final int length = mComposing.length();
if (!mPredicting && length > 0) {
final InputConnection ic = getCurrentInputConnection();
mPredicting = true;
mJustRevertedSeparator = ic.getTextBeforeCursor(1, 0);
if (deleteChar)
ic.deleteSurroundingText(1, 0);
int toDelete = mCommittedLength;
CharSequence toTheLeft = ic
.getTextBeforeCursor(mCommittedLength, 0);
if (toTheLeft != null && toTheLeft.length() > 0
&& isWordSeparator(toTheLeft.charAt(0))) {
toDelete--;
}
ic.deleteSurroundingText(toDelete, 0);
ic.setComposingText(mComposing, 1);
TextEntryState.backspace();
postUpdateSuggestions();
} else {
sendDownUpKeyEvents(KeyEvent.KEYCODE_DEL);
mJustRevertedSeparator = null;
}
}
protected String getWordSeparators() {
return mWordSeparators;
}
public boolean isWordSeparator(int code) {
String separators = getWordSeparators();
return separators.contains(String.valueOf((char) code));
}
private boolean isSentenceSeparator(int code) {
return mSentenceSeparators.contains(String.valueOf((char) code));
}
private void sendSpace() {
sendModifiableKeyChar((char) ASCII_SPACE);
updateShiftKeyState(getCurrentInputEditorInfo());
// onKey(KEY_SPACE[0], KEY_SPACE);
}
public boolean preferCapitalization() {
return mWord.isFirstCharCapitalized();
}
void toggleLanguage(boolean reset, boolean next) {
if (reset) {
mLanguageSwitcher.reset();
} else {
if (next) {
mLanguageSwitcher.next();
} else {
mLanguageSwitcher.prev();
}
}
int currentKeyboardMode = mKeyboardSwitcher.getKeyboardMode();
reloadKeyboards();
mKeyboardSwitcher.makeKeyboards(true);
mKeyboardSwitcher.setKeyboardMode(currentKeyboardMode, 0,
mEnableVoiceButton && mEnableVoice);
initSuggest(mLanguageSwitcher.getInputLanguage());
mLanguageSwitcher.persist();
mAutoCapActive = mAutoCapPref && mLanguageSwitcher.allowAutoCap();
mDeadKeysActive = mLanguageSwitcher.allowDeadKeys();
updateShiftKeyState(getCurrentInputEditorInfo());
setCandidatesViewShown(isPredictionOn());
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
Log.i("PCKeyboard", "onSharedPreferenceChanged()");
boolean needReload = false;
Resources res = getResources();
// Apply globally handled shared prefs
sKeyboardSettings.sharedPreferenceChanged(sharedPreferences, key);
if (sKeyboardSettings.hasFlag(GlobalKeyboardSettings.FLAG_PREF_NEED_RELOAD)) {
needReload = true;
}
if (sKeyboardSettings.hasFlag(GlobalKeyboardSettings.FLAG_PREF_NEW_PUNC_LIST)) {
initSuggestPuncList();
}
if (sKeyboardSettings.hasFlag(GlobalKeyboardSettings.FLAG_PREF_RECREATE_INPUT_VIEW)) {
mKeyboardSwitcher.recreateInputView();
}
if (sKeyboardSettings.hasFlag(GlobalKeyboardSettings.FLAG_PREF_RESET_MODE_OVERRIDE)) {
mKeyboardModeOverrideLandscape = 0;
mKeyboardModeOverridePortrait = 0;
}
if (sKeyboardSettings.hasFlag(GlobalKeyboardSettings.FLAG_PREF_RESET_KEYBOARDS)) {
toggleLanguage(true, true);
}
int unhandledFlags = sKeyboardSettings.unhandledFlags();
if (unhandledFlags != GlobalKeyboardSettings.FLAG_PREF_NONE) {
Log.w(TAG, "Not all flag settings handled, remaining=" + unhandledFlags);
}
if (PREF_SELECTED_LANGUAGES.equals(key)) {
mLanguageSwitcher.loadLocales(sharedPreferences);
mRefreshKeyboardRequired = true;
} else if (PREF_RECORRECTION_ENABLED.equals(key)) {
mReCorrectionEnabled = sharedPreferences.getBoolean(
PREF_RECORRECTION_ENABLED, res
.getBoolean(R.bool.default_recorrection_enabled));
if (mReCorrectionEnabled) {
// It doesn't work right on pre-Gingerbread phones.
Toast.makeText(getApplicationContext(),
res.getString(R.string.recorrect_warning), Toast.LENGTH_LONG)
.show();
}
} else if (PREF_CONNECTBOT_TAB_HACK.equals(key)) {
mConnectbotTabHack = sharedPreferences.getBoolean(
PREF_CONNECTBOT_TAB_HACK, res
.getBoolean(R.bool.default_connectbot_tab_hack));
} else if (PREF_FULLSCREEN_OVERRIDE.equals(key)) {
mFullscreenOverride = sharedPreferences.getBoolean(
PREF_FULLSCREEN_OVERRIDE, res
.getBoolean(R.bool.default_fullscreen_override));
needReload = true;
} else if (PREF_FORCE_KEYBOARD_ON.equals(key)) {
mForceKeyboardOn = sharedPreferences.getBoolean(
PREF_FORCE_KEYBOARD_ON, res
.getBoolean(R.bool.default_force_keyboard_on));
needReload = true;
} else if (PREF_KEYBOARD_NOTIFICATION.equals(key)) {
mKeyboardNotification = sharedPreferences.getBoolean(
PREF_KEYBOARD_NOTIFICATION, res
.getBoolean(R.bool.default_keyboard_notification));
setNotification(mKeyboardNotification);
} else if (PREF_SUGGESTIONS_IN_LANDSCAPE.equals(key)) {
mSuggestionsInLandscape = sharedPreferences.getBoolean(
PREF_SUGGESTIONS_IN_LANDSCAPE, res
.getBoolean(R.bool.default_suggestions_in_landscape));
// Respect the suggestion settings in legacy Gingerbread mode,
// in portrait mode, or if suggestions in landscape enabled.
mSuggestionForceOff = false;
mSuggestionForceOn = false;
setCandidatesViewShown(isPredictionOn());
} else if (PREF_SHOW_SUGGESTIONS.equals(key)) {
mShowSuggestions = sharedPreferences.getBoolean(
PREF_SHOW_SUGGESTIONS, res.getBoolean(R.bool.default_suggestions));
mSuggestionForceOff = false;
mSuggestionForceOn = false;
needReload = true;
} else if (PREF_HEIGHT_PORTRAIT.equals(key)) {
mHeightPortrait = getHeight(sharedPreferences,
PREF_HEIGHT_PORTRAIT, res.getString(R.string.default_height_portrait));
needReload = true;
} else if (PREF_HEIGHT_LANDSCAPE.equals(key)) {
mHeightLandscape = getHeight(sharedPreferences,
PREF_HEIGHT_LANDSCAPE, res.getString(R.string.default_height_landscape));
needReload = true;
} else if (PREF_HINT_MODE.equals(key)) {
LatinIME.sKeyboardSettings.hintMode = Integer.parseInt(sharedPreferences.getString(PREF_HINT_MODE,
res.getString(R.string.default_hint_mode)));
needReload = true;
} else if (PREF_LONGPRESS_TIMEOUT.equals(key)) {
LatinIME.sKeyboardSettings.longpressTimeout = getPrefInt(sharedPreferences, PREF_LONGPRESS_TIMEOUT,
res.getString(R.string.default_long_press_duration));
} else if (PREF_RENDER_MODE.equals(key)) {
LatinIME.sKeyboardSettings.renderMode = getPrefInt(sharedPreferences, PREF_RENDER_MODE,
res.getString(R.string.default_render_mode));
needReload = true;
} else if (PREF_SWIPE_UP.equals(key)) {
mSwipeUpAction = sharedPreferences.getString(PREF_SWIPE_UP, res.getString(R.string.default_swipe_up));
} else if (PREF_SWIPE_DOWN.equals(key)) {
mSwipeDownAction = sharedPreferences.getString(PREF_SWIPE_DOWN, res.getString(R.string.default_swipe_down));
} else if (PREF_SWIPE_LEFT.equals(key)) {
mSwipeLeftAction = sharedPreferences.getString(PREF_SWIPE_LEFT, res.getString(R.string.default_swipe_left));
} else if (PREF_SWIPE_RIGHT.equals(key)) {
mSwipeRightAction = sharedPreferences.getString(PREF_SWIPE_RIGHT, res.getString(R.string.default_swipe_right));
} else if (PREF_VOL_UP.equals(key)) {
mVolUpAction = sharedPreferences.getString(PREF_VOL_UP, res.getString(R.string.default_vol_up));
} else if (PREF_VOL_DOWN.equals(key)) {
mVolDownAction = sharedPreferences.getString(PREF_VOL_DOWN, res.getString(R.string.default_vol_down));
} else if (PREF_VIBRATE_LEN.equals(key)) {
mVibrateLen = getPrefInt(sharedPreferences, PREF_VIBRATE_LEN, getResources().getString(R.string.vibrate_duration_ms));
}
updateKeyboardOptions();
if (needReload) {
mKeyboardSwitcher.makeKeyboards(true);
}
}
private boolean doSwipeAction(String action) {
//Log.i(TAG, "doSwipeAction + " + action);
if (action == null || action.equals("") || action.equals("none")) {
return false;
} else if (action.equals("close")) {
handleClose();
} else if (action.equals("settings")) {
launchSettings();
} else if (action.equals("suggestions")) {
if (mSuggestionForceOn) {
mSuggestionForceOn = false;
mSuggestionForceOff = true;
} else if (mSuggestionForceOff) {
mSuggestionForceOn = true;
mSuggestionForceOff = false;
} else if (isPredictionWanted()) {
mSuggestionForceOff = true;
} else {
mSuggestionForceOn = true;
}
setCandidatesViewShown(isPredictionOn());
} else if (action.equals("lang_prev")) {
toggleLanguage(false, false);
} else if (action.equals("lang_next")) {
toggleLanguage(false, true);
} else if (action.equals("debug_auto_play")) {
if (LatinKeyboardView.DEBUG_AUTO_PLAY) {
ClipboardManager cm = ((ClipboardManager) getSystemService(CLIPBOARD_SERVICE));
CharSequence text = cm.getText();
if (!TextUtils.isEmpty(text)) {
mKeyboardSwitcher.getInputView().startPlaying(text.toString());
}
}
} else if (action.equals("full_mode")) {
if (isPortrait()) {
mKeyboardModeOverridePortrait = (mKeyboardModeOverridePortrait + 1) % mNumKeyboardModes;
} else {
mKeyboardModeOverrideLandscape = (mKeyboardModeOverrideLandscape + 1) % mNumKeyboardModes;
}
toggleLanguage(true, true);
} else if (action.equals("extension")) {
sKeyboardSettings.useExtension = !sKeyboardSettings.useExtension;
reloadKeyboards();
} else if (action.equals("height_up")) {
if (isPortrait()) {
mHeightPortrait += 5;
if (mHeightPortrait > 70) mHeightPortrait = 70;
} else {
mHeightLandscape += 5;
if (mHeightLandscape > 70) mHeightLandscape = 70;
}
toggleLanguage(true, true);
} else if (action.equals("height_down")) {
if (isPortrait()) {
mHeightPortrait -= 5;
if (mHeightPortrait < 15) mHeightPortrait = 15;
} else {
mHeightLandscape -= 5;
if (mHeightLandscape < 15) mHeightLandscape = 15;
}
toggleLanguage(true, true);
} else {
Log.i(TAG, "Unsupported swipe action config: " + action);
}
return true;
}
public boolean swipeRight() {
return doSwipeAction(mSwipeRightAction);
}
public boolean swipeLeft() {
return doSwipeAction(mSwipeLeftAction);
}
public boolean swipeDown() {
return doSwipeAction(mSwipeDownAction);
}
public boolean swipeUp() {
return doSwipeAction(mSwipeUpAction);
}
public void onPress(int primaryCode) {
InputConnection ic = getCurrentInputConnection();
if (mKeyboardSwitcher.isVibrateAndSoundFeedbackRequired()) {
vibrate();
playKeyClick(primaryCode);
}
final boolean distinctMultiTouch = mKeyboardSwitcher
.hasDistinctMultitouch();
if (distinctMultiTouch && primaryCode == Keyboard.KEYCODE_SHIFT) {
mShiftKeyState.onPress();
startMultitouchShift();
} else if (distinctMultiTouch
&& primaryCode == Keyboard.KEYCODE_MODE_CHANGE) {
changeKeyboardMode();
mSymbolKeyState.onPress();
mKeyboardSwitcher.setAutoModeSwitchStateMomentary();
} else if (distinctMultiTouch
&& primaryCode == LatinKeyboardView.KEYCODE_CTRL_LEFT) {
setModCtrl(!mModCtrl);
mCtrlKeyState.onPress();
sendCtrlKey(ic, true, true);
} else if (distinctMultiTouch
&& primaryCode == LatinKeyboardView.KEYCODE_ALT_LEFT) {
setModAlt(!mModAlt);
mAltKeyState.onPress();
sendAltKey(ic, true, true);
} else if (distinctMultiTouch
&& primaryCode == LatinKeyboardView.KEYCODE_META_LEFT) {
setModMeta(!mModMeta);
mMetaKeyState.onPress();
sendMetaKey(ic, true, true);
} else if (distinctMultiTouch
&& primaryCode == LatinKeyboardView.KEYCODE_FN) {
setModFn(!mModFn);
mFnKeyState.onPress();
} else {
mShiftKeyState.onOtherKeyPressed();
mSymbolKeyState.onOtherKeyPressed();
mCtrlKeyState.onOtherKeyPressed();
mAltKeyState.onOtherKeyPressed();
mMetaKeyState.onOtherKeyPressed();
mFnKeyState.onOtherKeyPressed();
}
}
public void onRelease(int primaryCode) {
// Reset any drag flags in the keyboard
((LatinKeyboard) mKeyboardSwitcher.getInputView().getKeyboard())
.keyReleased();
// vibrate();
final boolean distinctMultiTouch = mKeyboardSwitcher
.hasDistinctMultitouch();
InputConnection ic = getCurrentInputConnection();
if (distinctMultiTouch && primaryCode == Keyboard.KEYCODE_SHIFT) {
if (mShiftKeyState.isChording()) {
resetMultitouchShift();
} else {
commitMultitouchShift();
}
mShiftKeyState.onRelease();
} else if (distinctMultiTouch
&& primaryCode == Keyboard.KEYCODE_MODE_CHANGE) {
// Snap back to the previous keyboard mode if the user chords the
// mode change key and
// other key, then released the mode change key.
if (mKeyboardSwitcher.isInChordingAutoModeSwitchState())
changeKeyboardMode();
mSymbolKeyState.onRelease();
} else if (distinctMultiTouch
&& primaryCode == LatinKeyboardView.KEYCODE_CTRL_LEFT) {
if (mCtrlKeyState.isChording()) {
setModCtrl(false);
}
sendCtrlKey(ic, false, true);
mCtrlKeyState.onRelease();
} else if (distinctMultiTouch
&& primaryCode == LatinKeyboardView.KEYCODE_ALT_LEFT) {
if (mAltKeyState.isChording()) {
setModAlt(false);
}
sendAltKey(ic, false, true);
mAltKeyState.onRelease();
} else if (distinctMultiTouch
&& primaryCode == LatinKeyboardView.KEYCODE_META_LEFT) {
if (mMetaKeyState.isChording()) {
setModMeta(false);
}
sendMetaKey(ic, false, true);
mMetaKeyState.onRelease();
} else if (distinctMultiTouch
&& primaryCode == LatinKeyboardView.KEYCODE_FN) {
if (mFnKeyState.isChording()) {
setModFn(false);
}
mFnKeyState.onRelease();
}
// WARNING: Adding a chording modifier key? Make sure you also
// edit PointerTracker.isModifierInternal(), otherwise it will
// force a release event instead of chording.
}
// receive ringer mode changes to detect silent mode
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
updateRingerMode();
}
};
// update flags for silent mode
private void updateRingerMode() {
if (mAudioManager == null) {
mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
}
if (mAudioManager != null) {
mSilentMode = (mAudioManager.getRingerMode() != AudioManager.RINGER_MODE_NORMAL);
}
}
private float getKeyClickVolume() {
if (mAudioManager == null) return 0.0f; // shouldn't happen
// The volume calculations are poorly documented, this is the closest I could
// find for explaining volume conversions:
// http://developer.android.com/reference/android/media/MediaPlayer.html#setAuxEffectSendLevel(float)
//
// Note that the passed level value is a raw scalar. UI controls should be scaled logarithmically:
// the gain applied by audio framework ranges from -72dB to 0dB, so an appropriate conversion
// from linear UI input x to level is: x == 0 -> level = 0 0 < x <= R -> level = 10^(72*(x-R)/20/R)
int method = sKeyboardSettings.keyClickMethod; // See click_method_values in strings.xml
if (method == 0) return FX_VOLUME;
float targetVol = sKeyboardSettings.keyClickVolume;
if (method > 1) {
// TODO(klausw): on some devices the media volume controls the click volume?
// If that's the case, try to set a relative target volume.
int mediaMax = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
int mediaVol = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
//Log.i(TAG, "getKeyClickVolume relative, media vol=" + mediaVol + "/" + mediaMax);
float channelVol = (float) mediaVol / mediaMax;
if (method == 2) {
targetVol *= channelVol;
} else if (method == 3) {
if (channelVol == 0) return 0.0f; // Channel is silent, won't get audio
targetVol = Math.min(targetVol / channelVol, 1.0f); // Cap at 1.0
}
}
// Set absolute volume, treating the percentage as a logarithmic control
float vol = (float) Math.pow(10.0, FX_VOLUME_RANGE_DB * (targetVol - 1) / 20);
//Log.i(TAG, "getKeyClickVolume absolute, target=" + targetVol + " amp=" + vol);
return vol;
}
private void playKeyClick(int primaryCode) {
// if mAudioManager is null, we don't have the ringer state yet
// mAudioManager will be set by updateRingerMode
if (mAudioManager == null) {
if (mKeyboardSwitcher.getInputView() != null) {
updateRingerMode();
}
}
if (mSoundOn && !mSilentMode) {
// FIXME: Volume and enable should come from UI settings
// FIXME: These should be triggered after auto-repeat logic
int sound = AudioManager.FX_KEYPRESS_STANDARD;
switch (primaryCode) {
case Keyboard.KEYCODE_DELETE:
sound = AudioManager.FX_KEYPRESS_DELETE;
break;
case ASCII_ENTER:
sound = AudioManager.FX_KEYPRESS_RETURN;
break;
case ASCII_SPACE:
sound = AudioManager.FX_KEYPRESS_SPACEBAR;
break;
}
mAudioManager.playSoundEffect(sound, getKeyClickVolume());
}
}
private void vibrate() {
if (!mVibrateOn) {
return;
}
vibrate(mVibrateLen);
}
void vibrate(int len) {
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
if (v != null) {
v.vibrate(len);
return;
}
if (mKeyboardSwitcher.getInputView() != null) {
mKeyboardSwitcher.getInputView().performHapticFeedback(
HapticFeedbackConstants.KEYBOARD_TAP,
HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING);
}
}
private void checkTutorial(String privateImeOptions) {
if (privateImeOptions == null)
return;
if (privateImeOptions.equals("com.android.setupwizard:ShowTutorial")) {
if (mTutorial == null)
startTutorial();
} else if (privateImeOptions
.equals("com.android.setupwizard:HideTutorial")) {
if (mTutorial != null) {
if (mTutorial.close()) {
mTutorial = null;
}
}
}
}
private void startTutorial() {
mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_START_TUTORIAL),
500);
}
/* package */void tutorialDone() {
mTutorial = null;
}
/* package */void promoteToUserDictionary(String word, int frequency) {
if (mUserDictionary.isValidWord(word))
return;
mUserDictionary.addWord(word, frequency);
}
/* package */WordComposer getCurrentWord() {
return mWord;
}
/* package */boolean getPopupOn() {
return mPopupOn;
}
private void updateCorrectionMode() {
mHasDictionary = mSuggest != null ? mSuggest.hasMainDictionary()
: false;
mAutoCorrectOn = (mAutoCorrectEnabled || mQuickFixes)
&& !mInputTypeNoAutoCorrect && mHasDictionary;
mCorrectionMode = (mAutoCorrectOn && mAutoCorrectEnabled) ? Suggest.CORRECTION_FULL
: (mAutoCorrectOn ? Suggest.CORRECTION_BASIC
: Suggest.CORRECTION_NONE);
mCorrectionMode = (mBigramSuggestionEnabled && mAutoCorrectOn && mAutoCorrectEnabled) ? Suggest.CORRECTION_FULL_BIGRAM
: mCorrectionMode;
if (suggestionsDisabled()) {
mAutoCorrectOn = false;
mCorrectionMode = Suggest.CORRECTION_NONE;
}
if (mSuggest != null) {
mSuggest.setCorrectionMode(mCorrectionMode);
}
}
private void updateAutoTextEnabled(Locale systemLocale) {
if (mSuggest == null)
return;
boolean different = !systemLocale.getLanguage().equalsIgnoreCase(
mInputLocale.substring(0, 2));
mSuggest.setAutoTextEnabled(!different && mQuickFixes);
}
protected void launchSettings() {
launchSettings(LatinIMESettings.class);
}
public void launchDebugSettings() {
launchSettings(LatinIMEDebugSettings.class);
}
protected void launchSettings(
Class<? extends PreferenceActivity> settingsClass) {
handleClose();
Intent intent = new Intent();
intent.setClass(LatinIME.this, settingsClass);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
private void loadSettings() {
// Get the settings preferences
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(this);
mVibrateOn = sp.getBoolean(PREF_VIBRATE_ON, false);
mVibrateLen = getPrefInt(sp, PREF_VIBRATE_LEN, getResources().getString(R.string.vibrate_duration_ms));
mSoundOn = sp.getBoolean(PREF_SOUND_ON, false);
mPopupOn = sp.getBoolean(PREF_POPUP_ON, mResources
.getBoolean(R.bool.default_popup_preview));
mAutoCapPref = sp.getBoolean(PREF_AUTO_CAP, getResources().getBoolean(
R.bool.default_auto_cap));
mQuickFixes = sp.getBoolean(PREF_QUICK_FIXES, true);
mShowSuggestions = sp.getBoolean(PREF_SHOW_SUGGESTIONS, mResources
.getBoolean(R.bool.default_suggestions));
final String voiceMode = sp.getString(PREF_VOICE_MODE,
getString(R.string.voice_mode_main));
boolean enableVoice = !voiceMode
.equals(getString(R.string.voice_mode_off))
&& mEnableVoiceButton;
boolean voiceOnPrimary = voiceMode
.equals(getString(R.string.voice_mode_main));
if (mKeyboardSwitcher != null
&& (enableVoice != mEnableVoice || voiceOnPrimary != mVoiceOnPrimary)) {
mKeyboardSwitcher.setVoiceMode(enableVoice, voiceOnPrimary);
}
mEnableVoice = enableVoice;
mVoiceOnPrimary = voiceOnPrimary;
mAutoCorrectEnabled = sp.getBoolean(PREF_AUTO_COMPLETE, mResources
.getBoolean(R.bool.enable_autocorrect))
& mShowSuggestions;
// mBigramSuggestionEnabled = sp.getBoolean(
// PREF_BIGRAM_SUGGESTIONS, true) & mShowSuggestions;
updateCorrectionMode();
updateAutoTextEnabled(mResources.getConfiguration().locale);
mLanguageSwitcher.loadLocales(sp);
mAutoCapActive = mAutoCapPref && mLanguageSwitcher.allowAutoCap();
mDeadKeysActive = mLanguageSwitcher.allowDeadKeys();
}
private void initSuggestPuncList() {
mSuggestPuncList = new ArrayList<CharSequence>();
String suggestPuncs = sKeyboardSettings.suggestedPunctuation;
String defaultPuncs = getResources().getString(R.string.suggested_punctuations_default);
if (suggestPuncs.equals(defaultPuncs) || suggestPuncs.equals("")) {
// Not user-configured, load the language-specific default.
suggestPuncs = getResources().getString(R.string.suggested_punctuations);
}
if (suggestPuncs != null) {
for (int i = 0; i < suggestPuncs.length(); i++) {
mSuggestPuncList.add(suggestPuncs.subSequence(i, i + 1));
}
}
setNextSuggestions();
}
private boolean isSuggestedPunctuation(int code) {
return sKeyboardSettings.suggestedPunctuation.contains(String.valueOf((char) code));
}
private void showOptionsMenu() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setIcon(R.drawable.ic_dialog_keyboard);
builder.setNegativeButton(android.R.string.cancel, null);
CharSequence itemSettings = getString(R.string.english_ime_settings);
CharSequence itemInputMethod = getString(R.string.selectInputMethod);
builder.setItems(new CharSequence[] { itemInputMethod, itemSettings },
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface di, int position) {
di.dismiss();
switch (position) {
case POS_SETTINGS:
launchSettings();
break;
case POS_METHOD:
((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
.showInputMethodPicker();
break;
}
}
});
builder.setTitle(mResources
.getString(R.string.english_ime_input_options));
mOptionsDialog = builder.create();
Window window = mOptionsDialog.getWindow();
WindowManager.LayoutParams lp = window.getAttributes();
lp.token = mKeyboardSwitcher.getInputView().getWindowToken();
lp.type = WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG;
window.setAttributes(lp);
window.addFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
mOptionsDialog.show();
}
public void changeKeyboardMode() {
KeyboardSwitcher switcher = mKeyboardSwitcher;
if (switcher.isAlphabetMode()) {
mSavedShiftState = getShiftState();
}
switcher.toggleSymbols();
if (switcher.isAlphabetMode()) {
switcher.setShiftState(mSavedShiftState);
}
updateShiftKeyState(getCurrentInputEditorInfo());
}
public static <E> ArrayList<E> newArrayList(E... elements) {
int capacity = (elements.length * 110) / 100 + 5;
ArrayList<E> list = new ArrayList<E>(capacity);
Collections.addAll(list, elements);
return list;
}
@Override
protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
super.dump(fd, fout, args);
final Printer p = new PrintWriterPrinter(fout);
p.println("LatinIME state :");
p.println(" Keyboard mode = " + mKeyboardSwitcher.getKeyboardMode());
p.println(" mComposing=" + mComposing.toString());
p.println(" mPredictionOnForMode=" + mPredictionOnForMode);
p.println(" mCorrectionMode=" + mCorrectionMode);
p.println(" mPredicting=" + mPredicting);
p.println(" mAutoCorrectOn=" + mAutoCorrectOn);
p.println(" mAutoSpace=" + mAutoSpace);
p.println(" mCompletionOn=" + mCompletionOn);
p.println(" TextEntryState.state=" + TextEntryState.getState());
p.println(" mSoundOn=" + mSoundOn);
p.println(" mVibrateOn=" + mVibrateOn);
p.println(" mPopupOn=" + mPopupOn);
}
// Characters per second measurement
private long mLastCpsTime;
private static final int CPS_BUFFER_SIZE = 16;
private long[] mCpsIntervals = new long[CPS_BUFFER_SIZE];
private int mCpsIndex;
private static Pattern NUMBER_RE = Pattern.compile("(\\d+).*");
private void measureCps() {
long now = System.currentTimeMillis();
if (mLastCpsTime == 0)
mLastCpsTime = now - 100; // Initial
mCpsIntervals[mCpsIndex] = now - mLastCpsTime;
mLastCpsTime = now;
mCpsIndex = (mCpsIndex + 1) % CPS_BUFFER_SIZE;
long total = 0;
for (int i = 0; i < CPS_BUFFER_SIZE; i++)
total += mCpsIntervals[i];
System.out.println("CPS = " + ((CPS_BUFFER_SIZE * 1000f) / total));
}
public void onAutoCompletionStateChanged(boolean isAutoCompletion) {
mKeyboardSwitcher.onAutoCompletionStateChanged(isAutoCompletion);
}
static int getIntFromString(String val, int defVal) {
Matcher num = NUMBER_RE.matcher(val);
if (!num.matches()) return defVal;
return Integer.parseInt(num.group(1));
}
static int getPrefInt(SharedPreferences prefs, String prefName, int defVal) {
String prefVal = prefs.getString(prefName, Integer.toString(defVal));
//Log.i("PCKeyboard", "getPrefInt " + prefName + " = " + prefVal + ", default " + defVal);
return getIntFromString(prefVal, defVal);
}
static int getPrefInt(SharedPreferences prefs, String prefName, String defStr) {
int defVal = getIntFromString(defStr, 0);
return getPrefInt(prefs, prefName, defVal);
}
static int getHeight(SharedPreferences prefs, String prefName, String defVal) {
int val = getPrefInt(prefs, prefName, defVal);
if (val < 15)
val = 15;
if (val > 75)
val = 75;
return val;
}
}
| 11beeaosama-descrbvbnvbniption | java/src/org/pocketworkstation/pckeyboard/LatinIME.java | Java | asf20 | 146,087 |
/*
* Copyright (C) 2008-2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceGroup;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
public class InputLanguageSelection extends PreferenceActivity {
private static final String TAG = "PCKeyboardILS";
private ArrayList<Loc> mAvailableLanguages = new ArrayList<Loc>();
private static final String[] BLACKLIST_LANGUAGES = {
"ko", "ja", "zh"
};
// Languages for which auto-caps should be disabled
public static final Set<String> NOCAPS_LANGUAGES = new HashSet<String>();
static {
NOCAPS_LANGUAGES.add("ar");
NOCAPS_LANGUAGES.add("iw");
NOCAPS_LANGUAGES.add("th");
}
// Languages which should not use dead key logic. The modifier is entered after the base character.
public static final Set<String> NODEADKEY_LANGUAGES = new HashSet<String>();
static {
NODEADKEY_LANGUAGES.add("ar");
NODEADKEY_LANGUAGES.add("iw"); // TODO: currently no niqqud in the keymap?
NODEADKEY_LANGUAGES.add("th");
}
// Languages which should not auto-add space after completions
public static final Set<String> NOAUTOSPACE_LANGUAGES = new HashSet<String>();
static {
NOAUTOSPACE_LANGUAGES.add("th");
}
// Run the GetLanguages.sh script to update the following lists based on
// the available keyboard resources and dictionaries.
private static final String[] KBD_LOCALIZATIONS = {
"ar", "bg", "ca", "cs", "cs_QY", "da", "de", "el", "en", "en_DV",
"en_GB", "es", "es_LA", "es_US", "fa", "fi", "fr", "fr_CA", "he",
"hr", "hu", "hu_QY", "hy", "in", "it", "iw", "ja", "ka", "ko",
"lo", "lt", "lv", "nb", "nl", "pl", "pt", "pt_PT", "rm", "ro",
"ru", "ru_PH", "si", "sk", "sk_QY", "sl", "sr", "sv", "ta", "th",
"tl", "tr", "uk", "vi", "zh_CN", "zh_TW"
};
private static final String[] KBD_5_ROW = {
"ar", "bg", "cs", "cs_QY", "da", "de", "el", "en", "en_DV", "en_GB",
"es", "es_LA", "fa", "fi", "fr", "fr_CA", "he", "hr", "hu", "hu_QY",
"hy", "it", "iw", "lo", "nb", "pt_PT", "ro", "ru", "ru_PH", "si",
"sk", "sk_QY", "sl", "sr", "sv", "ta", "th", "tr", "uk"
};
private static final String[] KBD_4_ROW = {
"ar", "bg", "cs", "cs_QY", "da", "de", "el", "en", "en_DV", "es",
"es_LA", "es_US", "fa", "fr", "fr_CA", "he", "hr", "hu", "hu_QY",
"iw", "nb", "ru", "ru_PH", "sk", "sk_QY", "sl", "sr", "sv", "tr",
"uk"
};
private static String getLocaleName(Locale l) {
String lang = l.getLanguage();
String country = l.getCountry();
if (lang.equals("en") && country.equals("DV")) {
return "English (Dvorak)";
} else if (lang.equals("en") && country.equals("EX")) {
return "English (4x11)";
} else if (lang.equals("es") && country.equals("LA")) {
return "Español (Latinoamérica)";
} else if (lang.equals("cs") && country.equals("QY")) {
return "Čeština (QWERTY)";
} else if (lang.equals("hu") && country.equals("QY")) {
return "Magyar (QWERTY)";
} else if (lang.equals("sk") && country.equals("QY")) {
return "Slovenčina (QWERTY)";
} else if (lang.equals("ru") && country.equals("PH")) {
return "Русский (Phonetic)";
} else {
return LanguageSwitcher.toTitleCase(l.getDisplayName(l));
}
}
private static class Loc implements Comparable<Object> {
static Collator sCollator = Collator.getInstance();
String label;
Locale locale;
public Loc(String label, Locale locale) {
this.label = label;
this.locale = locale;
}
@Override
public String toString() {
return this.label;
}
public int compareTo(Object o) {
return sCollator.compare(this.label, ((Loc) o).label);
}
}
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
addPreferencesFromResource(R.xml.language_prefs);
// Get the settings preferences
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
String selectedLanguagePref = sp.getString(LatinIME.PREF_SELECTED_LANGUAGES, "");
Log.i(TAG, "selected languages: " + selectedLanguagePref);
String[] languageList = selectedLanguagePref.split(",");
mAvailableLanguages = getUniqueLocales();
// Compatibility hack for v1.22 and older - if a selected language 5-code isn't
// found in the current list of available languages, try adding the 2-letter
// language code. For example, "en_US" is no longer listed, so use "en" instead.
Set<String> availableLanguages = new HashSet<String>();
for (int i = 0; i < mAvailableLanguages.size(); i++) {
Locale locale = mAvailableLanguages.get(i).locale;
availableLanguages.add(get5Code(locale));
}
Set<String> languageSelections = new HashSet<String>();
for (int i = 0; i < languageList.length; ++i) {
String spec = languageList[i];
if (availableLanguages.contains(spec)) {
languageSelections.add(spec);
} else if (spec.length() > 2) {
String lang = spec.substring(0, 2);
if (availableLanguages.contains(lang)) languageSelections.add(lang);
}
}
PreferenceGroup parent = getPreferenceScreen();
for (int i = 0; i < mAvailableLanguages.size(); i++) {
CheckBoxPreference pref = new CheckBoxPreference(this);
Locale locale = mAvailableLanguages.get(i).locale;
pref.setTitle(mAvailableLanguages.get(i).label +
" [" + locale.toString() + "]");
String fivecode = get5Code(locale);
String language = locale.getLanguage();
boolean checked = languageSelections.contains(fivecode);
pref.setChecked(checked);
boolean has4Row = arrayContains(KBD_4_ROW, fivecode) || arrayContains(KBD_4_ROW, language);
boolean has5Row = arrayContains(KBD_5_ROW, fivecode) || arrayContains(KBD_5_ROW, language);
List<String> summaries = new ArrayList<String>(3);
if (has5Row) summaries.add("5-row");
if (has4Row) summaries.add("4-row");
if (hasDictionary(locale)) {
summaries.add(getResources().getString(R.string.has_dictionary));
}
if (!summaries.isEmpty()) {
StringBuilder summary = new StringBuilder();
for (int j = 0; j < summaries.size(); ++j) {
if (j > 0) summary.append(", ");
summary.append(summaries.get(j));
}
pref.setSummary(summary.toString());
}
parent.addPreference(pref);
}
}
private boolean hasDictionary(Locale locale) {
Resources res = getResources();
Configuration conf = res.getConfiguration();
Locale saveLocale = conf.locale;
boolean haveDictionary = false;
conf.locale = locale;
res.updateConfiguration(conf, res.getDisplayMetrics());
int[] dictionaries = LatinIME.getDictionary(res);
BinaryDictionary bd = new BinaryDictionary(this, dictionaries, Suggest.DIC_MAIN);
// Is the dictionary larger than a placeholder? Arbitrarily chose a lower limit of
// 4000-5000 words, whereas the LARGE_DICTIONARY is about 20000+ words.
if (bd.getSize() > Suggest.LARGE_DICTIONARY_THRESHOLD / 4) {
haveDictionary = true;
} else {
BinaryDictionary plug = PluginManager.getDictionary(getApplicationContext(), locale.getLanguage());
if (plug != null) {
bd.close();
bd = plug;
haveDictionary = true;
}
}
bd.close();
conf.locale = saveLocale;
res.updateConfiguration(conf, res.getDisplayMetrics());
return haveDictionary;
}
private String get5Code(Locale locale) {
String country = locale.getCountry();
return locale.getLanguage()
+ (TextUtils.isEmpty(country) ? "" : "_" + country);
}
@Override
protected void onResume() {
super.onResume();
}
@Override
protected void onPause() {
super.onPause();
// Save the selected languages
String checkedLanguages = "";
PreferenceGroup parent = getPreferenceScreen();
int count = parent.getPreferenceCount();
for (int i = 0; i < count; i++) {
CheckBoxPreference pref = (CheckBoxPreference) parent.getPreference(i);
if (pref.isChecked()) {
Locale locale = mAvailableLanguages.get(i).locale;
checkedLanguages += get5Code(locale) + ",";
}
}
if (checkedLanguages.length() < 1) checkedLanguages = null; // Save null
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
Editor editor = sp.edit();
editor.putString(LatinIME.PREF_SELECTED_LANGUAGES, checkedLanguages);
SharedPreferencesCompat.apply(editor);
}
private static String asString(Set<String> set) {
StringBuilder out = new StringBuilder();
out.append("set(");
String[] parts = new String[set.size()];
parts = set.toArray(parts);
Arrays.sort(parts);
for (int i = 0; i < parts.length; ++i) {
if (i > 0) out.append(", ");
out.append(parts[i]);
}
out.append(")");
return out.toString();
}
ArrayList<Loc> getUniqueLocales() {
Set<String> localeSet = new HashSet<String>();
Set<String> langSet = new HashSet<String>();
// Ignore the system (asset) locale list, it's inconsistent and incomplete
// String[] sysLocales = getAssets().getLocales();
//
// // First, add zz_ZZ style full language+country locales
// for (int i = 0; i < sysLocales.length; ++i) {
// String sl = sysLocales[i];
// if (sl.length() != 5) continue;
// localeSet.add(sl);
// langSet.add(sl.substring(0, 2));
// }
//
// // Add entries for system languages without country, but only if there's
// // no full locale for that language yet.
// for (int i = 0; i < sysLocales.length; ++i) {
// String sl = sysLocales[i];
// if (sl.length() != 2 || langSet.contains(sl)) continue;
// localeSet.add(sl);
// }
// Add entries for additional languages supported by the keyboard.
for (int i = 0; i < KBD_LOCALIZATIONS.length; ++i) {
String kl = KBD_LOCALIZATIONS[i];
if (kl.length() == 2 && langSet.contains(kl)) continue;
// replace zz_rYY with zz_YY
if (kl.length() == 6) kl = kl.substring(0, 2) + "_" + kl.substring(4, 6);
localeSet.add(kl);
}
Log.i(TAG, "localeSet=" + asString(localeSet));
Log.i(TAG, "langSet=" + asString(langSet));
// Now build the locale list for display
String[] locales = new String[localeSet.size()];
locales = localeSet.toArray(locales);
Arrays.sort(locales);
ArrayList<Loc> uniqueLocales = new ArrayList<Loc>();
final int origSize = locales.length;
Loc[] preprocess = new Loc[origSize];
int finalSize = 0;
for (int i = 0 ; i < origSize; i++ ) {
String s = locales[i];
int len = s.length();
if (len == 2 || len == 5 || len == 6) {
String language = s.substring(0, 2);
Locale l;
if (len == 5) {
// zz_YY
String country = s.substring(3, 5);
l = new Locale(language, country);
} else if (len == 6) {
// zz_rYY
l = new Locale(language, s.substring(4, 6));
} else {
l = new Locale(language);
}
// Exclude languages that are not relevant to LatinIME
if (arrayContains(BLACKLIST_LANGUAGES, language)) continue;
if (finalSize == 0) {
preprocess[finalSize++] =
new Loc(LanguageSwitcher.toTitleCase(l.getDisplayName(l)), l);
} else {
// check previous entry:
// same lang and a country -> upgrade to full name and
// insert ours with full name
// diff lang -> insert ours with lang-only name
if (preprocess[finalSize-1].locale.getLanguage().equals(
language)) {
preprocess[finalSize-1].label = getLocaleName(preprocess[finalSize-1].locale);
preprocess[finalSize++] =
new Loc(getLocaleName(l), l);
} else {
String displayName;
if (s.equals("zz_ZZ")) {
} else {
displayName = getLocaleName(l);
preprocess[finalSize++] = new Loc(displayName, l);
}
}
}
}
}
for (int i = 0; i < finalSize ; i++) {
uniqueLocales.add(preprocess[i]);
}
return uniqueLocales;
}
private boolean arrayContains(String[] array, String value) {
for (int i = 0; i < array.length; i++) {
if (array[i].equalsIgnoreCase(value)) return true;
}
return false;
}
}
| 11beeaosama-descrbvbnvbniption | java/src/org/pocketworkstation/pckeyboard/InputLanguageSelection.java | Java | asf20 | 15,082 |
/*
* Copyright (C) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import org.pocketworkstation.pckeyboard.Keyboard.Key;
import java.util.Arrays;
class ProximityKeyDetector extends KeyDetector {
private static final int MAX_NEARBY_KEYS = 12;
// working area
private int[] mDistances = new int[MAX_NEARBY_KEYS];
@Override
protected int getMaxNearbyKeys() {
return MAX_NEARBY_KEYS;
}
@Override
public int getKeyIndexAndNearbyCodes(int x, int y, int[] allKeys) {
final Key[] keys = getKeys();
final int touchX = getTouchX(x);
final int touchY = getTouchY(y);
int primaryIndex = LatinKeyboardBaseView.NOT_A_KEY;
int closestKey = LatinKeyboardBaseView.NOT_A_KEY;
int closestKeyDist = mProximityThresholdSquare + 1;
int[] distances = mDistances;
Arrays.fill(distances, Integer.MAX_VALUE);
int [] nearestKeyIndices = mKeyboard.getNearestKeys(touchX, touchY);
final int keyCount = nearestKeyIndices.length;
for (int i = 0; i < keyCount; i++) {
final Key key = keys[nearestKeyIndices[i]];
int dist = 0;
boolean isInside = key.isInside(touchX, touchY);
if (isInside) {
primaryIndex = nearestKeyIndices[i];
}
if (((mProximityCorrectOn
&& (dist = key.squaredDistanceFrom(touchX, touchY)) < mProximityThresholdSquare)
|| isInside)
&& key.codes[0] > 32) {
// Find insertion point
final int nCodes = key.codes.length;
if (dist < closestKeyDist) {
closestKeyDist = dist;
closestKey = nearestKeyIndices[i];
}
if (allKeys == null) continue;
for (int j = 0; j < distances.length; j++) {
if (distances[j] > dist) {
// Make space for nCodes codes
System.arraycopy(distances, j, distances, j + nCodes,
distances.length - j - nCodes);
System.arraycopy(allKeys, j, allKeys, j + nCodes,
allKeys.length - j - nCodes);
System.arraycopy(key.codes, 0, allKeys, j, nCodes);
Arrays.fill(distances, j, j + nCodes, dist);
break;
}
}
}
}
if (primaryIndex == LatinKeyboardBaseView.NOT_A_KEY) {
primaryIndex = closestKey;
}
return primaryIndex;
}
}
| 11beeaosama-descrbvbnvbniption | java/src/org/pocketworkstation/pckeyboard/ProximityKeyDetector.java | Java | asf20 | 3,229 |
/*
* Copyright (C) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import org.pocketworkstation.pckeyboard.Keyboard.Key;
class MiniKeyboardKeyDetector extends KeyDetector {
private static final int MAX_NEARBY_KEYS = 1;
private final int mSlideAllowanceSquare;
private final int mSlideAllowanceSquareTop;
public MiniKeyboardKeyDetector(float slideAllowance) {
super();
mSlideAllowanceSquare = (int)(slideAllowance * slideAllowance);
// Top slide allowance is slightly longer (sqrt(2) times) than other edges.
mSlideAllowanceSquareTop = mSlideAllowanceSquare * 2;
}
@Override
protected int getMaxNearbyKeys() {
return MAX_NEARBY_KEYS;
}
@Override
public int getKeyIndexAndNearbyCodes(int x, int y, int[] allKeys) {
final Key[] keys = getKeys();
final int touchX = getTouchX(x);
final int touchY = getTouchY(y);
int closestKeyIndex = LatinKeyboardBaseView.NOT_A_KEY;
int closestKeyDist = (y < 0) ? mSlideAllowanceSquareTop : mSlideAllowanceSquare;
final int keyCount = keys.length;
for (int i = 0; i < keyCount; i++) {
final Key key = keys[i];
int dist = key.squaredDistanceFrom(touchX, touchY);
if (dist < closestKeyDist) {
closestKeyIndex = i;
closestKeyDist = dist;
}
}
if (allKeys != null && closestKeyIndex != LatinKeyboardBaseView.NOT_A_KEY)
allKeys[0] = keys[closestKeyIndex].getPrimaryCode();
return closestKeyIndex;
}
}
| 11beeaosama-descrbvbnvbniption | java/src/org/pocketworkstation/pckeyboard/MiniKeyboardKeyDetector.java | Java | asf20 | 2,159 |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.pocketworkstation.pckeyboard;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BlurMaskFilter;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PorterDuffColorFilter;
import android.graphics.Paint.Align;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.graphics.Region.Op;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.StateListDrawable;
import org.pocketworkstation.pckeyboard.Keyboard.Key;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.PopupWindow;
import android.widget.TextView;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.Normalizer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.WeakHashMap;
/**
* A view that renders a virtual {@link LatinKeyboard}. It handles rendering of keys and
* detecting key presses and touch movements.
*
* TODO: References to LatinKeyboard in this class should be replaced with ones to its base class.
*
* @attr ref R.styleable#LatinKeyboardBaseView_keyBackground
* @attr ref R.styleable#LatinKeyboardBaseView_keyPreviewLayout
* @attr ref R.styleable#LatinKeyboardBaseView_keyPreviewOffset
* @attr ref R.styleable#LatinKeyboardBaseView_labelTextSize
* @attr ref R.styleable#LatinKeyboardBaseView_keyTextSize
* @attr ref R.styleable#LatinKeyboardBaseView_keyTextColor
* @attr ref R.styleable#LatinKeyboardBaseView_verticalCorrection
* @attr ref R.styleable#LatinKeyboardBaseView_popupLayout
*/
public class LatinKeyboardBaseView extends View implements PointerTracker.UIProxy {
private static final String TAG = "HK/LatinKeyboardBaseView";
private static final boolean DEBUG = false;
public static final int NOT_A_TOUCH_COORDINATE = -1;
public interface OnKeyboardActionListener {
/**
* Called when the user presses a key. This is sent before the
* {@link #onKey} is called. For keys that repeat, this is only
* called once.
*
* @param primaryCode
* the unicode of the key being pressed. If the touch is
* not on a valid key, the value will be zero.
*/
void onPress(int primaryCode);
/**
* Called when the user releases a key. This is sent after the
* {@link #onKey} is called. For keys that repeat, this is only
* called once.
*
* @param primaryCode
* the code of the key that was released
*/
void onRelease(int primaryCode);
/**
* Send a key press to the listener.
*
* @param primaryCode
* this is the key that was pressed
* @param keyCodes
* the codes for all the possible alternative keys with
* the primary code being the first. If the primary key
* code is a single character such as an alphabet or
* number or symbol, the alternatives will include other
* characters that may be on the same key or adjacent
* keys. These codes are useful to correct for
* accidental presses of a key adjacent to the intended
* key.
* @param x
* x-coordinate pixel of touched event. If onKey is not called by onTouchEvent,
* the value should be NOT_A_TOUCH_COORDINATE.
* @param y
* y-coordinate pixel of touched event. If onKey is not called by onTouchEvent,
* the value should be NOT_A_TOUCH_COORDINATE.
*/
void onKey(int primaryCode, int[] keyCodes, int x, int y);
/**
* Sends a sequence of characters to the listener.
*
* @param text
* the sequence of characters to be displayed.
*/
void onText(CharSequence text);
/**
* Called when user released a finger outside any key.
*/
void onCancel();
/**
* Called when the user quickly moves the finger from right to
* left.
*/
boolean swipeLeft();
/**
* Called when the user quickly moves the finger from left to
* right.
*/
boolean swipeRight();
/**
* Called when the user quickly moves the finger from up to down.
*/
boolean swipeDown();
/**
* Called when the user quickly moves the finger from down to up.
*/
boolean swipeUp();
}
// Timing constants
private final int mKeyRepeatInterval;
// Miscellaneous constants
/* package */ static final int NOT_A_KEY = -1;
private static final int NUMBER_HINT_VERTICAL_ADJUSTMENT_PIXEL = -1;
// XML attribute
private float mKeyTextSize;
private float mLabelScale = 1.0f;
private int mKeyTextColor;
private int mKeyHintColor;
private int mKeyCursorColor;
private boolean mRecolorSymbols;
private Typeface mKeyTextStyle = Typeface.DEFAULT;
private float mLabelTextSize;
private int mSymbolColorScheme = 0;
private int mShadowColor;
private float mShadowRadius;
private Drawable mKeyBackground;
private int mBackgroundAlpha;
private float mBackgroundDimAmount;
private float mKeyHysteresisDistance;
private float mVerticalCorrection;
protected int mPreviewOffset;
protected int mPreviewHeight;
protected int mPopupLayout;
// Main keyboard
private Keyboard mKeyboard;
private Key[] mKeys;
// TODO this attribute should be gotten from Keyboard.
private int mKeyboardVerticalGap;
// Key preview popup
protected TextView mPreviewText;
protected PopupWindow mPreviewPopup;
protected int mPreviewTextSizeLarge;
protected int[] mOffsetInWindow;
protected int mOldPreviewKeyIndex = NOT_A_KEY;
protected boolean mShowPreview = true;
protected boolean mShowTouchPoints = true;
protected int mPopupPreviewOffsetX;
protected int mPopupPreviewOffsetY;
protected int mWindowY;
protected int mPopupPreviewDisplayedY;
protected final int mDelayBeforePreview;
protected final int mDelayBeforeSpacePreview;
protected final int mDelayAfterPreview;
// Popup mini keyboard
protected PopupWindow mMiniKeyboardPopup;
protected LatinKeyboardBaseView mMiniKeyboard;
protected View mMiniKeyboardContainer;
protected View mMiniKeyboardParent;
protected boolean mMiniKeyboardVisible;
protected final WeakHashMap<Key, Keyboard> mMiniKeyboardCacheMain = new WeakHashMap<Key, Keyboard>();
protected final WeakHashMap<Key, Keyboard> mMiniKeyboardCacheShift = new WeakHashMap<Key, Keyboard>();
protected final WeakHashMap<Key, Keyboard> mMiniKeyboardCacheCaps = new WeakHashMap<Key, Keyboard>();
protected int mMiniKeyboardOriginX;
protected int mMiniKeyboardOriginY;
protected long mMiniKeyboardPopupTime;
protected int[] mWindowOffset;
protected final float mMiniKeyboardSlideAllowance;
protected int mMiniKeyboardTrackerId;
/** Listener for {@link OnKeyboardActionListener}. */
private OnKeyboardActionListener mKeyboardActionListener;
private final ArrayList<PointerTracker> mPointerTrackers = new ArrayList<PointerTracker>();
private boolean mIgnoreMove = false;
// TODO: Let the PointerTracker class manage this pointer queue
private final PointerQueue mPointerQueue = new PointerQueue();
private final boolean mHasDistinctMultitouch;
private int mOldPointerCount = 1;
protected KeyDetector mKeyDetector = new ProximityKeyDetector();
// Swipe gesture detector
private GestureDetector mGestureDetector;
private final SwipeTracker mSwipeTracker = new SwipeTracker();
private final int mSwipeThreshold;
private final boolean mDisambiguateSwipe;
// Drawing
/** Whether the keyboard bitmap needs to be redrawn before it's blitted. **/
private boolean mDrawPending;
/** The dirty region in the keyboard bitmap */
private final Rect mDirtyRect = new Rect();
/** The keyboard bitmap for faster updates */
private Bitmap mBuffer;
/** Notes if the keyboard just changed, so that we could possibly reallocate the mBuffer. */
private boolean mKeyboardChanged;
private Key mInvalidatedKey;
/** The canvas for the above mutable keyboard bitmap */
private Canvas mCanvas;
private final Paint mPaint;
private final Paint mPaintHint;
private final Rect mPadding;
private final Rect mClipRegion = new Rect(0, 0, 0, 0);
private int mViewWidth;
// This map caches key label text height in pixel as value and key label text size as map key.
private final HashMap<Integer, Integer> mTextHeightCache = new HashMap<Integer, Integer>();
// Distance from horizontal center of the key, proportional to key label text height.
private final float KEY_LABEL_VERTICAL_ADJUSTMENT_FACTOR = 0.55f;
private final String KEY_LABEL_HEIGHT_REFERENCE_CHAR = "H";
/* package */ static Method sSetRenderMode;
private static int sPrevRenderMode = -1;
private final UIHandler mHandler = new UIHandler();
class UIHandler extends Handler {
private static final int MSG_POPUP_PREVIEW = 1;
private static final int MSG_DISMISS_PREVIEW = 2;
private static final int MSG_REPEAT_KEY = 3;
private static final int MSG_LONGPRESS_KEY = 4;
private boolean mInKeyRepeat;
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_POPUP_PREVIEW:
showKey(msg.arg1, (PointerTracker)msg.obj);
break;
case MSG_DISMISS_PREVIEW:
mPreviewPopup.dismiss();
break;
case MSG_REPEAT_KEY: {
final PointerTracker tracker = (PointerTracker)msg.obj;
tracker.repeatKey(msg.arg1);
startKeyRepeatTimer(mKeyRepeatInterval, msg.arg1, tracker);
break;
}
case MSG_LONGPRESS_KEY: {
final PointerTracker tracker = (PointerTracker)msg.obj;
openPopupIfRequired(msg.arg1, tracker);
break;
}
}
}
public void popupPreview(long delay, int keyIndex, PointerTracker tracker) {
removeMessages(MSG_POPUP_PREVIEW);
if (mPreviewPopup.isShowing() && mPreviewText.getVisibility() == VISIBLE) {
// Show right away, if it's already visible and finger is moving around
showKey(keyIndex, tracker);
} else {
sendMessageDelayed(obtainMessage(MSG_POPUP_PREVIEW, keyIndex, 0, tracker),
delay);
}
}
public void cancelPopupPreview() {
removeMessages(MSG_POPUP_PREVIEW);
}
public void dismissPreview(long delay) {
if (mPreviewPopup.isShowing()) {
sendMessageDelayed(obtainMessage(MSG_DISMISS_PREVIEW), delay);
}
}
public void cancelDismissPreview() {
removeMessages(MSG_DISMISS_PREVIEW);
}
public void startKeyRepeatTimer(long delay, int keyIndex, PointerTracker tracker) {
mInKeyRepeat = true;
sendMessageDelayed(obtainMessage(MSG_REPEAT_KEY, keyIndex, 0, tracker), delay);
}
public void cancelKeyRepeatTimer() {
mInKeyRepeat = false;
removeMessages(MSG_REPEAT_KEY);
}
public boolean isInKeyRepeat() {
return mInKeyRepeat;
}
public void startLongPressTimer(long delay, int keyIndex, PointerTracker tracker) {
removeMessages(MSG_LONGPRESS_KEY);
sendMessageDelayed(obtainMessage(MSG_LONGPRESS_KEY, keyIndex, 0, tracker), delay);
}
public void cancelLongPressTimer() {
removeMessages(MSG_LONGPRESS_KEY);
}
public void cancelKeyTimers() {
cancelKeyRepeatTimer();
cancelLongPressTimer();
}
public void cancelAllMessages() {
cancelKeyTimers();
cancelPopupPreview();
cancelDismissPreview();
}
}
static class PointerQueue {
private LinkedList<PointerTracker> mQueue = new LinkedList<PointerTracker>();
public void add(PointerTracker tracker) {
mQueue.add(tracker);
}
public int lastIndexOf(PointerTracker tracker) {
LinkedList<PointerTracker> queue = mQueue;
for (int index = queue.size() - 1; index >= 0; index--) {
PointerTracker t = queue.get(index);
if (t == tracker)
return index;
}
return -1;
}
public void releaseAllPointersOlderThan(PointerTracker tracker, long eventTime) {
LinkedList<PointerTracker> queue = mQueue;
int oldestPos = 0;
for (PointerTracker t = queue.get(oldestPos); t != tracker; t = queue.get(oldestPos)) {
if (t.isModifier()) {
oldestPos++;
} else {
t.onUpEvent(t.getLastX(), t.getLastY(), eventTime);
t.setAlreadyProcessed();
queue.remove(oldestPos);
}
}
}
public void releaseAllPointersExcept(PointerTracker tracker, long eventTime) {
for (PointerTracker t : mQueue) {
if (t == tracker)
continue;
t.onUpEvent(t.getLastX(), t.getLastY(), eventTime);
t.setAlreadyProcessed();
}
mQueue.clear();
if (tracker != null)
mQueue.add(tracker);
}
public void remove(PointerTracker tracker) {
mQueue.remove(tracker);
}
public boolean isInSlidingKeyInput() {
for (final PointerTracker tracker : mQueue) {
if (tracker.isInSlidingKeyInput())
return true;
}
return false;
}
}
static {
initCompatibility();
}
static void initCompatibility() {
try {
sSetRenderMode = View.class.getMethod("setLayerType", int.class, Paint.class);
Log.i(TAG, "setRenderMode is supported");
} catch (SecurityException e) {
Log.w(TAG, "unexpected SecurityException", e);
} catch (NoSuchMethodException e) {
// ignore, not supported by API level pre-Honeycomb
Log.i(TAG, "ignoring render mode, not supported");
}
}
private void setRenderModeIfPossible(int mode) {
if (sSetRenderMode != null && mode != sPrevRenderMode) {
try {
sSetRenderMode.invoke(this, mode, null);
sPrevRenderMode = mode;
Log.i(TAG, "render mode set to " + LatinIME.sKeyboardSettings.renderMode);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
public LatinKeyboardBaseView(Context context, AttributeSet attrs) {
this(context, attrs, R.attr.keyboardViewStyle);
}
public LatinKeyboardBaseView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
Log.i(TAG, "Creating new LatinKeyboardBaseView " + this);
setRenderModeIfPossible(LatinIME.sKeyboardSettings.renderMode);
TypedArray a = context.obtainStyledAttributes(
attrs, R.styleable.LatinKeyboardBaseView, defStyle, R.style.LatinKeyboardBaseView);
int n = a.getIndexCount();
for (int i = 0; i < n; i++) {
int attr = a.getIndex(i);
switch (attr) {
case R.styleable.LatinKeyboardBaseView_keyBackground:
mKeyBackground = a.getDrawable(attr);
break;
case R.styleable.LatinKeyboardBaseView_keyHysteresisDistance:
mKeyHysteresisDistance = a.getDimensionPixelOffset(attr, 0);
break;
case R.styleable.LatinKeyboardBaseView_verticalCorrection:
mVerticalCorrection = a.getDimensionPixelOffset(attr, 0);
break;
case R.styleable.LatinKeyboardBaseView_keyTextSize:
mKeyTextSize = a.getDimensionPixelSize(attr, 18);
break;
case R.styleable.LatinKeyboardBaseView_keyTextColor:
mKeyTextColor = a.getColor(attr, 0xFF000000);
break;
case R.styleable.LatinKeyboardBaseView_keyHintColor:
mKeyHintColor = a.getColor(attr, 0xFFBBBBBB);
break;
case R.styleable.LatinKeyboardBaseView_keyCursorColor:
mKeyCursorColor = a.getColor(attr, 0xFF000000);
break;
case R.styleable.LatinKeyboardBaseView_recolorSymbols:
mRecolorSymbols = a.getBoolean(attr, false);
break;
case R.styleable.LatinKeyboardBaseView_labelTextSize:
mLabelTextSize = a.getDimensionPixelSize(attr, 14);
break;
case R.styleable.LatinKeyboardBaseView_shadowColor:
mShadowColor = a.getColor(attr, 0);
break;
case R.styleable.LatinKeyboardBaseView_shadowRadius:
mShadowRadius = a.getFloat(attr, 0f);
break;
// TODO: Use Theme (android.R.styleable.Theme_backgroundDimAmount)
case R.styleable.LatinKeyboardBaseView_backgroundDimAmount:
mBackgroundDimAmount = a.getFloat(attr, 0.5f);
break;
case R.styleable.LatinKeyboardBaseView_backgroundAlpha:
mBackgroundAlpha = a.getInteger(attr, 255);
break;
//case android.R.styleable.
case R.styleable.LatinKeyboardBaseView_keyTextStyle:
int textStyle = a.getInt(attr, 0);
switch (textStyle) {
case 0:
mKeyTextStyle = Typeface.DEFAULT;
break;
case 1:
mKeyTextStyle = Typeface.DEFAULT_BOLD;
break;
default:
mKeyTextStyle = Typeface.defaultFromStyle(textStyle);
break;
}
break;
case R.styleable.LatinKeyboardBaseView_symbolColorScheme:
mSymbolColorScheme = a.getInt(attr, 0);
break;
}
}
final Resources res = getResources();
mShowPreview = false;
mDelayBeforePreview = res.getInteger(R.integer.config_delay_before_preview);
mDelayBeforeSpacePreview = res.getInteger(R.integer.config_delay_before_space_preview);
mDelayAfterPreview = res.getInteger(R.integer.config_delay_after_preview);
mPopupLayout = 0;
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setTextAlign(Align.CENTER);
mPaint.setAlpha(255);
mPaintHint = new Paint();
mPaintHint.setAntiAlias(true);
mPaintHint.setTextAlign(Align.RIGHT);
mPaintHint.setAlpha(255);
mPaintHint.setTypeface(Typeface.DEFAULT_BOLD);
mPadding = new Rect(0, 0, 0, 0);
mKeyBackground.getPadding(mPadding);
mSwipeThreshold = (int) (300 * res.getDisplayMetrics().density);
// TODO: Refer frameworks/base/core/res/res/values/config.xml
// TODO(klausw): turn off mDisambiguateSwipe if no swipe actions are set?
mDisambiguateSwipe = res.getBoolean(R.bool.config_swipeDisambiguation);
mMiniKeyboardSlideAllowance = res.getDimension(R.dimen.mini_keyboard_slide_allowance);
GestureDetector.SimpleOnGestureListener listener =
new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onFling(MotionEvent me1, MotionEvent me2, float velocityX,
float velocityY) {
final float absX = Math.abs(velocityX);
final float absY = Math.abs(velocityY);
float deltaX = me2.getX() - me1.getX();
float deltaY = me2.getY() - me1.getY();
mSwipeTracker.computeCurrentVelocity(1000);
final float endingVelocityX = mSwipeTracker.getXVelocity();
final float endingVelocityY = mSwipeTracker.getYVelocity();
// Calculate swipe distance threshold based on screen width & height,
// taking the smaller distance.
int travelX = getWidth() / 3;
int travelY = getHeight() / 3;
int travelMin = Math.min(travelX, travelY);
// Log.i(TAG, "onFling vX=" + velocityX + " vY=" + velocityY + " threshold=" + mSwipeThreshold
// + " dX=" + deltaX + " dy=" + deltaY + " min=" + travelMin);
if (velocityX > mSwipeThreshold && absY < absX && deltaX > travelMin) {
if (mDisambiguateSwipe && endingVelocityX >= velocityX / 4) {
if (swipeRight()) return true;
}
} else if (velocityX < -mSwipeThreshold && absY < absX && deltaX < -travelMin) {
if (mDisambiguateSwipe && endingVelocityX <= velocityX / 4) {
if (swipeLeft()) return true;
}
} else if (velocityY < -mSwipeThreshold && absX < absY && deltaY < -travelMin) {
if (mDisambiguateSwipe && endingVelocityY <= velocityY / 4) {
if (swipeUp()) return true;
}
} else if (velocityY > mSwipeThreshold && absX < absY / 2 && deltaY > travelMin) {
if (mDisambiguateSwipe && endingVelocityY >= velocityY / 4) {
if (swipeDown()) return true;
}
}
return false;
}
};
final boolean ignoreMultitouch = true;
mGestureDetector = new GestureDetector(getContext(), listener, null, ignoreMultitouch);
mGestureDetector.setIsLongpressEnabled(false);
mHasDistinctMultitouch = context.getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH_DISTINCT);
mKeyRepeatInterval = res.getInteger(R.integer.config_key_repeat_interval);
}
private boolean showHints7Bit() {
return LatinIME.sKeyboardSettings.hintMode >= 1;
}
private boolean showHintsAll() {
return LatinIME.sKeyboardSettings.hintMode >= 2;
}
public void setOnKeyboardActionListener(OnKeyboardActionListener listener) {
mKeyboardActionListener = listener;
for (PointerTracker tracker : mPointerTrackers) {
tracker.setOnKeyboardActionListener(listener);
}
}
/**
* Returns the {@link OnKeyboardActionListener} object.
* @return the listener attached to this keyboard
*/
protected OnKeyboardActionListener getOnKeyboardActionListener() {
return mKeyboardActionListener;
}
/**
* Attaches a keyboard to this view. The keyboard can be switched at any time and the
* view will re-layout itself to accommodate the keyboard.
* @see Keyboard
* @see #getKeyboard()
* @param keyboard the keyboard to display in this view
*/
public void setKeyboard(Keyboard keyboard) {
if (mKeyboard != null) {
dismissKeyPreview();
}
//Log.i(TAG, "setKeyboard(" + keyboard + ") for " + this);
// Remove any pending messages, except dismissing preview
mHandler.cancelKeyTimers();
mHandler.cancelPopupPreview();
mKeyboard = keyboard;
LatinImeLogger.onSetKeyboard(keyboard);
mKeys = mKeyDetector.setKeyboard(keyboard, -getPaddingLeft(),
-getPaddingTop() + mVerticalCorrection);
mKeyboardVerticalGap = (int)getResources().getDimension(R.dimen.key_bottom_gap);
for (PointerTracker tracker : mPointerTrackers) {
tracker.setKeyboard(mKeys, mKeyHysteresisDistance);
}
mLabelScale = LatinIME.sKeyboardSettings.labelScalePref;
if (keyboard.mLayoutRows >= 4) mLabelScale *= 5.0f / keyboard.mLayoutRows;
requestLayout();
// Hint to reallocate the buffer if the size changed
mKeyboardChanged = true;
invalidateAllKeys();
computeProximityThreshold(keyboard);
mMiniKeyboardCacheMain.clear();
mMiniKeyboardCacheShift.clear();
mMiniKeyboardCacheCaps.clear();
setRenderModeIfPossible(LatinIME.sKeyboardSettings.renderMode);
mIgnoreMove = true;
}
/**
* Returns the current keyboard being displayed by this view.
* @return the currently attached keyboard
* @see #setKeyboard(Keyboard)
*/
public Keyboard getKeyboard() {
return mKeyboard;
}
/**
* Return whether the device has distinct multi-touch panel.
* @return true if the device has distinct multi-touch panel.
*/
public boolean hasDistinctMultitouch() {
return mHasDistinctMultitouch;
}
/**
* Sets the state of the shift key of the keyboard, if any.
* @param shifted whether or not to enable the state of the shift key
* @return true if the shift key state changed, false if there was no change
*/
public boolean setShiftState(int shiftState) {
//Log.i(TAG, "setShifted " + shiftState);
if (mKeyboard != null) {
if (mKeyboard.setShiftState(shiftState)) {
// The whole keyboard probably needs to be redrawn
invalidateAllKeys();
return true;
}
}
return false;
}
public void setCtrlIndicator(boolean active) {
if (mKeyboard != null) {
invalidateKey(mKeyboard.setCtrlIndicator(active));
}
}
public void setAltIndicator(boolean active) {
if (mKeyboard != null) {
invalidateKey(mKeyboard.setAltIndicator(active));
}
}
public void setMetaIndicator(boolean active) {
if (mKeyboard != null) {
invalidateKey(mKeyboard.setMetaIndicator(active));
}
}
/**
* Returns the state of the shift key of the keyboard, if any.
* @return true if the shift is in a pressed state, false otherwise. If there is
* no shift key on the keyboard or there is no keyboard attached, it returns false.
*/
public int getShiftState() {
if (mKeyboard != null) {
return mKeyboard.getShiftState();
}
return Keyboard.SHIFT_OFF;
}
public boolean isShiftCaps() {
return getShiftState() != Keyboard.SHIFT_OFF;
}
public boolean isShiftAll() {
int state = getShiftState();
if (LatinIME.sKeyboardSettings.shiftLockModifiers) {
return state == Keyboard.SHIFT_ON || state == Keyboard.SHIFT_LOCKED;
} else {
return state == Keyboard.SHIFT_ON;
}
}
/**
* Enables or disables the key feedback popup. This is a popup that shows a magnified
* version of the depressed key. By default the preview is enabled.
* @param previewEnabled whether or not to enable the key feedback popup
* @see #isPreviewEnabled()
*/
public void setPreviewEnabled(boolean previewEnabled) {
mShowPreview = previewEnabled;
}
/**
* Returns the enabled state of the key feedback popup.
* @return whether or not the key feedback popup is enabled
* @see #setPreviewEnabled(boolean)
*/
public boolean isPreviewEnabled() {
return mShowPreview;
}
private boolean isBlackSym() {
return mSymbolColorScheme == 1;
}
public void setPopupParent(View v) {
mMiniKeyboardParent = v;
}
public void setPopupOffset(int x, int y) {
mPopupPreviewOffsetX = x;
mPopupPreviewOffsetY = y;
if (mPreviewPopup != null) mPreviewPopup.dismiss();
}
/**
* When enabled, calls to {@link OnKeyboardActionListener#onKey} will include key
* codes for adjacent keys. When disabled, only the primary key code will be
* reported.
* @param enabled whether or not the proximity correction is enabled
*/
public void setProximityCorrectionEnabled(boolean enabled) {
mKeyDetector.setProximityCorrectionEnabled(enabled);
}
/**
* Returns true if proximity correction is enabled.
*/
public boolean isProximityCorrectionEnabled() {
return mKeyDetector.isProximityCorrectionEnabled();
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// Round up a little
if (mKeyboard == null) {
setMeasuredDimension(
getPaddingLeft() + getPaddingRight(), getPaddingTop() + getPaddingBottom());
} else {
int width = mKeyboard.getMinWidth() + getPaddingLeft() + getPaddingRight();
if (MeasureSpec.getSize(widthMeasureSpec) < width + 10) {
int badWidth = MeasureSpec.getSize(widthMeasureSpec);
if (badWidth != width) Log.i(TAG, "ignoring unexpected width=" + badWidth);
}
Log.i(TAG, "onMeasure width=" + width);
setMeasuredDimension(
width, mKeyboard.getHeight() + getPaddingTop() + getPaddingBottom());
}
}
/**
* Compute the average distance between adjacent keys (horizontally and vertically)
* and square it to get the proximity threshold. We use a square here and in computing
* the touch distance from a key's center to avoid taking a square root.
* @param keyboard
*/
private void computeProximityThreshold(Keyboard keyboard) {
if (keyboard == null) return;
final Key[] keys = mKeys;
if (keys == null) return;
int length = keys.length;
int dimensionSum = 0;
for (int i = 0; i < length; i++) {
Key key = keys[i];
dimensionSum += Math.min(key.width, key.height + mKeyboardVerticalGap) + key.gap;
}
if (dimensionSum < 0 || length == 0) return;
mKeyDetector.setProximityThreshold((int) (dimensionSum * 1.4f / length));
}
@Override
public void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
Log.i(TAG, "onSizeChanged, w=" + w + ", h=" + h);
mViewWidth = w;
// Release the buffer, if any and it will be reallocated on the next draw
mBuffer = null;
}
@Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
//Log.i(TAG, "onDraw called " + canvas.getClipBounds());
mCanvas = canvas;
if (mDrawPending || mBuffer == null || mKeyboardChanged) {
onBufferDraw(canvas);
}
if (mBuffer != null) canvas.drawBitmap(mBuffer, 0, 0, null);
}
private void drawDeadKeyLabel(Canvas canvas, String hint, int x, float baseline, Paint paint) {
char c = hint.charAt(0);
String accent = DeadAccentSequence.getSpacing(c);
canvas.drawText(Keyboard.DEAD_KEY_PLACEHOLDER_STRING, x, baseline, paint);
canvas.drawText(accent, x, baseline, paint);
}
private int getLabelHeight(Paint paint, int labelSize) {
Integer labelHeightValue = mTextHeightCache.get(labelSize);
if (labelHeightValue != null) {
return labelHeightValue;
} else {
Rect textBounds = new Rect();
paint.getTextBounds(KEY_LABEL_HEIGHT_REFERENCE_CHAR, 0, 1, textBounds);
int labelHeight = textBounds.height();
mTextHeightCache.put(labelSize, labelHeight);
return labelHeight;
}
}
private void onBufferDraw(Canvas canvas) {
//Log.i(TAG, "onBufferDraw called");
if (/*mBuffer == null ||*/ mKeyboardChanged) {
mKeyboard.setKeyboardWidth(mViewWidth);
// if (mBuffer == null || mKeyboardChanged &&
// (mBuffer.getWidth() != getWidth() || mBuffer.getHeight() != getHeight())) {
// // Make sure our bitmap is at least 1x1
// final int width = Math.max(1, getWidth());
// final int height = Math.max(1, getHeight());
// mBuffer = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
// mCanvas = new Canvas(mBuffer);
// }
invalidateAllKeys();
mKeyboardChanged = false;
}
//final Canvas canvas = mCanvas;
//canvas.clipRect(mDirtyRect, Op.REPLACE);
canvas.getClipBounds(mDirtyRect);
//canvas.drawColor(Color.BLACK);
if (mKeyboard == null) return;
final Paint paint = mPaint;
final Paint paintHint = mPaintHint;
paintHint.setColor(mKeyHintColor);
final Drawable keyBackground = mKeyBackground;
final Rect clipRegion = mClipRegion;
final Rect padding = mPadding;
final int kbdPaddingLeft = getPaddingLeft();
final int kbdPaddingTop = getPaddingTop();
final Key[] keys = mKeys;
final Key invalidKey = mInvalidatedKey;
ColorFilter iconColorFilter = null;
ColorFilter shadowColorFilter = null;
if (mRecolorSymbols) {
// TODO: cache these?
iconColorFilter = new PorterDuffColorFilter(
mKeyTextColor, PorterDuff.Mode.SRC_ATOP);
shadowColorFilter = new PorterDuffColorFilter(
mShadowColor, PorterDuff.Mode.SRC_ATOP);
}
boolean drawSingleKey = false;
if (invalidKey != null && canvas.getClipBounds(clipRegion)) {
// TODO we should use Rect.inset and Rect.contains here.
// Is clipRegion completely contained within the invalidated key?
if (invalidKey.x + kbdPaddingLeft - 1 <= clipRegion.left &&
invalidKey.y + kbdPaddingTop - 1 <= clipRegion.top &&
invalidKey.x + invalidKey.width + kbdPaddingLeft + 1 >= clipRegion.right &&
invalidKey.y + invalidKey.height + kbdPaddingTop + 1 >= clipRegion.bottom) {
drawSingleKey = true;
}
}
//canvas.drawColor(0x00000000, PorterDuff.Mode.CLEAR);
final int keyCount = keys.length;
int keysDrawn = 0;
for (int i = 0; i < keyCount; i++) {
final Key key = keys[i];
if (drawSingleKey && invalidKey != key) {
continue;
}
if (!mDirtyRect.intersects(
key.x + kbdPaddingLeft,
key.y + kbdPaddingTop,
key.x + key.width + kbdPaddingLeft,
key.y + key.height + kbdPaddingTop)) {
continue;
}
keysDrawn++;
paint.setColor(key.isCursor ? mKeyCursorColor : mKeyTextColor);
int[] drawableState = key.getCurrentDrawableState();
keyBackground.setState(drawableState);
// Switch the character to uppercase if shift is pressed
String label = key.getCaseLabel();
float yscale = 1.0f;
final Rect bounds = keyBackground.getBounds();
if (key.width != bounds.right || key.height != bounds.bottom) {
int minHeight = keyBackground.getMinimumHeight();
if (minHeight > key.height) {
yscale = (float) key.height / minHeight;
keyBackground.setBounds(0, 0, key.width, minHeight);
} else {
keyBackground.setBounds(0, 0, key.width, key.height);
}
}
canvas.translate(key.x + kbdPaddingLeft, key.y + kbdPaddingTop);
if (yscale != 1.0f) {
canvas.save();
canvas.scale(1.0f, yscale);
}
if (mBackgroundAlpha != 255) {
keyBackground.setAlpha(mBackgroundAlpha);
}
keyBackground.draw(canvas);
if (yscale != 1.0f) canvas.restore();
boolean shouldDrawIcon = true;
if (label != null) {
// For characters, use large font. For labels like "Done", use small font.
final int labelSize;
if (label.length() > 1 && key.codes.length < 2) {
//Log.i(TAG, "mLabelTextSize=" + mLabelTextSize + " LatinIME.sKeyboardSettings.labelScale=" + LatinIME.sKeyboardSettings.labelScale);
labelSize = (int)(mLabelTextSize * mLabelScale);
paint.setTypeface(Typeface.DEFAULT);
} else {
labelSize = (int)(mKeyTextSize * mLabelScale);
paint.setTypeface(mKeyTextStyle);
}
paint.setFakeBoldText(key.isCursor);
paint.setTextSize(labelSize);
final int labelHeight = getLabelHeight(paint, labelSize);
// Draw a drop shadow for the text
paint.setShadowLayer(mShadowRadius, 0, 0, mShadowColor);
// Draw hint label (if present) behind the main key
String hint = key.getHintLabel(showHints7Bit(), showHintsAll());
if (!hint.equals("") && !(key.isShifted() && key.shiftLabel != null && hint.charAt(0) == key.shiftLabel.charAt(0))) {
int hintTextSize = (int)(mKeyTextSize * 0.6 * mLabelScale);
paintHint.setTextSize(hintTextSize);
final int hintLabelHeight = getLabelHeight(paintHint, hintTextSize);
int x = key.width - padding.right;
int baseline = padding.top + hintLabelHeight * 12/10;
if (Character.getType(hint.charAt(0)) == Character.NON_SPACING_MARK) {
drawDeadKeyLabel(canvas, hint, x, baseline, paintHint);
} else {
canvas.drawText(hint, x, baseline, paintHint);
}
}
// Draw alternate hint label (if present) behind the main key
String altHint = key.getAltHintLabel(showHints7Bit(), showHintsAll());
if (!altHint.equals("")) {
int hintTextSize = (int)(mKeyTextSize * 0.6 * mLabelScale);
paintHint.setTextSize(hintTextSize);
final int hintLabelHeight = getLabelHeight(paintHint, hintTextSize);
int x = key.width - padding.right;
int baseline = padding.top + hintLabelHeight * (hint.equals("") ? 12 : 26)/10;
if (Character.getType(altHint.charAt(0)) == Character.NON_SPACING_MARK) {
drawDeadKeyLabel(canvas, altHint, x, baseline, paintHint);
} else {
canvas.drawText(altHint, x, baseline, paintHint);
}
}
// Draw main key label
final int centerX = (key.width + padding.left - padding.right) / 2;
final int centerY = (key.height + padding.top - padding.bottom) / 2;
final float baseline = centerY
+ labelHeight * KEY_LABEL_VERTICAL_ADJUSTMENT_FACTOR;
if (key.isDeadKey()) {
drawDeadKeyLabel(canvas, label, centerX, baseline, paint);
} else {
canvas.drawText(label, centerX, baseline, paint);
}
if (key.isCursor) {
// poor man's bold - FIXME
// Turn off drop shadow
paint.setShadowLayer(0, 0, 0, 0);
canvas.drawText(label, centerX+0.5f, baseline, paint);
canvas.drawText(label, centerX-0.5f, baseline, paint);
canvas.drawText(label, centerX, baseline+0.5f, paint);
canvas.drawText(label, centerX, baseline-0.5f, paint);
}
// Turn off drop shadow
paint.setShadowLayer(0, 0, 0, 0);
// Usually don't draw icon if label is not null, but we draw icon for the number
// hint and popup hint.
shouldDrawIcon = shouldDrawLabelAndIcon(key);
}
Drawable icon = key.icon;
if (icon != null && shouldDrawIcon) {
// Special handing for the upper-right number hint icons
final int drawableWidth;
final int drawableHeight;
final int drawableX;
final int drawableY;
if (shouldDrawIconFully(key)) {
drawableWidth = key.width;
drawableHeight = key.height;
drawableX = 0;
drawableY = NUMBER_HINT_VERTICAL_ADJUSTMENT_PIXEL;
} else {
drawableWidth = icon.getIntrinsicWidth();
drawableHeight = icon.getIntrinsicHeight();
drawableX = (key.width + padding.left - padding.right - drawableWidth) / 2;
drawableY = (key.height + padding.top - padding.bottom - drawableHeight) / 2;
}
canvas.translate(drawableX, drawableY);
icon.setBounds(0, 0, drawableWidth, drawableHeight);
if (shadowColorFilter != null && iconColorFilter != null) {
// Re-color the icon to match the theme, and draw a shadow for it manually.
//
// This doesn't seem to look quite right, possibly a problem with using
// premultiplied icon images?
// Try EmbossMaskFilter, and/or offset? Configurable?
BlurMaskFilter shadowBlur = new BlurMaskFilter(mShadowRadius, BlurMaskFilter.Blur.OUTER);
Paint blurPaint = new Paint();
blurPaint.setMaskFilter(shadowBlur);
Bitmap tmpIcon = Bitmap.createBitmap(key.width, key.height, Bitmap.Config.ARGB_8888);
Canvas tmpCanvas = new Canvas(tmpIcon);
icon.draw(tmpCanvas);
int[] offsets = new int[2];
Bitmap shadowBitmap = tmpIcon.extractAlpha(blurPaint, offsets);
Paint shadowPaint = new Paint();
shadowPaint.setColorFilter(shadowColorFilter);
canvas.drawBitmap(shadowBitmap, offsets[0], offsets[1], shadowPaint);
icon.setColorFilter(iconColorFilter);
icon.draw(canvas);
icon.setColorFilter(null);
} else {
icon.draw(canvas);
}
canvas.translate(-drawableX, -drawableY);
}
canvas.translate(-key.x - kbdPaddingLeft, -key.y - kbdPaddingTop);
}
//Log.i(TAG, "keysDrawn=" + keysDrawn);
mInvalidatedKey = null;
// Overlay a dark rectangle to dim the keyboard
if (mMiniKeyboardVisible) {
paint.setColor((int) (mBackgroundDimAmount * 0xFF) << 24);
canvas.drawRect(0, 0, getWidth(), getHeight(), paint);
}
if (LatinIME.sKeyboardSettings.showTouchPos || DEBUG) {
if (LatinIME.sKeyboardSettings.showTouchPos || mShowTouchPoints) {
for (PointerTracker tracker : mPointerTrackers) {
int startX = tracker.getStartX();
int startY = tracker.getStartY();
int lastX = tracker.getLastX();
int lastY = tracker.getLastY();
paint.setAlpha(128);
paint.setColor(0xFFFF0000);
canvas.drawCircle(startX, startY, 3, paint);
canvas.drawLine(startX, startY, lastX, lastY, paint);
paint.setColor(0xFF0000FF);
canvas.drawCircle(lastX, lastY, 3, paint);
paint.setColor(0xFF00FF00);
canvas.drawCircle((startX + lastX) / 2, (startY + lastY) / 2, 2, paint);
}
}
}
mDrawPending = false;
mDirtyRect.setEmpty();
}
// TODO: clean up this method.
private void dismissKeyPreview() {
for (PointerTracker tracker : mPointerTrackers)
tracker.updateKey(NOT_A_KEY);
//Log.i(TAG, "dismissKeyPreview() for " + this);
showPreview(NOT_A_KEY, null);
}
public void showPreview(int keyIndex, PointerTracker tracker) {
int oldKeyIndex = mOldPreviewKeyIndex;
mOldPreviewKeyIndex = keyIndex;
final boolean isLanguageSwitchEnabled = (mKeyboard instanceof LatinKeyboard)
&& ((LatinKeyboard)mKeyboard).isLanguageSwitchEnabled();
// We should re-draw popup preview when 1) we need to hide the preview, 2) we will show
// the space key preview and 3) pointer moves off the space key to other letter key, we
// should hide the preview of the previous key.
final boolean hidePreviewOrShowSpaceKeyPreview = (tracker == null)
|| tracker.isSpaceKey(keyIndex) || tracker.isSpaceKey(oldKeyIndex);
// If key changed and preview is on or the key is space (language switch is enabled)
if (oldKeyIndex != keyIndex
&& (mShowPreview
|| (hidePreviewOrShowSpaceKeyPreview && isLanguageSwitchEnabled))) {
if (keyIndex == NOT_A_KEY) {
mHandler.cancelPopupPreview();
mHandler.dismissPreview(mDelayAfterPreview);
} else if (tracker != null) {
int delay = mShowPreview ? mDelayBeforePreview : mDelayBeforeSpacePreview;
mHandler.popupPreview(delay, keyIndex, tracker);
}
}
}
private void showKey(final int keyIndex, PointerTracker tracker) {
Key key = tracker.getKey(keyIndex);
if (key == null)
return;
//Log.i(TAG, "showKey() for " + this);
// Should not draw hint icon in key preview
Drawable icon = key.icon;
if (icon != null && !shouldDrawLabelAndIcon(key)) {
mPreviewText.setCompoundDrawables(null, null, null,
key.iconPreview != null ? key.iconPreview : icon);
mPreviewText.setText(null);
} else {
mPreviewText.setCompoundDrawables(null, null, null, null);
mPreviewText.setText(key.getCaseLabel());
if (key.label.length() > 1 && key.codes.length < 2) {
mPreviewText.setTextSize(TypedValue.COMPLEX_UNIT_PX, mKeyTextSize);
mPreviewText.setTypeface(Typeface.DEFAULT_BOLD);
} else {
mPreviewText.setTextSize(TypedValue.COMPLEX_UNIT_PX, mPreviewTextSizeLarge);
mPreviewText.setTypeface(mKeyTextStyle);
}
}
mPreviewText.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
int popupWidth = Math.max(mPreviewText.getMeasuredWidth(), key.width
+ mPreviewText.getPaddingLeft() + mPreviewText.getPaddingRight());
final int popupHeight = mPreviewHeight;
LayoutParams lp = mPreviewText.getLayoutParams();
if (lp != null) {
lp.width = popupWidth;
lp.height = popupHeight;
}
int popupPreviewX = key.x - (popupWidth - key.width) / 2;
int popupPreviewY = key.y - popupHeight + mPreviewOffset;
mHandler.cancelDismissPreview();
if (mOffsetInWindow == null) {
mOffsetInWindow = new int[2];
getLocationInWindow(mOffsetInWindow);
mOffsetInWindow[0] += mPopupPreviewOffsetX; // Offset may be zero
mOffsetInWindow[1] += mPopupPreviewOffsetY; // Offset may be zero
int[] windowLocation = new int[2];
getLocationOnScreen(windowLocation);
mWindowY = windowLocation[1];
}
// Set the preview background state.
// Retrieve and cache the popup keyboard if any.
boolean hasPopup = (getLongPressKeyboard(key) != null);
// Set background manually, the StateListDrawable doesn't work.
mPreviewText.setBackgroundDrawable(getResources().getDrawable(hasPopup ? R.drawable.keyboard_key_feedback_more_background : R.drawable.keyboard_key_feedback_background));
popupPreviewX += mOffsetInWindow[0];
popupPreviewY += mOffsetInWindow[1];
// If the popup cannot be shown above the key, put it on the side
if (popupPreviewY + mWindowY < 0) {
// If the key you're pressing is on the left side of the keyboard, show the popup on
// the right, offset by enough to see at least one key to the left/right.
if (key.x + key.width <= getWidth() / 2) {
popupPreviewX += (int) (key.width * 2.5);
} else {
popupPreviewX -= (int) (key.width * 2.5);
}
popupPreviewY += popupHeight;
}
if (mPreviewPopup.isShowing()) {
mPreviewPopup.update(popupPreviewX, popupPreviewY, popupWidth, popupHeight);
} else {
mPreviewPopup.setWidth(popupWidth);
mPreviewPopup.setHeight(popupHeight);
mPreviewPopup.showAtLocation(mMiniKeyboardParent, Gravity.NO_GRAVITY,
popupPreviewX, popupPreviewY);
}
// Record popup preview position to display mini-keyboard later at the same positon
mPopupPreviewDisplayedY = popupPreviewY;
mPreviewText.setVisibility(VISIBLE);
}
/**
* Requests a redraw of the entire keyboard. Calling {@link #invalidate} is not sufficient
* because the keyboard renders the keys to an off-screen buffer and an invalidate() only
* draws the cached buffer.
* @see #invalidateKey(Key)
*/
public void invalidateAllKeys() {
mDirtyRect.union(0, 0, getWidth(), getHeight());
mDrawPending = true;
invalidate();
}
/**
* Invalidates a key so that it will be redrawn on the next repaint. Use this method if only
* one key is changing it's content. Any changes that affect the position or size of the key
* may not be honored.
* @param key key in the attached {@link Keyboard}.
* @see #invalidateAllKeys
*/
public void invalidateKey(Key key) {
if (key == null)
return;
mInvalidatedKey = key;
// TODO we should clean up this and record key's region to use in onBufferDraw.
mDirtyRect.union(key.x + getPaddingLeft(), key.y + getPaddingTop(),
key.x + key.width + getPaddingLeft(), key.y + key.height + getPaddingTop());
//onBufferDraw();
invalidate(key.x + getPaddingLeft(), key.y + getPaddingTop(),
key.x + key.width + getPaddingLeft(), key.y + key.height + getPaddingTop());
}
private boolean openPopupIfRequired(int keyIndex, PointerTracker tracker) {
// Check if we have a popup layout specified first.
if (mPopupLayout == 0) {
return false;
}
Key popupKey = tracker.getKey(keyIndex);
if (popupKey == null)
return false;
if (tracker.isInSlidingKeyInput())
return false;
boolean result = onLongPress(popupKey);
if (result) {
dismissKeyPreview();
mMiniKeyboardTrackerId = tracker.mPointerId;
// Mark this tracker "already processed" and remove it from the pointer queue
tracker.setAlreadyProcessed();
mPointerQueue.remove(tracker);
}
return result;
}
private void inflateMiniKeyboardContainer() {
//Log.i(TAG, "inflateMiniKeyboardContainer(), mPopupLayout=" + mPopupLayout + " from " + this);
LayoutInflater inflater = (LayoutInflater)getContext().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
View container = inflater.inflate(mPopupLayout, null);
mMiniKeyboard =
(LatinKeyboardBaseView)container.findViewById(R.id.LatinKeyboardBaseView);
mMiniKeyboard.setOnKeyboardActionListener(new OnKeyboardActionListener() {
public void onKey(int primaryCode, int[] keyCodes, int x, int y) {
mKeyboardActionListener.onKey(primaryCode, keyCodes, x, y);
dismissPopupKeyboard();
}
public void onText(CharSequence text) {
mKeyboardActionListener.onText(text);
dismissPopupKeyboard();
}
public void onCancel() {
mKeyboardActionListener.onCancel();
dismissPopupKeyboard();
}
public boolean swipeLeft() {
return false;
}
public boolean swipeRight() {
return false;
}
public boolean swipeUp() {
return false;
}
public boolean swipeDown() {
return false;
}
public void onPress(int primaryCode) {
mKeyboardActionListener.onPress(primaryCode);
}
public void onRelease(int primaryCode) {
mKeyboardActionListener.onRelease(primaryCode);
}
});
// Override default ProximityKeyDetector.
mMiniKeyboard.mKeyDetector = new MiniKeyboardKeyDetector(mMiniKeyboardSlideAllowance);
// Remove gesture detector on mini-keyboard
mMiniKeyboard.mGestureDetector = null;
mMiniKeyboard.setPopupParent(this);
mMiniKeyboardContainer = container;
}
private static boolean isOneRowKeys(List<Key> keys) {
if (keys.size() == 0) return false;
final int edgeFlags = keys.get(0).edgeFlags;
// HACK: The first key of mini keyboard which was inflated from xml and has multiple rows,
// does not have both top and bottom edge flags on at the same time. On the other hand,
// the first key of mini keyboard that was created with popupCharacters must have both top
// and bottom edge flags on.
// When you want to use one row mini-keyboard from xml file, make sure that the row has
// both top and bottom edge flags set.
return (edgeFlags & Keyboard.EDGE_TOP) != 0 && (edgeFlags & Keyboard.EDGE_BOTTOM) != 0;
}
private Keyboard getLongPressKeyboard(Key popupKey) {
final WeakHashMap<Key, Keyboard> cache;
if (popupKey.isDistinctCaps()) {
cache = mMiniKeyboardCacheCaps;
} else if (popupKey.isShifted()) {
cache = mMiniKeyboardCacheShift;
} else {
cache = mMiniKeyboardCacheMain;
}
Keyboard kbd = cache.get(popupKey);
if (kbd == null) {
kbd = popupKey.getPopupKeyboard(getContext(), getPaddingLeft() + getPaddingRight());
if (kbd != null) cache.put(popupKey, kbd);
}
//Log.i(TAG, "getLongPressKeyboard returns " + kbd + " for " + popupKey);
return kbd;
}
/**
* Called when a key is long pressed. By default this will open any popup keyboard associated
* with this key through the attributes popupLayout and popupCharacters.
* @param popupKey the key that was long pressed
* @return true if the long press is handled, false otherwise. Subclasses should call the
* method on the base class if the subclass doesn't wish to handle the call.
*/
protected boolean onLongPress(Key popupKey) {
// TODO if popupKey.popupCharacters has only one letter, send it as key without opening
// mini keyboard.
if (mPopupLayout == 0) return false; // No popups wanted
Keyboard kbd = getLongPressKeyboard(popupKey);
//Log.i(TAG, "onLongPress, kbd=" + kbd);
if (kbd == null) return false;
if (mMiniKeyboardContainer == null) {
inflateMiniKeyboardContainer();
}
if (mMiniKeyboard == null) return false;
mMiniKeyboard.setKeyboard(kbd);
mMiniKeyboardContainer.measure(MeasureSpec.makeMeasureSpec(getWidth(), MeasureSpec.AT_MOST),
MeasureSpec.makeMeasureSpec(getHeight(), MeasureSpec.AT_MOST));
if (mWindowOffset == null) {
mWindowOffset = new int[2];
getLocationInWindow(mWindowOffset);
}
// Get width of a key in the mini popup keyboard = "miniKeyWidth".
// On the other hand, "popupKey.width" is width of the pressed key on the main keyboard.
// We adjust the position of mini popup keyboard with the edge key in it:
// a) When we have the leftmost key in popup keyboard directly above the pressed key
// Right edges of both keys should be aligned for consistent default selection
// b) When we have the rightmost key in popup keyboard directly above the pressed key
// Left edges of both keys should be aligned for consistent default selection
final List<Key> miniKeys = mMiniKeyboard.getKeyboard().getKeys();
final int miniKeyWidth = miniKeys.size() > 0 ? miniKeys.get(0).width : 0;
int popupX = popupKey.x + mWindowOffset[0];
popupX += getPaddingLeft();
if (shouldAlignLeftmost(popupKey)) {
popupX += popupKey.width - miniKeyWidth; // adjustment for a) described above
popupX -= mMiniKeyboardContainer.getPaddingLeft();
} else {
popupX += miniKeyWidth; // adjustment for b) described above
popupX -= mMiniKeyboardContainer.getMeasuredWidth();
popupX += mMiniKeyboardContainer.getPaddingRight();
}
int popupY = popupKey.y + mWindowOffset[1];
popupY += getPaddingTop();
popupY -= mMiniKeyboardContainer.getMeasuredHeight();
popupY += mMiniKeyboardContainer.getPaddingBottom();
final int x = popupX;
final int y = mShowPreview && isOneRowKeys(miniKeys) ? mPopupPreviewDisplayedY : popupY;
int adjustedX = x;
if (x < 0) {
adjustedX = 0;
} else if (x > (getMeasuredWidth() - mMiniKeyboardContainer.getMeasuredWidth())) {
adjustedX = getMeasuredWidth() - mMiniKeyboardContainer.getMeasuredWidth();
}
mMiniKeyboardOriginX = adjustedX + mMiniKeyboardContainer.getPaddingLeft() - mWindowOffset[0];
mMiniKeyboardOriginY = y + mMiniKeyboardContainer.getPaddingTop() - mWindowOffset[1];
mMiniKeyboard.setPopupOffset(adjustedX, y);
mMiniKeyboard.setShiftState(getShiftState());
// Mini keyboard needs no pop-up key preview displayed.
mMiniKeyboard.setPreviewEnabled(false);
mMiniKeyboardPopup.setContentView(mMiniKeyboardContainer);
mMiniKeyboardPopup.setWidth(mMiniKeyboardContainer.getMeasuredWidth());
mMiniKeyboardPopup.setHeight(mMiniKeyboardContainer.getMeasuredHeight());
//Log.i(TAG, "About to show popup " + mMiniKeyboardPopup + " from " + this);
mMiniKeyboardPopup.showAtLocation(this, Gravity.NO_GRAVITY, x, y);
mMiniKeyboardVisible = true;
// Inject down event on the key to mini keyboard.
long eventTime = SystemClock.uptimeMillis();
mMiniKeyboardPopupTime = eventTime;
MotionEvent downEvent = generateMiniKeyboardMotionEvent(MotionEvent.ACTION_DOWN, popupKey.x
+ popupKey.width / 2, popupKey.y + popupKey.height / 2, eventTime);
mMiniKeyboard.onTouchEvent(downEvent);
downEvent.recycle();
invalidateAllKeys();
return true;
}
private boolean shouldDrawIconFully(Key key) {
return isNumberAtEdgeOfPopupChars(key) || isLatinF1Key(key)
|| LatinKeyboard.hasPuncOrSmileysPopup(key);
}
private boolean shouldDrawLabelAndIcon(Key key) {
// isNumberAtEdgeOfPopupChars(key) ||
return isNonMicLatinF1Key(key)
|| LatinKeyboard.hasPuncOrSmileysPopup(key);
}
private boolean shouldAlignLeftmost(Key key) {
return !key.popupReversed;
}
private boolean isLatinF1Key(Key key) {
return (mKeyboard instanceof LatinKeyboard) && ((LatinKeyboard)mKeyboard).isF1Key(key);
}
private boolean isNonMicLatinF1Key(Key key) {
return isLatinF1Key(key) && key.label != null;
}
private static boolean isNumberAtEdgeOfPopupChars(Key key) {
return isNumberAtLeftmostPopupChar(key) || isNumberAtRightmostPopupChar(key);
}
/* package */ static boolean isNumberAtLeftmostPopupChar(Key key) {
if (key.popupCharacters != null && key.popupCharacters.length() > 0
&& isAsciiDigit(key.popupCharacters.charAt(0))) {
return true;
}
return false;
}
/* package */ static boolean isNumberAtRightmostPopupChar(Key key) {
if (key.popupCharacters != null && key.popupCharacters.length() > 0
&& isAsciiDigit(key.popupCharacters.charAt(key.popupCharacters.length() - 1))) {
return true;
}
return false;
}
private static boolean isAsciiDigit(char c) {
return (c < 0x80) && Character.isDigit(c);
}
private MotionEvent generateMiniKeyboardMotionEvent(int action, int x, int y, long eventTime) {
return MotionEvent.obtain(mMiniKeyboardPopupTime, eventTime, action,
x - mMiniKeyboardOriginX, y - mMiniKeyboardOriginY, 0);
}
/*package*/ boolean enableSlideKeyHack() {
return false;
}
private PointerTracker getPointerTracker(final int id) {
final ArrayList<PointerTracker> pointers = mPointerTrackers;
final Key[] keys = mKeys;
final OnKeyboardActionListener listener = mKeyboardActionListener;
// Create pointer trackers until we can get 'id+1'-th tracker, if needed.
for (int i = pointers.size(); i <= id; i++) {
final PointerTracker tracker =
new PointerTracker(i, mHandler, mKeyDetector, this, getResources(), enableSlideKeyHack());
if (keys != null)
tracker.setKeyboard(keys, mKeyHysteresisDistance);
if (listener != null)
tracker.setOnKeyboardActionListener(listener);
pointers.add(tracker);
}
return pointers.get(id);
}
public boolean isInSlidingKeyInput() {
if (mMiniKeyboardVisible) {
return mMiniKeyboard.isInSlidingKeyInput();
} else {
return mPointerQueue.isInSlidingKeyInput();
}
}
public int getPointerCount() {
return mOldPointerCount;
}
@Override
public boolean onTouchEvent(MotionEvent me) {
return onTouchEvent(me, false);
}
public boolean onTouchEvent(MotionEvent me, boolean continuing) {
final int action = me.getActionMasked();
final int pointerCount = me.getPointerCount();
final int oldPointerCount = mOldPointerCount;
mOldPointerCount = pointerCount;
// TODO: cleanup this code into a multi-touch to single-touch event converter class?
// If the device does not have distinct multi-touch support panel, ignore all multi-touch
// events except a transition from/to single-touch.
if (!mHasDistinctMultitouch && pointerCount > 1 && oldPointerCount > 1) {
return true;
}
// Track the last few movements to look for spurious swipes.
mSwipeTracker.addMovement(me);
// Gesture detector must be enabled only when mini-keyboard is not on the screen.
if (!mMiniKeyboardVisible
&& mGestureDetector != null && mGestureDetector.onTouchEvent(me)) {
dismissKeyPreview();
mHandler.cancelKeyTimers();
return true;
}
final long eventTime = me.getEventTime();
final int index = me.getActionIndex();
final int id = me.getPointerId(index);
final int x = (int)me.getX(index);
final int y = (int)me.getY(index);
// Needs to be called after the gesture detector gets a turn, as it may have
// displayed the mini keyboard
if (mMiniKeyboardVisible) {
final int miniKeyboardPointerIndex = me.findPointerIndex(mMiniKeyboardTrackerId);
if (miniKeyboardPointerIndex >= 0 && miniKeyboardPointerIndex < pointerCount) {
final int miniKeyboardX = (int)me.getX(miniKeyboardPointerIndex);
final int miniKeyboardY = (int)me.getY(miniKeyboardPointerIndex);
MotionEvent translated = generateMiniKeyboardMotionEvent(action,
miniKeyboardX, miniKeyboardY, eventTime);
mMiniKeyboard.onTouchEvent(translated);
translated.recycle();
}
return true;
}
if (mHandler.isInKeyRepeat()) {
// It will keep being in the key repeating mode while the key is being pressed.
if (action == MotionEvent.ACTION_MOVE) {
return true;
}
final PointerTracker tracker = getPointerTracker(id);
// Key repeating timer will be canceled if 2 or more keys are in action, and current
// event (UP or DOWN) is non-modifier key.
if (pointerCount > 1 && !tracker.isModifier()) {
mHandler.cancelKeyRepeatTimer();
}
// Up event will pass through.
}
// TODO: cleanup this code into a multi-touch to single-touch event converter class?
// Translate mutli-touch event to single-touch events on the device that has no distinct
// multi-touch panel.
if (!mHasDistinctMultitouch) {
// Use only main (id=0) pointer tracker.
PointerTracker tracker = getPointerTracker(0);
if (pointerCount == 1 && oldPointerCount == 2) {
// Multi-touch to single touch transition.
// Send a down event for the latest pointer.
tracker.onDownEvent(x, y, eventTime);
} else if (pointerCount == 2 && oldPointerCount == 1) {
// Single-touch to multi-touch transition.
// Send an up event for the last pointer.
tracker.onUpEvent(tracker.getLastX(), tracker.getLastY(), eventTime);
} else if (pointerCount == 1 && oldPointerCount == 1) {
tracker.onTouchEvent(action, x, y, eventTime);
} else {
Log.w(TAG, "Unknown touch panel behavior: pointer count is " + pointerCount
+ " (old " + oldPointerCount + ")");
}
if (continuing)
tracker.setSlidingKeyInputState(true);
return true;
}
if (action == MotionEvent.ACTION_MOVE) {
if (!mIgnoreMove) {
for (int i = 0; i < pointerCount; i++) {
PointerTracker tracker = getPointerTracker(me.getPointerId(i));
tracker.onMoveEvent((int)me.getX(i), (int)me.getY(i), eventTime);
}
}
} else {
PointerTracker tracker = getPointerTracker(id);
switch (action) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_POINTER_DOWN:
mIgnoreMove = false;
onDownEvent(tracker, x, y, eventTime);
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_POINTER_UP:
mIgnoreMove = false;
onUpEvent(tracker, x, y, eventTime);
break;
case MotionEvent.ACTION_CANCEL:
onCancelEvent(tracker, x, y, eventTime);
break;
}
if (continuing)
tracker.setSlidingKeyInputState(true);
}
return true;
}
private void onDownEvent(PointerTracker tracker, int x, int y, long eventTime) {
if (tracker.isOnModifierKey(x, y)) {
// Before processing a down event of modifier key, all pointers already being tracked
// should be released.
mPointerQueue.releaseAllPointersExcept(null, eventTime);
}
tracker.onDownEvent(x, y, eventTime);
mPointerQueue.add(tracker);
}
private void onUpEvent(PointerTracker tracker, int x, int y, long eventTime) {
if (tracker.isModifier()) {
// Before processing an up event of modifier key, all pointers already being tracked
// should be released.
mPointerQueue.releaseAllPointersExcept(tracker, eventTime);
} else {
int index = mPointerQueue.lastIndexOf(tracker);
if (index >= 0) {
mPointerQueue.releaseAllPointersOlderThan(tracker, eventTime);
} else {
Log.w(TAG, "onUpEvent: corresponding down event not found for pointer "
+ tracker.mPointerId);
}
}
tracker.onUpEvent(x, y, eventTime);
mPointerQueue.remove(tracker);
}
private void onCancelEvent(PointerTracker tracker, int x, int y, long eventTime) {
tracker.onCancelEvent(x, y, eventTime);
mPointerQueue.remove(tracker);
}
protected boolean swipeRight() {
return mKeyboardActionListener.swipeRight();
}
protected boolean swipeLeft() {
return mKeyboardActionListener.swipeLeft();
}
/*package*/ boolean swipeUp() {
return mKeyboardActionListener.swipeUp();
}
protected boolean swipeDown() {
return mKeyboardActionListener.swipeDown();
}
public void closing() {
Log.i(TAG, "closing " + this);
if (mPreviewPopup != null) mPreviewPopup.dismiss();
mHandler.cancelAllMessages();
dismissPopupKeyboard();
//mMiniKeyboardContainer = null; // TODO: destroy/recycle the views?
//mMiniKeyboard = null;
// TODO(klausw): use a global bitmap repository, keeping two bitmaps permanently -
// one for main and one for popup.
//
// Allow having the backup bitmap be bigger than the canvas needed, only shrinking in rare cases -
// for example if reducing the size of the main keyboard.
//mBuffer = null;
//mCanvas = null;
mMiniKeyboardCacheMain.clear();
mMiniKeyboardCacheShift.clear();
mMiniKeyboardCacheCaps.clear();
}
@Override
public void onDetachedFromWindow() {
super.onDetachedFromWindow();
//Log.i(TAG, "onDetachedFromWindow() for " + this);
closing();
}
protected boolean popupKeyboardIsShowing() {
return mMiniKeyboardPopup != null && mMiniKeyboardPopup.isShowing();
}
protected void dismissPopupKeyboard() {
if (mMiniKeyboardPopup != null) {
//Log.i(TAG, "dismissPopupKeyboard() " + mMiniKeyboardPopup + " showing=" + mMiniKeyboardPopup.isShowing());
if (mMiniKeyboardPopup.isShowing()) {
mMiniKeyboardPopup.dismiss();
}
mMiniKeyboardVisible = false;
invalidateAllKeys();
}
}
public boolean handleBack() {
if (mMiniKeyboardPopup != null && mMiniKeyboardPopup.isShowing()) {
dismissPopupKeyboard();
return true;
}
return false;
}
}
| 11beeaosama-descrbvbnvbniption | java/src/org/pocketworkstation/pckeyboard/LatinKeyboardBaseView.java | Java | asf20 | 73,824 |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.pocketworkstation.pckeyboard;
import android.content.SharedPreferences;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* Reflection utils to call SharedPreferences$Editor.apply when possible,
* falling back to commit when apply isn't available.
*/
public class SharedPreferencesCompat {
private static final Method sApplyMethod = findApplyMethod();
private static Method findApplyMethod() {
try {
return SharedPreferences.Editor.class.getMethod("apply");
} catch (NoSuchMethodException unused) {
// fall through
}
return null;
}
public static void apply(SharedPreferences.Editor editor) {
if (sApplyMethod != null) {
try {
sApplyMethod.invoke(editor);
return;
} catch (InvocationTargetException unused) {
// fall through
} catch (IllegalAccessException unused) {
// fall through
}
}
editor.commit();
}
}
| 11beeaosama-descrbvbnvbniption | java/src/org/pocketworkstation/pckeyboard/SharedPreferencesCompat.java | Java | asf20 | 1,699 |
package org.pocketworkstation.pckeyboard;
import java.util.Locale;
import android.content.Context;
import android.content.res.TypedArray;
import android.preference.DialogPreference;
import android.util.AttributeSet;
import android.view.View;
import android.widget.SeekBar;
import android.widget.TextView;
/**
* SeekBarPreference provides a dialog for editing float-valued preferences with a slider.
*/
public class SeekBarPreference extends DialogPreference {
private TextView mMinText;
private TextView mMaxText;
private TextView mValText;
private SeekBar mSeek;
private float mMin;
private float mMax;
private float mVal;
private float mPrevVal;
private float mStep;
private boolean mAsPercent;
private boolean mLogScale;
private String mDisplayFormat;
public SeekBarPreference(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
protected void init(Context context, AttributeSet attrs) {
setDialogLayoutResource(R.layout.seek_bar_dialog);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SeekBarPreference);
mMin = a.getFloat(R.styleable.SeekBarPreference_minValue, 0.0f);
mMax = a.getFloat(R.styleable.SeekBarPreference_maxValue, 100.0f);
mStep = a.getFloat(R.styleable.SeekBarPreference_step, 0.0f);
mAsPercent = a.getBoolean(R.styleable.SeekBarPreference_asPercent, false);
mLogScale = a.getBoolean(R.styleable.SeekBarPreference_logScale, false);
mDisplayFormat = a.getString(R.styleable.SeekBarPreference_displayFormat);
}
@Override
protected Float onGetDefaultValue(TypedArray a, int index) {
return a.getFloat(index, 0.0f);
}
@Override
protected void onSetInitialValue(boolean restorePersistedValue, Object defaultValue) {
if (restorePersistedValue) {
setVal(getPersistedFloat(0.0f));
} else {
setVal((Float) defaultValue);
}
savePrevVal();
}
private String formatFloatDisplay(Float val) {
// Use current locale for format, this is for display only.
if (mAsPercent) {
return String.format("%d%%", (int) (val * 100));
}
if (mDisplayFormat != null) {
return String.format(mDisplayFormat, val);
} else {
return Float.toString(val);
}
}
private void showVal() {
mValText.setText(formatFloatDisplay(mVal));
}
protected void setVal(Float val) {
mVal = val;
}
protected void savePrevVal() {
mPrevVal = mVal;
}
protected void restoreVal() {
mVal = mPrevVal;
}
protected String getValString() {
return Float.toString(mVal);
}
private float percentToSteppedVal(int percent, float min, float max, float step, boolean logScale) {
float val;
if (logScale) {
val = (float) Math.exp(percentToSteppedVal(percent, (float) Math.log(min), (float) Math.log(max), step, false));
} else {
float delta = percent * (max - min) / 100;
if (step != 0.0f) {
delta = Math.round(delta / step) * step;
}
val = min + delta;
}
// Hack: Round number to 2 significant digits so that it looks nicer.
val = Float.valueOf(String.format(Locale.US, "%.2g", val));
return val;
}
private int getPercent(float val, float min, float max) {
return (int) (100 * (val - min) / (max - min));
}
private int getProgressVal() {
if (mLogScale) {
return getPercent((float) Math.log(mVal), (float) Math.log(mMin), (float) Math.log(mMax));
} else {
return getPercent(mVal, mMin, mMax);
}
}
@Override
protected void onBindDialogView(View view) {
mSeek = (SeekBar) view.findViewById(R.id.seekBarPref);
mMinText = (TextView) view.findViewById(R.id.seekMin);
mMaxText = (TextView) view.findViewById(R.id.seekMax);
mValText = (TextView) view.findViewById(R.id.seekVal);
showVal();
mMinText.setText(formatFloatDisplay(mMin));
mMaxText.setText(formatFloatDisplay(mMax));
mSeek.setProgress(getProgressVal());
mSeek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
public void onStopTrackingTouch(SeekBar seekBar) {}
public void onStartTrackingTouch(SeekBar seekBar) {}
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser) {
float newVal = percentToSteppedVal(progress, mMin, mMax, mStep, mLogScale);
if (newVal != mVal) {
onChange(newVal);
}
setVal(newVal);
mSeek.setProgress(getProgressVal());
}
showVal();
}
});
super.onBindDialogView(view);
}
public void onChange(float val) {
// override in subclasses
}
@Override
public CharSequence getSummary() {
return formatFloatDisplay(mVal);
}
@Override
protected void onDialogClosed(boolean positiveResult) {
if (!positiveResult) {
restoreVal();
return;
}
if (shouldPersist()) {
persistFloat(mVal);
savePrevVal();
}
notifyChanged();
}
}
| 11beeaosama-descrbvbnvbniption | java/src/org/pocketworkstation/pckeyboard/SeekBarPreference.java | Java | asf20 | 5,599 |
/*
* Copyright (C) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import android.view.MotionEvent;
class SwipeTracker {
private static final int NUM_PAST = 4;
private static final int LONGEST_PAST_TIME = 200;
final EventRingBuffer mBuffer = new EventRingBuffer(NUM_PAST);
private float mYVelocity;
private float mXVelocity;
public void addMovement(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
mBuffer.clear();
return;
}
long time = ev.getEventTime();
final int count = ev.getHistorySize();
for (int i = 0; i < count; i++) {
addPoint(ev.getHistoricalX(i), ev.getHistoricalY(i), ev.getHistoricalEventTime(i));
}
addPoint(ev.getX(), ev.getY(), time);
}
private void addPoint(float x, float y, long time) {
final EventRingBuffer buffer = mBuffer;
while (buffer.size() > 0) {
long lastT = buffer.getTime(0);
if (lastT >= time - LONGEST_PAST_TIME)
break;
buffer.dropOldest();
}
buffer.add(x, y, time);
}
public void computeCurrentVelocity(int units) {
computeCurrentVelocity(units, Float.MAX_VALUE);
}
public void computeCurrentVelocity(int units, float maxVelocity) {
final EventRingBuffer buffer = mBuffer;
final float oldestX = buffer.getX(0);
final float oldestY = buffer.getY(0);
final long oldestTime = buffer.getTime(0);
float accumX = 0;
float accumY = 0;
final int count = buffer.size();
for (int pos = 1; pos < count; pos++) {
final int dur = (int)(buffer.getTime(pos) - oldestTime);
if (dur == 0) continue;
float dist = buffer.getX(pos) - oldestX;
float vel = (dist / dur) * units; // pixels/frame.
if (accumX == 0) accumX = vel;
else accumX = (accumX + vel) * .5f;
dist = buffer.getY(pos) - oldestY;
vel = (dist / dur) * units; // pixels/frame.
if (accumY == 0) accumY = vel;
else accumY = (accumY + vel) * .5f;
}
mXVelocity = accumX < 0.0f ? Math.max(accumX, -maxVelocity)
: Math.min(accumX, maxVelocity);
mYVelocity = accumY < 0.0f ? Math.max(accumY, -maxVelocity)
: Math.min(accumY, maxVelocity);
}
public float getXVelocity() {
return mXVelocity;
}
public float getYVelocity() {
return mYVelocity;
}
static class EventRingBuffer {
private final int bufSize;
private final float xBuf[];
private final float yBuf[];
private final long timeBuf[];
private int top; // points new event
private int end; // points oldest event
private int count; // the number of valid data
public EventRingBuffer(int max) {
this.bufSize = max;
xBuf = new float[max];
yBuf = new float[max];
timeBuf = new long[max];
clear();
}
public void clear() {
top = end = count = 0;
}
public int size() {
return count;
}
// Position 0 points oldest event
private int index(int pos) {
return (end + pos) % bufSize;
}
private int advance(int index) {
return (index + 1) % bufSize;
}
public void add(float x, float y, long time) {
xBuf[top] = x;
yBuf[top] = y;
timeBuf[top] = time;
top = advance(top);
if (count < bufSize) {
count++;
} else {
end = advance(end);
}
}
public float getX(int pos) {
return xBuf[index(pos)];
}
public float getY(int pos) {
return yBuf[index(pos)];
}
public long getTime(int pos) {
return timeBuf[index(pos)];
}
public void dropOldest() {
count--;
end = advance(end);
}
}
} | 11beeaosama-descrbvbnvbniption | java/src/org/pocketworkstation/pckeyboard/SwipeTracker.java | Java | asf20 | 4,721 |
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import android.app.backup.BackupManager;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.PreferenceActivity;
public class PrefScreenView extends PreferenceActivity
implements SharedPreferences.OnSharedPreferenceChangeListener {
private ListPreference mRenderModePreference;
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
addPreferencesFromResource(R.xml.prefs_view);
SharedPreferences prefs = getPreferenceManager().getSharedPreferences();
prefs.registerOnSharedPreferenceChangeListener(this);
mRenderModePreference = (ListPreference) findPreference(LatinIME.PREF_RENDER_MODE);
}
@Override
protected void onDestroy() {
getPreferenceManager().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(
this);
super.onDestroy();
}
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
(new BackupManager(this)).dataChanged();
}
@Override
protected void onResume() {
super.onResume();
if (LatinKeyboardBaseView.sSetRenderMode == null) {
mRenderModePreference.setEnabled(false);
mRenderModePreference.setSummary(R.string.render_mode_unavailable);
}
}
}
| 11beeaosama-descrbvbnvbniption | java/src/org/pocketworkstation/pckeyboard/PrefScreenView.java | Java | asf20 | 2,050 |
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.InflateException;
import java.lang.ref.SoftReference;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Locale;
public class KeyboardSwitcher implements
SharedPreferences.OnSharedPreferenceChangeListener {
private static String TAG = "PCKeyboardKbSw";
public static final int MODE_NONE = 0;
public static final int MODE_TEXT = 1;
public static final int MODE_SYMBOLS = 2;
public static final int MODE_PHONE = 3;
public static final int MODE_URL = 4;
public static final int MODE_EMAIL = 5;
public static final int MODE_IM = 6;
public static final int MODE_WEB = 7;
// Main keyboard layouts without the settings key
public static final int KEYBOARDMODE_NORMAL = R.id.mode_normal;
public static final int KEYBOARDMODE_URL = R.id.mode_url;
public static final int KEYBOARDMODE_EMAIL = R.id.mode_email;
public static final int KEYBOARDMODE_IM = R.id.mode_im;
public static final int KEYBOARDMODE_WEB = R.id.mode_webentry;
// Main keyboard layouts with the settings key
public static final int KEYBOARDMODE_NORMAL_WITH_SETTINGS_KEY = R.id.mode_normal_with_settings_key;
public static final int KEYBOARDMODE_URL_WITH_SETTINGS_KEY = R.id.mode_url_with_settings_key;
public static final int KEYBOARDMODE_EMAIL_WITH_SETTINGS_KEY = R.id.mode_email_with_settings_key;
public static final int KEYBOARDMODE_IM_WITH_SETTINGS_KEY = R.id.mode_im_with_settings_key;
public static final int KEYBOARDMODE_WEB_WITH_SETTINGS_KEY = R.id.mode_webentry_with_settings_key;
// Symbols keyboard layout without the settings key
public static final int KEYBOARDMODE_SYMBOLS = R.id.mode_symbols;
// Symbols keyboard layout with the settings key
public static final int KEYBOARDMODE_SYMBOLS_WITH_SETTINGS_KEY = R.id.mode_symbols_with_settings_key;
public static final String DEFAULT_LAYOUT_ID = "0";
public static final String PREF_KEYBOARD_LAYOUT = "pref_keyboard_layout";
private static final int[] THEMES = new int[] {
R.layout.input_ics,
R.layout.input_gingerbread,
R.layout.input_stone_bold,
R.layout.input_trans_neon,
};
// Tables which contains resource ids for each character theme color
private static final int KBD_PHONE = R.xml.kbd_phone;
private static final int KBD_PHONE_SYMBOLS = R.xml.kbd_phone_symbols;
private static final int KBD_SYMBOLS = R.xml.kbd_symbols;
private static final int KBD_SYMBOLS_SHIFT = R.xml.kbd_symbols_shift;
private static final int KBD_QWERTY = R.xml.kbd_qwerty;
private static final int KBD_FULL = R.xml.kbd_full;
private static final int KBD_FULL_FN = R.xml.kbd_full_fn;
private static final int KBD_COMPACT = R.xml.kbd_compact;
private static final int KBD_COMPACT_FN = R.xml.kbd_compact_fn;
private LatinKeyboardView mInputView;
private static final int[] ALPHABET_MODES = { KEYBOARDMODE_NORMAL,
KEYBOARDMODE_URL, KEYBOARDMODE_EMAIL, KEYBOARDMODE_IM,
KEYBOARDMODE_WEB, KEYBOARDMODE_NORMAL_WITH_SETTINGS_KEY,
KEYBOARDMODE_URL_WITH_SETTINGS_KEY,
KEYBOARDMODE_EMAIL_WITH_SETTINGS_KEY,
KEYBOARDMODE_IM_WITH_SETTINGS_KEY,
KEYBOARDMODE_WEB_WITH_SETTINGS_KEY };
private LatinIME mInputMethodService;
private KeyboardId mSymbolsId;
private KeyboardId mSymbolsShiftedId;
private KeyboardId mCurrentId;
private final HashMap<KeyboardId, SoftReference<LatinKeyboard>> mKeyboards = new HashMap<KeyboardId, SoftReference<LatinKeyboard>>();
private int mMode = MODE_NONE;
/** One of the MODE_XXX values */
private int mImeOptions;
private boolean mIsSymbols;
private int mFullMode;
/**
* mIsAutoCompletionActive indicates that auto completed word will be input
* instead of what user actually typed.
*/
private boolean mIsAutoCompletionActive;
private boolean mHasVoice;
private boolean mVoiceOnPrimary;
private boolean mPreferSymbols;
private static final int AUTO_MODE_SWITCH_STATE_ALPHA = 0;
private static final int AUTO_MODE_SWITCH_STATE_SYMBOL_BEGIN = 1;
private static final int AUTO_MODE_SWITCH_STATE_SYMBOL = 2;
// The following states are used only on the distinct multi-touch panel
// devices.
private static final int AUTO_MODE_SWITCH_STATE_MOMENTARY = 3;
private static final int AUTO_MODE_SWITCH_STATE_CHORDING = 4;
private int mAutoModeSwitchState = AUTO_MODE_SWITCH_STATE_ALPHA;
// Indicates whether or not we have the settings key
private boolean mHasSettingsKey;
private static final int SETTINGS_KEY_MODE_AUTO = R.string.settings_key_mode_auto;
private static final int SETTINGS_KEY_MODE_ALWAYS_SHOW = R.string.settings_key_mode_always_show;
// NOTE: No need to have SETTINGS_KEY_MODE_ALWAYS_HIDE here because it's not
// being referred to
// in the source code now.
// Default is SETTINGS_KEY_MODE_AUTO.
private static final int DEFAULT_SETTINGS_KEY_MODE = SETTINGS_KEY_MODE_AUTO;
private int mLastDisplayWidth;
private LanguageSwitcher mLanguageSwitcher;
private int mLayoutId;
private static final KeyboardSwitcher sInstance = new KeyboardSwitcher();
public static KeyboardSwitcher getInstance() {
return sInstance;
}
private KeyboardSwitcher() {
// Intentional empty constructor for singleton.
}
public static void init(LatinIME ims) {
sInstance.mInputMethodService = ims;
final SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(ims);
sInstance.mLayoutId = Integer.valueOf(prefs.getString(
PREF_KEYBOARD_LAYOUT, DEFAULT_LAYOUT_ID));
sInstance.updateSettingsKeyState(prefs);
prefs.registerOnSharedPreferenceChangeListener(sInstance);
sInstance.mSymbolsId = sInstance.makeSymbolsId(false);
sInstance.mSymbolsShiftedId = sInstance.makeSymbolsShiftedId(false);
}
/**
* Sets the input locale, when there are multiple locales for input. If no
* locale switching is required, then the locale should be set to null.
*
* @param locale
* the current input locale, or null for default locale with no
* locale button.
*/
public void setLanguageSwitcher(LanguageSwitcher languageSwitcher) {
mLanguageSwitcher = languageSwitcher;
languageSwitcher.getInputLocale(); // for side effect
}
private KeyboardId makeSymbolsId(boolean hasVoice) {
if (mFullMode == 1) {
return new KeyboardId(KBD_COMPACT_FN, KEYBOARDMODE_SYMBOLS, true, hasVoice);
} else if (mFullMode == 2) {
return new KeyboardId(KBD_FULL_FN, KEYBOARDMODE_SYMBOLS, true, hasVoice);
}
return new KeyboardId(KBD_SYMBOLS,
mHasSettingsKey ? KEYBOARDMODE_SYMBOLS_WITH_SETTINGS_KEY
: KEYBOARDMODE_SYMBOLS, false, hasVoice);
}
private KeyboardId makeSymbolsShiftedId(boolean hasVoice) {
if (mFullMode > 0)
return null;
return new KeyboardId(KBD_SYMBOLS_SHIFT,
mHasSettingsKey ? KEYBOARDMODE_SYMBOLS_WITH_SETTINGS_KEY
: KEYBOARDMODE_SYMBOLS, false, hasVoice);
}
public void makeKeyboards(boolean forceCreate) {
mFullMode = LatinIME.sKeyboardSettings.keyboardMode;
mSymbolsId = makeSymbolsId(mHasVoice && !mVoiceOnPrimary);
mSymbolsShiftedId = makeSymbolsShiftedId(mHasVoice && !mVoiceOnPrimary);
if (forceCreate)
mKeyboards.clear();
// Configuration change is coming after the keyboard gets recreated. So
// don't rely on that.
// If keyboards have already been made, check if we have a screen width
// change and
// create the keyboard layouts again at the correct orientation
int displayWidth = mInputMethodService.getMaxWidth();
if (displayWidth == mLastDisplayWidth)
return;
mLastDisplayWidth = displayWidth;
if (!forceCreate)
mKeyboards.clear();
}
/**
* Represents the parameters necessary to construct a new LatinKeyboard,
* which also serve as a unique identifier for each keyboard type.
*/
private static class KeyboardId {
// TODO: should have locale and portrait/landscape orientation?
public final int mXml;
public final int mKeyboardMode;
/** A KEYBOARDMODE_XXX value */
public final boolean mEnableShiftLock;
public final boolean mHasVoice;
public final float mKeyboardHeightPercent;
public final boolean mUsingExtension;
private final int mHashCode;
public KeyboardId(int xml, int mode, boolean enableShiftLock,
boolean hasVoice) {
this.mXml = xml;
this.mKeyboardMode = mode;
this.mEnableShiftLock = enableShiftLock;
this.mHasVoice = hasVoice;
this.mKeyboardHeightPercent = LatinIME.sKeyboardSettings.keyboardHeightPercent;
this.mUsingExtension = LatinIME.sKeyboardSettings.useExtension;
this.mHashCode = Arrays.hashCode(new Object[] { xml, mode,
enableShiftLock, hasVoice });
}
@Override
public boolean equals(Object other) {
return other instanceof KeyboardId && equals((KeyboardId) other);
}
private boolean equals(KeyboardId other) {
return other != null
&& other.mXml == this.mXml
&& other.mKeyboardMode == this.mKeyboardMode
&& other.mUsingExtension == this.mUsingExtension
&& other.mEnableShiftLock == this.mEnableShiftLock
&& other.mHasVoice == this.mHasVoice;
}
@Override
public int hashCode() {
return mHashCode;
}
}
public void setVoiceMode(boolean enableVoice, boolean voiceOnPrimary) {
if (enableVoice != mHasVoice || voiceOnPrimary != mVoiceOnPrimary) {
mKeyboards.clear();
}
mHasVoice = enableVoice;
mVoiceOnPrimary = voiceOnPrimary;
setKeyboardMode(mMode, mImeOptions, mHasVoice, mIsSymbols);
}
private boolean hasVoiceButton(boolean isSymbols) {
return mHasVoice && (isSymbols != mVoiceOnPrimary);
}
public void setKeyboardMode(int mode, int imeOptions, boolean enableVoice) {
mAutoModeSwitchState = AUTO_MODE_SWITCH_STATE_ALPHA;
mPreferSymbols = mode == MODE_SYMBOLS;
if (mode == MODE_SYMBOLS) {
mode = MODE_TEXT;
}
try {
setKeyboardMode(mode, imeOptions, enableVoice, mPreferSymbols);
} catch (RuntimeException e) {
LatinImeLogger.logOnException(mode + "," + imeOptions + ","
+ mPreferSymbols, e);
}
}
private void setKeyboardMode(int mode, int imeOptions, boolean enableVoice,
boolean isSymbols) {
if (mInputView == null)
return;
mMode = mode;
mImeOptions = imeOptions;
if (enableVoice != mHasVoice) {
// TODO clean up this unnecessary recursive call.
setVoiceMode(enableVoice, mVoiceOnPrimary);
}
mIsSymbols = isSymbols;
mInputView.setPreviewEnabled(mInputMethodService.getPopupOn());
KeyboardId id = getKeyboardId(mode, imeOptions, isSymbols);
LatinKeyboard keyboard = null;
keyboard = getKeyboard(id);
if (mode == MODE_PHONE) {
mInputView.setPhoneKeyboard(keyboard);
}
mCurrentId = id;
mInputView.setKeyboard(keyboard);
keyboard.setShiftState(Keyboard.SHIFT_OFF);
keyboard.setImeOptions(mInputMethodService.getResources(), mMode,
imeOptions);
keyboard.updateSymbolIcons(mIsAutoCompletionActive);
}
private LatinKeyboard getKeyboard(KeyboardId id) {
SoftReference<LatinKeyboard> ref = mKeyboards.get(id);
LatinKeyboard keyboard = (ref == null) ? null : ref.get();
if (keyboard == null) {
Resources orig = mInputMethodService.getResources();
Configuration conf = orig.getConfiguration();
Locale saveLocale = conf.locale;
conf.locale = LatinIME.sKeyboardSettings.inputLocale;
orig.updateConfiguration(conf, null);
keyboard = new LatinKeyboard(mInputMethodService, id.mXml,
id.mKeyboardMode, id.mKeyboardHeightPercent);
keyboard.setVoiceMode(hasVoiceButton(id.mXml == R.xml.kbd_symbols), mHasVoice);
keyboard.setLanguageSwitcher(mLanguageSwitcher, mIsAutoCompletionActive);
// if (isFullMode()) {
// keyboard.setExtension(new LatinKeyboard(mInputMethodService,
// R.xml.kbd_extension_full, 0, id.mRowHeightPercent));
// } else if (isAlphabetMode()) { // TODO: not in full keyboard mode? Per-mode extension kbd?
// keyboard.setExtension(new LatinKeyboard(mInputMethodService,
// R.xml.kbd_extension, 0, id.mRowHeightPercent));
// }
if (id.mEnableShiftLock) {
keyboard.enableShiftLock();
}
mKeyboards.put(id, new SoftReference<LatinKeyboard>(keyboard));
conf.locale = saveLocale;
orig.updateConfiguration(conf, null);
}
return keyboard;
}
public boolean isFullMode() {
return mFullMode > 0;
}
private KeyboardId getKeyboardId(int mode, int imeOptions, boolean isSymbols) {
boolean hasVoice = hasVoiceButton(isSymbols);
if (mFullMode > 0) {
switch (mode) {
case MODE_TEXT:
case MODE_URL:
case MODE_EMAIL:
case MODE_IM:
case MODE_WEB:
return new KeyboardId(mFullMode == 1 ? KBD_COMPACT : KBD_FULL,
KEYBOARDMODE_NORMAL, true, hasVoice);
}
}
// TODO: generalize for any KeyboardId
int keyboardRowsResId = KBD_QWERTY;
if (isSymbols) {
if (mode == MODE_PHONE) {
return new KeyboardId(KBD_PHONE_SYMBOLS, 0, false, hasVoice);
} else {
return new KeyboardId(
KBD_SYMBOLS,
mHasSettingsKey ? KEYBOARDMODE_SYMBOLS_WITH_SETTINGS_KEY
: KEYBOARDMODE_SYMBOLS, false, hasVoice);
}
}
switch (mode) {
case MODE_NONE:
LatinImeLogger.logOnWarning("getKeyboardId:" + mode + ","
+ imeOptions + "," + isSymbols);
/* fall through */
case MODE_TEXT:
return new KeyboardId(keyboardRowsResId,
mHasSettingsKey ? KEYBOARDMODE_NORMAL_WITH_SETTINGS_KEY
: KEYBOARDMODE_NORMAL, true, hasVoice);
case MODE_SYMBOLS:
return new KeyboardId(KBD_SYMBOLS,
mHasSettingsKey ? KEYBOARDMODE_SYMBOLS_WITH_SETTINGS_KEY
: KEYBOARDMODE_SYMBOLS, false, hasVoice);
case MODE_PHONE:
return new KeyboardId(KBD_PHONE, 0, false, hasVoice);
case MODE_URL:
return new KeyboardId(keyboardRowsResId,
mHasSettingsKey ? KEYBOARDMODE_URL_WITH_SETTINGS_KEY
: KEYBOARDMODE_URL, true, hasVoice);
case MODE_EMAIL:
return new KeyboardId(keyboardRowsResId,
mHasSettingsKey ? KEYBOARDMODE_EMAIL_WITH_SETTINGS_KEY
: KEYBOARDMODE_EMAIL, true, hasVoice);
case MODE_IM:
return new KeyboardId(keyboardRowsResId,
mHasSettingsKey ? KEYBOARDMODE_IM_WITH_SETTINGS_KEY
: KEYBOARDMODE_IM, true, hasVoice);
case MODE_WEB:
return new KeyboardId(keyboardRowsResId,
mHasSettingsKey ? KEYBOARDMODE_WEB_WITH_SETTINGS_KEY
: KEYBOARDMODE_WEB, true, hasVoice);
}
return null;
}
public int getKeyboardMode() {
return mMode;
}
public boolean isAlphabetMode() {
if (mCurrentId == null) {
return false;
}
int currentMode = mCurrentId.mKeyboardMode;
if (mFullMode > 0 && currentMode == KEYBOARDMODE_NORMAL)
return true;
for (Integer mode : ALPHABET_MODES) {
if (currentMode == mode) {
return true;
}
}
return false;
}
public void setShiftState(int shiftState) {
if (mInputView != null) {
mInputView.setShiftState(shiftState);
}
}
public void setFn(boolean useFn) {
if (mInputView == null) return;
int oldShiftState = mInputView.getShiftState();
if (useFn) {
LatinKeyboard kbd = getKeyboard(mSymbolsId);
kbd.enableShiftLock();
mCurrentId = mSymbolsId;
mInputView.setKeyboard(kbd);
mInputView.setShiftState(oldShiftState);
} else {
// Return to default keyboard state
setKeyboardMode(mMode, mImeOptions, mHasVoice, false);
mInputView.setShiftState(oldShiftState);
}
}
public void setCtrlIndicator(boolean active) {
if (mInputView == null) return;
mInputView.setCtrlIndicator(active);
}
public void setAltIndicator(boolean active) {
if (mInputView == null) return;
mInputView.setAltIndicator(active);
}
public void setMetaIndicator(boolean active) {
if (mInputView == null) return;
mInputView.setMetaIndicator(active);
}
public void toggleShift() {
//Log.i(TAG, "toggleShift isAlphabetMode=" + isAlphabetMode() + " mSettings.fullMode=" + mSettings.fullMode);
if (isAlphabetMode())
return;
if (mFullMode > 0) {
boolean shifted = mInputView.isShiftAll();
mInputView.setShiftState(shifted ? Keyboard.SHIFT_OFF : Keyboard.SHIFT_ON);
return;
}
if (mCurrentId.equals(mSymbolsId)
|| !mCurrentId.equals(mSymbolsShiftedId)) {
LatinKeyboard symbolsShiftedKeyboard = getKeyboard(mSymbolsShiftedId);
mCurrentId = mSymbolsShiftedId;
mInputView.setKeyboard(symbolsShiftedKeyboard);
// Symbol shifted keyboard has a ALT_SYM key that has a caps lock style indicator.
// To enable the indicator, we need to set the shift state appropriately.
symbolsShiftedKeyboard.enableShiftLock();
symbolsShiftedKeyboard.setShiftState(Keyboard.SHIFT_LOCKED);
symbolsShiftedKeyboard.setImeOptions(mInputMethodService
.getResources(), mMode, mImeOptions);
} else {
LatinKeyboard symbolsKeyboard = getKeyboard(mSymbolsId);
mCurrentId = mSymbolsId;
mInputView.setKeyboard(symbolsKeyboard);
symbolsKeyboard.enableShiftLock();
symbolsKeyboard.setShiftState(Keyboard.SHIFT_OFF);
symbolsKeyboard.setImeOptions(mInputMethodService.getResources(),
mMode, mImeOptions);
}
}
public void onCancelInput() {
// Snap back to the previous keyboard mode if the user cancels sliding
// input.
if (mAutoModeSwitchState == AUTO_MODE_SWITCH_STATE_MOMENTARY
&& getPointerCount() == 1)
mInputMethodService.changeKeyboardMode();
}
public void toggleSymbols() {
setKeyboardMode(mMode, mImeOptions, mHasVoice, !mIsSymbols);
if (mIsSymbols && !mPreferSymbols) {
mAutoModeSwitchState = AUTO_MODE_SWITCH_STATE_SYMBOL_BEGIN;
} else {
mAutoModeSwitchState = AUTO_MODE_SWITCH_STATE_ALPHA;
}
}
public boolean hasDistinctMultitouch() {
return mInputView != null && mInputView.hasDistinctMultitouch();
}
public void setAutoModeSwitchStateMomentary() {
mAutoModeSwitchState = AUTO_MODE_SWITCH_STATE_MOMENTARY;
}
public boolean isInMomentaryAutoModeSwitchState() {
return mAutoModeSwitchState == AUTO_MODE_SWITCH_STATE_MOMENTARY;
}
public boolean isInChordingAutoModeSwitchState() {
return mAutoModeSwitchState == AUTO_MODE_SWITCH_STATE_CHORDING;
}
public boolean isVibrateAndSoundFeedbackRequired() {
return mInputView != null && !mInputView.isInSlidingKeyInput();
}
private int getPointerCount() {
return mInputView == null ? 0 : mInputView.getPointerCount();
}
/**
* Updates state machine to figure out when to automatically snap back to
* the previous mode.
*/
public void onKey(int key) {
// Switch back to alpha mode if user types one or more non-space/enter
// characters
// followed by a space/enter
switch (mAutoModeSwitchState) {
case AUTO_MODE_SWITCH_STATE_MOMENTARY:
// Only distinct multi touch devices can be in this state.
// On non-distinct multi touch devices, mode change key is handled
// by {@link onKey},
// not by {@link onPress} and {@link onRelease}. So, on such
// devices,
// {@link mAutoModeSwitchState} starts from {@link
// AUTO_MODE_SWITCH_STATE_SYMBOL_BEGIN},
// or {@link AUTO_MODE_SWITCH_STATE_ALPHA}, not from
// {@link AUTO_MODE_SWITCH_STATE_MOMENTARY}.
if (key == LatinKeyboard.KEYCODE_MODE_CHANGE) {
// Detected only the mode change key has been pressed, and then
// released.
if (mIsSymbols) {
mAutoModeSwitchState = AUTO_MODE_SWITCH_STATE_SYMBOL_BEGIN;
} else {
mAutoModeSwitchState = AUTO_MODE_SWITCH_STATE_ALPHA;
}
} else if (getPointerCount() == 1) {
// Snap back to the previous keyboard mode if the user pressed
// the mode change key
// and slid to other key, then released the finger.
// If the user cancels the sliding input, snapping back to the
// previous keyboard
// mode is handled by {@link #onCancelInput}.
mInputMethodService.changeKeyboardMode();
} else {
// Chording input is being started. The keyboard mode will be
// snapped back to the
// previous mode in {@link onReleaseSymbol} when the mode change
// key is released.
mAutoModeSwitchState = AUTO_MODE_SWITCH_STATE_CHORDING;
}
break;
case AUTO_MODE_SWITCH_STATE_SYMBOL_BEGIN:
if (key != LatinIME.ASCII_SPACE && key != LatinIME.ASCII_ENTER
&& key >= 0) {
mAutoModeSwitchState = AUTO_MODE_SWITCH_STATE_SYMBOL;
}
break;
case AUTO_MODE_SWITCH_STATE_SYMBOL:
// Snap back to alpha keyboard mode if user types one or more
// non-space/enter
// characters followed by a space/enter.
if (key == LatinIME.ASCII_ENTER || key == LatinIME.ASCII_SPACE) {
mInputMethodService.changeKeyboardMode();
}
break;
}
}
public LatinKeyboardView getInputView() {
return mInputView;
}
public void recreateInputView() {
changeLatinKeyboardView(mLayoutId, true);
}
private void changeLatinKeyboardView(int newLayout, boolean forceReset) {
if (mLayoutId != newLayout || mInputView == null || forceReset) {
if (mInputView != null) {
mInputView.closing();
}
if (THEMES.length <= newLayout) {
newLayout = Integer.valueOf(DEFAULT_LAYOUT_ID);
}
LatinIMEUtil.GCUtils.getInstance().reset();
boolean tryGC = true;
for (int i = 0; i < LatinIMEUtil.GCUtils.GC_TRY_LOOP_MAX && tryGC; ++i) {
try {
mInputView = (LatinKeyboardView) mInputMethodService
.getLayoutInflater().inflate(THEMES[newLayout],
null);
tryGC = false;
} catch (OutOfMemoryError e) {
tryGC = LatinIMEUtil.GCUtils.getInstance().tryGCOrWait(
mLayoutId + "," + newLayout, e);
} catch (InflateException e) {
tryGC = LatinIMEUtil.GCUtils.getInstance().tryGCOrWait(
mLayoutId + "," + newLayout, e);
}
}
mInputView.setExtensionLayoutResId(THEMES[newLayout]);
mInputView.setOnKeyboardActionListener(mInputMethodService);
mInputView.setPadding(0, 0, 0, 0);
mLayoutId = newLayout;
}
mInputMethodService.mHandler.post(new Runnable() {
public void run() {
if (mInputView != null) {
mInputMethodService.setInputView(mInputView);
}
mInputMethodService.updateInputViewShown();
}
});
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
if (PREF_KEYBOARD_LAYOUT.equals(key)) {
changeLatinKeyboardView(Integer.valueOf(sharedPreferences
.getString(key, DEFAULT_LAYOUT_ID)), true);
} else if (LatinIMESettings.PREF_SETTINGS_KEY.equals(key)) {
updateSettingsKeyState(sharedPreferences);
recreateInputView();
}
}
public void onAutoCompletionStateChanged(boolean isAutoCompletion) {
if (isAutoCompletion != mIsAutoCompletionActive) {
LatinKeyboardView keyboardView = getInputView();
mIsAutoCompletionActive = isAutoCompletion;
keyboardView.invalidateKey(((LatinKeyboard) keyboardView
.getKeyboard())
.onAutoCompletionStateChanged(isAutoCompletion));
}
}
private void updateSettingsKeyState(SharedPreferences prefs) {
Resources resources = mInputMethodService.getResources();
final String settingsKeyMode = prefs.getString(
LatinIMESettings.PREF_SETTINGS_KEY, resources
.getString(DEFAULT_SETTINGS_KEY_MODE));
// We show the settings key when 1) SETTINGS_KEY_MODE_ALWAYS_SHOW or
// 2) SETTINGS_KEY_MODE_AUTO and there are two or more enabled IMEs on
// the system
if (settingsKeyMode.equals(resources
.getString(SETTINGS_KEY_MODE_ALWAYS_SHOW))
|| (settingsKeyMode.equals(resources
.getString(SETTINGS_KEY_MODE_AUTO)))) {
mHasSettingsKey = true;
} else {
mHasSettingsKey = false;
}
}
}
| 11beeaosama-descrbvbnvbniption | java/src/org/pocketworkstation/pckeyboard/KeyboardSwitcher.java | Java | asf20 | 28,168 |
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import android.app.backup.BackupAgentHelper;
import android.app.backup.SharedPreferencesBackupHelper;
/**
* Backs up the Latin IME shared preferences.
*/
public class LatinIMEBackupAgent extends BackupAgentHelper {
@Override
public void onCreate() {
addHelper("shared_pref", new SharedPreferencesBackupHelper(this,
getPackageName() + "_preferences"));
}
}
| 11beeaosama-descrbvbnvbniption | java/src/org/pocketworkstation/pckeyboard/LatinIMEBackupAgent.java | Java | asf20 | 1,058 |
/**
*
*/
package org.pocketworkstation.pckeyboard;
import android.content.Context;
import android.preference.ListPreference;
import android.util.AttributeSet;
import android.util.Log;
public class AutoSummaryListPreference extends ListPreference {
private static final String TAG = "HK/AutoSummaryListPreference";
public AutoSummaryListPreference(Context context) {
super(context);
}
public AutoSummaryListPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
private void trySetSummary() {
CharSequence entry = null;
try {
entry = getEntry();
} catch (ArrayIndexOutOfBoundsException e) {
Log.i(TAG, "Malfunctioning ListPreference, can't get entry");
}
if (entry != null) {
//String percent = getResources().getString(R.string.percent);
String percent = "percent";
setSummary(entry.toString().replace("%", " " + percent));
}
}
@Override
public void setEntries(CharSequence[] entries) {
super.setEntries(entries);
trySetSummary();
}
@Override
public void setEntryValues(CharSequence[] entryValues) {
super.setEntryValues(entryValues);
trySetSummary();
}
@Override
public void setValue(String value) {
super.setValue(value);
trySetSummary();
}
}
| 11beeaosama-descrbvbnvbniption | java/src/org/pocketworkstation/pckeyboard/AutoSummaryListPreference.java | Java | asf20 | 1,411 |
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.pocketworkstation.pckeyboard;
import java.util.LinkedList;
import android.content.Context;
import android.os.AsyncTask;
/**
* Base class for an in-memory dictionary that can grow dynamically and can
* be searched for suggestions and valid words.
*/
public class ExpandableDictionary extends Dictionary {
/**
* There is difference between what java and native code can handle.
* It uses 32 because Java stack overflows when greater value is used.
*/
protected static final int MAX_WORD_LENGTH = 32;
private Context mContext;
private char[] mWordBuilder = new char[MAX_WORD_LENGTH];
private int mDicTypeId;
private int mMaxDepth;
private int mInputLength;
private int[] mNextLettersFrequencies;
private StringBuilder sb = new StringBuilder(MAX_WORD_LENGTH);
private static final char QUOTE = '\'';
private boolean mRequiresReload;
private boolean mUpdatingDictionary;
// Use this lock before touching mUpdatingDictionary & mRequiresDownload
private Object mUpdatingLock = new Object();
static class Node {
char code;
int frequency;
boolean terminal;
Node parent;
NodeArray children;
LinkedList<NextWord> ngrams; // Supports ngram
}
static class NodeArray {
Node[] data;
int length = 0;
private static final int INCREMENT = 2;
NodeArray() {
data = new Node[INCREMENT];
}
void add(Node n) {
if (length + 1 > data.length) {
Node[] tempData = new Node[length + INCREMENT];
if (length > 0) {
System.arraycopy(data, 0, tempData, 0, length);
}
data = tempData;
}
data[length++] = n;
}
}
static class NextWord {
Node word;
NextWord nextWord;
int frequency;
NextWord(Node word, int frequency) {
this.word = word;
this.frequency = frequency;
}
}
private NodeArray mRoots;
private int[][] mCodes;
ExpandableDictionary(Context context, int dicTypeId) {
mContext = context;
clearDictionary();
mCodes = new int[MAX_WORD_LENGTH][];
mDicTypeId = dicTypeId;
}
public void loadDictionary() {
synchronized (mUpdatingLock) {
startDictionaryLoadingTaskLocked();
}
}
public void startDictionaryLoadingTaskLocked() {
if (!mUpdatingDictionary) {
mUpdatingDictionary = true;
mRequiresReload = false;
new LoadDictionaryTask().execute();
}
}
public void setRequiresReload(boolean reload) {
synchronized (mUpdatingLock) {
mRequiresReload = reload;
}
}
public boolean getRequiresReload() {
return mRequiresReload;
}
/** Override to load your dictionary here, on a background thread. */
public void loadDictionaryAsync() {
}
Context getContext() {
return mContext;
}
int getMaxWordLength() {
return MAX_WORD_LENGTH;
}
public void addWord(String word, int frequency) {
addWordRec(mRoots, word, 0, frequency, null);
}
private void addWordRec(NodeArray children, final String word, final int depth,
final int frequency, Node parentNode) {
final int wordLength = word.length();
final char c = word.charAt(depth);
// Does children have the current character?
final int childrenLength = children.length;
Node childNode = null;
boolean found = false;
for (int i = 0; i < childrenLength; i++) {
childNode = children.data[i];
if (childNode.code == c) {
found = true;
break;
}
}
if (!found) {
childNode = new Node();
childNode.code = c;
childNode.parent = parentNode;
children.add(childNode);
}
if (wordLength == depth + 1) {
// Terminate this word
childNode.terminal = true;
childNode.frequency = Math.max(frequency, childNode.frequency);
if (childNode.frequency > 255) childNode.frequency = 255;
return;
}
if (childNode.children == null) {
childNode.children = new NodeArray();
}
addWordRec(childNode.children, word, depth + 1, frequency, childNode);
}
@Override
public void getWords(final WordComposer codes, final WordCallback callback,
int[] nextLettersFrequencies) {
synchronized (mUpdatingLock) {
// If we need to update, start off a background task
if (mRequiresReload) startDictionaryLoadingTaskLocked();
// Currently updating contacts, don't return any results.
if (mUpdatingDictionary) return;
}
mInputLength = codes.size();
mNextLettersFrequencies = nextLettersFrequencies;
if (mCodes.length < mInputLength) mCodes = new int[mInputLength][];
// Cache the codes so that we don't have to lookup an array list
for (int i = 0; i < mInputLength; i++) {
mCodes[i] = codes.getCodesAt(i);
}
mMaxDepth = mInputLength * 3;
getWordsRec(mRoots, codes, mWordBuilder, 0, false, 1, 0, -1, callback);
for (int i = 0; i < mInputLength; i++) {
getWordsRec(mRoots, codes, mWordBuilder, 0, false, 1, 0, i, callback);
}
}
@Override
public synchronized boolean isValidWord(CharSequence word) {
synchronized (mUpdatingLock) {
// If we need to update, start off a background task
if (mRequiresReload) startDictionaryLoadingTaskLocked();
if (mUpdatingDictionary) return false;
}
final int freq = getWordFrequency(word);
return freq > -1;
}
/**
* Returns the word's frequency or -1 if not found
*/
public int getWordFrequency(CharSequence word) {
Node node = searchNode(mRoots, word, 0, word.length());
return (node == null) ? -1 : node.frequency;
}
/**
* Recursively traverse the tree for words that match the input. Input consists of
* a list of arrays. Each item in the list is one input character position. An input
* character is actually an array of multiple possible candidates. This function is not
* optimized for speed, assuming that the user dictionary will only be a few hundred words in
* size.
* @param roots node whose children have to be search for matches
* @param codes the input character codes
* @param word the word being composed as a possible match
* @param depth the depth of traversal - the length of the word being composed thus far
* @param completion whether the traversal is now in completion mode - meaning that we've
* exhausted the input and we're looking for all possible suffixes.
* @param snr current weight of the word being formed
* @param inputIndex position in the input characters. This can be off from the depth in
* case we skip over some punctuations such as apostrophe in the traversal. That is, if you type
* "wouldve", it could be matching "would've", so the depth will be one more than the
* inputIndex
* @param callback the callback class for adding a word
*/
protected void getWordsRec(NodeArray roots, final WordComposer codes, final char[] word,
final int depth, boolean completion, int snr, int inputIndex, int skipPos,
WordCallback callback) {
final int count = roots.length;
final int codeSize = mInputLength;
// Optimization: Prune out words that are too long compared to how much was typed.
if (depth > mMaxDepth) {
return;
}
int[] currentChars = null;
if (codeSize <= inputIndex) {
completion = true;
} else {
currentChars = mCodes[inputIndex];
}
for (int i = 0; i < count; i++) {
final Node node = roots.data[i];
final char c = node.code;
final char lowerC = toLowerCase(c);
final boolean terminal = node.terminal;
final NodeArray children = node.children;
final int freq = node.frequency;
if (completion) {
word[depth] = c;
if (terminal) {
if (!callback.addWord(word, 0, depth + 1, freq * snr, mDicTypeId,
DataType.UNIGRAM)) {
return;
}
// Add to frequency of next letters for predictive correction
if (mNextLettersFrequencies != null && depth >= inputIndex && skipPos < 0
&& mNextLettersFrequencies.length > word[inputIndex]) {
mNextLettersFrequencies[word[inputIndex]]++;
}
}
if (children != null) {
getWordsRec(children, codes, word, depth + 1, completion, snr, inputIndex,
skipPos, callback);
}
} else if ((c == QUOTE && currentChars[0] != QUOTE) || depth == skipPos) {
// Skip the ' and continue deeper
word[depth] = c;
if (children != null) {
getWordsRec(children, codes, word, depth + 1, completion, snr, inputIndex,
skipPos, callback);
}
} else {
// Don't use alternatives if we're looking for missing characters
final int alternativesSize = skipPos >= 0? 1 : currentChars.length;
for (int j = 0; j < alternativesSize; j++) {
final int addedAttenuation = (j > 0 ? 1 : 2);
final int currentChar = currentChars[j];
if (currentChar == -1) {
break;
}
if (currentChar == lowerC || currentChar == c) {
word[depth] = c;
if (codeSize == inputIndex + 1) {
if (terminal) {
if (INCLUDE_TYPED_WORD_IF_VALID
|| !same(word, depth + 1, codes.getTypedWord())) {
int finalFreq = freq * snr * addedAttenuation;
if (skipPos < 0) finalFreq *= FULL_WORD_FREQ_MULTIPLIER;
callback.addWord(word, 0, depth + 1, finalFreq, mDicTypeId,
DataType.UNIGRAM);
}
}
if (children != null) {
getWordsRec(children, codes, word, depth + 1,
true, snr * addedAttenuation, inputIndex + 1,
skipPos, callback);
}
} else if (children != null) {
getWordsRec(children, codes, word, depth + 1,
false, snr * addedAttenuation, inputIndex + 1,
skipPos, callback);
}
}
}
}
}
}
protected int setBigram(String word1, String word2, int frequency) {
return addOrSetBigram(word1, word2, frequency, false);
}
protected int addBigram(String word1, String word2, int frequency) {
return addOrSetBigram(word1, word2, frequency, true);
}
/**
* Adds bigrams to the in-memory trie structure that is being used to retrieve any word
* @param frequency frequency for this bigrams
* @param addFrequency if true, it adds to current frequency
* @return returns the final frequency
*/
private int addOrSetBigram(String word1, String word2, int frequency, boolean addFrequency) {
Node firstWord = searchWord(mRoots, word1, 0, null);
Node secondWord = searchWord(mRoots, word2, 0, null);
LinkedList<NextWord> bigram = firstWord.ngrams;
if (bigram == null || bigram.size() == 0) {
firstWord.ngrams = new LinkedList<NextWord>();
bigram = firstWord.ngrams;
} else {
for (NextWord nw : bigram) {
if (nw.word == secondWord) {
if (addFrequency) {
nw.frequency += frequency;
} else {
nw.frequency = frequency;
}
return nw.frequency;
}
}
}
NextWord nw = new NextWord(secondWord, frequency);
firstWord.ngrams.add(nw);
return frequency;
}
/**
* Searches for the word and add the word if it does not exist.
* @return Returns the terminal node of the word we are searching for.
*/
private Node searchWord(NodeArray children, String word, int depth, Node parentNode) {
final int wordLength = word.length();
final char c = word.charAt(depth);
// Does children have the current character?
final int childrenLength = children.length;
Node childNode = null;
boolean found = false;
for (int i = 0; i < childrenLength; i++) {
childNode = children.data[i];
if (childNode.code == c) {
found = true;
break;
}
}
if (!found) {
childNode = new Node();
childNode.code = c;
childNode.parent = parentNode;
children.add(childNode);
}
if (wordLength == depth + 1) {
// Terminate this word
childNode.terminal = true;
return childNode;
}
if (childNode.children == null) {
childNode.children = new NodeArray();
}
return searchWord(childNode.children, word, depth + 1, childNode);
}
// @VisibleForTesting
boolean reloadDictionaryIfRequired() {
synchronized (mUpdatingLock) {
// If we need to update, start off a background task
if (mRequiresReload) startDictionaryLoadingTaskLocked();
// Currently updating contacts, don't return any results.
return mUpdatingDictionary;
}
}
private void runReverseLookUp(final CharSequence previousWord, final WordCallback callback) {
Node prevWord = searchNode(mRoots, previousWord, 0, previousWord.length());
if (prevWord != null && prevWord.ngrams != null) {
reverseLookUp(prevWord.ngrams, callback);
}
}
@Override
public void getBigrams(final WordComposer codes, final CharSequence previousWord,
final WordCallback callback, int[] nextLettersFrequencies) {
if (!reloadDictionaryIfRequired()) {
runReverseLookUp(previousWord, callback);
}
}
/**
* Used only for testing purposes
* This function will wait for loading from database to be done
*/
void waitForDictionaryLoading() {
while (mUpdatingDictionary) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
}
}
/**
* reverseLookUp retrieves the full word given a list of terminal nodes and adds those words
* through callback.
* @param terminalNodes list of terminal nodes we want to add
*/
private void reverseLookUp(LinkedList<NextWord> terminalNodes,
final WordCallback callback) {
Node node;
int freq;
for (NextWord nextWord : terminalNodes) {
node = nextWord.word;
freq = nextWord.frequency;
// TODO Not the best way to limit suggestion threshold
if (freq >= UserBigramDictionary.SUGGEST_THRESHOLD) {
sb.setLength(0);
do {
sb.insert(0, node.code);
node = node.parent;
} while(node != null);
// TODO better way to feed char array?
callback.addWord(sb.toString().toCharArray(), 0, sb.length(), freq, mDicTypeId,
DataType.BIGRAM);
}
}
}
/**
* Search for the terminal node of the word
* @return Returns the terminal node of the word if the word exists
*/
private Node searchNode(final NodeArray children, final CharSequence word, final int offset,
final int length) {
// TODO Consider combining with addWordRec
final int count = children.length;
char currentChar = word.charAt(offset);
for (int j = 0; j < count; j++) {
final Node node = children.data[j];
if (node.code == currentChar) {
if (offset == length - 1) {
if (node.terminal) {
return node;
}
} else {
if (node.children != null) {
Node returnNode = searchNode(node.children, word, offset + 1, length);
if (returnNode != null) return returnNode;
}
}
}
}
return null;
}
protected void clearDictionary() {
mRoots = new NodeArray();
}
private class LoadDictionaryTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... v) {
loadDictionaryAsync();
synchronized (mUpdatingLock) {
mUpdatingDictionary = false;
}
return null;
}
}
static char toLowerCase(char c) {
if (c < BASE_CHARS.length) {
c = BASE_CHARS[c];
}
if (c >= 'A' && c <= 'Z') {
c = (char) (c | 32);
} else if (c > 127) {
c = Character.toLowerCase(c);
}
return c;
}
/**
* Table mapping most combined Latin, Greek, and Cyrillic characters
* to their base characters. If c is in range, BASE_CHARS[c] == c
* if c is not a combined character, or the base character if it
* is combined.
*/
static final char BASE_CHARS[] = {
0x0000, 0x0001, 0x0002, 0x0003, 0x0004, 0x0005, 0x0006, 0x0007,
0x0008, 0x0009, 0x000a, 0x000b, 0x000c, 0x000d, 0x000e, 0x000f,
0x0010, 0x0011, 0x0012, 0x0013, 0x0014, 0x0015, 0x0016, 0x0017,
0x0018, 0x0019, 0x001a, 0x001b, 0x001c, 0x001d, 0x001e, 0x001f,
0x0020, 0x0021, 0x0022, 0x0023, 0x0024, 0x0025, 0x0026, 0x0027,
0x0028, 0x0029, 0x002a, 0x002b, 0x002c, 0x002d, 0x002e, 0x002f,
0x0030, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, 0x0036, 0x0037,
0x0038, 0x0039, 0x003a, 0x003b, 0x003c, 0x003d, 0x003e, 0x003f,
0x0040, 0x0041, 0x0042, 0x0043, 0x0044, 0x0045, 0x0046, 0x0047,
0x0048, 0x0049, 0x004a, 0x004b, 0x004c, 0x004d, 0x004e, 0x004f,
0x0050, 0x0051, 0x0052, 0x0053, 0x0054, 0x0055, 0x0056, 0x0057,
0x0058, 0x0059, 0x005a, 0x005b, 0x005c, 0x005d, 0x005e, 0x005f,
0x0060, 0x0061, 0x0062, 0x0063, 0x0064, 0x0065, 0x0066, 0x0067,
0x0068, 0x0069, 0x006a, 0x006b, 0x006c, 0x006d, 0x006e, 0x006f,
0x0070, 0x0071, 0x0072, 0x0073, 0x0074, 0x0075, 0x0076, 0x0077,
0x0078, 0x0079, 0x007a, 0x007b, 0x007c, 0x007d, 0x007e, 0x007f,
0x0080, 0x0081, 0x0082, 0x0083, 0x0084, 0x0085, 0x0086, 0x0087,
0x0088, 0x0089, 0x008a, 0x008b, 0x008c, 0x008d, 0x008e, 0x008f,
0x0090, 0x0091, 0x0092, 0x0093, 0x0094, 0x0095, 0x0096, 0x0097,
0x0098, 0x0099, 0x009a, 0x009b, 0x009c, 0x009d, 0x009e, 0x009f,
0x0020, 0x00a1, 0x00a2, 0x00a3, 0x00a4, 0x00a5, 0x00a6, 0x00a7,
0x0020, 0x00a9, 0x0061, 0x00ab, 0x00ac, 0x00ad, 0x00ae, 0x0020,
0x00b0, 0x00b1, 0x0032, 0x0033, 0x0020, 0x03bc, 0x00b6, 0x00b7,
0x0020, 0x0031, 0x006f, 0x00bb, 0x0031, 0x0031, 0x0033, 0x00bf,
0x0041, 0x0041, 0x0041, 0x0041, 0x0041, 0x0041, 0x00c6, 0x0043,
0x0045, 0x0045, 0x0045, 0x0045, 0x0049, 0x0049, 0x0049, 0x0049,
0x00d0, 0x004e, 0x004f, 0x004f, 0x004f, 0x004f, 0x004f, 0x00d7,
0x004f, 0x0055, 0x0055, 0x0055, 0x0055, 0x0059, 0x00de, 0x0073, // Manually changed d8 to 4f
// Manually changed df to 73
0x0061, 0x0061, 0x0061, 0x0061, 0x0061, 0x0061, 0x00e6, 0x0063,
0x0065, 0x0065, 0x0065, 0x0065, 0x0069, 0x0069, 0x0069, 0x0069,
0x00f0, 0x006e, 0x006f, 0x006f, 0x006f, 0x006f, 0x006f, 0x00f7,
0x006f, 0x0075, 0x0075, 0x0075, 0x0075, 0x0079, 0x00fe, 0x0079, // Manually changed f8 to 6f
0x0041, 0x0061, 0x0041, 0x0061, 0x0041, 0x0061, 0x0043, 0x0063,
0x0043, 0x0063, 0x0043, 0x0063, 0x0043, 0x0063, 0x0044, 0x0064,
0x0110, 0x0111, 0x0045, 0x0065, 0x0045, 0x0065, 0x0045, 0x0065,
0x0045, 0x0065, 0x0045, 0x0065, 0x0047, 0x0067, 0x0047, 0x0067,
0x0047, 0x0067, 0x0047, 0x0067, 0x0048, 0x0068, 0x0126, 0x0127,
0x0049, 0x0069, 0x0049, 0x0069, 0x0049, 0x0069, 0x0049, 0x0069,
0x0049, 0x0131, 0x0049, 0x0069, 0x004a, 0x006a, 0x004b, 0x006b,
0x0138, 0x004c, 0x006c, 0x004c, 0x006c, 0x004c, 0x006c, 0x004c,
0x006c, 0x0141, 0x0142, 0x004e, 0x006e, 0x004e, 0x006e, 0x004e,
0x006e, 0x02bc, 0x014a, 0x014b, 0x004f, 0x006f, 0x004f, 0x006f,
0x004f, 0x006f, 0x0152, 0x0153, 0x0052, 0x0072, 0x0052, 0x0072,
0x0052, 0x0072, 0x0053, 0x0073, 0x0053, 0x0073, 0x0053, 0x0073,
0x0053, 0x0073, 0x0054, 0x0074, 0x0054, 0x0074, 0x0166, 0x0167,
0x0055, 0x0075, 0x0055, 0x0075, 0x0055, 0x0075, 0x0055, 0x0075,
0x0055, 0x0075, 0x0055, 0x0075, 0x0057, 0x0077, 0x0059, 0x0079,
0x0059, 0x005a, 0x007a, 0x005a, 0x007a, 0x005a, 0x007a, 0x0073,
0x0180, 0x0181, 0x0182, 0x0183, 0x0184, 0x0185, 0x0186, 0x0187,
0x0188, 0x0189, 0x018a, 0x018b, 0x018c, 0x018d, 0x018e, 0x018f,
0x0190, 0x0191, 0x0192, 0x0193, 0x0194, 0x0195, 0x0196, 0x0197,
0x0198, 0x0199, 0x019a, 0x019b, 0x019c, 0x019d, 0x019e, 0x019f,
0x004f, 0x006f, 0x01a2, 0x01a3, 0x01a4, 0x01a5, 0x01a6, 0x01a7,
0x01a8, 0x01a9, 0x01aa, 0x01ab, 0x01ac, 0x01ad, 0x01ae, 0x0055,
0x0075, 0x01b1, 0x01b2, 0x01b3, 0x01b4, 0x01b5, 0x01b6, 0x01b7,
0x01b8, 0x01b9, 0x01ba, 0x01bb, 0x01bc, 0x01bd, 0x01be, 0x01bf,
0x01c0, 0x01c1, 0x01c2, 0x01c3, 0x0044, 0x0044, 0x0064, 0x004c,
0x004c, 0x006c, 0x004e, 0x004e, 0x006e, 0x0041, 0x0061, 0x0049,
0x0069, 0x004f, 0x006f, 0x0055, 0x0075, 0x00dc, 0x00fc, 0x00dc,
0x00fc, 0x00dc, 0x00fc, 0x00dc, 0x00fc, 0x01dd, 0x00c4, 0x00e4,
0x0226, 0x0227, 0x00c6, 0x00e6, 0x01e4, 0x01e5, 0x0047, 0x0067,
0x004b, 0x006b, 0x004f, 0x006f, 0x01ea, 0x01eb, 0x01b7, 0x0292,
0x006a, 0x0044, 0x0044, 0x0064, 0x0047, 0x0067, 0x01f6, 0x01f7,
0x004e, 0x006e, 0x00c5, 0x00e5, 0x00c6, 0x00e6, 0x00d8, 0x00f8,
0x0041, 0x0061, 0x0041, 0x0061, 0x0045, 0x0065, 0x0045, 0x0065,
0x0049, 0x0069, 0x0049, 0x0069, 0x004f, 0x006f, 0x004f, 0x006f,
0x0052, 0x0072, 0x0052, 0x0072, 0x0055, 0x0075, 0x0055, 0x0075,
0x0053, 0x0073, 0x0054, 0x0074, 0x021c, 0x021d, 0x0048, 0x0068,
0x0220, 0x0221, 0x0222, 0x0223, 0x0224, 0x0225, 0x0041, 0x0061,
0x0045, 0x0065, 0x00d6, 0x00f6, 0x00d5, 0x00f5, 0x004f, 0x006f,
0x022e, 0x022f, 0x0059, 0x0079, 0x0234, 0x0235, 0x0236, 0x0237,
0x0238, 0x0239, 0x023a, 0x023b, 0x023c, 0x023d, 0x023e, 0x023f,
0x0240, 0x0241, 0x0242, 0x0243, 0x0244, 0x0245, 0x0246, 0x0247,
0x0248, 0x0249, 0x024a, 0x024b, 0x024c, 0x024d, 0x024e, 0x024f,
0x0250, 0x0251, 0x0252, 0x0253, 0x0254, 0x0255, 0x0256, 0x0257,
0x0258, 0x0259, 0x025a, 0x025b, 0x025c, 0x025d, 0x025e, 0x025f,
0x0260, 0x0261, 0x0262, 0x0263, 0x0264, 0x0265, 0x0266, 0x0267,
0x0268, 0x0269, 0x026a, 0x026b, 0x026c, 0x026d, 0x026e, 0x026f,
0x0270, 0x0271, 0x0272, 0x0273, 0x0274, 0x0275, 0x0276, 0x0277,
0x0278, 0x0279, 0x027a, 0x027b, 0x027c, 0x027d, 0x027e, 0x027f,
0x0280, 0x0281, 0x0282, 0x0283, 0x0284, 0x0285, 0x0286, 0x0287,
0x0288, 0x0289, 0x028a, 0x028b, 0x028c, 0x028d, 0x028e, 0x028f,
0x0290, 0x0291, 0x0292, 0x0293, 0x0294, 0x0295, 0x0296, 0x0297,
0x0298, 0x0299, 0x029a, 0x029b, 0x029c, 0x029d, 0x029e, 0x029f,
0x02a0, 0x02a1, 0x02a2, 0x02a3, 0x02a4, 0x02a5, 0x02a6, 0x02a7,
0x02a8, 0x02a9, 0x02aa, 0x02ab, 0x02ac, 0x02ad, 0x02ae, 0x02af,
0x0068, 0x0266, 0x006a, 0x0072, 0x0279, 0x027b, 0x0281, 0x0077,
0x0079, 0x02b9, 0x02ba, 0x02bb, 0x02bc, 0x02bd, 0x02be, 0x02bf,
0x02c0, 0x02c1, 0x02c2, 0x02c3, 0x02c4, 0x02c5, 0x02c6, 0x02c7,
0x02c8, 0x02c9, 0x02ca, 0x02cb, 0x02cc, 0x02cd, 0x02ce, 0x02cf,
0x02d0, 0x02d1, 0x02d2, 0x02d3, 0x02d4, 0x02d5, 0x02d6, 0x02d7,
0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x02de, 0x02df,
0x0263, 0x006c, 0x0073, 0x0078, 0x0295, 0x02e5, 0x02e6, 0x02e7,
0x02e8, 0x02e9, 0x02ea, 0x02eb, 0x02ec, 0x02ed, 0x02ee, 0x02ef,
0x02f0, 0x02f1, 0x02f2, 0x02f3, 0x02f4, 0x02f5, 0x02f6, 0x02f7,
0x02f8, 0x02f9, 0x02fa, 0x02fb, 0x02fc, 0x02fd, 0x02fe, 0x02ff,
0x0300, 0x0301, 0x0302, 0x0303, 0x0304, 0x0305, 0x0306, 0x0307,
0x0308, 0x0309, 0x030a, 0x030b, 0x030c, 0x030d, 0x030e, 0x030f,
0x0310, 0x0311, 0x0312, 0x0313, 0x0314, 0x0315, 0x0316, 0x0317,
0x0318, 0x0319, 0x031a, 0x031b, 0x031c, 0x031d, 0x031e, 0x031f,
0x0320, 0x0321, 0x0322, 0x0323, 0x0324, 0x0325, 0x0326, 0x0327,
0x0328, 0x0329, 0x032a, 0x032b, 0x032c, 0x032d, 0x032e, 0x032f,
0x0330, 0x0331, 0x0332, 0x0333, 0x0334, 0x0335, 0x0336, 0x0337,
0x0338, 0x0339, 0x033a, 0x033b, 0x033c, 0x033d, 0x033e, 0x033f,
0x0300, 0x0301, 0x0342, 0x0313, 0x0308, 0x0345, 0x0346, 0x0347,
0x0348, 0x0349, 0x034a, 0x034b, 0x034c, 0x034d, 0x034e, 0x034f,
0x0350, 0x0351, 0x0352, 0x0353, 0x0354, 0x0355, 0x0356, 0x0357,
0x0358, 0x0359, 0x035a, 0x035b, 0x035c, 0x035d, 0x035e, 0x035f,
0x0360, 0x0361, 0x0362, 0x0363, 0x0364, 0x0365, 0x0366, 0x0367,
0x0368, 0x0369, 0x036a, 0x036b, 0x036c, 0x036d, 0x036e, 0x036f,
0x0370, 0x0371, 0x0372, 0x0373, 0x02b9, 0x0375, 0x0376, 0x0377,
0x0378, 0x0379, 0x0020, 0x037b, 0x037c, 0x037d, 0x003b, 0x037f,
0x0380, 0x0381, 0x0382, 0x0383, 0x0020, 0x00a8, 0x0391, 0x00b7,
0x0395, 0x0397, 0x0399, 0x038b, 0x039f, 0x038d, 0x03a5, 0x03a9,
0x03ca, 0x0391, 0x0392, 0x0393, 0x0394, 0x0395, 0x0396, 0x0397,
0x0398, 0x0399, 0x039a, 0x039b, 0x039c, 0x039d, 0x039e, 0x039f,
0x03a0, 0x03a1, 0x03a2, 0x03a3, 0x03a4, 0x03a5, 0x03a6, 0x03a7,
0x03a8, 0x03a9, 0x0399, 0x03a5, 0x03b1, 0x03b5, 0x03b7, 0x03b9,
0x03cb, 0x03b1, 0x03b2, 0x03b3, 0x03b4, 0x03b5, 0x03b6, 0x03b7,
0x03b8, 0x03b9, 0x03ba, 0x03bb, 0x03bc, 0x03bd, 0x03be, 0x03bf,
0x03c0, 0x03c1, 0x03c2, 0x03c3, 0x03c4, 0x03c5, 0x03c6, 0x03c7,
0x03c8, 0x03c9, 0x03b9, 0x03c5, 0x03bf, 0x03c5, 0x03c9, 0x03cf,
0x03b2, 0x03b8, 0x03a5, 0x03d2, 0x03d2, 0x03c6, 0x03c0, 0x03d7,
0x03d8, 0x03d9, 0x03da, 0x03db, 0x03dc, 0x03dd, 0x03de, 0x03df,
0x03e0, 0x03e1, 0x03e2, 0x03e3, 0x03e4, 0x03e5, 0x03e6, 0x03e7,
0x03e8, 0x03e9, 0x03ea, 0x03eb, 0x03ec, 0x03ed, 0x03ee, 0x03ef,
0x03ba, 0x03c1, 0x03c2, 0x03f3, 0x0398, 0x03b5, 0x03f6, 0x03f7,
0x03f8, 0x03a3, 0x03fa, 0x03fb, 0x03fc, 0x03fd, 0x03fe, 0x03ff,
0x0415, 0x0415, 0x0402, 0x0413, 0x0404, 0x0405, 0x0406, 0x0406,
0x0408, 0x0409, 0x040a, 0x040b, 0x041a, 0x0418, 0x0423, 0x040f,
0x0410, 0x0411, 0x0412, 0x0413, 0x0414, 0x0415, 0x0416, 0x0417,
0x0418, 0x0418, 0x041a, 0x041b, 0x041c, 0x041d, 0x041e, 0x041f,
0x0420, 0x0421, 0x0422, 0x0423, 0x0424, 0x0425, 0x0426, 0x0427,
0x0428, 0x0429, 0x042a, 0x042b, 0x042c, 0x042d, 0x042e, 0x042f,
0x0430, 0x0431, 0x0432, 0x0433, 0x0434, 0x0435, 0x0436, 0x0437,
0x0438, 0x0438, 0x043a, 0x043b, 0x043c, 0x043d, 0x043e, 0x043f,
0x0440, 0x0441, 0x0442, 0x0443, 0x0444, 0x0445, 0x0446, 0x0447,
0x0448, 0x0449, 0x044a, 0x044b, 0x044c, 0x044d, 0x044e, 0x044f,
0x0435, 0x0435, 0x0452, 0x0433, 0x0454, 0x0455, 0x0456, 0x0456,
0x0458, 0x0459, 0x045a, 0x045b, 0x043a, 0x0438, 0x0443, 0x045f,
0x0460, 0x0461, 0x0462, 0x0463, 0x0464, 0x0465, 0x0466, 0x0467,
0x0468, 0x0469, 0x046a, 0x046b, 0x046c, 0x046d, 0x046e, 0x046f,
0x0470, 0x0471, 0x0472, 0x0473, 0x0474, 0x0475, 0x0474, 0x0475,
0x0478, 0x0479, 0x047a, 0x047b, 0x047c, 0x047d, 0x047e, 0x047f,
0x0480, 0x0481, 0x0482, 0x0483, 0x0484, 0x0485, 0x0486, 0x0487,
0x0488, 0x0489, 0x048a, 0x048b, 0x048c, 0x048d, 0x048e, 0x048f,
0x0490, 0x0491, 0x0492, 0x0493, 0x0494, 0x0495, 0x0496, 0x0497,
0x0498, 0x0499, 0x049a, 0x049b, 0x049c, 0x049d, 0x049e, 0x049f,
0x04a0, 0x04a1, 0x04a2, 0x04a3, 0x04a4, 0x04a5, 0x04a6, 0x04a7,
0x04a8, 0x04a9, 0x04aa, 0x04ab, 0x04ac, 0x04ad, 0x04ae, 0x04af,
0x04b0, 0x04b1, 0x04b2, 0x04b3, 0x04b4, 0x04b5, 0x04b6, 0x04b7,
0x04b8, 0x04b9, 0x04ba, 0x04bb, 0x04bc, 0x04bd, 0x04be, 0x04bf,
0x04c0, 0x0416, 0x0436, 0x04c3, 0x04c4, 0x04c5, 0x04c6, 0x04c7,
0x04c8, 0x04c9, 0x04ca, 0x04cb, 0x04cc, 0x04cd, 0x04ce, 0x04cf,
0x0410, 0x0430, 0x0410, 0x0430, 0x04d4, 0x04d5, 0x0415, 0x0435,
0x04d8, 0x04d9, 0x04d8, 0x04d9, 0x0416, 0x0436, 0x0417, 0x0437,
0x04e0, 0x04e1, 0x0418, 0x0438, 0x0418, 0x0438, 0x041e, 0x043e,
0x04e8, 0x04e9, 0x04e8, 0x04e9, 0x042d, 0x044d, 0x0423, 0x0443,
0x0423, 0x0443, 0x0423, 0x0443, 0x0427, 0x0447, 0x04f6, 0x04f7,
0x042b, 0x044b, 0x04fa, 0x04fb, 0x04fc, 0x04fd, 0x04fe, 0x04ff,
};
// generated with:
// cat UnicodeData.txt | perl -e 'while (<>) { @foo = split(/;/); $foo[5] =~ s/<.*> //; $base[hex($foo[0])] = hex($foo[5]);} for ($i = 0; $i < 0x500; $i += 8) { for ($j = $i; $j < $i + 8; $j++) { printf("0x%04x, ", $base[$j] ? $base[$j] : $j)}; print "\n"; }'
}
| 11beeaosama-descrbvbnvbniption | java/src/org/pocketworkstation/pckeyboard/ExpandableDictionary.java | Java | asf20 | 31,364 |
package org.pocketworkstation.pckeyboard;
import android.content.Context;
import android.preference.EditTextPreference;
import android.util.AttributeSet;
public class AutoSummaryEditTextPreference extends EditTextPreference {
public AutoSummaryEditTextPreference(Context context) {
super(context);
}
public AutoSummaryEditTextPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
public AutoSummaryEditTextPreference(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
}
@Override
public void setText(String text) {
super.setText(text);
setSummary(text);
}
}
| 11beeaosama-descrbvbnvbniption | java/src/org/pocketworkstation/pckeyboard/AutoSummaryEditTextPreference.java | Java | asf20 | 708 |
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import android.content.Context;
import android.text.AutoText;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
/**
* This class loads a dictionary and provides a list of suggestions for a given sequence of
* characters. This includes corrections and completions.
* @hide pending API Council Approval
*/
public class Suggest implements Dictionary.WordCallback {
private static String TAG = "PCKeyboard";
public static final int APPROX_MAX_WORD_LENGTH = 32;
public static final int CORRECTION_NONE = 0;
public static final int CORRECTION_BASIC = 1;
public static final int CORRECTION_FULL = 2;
public static final int CORRECTION_FULL_BIGRAM = 3;
/**
* Words that appear in both bigram and unigram data gets multiplier ranging from
* BIGRAM_MULTIPLIER_MIN to BIGRAM_MULTIPLIER_MAX depending on the frequency score from
* bigram data.
*/
public static final double BIGRAM_MULTIPLIER_MIN = 1.2;
public static final double BIGRAM_MULTIPLIER_MAX = 1.5;
/**
* Maximum possible bigram frequency. Will depend on how many bits are being used in data
* structure. Maximum bigram freqeuncy will get the BIGRAM_MULTIPLIER_MAX as the multiplier.
*/
public static final int MAXIMUM_BIGRAM_FREQUENCY = 127;
public static final int DIC_USER_TYPED = 0;
public static final int DIC_MAIN = 1;
public static final int DIC_USER = 2;
public static final int DIC_AUTO = 3;
public static final int DIC_CONTACTS = 4;
// If you add a type of dictionary, increment DIC_TYPE_LAST_ID
public static final int DIC_TYPE_LAST_ID = 4;
static final int LARGE_DICTIONARY_THRESHOLD = 200 * 1000;
private BinaryDictionary mMainDict;
private Dictionary mUserDictionary;
private Dictionary mAutoDictionary;
private Dictionary mContactsDictionary;
private Dictionary mUserBigramDictionary;
private int mPrefMaxSuggestions = 12;
private static final int PREF_MAX_BIGRAMS = 60;
private boolean mAutoTextEnabled;
private int[] mPriorities = new int[mPrefMaxSuggestions];
private int[] mBigramPriorities = new int[PREF_MAX_BIGRAMS];
// Handle predictive correction for only the first 1280 characters for performance reasons
// If we support scripts that need latin characters beyond that, we should probably use some
// kind of a sparse array or language specific list with a mapping lookup table.
// 1280 is the size of the BASE_CHARS array in ExpandableDictionary, which is a basic set of
// latin characters.
private int[] mNextLettersFrequencies = new int[1280];
private ArrayList<CharSequence> mSuggestions = new ArrayList<CharSequence>();
ArrayList<CharSequence> mBigramSuggestions = new ArrayList<CharSequence>();
private ArrayList<CharSequence> mStringPool = new ArrayList<CharSequence>();
private boolean mHaveCorrection;
private CharSequence mOriginalWord;
private String mLowerOriginalWord;
// TODO: Remove these member variables by passing more context to addWord() callback method
private boolean mIsFirstCharCapitalized;
private boolean mIsAllUpperCase;
private int mCorrectionMode = CORRECTION_BASIC;
public Suggest(Context context, int[] dictionaryResId) {
mMainDict = new BinaryDictionary(context, dictionaryResId, DIC_MAIN);
if (!hasMainDictionary()) {
Locale locale = context.getResources().getConfiguration().locale;
BinaryDictionary plug = PluginManager.getDictionary(context, locale.getLanguage());
if (plug != null) {
mMainDict.close();
mMainDict = plug;
}
}
initPool();
}
public Suggest(Context context, ByteBuffer byteBuffer) {
mMainDict = new BinaryDictionary(context, byteBuffer, DIC_MAIN);
initPool();
}
private void initPool() {
for (int i = 0; i < mPrefMaxSuggestions; i++) {
StringBuilder sb = new StringBuilder(getApproxMaxWordLength());
mStringPool.add(sb);
}
}
public void setAutoTextEnabled(boolean enabled) {
mAutoTextEnabled = enabled;
}
public int getCorrectionMode() {
return mCorrectionMode;
}
public void setCorrectionMode(int mode) {
mCorrectionMode = mode;
}
public boolean hasMainDictionary() {
return mMainDict.getSize() > LARGE_DICTIONARY_THRESHOLD;
}
public int getApproxMaxWordLength() {
return APPROX_MAX_WORD_LENGTH;
}
/**
* Sets an optional user dictionary resource to be loaded. The user dictionary is consulted
* before the main dictionary, if set.
*/
public void setUserDictionary(Dictionary userDictionary) {
mUserDictionary = userDictionary;
}
/**
* Sets an optional contacts dictionary resource to be loaded.
*/
public void setContactsDictionary(Dictionary userDictionary) {
mContactsDictionary = userDictionary;
}
public void setAutoDictionary(Dictionary autoDictionary) {
mAutoDictionary = autoDictionary;
}
public void setUserBigramDictionary(Dictionary userBigramDictionary) {
mUserBigramDictionary = userBigramDictionary;
}
/**
* Number of suggestions to generate from the input key sequence. This has
* to be a number between 1 and 100 (inclusive).
* @param maxSuggestions
* @throws IllegalArgumentException if the number is out of range
*/
public void setMaxSuggestions(int maxSuggestions) {
if (maxSuggestions < 1 || maxSuggestions > 100) {
throw new IllegalArgumentException("maxSuggestions must be between 1 and 100");
}
mPrefMaxSuggestions = maxSuggestions;
mPriorities = new int[mPrefMaxSuggestions];
mBigramPriorities = new int[PREF_MAX_BIGRAMS];
collectGarbage(mSuggestions, mPrefMaxSuggestions);
while (mStringPool.size() < mPrefMaxSuggestions) {
StringBuilder sb = new StringBuilder(getApproxMaxWordLength());
mStringPool.add(sb);
}
}
private boolean haveSufficientCommonality(String original, CharSequence suggestion) {
final int originalLength = original.length();
final int suggestionLength = suggestion.length();
final int minLength = Math.min(originalLength, suggestionLength);
if (minLength <= 2) return true;
int matching = 0;
int lessMatching = 0; // Count matches if we skip one character
int i;
for (i = 0; i < minLength; i++) {
final char origChar = ExpandableDictionary.toLowerCase(original.charAt(i));
if (origChar == ExpandableDictionary.toLowerCase(suggestion.charAt(i))) {
matching++;
lessMatching++;
} else if (i + 1 < suggestionLength
&& origChar == ExpandableDictionary.toLowerCase(suggestion.charAt(i + 1))) {
lessMatching++;
}
}
matching = Math.max(matching, lessMatching);
if (minLength <= 4) {
return matching >= 2;
} else {
return matching > minLength / 2;
}
}
/**
* Returns a list of words that match the list of character codes passed in.
* This list will be overwritten the next time this function is called.
* @param view a view for retrieving the context for AutoText
* @param wordComposer contains what is currently being typed
* @param prevWordForBigram previous word (used only for bigram)
* @return list of suggestions.
*/
public List<CharSequence> getSuggestions(View view, WordComposer wordComposer,
boolean includeTypedWordIfValid, CharSequence prevWordForBigram) {
LatinImeLogger.onStartSuggestion(prevWordForBigram);
mHaveCorrection = false;
mIsFirstCharCapitalized = wordComposer.isFirstCharCapitalized();
mIsAllUpperCase = wordComposer.isAllUpperCase();
collectGarbage(mSuggestions, mPrefMaxSuggestions);
Arrays.fill(mPriorities, 0);
Arrays.fill(mNextLettersFrequencies, 0);
// Save a lowercase version of the original word
mOriginalWord = wordComposer.getTypedWord();
if (mOriginalWord != null) {
final String mOriginalWordString = mOriginalWord.toString();
mOriginalWord = mOriginalWordString;
mLowerOriginalWord = mOriginalWordString.toLowerCase();
// Treating USER_TYPED as UNIGRAM suggestion for logging now.
LatinImeLogger.onAddSuggestedWord(mOriginalWordString, Suggest.DIC_USER_TYPED,
Dictionary.DataType.UNIGRAM);
} else {
mLowerOriginalWord = "";
}
if (wordComposer.size() == 1 && (mCorrectionMode == CORRECTION_FULL_BIGRAM
|| mCorrectionMode == CORRECTION_BASIC)) {
// At first character typed, search only the bigrams
Arrays.fill(mBigramPriorities, 0);
collectGarbage(mBigramSuggestions, PREF_MAX_BIGRAMS);
if (!TextUtils.isEmpty(prevWordForBigram)) {
CharSequence lowerPrevWord = prevWordForBigram.toString().toLowerCase();
if (mMainDict.isValidWord(lowerPrevWord)) {
prevWordForBigram = lowerPrevWord;
}
if (mUserBigramDictionary != null) {
mUserBigramDictionary.getBigrams(wordComposer, prevWordForBigram, this,
mNextLettersFrequencies);
}
if (mContactsDictionary != null) {
mContactsDictionary.getBigrams(wordComposer, prevWordForBigram, this,
mNextLettersFrequencies);
}
if (mMainDict != null) {
mMainDict.getBigrams(wordComposer, prevWordForBigram, this,
mNextLettersFrequencies);
}
char currentChar = wordComposer.getTypedWord().charAt(0);
char currentCharUpper = Character.toUpperCase(currentChar);
int count = 0;
int bigramSuggestionSize = mBigramSuggestions.size();
for (int i = 0; i < bigramSuggestionSize; i++) {
if (mBigramSuggestions.get(i).charAt(0) == currentChar
|| mBigramSuggestions.get(i).charAt(0) == currentCharUpper) {
int poolSize = mStringPool.size();
StringBuilder sb = poolSize > 0 ?
(StringBuilder) mStringPool.remove(poolSize - 1)
: new StringBuilder(getApproxMaxWordLength());
sb.setLength(0);
sb.append(mBigramSuggestions.get(i));
mSuggestions.add(count++, sb);
if (count > mPrefMaxSuggestions) break;
}
}
}
} else if (wordComposer.size() > 1) {
// At second character typed, search the unigrams (scores being affected by bigrams)
if (mUserDictionary != null || mContactsDictionary != null) {
if (mUserDictionary != null) {
mUserDictionary.getWords(wordComposer, this, mNextLettersFrequencies);
}
if (mContactsDictionary != null) {
mContactsDictionary.getWords(wordComposer, this, mNextLettersFrequencies);
}
if (mSuggestions.size() > 0 && isValidWord(mOriginalWord)
&& (mCorrectionMode == CORRECTION_FULL
|| mCorrectionMode == CORRECTION_FULL_BIGRAM)) {
mHaveCorrection = true;
}
}
mMainDict.getWords(wordComposer, this, mNextLettersFrequencies);
if ((mCorrectionMode == CORRECTION_FULL || mCorrectionMode == CORRECTION_FULL_BIGRAM)
&& mSuggestions.size() > 0) {
mHaveCorrection = true;
}
}
if (mOriginalWord != null) {
mSuggestions.add(0, mOriginalWord.toString());
}
// Check if the first suggestion has a minimum number of characters in common
if (wordComposer.size() > 1 && mSuggestions.size() > 1
&& (mCorrectionMode == CORRECTION_FULL
|| mCorrectionMode == CORRECTION_FULL_BIGRAM)) {
if (!haveSufficientCommonality(mLowerOriginalWord, mSuggestions.get(1))) {
mHaveCorrection = false;
}
}
if (mAutoTextEnabled) {
int i = 0;
int max = 6;
// Don't autotext the suggestions from the dictionaries
if (mCorrectionMode == CORRECTION_BASIC) max = 1;
while (i < mSuggestions.size() && i < max) {
String suggestedWord = mSuggestions.get(i).toString().toLowerCase();
CharSequence autoText =
AutoText.get(suggestedWord, 0, suggestedWord.length(), view);
// Is there an AutoText correction?
boolean canAdd = autoText != null;
// Is that correction already the current prediction (or original word)?
canAdd &= !TextUtils.equals(autoText, mSuggestions.get(i));
// Is that correction already the next predicted word?
if (canAdd && i + 1 < mSuggestions.size() && mCorrectionMode != CORRECTION_BASIC) {
canAdd &= !TextUtils.equals(autoText, mSuggestions.get(i + 1));
}
if (canAdd) {
mHaveCorrection = true;
mSuggestions.add(i + 1, autoText);
i++;
}
i++;
}
}
removeDupes();
return mSuggestions;
}
public int[] getNextLettersFrequencies() {
return mNextLettersFrequencies;
}
private void removeDupes() {
final ArrayList<CharSequence> suggestions = mSuggestions;
if (suggestions.size() < 2) return;
int i = 1;
// Don't cache suggestions.size(), since we may be removing items
while (i < suggestions.size()) {
final CharSequence cur = suggestions.get(i);
// Compare each candidate with each previous candidate
for (int j = 0; j < i; j++) {
CharSequence previous = suggestions.get(j);
if (TextUtils.equals(cur, previous)) {
removeFromSuggestions(i);
i--;
break;
}
}
i++;
}
}
private void removeFromSuggestions(int index) {
CharSequence garbage = mSuggestions.remove(index);
if (garbage != null && garbage instanceof StringBuilder) {
mStringPool.add(garbage);
}
}
public boolean hasMinimalCorrection() {
return mHaveCorrection;
}
private boolean compareCaseInsensitive(final String mLowerOriginalWord,
final char[] word, final int offset, final int length) {
final int originalLength = mLowerOriginalWord.length();
if (originalLength == length && Character.isUpperCase(word[offset])) {
for (int i = 0; i < originalLength; i++) {
if (mLowerOriginalWord.charAt(i) != Character.toLowerCase(word[offset+i])) {
return false;
}
}
return true;
}
return false;
}
public boolean addWord(final char[] word, final int offset, final int length, int freq,
final int dicTypeId, final Dictionary.DataType dataType) {
Dictionary.DataType dataTypeForLog = dataType;
ArrayList<CharSequence> suggestions;
int[] priorities;
int prefMaxSuggestions;
if(dataType == Dictionary.DataType.BIGRAM) {
suggestions = mBigramSuggestions;
priorities = mBigramPriorities;
prefMaxSuggestions = PREF_MAX_BIGRAMS;
} else {
suggestions = mSuggestions;
priorities = mPriorities;
prefMaxSuggestions = mPrefMaxSuggestions;
}
int pos = 0;
// Check if it's the same word, only caps are different
if (compareCaseInsensitive(mLowerOriginalWord, word, offset, length)) {
pos = 0;
} else {
if (dataType == Dictionary.DataType.UNIGRAM) {
// Check if the word was already added before (by bigram data)
int bigramSuggestion = searchBigramSuggestion(word,offset,length);
if(bigramSuggestion >= 0) {
dataTypeForLog = Dictionary.DataType.BIGRAM;
// turn freq from bigram into multiplier specified above
double multiplier = (((double) mBigramPriorities[bigramSuggestion])
/ MAXIMUM_BIGRAM_FREQUENCY)
* (BIGRAM_MULTIPLIER_MAX - BIGRAM_MULTIPLIER_MIN)
+ BIGRAM_MULTIPLIER_MIN;
/* Log.d(TAG,"bigram num: " + bigramSuggestion
+ " wordB: " + mBigramSuggestions.get(bigramSuggestion).toString()
+ " currentPriority: " + freq + " bigramPriority: "
+ mBigramPriorities[bigramSuggestion]
+ " multiplier: " + multiplier); */
freq = (int)Math.round((freq * multiplier));
}
}
// Check the last one's priority and bail
if (priorities[prefMaxSuggestions - 1] >= freq) return true;
while (pos < prefMaxSuggestions) {
if (priorities[pos] < freq
|| (priorities[pos] == freq && length < suggestions.get(pos).length())) {
break;
}
pos++;
}
}
if (pos >= prefMaxSuggestions) {
return true;
}
System.arraycopy(priorities, pos, priorities, pos + 1,
prefMaxSuggestions - pos - 1);
priorities[pos] = freq;
int poolSize = mStringPool.size();
StringBuilder sb = poolSize > 0 ? (StringBuilder) mStringPool.remove(poolSize - 1)
: new StringBuilder(getApproxMaxWordLength());
sb.setLength(0);
if (mIsAllUpperCase) {
sb.append(new String(word, offset, length).toUpperCase());
} else if (mIsFirstCharCapitalized) {
sb.append(Character.toUpperCase(word[offset]));
if (length > 1) {
sb.append(word, offset + 1, length - 1);
}
} else {
sb.append(word, offset, length);
}
suggestions.add(pos, sb);
if (suggestions.size() > prefMaxSuggestions) {
CharSequence garbage = suggestions.remove(prefMaxSuggestions);
if (garbage instanceof StringBuilder) {
mStringPool.add(garbage);
}
} else {
LatinImeLogger.onAddSuggestedWord(sb.toString(), dicTypeId, dataTypeForLog);
}
return true;
}
private int searchBigramSuggestion(final char[] word, final int offset, final int length) {
// TODO This is almost O(n^2). Might need fix.
// search whether the word appeared in bigram data
int bigramSuggestSize = mBigramSuggestions.size();
for(int i = 0; i < bigramSuggestSize; i++) {
if(mBigramSuggestions.get(i).length() == length) {
boolean chk = true;
for(int j = 0; j < length; j++) {
if(mBigramSuggestions.get(i).charAt(j) != word[offset+j]) {
chk = false;
break;
}
}
if(chk) return i;
}
}
return -1;
}
public boolean isValidWord(final CharSequence word) {
if (word == null || word.length() == 0) {
return false;
}
return mMainDict.isValidWord(word)
|| (mUserDictionary != null && mUserDictionary.isValidWord(word))
|| (mAutoDictionary != null && mAutoDictionary.isValidWord(word))
|| (mContactsDictionary != null && mContactsDictionary.isValidWord(word));
}
private void collectGarbage(ArrayList<CharSequence> suggestions, int prefMaxSuggestions) {
int poolSize = mStringPool.size();
int garbageSize = suggestions.size();
while (poolSize < prefMaxSuggestions && garbageSize > 0) {
CharSequence garbage = suggestions.get(garbageSize - 1);
if (garbage != null && garbage instanceof StringBuilder) {
mStringPool.add(garbage);
poolSize++;
}
garbageSize--;
}
if (poolSize == prefMaxSuggestions + 1) {
Log.w("Suggest", "String pool got too big: " + poolSize);
}
suggestions.clear();
}
public void close() {
if (mMainDict != null) {
mMainDict.close();
}
}
}
| 11beeaosama-descrbvbnvbniption | java/src/org/pocketworkstation/pckeyboard/Suggest.java | Java | asf20 | 22,169 |
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.PopupWindow;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class CandidateView extends View {
private static final int OUT_OF_BOUNDS_WORD_INDEX = -1;
private static final int OUT_OF_BOUNDS_X_COORD = -1;
private LatinIME mService;
private final ArrayList<CharSequence> mSuggestions = new ArrayList<CharSequence>();
private boolean mShowingCompletions;
private CharSequence mSelectedString;
private int mSelectedIndex;
private int mTouchX = OUT_OF_BOUNDS_X_COORD;
private final Drawable mSelectionHighlight;
private boolean mTypedWordValid;
private boolean mHaveMinimalSuggestion;
private Rect mBgPadding;
private final TextView mPreviewText;
private final PopupWindow mPreviewPopup;
private int mCurrentWordIndex;
private Drawable mDivider;
private static final int MAX_SUGGESTIONS = 32;
private static final int SCROLL_PIXELS = 20;
private final int[] mWordWidth = new int[MAX_SUGGESTIONS];
private final int[] mWordX = new int[MAX_SUGGESTIONS];
private int mPopupPreviewX;
private int mPopupPreviewY;
private static final int X_GAP = 10;
private final int mColorNormal;
private final int mColorRecommended;
private final int mColorOther;
private final Paint mPaint;
private final int mDescent;
private boolean mScrolled;
private boolean mShowingAddToDictionary;
private CharSequence mAddToDictionaryHint;
private int mTargetScrollX;
private final int mMinTouchableWidth;
private int mTotalWidth;
private final GestureDetector mGestureDetector;
/**
* Construct a CandidateView for showing suggested words for completion.
* @param context
* @param attrs
*/
public CandidateView(Context context, AttributeSet attrs) {
super(context, attrs);
mSelectionHighlight = context.getResources().getDrawable(
R.drawable.list_selector_background_pressed);
LayoutInflater inflate =
(LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resources res = context.getResources();
mPreviewPopup = new PopupWindow(context);
mPreviewText = (TextView) inflate.inflate(R.layout.candidate_preview, null);
mPreviewPopup.setWindowLayoutMode(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
mPreviewPopup.setContentView(mPreviewText);
mPreviewPopup.setBackgroundDrawable(null);
mPreviewPopup.setAnimationStyle(R.style.KeyPreviewAnimation);
mColorNormal = res.getColor(R.color.candidate_normal);
mColorRecommended = res.getColor(R.color.candidate_recommended);
mColorOther = res.getColor(R.color.candidate_other);
mDivider = res.getDrawable(R.drawable.keyboard_suggest_strip_divider);
mAddToDictionaryHint = res.getString(R.string.hint_add_to_dictionary);
mPaint = new Paint();
mPaint.setColor(mColorNormal);
mPaint.setAntiAlias(true);
mPaint.setTextSize(mPreviewText.getTextSize() * LatinIME.sKeyboardSettings.candidateScalePref);
mPaint.setStrokeWidth(0);
mPaint.setTextAlign(Align.CENTER);
mDescent = (int) mPaint.descent();
mMinTouchableWidth = (int)res.getDimension(R.dimen.candidate_min_touchable_width);
mGestureDetector = new GestureDetector(
new CandidateStripGestureListener(mMinTouchableWidth));
setWillNotDraw(false);
setHorizontalScrollBarEnabled(false);
setVerticalScrollBarEnabled(false);
scrollTo(0, getScrollY());
}
private class CandidateStripGestureListener extends GestureDetector.SimpleOnGestureListener {
private final int mTouchSlopSquare;
public CandidateStripGestureListener(int touchSlop) {
// Slightly reluctant to scroll to be able to easily choose the suggestion
mTouchSlopSquare = touchSlop * touchSlop;
}
@Override
public void onLongPress(MotionEvent me) {
if (mSuggestions.size() > 0) {
if (me.getX() + getScrollX() < mWordWidth[0] && getScrollX() < 10) {
longPressFirstWord();
}
}
}
@Override
public boolean onDown(MotionEvent e) {
mScrolled = false;
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2,
float distanceX, float distanceY) {
if (!mScrolled) {
// This is applied only when we recognize that scrolling is starting.
final int deltaX = (int) (e2.getX() - e1.getX());
final int deltaY = (int) (e2.getY() - e1.getY());
final int distance = (deltaX * deltaX) + (deltaY * deltaY);
if (distance < mTouchSlopSquare) {
return true;
}
mScrolled = true;
}
final int width = getWidth();
mScrolled = true;
int scrollX = getScrollX();
scrollX += (int) distanceX;
if (scrollX < 0) {
scrollX = 0;
}
if (distanceX > 0 && scrollX + width > mTotalWidth) {
scrollX -= (int) distanceX;
}
mTargetScrollX = scrollX;
scrollTo(scrollX, getScrollY());
hidePreview();
invalidate();
return true;
}
}
/**
* A connection back to the service to communicate with the text field
* @param listener
*/
public void setService(LatinIME listener) {
mService = listener;
}
@Override
public int computeHorizontalScrollRange() {
return mTotalWidth;
}
/**
* If the canvas is null, then only touch calculations are performed to pick the target
* candidate.
*/
@Override
protected void onDraw(Canvas canvas) {
if (canvas != null) {
super.onDraw(canvas);
}
mTotalWidth = 0;
final int height = getHeight();
if (mBgPadding == null) {
mBgPadding = new Rect(0, 0, 0, 0);
if (getBackground() != null) {
getBackground().getPadding(mBgPadding);
}
mDivider.setBounds(0, 0, mDivider.getIntrinsicWidth(),
mDivider.getIntrinsicHeight());
}
final int count = mSuggestions.size();
final Rect bgPadding = mBgPadding;
final Paint paint = mPaint;
final int touchX = mTouchX;
final int scrollX = getScrollX();
final boolean scrolled = mScrolled;
final boolean typedWordValid = mTypedWordValid;
final int y = (int) (height + mPaint.getTextSize() - mDescent) / 2;
boolean existsAutoCompletion = false;
int x = 0;
for (int i = 0; i < count; i++) {
CharSequence suggestion = mSuggestions.get(i);
if (suggestion == null) continue;
final int wordLength = suggestion.length();
paint.setColor(mColorNormal);
if (mHaveMinimalSuggestion
&& ((i == 1 && !typedWordValid) || (i == 0 && typedWordValid))) {
paint.setTypeface(Typeface.DEFAULT_BOLD);
paint.setColor(mColorRecommended);
existsAutoCompletion = true;
} else if (i != 0 || (wordLength == 1 && count > 1)) {
// HACK: even if i == 0, we use mColorOther when this suggestion's length is 1 and
// there are multiple suggestions, such as the default punctuation list.
paint.setColor(mColorOther);
}
int wordWidth;
if ((wordWidth = mWordWidth[i]) == 0) {
float textWidth = paint.measureText(suggestion, 0, wordLength);
wordWidth = Math.max(mMinTouchableWidth, (int) textWidth + X_GAP * 2);
mWordWidth[i] = wordWidth;
}
mWordX[i] = x;
if (touchX != OUT_OF_BOUNDS_X_COORD && !scrolled
&& touchX + scrollX >= x && touchX + scrollX < x + wordWidth) {
if (canvas != null && !mShowingAddToDictionary) {
canvas.translate(x, 0);
mSelectionHighlight.setBounds(0, bgPadding.top, wordWidth, height);
mSelectionHighlight.draw(canvas);
canvas.translate(-x, 0);
}
mSelectedString = suggestion;
mSelectedIndex = i;
}
if (canvas != null) {
canvas.drawText(suggestion, 0, wordLength, x + wordWidth / 2, y, paint);
paint.setColor(mColorOther);
canvas.translate(x + wordWidth, 0);
// Draw a divider unless it's after the hint
if (!(mShowingAddToDictionary && i == 1)) {
mDivider.draw(canvas);
}
canvas.translate(-x - wordWidth, 0);
}
paint.setTypeface(Typeface.DEFAULT);
x += wordWidth;
}
mService.onAutoCompletionStateChanged(existsAutoCompletion);
mTotalWidth = x;
if (mTargetScrollX != scrollX) {
scrollToTarget();
}
}
private void scrollToTarget() {
int scrollX = getScrollX();
if (mTargetScrollX > scrollX) {
scrollX += SCROLL_PIXELS;
if (scrollX >= mTargetScrollX) {
scrollX = mTargetScrollX;
scrollTo(scrollX, getScrollY());
requestLayout();
} else {
scrollTo(scrollX, getScrollY());
}
} else {
scrollX -= SCROLL_PIXELS;
if (scrollX <= mTargetScrollX) {
scrollX = mTargetScrollX;
scrollTo(scrollX, getScrollY());
requestLayout();
} else {
scrollTo(scrollX, getScrollY());
}
}
invalidate();
}
public void setSuggestions(List<CharSequence> suggestions, boolean completions,
boolean typedWordValid, boolean haveMinimalSuggestion) {
clear();
if (suggestions != null) {
int insertCount = Math.min(suggestions.size(), MAX_SUGGESTIONS);
for (CharSequence suggestion : suggestions) {
mSuggestions.add(suggestion);
if (--insertCount == 0)
break;
}
}
mShowingCompletions = completions;
mTypedWordValid = typedWordValid;
scrollTo(0, getScrollY());
mTargetScrollX = 0;
mHaveMinimalSuggestion = haveMinimalSuggestion;
// Compute the total width
onDraw(null);
invalidate();
requestLayout();
}
public boolean isShowingAddToDictionaryHint() {
return mShowingAddToDictionary;
}
public void showAddToDictionaryHint(CharSequence word) {
ArrayList<CharSequence> suggestions = new ArrayList<CharSequence>();
suggestions.add(word);
suggestions.add(mAddToDictionaryHint);
setSuggestions(suggestions, false, false, false);
mShowingAddToDictionary = true;
}
public boolean dismissAddToDictionaryHint() {
if (!mShowingAddToDictionary) return false;
clear();
return true;
}
/* package */ List<CharSequence> getSuggestions() {
return mSuggestions;
}
public void clear() {
// Don't call mSuggestions.clear() because it's being used for logging
// in LatinIME.pickSuggestionManually().
mSuggestions.clear();
mTouchX = OUT_OF_BOUNDS_X_COORD;
mSelectedString = null;
mSelectedIndex = -1;
mShowingAddToDictionary = false;
invalidate();
Arrays.fill(mWordWidth, 0);
Arrays.fill(mWordX, 0);
}
@Override
public boolean onTouchEvent(MotionEvent me) {
if (mGestureDetector.onTouchEvent(me)) {
return true;
}
int action = me.getAction();
int x = (int) me.getX();
int y = (int) me.getY();
mTouchX = x;
switch (action) {
case MotionEvent.ACTION_DOWN:
invalidate();
break;
case MotionEvent.ACTION_MOVE:
if (y <= 0) {
// Fling up!?
if (mSelectedString != null) {
// If there are completions from the application, we don't change the state to
// STATE_PICKED_SUGGESTION
if (!mShowingCompletions) {
// This "acceptedSuggestion" will not be counted as a word because
// it will be counted in pickSuggestion instead.
//TextEntryState.acceptedSuggestion(mSuggestions.get(0), mSelectedString);
//TextEntryState.manualTyped(mSelectedString);
}
mService.pickSuggestionManually(mSelectedIndex, mSelectedString);
mSelectedString = null;
mSelectedIndex = -1;
}
}
break;
case MotionEvent.ACTION_UP:
if (!mScrolled) {
if (mSelectedString != null) {
if (mShowingAddToDictionary) {
longPressFirstWord();
clear();
} else {
if (!mShowingCompletions) {
//TextEntryState.acceptedSuggestion(mSuggestions.get(0), mSelectedString);
//TextEntryState.manualTyped(mSelectedString);
}
mService.pickSuggestionManually(mSelectedIndex, mSelectedString);
}
}
}
mSelectedString = null;
mSelectedIndex = -1;
requestLayout();
hidePreview();
invalidate();
break;
}
return true;
}
private void hidePreview() {
mTouchX = OUT_OF_BOUNDS_X_COORD;
mCurrentWordIndex = OUT_OF_BOUNDS_WORD_INDEX;
mPreviewPopup.dismiss();
}
private void showPreview(int wordIndex, String altText) {
int oldWordIndex = mCurrentWordIndex;
mCurrentWordIndex = wordIndex;
// If index changed or changing text
if (oldWordIndex != mCurrentWordIndex || altText != null) {
if (wordIndex == OUT_OF_BOUNDS_WORD_INDEX) {
hidePreview();
} else {
CharSequence word = altText != null? altText : mSuggestions.get(wordIndex);
mPreviewText.setText(word);
mPreviewText.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
int wordWidth = (int) (mPaint.measureText(word, 0, word.length()) + X_GAP * 2);
final int popupWidth = wordWidth
+ mPreviewText.getPaddingLeft() + mPreviewText.getPaddingRight();
final int popupHeight = mPreviewText.getMeasuredHeight();
//mPreviewText.setVisibility(INVISIBLE);
mPopupPreviewX = mWordX[wordIndex] - mPreviewText.getPaddingLeft() - getScrollX()
+ (mWordWidth[wordIndex] - wordWidth) / 2;
mPopupPreviewY = - popupHeight;
int [] offsetInWindow = new int[2];
getLocationInWindow(offsetInWindow);
if (mPreviewPopup.isShowing()) {
mPreviewPopup.update(mPopupPreviewX, mPopupPreviewY + offsetInWindow[1],
popupWidth, popupHeight);
} else {
mPreviewPopup.setWidth(popupWidth);
mPreviewPopup.setHeight(popupHeight);
mPreviewPopup.showAtLocation(this, Gravity.NO_GRAVITY, mPopupPreviewX,
mPopupPreviewY + offsetInWindow[1]);
}
mPreviewText.setVisibility(VISIBLE);
}
}
}
private void longPressFirstWord() {
CharSequence word = mSuggestions.get(0);
if (word.length() < 2) return;
if (mService.addWordToDictionary(word.toString())) {
showPreview(0, getContext().getResources().getString(R.string.added_word, word));
}
}
@Override
public void onDetachedFromWindow() {
super.onDetachedFromWindow();
hidePreview();
}
}
| 11beeaosama-descrbvbnvbniption | java/src/org/pocketworkstation/pckeyboard/CandidateView.java | Java | asf20 | 18,067 |
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import java.util.List;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import org.pocketworkstation.pckeyboard.Keyboard.Key;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.widget.PopupWindow;
import android.widget.TextView;
public class LatinKeyboardView extends LatinKeyboardBaseView {
static final String TAG = "HK/LatinKeyboardView";
// The keycode list needs to stay in sync with the
// res/values/keycodes.xml file.
// FIXME: The following keycodes should really be renumbered
// since they conflict with existing KeyEvent keycodes.
static final int KEYCODE_OPTIONS = -100;
static final int KEYCODE_OPTIONS_LONGPRESS = -101;
static final int KEYCODE_VOICE = -102;
static final int KEYCODE_F1 = -103;
static final int KEYCODE_NEXT_LANGUAGE = -104;
static final int KEYCODE_PREV_LANGUAGE = -105;
static final int KEYCODE_COMPOSE = -10024;
// The following keycodes match (negative) KeyEvent keycodes.
// Would be better to use the real KeyEvent values, but many
// don't exist prior to the Honeycomb API (level 11).
static final int KEYCODE_DPAD_UP = -19;
static final int KEYCODE_DPAD_DOWN = -20;
static final int KEYCODE_DPAD_LEFT = -21;
static final int KEYCODE_DPAD_RIGHT = -22;
static final int KEYCODE_DPAD_CENTER = -23;
static final int KEYCODE_ALT_LEFT = -57;
static final int KEYCODE_PAGE_UP = -92;
static final int KEYCODE_PAGE_DOWN = -93;
static final int KEYCODE_ESCAPE = -111;
static final int KEYCODE_FORWARD_DEL = -112;
static final int KEYCODE_CTRL_LEFT = -113;
static final int KEYCODE_CAPS_LOCK = -115;
static final int KEYCODE_SCROLL_LOCK = -116;
static final int KEYCODE_META_LEFT = -117;
static final int KEYCODE_FN = -119;
static final int KEYCODE_SYSRQ = -120;
static final int KEYCODE_BREAK = -121;
static final int KEYCODE_HOME = -122;
static final int KEYCODE_END = -123;
static final int KEYCODE_INSERT = -124;
static final int KEYCODE_FKEY_F1 = -131;
static final int KEYCODE_FKEY_F2 = -132;
static final int KEYCODE_FKEY_F3 = -133;
static final int KEYCODE_FKEY_F4 = -134;
static final int KEYCODE_FKEY_F5 = -135;
static final int KEYCODE_FKEY_F6 = -136;
static final int KEYCODE_FKEY_F7 = -137;
static final int KEYCODE_FKEY_F8 = -138;
static final int KEYCODE_FKEY_F9 = -139;
static final int KEYCODE_FKEY_F10 = -140;
static final int KEYCODE_FKEY_F11 = -141;
static final int KEYCODE_FKEY_F12 = -142;
static final int KEYCODE_NUM_LOCK = -143;
private Keyboard mPhoneKeyboard;
/** Whether the extension of this keyboard is visible */
private boolean mExtensionVisible;
/** The view that is shown as an extension of this keyboard view */
private LatinKeyboardView mExtension;
/** The popup window that contains the extension of this keyboard */
private PopupWindow mExtensionPopup;
/** Whether this view is an extension of another keyboard */
private boolean mIsExtensionType;
private boolean mFirstEvent;
/** Whether we've started dropping move events because we found a big jump */
private boolean mDroppingEvents;
/**
* Whether multi-touch disambiguation needs to be disabled for any reason. There are 2 reasons
* for this to happen - (1) if a real multi-touch event has occured and (2) we've opened an
* extension keyboard.
*/
private boolean mDisableDisambiguation;
/** The distance threshold at which we start treating the touch session as a multi-touch */
private int mJumpThresholdSquare = Integer.MAX_VALUE;
/** The y coordinate of the last row */
private int mLastRowY;
private int mExtensionLayoutResId = 0;
private LatinKeyboard mExtensionKeyboard;
public LatinKeyboardView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public LatinKeyboardView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO(klausw): migrate attribute styles to LatinKeyboardView?
TypedArray a = context.obtainStyledAttributes(
attrs, R.styleable.LatinKeyboardBaseView, defStyle, R.style.LatinKeyboardBaseView);
LayoutInflater inflate =
(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
int previewLayout = 0;
int n = a.getIndexCount();
for (int i = 0; i < n; i++) {
int attr = a.getIndex(i);
switch (attr) {
case R.styleable.LatinKeyboardBaseView_keyPreviewLayout:
previewLayout = a.getResourceId(attr, 0);
if (previewLayout == R.layout.null_layout) previewLayout = 0;
break;
case R.styleable.LatinKeyboardBaseView_keyPreviewOffset:
mPreviewOffset = a.getDimensionPixelOffset(attr, 0);
break;
case R.styleable.LatinKeyboardBaseView_keyPreviewHeight:
mPreviewHeight = a.getDimensionPixelSize(attr, 80);
break;
case R.styleable.LatinKeyboardBaseView_popupLayout:
mPopupLayout = a.getResourceId(attr, 0);
if (mPopupLayout == R.layout.null_layout) mPopupLayout = 0;
break;
}
}
final Resources res = getResources();
if (previewLayout != 0) {
mPreviewPopup = new PopupWindow(context);
Log.i(TAG, "new mPreviewPopup " + mPreviewPopup + " from " + this);
mPreviewText = (TextView) inflate.inflate(previewLayout, null);
mPreviewTextSizeLarge = (int) res.getDimension(R.dimen.key_preview_text_size_large);
mPreviewPopup.setContentView(mPreviewText);
mPreviewPopup.setBackgroundDrawable(null);
mPreviewPopup.setTouchable(false);
mPreviewPopup.setAnimationStyle(R.style.KeyPreviewAnimation);
} else {
mShowPreview = false;
}
if (mPopupLayout != 0) {
mMiniKeyboardParent = this;
mMiniKeyboardPopup = new PopupWindow(context);
Log.i(TAG, "new mMiniKeyboardPopup " + mMiniKeyboardPopup + " from " + this);
mMiniKeyboardPopup.setBackgroundDrawable(null);
mMiniKeyboardPopup.setAnimationStyle(R.style.MiniKeyboardAnimation);
mMiniKeyboardVisible = false;
}
}
public void setPhoneKeyboard(Keyboard phoneKeyboard) {
mPhoneKeyboard = phoneKeyboard;
}
public void setExtensionLayoutResId (int id) {
mExtensionLayoutResId = id;
}
@Override
public void setPreviewEnabled(boolean previewEnabled) {
if (getKeyboard() == mPhoneKeyboard) {
// Phone keyboard never shows popup preview (except language switch).
super.setPreviewEnabled(false);
} else {
super.setPreviewEnabled(previewEnabled);
}
}
@Override
public void setKeyboard(Keyboard newKeyboard) {
final Keyboard oldKeyboard = getKeyboard();
if (oldKeyboard instanceof LatinKeyboard) {
// Reset old keyboard state before switching to new keyboard.
((LatinKeyboard)oldKeyboard).keyReleased();
}
super.setKeyboard(newKeyboard);
// One-seventh of the keyboard width seems like a reasonable threshold
mJumpThresholdSquare = newKeyboard.getMinWidth() / 7;
mJumpThresholdSquare *= mJumpThresholdSquare;
// Get Y coordinate of the last row based on the row count, assuming equal height
int numRows = newKeyboard.mRowCount;
mLastRowY = (newKeyboard.getHeight() * (numRows - 1)) / numRows;
mExtensionKeyboard = ((LatinKeyboard) newKeyboard).getExtension();
if (mExtensionKeyboard != null && mExtension != null) mExtension.setKeyboard(mExtensionKeyboard);
setKeyboardLocal(newKeyboard);
}
@Override
/*package*/ boolean enableSlideKeyHack() {
return true;
}
@Override
protected boolean onLongPress(Key key) {
PointerTracker.clearSlideKeys();
int primaryCode = key.codes[0];
if (primaryCode == KEYCODE_OPTIONS) {
return invokeOnKey(KEYCODE_OPTIONS_LONGPRESS);
} else if (primaryCode == KEYCODE_DPAD_CENTER) {
return invokeOnKey(KEYCODE_COMPOSE);
} else if (primaryCode == '0' && getKeyboard() == mPhoneKeyboard) {
// Long pressing on 0 in phone number keypad gives you a '+'.
return invokeOnKey('+');
} else {
return super.onLongPress(key);
}
}
private boolean invokeOnKey(int primaryCode) {
getOnKeyboardActionListener().onKey(primaryCode, null,
LatinKeyboardBaseView.NOT_A_TOUCH_COORDINATE,
LatinKeyboardBaseView.NOT_A_TOUCH_COORDINATE);
return true;
}
/**
* This function checks to see if we need to handle any sudden jumps in the pointer location
* that could be due to a multi-touch being treated as a move by the firmware or hardware.
* Once a sudden jump is detected, all subsequent move events are discarded
* until an UP is received.<P>
* When a sudden jump is detected, an UP event is simulated at the last position and when
* the sudden moves subside, a DOWN event is simulated for the second key.
* @param me the motion event
* @return true if the event was consumed, so that it doesn't continue to be handled by
* KeyboardView.
*/
private boolean handleSuddenJump(MotionEvent me) {
final int action = me.getAction();
final int x = (int) me.getX();
final int y = (int) me.getY();
boolean result = false;
// Real multi-touch event? Stop looking for sudden jumps
if (me.getPointerCount() > 1) {
mDisableDisambiguation = true;
}
if (mDisableDisambiguation) {
// If UP, reset the multi-touch flag
if (action == MotionEvent.ACTION_UP) mDisableDisambiguation = false;
return false;
}
switch (action) {
case MotionEvent.ACTION_DOWN:
// Reset the "session"
mDroppingEvents = false;
mDisableDisambiguation = false;
break;
case MotionEvent.ACTION_MOVE:
// Is this a big jump?
final int distanceSquare = (mLastX - x) * (mLastX - x) + (mLastY - y) * (mLastY - y);
// Check the distance and also if the move is not entirely within the bottom row
// If it's only in the bottom row, it might be an intentional slide gesture
// for language switching
if (distanceSquare > mJumpThresholdSquare
&& (mLastY < mLastRowY || y < mLastRowY)) {
// If we're not yet dropping events, start dropping and send an UP event
if (!mDroppingEvents) {
mDroppingEvents = true;
// Send an up event
MotionEvent translated = MotionEvent.obtain(me.getEventTime(), me.getEventTime(),
MotionEvent.ACTION_UP,
mLastX, mLastY, me.getMetaState());
super.onTouchEvent(translated);
translated.recycle();
}
result = true;
} else if (mDroppingEvents) {
// If moves are small and we're already dropping events, continue dropping
result = true;
}
break;
case MotionEvent.ACTION_UP:
if (mDroppingEvents) {
// Send a down event first, as we dropped a bunch of sudden jumps and assume that
// the user is releasing the touch on the second key.
MotionEvent translated = MotionEvent.obtain(me.getEventTime(), me.getEventTime(),
MotionEvent.ACTION_DOWN,
x, y, me.getMetaState());
super.onTouchEvent(translated);
translated.recycle();
mDroppingEvents = false;
// Let the up event get processed as well, result = false
}
break;
}
// Track the previous coordinate
mLastX = x;
mLastY = y;
return result;
}
@Override
public boolean onTouchEvent(MotionEvent me) {
LatinKeyboard keyboard = (LatinKeyboard) getKeyboard();
if (LatinIME.sKeyboardSettings.showTouchPos || DEBUG_LINE) {
mLastX = (int) me.getX();
mLastY = (int) me.getY();
invalidate();
}
// If an extension keyboard is visible or this is an extension keyboard, don't look
// for sudden jumps. Otherwise, if there was a sudden jump, return without processing the
// actual motion event.
if (!mExtensionVisible && !mIsExtensionType
&& handleSuddenJump(me)) return true;
// Reset any bounding box controls in the keyboard
if (me.getAction() == MotionEvent.ACTION_DOWN) {
keyboard.keyReleased();
}
if (me.getAction() == MotionEvent.ACTION_UP) {
int languageDirection = keyboard.getLanguageChangeDirection();
if (languageDirection != 0) {
getOnKeyboardActionListener().onKey(
languageDirection == 1 ? KEYCODE_NEXT_LANGUAGE : KEYCODE_PREV_LANGUAGE,
null, mLastX, mLastY);
me.setAction(MotionEvent.ACTION_CANCEL);
keyboard.keyReleased();
return super.onTouchEvent(me);
}
}
// If we don't have an extension keyboard, don't go any further.
if (keyboard.getExtension() == null) {
return super.onTouchEvent(me);
}
// If the motion event is above the keyboard and it's not an UP event coming
// even before the first MOVE event into the extension area
if (me.getY() < 0 && (mExtensionVisible || me.getAction() != MotionEvent.ACTION_UP)) {
if (mExtensionVisible) {
int action = me.getAction();
if (mFirstEvent) action = MotionEvent.ACTION_DOWN;
mFirstEvent = false;
MotionEvent translated = MotionEvent.obtain(me.getEventTime(), me.getEventTime(),
action,
me.getX(), me.getY() + mExtension.getHeight(), me.getMetaState());
if (me.getActionIndex() > 0)
return true; // ignore second touches to avoid "pointerIndex out of range"
boolean result = mExtension.onTouchEvent(translated);
translated.recycle();
if (me.getAction() == MotionEvent.ACTION_UP
|| me.getAction() == MotionEvent.ACTION_CANCEL) {
closeExtension();
}
return result;
} else {
if (swipeUp()) {
return true;
} else if (openExtension()) {
MotionEvent cancel = MotionEvent.obtain(me.getDownTime(), me.getEventTime(),
MotionEvent.ACTION_CANCEL, me.getX() - 100, me.getY() - 100, 0);
super.onTouchEvent(cancel);
cancel.recycle();
if (mExtension.getHeight() > 0) {
MotionEvent translated = MotionEvent.obtain(me.getEventTime(),
me.getEventTime(),
MotionEvent.ACTION_DOWN,
me.getX(), me.getY() + mExtension.getHeight(),
me.getMetaState());
mExtension.onTouchEvent(translated);
translated.recycle();
} else {
mFirstEvent = true;
}
// Stop processing multi-touch errors
mDisableDisambiguation = true;
}
return true;
}
} else if (mExtensionVisible) {
closeExtension();
// Send a down event into the main keyboard first
MotionEvent down = MotionEvent.obtain(me.getEventTime(), me.getEventTime(),
MotionEvent.ACTION_DOWN,
me.getX(), me.getY(), me.getMetaState());
super.onTouchEvent(down, true);
down.recycle();
// Send the actual event
return super.onTouchEvent(me);
} else {
return super.onTouchEvent(me);
}
}
private void setExtensionType(boolean isExtensionType) {
mIsExtensionType = isExtensionType;
}
private boolean openExtension() {
// If the current keyboard is not visible, or if the mini keyboard is active, don't show the popup
if (!isShown() || popupKeyboardIsShowing()) {
return false;
}
PointerTracker.clearSlideKeys();
if (((LatinKeyboard) getKeyboard()).getExtension() == null) return false;
makePopupWindow();
mExtensionVisible = true;
return true;
}
private void makePopupWindow() {
dismissPopupKeyboard();
if (mExtensionPopup == null) {
int[] windowLocation = new int[2];
mExtensionPopup = new PopupWindow(getContext());
mExtensionPopup.setBackgroundDrawable(null);
LayoutInflater li = (LayoutInflater) getContext().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
mExtension = (LatinKeyboardView) li.inflate(mExtensionLayoutResId == 0 ?
R.layout.input_trans : mExtensionLayoutResId, null);
Keyboard keyboard = mExtensionKeyboard;
mExtension.setKeyboard(keyboard);
mExtension.setExtensionType(true);
mExtension.setPadding(0, 0, 0, 0);
mExtension.setOnKeyboardActionListener(
new ExtensionKeyboardListener(getOnKeyboardActionListener()));
mExtension.setPopupParent(this);
mExtension.setPopupOffset(0, -windowLocation[1]);
mExtensionPopup.setContentView(mExtension);
mExtensionPopup.setWidth(getWidth());
mExtensionPopup.setHeight(keyboard.getHeight());
mExtensionPopup.setAnimationStyle(-1);
getLocationInWindow(windowLocation);
// TODO: Fix the "- 30".
mExtension.setPopupOffset(0, -windowLocation[1] - 30);
mExtensionPopup.showAtLocation(this, 0, 0, -keyboard.getHeight()
+ windowLocation[1] + this.getPaddingTop());
} else {
mExtension.setVisibility(VISIBLE);
}
mExtension.setShiftState(getShiftState()); // propagate shift state
}
@Override
public void closing() {
super.closing();
if (mExtensionPopup != null && mExtensionPopup.isShowing()) {
mExtensionPopup.dismiss();
mExtensionPopup = null;
}
}
private void closeExtension() {
mExtension.closing();
mExtension.setVisibility(INVISIBLE);
mExtensionVisible = false;
}
private static class ExtensionKeyboardListener implements OnKeyboardActionListener {
private OnKeyboardActionListener mTarget;
ExtensionKeyboardListener(OnKeyboardActionListener target) {
mTarget = target;
}
public void onKey(int primaryCode, int[] keyCodes, int x, int y) {
mTarget.onKey(primaryCode, keyCodes, x, y);
}
public void onPress(int primaryCode) {
mTarget.onPress(primaryCode);
}
public void onRelease(int primaryCode) {
mTarget.onRelease(primaryCode);
}
public void onText(CharSequence text) {
mTarget.onText(text);
}
public void onCancel() {
mTarget.onCancel();
}
public boolean swipeDown() {
// Don't pass through
return true;
}
public boolean swipeLeft() {
// Don't pass through
return true;
}
public boolean swipeRight() {
// Don't pass through
return true;
}
public boolean swipeUp() {
// Don't pass through
return true;
}
}
/**************************** INSTRUMENTATION *******************************/
static final boolean DEBUG_AUTO_PLAY = false;
static final boolean DEBUG_LINE = false;
private static final int MSG_TOUCH_DOWN = 1;
private static final int MSG_TOUCH_UP = 2;
Handler mHandler2;
private String mStringToPlay;
private int mStringIndex;
private boolean mDownDelivered;
private Key[] mAsciiKeys = new Key[256];
private boolean mPlaying;
private int mLastX;
private int mLastY;
private Paint mPaint;
private void setKeyboardLocal(Keyboard k) {
if (DEBUG_AUTO_PLAY) {
findKeys();
if (mHandler2 == null) {
mHandler2 = new Handler() {
@Override
public void handleMessage(Message msg) {
removeMessages(MSG_TOUCH_DOWN);
removeMessages(MSG_TOUCH_UP);
if (mPlaying == false) return;
switch (msg.what) {
case MSG_TOUCH_DOWN:
if (mStringIndex >= mStringToPlay.length()) {
mPlaying = false;
return;
}
char c = mStringToPlay.charAt(mStringIndex);
while (c > 255 || mAsciiKeys[c] == null) {
mStringIndex++;
if (mStringIndex >= mStringToPlay.length()) {
mPlaying = false;
return;
}
c = mStringToPlay.charAt(mStringIndex);
}
int x = mAsciiKeys[c].x + 10;
int y = mAsciiKeys[c].y + 26;
MotionEvent me = MotionEvent.obtain(SystemClock.uptimeMillis(),
SystemClock.uptimeMillis(),
MotionEvent.ACTION_DOWN, x, y, 0);
LatinKeyboardView.this.dispatchTouchEvent(me);
me.recycle();
sendEmptyMessageDelayed(MSG_TOUCH_UP, 500); // Deliver up in 500ms if nothing else
// happens
mDownDelivered = true;
break;
case MSG_TOUCH_UP:
char cUp = mStringToPlay.charAt(mStringIndex);
int x2 = mAsciiKeys[cUp].x + 10;
int y2 = mAsciiKeys[cUp].y + 26;
mStringIndex++;
MotionEvent me2 = MotionEvent.obtain(SystemClock.uptimeMillis(),
SystemClock.uptimeMillis(),
MotionEvent.ACTION_UP, x2, y2, 0);
LatinKeyboardView.this.dispatchTouchEvent(me2);
me2.recycle();
sendEmptyMessageDelayed(MSG_TOUCH_DOWN, 500); // Deliver up in 500ms if nothing else
// happens
mDownDelivered = false;
break;
}
}
};
}
}
}
private void findKeys() {
List<Key> keys = getKeyboard().getKeys();
// Get the keys on this keyboard
for (int i = 0; i < keys.size(); i++) {
int code = keys.get(i).codes[0];
if (code >= 0 && code <= 255) {
mAsciiKeys[code] = keys.get(i);
}
}
}
public void startPlaying(String s) {
if (DEBUG_AUTO_PLAY) {
if (s == null) return;
mStringToPlay = s.toLowerCase();
mPlaying = true;
mDownDelivered = false;
mStringIndex = 0;
mHandler2.sendEmptyMessageDelayed(MSG_TOUCH_DOWN, 10);
}
}
@Override
public void draw(Canvas c) {
LatinIMEUtil.GCUtils.getInstance().reset();
boolean tryGC = true;
for (int i = 0; i < LatinIMEUtil.GCUtils.GC_TRY_LOOP_MAX && tryGC; ++i) {
try {
super.draw(c);
tryGC = false;
} catch (OutOfMemoryError e) {
tryGC = LatinIMEUtil.GCUtils.getInstance().tryGCOrWait("LatinKeyboardView", e);
}
}
if (DEBUG_AUTO_PLAY) {
if (mPlaying) {
mHandler2.removeMessages(MSG_TOUCH_DOWN);
mHandler2.removeMessages(MSG_TOUCH_UP);
if (mDownDelivered) {
mHandler2.sendEmptyMessageDelayed(MSG_TOUCH_UP, 20);
} else {
mHandler2.sendEmptyMessageDelayed(MSG_TOUCH_DOWN, 20);
}
}
}
if (LatinIME.sKeyboardSettings.showTouchPos || DEBUG_LINE) {
if (mPaint == null) {
mPaint = new Paint();
mPaint.setColor(0x80FFFFFF);
mPaint.setAntiAlias(false);
}
c.drawLine(mLastX, 0, mLastX, getHeight(), mPaint);
c.drawLine(0, mLastY, getWidth(), mLastY, mPaint);
}
}
}
| 11beeaosama-descrbvbnvbniption | java/src/org/pocketworkstation/pckeyboard/LatinKeyboardView.java | Java | asf20 | 27,100 |
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import java.util.HashMap;
import java.util.Map;
import android.app.Dialog;
import android.app.backup.BackupManager;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceGroup;
import android.text.AutoText;
import android.text.InputType;
import android.util.Log;
public class LatinIMESettings extends PreferenceActivity
implements SharedPreferences.OnSharedPreferenceChangeListener,
DialogInterface.OnDismissListener {
private static final String QUICK_FIXES_KEY = "quick_fixes";
private static final String PREDICTION_SETTINGS_KEY = "prediction_settings";
private static final String VOICE_SETTINGS_KEY = "voice_mode";
/* package */ static final String PREF_SETTINGS_KEY = "settings_key";
static final String INPUT_CONNECTION_INFO = "input_connection_info";
private static final String TAG = "LatinIMESettings";
// Dialog ids
private static final int VOICE_INPUT_CONFIRM_DIALOG = 0;
private CheckBoxPreference mQuickFixes;
private ListPreference mVoicePreference;
private ListPreference mSettingsKeyPreference;
private ListPreference mKeyboardModePortraitPreference;
private ListPreference mKeyboardModeLandscapePreference;
private Preference mInputConnectionInfo;
private boolean mVoiceOn;
private boolean mOkClicked = false;
private String mVoiceModeOff;
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
addPreferencesFromResource(R.xml.prefs);
mQuickFixes = (CheckBoxPreference) findPreference(QUICK_FIXES_KEY);
mVoicePreference = (ListPreference) findPreference(VOICE_SETTINGS_KEY);
mSettingsKeyPreference = (ListPreference) findPreference(PREF_SETTINGS_KEY);
mInputConnectionInfo = (Preference) findPreference(INPUT_CONNECTION_INFO);
// TODO(klausw): remove these when no longer needed
mKeyboardModePortraitPreference = (ListPreference) findPreference("pref_keyboard_mode_portrait");
mKeyboardModeLandscapePreference = (ListPreference) findPreference("pref_keyboard_mode_landscape");
SharedPreferences prefs = getPreferenceManager().getSharedPreferences();
prefs.registerOnSharedPreferenceChangeListener(this);
mVoiceModeOff = getString(R.string.voice_mode_off);
mVoiceOn = !(prefs.getString(VOICE_SETTINGS_KEY, mVoiceModeOff).equals(mVoiceModeOff));
}
@Override
protected void onResume() {
super.onResume();
int autoTextSize = AutoText.getSize(getListView());
if (autoTextSize < 1) {
((PreferenceGroup) findPreference(PREDICTION_SETTINGS_KEY))
.removePreference(mQuickFixes);
}
Log.i(TAG, "compactModeEnabled=" + LatinIME.sKeyboardSettings.compactModeEnabled);
if (!LatinIME.sKeyboardSettings.compactModeEnabled) {
CharSequence[] oldEntries = mKeyboardModePortraitPreference.getEntries();
CharSequence[] oldValues = mKeyboardModePortraitPreference.getEntryValues();
if (oldEntries.length > 2) {
CharSequence[] newEntries = new CharSequence[] { oldEntries[0], oldEntries[2] };
CharSequence[] newValues = new CharSequence[] { oldValues[0], oldValues[2] };
mKeyboardModePortraitPreference.setEntries(newEntries);
mKeyboardModePortraitPreference.setEntryValues(newValues);
mKeyboardModeLandscapePreference.setEntries(newEntries);
mKeyboardModeLandscapePreference.setEntryValues(newValues);
}
}
updateSummaries();
}
@Override
protected void onDestroy() {
getPreferenceManager().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(
this);
super.onDestroy();
}
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
(new BackupManager(this)).dataChanged();
// If turning on voice input, show dialog
if (key.equals(VOICE_SETTINGS_KEY) && !mVoiceOn) {
if (!prefs.getString(VOICE_SETTINGS_KEY, mVoiceModeOff)
.equals(mVoiceModeOff)) {
showVoiceConfirmation();
}
}
mVoiceOn = !(prefs.getString(VOICE_SETTINGS_KEY, mVoiceModeOff).equals(mVoiceModeOff));
updateVoiceModeSummary();
updateSummaries();
}
static Map<Integer, String> INPUT_CLASSES = new HashMap<Integer, String>();
static Map<Integer, String> DATETIME_VARIATIONS = new HashMap<Integer, String>();
static Map<Integer, String> TEXT_VARIATIONS = new HashMap<Integer, String>();
static Map<Integer, String> NUMBER_VARIATIONS = new HashMap<Integer, String>();
static {
INPUT_CLASSES.put(0x00000004, "DATETIME");
INPUT_CLASSES.put(0x00000002, "NUMBER");
INPUT_CLASSES.put(0x00000003, "PHONE");
INPUT_CLASSES.put(0x00000001, "TEXT");
INPUT_CLASSES.put(0x00000000, "NULL");
DATETIME_VARIATIONS.put(0x00000010, "DATE");
DATETIME_VARIATIONS.put(0x00000020, "TIME");
NUMBER_VARIATIONS.put(0x00000010, "PASSWORD");
TEXT_VARIATIONS.put(0x00000020, "EMAIL_ADDRESS");
TEXT_VARIATIONS.put(0x00000030, "EMAIL_SUBJECT");
TEXT_VARIATIONS.put(0x000000b0, "FILTER");
TEXT_VARIATIONS.put(0x00000050, "LONG_MESSAGE");
TEXT_VARIATIONS.put(0x00000080, "PASSWORD");
TEXT_VARIATIONS.put(0x00000060, "PERSON_NAME");
TEXT_VARIATIONS.put(0x000000c0, "PHONETIC");
TEXT_VARIATIONS.put(0x00000070, "POSTAL_ADDRESS");
TEXT_VARIATIONS.put(0x00000040, "SHORT_MESSAGE");
TEXT_VARIATIONS.put(0x00000010, "URI");
TEXT_VARIATIONS.put(0x00000090, "VISIBLE_PASSWORD");
TEXT_VARIATIONS.put(0x000000a0, "WEB_EDIT_TEXT");
TEXT_VARIATIONS.put(0x000000d0, "WEB_EMAIL_ADDRESS");
TEXT_VARIATIONS.put(0x000000e0, "WEB_PASSWORD");
}
private static void addBit(StringBuffer buf, int bit, String str) {
if (bit != 0) {
buf.append("|");
buf.append(str);
}
}
private static String inputTypeDesc(int type) {
int cls = type & 0x0000000f; // MASK_CLASS
int flags = type & 0x00fff000; // MASK_FLAGS
int var = type & 0x00000ff0; // MASK_VARIATION
StringBuffer out = new StringBuffer();
String clsName = INPUT_CLASSES.get(cls);
out.append(clsName != null ? clsName : "?");
if (cls == InputType.TYPE_CLASS_TEXT) {
String varName = TEXT_VARIATIONS.get(var);
if (varName != null) {
out.append(".");
out.append(varName);
}
addBit(out, flags & 0x00010000, "AUTO_COMPLETE");
addBit(out, flags & 0x00008000, "AUTO_CORRECT");
addBit(out, flags & 0x00001000, "CAP_CHARACTERS");
addBit(out, flags & 0x00004000, "CAP_SENTENCES");
addBit(out, flags & 0x00002000, "CAP_WORDS");
addBit(out, flags & 0x00040000, "IME_MULTI_LINE");
addBit(out, flags & 0x00020000, "MULTI_LINE");
addBit(out, flags & 0x00080000, "NO_SUGGESTIONS");
} else if (cls == InputType.TYPE_CLASS_NUMBER) {
String varName = NUMBER_VARIATIONS.get(var);
if (varName != null) {
out.append(".");
out.append(varName);
}
addBit(out, flags & 0x00002000, "DECIMAL");
addBit(out, flags & 0x00001000, "SIGNED");
} else if (cls == InputType.TYPE_CLASS_DATETIME) {
String varName = DATETIME_VARIATIONS.get(var);
if (varName != null) {
out.append(".");
out.append(varName);
}
}
return out.toString();
}
private void updateSummaries() {
Resources res = getResources();
mSettingsKeyPreference.setSummary(
res.getStringArray(R.array.settings_key_modes)
[mSettingsKeyPreference.findIndexOfValue(mSettingsKeyPreference.getValue())]);
mInputConnectionInfo.setSummary(String.format("%s type=%s",
LatinIME.sKeyboardSettings.editorPackageName,
inputTypeDesc(LatinIME.sKeyboardSettings.editorInputType)
));
}
private void showVoiceConfirmation() {
mOkClicked = false;
showDialog(VOICE_INPUT_CONFIRM_DIALOG);
}
private void updateVoiceModeSummary() {
mVoicePreference.setSummary(
getResources().getStringArray(R.array.voice_input_modes_summary)
[mVoicePreference.findIndexOfValue(mVoicePreference.getValue())]);
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
default:
Log.e(TAG, "unknown dialog " + id);
return null;
}
}
public void onDismiss(DialogInterface dialog) {
if (!mOkClicked) {
// This assumes that onPreferenceClick gets called first, and this if the user
// agreed after the warning, we set the mOkClicked value to true.
mVoicePreference.setValue(mVoiceModeOff);
}
}
private void updateVoicePreference() {
}
}
| 11beeaosama-descrbvbnvbniption | java/src/org/pocketworkstation/pckeyboard/LatinIMESettings.java | Java | asf20 | 10,307 |
/*
* Copyright (C) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.os.AsyncTask;
import android.provider.BaseColumns;
import android.util.Log;
/**
* Stores all the pairs user types in databases. Prune the database if the size
* gets too big. Unlike AutoDictionary, it even stores the pairs that are already
* in the dictionary.
*/
public class UserBigramDictionary extends ExpandableDictionary {
private static final String TAG = "UserBigramDictionary";
/** Any pair being typed or picked */
private static final int FREQUENCY_FOR_TYPED = 2;
/** Maximum frequency for all pairs */
private static final int FREQUENCY_MAX = 127;
/**
* If this pair is typed 6 times, it would be suggested.
* Should be smaller than ContactsDictionary.FREQUENCY_FOR_CONTACTS_BIGRAM
*/
protected static final int SUGGEST_THRESHOLD = 6 * FREQUENCY_FOR_TYPED;
/** Maximum number of pairs. Pruning will start when databases goes above this number. */
private static int sMaxUserBigrams = 10000;
/**
* When it hits maximum bigram pair, it will delete until you are left with
* only (sMaxUserBigrams - sDeleteUserBigrams) pairs.
* Do not keep this number small to avoid deleting too often.
*/
private static int sDeleteUserBigrams = 1000;
/**
* Database version should increase if the database structure changes
*/
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "userbigram_dict.db";
/** Name of the words table in the database */
private static final String MAIN_TABLE_NAME = "main";
// TODO: Consume less space by using a unique id for locale instead of the whole
// 2-5 character string. (Same TODO from AutoDictionary)
private static final String MAIN_COLUMN_ID = BaseColumns._ID;
private static final String MAIN_COLUMN_WORD1 = "word1";
private static final String MAIN_COLUMN_WORD2 = "word2";
private static final String MAIN_COLUMN_LOCALE = "locale";
/** Name of the frequency table in the database */
private static final String FREQ_TABLE_NAME = "frequency";
private static final String FREQ_COLUMN_ID = BaseColumns._ID;
private static final String FREQ_COLUMN_PAIR_ID = "pair_id";
private static final String FREQ_COLUMN_FREQUENCY = "freq";
private final LatinIME mIme;
/** Locale for which this auto dictionary is storing words */
private String mLocale;
private HashSet<Bigram> mPendingWrites = new HashSet<Bigram>();
private final Object mPendingWritesLock = new Object();
private static volatile boolean sUpdatingDB = false;
private final static HashMap<String, String> sDictProjectionMap;
static {
sDictProjectionMap = new HashMap<String, String>();
sDictProjectionMap.put(MAIN_COLUMN_ID, MAIN_COLUMN_ID);
sDictProjectionMap.put(MAIN_COLUMN_WORD1, MAIN_COLUMN_WORD1);
sDictProjectionMap.put(MAIN_COLUMN_WORD2, MAIN_COLUMN_WORD2);
sDictProjectionMap.put(MAIN_COLUMN_LOCALE, MAIN_COLUMN_LOCALE);
sDictProjectionMap.put(FREQ_COLUMN_ID, FREQ_COLUMN_ID);
sDictProjectionMap.put(FREQ_COLUMN_PAIR_ID, FREQ_COLUMN_PAIR_ID);
sDictProjectionMap.put(FREQ_COLUMN_FREQUENCY, FREQ_COLUMN_FREQUENCY);
}
private static DatabaseHelper sOpenHelper = null;
private static class Bigram {
String word1;
String word2;
int frequency;
Bigram(String word1, String word2, int frequency) {
this.word1 = word1;
this.word2 = word2;
this.frequency = frequency;
}
@Override
public boolean equals(Object bigram) {
Bigram bigram2 = (Bigram) bigram;
return (word1.equals(bigram2.word1) && word2.equals(bigram2.word2));
}
@Override
public int hashCode() {
return (word1 + " " + word2).hashCode();
}
}
public void setDatabaseMax(int maxUserBigram) {
sMaxUserBigrams = maxUserBigram;
}
public void setDatabaseDelete(int deleteUserBigram) {
sDeleteUserBigrams = deleteUserBigram;
}
public UserBigramDictionary(Context context, LatinIME ime, String locale, int dicTypeId) {
super(context, dicTypeId);
mIme = ime;
mLocale = locale;
if (sOpenHelper == null) {
sOpenHelper = new DatabaseHelper(getContext());
}
if (mLocale != null && mLocale.length() > 1) {
loadDictionary();
}
}
@Override
public void close() {
flushPendingWrites();
// Don't close the database as locale changes will require it to be reopened anyway
// Also, the database is written to somewhat frequently, so it needs to be kept alive
// throughout the life of the process.
// mOpenHelper.close();
super.close();
}
/**
* Pair will be added to the userbigram database.
*/
public int addBigrams(String word1, String word2) {
// remove caps
if (mIme != null && mIme.getCurrentWord().isAutoCapitalized()) {
word2 = Character.toLowerCase(word2.charAt(0)) + word2.substring(1);
}
int freq = super.addBigram(word1, word2, FREQUENCY_FOR_TYPED);
if (freq > FREQUENCY_MAX) freq = FREQUENCY_MAX;
synchronized (mPendingWritesLock) {
if (freq == FREQUENCY_FOR_TYPED || mPendingWrites.isEmpty()) {
mPendingWrites.add(new Bigram(word1, word2, freq));
} else {
Bigram bi = new Bigram(word1, word2, freq);
mPendingWrites.remove(bi);
mPendingWrites.add(bi);
}
}
return freq;
}
/**
* Schedules a background thread to write any pending words to the database.
*/
public void flushPendingWrites() {
synchronized (mPendingWritesLock) {
// Nothing pending? Return
if (mPendingWrites.isEmpty()) return;
// Create a background thread to write the pending entries
new UpdateDbTask(getContext(), sOpenHelper, mPendingWrites, mLocale).execute();
// Create a new map for writing new entries into while the old one is written to db
mPendingWrites = new HashSet<Bigram>();
}
}
/** Used for testing purpose **/
void waitUntilUpdateDBDone() {
synchronized (mPendingWritesLock) {
while (sUpdatingDB) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
}
return;
}
}
@Override
public void loadDictionaryAsync() {
// Load the words that correspond to the current input locale
Cursor cursor = query(MAIN_COLUMN_LOCALE + "=?", new String[] { mLocale });
try {
if (cursor.moveToFirst()) {
int word1Index = cursor.getColumnIndex(MAIN_COLUMN_WORD1);
int word2Index = cursor.getColumnIndex(MAIN_COLUMN_WORD2);
int frequencyIndex = cursor.getColumnIndex(FREQ_COLUMN_FREQUENCY);
while (!cursor.isAfterLast()) {
String word1 = cursor.getString(word1Index);
String word2 = cursor.getString(word2Index);
int frequency = cursor.getInt(frequencyIndex);
// Safeguard against adding really long words. Stack may overflow due
// to recursive lookup
if (word1.length() < MAX_WORD_LENGTH && word2.length() < MAX_WORD_LENGTH) {
super.setBigram(word1, word2, frequency);
}
cursor.moveToNext();
}
}
} finally {
cursor.close();
}
}
/**
* Query the database
*/
private Cursor query(String selection, String[] selectionArgs) {
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
// main INNER JOIN frequency ON (main._id=freq.pair_id)
qb.setTables(MAIN_TABLE_NAME + " INNER JOIN " + FREQ_TABLE_NAME + " ON ("
+ MAIN_TABLE_NAME + "." + MAIN_COLUMN_ID + "=" + FREQ_TABLE_NAME + "."
+ FREQ_COLUMN_PAIR_ID +")");
qb.setProjectionMap(sDictProjectionMap);
// Get the database and run the query
SQLiteDatabase db = sOpenHelper.getReadableDatabase();
Cursor c = qb.query(db,
new String[] { MAIN_COLUMN_WORD1, MAIN_COLUMN_WORD2, FREQ_COLUMN_FREQUENCY },
selection, selectionArgs, null, null, null);
return c;
}
/**
* This class helps open, create, and upgrade the database file.
*/
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("PRAGMA foreign_keys = ON;");
db.execSQL("CREATE TABLE " + MAIN_TABLE_NAME + " ("
+ MAIN_COLUMN_ID + " INTEGER PRIMARY KEY,"
+ MAIN_COLUMN_WORD1 + " TEXT,"
+ MAIN_COLUMN_WORD2 + " TEXT,"
+ MAIN_COLUMN_LOCALE + " TEXT"
+ ");");
db.execSQL("CREATE TABLE " + FREQ_TABLE_NAME + " ("
+ FREQ_COLUMN_ID + " INTEGER PRIMARY KEY,"
+ FREQ_COLUMN_PAIR_ID + " INTEGER,"
+ FREQ_COLUMN_FREQUENCY + " INTEGER,"
+ "FOREIGN KEY(" + FREQ_COLUMN_PAIR_ID + ") REFERENCES " + MAIN_TABLE_NAME
+ "(" + MAIN_COLUMN_ID + ")" + " ON DELETE CASCADE"
+ ");");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + MAIN_TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS " + FREQ_TABLE_NAME);
onCreate(db);
}
}
/**
* Async task to write pending words to the database so that it stays in sync with
* the in-memory trie.
*/
private static class UpdateDbTask extends AsyncTask<Void, Void, Void> {
private final HashSet<Bigram> mMap;
private final DatabaseHelper mDbHelper;
private final String mLocale;
public UpdateDbTask(Context context, DatabaseHelper openHelper,
HashSet<Bigram> pendingWrites, String locale) {
mMap = pendingWrites;
mLocale = locale;
mDbHelper = openHelper;
}
/** Prune any old data if the database is getting too big. */
private void checkPruneData(SQLiteDatabase db) {
db.execSQL("PRAGMA foreign_keys = ON;");
Cursor c = db.query(FREQ_TABLE_NAME, new String[] { FREQ_COLUMN_PAIR_ID },
null, null, null, null, null);
try {
int totalRowCount = c.getCount();
// prune out old data if we have too much data
if (totalRowCount > sMaxUserBigrams) {
int numDeleteRows = (totalRowCount - sMaxUserBigrams) + sDeleteUserBigrams;
int pairIdColumnId = c.getColumnIndex(FREQ_COLUMN_PAIR_ID);
c.moveToFirst();
int count = 0;
while (count < numDeleteRows && !c.isAfterLast()) {
String pairId = c.getString(pairIdColumnId);
// Deleting from MAIN table will delete the frequencies
// due to FOREIGN KEY .. ON DELETE CASCADE
db.delete(MAIN_TABLE_NAME, MAIN_COLUMN_ID + "=?",
new String[] { pairId });
c.moveToNext();
count++;
}
}
} finally {
c.close();
}
}
@Override
protected void onPreExecute() {
sUpdatingDB = true;
}
@Override
protected Void doInBackground(Void... v) {
SQLiteDatabase db = mDbHelper.getWritableDatabase();
db.execSQL("PRAGMA foreign_keys = ON;");
// Write all the entries to the db
Iterator<Bigram> iterator = mMap.iterator();
while (iterator.hasNext()) {
Bigram bi = iterator.next();
// find pair id
Cursor c = db.query(MAIN_TABLE_NAME, new String[] { MAIN_COLUMN_ID },
MAIN_COLUMN_WORD1 + "=? AND " + MAIN_COLUMN_WORD2 + "=? AND "
+ MAIN_COLUMN_LOCALE + "=?",
new String[] { bi.word1, bi.word2, mLocale }, null, null, null);
int pairId;
if (c.moveToFirst()) {
// existing pair
pairId = c.getInt(c.getColumnIndex(MAIN_COLUMN_ID));
db.delete(FREQ_TABLE_NAME, FREQ_COLUMN_PAIR_ID + "=?",
new String[] { Integer.toString(pairId) });
} else {
// new pair
Long pairIdLong = db.insert(MAIN_TABLE_NAME, null,
getContentValues(bi.word1, bi.word2, mLocale));
pairId = pairIdLong.intValue();
}
c.close();
// insert new frequency
db.insert(FREQ_TABLE_NAME, null, getFrequencyContentValues(pairId, bi.frequency));
}
checkPruneData(db);
sUpdatingDB = false;
return null;
}
private ContentValues getContentValues(String word1, String word2, String locale) {
ContentValues values = new ContentValues(3);
values.put(MAIN_COLUMN_WORD1, word1);
values.put(MAIN_COLUMN_WORD2, word2);
values.put(MAIN_COLUMN_LOCALE, locale);
return values;
}
private ContentValues getFrequencyContentValues(int pairId, int frequency) {
ContentValues values = new ContentValues(2);
values.put(FREQ_COLUMN_PAIR_ID, pairId);
values.put(FREQ_COLUMN_FREQUENCY, frequency);
return values;
}
}
}
| 11beeaosama-descrbvbnvbniption | java/src/org/pocketworkstation/pckeyboard/UserBigramDictionary.java | Java | asf20 | 15,477 |
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Html;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.TextView.BufferType;
public class Main extends Activity {
private final static String MARKET_URI = "market://search?q=pub:\"Klaus Weidner\"";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String html = getString(R.string.main_body);
html += "<p><i>Version: " + getString(R.string.auto_version) + "</i></p>";
Spanned content = Html.fromHtml(html);
TextView description = (TextView) findViewById(R.id.main_description);
description.setMovementMethod(LinkMovementMethod.getInstance());
description.setText(content, BufferType.SPANNABLE);
final Button setup1 = (Button) findViewById(R.id.main_setup_btn_configure_imes);
setup1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivityForResult(new Intent(android.provider.Settings.ACTION_INPUT_METHOD_SETTINGS), 0);
}
});
final Button setup2 = (Button) findViewById(R.id.main_setup_btn_set_ime);
setup2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.showInputMethodPicker();
}
});
final Activity that = this;
final Button setup4 = (Button) findViewById(R.id.main_setup_btn_input_lang);
setup4.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivityForResult(new Intent(that, InputLanguageSelection.class), 0);
}
});
final Button setup3 = (Button) findViewById(R.id.main_setup_btn_get_dicts);
setup3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent it = new Intent(Intent.ACTION_VIEW, Uri.parse(MARKET_URI));
try {
startActivity(it);
} catch (ActivityNotFoundException e) {
Toast.makeText(getApplicationContext(),
getResources().getString(
R.string.no_market_warning), Toast.LENGTH_LONG)
.show();
}
}
});
// PluginManager.getPluginDictionaries(getApplicationContext()); // why?
}
}
| 11beeaosama-descrbvbnvbniption | java/src/org/pocketworkstation/pckeyboard/Main.java | Java | asf20 | 3,648 |
/*
* Copyright (C) 2008-2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import org.xmlpull.v1.XmlPullParserException;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.content.res.XmlResourceParser;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.util.Xml;
import android.util.DisplayMetrics;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.StringTokenizer;
/**
* Loads an XML description of a keyboard and stores the attributes of the keys. A keyboard
* consists of rows of keys.
* <p>The layout file for a keyboard contains XML that looks like the following snippet:</p>
* <pre>
* <Keyboard
* android:keyWidth="%10p"
* android:keyHeight="50px"
* android:horizontalGap="2px"
* android:verticalGap="2px" >
* <Row android:keyWidth="32px" >
* <Key android:keyLabel="A" />
* ...
* </Row>
* ...
* </Keyboard>
* </pre>
* @attr ref android.R.styleable#Keyboard_keyWidth
* @attr ref android.R.styleable#Keyboard_keyHeight
* @attr ref android.R.styleable#Keyboard_horizontalGap
* @attr ref android.R.styleable#Keyboard_verticalGap
*/
public class Keyboard {
static final String TAG = "Keyboard";
public final static char DEAD_KEY_PLACEHOLDER = 0x25cc; // dotted small circle
public final static String DEAD_KEY_PLACEHOLDER_STRING = Character.toString(DEAD_KEY_PLACEHOLDER);
// Keyboard XML Tags
private static final String TAG_KEYBOARD = "Keyboard";
private static final String TAG_ROW = "Row";
private static final String TAG_KEY = "Key";
public static final int EDGE_LEFT = 0x01;
public static final int EDGE_RIGHT = 0x02;
public static final int EDGE_TOP = 0x04;
public static final int EDGE_BOTTOM = 0x08;
public static final int KEYCODE_SHIFT = -1;
public static final int KEYCODE_MODE_CHANGE = -2;
public static final int KEYCODE_CANCEL = -3;
public static final int KEYCODE_DONE = -4;
public static final int KEYCODE_DELETE = -5;
public static final int KEYCODE_ALT_SYM = -6;
// Backwards compatible setting to avoid having to change all the kbd_qwerty files
public static final int DEFAULT_LAYOUT_ROWS = 4;
public static final int DEFAULT_LAYOUT_COLUMNS = 10;
// Flag values for popup key contents. Keep in sync with strings.xml values.
public static final int POPUP_ADD_SHIFT = 1;
public static final int POPUP_ADD_CASE = 2;
public static final int POPUP_ADD_SELF = 4;
public static final int POPUP_DISABLE = 256;
public static final int POPUP_AUTOREPEAT = 512;
/** Horizontal gap default for all rows */
private float mDefaultHorizontalGap;
private float mHorizontalPad;
private float mVerticalPad;
/** Default key width */
private float mDefaultWidth;
/** Default key height */
private int mDefaultHeight;
/** Default gap between rows */
private int mDefaultVerticalGap;
public static final int SHIFT_OFF = 0;
public static final int SHIFT_ON = 1;
public static final int SHIFT_LOCKED = 2;
public static final int SHIFT_CAPS = 3;
public static final int SHIFT_CAPS_LOCKED = 4;
/** Is the keyboard in the shifted state */
private int mShiftState = SHIFT_OFF;
/** Key instance for the shift key, if present */
private Key mShiftKey;
private Key mAltKey;
private Key mCtrlKey;
private Key mMetaKey;
/** Key index for the shift key, if present */
private int mShiftKeyIndex = -1;
/** Total height of the keyboard, including the padding and keys */
private int mTotalHeight;
/**
* Total width of the keyboard, including left side gaps and keys, but not any gaps on the
* right side.
*/
private int mTotalWidth;
/** List of keys in this keyboard */
private List<Key> mKeys;
/** List of modifier keys such as Shift & Alt, if any */
private List<Key> mModifierKeys;
/** Width of the screen available to fit the keyboard */
private int mDisplayWidth;
/** Height of the screen and keyboard */
private int mDisplayHeight;
private int mKeyboardHeight;
/** Keyboard mode, or zero, if none. */
private int mKeyboardMode;
private boolean mUseExtension;
public int mLayoutRows;
public int mLayoutColumns;
public int mRowCount = 1;
public int mExtensionRowCount = 0;
// Variables for pre-computing nearest keys.
private int mCellWidth;
private int mCellHeight;
private int[][] mGridNeighbors;
private int mProximityThreshold;
/** Number of key widths from current touch point to search for nearest keys. */
private static float SEARCH_DISTANCE = 1.8f;
/**
* Container for keys in the keyboard. All keys in a row are at the same Y-coordinate.
* Some of the key size defaults can be overridden per row from what the {@link Keyboard}
* defines.
* @attr ref android.R.styleable#Keyboard_keyWidth
* @attr ref android.R.styleable#Keyboard_keyHeight
* @attr ref android.R.styleable#Keyboard_horizontalGap
* @attr ref android.R.styleable#Keyboard_verticalGap
* @attr ref android.R.styleable#Keyboard_Row_keyboardMode
*/
public static class Row {
/** Default width of a key in this row. */
public float defaultWidth;
/** Default height of a key in this row. */
public int defaultHeight;
/** Default horizontal gap between keys in this row. */
public float defaultHorizontalGap;
/** Vertical gap following this row. */
public int verticalGap;
/** The keyboard mode for this row */
public int mode;
public boolean extension;
private Keyboard parent;
public Row(Keyboard parent) {
this.parent = parent;
}
public Row(Resources res, Keyboard parent, XmlResourceParser parser) {
this.parent = parent;
TypedArray a = res.obtainAttributes(Xml.asAttributeSet(parser),
R.styleable.Keyboard);
defaultWidth = getDimensionOrFraction(a,
R.styleable.Keyboard_keyWidth,
parent.mDisplayWidth, parent.mDefaultWidth);
defaultHeight = Math.round(getDimensionOrFraction(a,
R.styleable.Keyboard_keyHeight,
parent.mDisplayHeight, parent.mDefaultHeight));
defaultHorizontalGap = getDimensionOrFraction(a,
R.styleable.Keyboard_horizontalGap,
parent.mDisplayWidth, parent.mDefaultHorizontalGap);
verticalGap = Math.round(getDimensionOrFraction(a,
R.styleable.Keyboard_verticalGap,
parent.mDisplayHeight, parent.mDefaultVerticalGap));
a.recycle();
a = res.obtainAttributes(Xml.asAttributeSet(parser),
R.styleable.Keyboard_Row);
mode = a.getResourceId(R.styleable.Keyboard_Row_keyboardMode,
0);
extension = a.getBoolean(R.styleable.Keyboard_Row_extension, false);
if (parent.mLayoutRows >= 5) {
boolean isTop = (extension || parent.mRowCount - parent.mExtensionRowCount <= 0);
float topScale = LatinIME.sKeyboardSettings.topRowScale;
float scale = isTop ? topScale : 1.0f + (1.0f - topScale) / (parent.mLayoutRows - 1);
defaultHeight = Math.round(defaultHeight * scale);
}
a.recycle();
}
}
/**
* Class for describing the position and characteristics of a single key in the keyboard.
*
* @attr ref android.R.styleable#Keyboard_keyWidth
* @attr ref android.R.styleable#Keyboard_keyHeight
* @attr ref android.R.styleable#Keyboard_horizontalGap
* @attr ref android.R.styleable#Keyboard_Key_codes
* @attr ref android.R.styleable#Keyboard_Key_keyIcon
* @attr ref android.R.styleable#Keyboard_Key_keyLabel
* @attr ref android.R.styleable#Keyboard_Key_iconPreview
* @attr ref android.R.styleable#Keyboard_Key_isSticky
* @attr ref android.R.styleable#Keyboard_Key_isRepeatable
* @attr ref android.R.styleable#Keyboard_Key_isModifier
* @attr ref android.R.styleable#Keyboard_Key_popupKeyboard
* @attr ref android.R.styleable#Keyboard_Key_popupCharacters
* @attr ref android.R.styleable#Keyboard_Key_keyOutputText
*/
public static class Key {
/**
* All the key codes (unicode or custom code) that this key could generate, zero'th
* being the most important.
*/
public int[] codes;
/** Label to display */
public CharSequence label;
public CharSequence shiftLabel;
public CharSequence capsLabel;
/** Icon to display instead of a label. Icon takes precedence over a label */
public Drawable icon;
/** Preview version of the icon, for the preview popup */
public Drawable iconPreview;
/** Width of the key, not including the gap */
public int width;
/** Height of the key, not including the gap */
private float realWidth;
public int height;
/** The horizontal gap before this key */
public int gap;
private float realGap;
/** Whether this key is sticky, i.e., a toggle key */
public boolean sticky;
/** X coordinate of the key in the keyboard layout */
public int x;
private float realX;
/** Y coordinate of the key in the keyboard layout */
public int y;
/** The current pressed state of this key */
public boolean pressed;
/** If this is a sticky key, is it on or locked? */
public boolean on;
public boolean locked;
/** Text to output when pressed. This can be multiple characters, like ".com" */
public CharSequence text;
/** Popup characters */
public CharSequence popupCharacters;
public boolean popupReversed;
public boolean isCursor;
public String hint; // Set by LatinKeyboardBaseView
public String altHint; // Set by LatinKeyboardBaseView
/**
* Flags that specify the anchoring to edges of the keyboard for detecting touch events
* that are just out of the boundary of the key. This is a bit mask of
* {@link Keyboard#EDGE_LEFT}, {@link Keyboard#EDGE_RIGHT}, {@link Keyboard#EDGE_TOP} and
* {@link Keyboard#EDGE_BOTTOM}.
*/
public int edgeFlags;
/** Whether this is a modifier key, such as Shift or Alt */
public boolean modifier;
/** The keyboard that this key belongs to */
private Keyboard keyboard;
/**
* If this key pops up a mini keyboard, this is the resource id for the XML layout for that
* keyboard.
*/
public int popupResId;
/** Whether this key repeats itself when held down */
public boolean repeatable;
/** Is the shifted character the uppercase equivalent of the unshifted one? */
private boolean isSimpleUppercase;
/** Is the shifted character a distinct uppercase char that's different from the shifted char? */
private boolean isDistinctUppercase;
private final static int[] KEY_STATE_NORMAL_ON = {
android.R.attr.state_checkable,
android.R.attr.state_checked
};
private final static int[] KEY_STATE_PRESSED_ON = {
android.R.attr.state_pressed,
android.R.attr.state_checkable,
android.R.attr.state_checked
};
private final static int[] KEY_STATE_NORMAL_LOCK = {
android.R.attr.state_active,
android.R.attr.state_checkable,
android.R.attr.state_checked
};
private final static int[] KEY_STATE_PRESSED_LOCK = {
android.R.attr.state_active,
android.R.attr.state_pressed,
android.R.attr.state_checkable,
android.R.attr.state_checked
};
private final static int[] KEY_STATE_NORMAL_OFF = {
android.R.attr.state_checkable
};
private final static int[] KEY_STATE_PRESSED_OFF = {
android.R.attr.state_pressed,
android.R.attr.state_checkable
};
private final static int[] KEY_STATE_NORMAL = {
};
private final static int[] KEY_STATE_PRESSED = {
android.R.attr.state_pressed
};
/** Create an empty key with no attributes. */
public Key(Row parent) {
keyboard = parent.parent;
height = parent.defaultHeight;
width = Math.round(parent.defaultWidth);
realWidth = parent.defaultWidth;
gap = Math.round(parent.defaultHorizontalGap);
realGap = parent.defaultHorizontalGap;
}
/** Create a key with the given top-left coordinate and extract its attributes from
* the XML parser.
* @param res resources associated with the caller's context
* @param parent the row that this key belongs to. The row must already be attached to
* a {@link Keyboard}.
* @param x the x coordinate of the top-left
* @param y the y coordinate of the top-left
* @param parser the XML parser containing the attributes for this key
*/
public Key(Resources res, Row parent, int x, int y, XmlResourceParser parser) {
this(parent);
this.x = x;
this.y = y;
TypedArray a = res.obtainAttributes(Xml.asAttributeSet(parser),
R.styleable.Keyboard);
realWidth = getDimensionOrFraction(a,
R.styleable.Keyboard_keyWidth,
keyboard.mDisplayWidth, parent.defaultWidth);
float realHeight = getDimensionOrFraction(a,
R.styleable.Keyboard_keyHeight,
keyboard.mDisplayHeight, parent.defaultHeight);
realHeight -= parent.parent.mVerticalPad;
height = Math.round(realHeight);
this.y += parent.parent.mVerticalPad / 2;
realGap = getDimensionOrFraction(a,
R.styleable.Keyboard_horizontalGap,
keyboard.mDisplayWidth, parent.defaultHorizontalGap);
realGap += parent.parent.mHorizontalPad;
realWidth -= parent.parent.mHorizontalPad;
width = Math.round(realWidth);
gap = Math.round(realGap);
a.recycle();
a = res.obtainAttributes(Xml.asAttributeSet(parser),
R.styleable.Keyboard_Key);
this.realX = this.x + realGap - parent.parent.mHorizontalPad / 2;
this.x = Math.round(this.realX);
TypedValue codesValue = new TypedValue();
a.getValue(R.styleable.Keyboard_Key_codes,
codesValue);
if (codesValue.type == TypedValue.TYPE_INT_DEC
|| codesValue.type == TypedValue.TYPE_INT_HEX) {
codes = new int[] { codesValue.data };
} else if (codesValue.type == TypedValue.TYPE_STRING) {
codes = parseCSV(codesValue.string.toString());
}
iconPreview = a.getDrawable(R.styleable.Keyboard_Key_iconPreview);
if (iconPreview != null) {
iconPreview.setBounds(0, 0, iconPreview.getIntrinsicWidth(),
iconPreview.getIntrinsicHeight());
}
popupCharacters = a.getText(
R.styleable.Keyboard_Key_popupCharacters);
popupResId = a.getResourceId(
R.styleable.Keyboard_Key_popupKeyboard, 0);
repeatable = a.getBoolean(
R.styleable.Keyboard_Key_isRepeatable, false);
modifier = a.getBoolean(
R.styleable.Keyboard_Key_isModifier, false);
sticky = a.getBoolean(
R.styleable.Keyboard_Key_isSticky, false);
isCursor = a.getBoolean(
R.styleable.Keyboard_Key_isCursor, false);
icon = a.getDrawable(
R.styleable.Keyboard_Key_keyIcon);
if (icon != null) {
icon.setBounds(0, 0, icon.getIntrinsicWidth(), icon.getIntrinsicHeight());
}
label = a.getText(R.styleable.Keyboard_Key_keyLabel);
shiftLabel = a.getText(R.styleable.Keyboard_Key_shiftLabel);
if (shiftLabel != null && shiftLabel.length() == 0) shiftLabel = null;
capsLabel = a.getText(R.styleable.Keyboard_Key_capsLabel);
if (capsLabel != null && capsLabel.length() == 0) capsLabel = null;
text = a.getText(R.styleable.Keyboard_Key_keyOutputText);
if (codes == null && !TextUtils.isEmpty(label)) {
codes = getFromString(label);
if (codes != null && codes.length == 1) {
final Locale locale = LatinIME.sKeyboardSettings.inputLocale;
String upperLabel = label.toString().toUpperCase(locale);
if (shiftLabel == null) {
// No shiftLabel supplied, auto-set to uppercase if possible.
if (!upperLabel.equals(label.toString()) && upperLabel.length() == 1) {
shiftLabel = upperLabel;
isSimpleUppercase = true;
}
} else {
// Both label and shiftLabel supplied. Check if
// the shiftLabel is the uppercased normal label.
// If not, treat it as a distinct uppercase variant.
if (capsLabel != null) {
isDistinctUppercase = true;
} else if (upperLabel.equals(shiftLabel.toString())) {
isSimpleUppercase = true;
} else if (upperLabel.length() == 1) {
capsLabel = upperLabel;
isDistinctUppercase = true;
}
}
}
if ((LatinIME.sKeyboardSettings.popupKeyboardFlags & POPUP_DISABLE) != 0) {
popupCharacters = null;
popupResId = 0;
}
if ((LatinIME.sKeyboardSettings.popupKeyboardFlags & POPUP_AUTOREPEAT) != 0) {
// Assume POPUP_DISABLED is set too, otherwise things may get weird.
repeatable = true;
}
}
//Log.i(TAG, "added key definition: " + this);
a.recycle();
}
public boolean isDistinctCaps() {
return isDistinctUppercase && keyboard.isShiftCaps();
}
public boolean isShifted() {
boolean shifted = keyboard.isShifted(isSimpleUppercase);
//Log.i(TAG, "FIXME isShifted=" + shifted + " for " + this);
return shifted;
}
public int getPrimaryCode(boolean isShiftCaps, boolean isShifted) {
if (isDistinctUppercase && isShiftCaps) {
return capsLabel.charAt(0);
}
//Log.i(TAG, "getPrimaryCode(), shifted=" + shifted);
if (isShifted && shiftLabel != null) {
if (shiftLabel.charAt(0) == DEAD_KEY_PLACEHOLDER && shiftLabel.length() >= 2) {
return shiftLabel.charAt(1);
} else {
return shiftLabel.charAt(0);
}
} else {
return codes[0];
}
}
public int getPrimaryCode() {
return getPrimaryCode(keyboard.isShiftCaps(), keyboard.isShifted(isSimpleUppercase));
}
public boolean isDeadKey() {
if (codes == null || codes.length < 1) return false;
return Character.getType(codes[0]) == Character.NON_SPACING_MARK;
}
public int[] getFromString(CharSequence str) {
if (str.length() > 1) {
if (str.charAt(0) == DEAD_KEY_PLACEHOLDER && str.length() >= 2) {
return new int[] { str.charAt(1) }; // FIXME: >1 length?
} else {
text = str; // TODO: add space?
return new int[] { 0 };
}
} else {
char c = str.charAt(0);
return new int[] { c };
}
}
public String getCaseLabel() {
if (isDistinctUppercase && keyboard.isShiftCaps()) {
return capsLabel.toString();
}
boolean isShifted = keyboard.isShifted(isSimpleUppercase);
if (isShifted && shiftLabel != null) {
return shiftLabel.toString();
} else {
return label != null ? label.toString() : null;
}
}
private String getPopupKeyboardContent(boolean isShiftCaps, boolean isShifted, boolean addExtra) {
int mainChar = getPrimaryCode(false, false);
int shiftChar = getPrimaryCode(false, true);
int capsChar = getPrimaryCode(true, true);
// Remove duplicates
if (shiftChar == mainChar) shiftChar = 0;
if (capsChar == shiftChar || capsChar == mainChar) capsChar = 0;
int popupLen = (popupCharacters == null) ? 0 : popupCharacters.length();
StringBuilder popup = new StringBuilder(popupLen);
for (int i = 0; i < popupLen; ++i) {
char c = popupCharacters.charAt(i);
if (isShifted || isShiftCaps) {
String upper = Character.toString(c).toUpperCase(LatinIME.sKeyboardSettings.inputLocale);
if (upper.length() == 1) c = upper.charAt(0);
}
if (c == mainChar || c == shiftChar || c == capsChar) continue;
popup.append(c);
}
if (addExtra) {
StringBuilder extra = new StringBuilder(3 + popup.length());
int flags = LatinIME.sKeyboardSettings.popupKeyboardFlags;
if ((flags & POPUP_ADD_SELF) != 0) {
// if shifted, add unshifted key to extra, and vice versa
if (isDistinctUppercase && isShiftCaps) {
if (capsChar > 0) { extra.append((char) capsChar); capsChar = 0; }
} else if (isShifted) {
if (shiftChar > 0) { extra.append((char) shiftChar); shiftChar = 0; }
} else {
if (mainChar > 0) { extra.append((char) mainChar); mainChar = 0; }
}
}
if ((flags & POPUP_ADD_CASE) != 0) {
// if shifted, add unshifted key to popup, and vice versa
if (isDistinctUppercase && isShiftCaps) {
if (mainChar > 0) { extra.append((char) mainChar); mainChar = 0; }
if (shiftChar > 0) { extra.append((char) shiftChar); shiftChar = 0; }
} else if (isShifted) {
if (mainChar > 0) { extra.append((char) mainChar); mainChar = 0; }
if (capsChar > 0) { extra.append((char) capsChar); capsChar = 0; }
} else {
if (shiftChar > 0) { extra.append((char) shiftChar); shiftChar = 0; }
if (capsChar > 0) { extra.append((char) capsChar); capsChar = 0; }
}
}
if (!isSimpleUppercase && (flags & POPUP_ADD_SHIFT) != 0) {
// if shifted, add unshifted key to popup, and vice versa
if (isShifted) {
if (mainChar > 0) { extra.append((char) mainChar); mainChar = 0; }
} else {
if (shiftChar > 0) { extra.append((char) shiftChar); shiftChar = 0; }
}
}
extra.append(popup);
return extra.toString();
}
return popup.toString();
}
public Keyboard getPopupKeyboard(Context context, int padding) {
if (popupCharacters == null) {
if (popupResId != 0) {
return new Keyboard(context, keyboard.mDefaultHeight, popupResId);
} else {
if (modifier) return null; // Space, Return etc.
}
}
if ((LatinIME.sKeyboardSettings.popupKeyboardFlags & POPUP_DISABLE) != 0) return null;
String popup = getPopupKeyboardContent(keyboard.isShiftCaps(), keyboard.isShifted(isSimpleUppercase), true);
//Log.i(TAG, "getPopupKeyboard: popup='" + popup + "' for " + this);
if (popup.length() > 0) {
int resId = popupResId;
if (resId == 0) resId = R.xml.kbd_popup_template;
return new Keyboard(context, keyboard.mDefaultHeight, resId, popup, popupReversed, -1, padding);
} else {
return null;
}
}
public String getHintLabel(boolean wantAscii, boolean wantAll) {
if (hint == null) {
hint = "";
if (shiftLabel != null && !isSimpleUppercase) {
char c = shiftLabel.charAt(0);
if (wantAll || wantAscii && is7BitAscii(c)) {
hint = Character.toString(c);
}
}
}
return hint;
}
public String getAltHintLabel(boolean wantAscii, boolean wantAll) {
if (altHint == null) {
altHint = "";
String popup = getPopupKeyboardContent(false, false, false);
if (popup.length() > 0) {
char c = popup.charAt(0);
if (wantAll || wantAscii && is7BitAscii(c)) {
altHint = Character.toString(c);
}
}
}
return altHint;
}
private static boolean is7BitAscii(char c) {
if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')) return false;
return c >= 32 && c < 127;
}
/**
* Informs the key that it has been pressed, in case it needs to change its appearance or
* state.
* @see #onReleased(boolean)
*/
public void onPressed() {
pressed = !pressed;
}
/**
* Changes the pressed state of the key. Sticky key indicators are handled explicitly elsewhere.
* @param inside whether the finger was released inside the key
* @see #onPressed()
*/
public void onReleased(boolean inside) {
pressed = !pressed;
}
int[] parseCSV(String value) {
int count = 0;
int lastIndex = 0;
if (value.length() > 0) {
count++;
while ((lastIndex = value.indexOf(",", lastIndex + 1)) > 0) {
count++;
}
}
int[] values = new int[count];
count = 0;
StringTokenizer st = new StringTokenizer(value, ",");
while (st.hasMoreTokens()) {
try {
values[count++] = Integer.parseInt(st.nextToken());
} catch (NumberFormatException nfe) {
Log.e(TAG, "Error parsing keycodes " + value);
}
}
return values;
}
/**
* Detects if a point falls inside this key.
* @param x the x-coordinate of the point
* @param y the y-coordinate of the point
* @return whether or not the point falls inside the key. If the key is attached to an edge,
* it will assume that all points between the key and the edge are considered to be inside
* the key.
*/
public boolean isInside(int x, int y) {
boolean leftEdge = (edgeFlags & EDGE_LEFT) > 0;
boolean rightEdge = (edgeFlags & EDGE_RIGHT) > 0;
boolean topEdge = (edgeFlags & EDGE_TOP) > 0;
boolean bottomEdge = (edgeFlags & EDGE_BOTTOM) > 0;
if ((x >= this.x || (leftEdge && x <= this.x + this.width))
&& (x < this.x + this.width || (rightEdge && x >= this.x))
&& (y >= this.y || (topEdge && y <= this.y + this.height))
&& (y < this.y + this.height || (bottomEdge && y >= this.y))) {
return true;
} else {
return false;
}
}
/**
* Returns the square of the distance between the center of the key and the given point.
* @param x the x-coordinate of the point
* @param y the y-coordinate of the point
* @return the square of the distance of the point from the center of the key
*/
public int squaredDistanceFrom(int x, int y) {
int xDist = this.x + width / 2 - x;
int yDist = this.y + height / 2 - y;
return xDist * xDist + yDist * yDist;
}
/**
* Returns the drawable state for the key, based on the current state and type of the key.
* @return the drawable state of the key.
* @see android.graphics.drawable.StateListDrawable#setState(int[])
*/
public int[] getCurrentDrawableState() {
int[] states = KEY_STATE_NORMAL;
if (locked) {
if (pressed) {
states = KEY_STATE_PRESSED_LOCK;
} else {
states = KEY_STATE_NORMAL_LOCK;
}
} else if (on) {
if (pressed) {
states = KEY_STATE_PRESSED_ON;
} else {
states = KEY_STATE_NORMAL_ON;
}
} else {
if (sticky) {
if (pressed) {
states = KEY_STATE_PRESSED_OFF;
} else {
states = KEY_STATE_NORMAL_OFF;
}
} else {
if (pressed) {
states = KEY_STATE_PRESSED;
}
}
}
return states;
}
public String toString() {
int code = (codes != null && codes.length > 0) ? codes[0] : 0;
String edges = (
((edgeFlags & Keyboard.EDGE_LEFT) != 0 ? "L" : "-") +
((edgeFlags & Keyboard.EDGE_RIGHT) != 0 ? "R" : "-") +
((edgeFlags & Keyboard.EDGE_TOP) != 0 ? "T" : "-") +
((edgeFlags & Keyboard.EDGE_BOTTOM) != 0 ? "B" : "-"));
return "KeyDebugFIXME(label=" + label +
(shiftLabel != null ? " shift=" + shiftLabel : "") +
(capsLabel != null ? " caps=" + capsLabel : "") +
(text != null ? " text=" + text : "" ) +
" code=" + code +
(code <= 0 || Character.isWhitespace(code) ? "" : ":'" + (char)code + "'" ) +
" x=" + x + ".." + (x+width) + " y=" + y + ".." + (y+height) +
" edgeFlags=" + edges +
(popupCharacters != null ? " pop=" + popupCharacters : "" ) +
" res=" + popupResId +
")";
}
}
/**
* Creates a keyboard from the given xml key layout file.
* @param context the application or service context
* @param xmlLayoutResId the resource file that contains the keyboard layout and keys.
*/
public Keyboard(Context context, int defaultHeight, int xmlLayoutResId) {
this(context, defaultHeight, xmlLayoutResId, 0);
}
public Keyboard(Context context, int defaultHeight, int xmlLayoutResId, int modeId) {
this(context, defaultHeight, xmlLayoutResId, modeId, 0);
}
/**
* Creates a keyboard from the given xml key layout file. Weeds out rows
* that have a keyboard mode defined but don't match the specified mode.
* @param context the application or service context
* @param xmlLayoutResId the resource file that contains the keyboard layout and keys.
* @param modeId keyboard mode identifier
* @param rowHeightPercent height of each row as percentage of screen height
*/
public Keyboard(Context context, int defaultHeight, int xmlLayoutResId, int modeId, float kbHeightPercent) {
DisplayMetrics dm = context.getResources().getDisplayMetrics();
mDisplayWidth = dm.widthPixels;
mDisplayHeight = dm.heightPixels;
Log.v(TAG, "keyboard's display metrics:" + dm + ", mDisplayWidth=" + mDisplayWidth);
mDefaultHorizontalGap = 0;
mDefaultWidth = mDisplayWidth / 10;
mDefaultVerticalGap = 0;
mDefaultHeight = defaultHeight; // may be zero, to be adjusted below
mKeyboardHeight = Math.round(mDisplayHeight * kbHeightPercent / 100);
//Log.i("PCKeyboard", "mDefaultHeight=" + mDefaultHeight + "(arg=" + defaultHeight + ")" + " kbHeight=" + mKeyboardHeight + " displayHeight="+mDisplayHeight+")");
mKeys = new ArrayList<Key>();
mModifierKeys = new ArrayList<Key>();
mKeyboardMode = modeId;
mUseExtension = LatinIME.sKeyboardSettings.useExtension;
loadKeyboard(context, context.getResources().getXml(xmlLayoutResId));
setEdgeFlags();
fixAltChars(LatinIME.sKeyboardSettings.inputLocale);
}
/**
* <p>Creates a blank keyboard from the given resource file and populates it with the specified
* characters in left-to-right, top-to-bottom fashion, using the specified number of columns.
* </p>
* <p>If the specified number of columns is -1, then the keyboard will fit as many keys as
* possible in each row.</p>
* @param context the application or service context
* @param layoutTemplateResId the layout template file, containing no keys.
* @param characters the list of characters to display on the keyboard. One key will be created
* for each character.
* @param columns the number of columns of keys to display. If this number is greater than the
* number of keys that can fit in a row, it will be ignored. If this number is -1, the
* keyboard will fit as many keys as possible in each row.
*/
private Keyboard(Context context, int defaultHeight, int layoutTemplateResId,
CharSequence characters, boolean reversed, int columns, int horizontalPadding) {
this(context, defaultHeight, layoutTemplateResId);
int x = 0;
int y = 0;
int column = 0;
mTotalWidth = 0;
Row row = new Row(this);
row.defaultHeight = mDefaultHeight;
row.defaultWidth = mDefaultWidth;
row.defaultHorizontalGap = mDefaultHorizontalGap;
row.verticalGap = mDefaultVerticalGap;
final int maxColumns = columns == -1 ? Integer.MAX_VALUE : columns;
mLayoutRows = 1;
int start = reversed ? characters.length()-1 : 0;
int end = reversed ? -1 : characters.length();
int step = reversed ? -1 : 1;
for (int i = start; i != end; i+=step) {
char c = characters.charAt(i);
if (column >= maxColumns
|| x + mDefaultWidth + horizontalPadding > mDisplayWidth) {
x = 0;
y += mDefaultVerticalGap + mDefaultHeight;
column = 0;
++mLayoutRows;
}
final Key key = new Key(row);
key.x = x;
key.realX = x;
key.y = y;
key.label = String.valueOf(c);
key.codes = key.getFromString(key.label);
column++;
x += key.width + key.gap;
mKeys.add(key);
if (x > mTotalWidth) {
mTotalWidth = x;
}
}
mTotalHeight = y + mDefaultHeight;
mLayoutColumns = columns == -1 ? column : maxColumns;
setEdgeFlags();
}
private void setEdgeFlags() {
if (mRowCount == 0) mRowCount = 1; // Assume one row if not set
int row = 0;
Key prevKey = null;
int rowFlags = 0;
for (Key key : mKeys) {
int keyFlags = 0;
if (prevKey == null || key.x <= prevKey.x) {
// Start new row.
if (prevKey != null) {
// Add "right edge" to rightmost key of previous row.
// Need to do the last key separately below.
prevKey.edgeFlags |= Keyboard.EDGE_RIGHT;
}
// Set the row flags for the current row.
rowFlags = 0;
if (row == 0) rowFlags |= Keyboard.EDGE_TOP;
if (row == mRowCount - 1) rowFlags |= Keyboard.EDGE_BOTTOM;
++row;
// Mark current key as "left edge"
keyFlags |= Keyboard.EDGE_LEFT;
}
key.edgeFlags = rowFlags | keyFlags;
prevKey = key;
}
// Fix up the last key
if (prevKey != null) prevKey.edgeFlags |= Keyboard.EDGE_RIGHT;
// Log.i(TAG, "setEdgeFlags() done:");
// for (Key key : mKeys) {
// Log.i(TAG, "key=" + key);
// }
}
private void fixAltChars(Locale locale) {
if (locale == null) locale = Locale.getDefault();
Set<Character> mainKeys = new HashSet<Character>();
for (Key key : mKeys) {
// Remember characters on the main keyboard so that they can be removed from popups.
// This makes it easy to share popup char maps between the normal and shifted
// keyboards.
if (key.label != null && !key.modifier && key.label.length() == 1) {
char c = key.label.charAt(0);
mainKeys.add(c);
}
}
for (Key key : mKeys) {
if (key.popupCharacters == null) continue;
int popupLen = key.popupCharacters.length();
if (popupLen == 0) {
continue;
}
if (key.x >= mTotalWidth / 2) {
key.popupReversed = true;
}
// Uppercase the alt chars if the main key is uppercase
boolean needUpcase = key.label != null && key.label.length() == 1 && Character.isUpperCase(key.label.charAt(0));
if (needUpcase) {
key.popupCharacters = key.popupCharacters.toString().toUpperCase();
popupLen = key.popupCharacters.length();
}
StringBuilder newPopup = new StringBuilder(popupLen);
for (int i = 0; i < popupLen; ++i) {
char c = key.popupCharacters.charAt(i);
if (Character.isDigit(c) && mainKeys.contains(c)) continue; // already present elsewhere
// Skip extra digit alt keys on 5-row keyboards
if ((key.edgeFlags & EDGE_TOP) == 0 && Character.isDigit(c)) continue;
newPopup.append(c);
}
//Log.i("PCKeyboard", "popup for " + key.label + " '" + key.popupCharacters + "' => '"+ newPopup + "' length " + newPopup.length());
key.popupCharacters = newPopup.toString();
}
}
public List<Key> getKeys() {
return mKeys;
}
public List<Key> getModifierKeys() {
return mModifierKeys;
}
protected int getHorizontalGap() {
return Math.round(mDefaultHorizontalGap);
}
protected void setHorizontalGap(int gap) {
mDefaultHorizontalGap = gap;
}
protected int getVerticalGap() {
return mDefaultVerticalGap;
}
protected void setVerticalGap(int gap) {
mDefaultVerticalGap = gap;
}
protected int getKeyHeight() {
return mDefaultHeight;
}
protected void setKeyHeight(int height) {
mDefaultHeight = height;
}
protected int getKeyWidth() {
return Math.round(mDefaultWidth);
}
protected void setKeyWidth(int width) {
mDefaultWidth = width;
}
/**
* Returns the total height of the keyboard
* @return the total height of the keyboard
*/
public int getHeight() {
return mTotalHeight;
}
public int getScreenHeight() {
return mDisplayHeight;
}
public int getMinWidth() {
return mTotalWidth;
}
public boolean setShiftState(int shiftState, boolean updateKey) {
//Log.i(TAG, "setShiftState " + mShiftState + " -> " + shiftState);
if (updateKey && mShiftKey != null) {
mShiftKey.on = (shiftState != SHIFT_OFF);
}
if (mShiftState != shiftState) {
mShiftState = shiftState;
return true;
}
return false;
}
public boolean setShiftState(int shiftState) {
return setShiftState(shiftState, true);
}
public Key setCtrlIndicator(boolean active) {
//Log.i(TAG, "setCtrlIndicator " + active + " ctrlKey=" + mCtrlKey);
if (mCtrlKey != null) mCtrlKey.on = active;
return mCtrlKey;
}
public Key setAltIndicator(boolean active) {
if (mAltKey != null) mAltKey.on = active;
return mAltKey;
}
public Key setMetaIndicator(boolean active) {
if (mMetaKey != null) mMetaKey.on = active;
return mMetaKey;
}
public boolean isShiftCaps() {
return mShiftState == SHIFT_CAPS || mShiftState == SHIFT_CAPS_LOCKED;
}
public boolean isShifted(boolean applyCaps) {
if (applyCaps) {
return mShiftState != SHIFT_OFF;
} else {
return mShiftState == SHIFT_ON || mShiftState == SHIFT_LOCKED;
}
}
public int getShiftState() {
return mShiftState;
}
public int getShiftKeyIndex() {
return mShiftKeyIndex;
}
private void computeNearestNeighbors() {
// Round-up so we don't have any pixels outside the grid
mCellWidth = (getMinWidth() + mLayoutColumns - 1) / mLayoutColumns;
mCellHeight = (getHeight() + mLayoutRows - 1) / mLayoutRows;
mGridNeighbors = new int[mLayoutColumns * mLayoutRows][];
int[] indices = new int[mKeys.size()];
final int gridWidth = mLayoutColumns * mCellWidth;
final int gridHeight = mLayoutRows * mCellHeight;
for (int x = 0; x < gridWidth; x += mCellWidth) {
for (int y = 0; y < gridHeight; y += mCellHeight) {
int count = 0;
for (int i = 0; i < mKeys.size(); i++) {
final Key key = mKeys.get(i);
boolean isSpace = key.codes != null && key.codes.length > 0 &&
key.codes[0] == LatinIME.ASCII_SPACE;
if (key.squaredDistanceFrom(x, y) < mProximityThreshold ||
key.squaredDistanceFrom(x + mCellWidth - 1, y) < mProximityThreshold ||
key.squaredDistanceFrom(x + mCellWidth - 1, y + mCellHeight - 1)
< mProximityThreshold ||
key.squaredDistanceFrom(x, y + mCellHeight - 1) < mProximityThreshold ||
isSpace && !(
x + mCellWidth - 1 < key.x ||
x > key.x + key.width ||
y + mCellHeight - 1 < key.y ||
y > key.y + key.height)) {
//if (isSpace) Log.i(TAG, "space at grid" + x + "," + y);
indices[count++] = i;
}
}
int [] cell = new int[count];
System.arraycopy(indices, 0, cell, 0, count);
mGridNeighbors[(y / mCellHeight) * mLayoutColumns + (x / mCellWidth)] = cell;
}
}
}
/**
* Returns the indices of the keys that are closest to the given point.
* @param x the x-coordinate of the point
* @param y the y-coordinate of the point
* @return the array of integer indices for the nearest keys to the given point. If the given
* point is out of range, then an array of size zero is returned.
*/
public int[] getNearestKeys(int x, int y) {
if (mGridNeighbors == null) computeNearestNeighbors();
if (x >= 0 && x < getMinWidth() && y >= 0 && y < getHeight()) {
int index = (y / mCellHeight) * mLayoutColumns + (x / mCellWidth);
if (index < mLayoutRows * mLayoutColumns) {
return mGridNeighbors[index];
}
}
return new int[0];
}
protected Row createRowFromXml(Resources res, XmlResourceParser parser) {
return new Row(res, this, parser);
}
protected Key createKeyFromXml(Resources res, Row parent, int x, int y,
XmlResourceParser parser) {
return new Key(res, parent, x, y, parser);
}
private void loadKeyboard(Context context, XmlResourceParser parser) {
boolean inKey = false;
boolean inRow = false;
float x = 0;
int y = 0;
Key key = null;
Row currentRow = null;
Resources res = context.getResources();
boolean skipRow = false;
mRowCount = 0;
try {
int event;
Key prevKey = null;
while ((event = parser.next()) != XmlResourceParser.END_DOCUMENT) {
if (event == XmlResourceParser.START_TAG) {
String tag = parser.getName();
if (TAG_ROW.equals(tag)) {
inRow = true;
x = 0;
currentRow = createRowFromXml(res, parser);
skipRow = currentRow.mode != 0 && currentRow.mode != mKeyboardMode;
if (currentRow.extension) {
if (mUseExtension) {
++mExtensionRowCount;
} else {
skipRow = true;
}
}
if (skipRow) {
skipToEndOfRow(parser);
inRow = false;
}
} else if (TAG_KEY.equals(tag)) {
inKey = true;
key = createKeyFromXml(res, currentRow, Math.round(x), y, parser);
key.realX = x;
if (key.codes == null) {
// skip this key, adding its width to the previous one
if (prevKey != null) {
prevKey.width += key.width;
}
} else {
mKeys.add(key);
prevKey = key;
if (key.codes[0] == KEYCODE_SHIFT) {
if (mShiftKeyIndex == -1) {
mShiftKey = key;
mShiftKeyIndex = mKeys.size()-1;
}
mModifierKeys.add(key);
} else if (key.codes[0] == KEYCODE_ALT_SYM) {
mModifierKeys.add(key);
} else if (key.codes[0] == LatinKeyboardView.KEYCODE_CTRL_LEFT) {
mCtrlKey = key;
} else if (key.codes[0] == LatinKeyboardView.KEYCODE_ALT_LEFT) {
mAltKey = key;
} else if (key.codes[0] == LatinKeyboardView.KEYCODE_META_LEFT) {
mMetaKey = key;
}
}
} else if (TAG_KEYBOARD.equals(tag)) {
parseKeyboardAttributes(res, parser);
}
} else if (event == XmlResourceParser.END_TAG) {
if (inKey) {
inKey = false;
x += key.realGap + key.realWidth;
if (x > mTotalWidth) {
mTotalWidth = Math.round(x);
}
} else if (inRow) {
inRow = false;
y += currentRow.verticalGap;
y += currentRow.defaultHeight;
mRowCount++;
} else {
// TODO: error or extend?
}
}
}
} catch (Exception e) {
Log.e(TAG, "Parse error:" + e);
e.printStackTrace();
}
mTotalHeight = y - mDefaultVerticalGap;
}
public void setKeyboardWidth(int newWidth) {
Log.i(TAG, "setKeyboardWidth newWidth=" + newWidth + ", mTotalWidth=" + mTotalWidth);
if (newWidth <= 0) return; // view not initialized?
if (mTotalWidth <= newWidth) return; // it already fits
float scale = (float) newWidth / mDisplayWidth;
Log.i("PCKeyboard", "Rescaling keyboard: " + mTotalWidth + " => " + newWidth);
for (Key key : mKeys) {
key.x = Math.round(key.realX * scale);
}
mTotalWidth = newWidth;
}
private void skipToEndOfRow(XmlResourceParser parser)
throws XmlPullParserException, IOException {
int event;
while ((event = parser.next()) != XmlResourceParser.END_DOCUMENT) {
if (event == XmlResourceParser.END_TAG
&& parser.getName().equals(TAG_ROW)) {
break;
}
}
}
private void parseKeyboardAttributes(Resources res, XmlResourceParser parser) {
TypedArray a = res.obtainAttributes(Xml.asAttributeSet(parser),
R.styleable.Keyboard);
mDefaultWidth = getDimensionOrFraction(a,
R.styleable.Keyboard_keyWidth,
mDisplayWidth, mDisplayWidth / 10);
mDefaultHeight = Math.round(getDimensionOrFraction(a,
R.styleable.Keyboard_keyHeight,
mDisplayHeight, mDefaultHeight));
mDefaultHorizontalGap = getDimensionOrFraction(a,
R.styleable.Keyboard_horizontalGap,
mDisplayWidth, 0);
mDefaultVerticalGap = Math.round(getDimensionOrFraction(a,
R.styleable.Keyboard_verticalGap,
mDisplayHeight, 0));
mHorizontalPad = getDimensionOrFraction(a,
R.styleable.Keyboard_horizontalPad,
mDisplayWidth, res.getDimension(R.dimen.key_horizontal_pad));
mVerticalPad = getDimensionOrFraction(a,
R.styleable.Keyboard_verticalPad,
mDisplayHeight, res.getDimension(R.dimen.key_vertical_pad));
mLayoutRows = a.getInteger(R.styleable.Keyboard_layoutRows, DEFAULT_LAYOUT_ROWS);
mLayoutColumns = a.getInteger(R.styleable.Keyboard_layoutColumns, DEFAULT_LAYOUT_COLUMNS);
if (mDefaultHeight == 0 && mKeyboardHeight > 0 && mLayoutRows > 0) {
mDefaultHeight = mKeyboardHeight / mLayoutRows;
//Log.i(TAG, "got mLayoutRows=" + mLayoutRows + ", mDefaultHeight=" + mDefaultHeight);
}
mProximityThreshold = (int) (mDefaultWidth * SEARCH_DISTANCE);
mProximityThreshold = mProximityThreshold * mProximityThreshold; // Square it for comparison
a.recycle();
}
static float getDimensionOrFraction(TypedArray a, int index, int base, float defValue) {
TypedValue value = a.peekValue(index);
if (value == null) return defValue;
if (value.type == TypedValue.TYPE_DIMENSION) {
return a.getDimensionPixelOffset(index, Math.round(defValue));
} else if (value.type == TypedValue.TYPE_FRACTION) {
// Round it to avoid values like 47.9999 from getting truncated
//return Math.round(a.getFraction(index, base, base, defValue));
return a.getFraction(index, base, base, defValue);
}
return defValue;
}
@Override
public String toString() {
return "Keyboard(" + mLayoutColumns + "x" + mLayoutRows +
" keys=" + mKeys.size() +
" rowCount=" + mRowCount +
" mode=" + mKeyboardMode +
" size=" + mTotalWidth + "x" + mTotalHeight +
")";
}
}
| 11beeaosama-descrbvbnvbniption | java/src/org/pocketworkstation/pckeyboard/Keyboard.java | Java | asf20 | 53,837 |
/*
* Copyright (C) 2011 Darren Salt
*
* Licensed under the Apache License, Version 2.0 (the "Licence"); you may
* not use this file except in compliance with the Licence. You may obtain
* a copy of the Licence at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the Licence is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* Licence for the specific language governing permissions and limitations
* under the Licence.
*/
package org.pocketworkstation.pckeyboard;
import android.inputmethodservice.InputMethodService;
import android.util.Log;
import android.view.inputmethod.EditorInfo;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
interface ComposeSequencing {
public void onText(CharSequence text);
public void updateShiftKeyState(EditorInfo attr);
public EditorInfo getCurrentInputEditorInfo();
}
public abstract class ComposeBase {
private static final String TAG = "HK/ComposeBase";
protected static final Map<String, String> mMap =
new HashMap<String, String>();
protected static final Set<String> mPrefixes =
new HashSet<String>();
protected static String get(String key) {
if (key == null || key.length() == 0) {
return null;
}
//Log.i(TAG, "ComposeBase get, key=" + showString(key) + " result=" + mMap.get(key));
return mMap.get(key);
}
private static String showString(String in) {
// TODO Auto-generated method stub
StringBuilder out = new StringBuilder(in);
out.append("{");
for (int i = 0; i < in.length(); ++i) {
if (i > 0) out.append(",");
out.append((int) in.charAt(i));
}
out.append("}");
return out.toString();
}
private static boolean isValid(String partialKey) {
if (partialKey == null || partialKey.length() == 0) {
return false;
}
return mPrefixes.contains(partialKey);
}
protected static void put(String key, String value) {
mMap.put(key, value);
for (int i = 1; i < key.length(); ++i) {
mPrefixes.add(key.substring(0, i));
}
}
protected StringBuilder composeBuffer = new StringBuilder(10);
protected ComposeSequencing composeUser;
protected void init(ComposeSequencing user) {
clear();
composeUser = user;
}
public void clear() {
composeBuffer.setLength(0);
}
public void bufferKey(char code) {
composeBuffer.append(code);
//Log.i(TAG, "bufferKey code=" + (int) code + " => " + showString(composeBuffer.toString()));
}
// returns true if the compose sequence is valid but incomplete
public String executeToString(int code) {
KeyboardSwitcher ks = KeyboardSwitcher.getInstance();
if (ks.getInputView().isShiftCaps()
&& ks.isAlphabetMode()
&& Character.isLowerCase(code)) {
code = Character.toUpperCase(code);
}
bufferKey((char) code);
composeUser.updateShiftKeyState(composeUser.getCurrentInputEditorInfo());
String composed = get(composeBuffer.toString());
if (composed != null) {
// If we get here, we have a complete compose sequence
return composed;
} else if (!isValid(composeBuffer.toString())) {
// If we get here, then the sequence typed isn't recognised
return "";
}
return null;
}
public boolean execute(int code) {
String composed = executeToString(code);
if (composed != null) {
clear();
composeUser.onText(composed);
return false;
}
return true;
}
public boolean execute(CharSequence sequence) {
int i, len = sequence.length();
boolean result = true;
for (i = 0; i < len; ++i) {
result = execute(sequence.charAt(i));
}
return result; // only last one matters
}
}
| 11beeaosama-descrbvbnvbniption | java/src/org/pocketworkstation/pckeyboard/ComposeBase.java | Java | asf20 | 4,179 |
/*
* Copyright (C) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import java.util.HashMap;
import java.util.Set;
import java.util.Map.Entry;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.os.AsyncTask;
import android.provider.BaseColumns;
import android.util.Log;
/**
* Stores new words temporarily until they are promoted to the user dictionary
* for longevity. Words in the auto dictionary are used to determine if it's ok
* to accept a word that's not in the main or user dictionary. Using a new word
* repeatedly will promote it to the user dictionary.
*/
public class AutoDictionary extends ExpandableDictionary {
// Weight added to a user picking a new word from the suggestion strip
static final int FREQUENCY_FOR_PICKED = 3;
// Weight added to a user typing a new word that doesn't get corrected (or is reverted)
static final int FREQUENCY_FOR_TYPED = 1;
// A word that is frequently typed and gets promoted to the user dictionary, uses this
// frequency.
static final int FREQUENCY_FOR_AUTO_ADD = 250;
// If the user touches a typed word 2 times or more, it will become valid.
private static final int VALIDITY_THRESHOLD = 2 * FREQUENCY_FOR_PICKED;
// If the user touches a typed word 4 times or more, it will be added to the user dict.
private static final int PROMOTION_THRESHOLD = 4 * FREQUENCY_FOR_PICKED;
private LatinIME mIme;
// Locale for which this auto dictionary is storing words
private String mLocale;
private HashMap<String,Integer> mPendingWrites = new HashMap<String,Integer>();
private final Object mPendingWritesLock = new Object();
private static final String DATABASE_NAME = "auto_dict.db";
private static final int DATABASE_VERSION = 1;
// These are the columns in the dictionary
// TODO: Consume less space by using a unique id for locale instead of the whole
// 2-5 character string.
private static final String COLUMN_ID = BaseColumns._ID;
private static final String COLUMN_WORD = "word";
private static final String COLUMN_FREQUENCY = "freq";
private static final String COLUMN_LOCALE = "locale";
/** Sort by descending order of frequency. */
public static final String DEFAULT_SORT_ORDER = COLUMN_FREQUENCY + " DESC";
/** Name of the words table in the auto_dict.db */
private static final String AUTODICT_TABLE_NAME = "words";
private static HashMap<String, String> sDictProjectionMap;
static {
sDictProjectionMap = new HashMap<String, String>();
sDictProjectionMap.put(COLUMN_ID, COLUMN_ID);
sDictProjectionMap.put(COLUMN_WORD, COLUMN_WORD);
sDictProjectionMap.put(COLUMN_FREQUENCY, COLUMN_FREQUENCY);
sDictProjectionMap.put(COLUMN_LOCALE, COLUMN_LOCALE);
}
private static DatabaseHelper sOpenHelper = null;
public AutoDictionary(Context context, LatinIME ime, String locale, int dicTypeId) {
super(context, dicTypeId);
mIme = ime;
mLocale = locale;
if (sOpenHelper == null) {
sOpenHelper = new DatabaseHelper(getContext());
}
if (mLocale != null && mLocale.length() > 1) {
loadDictionary();
}
}
@Override
public boolean isValidWord(CharSequence word) {
final int frequency = getWordFrequency(word);
return frequency >= VALIDITY_THRESHOLD;
}
@Override
public void close() {
flushPendingWrites();
// Don't close the database as locale changes will require it to be reopened anyway
// Also, the database is written to somewhat frequently, so it needs to be kept alive
// throughout the life of the process.
// mOpenHelper.close();
super.close();
}
@Override
public void loadDictionaryAsync() {
// Load the words that correspond to the current input locale
Cursor cursor = query(COLUMN_LOCALE + "=?", new String[] { mLocale });
try {
if (cursor.moveToFirst()) {
int wordIndex = cursor.getColumnIndex(COLUMN_WORD);
int frequencyIndex = cursor.getColumnIndex(COLUMN_FREQUENCY);
while (!cursor.isAfterLast()) {
String word = cursor.getString(wordIndex);
int frequency = cursor.getInt(frequencyIndex);
// Safeguard against adding really long words. Stack may overflow due
// to recursive lookup
if (word.length() < getMaxWordLength()) {
super.addWord(word, frequency);
}
cursor.moveToNext();
}
}
} finally {
cursor.close();
}
}
@Override
public void addWord(String word, int addFrequency) {
final int length = word.length();
// Don't add very short or very long words.
if (length < 2 || length > getMaxWordLength()) return;
if (mIme.getCurrentWord().isAutoCapitalized()) {
// Remove caps before adding
word = Character.toLowerCase(word.charAt(0)) + word.substring(1);
}
int freq = getWordFrequency(word);
freq = freq < 0 ? addFrequency : freq + addFrequency;
super.addWord(word, freq);
if (freq >= PROMOTION_THRESHOLD) {
mIme.promoteToUserDictionary(word, FREQUENCY_FOR_AUTO_ADD);
freq = 0;
}
synchronized (mPendingWritesLock) {
// Write a null frequency if it is to be deleted from the db
mPendingWrites.put(word, freq == 0 ? null : new Integer(freq));
}
}
/**
* Schedules a background thread to write any pending words to the database.
*/
public void flushPendingWrites() {
synchronized (mPendingWritesLock) {
// Nothing pending? Return
if (mPendingWrites.isEmpty()) return;
// Create a background thread to write the pending entries
new UpdateDbTask(getContext(), sOpenHelper, mPendingWrites, mLocale).execute();
// Create a new map for writing new entries into while the old one is written to db
mPendingWrites = new HashMap<String, Integer>();
}
}
/**
* This class helps open, create, and upgrade the database file.
*/
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + AUTODICT_TABLE_NAME + " ("
+ COLUMN_ID + " INTEGER PRIMARY KEY,"
+ COLUMN_WORD + " TEXT,"
+ COLUMN_FREQUENCY + " INTEGER,"
+ COLUMN_LOCALE + " TEXT"
+ ");");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w("AutoDictionary", "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + AUTODICT_TABLE_NAME);
onCreate(db);
}
}
private Cursor query(String selection, String[] selectionArgs) {
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(AUTODICT_TABLE_NAME);
qb.setProjectionMap(sDictProjectionMap);
// Get the database and run the query
SQLiteDatabase db = sOpenHelper.getReadableDatabase();
Cursor c = qb.query(db, null, selection, selectionArgs, null, null,
DEFAULT_SORT_ORDER);
return c;
}
/**
* Async task to write pending words to the database so that it stays in sync with
* the in-memory trie.
*/
private static class UpdateDbTask extends AsyncTask<Void, Void, Void> {
private final HashMap<String, Integer> mMap;
private final DatabaseHelper mDbHelper;
private final String mLocale;
public UpdateDbTask(Context context, DatabaseHelper openHelper,
HashMap<String, Integer> pendingWrites, String locale) {
mMap = pendingWrites;
mLocale = locale;
mDbHelper = openHelper;
}
@Override
protected Void doInBackground(Void... v) {
SQLiteDatabase db = mDbHelper.getWritableDatabase();
// Write all the entries to the db
Set<Entry<String,Integer>> mEntries = mMap.entrySet();
for (Entry<String,Integer> entry : mEntries) {
Integer freq = entry.getValue();
db.delete(AUTODICT_TABLE_NAME, COLUMN_WORD + "=? AND " + COLUMN_LOCALE + "=?",
new String[] { entry.getKey(), mLocale });
if (freq != null) {
db.insert(AUTODICT_TABLE_NAME, null,
getContentValues(entry.getKey(), freq, mLocale));
}
}
return null;
}
private ContentValues getContentValues(String word, int frequency, String locale) {
ContentValues values = new ContentValues(4);
values.put(COLUMN_WORD, word);
values.put(COLUMN_FREQUENCY, frequency);
values.put(COLUMN_LOCALE, locale);
return values;
}
}
}
| 11beeaosama-descrbvbnvbniption | java/src/org/pocketworkstation/pckeyboard/AutoDictionary.java | Java | asf20 | 10,249 |
package org.pocketworkstation.pckeyboard;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.xmlpull.v1.XmlPullParserException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources;
import android.content.res.XmlResourceParser;
import android.util.Log;
public class PluginManager extends BroadcastReceiver {
private static String TAG = "PCKeyboard";
private static String HK_INTENT_DICT = "org.pocketworkstation.DICT";
private static String SOFTKEYBOARD_INTENT_DICT = "com.menny.android.anysoftkeyboard.DICTIONARY";
private LatinIME mIME;
// Apparently anysoftkeyboard doesn't use ISO 639-1 language codes for its locales?
// Add exceptions as needed.
private static Map<String, String> SOFTKEYBOARD_LANG_MAP = new HashMap<String, String>();
static {
SOFTKEYBOARD_LANG_MAP.put("dk", "da");
}
PluginManager(LatinIME ime) {
super();
mIME = ime;
}
private static Map<String, DictPluginSpec> mPluginDicts =
new HashMap<String, DictPluginSpec>();
static interface DictPluginSpec {
BinaryDictionary getDict(Context context);
}
static private abstract class DictPluginSpecBase
implements DictPluginSpec {
String mPackageName;
Resources getResources(Context context) {
PackageManager packageManager = context.getPackageManager();
Resources res = null;
try {
ApplicationInfo appInfo = packageManager.getApplicationInfo(mPackageName, 0);
res = packageManager.getResourcesForApplication(appInfo);
} catch (NameNotFoundException e) {
Log.i(TAG, "couldn't get resources");
}
return res;
}
abstract InputStream[] getStreams(Resources res);
public BinaryDictionary getDict(Context context) {
Resources res = getResources(context);
if (res == null) return null;
InputStream[] dicts = getStreams(res);
if (dicts == null) return null;
BinaryDictionary dict = new BinaryDictionary(
context, dicts, Suggest.DIC_MAIN);
if (dict.getSize() == 0) return null;
//Log.i(TAG, "dict size=" + dict.getSize());
return dict;
}
}
static private class DictPluginSpecHK
extends DictPluginSpecBase {
int[] mRawIds;
public DictPluginSpecHK(String pkg, int[] ids) {
mPackageName = pkg;
mRawIds = ids;
}
@Override
InputStream[] getStreams(Resources res) {
if (mRawIds == null || mRawIds.length == 0) return null;
InputStream[] streams = new InputStream[mRawIds.length];
for (int i = 0; i < mRawIds.length; ++i) {
streams[i] = res.openRawResource(mRawIds[i]);
}
return streams;
}
}
static private class DictPluginSpecSoftKeyboard
extends DictPluginSpecBase {
String mAssetName;
public DictPluginSpecSoftKeyboard(String pkg, String asset) {
mPackageName = pkg;
mAssetName = asset;
}
@Override
InputStream[] getStreams(Resources res) {
if (mAssetName == null) return null;
try {
InputStream in = res.getAssets().open(mAssetName);
return new InputStream[] {in};
} catch (IOException e) {
Log.e(TAG, "Dictionary asset loading failure");
return null;
}
}
}
@Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "Package information changed, updating dictionaries.");
getPluginDictionaries(context);
Log.i(TAG, "Finished updating dictionaries.");
mIME.toggleLanguage(true, true);
}
static void getSoftKeyboardDictionaries(PackageManager packageManager) {
Intent dictIntent = new Intent(SOFTKEYBOARD_INTENT_DICT);
List<ResolveInfo> dictPacks = packageManager.queryBroadcastReceivers(
dictIntent, PackageManager.GET_RECEIVERS);
for (ResolveInfo ri : dictPacks) {
ApplicationInfo appInfo = ri.activityInfo.applicationInfo;
String pkgName = appInfo.packageName;
boolean success = false;
try {
Resources res = packageManager.getResourcesForApplication(appInfo);
//Log.i(TAG, "Found dictionary plugin package: " + pkgName);
int dictId = res.getIdentifier("dictionaries", "xml", pkgName);
if (dictId == 0) continue;
XmlResourceParser xrp = res.getXml(dictId);
String assetName = null;
String lang = null;
try {
int current = xrp.getEventType();
while (current != XmlResourceParser.END_DOCUMENT) {
if (current == XmlResourceParser.START_TAG) {
String tag = xrp.getName();
if (tag != null) {
if (tag.equals("Dictionary")) {
lang = xrp.getAttributeValue(null, "locale");
String convLang = SOFTKEYBOARD_LANG_MAP.get(lang);
if (convLang != null) lang = convLang;
String type = xrp.getAttributeValue(null, "type");
if (type == null || type.equals("raw") || type.equals("binary")) {
assetName = xrp.getAttributeValue(null, "dictionaryAssertName"); // sic
} else {
Log.w(TAG, "Unsupported AnySoftKeyboard dict type " + type);
}
//Log.i(TAG, "asset=" + assetName + " lang=" + lang);
}
}
}
xrp.next();
current = xrp.getEventType();
}
} catch (XmlPullParserException e) {
Log.e(TAG, "Dictionary XML parsing failure");
} catch (IOException e) {
Log.e(TAG, "Dictionary XML IOException");
}
if (assetName == null || lang == null) continue;
DictPluginSpec spec = new DictPluginSpecSoftKeyboard(pkgName, assetName);
mPluginDicts.put(lang, spec);
Log.i(TAG, "Found plugin dictionary: lang=" + lang + ", pkg=" + pkgName);
success = true;
} catch (NameNotFoundException e) {
Log.i(TAG, "bad");
} finally {
if (!success) {
Log.i(TAG, "failed to load plugin dictionary spec from " + pkgName);
}
}
}
}
static void getHKDictionaries(PackageManager packageManager) {
Intent dictIntent = new Intent(HK_INTENT_DICT);
List<ResolveInfo> dictPacks = packageManager.queryIntentActivities(dictIntent, 0);
for (ResolveInfo ri : dictPacks) {
ApplicationInfo appInfo = ri.activityInfo.applicationInfo;
String pkgName = appInfo.packageName;
boolean success = false;
try {
Resources res = packageManager.getResourcesForApplication(appInfo);
//Log.i(TAG, "Found dictionary plugin package: " + pkgName);
int langId = res.getIdentifier("dict_language", "string", pkgName);
if (langId == 0) continue;
String lang = res.getString(langId);
int[] rawIds = null;
// Try single-file version first
int rawId = res.getIdentifier("main", "raw", pkgName);
if (rawId != 0) {
rawIds = new int[] { rawId };
} else {
// try multi-part version
int parts = 0;
List<Integer> ids = new ArrayList<Integer>();
while (true) {
int id = res.getIdentifier("main" + parts, "raw", pkgName);
if (id == 0) break;
ids.add(id);
++parts;
}
if (parts == 0) continue; // no parts found
rawIds = new int[parts];
for (int i = 0; i < parts; ++i) rawIds[i] = ids.get(i);
}
DictPluginSpec spec = new DictPluginSpecHK(pkgName, rawIds);
mPluginDicts.put(lang, spec);
Log.i(TAG, "Found plugin dictionary: lang=" + lang + ", pkg=" + pkgName);
success = true;
} catch (NameNotFoundException e) {
Log.i(TAG, "bad");
} finally {
if (!success) {
Log.i(TAG, "failed to load plugin dictionary spec from " + pkgName);
}
}
}
}
static void getPluginDictionaries(Context context) {
mPluginDicts.clear();
PackageManager packageManager = context.getPackageManager();
getSoftKeyboardDictionaries(packageManager);
getHKDictionaries(packageManager);
}
static BinaryDictionary getDictionary(Context context, String lang) {
//Log.i(TAG, "Looking for plugin dictionary for lang=" + lang);
DictPluginSpec spec = mPluginDicts.get(lang);
if (spec == null) spec = mPluginDicts.get(lang.substring(0, 2));
if (spec == null) {
//Log.i(TAG, "No plugin found.");
return null;
}
BinaryDictionary dict = spec.getDict(context);
Log.i(TAG, "Found plugin dictionary for " + lang + (dict == null ? " is null" : ", size=" + dict.getSize()));
return dict;
}
}
| 11beeaosama-descrbvbnvbniption | java/src/org/pocketworkstation/pckeyboard/PluginManager.java | Java | asf20 | 10,528 |
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
/**
* Abstract base class for a dictionary that can do a fuzzy search for words based on a set of key
* strokes.
*/
abstract public class Dictionary {
/**
* Whether or not to replicate the typed word in the suggested list, even if it's valid.
*/
protected static final boolean INCLUDE_TYPED_WORD_IF_VALID = false;
/**
* The weight to give to a word if it's length is the same as the number of typed characters.
*/
protected static final int FULL_WORD_FREQ_MULTIPLIER = 2;
public static enum DataType {
UNIGRAM, BIGRAM
}
/**
* Interface to be implemented by classes requesting words to be fetched from the dictionary.
* @see #getWords(WordComposer, WordCallback)
*/
public interface WordCallback {
/**
* Adds a word to a list of suggestions. The word is expected to be ordered based on
* the provided frequency.
* @param word the character array containing the word
* @param wordOffset starting offset of the word in the character array
* @param wordLength length of valid characters in the character array
* @param frequency the frequency of occurence. This is normalized between 1 and 255, but
* can exceed those limits
* @param dicTypeId of the dictionary where word was from
* @param dataType tells type of this data
* @return true if the word was added, false if no more words are required
*/
boolean addWord(char[] word, int wordOffset, int wordLength, int frequency, int dicTypeId,
DataType dataType);
}
/**
* Searches for words in the dictionary that match the characters in the composer. Matched
* words are added through the callback object.
* @param composer the key sequence to match
* @param callback the callback object to send matched words to as possible candidates
* @param nextLettersFrequencies array of frequencies of next letters that could follow the
* word so far. For instance, "bracke" can be followed by "t", so array['t'] will have
* a non-zero value on returning from this method.
* Pass in null if you don't want the dictionary to look up next letters.
* @see WordCallback#addWord(char[], int, int)
*/
abstract public void getWords(final WordComposer composer, final WordCallback callback,
int[] nextLettersFrequencies);
/**
* Searches for pairs in the bigram dictionary that matches the previous word and all the
* possible words following are added through the callback object.
* @param composer the key sequence to match
* @param callback the callback object to send possible word following previous word
* @param nextLettersFrequencies array of frequencies of next letters that could follow the
* word so far. For instance, "bracke" can be followed by "t", so array['t'] will have
* a non-zero value on returning from this method.
* Pass in null if you don't want the dictionary to look up next letters.
*/
public void getBigrams(final WordComposer composer, final CharSequence previousWord,
final WordCallback callback, int[] nextLettersFrequencies) {
// empty base implementation
}
/**
* Checks if the given word occurs in the dictionary
* @param word the word to search for. The search should be case-insensitive.
* @return true if the word exists, false otherwise
*/
abstract public boolean isValidWord(CharSequence word);
/**
* Compares the contents of the character array with the typed word and returns true if they
* are the same.
* @param word the array of characters that make up the word
* @param length the number of valid characters in the character array
* @param typedWord the word to compare with
* @return true if they are the same, false otherwise.
*/
protected boolean same(final char[] word, final int length, final CharSequence typedWord) {
if (typedWord.length() != length) {
return false;
}
for (int i = 0; i < length; i++) {
if (word[i] != typedWord.charAt(i)) {
return false;
}
}
return true;
}
/**
* Override to clean up any resources.
*/
public void close() {
}
}
| 11beeaosama-descrbvbnvbniption | java/src/org/pocketworkstation/pckeyboard/Dictionary.java | Java | asf20 | 5,095 |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdlib.h>
namespace latinime {
struct LatinCapitalSmallPair {
unsigned short capital;
unsigned short small;
};
// Generated from http://unicode.org/Public/UNIDATA/UnicodeData.txt
//
// 1. Run the following code. Bascially taken from
// Dictionary::toLowerCase(unsigned short c) in dictionary.cpp.
// Then, get the list of chars where cc != ccc.
//
// unsigned short c, cc, ccc, ccc2;
// for (c = 0; c < 0xFFFF ; c++) {
// if (c < sizeof(BASE_CHARS) / sizeof(BASE_CHARS[0])) {
// cc = BASE_CHARS[c];
// } else {
// cc = c;
// }
//
// // tolower
// int isBase = 0;
// if (cc >='A' && cc <= 'Z') {
// ccc = (cc | 0x20);
// ccc2 = ccc;
// isBase = 1;
// } else if (cc > 0x7F) {
// ccc = u_tolower(cc);
// ccc2 = latin_tolower(cc);
// } else {
// ccc = cc;
// ccc2 = ccc;
// }
// if (!isBase && cc != ccc) {
// wprintf(L" 0x%04X => 0x%04X => 0x%04X %lc => %lc => %lc \n",
// c, cc, ccc, c, cc, ccc);
// //assert(ccc == ccc2);
// }
// }
//
// Initially, started with an empty latin_tolower() as below.
//
// unsigned short latin_tolower(unsigned short c) {
// return c;
// }
//
//
// 2. Process the list obtained by 1 by the following perl script and apply
// 'sort -u' as well. Get the SORTED_CHAR_MAP[].
// Note that '$1' in the perl script is 'cc' in the above C code.
//
// while(<>) {
// / 0x\w* => 0x(\w*) =/;
// open(HDL, "grep -iw ^" . $1 . " UnicodeData.txt | ");
// $line = <HDL>;
// chomp $line;
// @cols = split(/;/, $line);
// print " { 0x$1, 0x$cols[13] }, // $cols[1]\n";
// }
//
//
// 3. Update the latin_tolower() function above with SORTED_CHAR_MAP. Enable
// the assert(ccc == ccc2) above and confirm the function exits successfully.
//
static const struct LatinCapitalSmallPair SORTED_CHAR_MAP[] = {
{ 0x00C4, 0x00E4 }, // LATIN CAPITAL LETTER A WITH DIAERESIS
{ 0x00C5, 0x00E5 }, // LATIN CAPITAL LETTER A WITH RING ABOVE
{ 0x00C6, 0x00E6 }, // LATIN CAPITAL LETTER AE
{ 0x00D0, 0x00F0 }, // LATIN CAPITAL LETTER ETH
{ 0x00D5, 0x00F5 }, // LATIN CAPITAL LETTER O WITH TILDE
{ 0x00D6, 0x00F6 }, // LATIN CAPITAL LETTER O WITH DIAERESIS
{ 0x00D8, 0x00F8 }, // LATIN CAPITAL LETTER O WITH STROKE
{ 0x00DC, 0x00FC }, // LATIN CAPITAL LETTER U WITH DIAERESIS
{ 0x00DE, 0x00FE }, // LATIN CAPITAL LETTER THORN
{ 0x0110, 0x0111 }, // LATIN CAPITAL LETTER D WITH STROKE
{ 0x0126, 0x0127 }, // LATIN CAPITAL LETTER H WITH STROKE
{ 0x0141, 0x0142 }, // LATIN CAPITAL LETTER L WITH STROKE
{ 0x014A, 0x014B }, // LATIN CAPITAL LETTER ENG
{ 0x0152, 0x0153 }, // LATIN CAPITAL LIGATURE OE
{ 0x0166, 0x0167 }, // LATIN CAPITAL LETTER T WITH STROKE
{ 0x0181, 0x0253 }, // LATIN CAPITAL LETTER B WITH HOOK
{ 0x0182, 0x0183 }, // LATIN CAPITAL LETTER B WITH TOPBAR
{ 0x0184, 0x0185 }, // LATIN CAPITAL LETTER TONE SIX
{ 0x0186, 0x0254 }, // LATIN CAPITAL LETTER OPEN O
{ 0x0187, 0x0188 }, // LATIN CAPITAL LETTER C WITH HOOK
{ 0x0189, 0x0256 }, // LATIN CAPITAL LETTER AFRICAN D
{ 0x018A, 0x0257 }, // LATIN CAPITAL LETTER D WITH HOOK
{ 0x018B, 0x018C }, // LATIN CAPITAL LETTER D WITH TOPBAR
{ 0x018E, 0x01DD }, // LATIN CAPITAL LETTER REVERSED E
{ 0x018F, 0x0259 }, // LATIN CAPITAL LETTER SCHWA
{ 0x0190, 0x025B }, // LATIN CAPITAL LETTER OPEN E
{ 0x0191, 0x0192 }, // LATIN CAPITAL LETTER F WITH HOOK
{ 0x0193, 0x0260 }, // LATIN CAPITAL LETTER G WITH HOOK
{ 0x0194, 0x0263 }, // LATIN CAPITAL LETTER GAMMA
{ 0x0196, 0x0269 }, // LATIN CAPITAL LETTER IOTA
{ 0x0197, 0x0268 }, // LATIN CAPITAL LETTER I WITH STROKE
{ 0x0198, 0x0199 }, // LATIN CAPITAL LETTER K WITH HOOK
{ 0x019C, 0x026F }, // LATIN CAPITAL LETTER TURNED M
{ 0x019D, 0x0272 }, // LATIN CAPITAL LETTER N WITH LEFT HOOK
{ 0x019F, 0x0275 }, // LATIN CAPITAL LETTER O WITH MIDDLE TILDE
{ 0x01A2, 0x01A3 }, // LATIN CAPITAL LETTER OI
{ 0x01A4, 0x01A5 }, // LATIN CAPITAL LETTER P WITH HOOK
{ 0x01A6, 0x0280 }, // LATIN LETTER YR
{ 0x01A7, 0x01A8 }, // LATIN CAPITAL LETTER TONE TWO
{ 0x01A9, 0x0283 }, // LATIN CAPITAL LETTER ESH
{ 0x01AC, 0x01AD }, // LATIN CAPITAL LETTER T WITH HOOK
{ 0x01AE, 0x0288 }, // LATIN CAPITAL LETTER T WITH RETROFLEX HOOK
{ 0x01B1, 0x028A }, // LATIN CAPITAL LETTER UPSILON
{ 0x01B2, 0x028B }, // LATIN CAPITAL LETTER V WITH HOOK
{ 0x01B3, 0x01B4 }, // LATIN CAPITAL LETTER Y WITH HOOK
{ 0x01B5, 0x01B6 }, // LATIN CAPITAL LETTER Z WITH STROKE
{ 0x01B7, 0x0292 }, // LATIN CAPITAL LETTER EZH
{ 0x01B8, 0x01B9 }, // LATIN CAPITAL LETTER EZH REVERSED
{ 0x01BC, 0x01BD }, // LATIN CAPITAL LETTER TONE FIVE
{ 0x01E4, 0x01E5 }, // LATIN CAPITAL LETTER G WITH STROKE
{ 0x01EA, 0x01EB }, // LATIN CAPITAL LETTER O WITH OGONEK
{ 0x01F6, 0x0195 }, // LATIN CAPITAL LETTER HWAIR
{ 0x01F7, 0x01BF }, // LATIN CAPITAL LETTER WYNN
{ 0x021C, 0x021D }, // LATIN CAPITAL LETTER YOGH
{ 0x0220, 0x019E }, // LATIN CAPITAL LETTER N WITH LONG RIGHT LEG
{ 0x0222, 0x0223 }, // LATIN CAPITAL LETTER OU
{ 0x0224, 0x0225 }, // LATIN CAPITAL LETTER Z WITH HOOK
{ 0x0226, 0x0227 }, // LATIN CAPITAL LETTER A WITH DOT ABOVE
{ 0x022E, 0x022F }, // LATIN CAPITAL LETTER O WITH DOT ABOVE
{ 0x023A, 0x2C65 }, // LATIN CAPITAL LETTER A WITH STROKE
{ 0x023B, 0x023C }, // LATIN CAPITAL LETTER C WITH STROKE
{ 0x023D, 0x019A }, // LATIN CAPITAL LETTER L WITH BAR
{ 0x023E, 0x2C66 }, // LATIN CAPITAL LETTER T WITH DIAGONAL STROKE
{ 0x0241, 0x0242 }, // LATIN CAPITAL LETTER GLOTTAL STOP
{ 0x0243, 0x0180 }, // LATIN CAPITAL LETTER B WITH STROKE
{ 0x0244, 0x0289 }, // LATIN CAPITAL LETTER U BAR
{ 0x0245, 0x028C }, // LATIN CAPITAL LETTER TURNED V
{ 0x0246, 0x0247 }, // LATIN CAPITAL LETTER E WITH STROKE
{ 0x0248, 0x0249 }, // LATIN CAPITAL LETTER J WITH STROKE
{ 0x024A, 0x024B }, // LATIN CAPITAL LETTER SMALL Q WITH HOOK TAIL
{ 0x024C, 0x024D }, // LATIN CAPITAL LETTER R WITH STROKE
{ 0x024E, 0x024F }, // LATIN CAPITAL LETTER Y WITH STROKE
{ 0x0370, 0x0371 }, // GREEK CAPITAL LETTER HETA
{ 0x0372, 0x0373 }, // GREEK CAPITAL LETTER ARCHAIC SAMPI
{ 0x0376, 0x0377 }, // GREEK CAPITAL LETTER PAMPHYLIAN DIGAMMA
{ 0x0391, 0x03B1 }, // GREEK CAPITAL LETTER ALPHA
{ 0x0392, 0x03B2 }, // GREEK CAPITAL LETTER BETA
{ 0x0393, 0x03B3 }, // GREEK CAPITAL LETTER GAMMA
{ 0x0394, 0x03B4 }, // GREEK CAPITAL LETTER DELTA
{ 0x0395, 0x03B5 }, // GREEK CAPITAL LETTER EPSILON
{ 0x0396, 0x03B6 }, // GREEK CAPITAL LETTER ZETA
{ 0x0397, 0x03B7 }, // GREEK CAPITAL LETTER ETA
{ 0x0398, 0x03B8 }, // GREEK CAPITAL LETTER THETA
{ 0x0399, 0x03B9 }, // GREEK CAPITAL LETTER IOTA
{ 0x039A, 0x03BA }, // GREEK CAPITAL LETTER KAPPA
{ 0x039B, 0x03BB }, // GREEK CAPITAL LETTER LAMDA
{ 0x039C, 0x03BC }, // GREEK CAPITAL LETTER MU
{ 0x039D, 0x03BD }, // GREEK CAPITAL LETTER NU
{ 0x039E, 0x03BE }, // GREEK CAPITAL LETTER XI
{ 0x039F, 0x03BF }, // GREEK CAPITAL LETTER OMICRON
{ 0x03A0, 0x03C0 }, // GREEK CAPITAL LETTER PI
{ 0x03A1, 0x03C1 }, // GREEK CAPITAL LETTER RHO
{ 0x03A3, 0x03C3 }, // GREEK CAPITAL LETTER SIGMA
{ 0x03A4, 0x03C4 }, // GREEK CAPITAL LETTER TAU
{ 0x03A5, 0x03C5 }, // GREEK CAPITAL LETTER UPSILON
{ 0x03A6, 0x03C6 }, // GREEK CAPITAL LETTER PHI
{ 0x03A7, 0x03C7 }, // GREEK CAPITAL LETTER CHI
{ 0x03A8, 0x03C8 }, // GREEK CAPITAL LETTER PSI
{ 0x03A9, 0x03C9 }, // GREEK CAPITAL LETTER OMEGA
{ 0x03CF, 0x03D7 }, // GREEK CAPITAL KAI SYMBOL
{ 0x03D8, 0x03D9 }, // GREEK LETTER ARCHAIC KOPPA
{ 0x03DA, 0x03DB }, // GREEK LETTER STIGMA
{ 0x03DC, 0x03DD }, // GREEK LETTER DIGAMMA
{ 0x03DE, 0x03DF }, // GREEK LETTER KOPPA
{ 0x03E0, 0x03E1 }, // GREEK LETTER SAMPI
{ 0x03E2, 0x03E3 }, // COPTIC CAPITAL LETTER SHEI
{ 0x03E4, 0x03E5 }, // COPTIC CAPITAL LETTER FEI
{ 0x03E6, 0x03E7 }, // COPTIC CAPITAL LETTER KHEI
{ 0x03E8, 0x03E9 }, // COPTIC CAPITAL LETTER HORI
{ 0x03EA, 0x03EB }, // COPTIC CAPITAL LETTER GANGIA
{ 0x03EC, 0x03ED }, // COPTIC CAPITAL LETTER SHIMA
{ 0x03EE, 0x03EF }, // COPTIC CAPITAL LETTER DEI
{ 0x03F7, 0x03F8 }, // GREEK CAPITAL LETTER SHO
{ 0x03FA, 0x03FB }, // GREEK CAPITAL LETTER SAN
{ 0x03FD, 0x037B }, // GREEK CAPITAL REVERSED LUNATE SIGMA SYMBOL
{ 0x03FE, 0x037C }, // GREEK CAPITAL DOTTED LUNATE SIGMA SYMBOL
{ 0x03FF, 0x037D }, // GREEK CAPITAL REVERSED DOTTED LUNATE SIGMA SYMBOL
{ 0x0402, 0x0452 }, // CYRILLIC CAPITAL LETTER DJE
{ 0x0404, 0x0454 }, // CYRILLIC CAPITAL LETTER UKRAINIAN IE
{ 0x0405, 0x0455 }, // CYRILLIC CAPITAL LETTER DZE
{ 0x0406, 0x0456 }, // CYRILLIC CAPITAL LETTER BYELORUSSIAN-UKRAINIAN I
{ 0x0408, 0x0458 }, // CYRILLIC CAPITAL LETTER JE
{ 0x0409, 0x0459 }, // CYRILLIC CAPITAL LETTER LJE
{ 0x040A, 0x045A }, // CYRILLIC CAPITAL LETTER NJE
{ 0x040B, 0x045B }, // CYRILLIC CAPITAL LETTER TSHE
{ 0x040F, 0x045F }, // CYRILLIC CAPITAL LETTER DZHE
{ 0x0410, 0x0430 }, // CYRILLIC CAPITAL LETTER A
{ 0x0411, 0x0431 }, // CYRILLIC CAPITAL LETTER BE
{ 0x0412, 0x0432 }, // CYRILLIC CAPITAL LETTER VE
{ 0x0413, 0x0433 }, // CYRILLIC CAPITAL LETTER GHE
{ 0x0414, 0x0434 }, // CYRILLIC CAPITAL LETTER DE
{ 0x0415, 0x0435 }, // CYRILLIC CAPITAL LETTER IE
{ 0x0416, 0x0436 }, // CYRILLIC CAPITAL LETTER ZHE
{ 0x0417, 0x0437 }, // CYRILLIC CAPITAL LETTER ZE
{ 0x0418, 0x0438 }, // CYRILLIC CAPITAL LETTER I
{ 0x041A, 0x043A }, // CYRILLIC CAPITAL LETTER KA
{ 0x041B, 0x043B }, // CYRILLIC CAPITAL LETTER EL
{ 0x041C, 0x043C }, // CYRILLIC CAPITAL LETTER EM
{ 0x041D, 0x043D }, // CYRILLIC CAPITAL LETTER EN
{ 0x041E, 0x043E }, // CYRILLIC CAPITAL LETTER O
{ 0x041F, 0x043F }, // CYRILLIC CAPITAL LETTER PE
{ 0x0420, 0x0440 }, // CYRILLIC CAPITAL LETTER ER
{ 0x0421, 0x0441 }, // CYRILLIC CAPITAL LETTER ES
{ 0x0422, 0x0442 }, // CYRILLIC CAPITAL LETTER TE
{ 0x0423, 0x0443 }, // CYRILLIC CAPITAL LETTER U
{ 0x0424, 0x0444 }, // CYRILLIC CAPITAL LETTER EF
{ 0x0425, 0x0445 }, // CYRILLIC CAPITAL LETTER HA
{ 0x0426, 0x0446 }, // CYRILLIC CAPITAL LETTER TSE
{ 0x0427, 0x0447 }, // CYRILLIC CAPITAL LETTER CHE
{ 0x0428, 0x0448 }, // CYRILLIC CAPITAL LETTER SHA
{ 0x0429, 0x0449 }, // CYRILLIC CAPITAL LETTER SHCHA
{ 0x042A, 0x044A }, // CYRILLIC CAPITAL LETTER HARD SIGN
{ 0x042B, 0x044B }, // CYRILLIC CAPITAL LETTER YERU
{ 0x042C, 0x044C }, // CYRILLIC CAPITAL LETTER SOFT SIGN
{ 0x042D, 0x044D }, // CYRILLIC CAPITAL LETTER E
{ 0x042E, 0x044E }, // CYRILLIC CAPITAL LETTER YU
{ 0x042F, 0x044F }, // CYRILLIC CAPITAL LETTER YA
{ 0x0460, 0x0461 }, // CYRILLIC CAPITAL LETTER OMEGA
{ 0x0462, 0x0463 }, // CYRILLIC CAPITAL LETTER YAT
{ 0x0464, 0x0465 }, // CYRILLIC CAPITAL LETTER IOTIFIED E
{ 0x0466, 0x0467 }, // CYRILLIC CAPITAL LETTER LITTLE YUS
{ 0x0468, 0x0469 }, // CYRILLIC CAPITAL LETTER IOTIFIED LITTLE YUS
{ 0x046A, 0x046B }, // CYRILLIC CAPITAL LETTER BIG YUS
{ 0x046C, 0x046D }, // CYRILLIC CAPITAL LETTER IOTIFIED BIG YUS
{ 0x046E, 0x046F }, // CYRILLIC CAPITAL LETTER KSI
{ 0x0470, 0x0471 }, // CYRILLIC CAPITAL LETTER PSI
{ 0x0472, 0x0473 }, // CYRILLIC CAPITAL LETTER FITA
{ 0x0474, 0x0475 }, // CYRILLIC CAPITAL LETTER IZHITSA
{ 0x0478, 0x0479 }, // CYRILLIC CAPITAL LETTER UK
{ 0x047A, 0x047B }, // CYRILLIC CAPITAL LETTER ROUND OMEGA
{ 0x047C, 0x047D }, // CYRILLIC CAPITAL LETTER OMEGA WITH TITLO
{ 0x047E, 0x047F }, // CYRILLIC CAPITAL LETTER OT
{ 0x0480, 0x0481 }, // CYRILLIC CAPITAL LETTER KOPPA
{ 0x048A, 0x048B }, // CYRILLIC CAPITAL LETTER SHORT I WITH TAIL
{ 0x048C, 0x048D }, // CYRILLIC CAPITAL LETTER SEMISOFT SIGN
{ 0x048E, 0x048F }, // CYRILLIC CAPITAL LETTER ER WITH TICK
{ 0x0490, 0x0491 }, // CYRILLIC CAPITAL LETTER GHE WITH UPTURN
{ 0x0492, 0x0493 }, // CYRILLIC CAPITAL LETTER GHE WITH STROKE
{ 0x0494, 0x0495 }, // CYRILLIC CAPITAL LETTER GHE WITH MIDDLE HOOK
{ 0x0496, 0x0497 }, // CYRILLIC CAPITAL LETTER ZHE WITH DESCENDER
{ 0x0498, 0x0499 }, // CYRILLIC CAPITAL LETTER ZE WITH DESCENDER
{ 0x049A, 0x049B }, // CYRILLIC CAPITAL LETTER KA WITH DESCENDER
{ 0x049C, 0x049D }, // CYRILLIC CAPITAL LETTER KA WITH VERTICAL STROKE
{ 0x049E, 0x049F }, // CYRILLIC CAPITAL LETTER KA WITH STROKE
{ 0x04A0, 0x04A1 }, // CYRILLIC CAPITAL LETTER BASHKIR KA
{ 0x04A2, 0x04A3 }, // CYRILLIC CAPITAL LETTER EN WITH DESCENDER
{ 0x04A4, 0x04A5 }, // CYRILLIC CAPITAL LIGATURE EN GHE
{ 0x04A6, 0x04A7 }, // CYRILLIC CAPITAL LETTER PE WITH MIDDLE HOOK
{ 0x04A8, 0x04A9 }, // CYRILLIC CAPITAL LETTER ABKHASIAN HA
{ 0x04AA, 0x04AB }, // CYRILLIC CAPITAL LETTER ES WITH DESCENDER
{ 0x04AC, 0x04AD }, // CYRILLIC CAPITAL LETTER TE WITH DESCENDER
{ 0x04AE, 0x04AF }, // CYRILLIC CAPITAL LETTER STRAIGHT U
{ 0x04B0, 0x04B1 }, // CYRILLIC CAPITAL LETTER STRAIGHT U WITH STROKE
{ 0x04B2, 0x04B3 }, // CYRILLIC CAPITAL LETTER HA WITH DESCENDER
{ 0x04B4, 0x04B5 }, // CYRILLIC CAPITAL LIGATURE TE TSE
{ 0x04B6, 0x04B7 }, // CYRILLIC CAPITAL LETTER CHE WITH DESCENDER
{ 0x04B8, 0x04B9 }, // CYRILLIC CAPITAL LETTER CHE WITH VERTICAL STROKE
{ 0x04BA, 0x04BB }, // CYRILLIC CAPITAL LETTER SHHA
{ 0x04BC, 0x04BD }, // CYRILLIC CAPITAL LETTER ABKHASIAN CHE
{ 0x04BE, 0x04BF }, // CYRILLIC CAPITAL LETTER ABKHASIAN CHE WITH DESCENDER
{ 0x04C0, 0x04CF }, // CYRILLIC LETTER PALOCHKA
{ 0x04C3, 0x04C4 }, // CYRILLIC CAPITAL LETTER KA WITH HOOK
{ 0x04C5, 0x04C6 }, // CYRILLIC CAPITAL LETTER EL WITH TAIL
{ 0x04C7, 0x04C8 }, // CYRILLIC CAPITAL LETTER EN WITH HOOK
{ 0x04C9, 0x04CA }, // CYRILLIC CAPITAL LETTER EN WITH TAIL
{ 0x04CB, 0x04CC }, // CYRILLIC CAPITAL LETTER KHAKASSIAN CHE
{ 0x04CD, 0x04CE }, // CYRILLIC CAPITAL LETTER EM WITH TAIL
{ 0x04D4, 0x04D5 }, // CYRILLIC CAPITAL LIGATURE A IE
{ 0x04D8, 0x04D9 }, // CYRILLIC CAPITAL LETTER SCHWA
{ 0x04E0, 0x04E1 }, // CYRILLIC CAPITAL LETTER ABKHASIAN DZE
{ 0x04E8, 0x04E9 }, // CYRILLIC CAPITAL LETTER BARRED O
{ 0x04F6, 0x04F7 }, // CYRILLIC CAPITAL LETTER GHE WITH DESCENDER
{ 0x04FA, 0x04FB }, // CYRILLIC CAPITAL LETTER GHE WITH STROKE AND HOOK
{ 0x04FC, 0x04FD }, // CYRILLIC CAPITAL LETTER HA WITH HOOK
{ 0x04FE, 0x04FF }, // CYRILLIC CAPITAL LETTER HA WITH STROKE
{ 0x0500, 0x0501 }, // CYRILLIC CAPITAL LETTER KOMI DE
{ 0x0502, 0x0503 }, // CYRILLIC CAPITAL LETTER KOMI DJE
{ 0x0504, 0x0505 }, // CYRILLIC CAPITAL LETTER KOMI ZJE
{ 0x0506, 0x0507 }, // CYRILLIC CAPITAL LETTER KOMI DZJE
{ 0x0508, 0x0509 }, // CYRILLIC CAPITAL LETTER KOMI LJE
{ 0x050A, 0x050B }, // CYRILLIC CAPITAL LETTER KOMI NJE
{ 0x050C, 0x050D }, // CYRILLIC CAPITAL LETTER KOMI SJE
{ 0x050E, 0x050F }, // CYRILLIC CAPITAL LETTER KOMI TJE
{ 0x0510, 0x0511 }, // CYRILLIC CAPITAL LETTER REVERSED ZE
{ 0x0512, 0x0513 }, // CYRILLIC CAPITAL LETTER EL WITH HOOK
{ 0x0514, 0x0515 }, // CYRILLIC CAPITAL LETTER LHA
{ 0x0516, 0x0517 }, // CYRILLIC CAPITAL LETTER RHA
{ 0x0518, 0x0519 }, // CYRILLIC CAPITAL LETTER YAE
{ 0x051A, 0x051B }, // CYRILLIC CAPITAL LETTER QA
{ 0x051C, 0x051D }, // CYRILLIC CAPITAL LETTER WE
{ 0x051E, 0x051F }, // CYRILLIC CAPITAL LETTER ALEUT KA
{ 0x0520, 0x0521 }, // CYRILLIC CAPITAL LETTER EL WITH MIDDLE HOOK
{ 0x0522, 0x0523 }, // CYRILLIC CAPITAL LETTER EN WITH MIDDLE HOOK
{ 0x0524, 0x0525 }, // CYRILLIC CAPITAL LETTER PE WITH DESCENDER
{ 0x0531, 0x0561 }, // ARMENIAN CAPITAL LETTER AYB
{ 0x0532, 0x0562 }, // ARMENIAN CAPITAL LETTER BEN
{ 0x0533, 0x0563 }, // ARMENIAN CAPITAL LETTER GIM
{ 0x0534, 0x0564 }, // ARMENIAN CAPITAL LETTER DA
{ 0x0535, 0x0565 }, // ARMENIAN CAPITAL LETTER ECH
{ 0x0536, 0x0566 }, // ARMENIAN CAPITAL LETTER ZA
{ 0x0537, 0x0567 }, // ARMENIAN CAPITAL LETTER EH
{ 0x0538, 0x0568 }, // ARMENIAN CAPITAL LETTER ET
{ 0x0539, 0x0569 }, // ARMENIAN CAPITAL LETTER TO
{ 0x053A, 0x056A }, // ARMENIAN CAPITAL LETTER ZHE
{ 0x053B, 0x056B }, // ARMENIAN CAPITAL LETTER INI
{ 0x053C, 0x056C }, // ARMENIAN CAPITAL LETTER LIWN
{ 0x053D, 0x056D }, // ARMENIAN CAPITAL LETTER XEH
{ 0x053E, 0x056E }, // ARMENIAN CAPITAL LETTER CA
{ 0x053F, 0x056F }, // ARMENIAN CAPITAL LETTER KEN
{ 0x0540, 0x0570 }, // ARMENIAN CAPITAL LETTER HO
{ 0x0541, 0x0571 }, // ARMENIAN CAPITAL LETTER JA
{ 0x0542, 0x0572 }, // ARMENIAN CAPITAL LETTER GHAD
{ 0x0543, 0x0573 }, // ARMENIAN CAPITAL LETTER CHEH
{ 0x0544, 0x0574 }, // ARMENIAN CAPITAL LETTER MEN
{ 0x0545, 0x0575 }, // ARMENIAN CAPITAL LETTER YI
{ 0x0546, 0x0576 }, // ARMENIAN CAPITAL LETTER NOW
{ 0x0547, 0x0577 }, // ARMENIAN CAPITAL LETTER SHA
{ 0x0548, 0x0578 }, // ARMENIAN CAPITAL LETTER VO
{ 0x0549, 0x0579 }, // ARMENIAN CAPITAL LETTER CHA
{ 0x054A, 0x057A }, // ARMENIAN CAPITAL LETTER PEH
{ 0x054B, 0x057B }, // ARMENIAN CAPITAL LETTER JHEH
{ 0x054C, 0x057C }, // ARMENIAN CAPITAL LETTER RA
{ 0x054D, 0x057D }, // ARMENIAN CAPITAL LETTER SEH
{ 0x054E, 0x057E }, // ARMENIAN CAPITAL LETTER VEW
{ 0x054F, 0x057F }, // ARMENIAN CAPITAL LETTER TIWN
{ 0x0550, 0x0580 }, // ARMENIAN CAPITAL LETTER REH
{ 0x0551, 0x0581 }, // ARMENIAN CAPITAL LETTER CO
{ 0x0552, 0x0582 }, // ARMENIAN CAPITAL LETTER YIWN
{ 0x0553, 0x0583 }, // ARMENIAN CAPITAL LETTER PIWR
{ 0x0554, 0x0584 }, // ARMENIAN CAPITAL LETTER KEH
{ 0x0555, 0x0585 }, // ARMENIAN CAPITAL LETTER OH
{ 0x0556, 0x0586 }, // ARMENIAN CAPITAL LETTER FEH
{ 0x10A0, 0x2D00 }, // GEORGIAN CAPITAL LETTER AN
{ 0x10A1, 0x2D01 }, // GEORGIAN CAPITAL LETTER BAN
{ 0x10A2, 0x2D02 }, // GEORGIAN CAPITAL LETTER GAN
{ 0x10A3, 0x2D03 }, // GEORGIAN CAPITAL LETTER DON
{ 0x10A4, 0x2D04 }, // GEORGIAN CAPITAL LETTER EN
{ 0x10A5, 0x2D05 }, // GEORGIAN CAPITAL LETTER VIN
{ 0x10A6, 0x2D06 }, // GEORGIAN CAPITAL LETTER ZEN
{ 0x10A7, 0x2D07 }, // GEORGIAN CAPITAL LETTER TAN
{ 0x10A8, 0x2D08 }, // GEORGIAN CAPITAL LETTER IN
{ 0x10A9, 0x2D09 }, // GEORGIAN CAPITAL LETTER KAN
{ 0x10AA, 0x2D0A }, // GEORGIAN CAPITAL LETTER LAS
{ 0x10AB, 0x2D0B }, // GEORGIAN CAPITAL LETTER MAN
{ 0x10AC, 0x2D0C }, // GEORGIAN CAPITAL LETTER NAR
{ 0x10AD, 0x2D0D }, // GEORGIAN CAPITAL LETTER ON
{ 0x10AE, 0x2D0E }, // GEORGIAN CAPITAL LETTER PAR
{ 0x10AF, 0x2D0F }, // GEORGIAN CAPITAL LETTER ZHAR
{ 0x10B0, 0x2D10 }, // GEORGIAN CAPITAL LETTER RAE
{ 0x10B1, 0x2D11 }, // GEORGIAN CAPITAL LETTER SAN
{ 0x10B2, 0x2D12 }, // GEORGIAN CAPITAL LETTER TAR
{ 0x10B3, 0x2D13 }, // GEORGIAN CAPITAL LETTER UN
{ 0x10B4, 0x2D14 }, // GEORGIAN CAPITAL LETTER PHAR
{ 0x10B5, 0x2D15 }, // GEORGIAN CAPITAL LETTER KHAR
{ 0x10B6, 0x2D16 }, // GEORGIAN CAPITAL LETTER GHAN
{ 0x10B7, 0x2D17 }, // GEORGIAN CAPITAL LETTER QAR
{ 0x10B8, 0x2D18 }, // GEORGIAN CAPITAL LETTER SHIN
{ 0x10B9, 0x2D19 }, // GEORGIAN CAPITAL LETTER CHIN
{ 0x10BA, 0x2D1A }, // GEORGIAN CAPITAL LETTER CAN
{ 0x10BB, 0x2D1B }, // GEORGIAN CAPITAL LETTER JIL
{ 0x10BC, 0x2D1C }, // GEORGIAN CAPITAL LETTER CIL
{ 0x10BD, 0x2D1D }, // GEORGIAN CAPITAL LETTER CHAR
{ 0x10BE, 0x2D1E }, // GEORGIAN CAPITAL LETTER XAN
{ 0x10BF, 0x2D1F }, // GEORGIAN CAPITAL LETTER JHAN
{ 0x10C0, 0x2D20 }, // GEORGIAN CAPITAL LETTER HAE
{ 0x10C1, 0x2D21 }, // GEORGIAN CAPITAL LETTER HE
{ 0x10C2, 0x2D22 }, // GEORGIAN CAPITAL LETTER HIE
{ 0x10C3, 0x2D23 }, // GEORGIAN CAPITAL LETTER WE
{ 0x10C4, 0x2D24 }, // GEORGIAN CAPITAL LETTER HAR
{ 0x10C5, 0x2D25 }, // GEORGIAN CAPITAL LETTER HOE
{ 0x1E00, 0x1E01 }, // LATIN CAPITAL LETTER A WITH RING BELOW
{ 0x1E02, 0x1E03 }, // LATIN CAPITAL LETTER B WITH DOT ABOVE
{ 0x1E04, 0x1E05 }, // LATIN CAPITAL LETTER B WITH DOT BELOW
{ 0x1E06, 0x1E07 }, // LATIN CAPITAL LETTER B WITH LINE BELOW
{ 0x1E08, 0x1E09 }, // LATIN CAPITAL LETTER C WITH CEDILLA AND ACUTE
{ 0x1E0A, 0x1E0B }, // LATIN CAPITAL LETTER D WITH DOT ABOVE
{ 0x1E0C, 0x1E0D }, // LATIN CAPITAL LETTER D WITH DOT BELOW
{ 0x1E0E, 0x1E0F }, // LATIN CAPITAL LETTER D WITH LINE BELOW
{ 0x1E10, 0x1E11 }, // LATIN CAPITAL LETTER D WITH CEDILLA
{ 0x1E12, 0x1E13 }, // LATIN CAPITAL LETTER D WITH CIRCUMFLEX BELOW
{ 0x1E14, 0x1E15 }, // LATIN CAPITAL LETTER E WITH MACRON AND GRAVE
{ 0x1E16, 0x1E17 }, // LATIN CAPITAL LETTER E WITH MACRON AND ACUTE
{ 0x1E18, 0x1E19 }, // LATIN CAPITAL LETTER E WITH CIRCUMFLEX BELOW
{ 0x1E1A, 0x1E1B }, // LATIN CAPITAL LETTER E WITH TILDE BELOW
{ 0x1E1C, 0x1E1D }, // LATIN CAPITAL LETTER E WITH CEDILLA AND BREVE
{ 0x1E1E, 0x1E1F }, // LATIN CAPITAL LETTER F WITH DOT ABOVE
{ 0x1E20, 0x1E21 }, // LATIN CAPITAL LETTER G WITH MACRON
{ 0x1E22, 0x1E23 }, // LATIN CAPITAL LETTER H WITH DOT ABOVE
{ 0x1E24, 0x1E25 }, // LATIN CAPITAL LETTER H WITH DOT BELOW
{ 0x1E26, 0x1E27 }, // LATIN CAPITAL LETTER H WITH DIAERESIS
{ 0x1E28, 0x1E29 }, // LATIN CAPITAL LETTER H WITH CEDILLA
{ 0x1E2A, 0x1E2B }, // LATIN CAPITAL LETTER H WITH BREVE BELOW
{ 0x1E2C, 0x1E2D }, // LATIN CAPITAL LETTER I WITH TILDE BELOW
{ 0x1E2E, 0x1E2F }, // LATIN CAPITAL LETTER I WITH DIAERESIS AND ACUTE
{ 0x1E30, 0x1E31 }, // LATIN CAPITAL LETTER K WITH ACUTE
{ 0x1E32, 0x1E33 }, // LATIN CAPITAL LETTER K WITH DOT BELOW
{ 0x1E34, 0x1E35 }, // LATIN CAPITAL LETTER K WITH LINE BELOW
{ 0x1E36, 0x1E37 }, // LATIN CAPITAL LETTER L WITH DOT BELOW
{ 0x1E38, 0x1E39 }, // LATIN CAPITAL LETTER L WITH DOT BELOW AND MACRON
{ 0x1E3A, 0x1E3B }, // LATIN CAPITAL LETTER L WITH LINE BELOW
{ 0x1E3C, 0x1E3D }, // LATIN CAPITAL LETTER L WITH CIRCUMFLEX BELOW
{ 0x1E3E, 0x1E3F }, // LATIN CAPITAL LETTER M WITH ACUTE
{ 0x1E40, 0x1E41 }, // LATIN CAPITAL LETTER M WITH DOT ABOVE
{ 0x1E42, 0x1E43 }, // LATIN CAPITAL LETTER M WITH DOT BELOW
{ 0x1E44, 0x1E45 }, // LATIN CAPITAL LETTER N WITH DOT ABOVE
{ 0x1E46, 0x1E47 }, // LATIN CAPITAL LETTER N WITH DOT BELOW
{ 0x1E48, 0x1E49 }, // LATIN CAPITAL LETTER N WITH LINE BELOW
{ 0x1E4A, 0x1E4B }, // LATIN CAPITAL LETTER N WITH CIRCUMFLEX BELOW
{ 0x1E4C, 0x1E4D }, // LATIN CAPITAL LETTER O WITH TILDE AND ACUTE
{ 0x1E4E, 0x1E4F }, // LATIN CAPITAL LETTER O WITH TILDE AND DIAERESIS
{ 0x1E50, 0x1E51 }, // LATIN CAPITAL LETTER O WITH MACRON AND GRAVE
{ 0x1E52, 0x1E53 }, // LATIN CAPITAL LETTER O WITH MACRON AND ACUTE
{ 0x1E54, 0x1E55 }, // LATIN CAPITAL LETTER P WITH ACUTE
{ 0x1E56, 0x1E57 }, // LATIN CAPITAL LETTER P WITH DOT ABOVE
{ 0x1E58, 0x1E59 }, // LATIN CAPITAL LETTER R WITH DOT ABOVE
{ 0x1E5A, 0x1E5B }, // LATIN CAPITAL LETTER R WITH DOT BELOW
{ 0x1E5C, 0x1E5D }, // LATIN CAPITAL LETTER R WITH DOT BELOW AND MACRON
{ 0x1E5E, 0x1E5F }, // LATIN CAPITAL LETTER R WITH LINE BELOW
{ 0x1E60, 0x1E61 }, // LATIN CAPITAL LETTER S WITH DOT ABOVE
{ 0x1E62, 0x1E63 }, // LATIN CAPITAL LETTER S WITH DOT BELOW
{ 0x1E64, 0x1E65 }, // LATIN CAPITAL LETTER S WITH ACUTE AND DOT ABOVE
{ 0x1E66, 0x1E67 }, // LATIN CAPITAL LETTER S WITH CARON AND DOT ABOVE
{ 0x1E68, 0x1E69 }, // LATIN CAPITAL LETTER S WITH DOT BELOW AND DOT ABOVE
{ 0x1E6A, 0x1E6B }, // LATIN CAPITAL LETTER T WITH DOT ABOVE
{ 0x1E6C, 0x1E6D }, // LATIN CAPITAL LETTER T WITH DOT BELOW
{ 0x1E6E, 0x1E6F }, // LATIN CAPITAL LETTER T WITH LINE BELOW
{ 0x1E70, 0x1E71 }, // LATIN CAPITAL LETTER T WITH CIRCUMFLEX BELOW
{ 0x1E72, 0x1E73 }, // LATIN CAPITAL LETTER U WITH DIAERESIS BELOW
{ 0x1E74, 0x1E75 }, // LATIN CAPITAL LETTER U WITH TILDE BELOW
{ 0x1E76, 0x1E77 }, // LATIN CAPITAL LETTER U WITH CIRCUMFLEX BELOW
{ 0x1E78, 0x1E79 }, // LATIN CAPITAL LETTER U WITH TILDE AND ACUTE
{ 0x1E7A, 0x1E7B }, // LATIN CAPITAL LETTER U WITH MACRON AND DIAERESIS
{ 0x1E7C, 0x1E7D }, // LATIN CAPITAL LETTER V WITH TILDE
{ 0x1E7E, 0x1E7F }, // LATIN CAPITAL LETTER V WITH DOT BELOW
{ 0x1E80, 0x1E81 }, // LATIN CAPITAL LETTER W WITH GRAVE
{ 0x1E82, 0x1E83 }, // LATIN CAPITAL LETTER W WITH ACUTE
{ 0x1E84, 0x1E85 }, // LATIN CAPITAL LETTER W WITH DIAERESIS
{ 0x1E86, 0x1E87 }, // LATIN CAPITAL LETTER W WITH DOT ABOVE
{ 0x1E88, 0x1E89 }, // LATIN CAPITAL LETTER W WITH DOT BELOW
{ 0x1E8A, 0x1E8B }, // LATIN CAPITAL LETTER X WITH DOT ABOVE
{ 0x1E8C, 0x1E8D }, // LATIN CAPITAL LETTER X WITH DIAERESIS
{ 0x1E8E, 0x1E8F }, // LATIN CAPITAL LETTER Y WITH DOT ABOVE
{ 0x1E90, 0x1E91 }, // LATIN CAPITAL LETTER Z WITH CIRCUMFLEX
{ 0x1E92, 0x1E93 }, // LATIN CAPITAL LETTER Z WITH DOT BELOW
{ 0x1E94, 0x1E95 }, // LATIN CAPITAL LETTER Z WITH LINE BELOW
{ 0x1E9E, 0x00DF }, // LATIN CAPITAL LETTER SHARP S
{ 0x1EA0, 0x1EA1 }, // LATIN CAPITAL LETTER A WITH DOT BELOW
{ 0x1EA2, 0x1EA3 }, // LATIN CAPITAL LETTER A WITH HOOK ABOVE
{ 0x1EA4, 0x1EA5 }, // LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND ACUTE
{ 0x1EA6, 0x1EA7 }, // LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND GRAVE
{ 0x1EA8, 0x1EA9 }, // LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND HOOK ABOVE
{ 0x1EAA, 0x1EAB }, // LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND TILDE
{ 0x1EAC, 0x1EAD }, // LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND DOT BELOW
{ 0x1EAE, 0x1EAF }, // LATIN CAPITAL LETTER A WITH BREVE AND ACUTE
{ 0x1EB0, 0x1EB1 }, // LATIN CAPITAL LETTER A WITH BREVE AND GRAVE
{ 0x1EB2, 0x1EB3 }, // LATIN CAPITAL LETTER A WITH BREVE AND HOOK ABOVE
{ 0x1EB4, 0x1EB5 }, // LATIN CAPITAL LETTER A WITH BREVE AND TILDE
{ 0x1EB6, 0x1EB7 }, // LATIN CAPITAL LETTER A WITH BREVE AND DOT BELOW
{ 0x1EB8, 0x1EB9 }, // LATIN CAPITAL LETTER E WITH DOT BELOW
{ 0x1EBA, 0x1EBB }, // LATIN CAPITAL LETTER E WITH HOOK ABOVE
{ 0x1EBC, 0x1EBD }, // LATIN CAPITAL LETTER E WITH TILDE
{ 0x1EBE, 0x1EBF }, // LATIN CAPITAL LETTER E WITH CIRCUMFLEX AND ACUTE
{ 0x1EC0, 0x1EC1 }, // LATIN CAPITAL LETTER E WITH CIRCUMFLEX AND GRAVE
{ 0x1EC2, 0x1EC3 }, // LATIN CAPITAL LETTER E WITH CIRCUMFLEX AND HOOK ABOVE
{ 0x1EC4, 0x1EC5 }, // LATIN CAPITAL LETTER E WITH CIRCUMFLEX AND TILDE
{ 0x1EC6, 0x1EC7 }, // LATIN CAPITAL LETTER E WITH CIRCUMFLEX AND DOT BELOW
{ 0x1EC8, 0x1EC9 }, // LATIN CAPITAL LETTER I WITH HOOK ABOVE
{ 0x1ECA, 0x1ECB }, // LATIN CAPITAL LETTER I WITH DOT BELOW
{ 0x1ECC, 0x1ECD }, // LATIN CAPITAL LETTER O WITH DOT BELOW
{ 0x1ECE, 0x1ECF }, // LATIN CAPITAL LETTER O WITH HOOK ABOVE
{ 0x1ED0, 0x1ED1 }, // LATIN CAPITAL LETTER O WITH CIRCUMFLEX AND ACUTE
{ 0x1ED2, 0x1ED3 }, // LATIN CAPITAL LETTER O WITH CIRCUMFLEX AND GRAVE
{ 0x1ED4, 0x1ED5 }, // LATIN CAPITAL LETTER O WITH CIRCUMFLEX AND HOOK ABOVE
{ 0x1ED6, 0x1ED7 }, // LATIN CAPITAL LETTER O WITH CIRCUMFLEX AND TILDE
{ 0x1ED8, 0x1ED9 }, // LATIN CAPITAL LETTER O WITH CIRCUMFLEX AND DOT BELOW
{ 0x1EDA, 0x1EDB }, // LATIN CAPITAL LETTER O WITH HORN AND ACUTE
{ 0x1EDC, 0x1EDD }, // LATIN CAPITAL LETTER O WITH HORN AND GRAVE
{ 0x1EDE, 0x1EDF }, // LATIN CAPITAL LETTER O WITH HORN AND HOOK ABOVE
{ 0x1EE0, 0x1EE1 }, // LATIN CAPITAL LETTER O WITH HORN AND TILDE
{ 0x1EE2, 0x1EE3 }, // LATIN CAPITAL LETTER O WITH HORN AND DOT BELOW
{ 0x1EE4, 0x1EE5 }, // LATIN CAPITAL LETTER U WITH DOT BELOW
{ 0x1EE6, 0x1EE7 }, // LATIN CAPITAL LETTER U WITH HOOK ABOVE
{ 0x1EE8, 0x1EE9 }, // LATIN CAPITAL LETTER U WITH HORN AND ACUTE
{ 0x1EEA, 0x1EEB }, // LATIN CAPITAL LETTER U WITH HORN AND GRAVE
{ 0x1EEC, 0x1EED }, // LATIN CAPITAL LETTER U WITH HORN AND HOOK ABOVE
{ 0x1EEE, 0x1EEF }, // LATIN CAPITAL LETTER U WITH HORN AND TILDE
{ 0x1EF0, 0x1EF1 }, // LATIN CAPITAL LETTER U WITH HORN AND DOT BELOW
{ 0x1EF2, 0x1EF3 }, // LATIN CAPITAL LETTER Y WITH GRAVE
{ 0x1EF4, 0x1EF5 }, // LATIN CAPITAL LETTER Y WITH DOT BELOW
{ 0x1EF6, 0x1EF7 }, // LATIN CAPITAL LETTER Y WITH HOOK ABOVE
{ 0x1EF8, 0x1EF9 }, // LATIN CAPITAL LETTER Y WITH TILDE
{ 0x1EFA, 0x1EFB }, // LATIN CAPITAL LETTER MIDDLE-WELSH LL
{ 0x1EFC, 0x1EFD }, // LATIN CAPITAL LETTER MIDDLE-WELSH V
{ 0x1EFE, 0x1EFF }, // LATIN CAPITAL LETTER Y WITH LOOP
{ 0x1F08, 0x1F00 }, // GREEK CAPITAL LETTER ALPHA WITH PSILI
{ 0x1F09, 0x1F01 }, // GREEK CAPITAL LETTER ALPHA WITH DASIA
{ 0x1F0A, 0x1F02 }, // GREEK CAPITAL LETTER ALPHA WITH PSILI AND VARIA
{ 0x1F0B, 0x1F03 }, // GREEK CAPITAL LETTER ALPHA WITH DASIA AND VARIA
{ 0x1F0C, 0x1F04 }, // GREEK CAPITAL LETTER ALPHA WITH PSILI AND OXIA
{ 0x1F0D, 0x1F05 }, // GREEK CAPITAL LETTER ALPHA WITH DASIA AND OXIA
{ 0x1F0E, 0x1F06 }, // GREEK CAPITAL LETTER ALPHA WITH PSILI AND PERISPOMENI
{ 0x1F0F, 0x1F07 }, // GREEK CAPITAL LETTER ALPHA WITH DASIA AND PERISPOMENI
{ 0x1F18, 0x1F10 }, // GREEK CAPITAL LETTER EPSILON WITH PSILI
{ 0x1F19, 0x1F11 }, // GREEK CAPITAL LETTER EPSILON WITH DASIA
{ 0x1F1A, 0x1F12 }, // GREEK CAPITAL LETTER EPSILON WITH PSILI AND VARIA
{ 0x1F1B, 0x1F13 }, // GREEK CAPITAL LETTER EPSILON WITH DASIA AND VARIA
{ 0x1F1C, 0x1F14 }, // GREEK CAPITAL LETTER EPSILON WITH PSILI AND OXIA
{ 0x1F1D, 0x1F15 }, // GREEK CAPITAL LETTER EPSILON WITH DASIA AND OXIA
{ 0x1F28, 0x1F20 }, // GREEK CAPITAL LETTER ETA WITH PSILI
{ 0x1F29, 0x1F21 }, // GREEK CAPITAL LETTER ETA WITH DASIA
{ 0x1F2A, 0x1F22 }, // GREEK CAPITAL LETTER ETA WITH PSILI AND VARIA
{ 0x1F2B, 0x1F23 }, // GREEK CAPITAL LETTER ETA WITH DASIA AND VARIA
{ 0x1F2C, 0x1F24 }, // GREEK CAPITAL LETTER ETA WITH PSILI AND OXIA
{ 0x1F2D, 0x1F25 }, // GREEK CAPITAL LETTER ETA WITH DASIA AND OXIA
{ 0x1F2E, 0x1F26 }, // GREEK CAPITAL LETTER ETA WITH PSILI AND PERISPOMENI
{ 0x1F2F, 0x1F27 }, // GREEK CAPITAL LETTER ETA WITH DASIA AND PERISPOMENI
{ 0x1F38, 0x1F30 }, // GREEK CAPITAL LETTER IOTA WITH PSILI
{ 0x1F39, 0x1F31 }, // GREEK CAPITAL LETTER IOTA WITH DASIA
{ 0x1F3A, 0x1F32 }, // GREEK CAPITAL LETTER IOTA WITH PSILI AND VARIA
{ 0x1F3B, 0x1F33 }, // GREEK CAPITAL LETTER IOTA WITH DASIA AND VARIA
{ 0x1F3C, 0x1F34 }, // GREEK CAPITAL LETTER IOTA WITH PSILI AND OXIA
{ 0x1F3D, 0x1F35 }, // GREEK CAPITAL LETTER IOTA WITH DASIA AND OXIA
{ 0x1F3E, 0x1F36 }, // GREEK CAPITAL LETTER IOTA WITH PSILI AND PERISPOMENI
{ 0x1F3F, 0x1F37 }, // GREEK CAPITAL LETTER IOTA WITH DASIA AND PERISPOMENI
{ 0x1F48, 0x1F40 }, // GREEK CAPITAL LETTER OMICRON WITH PSILI
{ 0x1F49, 0x1F41 }, // GREEK CAPITAL LETTER OMICRON WITH DASIA
{ 0x1F4A, 0x1F42 }, // GREEK CAPITAL LETTER OMICRON WITH PSILI AND VARIA
{ 0x1F4B, 0x1F43 }, // GREEK CAPITAL LETTER OMICRON WITH DASIA AND VARIA
{ 0x1F4C, 0x1F44 }, // GREEK CAPITAL LETTER OMICRON WITH PSILI AND OXIA
{ 0x1F4D, 0x1F45 }, // GREEK CAPITAL LETTER OMICRON WITH DASIA AND OXIA
{ 0x1F59, 0x1F51 }, // GREEK CAPITAL LETTER UPSILON WITH DASIA
{ 0x1F5B, 0x1F53 }, // GREEK CAPITAL LETTER UPSILON WITH DASIA AND VARIA
{ 0x1F5D, 0x1F55 }, // GREEK CAPITAL LETTER UPSILON WITH DASIA AND OXIA
{ 0x1F5F, 0x1F57 }, // GREEK CAPITAL LETTER UPSILON WITH DASIA AND PERISPOMENI
{ 0x1F68, 0x1F60 }, // GREEK CAPITAL LETTER OMEGA WITH PSILI
{ 0x1F69, 0x1F61 }, // GREEK CAPITAL LETTER OMEGA WITH DASIA
{ 0x1F6A, 0x1F62 }, // GREEK CAPITAL LETTER OMEGA WITH PSILI AND VARIA
{ 0x1F6B, 0x1F63 }, // GREEK CAPITAL LETTER OMEGA WITH DASIA AND VARIA
{ 0x1F6C, 0x1F64 }, // GREEK CAPITAL LETTER OMEGA WITH PSILI AND OXIA
{ 0x1F6D, 0x1F65 }, // GREEK CAPITAL LETTER OMEGA WITH DASIA AND OXIA
{ 0x1F6E, 0x1F66 }, // GREEK CAPITAL LETTER OMEGA WITH PSILI AND PERISPOMENI
{ 0x1F6F, 0x1F67 }, // GREEK CAPITAL LETTER OMEGA WITH DASIA AND PERISPOMENI
{ 0x1F88, 0x1F80 }, // GREEK CAPITAL LETTER ALPHA WITH PSILI AND PROSGEGRAMMENI
{ 0x1F89, 0x1F81 }, // GREEK CAPITAL LETTER ALPHA WITH DASIA AND PROSGEGRAMMENI
{ 0x1F8A, 0x1F82 }, // GREEK CAPITAL LETTER ALPHA WITH PSILI AND VARIA AND PROSGEGRAMMENI
{ 0x1F8B, 0x1F83 }, // GREEK CAPITAL LETTER ALPHA WITH DASIA AND VARIA AND PROSGEGRAMMENI
{ 0x1F8C, 0x1F84 }, // GREEK CAPITAL LETTER ALPHA WITH PSILI AND OXIA AND PROSGEGRAMMENI
{ 0x1F8D, 0x1F85 }, // GREEK CAPITAL LETTER ALPHA WITH DASIA AND OXIA AND PROSGEGRAMMENI
{ 0x1F8E, 0x1F86 }, // GREEK CAPITAL LETTER ALPHA WITH PSILI AND PERISPOMENI AND PROSGEGRAMMENI
{ 0x1F8F, 0x1F87 }, // GREEK CAPITAL LETTER ALPHA WITH DASIA AND PERISPOMENI AND PROSGEGRAMMENI
{ 0x1F98, 0x1F90 }, // GREEK CAPITAL LETTER ETA WITH PSILI AND PROSGEGRAMMENI
{ 0x1F99, 0x1F91 }, // GREEK CAPITAL LETTER ETA WITH DASIA AND PROSGEGRAMMENI
{ 0x1F9A, 0x1F92 }, // GREEK CAPITAL LETTER ETA WITH PSILI AND VARIA AND PROSGEGRAMMENI
{ 0x1F9B, 0x1F93 }, // GREEK CAPITAL LETTER ETA WITH DASIA AND VARIA AND PROSGEGRAMMENI
{ 0x1F9C, 0x1F94 }, // GREEK CAPITAL LETTER ETA WITH PSILI AND OXIA AND PROSGEGRAMMENI
{ 0x1F9D, 0x1F95 }, // GREEK CAPITAL LETTER ETA WITH DASIA AND OXIA AND PROSGEGRAMMENI
{ 0x1F9E, 0x1F96 }, // GREEK CAPITAL LETTER ETA WITH PSILI AND PERISPOMENI AND PROSGEGRAMMENI
{ 0x1F9F, 0x1F97 }, // GREEK CAPITAL LETTER ETA WITH DASIA AND PERISPOMENI AND PROSGEGRAMMENI
{ 0x1FA8, 0x1FA0 }, // GREEK CAPITAL LETTER OMEGA WITH PSILI AND PROSGEGRAMMENI
{ 0x1FA9, 0x1FA1 }, // GREEK CAPITAL LETTER OMEGA WITH DASIA AND PROSGEGRAMMENI
{ 0x1FAA, 0x1FA2 }, // GREEK CAPITAL LETTER OMEGA WITH PSILI AND VARIA AND PROSGEGRAMMENI
{ 0x1FAB, 0x1FA3 }, // GREEK CAPITAL LETTER OMEGA WITH DASIA AND VARIA AND PROSGEGRAMMENI
{ 0x1FAC, 0x1FA4 }, // GREEK CAPITAL LETTER OMEGA WITH PSILI AND OXIA AND PROSGEGRAMMENI
{ 0x1FAD, 0x1FA5 }, // GREEK CAPITAL LETTER OMEGA WITH DASIA AND OXIA AND PROSGEGRAMMENI
{ 0x1FAE, 0x1FA6 }, // GREEK CAPITAL LETTER OMEGA WITH PSILI AND PERISPOMENI AND PROSGEGRAMMENI
{ 0x1FAF, 0x1FA7 }, // GREEK CAPITAL LETTER OMEGA WITH DASIA AND PERISPOMENI AND PROSGEGRAMMENI
{ 0x1FB8, 0x1FB0 }, // GREEK CAPITAL LETTER ALPHA WITH VRACHY
{ 0x1FB9, 0x1FB1 }, // GREEK CAPITAL LETTER ALPHA WITH MACRON
{ 0x1FBA, 0x1F70 }, // GREEK CAPITAL LETTER ALPHA WITH VARIA
{ 0x1FBB, 0x1F71 }, // GREEK CAPITAL LETTER ALPHA WITH OXIA
{ 0x1FBC, 0x1FB3 }, // GREEK CAPITAL LETTER ALPHA WITH PROSGEGRAMMENI
{ 0x1FC8, 0x1F72 }, // GREEK CAPITAL LETTER EPSILON WITH VARIA
{ 0x1FC9, 0x1F73 }, // GREEK CAPITAL LETTER EPSILON WITH OXIA
{ 0x1FCA, 0x1F74 }, // GREEK CAPITAL LETTER ETA WITH VARIA
{ 0x1FCB, 0x1F75 }, // GREEK CAPITAL LETTER ETA WITH OXIA
{ 0x1FCC, 0x1FC3 }, // GREEK CAPITAL LETTER ETA WITH PROSGEGRAMMENI
{ 0x1FD8, 0x1FD0 }, // GREEK CAPITAL LETTER IOTA WITH VRACHY
{ 0x1FD9, 0x1FD1 }, // GREEK CAPITAL LETTER IOTA WITH MACRON
{ 0x1FDA, 0x1F76 }, // GREEK CAPITAL LETTER IOTA WITH VARIA
{ 0x1FDB, 0x1F77 }, // GREEK CAPITAL LETTER IOTA WITH OXIA
{ 0x1FE8, 0x1FE0 }, // GREEK CAPITAL LETTER UPSILON WITH VRACHY
{ 0x1FE9, 0x1FE1 }, // GREEK CAPITAL LETTER UPSILON WITH MACRON
{ 0x1FEA, 0x1F7A }, // GREEK CAPITAL LETTER UPSILON WITH VARIA
{ 0x1FEB, 0x1F7B }, // GREEK CAPITAL LETTER UPSILON WITH OXIA
{ 0x1FEC, 0x1FE5 }, // GREEK CAPITAL LETTER RHO WITH DASIA
{ 0x1FF8, 0x1F78 }, // GREEK CAPITAL LETTER OMICRON WITH VARIA
{ 0x1FF9, 0x1F79 }, // GREEK CAPITAL LETTER OMICRON WITH OXIA
{ 0x1FFA, 0x1F7C }, // GREEK CAPITAL LETTER OMEGA WITH VARIA
{ 0x1FFB, 0x1F7D }, // GREEK CAPITAL LETTER OMEGA WITH OXIA
{ 0x1FFC, 0x1FF3 }, // GREEK CAPITAL LETTER OMEGA WITH PROSGEGRAMMENI
{ 0x2126, 0x03C9 }, // OHM SIGN
{ 0x212A, 0x006B }, // KELVIN SIGN
{ 0x212B, 0x00E5 }, // ANGSTROM SIGN
{ 0x2132, 0x214E }, // TURNED CAPITAL F
{ 0x2160, 0x2170 }, // ROMAN NUMERAL ONE
{ 0x2161, 0x2171 }, // ROMAN NUMERAL TWO
{ 0x2162, 0x2172 }, // ROMAN NUMERAL THREE
{ 0x2163, 0x2173 }, // ROMAN NUMERAL FOUR
{ 0x2164, 0x2174 }, // ROMAN NUMERAL FIVE
{ 0x2165, 0x2175 }, // ROMAN NUMERAL SIX
{ 0x2166, 0x2176 }, // ROMAN NUMERAL SEVEN
{ 0x2167, 0x2177 }, // ROMAN NUMERAL EIGHT
{ 0x2168, 0x2178 }, // ROMAN NUMERAL NINE
{ 0x2169, 0x2179 }, // ROMAN NUMERAL TEN
{ 0x216A, 0x217A }, // ROMAN NUMERAL ELEVEN
{ 0x216B, 0x217B }, // ROMAN NUMERAL TWELVE
{ 0x216C, 0x217C }, // ROMAN NUMERAL FIFTY
{ 0x216D, 0x217D }, // ROMAN NUMERAL ONE HUNDRED
{ 0x216E, 0x217E }, // ROMAN NUMERAL FIVE HUNDRED
{ 0x216F, 0x217F }, // ROMAN NUMERAL ONE THOUSAND
{ 0x2183, 0x2184 }, // ROMAN NUMERAL REVERSED ONE HUNDRED
{ 0x24B6, 0x24D0 }, // CIRCLED LATIN CAPITAL LETTER A
{ 0x24B7, 0x24D1 }, // CIRCLED LATIN CAPITAL LETTER B
{ 0x24B8, 0x24D2 }, // CIRCLED LATIN CAPITAL LETTER C
{ 0x24B9, 0x24D3 }, // CIRCLED LATIN CAPITAL LETTER D
{ 0x24BA, 0x24D4 }, // CIRCLED LATIN CAPITAL LETTER E
{ 0x24BB, 0x24D5 }, // CIRCLED LATIN CAPITAL LETTER F
{ 0x24BC, 0x24D6 }, // CIRCLED LATIN CAPITAL LETTER G
{ 0x24BD, 0x24D7 }, // CIRCLED LATIN CAPITAL LETTER H
{ 0x24BE, 0x24D8 }, // CIRCLED LATIN CAPITAL LETTER I
{ 0x24BF, 0x24D9 }, // CIRCLED LATIN CAPITAL LETTER J
{ 0x24C0, 0x24DA }, // CIRCLED LATIN CAPITAL LETTER K
{ 0x24C1, 0x24DB }, // CIRCLED LATIN CAPITAL LETTER L
{ 0x24C2, 0x24DC }, // CIRCLED LATIN CAPITAL LETTER M
{ 0x24C3, 0x24DD }, // CIRCLED LATIN CAPITAL LETTER N
{ 0x24C4, 0x24DE }, // CIRCLED LATIN CAPITAL LETTER O
{ 0x24C5, 0x24DF }, // CIRCLED LATIN CAPITAL LETTER P
{ 0x24C6, 0x24E0 }, // CIRCLED LATIN CAPITAL LETTER Q
{ 0x24C7, 0x24E1 }, // CIRCLED LATIN CAPITAL LETTER R
{ 0x24C8, 0x24E2 }, // CIRCLED LATIN CAPITAL LETTER S
{ 0x24C9, 0x24E3 }, // CIRCLED LATIN CAPITAL LETTER T
{ 0x24CA, 0x24E4 }, // CIRCLED LATIN CAPITAL LETTER U
{ 0x24CB, 0x24E5 }, // CIRCLED LATIN CAPITAL LETTER V
{ 0x24CC, 0x24E6 }, // CIRCLED LATIN CAPITAL LETTER W
{ 0x24CD, 0x24E7 }, // CIRCLED LATIN CAPITAL LETTER X
{ 0x24CE, 0x24E8 }, // CIRCLED LATIN CAPITAL LETTER Y
{ 0x24CF, 0x24E9 }, // CIRCLED LATIN CAPITAL LETTER Z
{ 0x2C00, 0x2C30 }, // GLAGOLITIC CAPITAL LETTER AZU
{ 0x2C01, 0x2C31 }, // GLAGOLITIC CAPITAL LETTER BUKY
{ 0x2C02, 0x2C32 }, // GLAGOLITIC CAPITAL LETTER VEDE
{ 0x2C03, 0x2C33 }, // GLAGOLITIC CAPITAL LETTER GLAGOLI
{ 0x2C04, 0x2C34 }, // GLAGOLITIC CAPITAL LETTER DOBRO
{ 0x2C05, 0x2C35 }, // GLAGOLITIC CAPITAL LETTER YESTU
{ 0x2C06, 0x2C36 }, // GLAGOLITIC CAPITAL LETTER ZHIVETE
{ 0x2C07, 0x2C37 }, // GLAGOLITIC CAPITAL LETTER DZELO
{ 0x2C08, 0x2C38 }, // GLAGOLITIC CAPITAL LETTER ZEMLJA
{ 0x2C09, 0x2C39 }, // GLAGOLITIC CAPITAL LETTER IZHE
{ 0x2C0A, 0x2C3A }, // GLAGOLITIC CAPITAL LETTER INITIAL IZHE
{ 0x2C0B, 0x2C3B }, // GLAGOLITIC CAPITAL LETTER I
{ 0x2C0C, 0x2C3C }, // GLAGOLITIC CAPITAL LETTER DJERVI
{ 0x2C0D, 0x2C3D }, // GLAGOLITIC CAPITAL LETTER KAKO
{ 0x2C0E, 0x2C3E }, // GLAGOLITIC CAPITAL LETTER LJUDIJE
{ 0x2C0F, 0x2C3F }, // GLAGOLITIC CAPITAL LETTER MYSLITE
{ 0x2C10, 0x2C40 }, // GLAGOLITIC CAPITAL LETTER NASHI
{ 0x2C11, 0x2C41 }, // GLAGOLITIC CAPITAL LETTER ONU
{ 0x2C12, 0x2C42 }, // GLAGOLITIC CAPITAL LETTER POKOJI
{ 0x2C13, 0x2C43 }, // GLAGOLITIC CAPITAL LETTER RITSI
{ 0x2C14, 0x2C44 }, // GLAGOLITIC CAPITAL LETTER SLOVO
{ 0x2C15, 0x2C45 }, // GLAGOLITIC CAPITAL LETTER TVRIDO
{ 0x2C16, 0x2C46 }, // GLAGOLITIC CAPITAL LETTER UKU
{ 0x2C17, 0x2C47 }, // GLAGOLITIC CAPITAL LETTER FRITU
{ 0x2C18, 0x2C48 }, // GLAGOLITIC CAPITAL LETTER HERU
{ 0x2C19, 0x2C49 }, // GLAGOLITIC CAPITAL LETTER OTU
{ 0x2C1A, 0x2C4A }, // GLAGOLITIC CAPITAL LETTER PE
{ 0x2C1B, 0x2C4B }, // GLAGOLITIC CAPITAL LETTER SHTA
{ 0x2C1C, 0x2C4C }, // GLAGOLITIC CAPITAL LETTER TSI
{ 0x2C1D, 0x2C4D }, // GLAGOLITIC CAPITAL LETTER CHRIVI
{ 0x2C1E, 0x2C4E }, // GLAGOLITIC CAPITAL LETTER SHA
{ 0x2C1F, 0x2C4F }, // GLAGOLITIC CAPITAL LETTER YERU
{ 0x2C20, 0x2C50 }, // GLAGOLITIC CAPITAL LETTER YERI
{ 0x2C21, 0x2C51 }, // GLAGOLITIC CAPITAL LETTER YATI
{ 0x2C22, 0x2C52 }, // GLAGOLITIC CAPITAL LETTER SPIDERY HA
{ 0x2C23, 0x2C53 }, // GLAGOLITIC CAPITAL LETTER YU
{ 0x2C24, 0x2C54 }, // GLAGOLITIC CAPITAL LETTER SMALL YUS
{ 0x2C25, 0x2C55 }, // GLAGOLITIC CAPITAL LETTER SMALL YUS WITH TAIL
{ 0x2C26, 0x2C56 }, // GLAGOLITIC CAPITAL LETTER YO
{ 0x2C27, 0x2C57 }, // GLAGOLITIC CAPITAL LETTER IOTATED SMALL YUS
{ 0x2C28, 0x2C58 }, // GLAGOLITIC CAPITAL LETTER BIG YUS
{ 0x2C29, 0x2C59 }, // GLAGOLITIC CAPITAL LETTER IOTATED BIG YUS
{ 0x2C2A, 0x2C5A }, // GLAGOLITIC CAPITAL LETTER FITA
{ 0x2C2B, 0x2C5B }, // GLAGOLITIC CAPITAL LETTER IZHITSA
{ 0x2C2C, 0x2C5C }, // GLAGOLITIC CAPITAL LETTER SHTAPIC
{ 0x2C2D, 0x2C5D }, // GLAGOLITIC CAPITAL LETTER TROKUTASTI A
{ 0x2C2E, 0x2C5E }, // GLAGOLITIC CAPITAL LETTER LATINATE MYSLITE
{ 0x2C60, 0x2C61 }, // LATIN CAPITAL LETTER L WITH DOUBLE BAR
{ 0x2C62, 0x026B }, // LATIN CAPITAL LETTER L WITH MIDDLE TILDE
{ 0x2C63, 0x1D7D }, // LATIN CAPITAL LETTER P WITH STROKE
{ 0x2C64, 0x027D }, // LATIN CAPITAL LETTER R WITH TAIL
{ 0x2C67, 0x2C68 }, // LATIN CAPITAL LETTER H WITH DESCENDER
{ 0x2C69, 0x2C6A }, // LATIN CAPITAL LETTER K WITH DESCENDER
{ 0x2C6B, 0x2C6C }, // LATIN CAPITAL LETTER Z WITH DESCENDER
{ 0x2C6D, 0x0251 }, // LATIN CAPITAL LETTER ALPHA
{ 0x2C6E, 0x0271 }, // LATIN CAPITAL LETTER M WITH HOOK
{ 0x2C6F, 0x0250 }, // LATIN CAPITAL LETTER TURNED A
{ 0x2C70, 0x0252 }, // LATIN CAPITAL LETTER TURNED ALPHA
{ 0x2C72, 0x2C73 }, // LATIN CAPITAL LETTER W WITH HOOK
{ 0x2C75, 0x2C76 }, // LATIN CAPITAL LETTER HALF H
{ 0x2C7E, 0x023F }, // LATIN CAPITAL LETTER S WITH SWASH TAIL
{ 0x2C7F, 0x0240 }, // LATIN CAPITAL LETTER Z WITH SWASH TAIL
{ 0x2C80, 0x2C81 }, // COPTIC CAPITAL LETTER ALFA
{ 0x2C82, 0x2C83 }, // COPTIC CAPITAL LETTER VIDA
{ 0x2C84, 0x2C85 }, // COPTIC CAPITAL LETTER GAMMA
{ 0x2C86, 0x2C87 }, // COPTIC CAPITAL LETTER DALDA
{ 0x2C88, 0x2C89 }, // COPTIC CAPITAL LETTER EIE
{ 0x2C8A, 0x2C8B }, // COPTIC CAPITAL LETTER SOU
{ 0x2C8C, 0x2C8D }, // COPTIC CAPITAL LETTER ZATA
{ 0x2C8E, 0x2C8F }, // COPTIC CAPITAL LETTER HATE
{ 0x2C90, 0x2C91 }, // COPTIC CAPITAL LETTER THETHE
{ 0x2C92, 0x2C93 }, // COPTIC CAPITAL LETTER IAUDA
{ 0x2C94, 0x2C95 }, // COPTIC CAPITAL LETTER KAPA
{ 0x2C96, 0x2C97 }, // COPTIC CAPITAL LETTER LAULA
{ 0x2C98, 0x2C99 }, // COPTIC CAPITAL LETTER MI
{ 0x2C9A, 0x2C9B }, // COPTIC CAPITAL LETTER NI
{ 0x2C9C, 0x2C9D }, // COPTIC CAPITAL LETTER KSI
{ 0x2C9E, 0x2C9F }, // COPTIC CAPITAL LETTER O
{ 0x2CA0, 0x2CA1 }, // COPTIC CAPITAL LETTER PI
{ 0x2CA2, 0x2CA3 }, // COPTIC CAPITAL LETTER RO
{ 0x2CA4, 0x2CA5 }, // COPTIC CAPITAL LETTER SIMA
{ 0x2CA6, 0x2CA7 }, // COPTIC CAPITAL LETTER TAU
{ 0x2CA8, 0x2CA9 }, // COPTIC CAPITAL LETTER UA
{ 0x2CAA, 0x2CAB }, // COPTIC CAPITAL LETTER FI
{ 0x2CAC, 0x2CAD }, // COPTIC CAPITAL LETTER KHI
{ 0x2CAE, 0x2CAF }, // COPTIC CAPITAL LETTER PSI
{ 0x2CB0, 0x2CB1 }, // COPTIC CAPITAL LETTER OOU
{ 0x2CB2, 0x2CB3 }, // COPTIC CAPITAL LETTER DIALECT-P ALEF
{ 0x2CB4, 0x2CB5 }, // COPTIC CAPITAL LETTER OLD COPTIC AIN
{ 0x2CB6, 0x2CB7 }, // COPTIC CAPITAL LETTER CRYPTOGRAMMIC EIE
{ 0x2CB8, 0x2CB9 }, // COPTIC CAPITAL LETTER DIALECT-P KAPA
{ 0x2CBA, 0x2CBB }, // COPTIC CAPITAL LETTER DIALECT-P NI
{ 0x2CBC, 0x2CBD }, // COPTIC CAPITAL LETTER CRYPTOGRAMMIC NI
{ 0x2CBE, 0x2CBF }, // COPTIC CAPITAL LETTER OLD COPTIC OOU
{ 0x2CC0, 0x2CC1 }, // COPTIC CAPITAL LETTER SAMPI
{ 0x2CC2, 0x2CC3 }, // COPTIC CAPITAL LETTER CROSSED SHEI
{ 0x2CC4, 0x2CC5 }, // COPTIC CAPITAL LETTER OLD COPTIC SHEI
{ 0x2CC6, 0x2CC7 }, // COPTIC CAPITAL LETTER OLD COPTIC ESH
{ 0x2CC8, 0x2CC9 }, // COPTIC CAPITAL LETTER AKHMIMIC KHEI
{ 0x2CCA, 0x2CCB }, // COPTIC CAPITAL LETTER DIALECT-P HORI
{ 0x2CCC, 0x2CCD }, // COPTIC CAPITAL LETTER OLD COPTIC HORI
{ 0x2CCE, 0x2CCF }, // COPTIC CAPITAL LETTER OLD COPTIC HA
{ 0x2CD0, 0x2CD1 }, // COPTIC CAPITAL LETTER L-SHAPED HA
{ 0x2CD2, 0x2CD3 }, // COPTIC CAPITAL LETTER OLD COPTIC HEI
{ 0x2CD4, 0x2CD5 }, // COPTIC CAPITAL LETTER OLD COPTIC HAT
{ 0x2CD6, 0x2CD7 }, // COPTIC CAPITAL LETTER OLD COPTIC GANGIA
{ 0x2CD8, 0x2CD9 }, // COPTIC CAPITAL LETTER OLD COPTIC DJA
{ 0x2CDA, 0x2CDB }, // COPTIC CAPITAL LETTER OLD COPTIC SHIMA
{ 0x2CDC, 0x2CDD }, // COPTIC CAPITAL LETTER OLD NUBIAN SHIMA
{ 0x2CDE, 0x2CDF }, // COPTIC CAPITAL LETTER OLD NUBIAN NGI
{ 0x2CE0, 0x2CE1 }, // COPTIC CAPITAL LETTER OLD NUBIAN NYI
{ 0x2CE2, 0x2CE3 }, // COPTIC CAPITAL LETTER OLD NUBIAN WAU
{ 0x2CEB, 0x2CEC }, // COPTIC CAPITAL LETTER CRYPTOGRAMMIC SHEI
{ 0x2CED, 0x2CEE }, // COPTIC CAPITAL LETTER CRYPTOGRAMMIC GANGIA
{ 0xA640, 0xA641 }, // CYRILLIC CAPITAL LETTER ZEMLYA
{ 0xA642, 0xA643 }, // CYRILLIC CAPITAL LETTER DZELO
{ 0xA644, 0xA645 }, // CYRILLIC CAPITAL LETTER REVERSED DZE
{ 0xA646, 0xA647 }, // CYRILLIC CAPITAL LETTER IOTA
{ 0xA648, 0xA649 }, // CYRILLIC CAPITAL LETTER DJERV
{ 0xA64A, 0xA64B }, // CYRILLIC CAPITAL LETTER MONOGRAPH UK
{ 0xA64C, 0xA64D }, // CYRILLIC CAPITAL LETTER BROAD OMEGA
{ 0xA64E, 0xA64F }, // CYRILLIC CAPITAL LETTER NEUTRAL YER
{ 0xA650, 0xA651 }, // CYRILLIC CAPITAL LETTER YERU WITH BACK YER
{ 0xA652, 0xA653 }, // CYRILLIC CAPITAL LETTER IOTIFIED YAT
{ 0xA654, 0xA655 }, // CYRILLIC CAPITAL LETTER REVERSED YU
{ 0xA656, 0xA657 }, // CYRILLIC CAPITAL LETTER IOTIFIED A
{ 0xA658, 0xA659 }, // CYRILLIC CAPITAL LETTER CLOSED LITTLE YUS
{ 0xA65A, 0xA65B }, // CYRILLIC CAPITAL LETTER BLENDED YUS
{ 0xA65C, 0xA65D }, // CYRILLIC CAPITAL LETTER IOTIFIED CLOSED LITTLE YUS
{ 0xA65E, 0xA65F }, // CYRILLIC CAPITAL LETTER YN
{ 0xA662, 0xA663 }, // CYRILLIC CAPITAL LETTER SOFT DE
{ 0xA664, 0xA665 }, // CYRILLIC CAPITAL LETTER SOFT EL
{ 0xA666, 0xA667 }, // CYRILLIC CAPITAL LETTER SOFT EM
{ 0xA668, 0xA669 }, // CYRILLIC CAPITAL LETTER MONOCULAR O
{ 0xA66A, 0xA66B }, // CYRILLIC CAPITAL LETTER BINOCULAR O
{ 0xA66C, 0xA66D }, // CYRILLIC CAPITAL LETTER DOUBLE MONOCULAR O
{ 0xA680, 0xA681 }, // CYRILLIC CAPITAL LETTER DWE
{ 0xA682, 0xA683 }, // CYRILLIC CAPITAL LETTER DZWE
{ 0xA684, 0xA685 }, // CYRILLIC CAPITAL LETTER ZHWE
{ 0xA686, 0xA687 }, // CYRILLIC CAPITAL LETTER CCHE
{ 0xA688, 0xA689 }, // CYRILLIC CAPITAL LETTER DZZE
{ 0xA68A, 0xA68B }, // CYRILLIC CAPITAL LETTER TE WITH MIDDLE HOOK
{ 0xA68C, 0xA68D }, // CYRILLIC CAPITAL LETTER TWE
{ 0xA68E, 0xA68F }, // CYRILLIC CAPITAL LETTER TSWE
{ 0xA690, 0xA691 }, // CYRILLIC CAPITAL LETTER TSSE
{ 0xA692, 0xA693 }, // CYRILLIC CAPITAL LETTER TCHE
{ 0xA694, 0xA695 }, // CYRILLIC CAPITAL LETTER HWE
{ 0xA696, 0xA697 }, // CYRILLIC CAPITAL LETTER SHWE
{ 0xA722, 0xA723 }, // LATIN CAPITAL LETTER EGYPTOLOGICAL ALEF
{ 0xA724, 0xA725 }, // LATIN CAPITAL LETTER EGYPTOLOGICAL AIN
{ 0xA726, 0xA727 }, // LATIN CAPITAL LETTER HENG
{ 0xA728, 0xA729 }, // LATIN CAPITAL LETTER TZ
{ 0xA72A, 0xA72B }, // LATIN CAPITAL LETTER TRESILLO
{ 0xA72C, 0xA72D }, // LATIN CAPITAL LETTER CUATRILLO
{ 0xA72E, 0xA72F }, // LATIN CAPITAL LETTER CUATRILLO WITH COMMA
{ 0xA732, 0xA733 }, // LATIN CAPITAL LETTER AA
{ 0xA734, 0xA735 }, // LATIN CAPITAL LETTER AO
{ 0xA736, 0xA737 }, // LATIN CAPITAL LETTER AU
{ 0xA738, 0xA739 }, // LATIN CAPITAL LETTER AV
{ 0xA73A, 0xA73B }, // LATIN CAPITAL LETTER AV WITH HORIZONTAL BAR
{ 0xA73C, 0xA73D }, // LATIN CAPITAL LETTER AY
{ 0xA73E, 0xA73F }, // LATIN CAPITAL LETTER REVERSED C WITH DOT
{ 0xA740, 0xA741 }, // LATIN CAPITAL LETTER K WITH STROKE
{ 0xA742, 0xA743 }, // LATIN CAPITAL LETTER K WITH DIAGONAL STROKE
{ 0xA744, 0xA745 }, // LATIN CAPITAL LETTER K WITH STROKE AND DIAGONAL STROKE
{ 0xA746, 0xA747 }, // LATIN CAPITAL LETTER BROKEN L
{ 0xA748, 0xA749 }, // LATIN CAPITAL LETTER L WITH HIGH STROKE
{ 0xA74A, 0xA74B }, // LATIN CAPITAL LETTER O WITH LONG STROKE OVERLAY
{ 0xA74C, 0xA74D }, // LATIN CAPITAL LETTER O WITH LOOP
{ 0xA74E, 0xA74F }, // LATIN CAPITAL LETTER OO
{ 0xA750, 0xA751 }, // LATIN CAPITAL LETTER P WITH STROKE THROUGH DESCENDER
{ 0xA752, 0xA753 }, // LATIN CAPITAL LETTER P WITH FLOURISH
{ 0xA754, 0xA755 }, // LATIN CAPITAL LETTER P WITH SQUIRREL TAIL
{ 0xA756, 0xA757 }, // LATIN CAPITAL LETTER Q WITH STROKE THROUGH DESCENDER
{ 0xA758, 0xA759 }, // LATIN CAPITAL LETTER Q WITH DIAGONAL STROKE
{ 0xA75A, 0xA75B }, // LATIN CAPITAL LETTER R ROTUNDA
{ 0xA75C, 0xA75D }, // LATIN CAPITAL LETTER RUM ROTUNDA
{ 0xA75E, 0xA75F }, // LATIN CAPITAL LETTER V WITH DIAGONAL STROKE
{ 0xA760, 0xA761 }, // LATIN CAPITAL LETTER VY
{ 0xA762, 0xA763 }, // LATIN CAPITAL LETTER VISIGOTHIC Z
{ 0xA764, 0xA765 }, // LATIN CAPITAL LETTER THORN WITH STROKE
{ 0xA766, 0xA767 }, // LATIN CAPITAL LETTER THORN WITH STROKE THROUGH DESCENDER
{ 0xA768, 0xA769 }, // LATIN CAPITAL LETTER VEND
{ 0xA76A, 0xA76B }, // LATIN CAPITAL LETTER ET
{ 0xA76C, 0xA76D }, // LATIN CAPITAL LETTER IS
{ 0xA76E, 0xA76F }, // LATIN CAPITAL LETTER CON
{ 0xA779, 0xA77A }, // LATIN CAPITAL LETTER INSULAR D
{ 0xA77B, 0xA77C }, // LATIN CAPITAL LETTER INSULAR F
{ 0xA77D, 0x1D79 }, // LATIN CAPITAL LETTER INSULAR G
{ 0xA77E, 0xA77F }, // LATIN CAPITAL LETTER TURNED INSULAR G
{ 0xA780, 0xA781 }, // LATIN CAPITAL LETTER TURNED L
{ 0xA782, 0xA783 }, // LATIN CAPITAL LETTER INSULAR R
{ 0xA784, 0xA785 }, // LATIN CAPITAL LETTER INSULAR S
{ 0xA786, 0xA787 }, // LATIN CAPITAL LETTER INSULAR T
{ 0xA78B, 0xA78C }, // LATIN CAPITAL LETTER SALTILLO
{ 0xFF21, 0xFF41 }, // FULLWIDTH LATIN CAPITAL LETTER A
{ 0xFF22, 0xFF42 }, // FULLWIDTH LATIN CAPITAL LETTER B
{ 0xFF23, 0xFF43 }, // FULLWIDTH LATIN CAPITAL LETTER C
{ 0xFF24, 0xFF44 }, // FULLWIDTH LATIN CAPITAL LETTER D
{ 0xFF25, 0xFF45 }, // FULLWIDTH LATIN CAPITAL LETTER E
{ 0xFF26, 0xFF46 }, // FULLWIDTH LATIN CAPITAL LETTER F
{ 0xFF27, 0xFF47 }, // FULLWIDTH LATIN CAPITAL LETTER G
{ 0xFF28, 0xFF48 }, // FULLWIDTH LATIN CAPITAL LETTER H
{ 0xFF29, 0xFF49 }, // FULLWIDTH LATIN CAPITAL LETTER I
{ 0xFF2A, 0xFF4A }, // FULLWIDTH LATIN CAPITAL LETTER J
{ 0xFF2B, 0xFF4B }, // FULLWIDTH LATIN CAPITAL LETTER K
{ 0xFF2C, 0xFF4C }, // FULLWIDTH LATIN CAPITAL LETTER L
{ 0xFF2D, 0xFF4D }, // FULLWIDTH LATIN CAPITAL LETTER M
{ 0xFF2E, 0xFF4E }, // FULLWIDTH LATIN CAPITAL LETTER N
{ 0xFF2F, 0xFF4F }, // FULLWIDTH LATIN CAPITAL LETTER O
{ 0xFF30, 0xFF50 }, // FULLWIDTH LATIN CAPITAL LETTER P
{ 0xFF31, 0xFF51 }, // FULLWIDTH LATIN CAPITAL LETTER Q
{ 0xFF32, 0xFF52 }, // FULLWIDTH LATIN CAPITAL LETTER R
{ 0xFF33, 0xFF53 }, // FULLWIDTH LATIN CAPITAL LETTER S
{ 0xFF34, 0xFF54 }, // FULLWIDTH LATIN CAPITAL LETTER T
{ 0xFF35, 0xFF55 }, // FULLWIDTH LATIN CAPITAL LETTER U
{ 0xFF36, 0xFF56 }, // FULLWIDTH LATIN CAPITAL LETTER V
{ 0xFF37, 0xFF57 }, // FULLWIDTH LATIN CAPITAL LETTER W
{ 0xFF38, 0xFF58 }, // FULLWIDTH LATIN CAPITAL LETTER X
{ 0xFF39, 0xFF59 }, // FULLWIDTH LATIN CAPITAL LETTER Y
{ 0xFF3A, 0xFF5A } // FULLWIDTH LATIN CAPITAL LETTER Z
};
static int compare_pair_capital(const void *a, const void *b) {
return (int)(*(unsigned short *)a)
- (int)((struct LatinCapitalSmallPair*)b)->capital;
}
unsigned short latin_tolower(unsigned short c) {
struct LatinCapitalSmallPair *p =
(struct LatinCapitalSmallPair *)bsearch(&c, SORTED_CHAR_MAP,
sizeof(SORTED_CHAR_MAP) / sizeof(SORTED_CHAR_MAP[0]),
sizeof(SORTED_CHAR_MAP[0]),
compare_pair_capital);
return p ? p->small : c;
}
} // namespace latinime
| 11beeaosama-descrbvbnvbniption | java/jni/src/char_utils.cpp | C++ | asf20 | 53,690 |
/**
* Table mapping most combined Latin, Greek, and Cyrillic characters
* to their base characters. If c is in range, BASE_CHARS[c] == c
* if c is not a combined character, or the base character if it
* is combined.
*/
static unsigned short BASE_CHARS[] = {
0x0000, 0x0001, 0x0002, 0x0003, 0x0004, 0x0005, 0x0006, 0x0007,
0x0008, 0x0009, 0x000a, 0x000b, 0x000c, 0x000d, 0x000e, 0x000f,
0x0010, 0x0011, 0x0012, 0x0013, 0x0014, 0x0015, 0x0016, 0x0017,
0x0018, 0x0019, 0x001a, 0x001b, 0x001c, 0x001d, 0x001e, 0x001f,
0x0020, 0x0021, 0x0022, 0x0023, 0x0024, 0x0025, 0x0026, 0x0027,
0x0028, 0x0029, 0x002a, 0x002b, 0x002c, 0x002d, 0x002e, 0x002f,
0x0030, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, 0x0036, 0x0037,
0x0038, 0x0039, 0x003a, 0x003b, 0x003c, 0x003d, 0x003e, 0x003f,
0x0040, 0x0041, 0x0042, 0x0043, 0x0044, 0x0045, 0x0046, 0x0047,
0x0048, 0x0049, 0x004a, 0x004b, 0x004c, 0x004d, 0x004e, 0x004f,
0x0050, 0x0051, 0x0052, 0x0053, 0x0054, 0x0055, 0x0056, 0x0057,
0x0058, 0x0059, 0x005a, 0x005b, 0x005c, 0x005d, 0x005e, 0x005f,
0x0060, 0x0061, 0x0062, 0x0063, 0x0064, 0x0065, 0x0066, 0x0067,
0x0068, 0x0069, 0x006a, 0x006b, 0x006c, 0x006d, 0x006e, 0x006f,
0x0070, 0x0071, 0x0072, 0x0073, 0x0074, 0x0075, 0x0076, 0x0077,
0x0078, 0x0079, 0x007a, 0x007b, 0x007c, 0x007d, 0x007e, 0x007f,
0x0080, 0x0081, 0x0082, 0x0083, 0x0084, 0x0085, 0x0086, 0x0087,
0x0088, 0x0089, 0x008a, 0x008b, 0x008c, 0x008d, 0x008e, 0x008f,
0x0090, 0x0091, 0x0092, 0x0093, 0x0094, 0x0095, 0x0096, 0x0097,
0x0098, 0x0099, 0x009a, 0x009b, 0x009c, 0x009d, 0x009e, 0x009f,
0x0020, 0x00a1, 0x00a2, 0x00a3, 0x00a4, 0x00a5, 0x00a6, 0x00a7,
0x0020, 0x00a9, 0x0061, 0x00ab, 0x00ac, 0x00ad, 0x00ae, 0x0020,
0x00b0, 0x00b1, 0x0032, 0x0033, 0x0020, 0x03bc, 0x00b6, 0x00b7,
0x0020, 0x0031, 0x006f, 0x00bb, 0x0031, 0x0031, 0x0033, 0x00bf,
0x0041, 0x0041, 0x0041, 0x0041, 0x0041, 0x0041, 0x00c6, 0x0043,
0x0045, 0x0045, 0x0045, 0x0045, 0x0049, 0x0049, 0x0049, 0x0049,
0x00d0, 0x004e, 0x004f, 0x004f, 0x004f, 0x004f, 0x004f, 0x00d7,
0x004f, 0x0055, 0x0055, 0x0055, 0x0055, 0x0059, 0x00de, 0x0073, // Manually changed d8 to 4f
// Manually changed df to 73
0x0061, 0x0061, 0x0061, 0x0061, 0x0061, 0x0061, 0x00e6, 0x0063,
0x0065, 0x0065, 0x0065, 0x0065, 0x0069, 0x0069, 0x0069, 0x0069,
0x00f0, 0x006e, 0x006f, 0x006f, 0x006f, 0x006f, 0x006f, 0x00f7,
0x006f, 0x0075, 0x0075, 0x0075, 0x0075, 0x0079, 0x00fe, 0x0079, // Manually changed f8 to 6f
0x0041, 0x0061, 0x0041, 0x0061, 0x0041, 0x0061, 0x0043, 0x0063,
0x0043, 0x0063, 0x0043, 0x0063, 0x0043, 0x0063, 0x0044, 0x0064,
0x0110, 0x0111, 0x0045, 0x0065, 0x0045, 0x0065, 0x0045, 0x0065,
0x0045, 0x0065, 0x0045, 0x0065, 0x0047, 0x0067, 0x0047, 0x0067,
0x0047, 0x0067, 0x0047, 0x0067, 0x0048, 0x0068, 0x0126, 0x0127,
0x0049, 0x0069, 0x0049, 0x0069, 0x0049, 0x0069, 0x0049, 0x0069,
0x0049, 0x0131, 0x0049, 0x0069, 0x004a, 0x006a, 0x004b, 0x006b,
0x0138, 0x004c, 0x006c, 0x004c, 0x006c, 0x004c, 0x006c, 0x004c,
0x006c, 0x0141, 0x0142, 0x004e, 0x006e, 0x004e, 0x006e, 0x004e,
0x006e, 0x02bc, 0x014a, 0x014b, 0x004f, 0x006f, 0x004f, 0x006f,
0x004f, 0x006f, 0x0152, 0x0153, 0x0052, 0x0072, 0x0052, 0x0072,
0x0052, 0x0072, 0x0053, 0x0073, 0x0053, 0x0073, 0x0053, 0x0073,
0x0053, 0x0073, 0x0054, 0x0074, 0x0054, 0x0074, 0x0166, 0x0167,
0x0055, 0x0075, 0x0055, 0x0075, 0x0055, 0x0075, 0x0055, 0x0075,
0x0055, 0x0075, 0x0055, 0x0075, 0x0057, 0x0077, 0x0059, 0x0079,
0x0059, 0x005a, 0x007a, 0x005a, 0x007a, 0x005a, 0x007a, 0x0073,
0x0180, 0x0181, 0x0182, 0x0183, 0x0184, 0x0185, 0x0186, 0x0187,
0x0188, 0x0189, 0x018a, 0x018b, 0x018c, 0x018d, 0x018e, 0x018f,
0x0190, 0x0191, 0x0192, 0x0193, 0x0194, 0x0195, 0x0196, 0x0197,
0x0198, 0x0199, 0x019a, 0x019b, 0x019c, 0x019d, 0x019e, 0x019f,
0x004f, 0x006f, 0x01a2, 0x01a3, 0x01a4, 0x01a5, 0x01a6, 0x01a7,
0x01a8, 0x01a9, 0x01aa, 0x01ab, 0x01ac, 0x01ad, 0x01ae, 0x0055,
0x0075, 0x01b1, 0x01b2, 0x01b3, 0x01b4, 0x01b5, 0x01b6, 0x01b7,
0x01b8, 0x01b9, 0x01ba, 0x01bb, 0x01bc, 0x01bd, 0x01be, 0x01bf,
0x01c0, 0x01c1, 0x01c2, 0x01c3, 0x0044, 0x0044, 0x0064, 0x004c,
0x004c, 0x006c, 0x004e, 0x004e, 0x006e, 0x0041, 0x0061, 0x0049,
0x0069, 0x004f, 0x006f, 0x0055, 0x0075, 0x00dc, 0x00fc, 0x00dc,
0x00fc, 0x00dc, 0x00fc, 0x00dc, 0x00fc, 0x01dd, 0x00c4, 0x00e4,
0x0226, 0x0227, 0x00c6, 0x00e6, 0x01e4, 0x01e5, 0x0047, 0x0067,
0x004b, 0x006b, 0x004f, 0x006f, 0x01ea, 0x01eb, 0x01b7, 0x0292,
0x006a, 0x0044, 0x0044, 0x0064, 0x0047, 0x0067, 0x01f6, 0x01f7,
0x004e, 0x006e, 0x00c5, 0x00e5, 0x00c6, 0x00e6, 0x00d8, 0x00f8,
0x0041, 0x0061, 0x0041, 0x0061, 0x0045, 0x0065, 0x0045, 0x0065,
0x0049, 0x0069, 0x0049, 0x0069, 0x004f, 0x006f, 0x004f, 0x006f,
0x0052, 0x0072, 0x0052, 0x0072, 0x0055, 0x0075, 0x0055, 0x0075,
0x0053, 0x0073, 0x0054, 0x0074, 0x021c, 0x021d, 0x0048, 0x0068,
0x0220, 0x0221, 0x0222, 0x0223, 0x0224, 0x0225, 0x0041, 0x0061,
0x0045, 0x0065, 0x00d6, 0x00f6, 0x00d5, 0x00f5, 0x004f, 0x006f,
0x022e, 0x022f, 0x0059, 0x0079, 0x0234, 0x0235, 0x0236, 0x0237,
0x0238, 0x0239, 0x023a, 0x023b, 0x023c, 0x023d, 0x023e, 0x023f,
0x0240, 0x0241, 0x0242, 0x0243, 0x0244, 0x0245, 0x0246, 0x0247,
0x0248, 0x0249, 0x024a, 0x024b, 0x024c, 0x024d, 0x024e, 0x024f,
0x0250, 0x0251, 0x0252, 0x0253, 0x0254, 0x0255, 0x0256, 0x0257,
0x0258, 0x0259, 0x025a, 0x025b, 0x025c, 0x025d, 0x025e, 0x025f,
0x0260, 0x0261, 0x0262, 0x0263, 0x0264, 0x0265, 0x0266, 0x0267,
0x0268, 0x0269, 0x026a, 0x026b, 0x026c, 0x026d, 0x026e, 0x026f,
0x0270, 0x0271, 0x0272, 0x0273, 0x0274, 0x0275, 0x0276, 0x0277,
0x0278, 0x0279, 0x027a, 0x027b, 0x027c, 0x027d, 0x027e, 0x027f,
0x0280, 0x0281, 0x0282, 0x0283, 0x0284, 0x0285, 0x0286, 0x0287,
0x0288, 0x0289, 0x028a, 0x028b, 0x028c, 0x028d, 0x028e, 0x028f,
0x0290, 0x0291, 0x0292, 0x0293, 0x0294, 0x0295, 0x0296, 0x0297,
0x0298, 0x0299, 0x029a, 0x029b, 0x029c, 0x029d, 0x029e, 0x029f,
0x02a0, 0x02a1, 0x02a2, 0x02a3, 0x02a4, 0x02a5, 0x02a6, 0x02a7,
0x02a8, 0x02a9, 0x02aa, 0x02ab, 0x02ac, 0x02ad, 0x02ae, 0x02af,
0x0068, 0x0266, 0x006a, 0x0072, 0x0279, 0x027b, 0x0281, 0x0077,
0x0079, 0x02b9, 0x02ba, 0x02bb, 0x02bc, 0x02bd, 0x02be, 0x02bf,
0x02c0, 0x02c1, 0x02c2, 0x02c3, 0x02c4, 0x02c5, 0x02c6, 0x02c7,
0x02c8, 0x02c9, 0x02ca, 0x02cb, 0x02cc, 0x02cd, 0x02ce, 0x02cf,
0x02d0, 0x02d1, 0x02d2, 0x02d3, 0x02d4, 0x02d5, 0x02d6, 0x02d7,
0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x02de, 0x02df,
0x0263, 0x006c, 0x0073, 0x0078, 0x0295, 0x02e5, 0x02e6, 0x02e7,
0x02e8, 0x02e9, 0x02ea, 0x02eb, 0x02ec, 0x02ed, 0x02ee, 0x02ef,
0x02f0, 0x02f1, 0x02f2, 0x02f3, 0x02f4, 0x02f5, 0x02f6, 0x02f7,
0x02f8, 0x02f9, 0x02fa, 0x02fb, 0x02fc, 0x02fd, 0x02fe, 0x02ff,
0x0300, 0x0301, 0x0302, 0x0303, 0x0304, 0x0305, 0x0306, 0x0307,
0x0308, 0x0309, 0x030a, 0x030b, 0x030c, 0x030d, 0x030e, 0x030f,
0x0310, 0x0311, 0x0312, 0x0313, 0x0314, 0x0315, 0x0316, 0x0317,
0x0318, 0x0319, 0x031a, 0x031b, 0x031c, 0x031d, 0x031e, 0x031f,
0x0320, 0x0321, 0x0322, 0x0323, 0x0324, 0x0325, 0x0326, 0x0327,
0x0328, 0x0329, 0x032a, 0x032b, 0x032c, 0x032d, 0x032e, 0x032f,
0x0330, 0x0331, 0x0332, 0x0333, 0x0334, 0x0335, 0x0336, 0x0337,
0x0338, 0x0339, 0x033a, 0x033b, 0x033c, 0x033d, 0x033e, 0x033f,
0x0300, 0x0301, 0x0342, 0x0313, 0x0308, 0x0345, 0x0346, 0x0347,
0x0348, 0x0349, 0x034a, 0x034b, 0x034c, 0x034d, 0x034e, 0x034f,
0x0350, 0x0351, 0x0352, 0x0353, 0x0354, 0x0355, 0x0356, 0x0357,
0x0358, 0x0359, 0x035a, 0x035b, 0x035c, 0x035d, 0x035e, 0x035f,
0x0360, 0x0361, 0x0362, 0x0363, 0x0364, 0x0365, 0x0366, 0x0367,
0x0368, 0x0369, 0x036a, 0x036b, 0x036c, 0x036d, 0x036e, 0x036f,
0x0370, 0x0371, 0x0372, 0x0373, 0x02b9, 0x0375, 0x0376, 0x0377,
0x0378, 0x0379, 0x0020, 0x037b, 0x037c, 0x037d, 0x003b, 0x037f,
0x0380, 0x0381, 0x0382, 0x0383, 0x0020, 0x00a8, 0x0391, 0x00b7,
0x0395, 0x0397, 0x0399, 0x038b, 0x039f, 0x038d, 0x03a5, 0x03a9,
0x03ca, 0x0391, 0x0392, 0x0393, 0x0394, 0x0395, 0x0396, 0x0397,
0x0398, 0x0399, 0x039a, 0x039b, 0x039c, 0x039d, 0x039e, 0x039f,
0x03a0, 0x03a1, 0x03a2, 0x03a3, 0x03a4, 0x03a5, 0x03a6, 0x03a7,
0x03a8, 0x03a9, 0x0399, 0x03a5, 0x03b1, 0x03b5, 0x03b7, 0x03b9,
0x03cb, 0x03b1, 0x03b2, 0x03b3, 0x03b4, 0x03b5, 0x03b6, 0x03b7,
0x03b8, 0x03b9, 0x03ba, 0x03bb, 0x03bc, 0x03bd, 0x03be, 0x03bf,
0x03c0, 0x03c1, 0x03c2, 0x03c3, 0x03c4, 0x03c5, 0x03c6, 0x03c7,
0x03c8, 0x03c9, 0x03b9, 0x03c5, 0x03bf, 0x03c5, 0x03c9, 0x03cf,
0x03b2, 0x03b8, 0x03a5, 0x03d2, 0x03d2, 0x03c6, 0x03c0, 0x03d7,
0x03d8, 0x03d9, 0x03da, 0x03db, 0x03dc, 0x03dd, 0x03de, 0x03df,
0x03e0, 0x03e1, 0x03e2, 0x03e3, 0x03e4, 0x03e5, 0x03e6, 0x03e7,
0x03e8, 0x03e9, 0x03ea, 0x03eb, 0x03ec, 0x03ed, 0x03ee, 0x03ef,
0x03ba, 0x03c1, 0x03c2, 0x03f3, 0x0398, 0x03b5, 0x03f6, 0x03f7,
0x03f8, 0x03a3, 0x03fa, 0x03fb, 0x03fc, 0x03fd, 0x03fe, 0x03ff,
0x0415, 0x0415, 0x0402, 0x0413, 0x0404, 0x0405, 0x0406, 0x0406,
0x0408, 0x0409, 0x040a, 0x040b, 0x041a, 0x0418, 0x0423, 0x040f,
0x0410, 0x0411, 0x0412, 0x0413, 0x0414, 0x0415, 0x0416, 0x0417,
0x0418, 0x0418, 0x041a, 0x041b, 0x041c, 0x041d, 0x041e, 0x041f,
0x0420, 0x0421, 0x0422, 0x0423, 0x0424, 0x0425, 0x0426, 0x0427,
0x0428, 0x0429, 0x042a, 0x042b, 0x042c, 0x042d, 0x042e, 0x042f,
0x0430, 0x0431, 0x0432, 0x0433, 0x0434, 0x0435, 0x0436, 0x0437,
0x0438, 0x0438, 0x043a, 0x043b, 0x043c, 0x043d, 0x043e, 0x043f,
0x0440, 0x0441, 0x0442, 0x0443, 0x0444, 0x0445, 0x0446, 0x0447,
0x0448, 0x0449, 0x044a, 0x044b, 0x044c, 0x044d, 0x044e, 0x044f,
0x0435, 0x0435, 0x0452, 0x0433, 0x0454, 0x0455, 0x0456, 0x0456,
0x0458, 0x0459, 0x045a, 0x045b, 0x043a, 0x0438, 0x0443, 0x045f,
0x0460, 0x0461, 0x0462, 0x0463, 0x0464, 0x0465, 0x0466, 0x0467,
0x0468, 0x0469, 0x046a, 0x046b, 0x046c, 0x046d, 0x046e, 0x046f,
0x0470, 0x0471, 0x0472, 0x0473, 0x0474, 0x0475, 0x0474, 0x0475,
0x0478, 0x0479, 0x047a, 0x047b, 0x047c, 0x047d, 0x047e, 0x047f,
0x0480, 0x0481, 0x0482, 0x0483, 0x0484, 0x0485, 0x0486, 0x0487,
0x0488, 0x0489, 0x048a, 0x048b, 0x048c, 0x048d, 0x048e, 0x048f,
0x0490, 0x0491, 0x0492, 0x0493, 0x0494, 0x0495, 0x0496, 0x0497,
0x0498, 0x0499, 0x049a, 0x049b, 0x049c, 0x049d, 0x049e, 0x049f,
0x04a0, 0x04a1, 0x04a2, 0x04a3, 0x04a4, 0x04a5, 0x04a6, 0x04a7,
0x04a8, 0x04a9, 0x04aa, 0x04ab, 0x04ac, 0x04ad, 0x04ae, 0x04af,
0x04b0, 0x04b1, 0x04b2, 0x04b3, 0x04b4, 0x04b5, 0x04b6, 0x04b7,
0x04b8, 0x04b9, 0x04ba, 0x04bb, 0x04bc, 0x04bd, 0x04be, 0x04bf,
0x04c0, 0x0416, 0x0436, 0x04c3, 0x04c4, 0x04c5, 0x04c6, 0x04c7,
0x04c8, 0x04c9, 0x04ca, 0x04cb, 0x04cc, 0x04cd, 0x04ce, 0x04cf,
0x0410, 0x0430, 0x0410, 0x0430, 0x04d4, 0x04d5, 0x0415, 0x0435,
0x04d8, 0x04d9, 0x04d8, 0x04d9, 0x0416, 0x0436, 0x0417, 0x0437,
0x04e0, 0x04e1, 0x0418, 0x0438, 0x0418, 0x0438, 0x041e, 0x043e,
0x04e8, 0x04e9, 0x04e8, 0x04e9, 0x042d, 0x044d, 0x0423, 0x0443,
0x0423, 0x0443, 0x0423, 0x0443, 0x0427, 0x0447, 0x04f6, 0x04f7,
0x042b, 0x044b, 0x04fa, 0x04fb, 0x04fc, 0x04fd, 0x04fe, 0x04ff,
};
// generated with:
// cat UnicodeData.txt | perl -e 'while (<>) { @foo = split(/;/); $foo[5] =~ s/<.*> //; $base[hex($foo[0])] = hex($foo[5]);} for ($i = 0; $i < 0x500; $i += 8) { for ($j = $i; $j < $i + 8; $j++) { printf("0x%04x, ", $base[$j] ? $base[$j] : $j)}; print "\n"; }'
| 11beeaosama-descrbvbnvbniption | java/jni/src/basechars.h | C | asf20 | 11,582 |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef LATINIME_CHAR_UTILS_H
#define LATINIME_CHAR_UTILS_H
namespace latinime {
unsigned short latin_tolower(unsigned short c);
}; // namespace latinime
#endif // LATINIME_CHAR_UTILS_H
| 11beeaosama-descrbvbnvbniption | java/jni/src/char_utils.h | C++ | asf20 | 811 |
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef LATINIME_DICTIONARY_H
#define LATINIME_DICTIONARY_H
namespace latinime {
// 22-bit address = ~4MB dictionary size limit, which on average would be about 200k-300k words
#define ADDRESS_MASK 0x3FFFFF
// The bit that decides if an address follows in the next 22 bits
#define FLAG_ADDRESS_MASK 0x40
// The bit that decides if this is a terminal node for a word. The node could still have children,
// if the word has other endings.
#define FLAG_TERMINAL_MASK 0x80
#define FLAG_BIGRAM_READ 0x80
#define FLAG_BIGRAM_CHILDEXIST 0x40
#define FLAG_BIGRAM_CONTINUED 0x80
#define FLAG_BIGRAM_FREQ 0x7F
class Dictionary {
public:
Dictionary(void *dict, int typedLetterMultipler, int fullWordMultiplier, int dictSize);
int getSuggestions(int *codes, int codesSize, unsigned short *outWords, int *frequencies,
int maxWordLength, int maxWords, int maxAlternatives, int skipPos,
int *nextLetters, int nextLettersSize);
int getBigrams(unsigned short *word, int length, int *codes, int codesSize,
unsigned short *outWords, int *frequencies, int maxWordLength, int maxBigrams,
int maxAlternatives);
bool isValidWord(unsigned short *word, int length);
void setAsset(void *asset) { mAsset = asset; }
void *getAsset() { return mAsset; }
~Dictionary();
private:
void getVersionNumber();
bool checkIfDictVersionIsLatest();
int getAddress(int *pos);
int getBigramAddress(int *pos, bool advance);
int getFreq(int *pos);
int getBigramFreq(int *pos);
void searchForTerminalNode(int address, int frequency);
bool getFirstBitOfByte(int *pos) { return (mDict[*pos] & 0x80) > 0; }
bool getSecondBitOfByte(int *pos) { return (mDict[*pos] & 0x40) > 0; }
bool getTerminal(int *pos) { return (mDict[*pos] & FLAG_TERMINAL_MASK) > 0; }
int getCount(int *pos) { return mDict[(*pos)++] & 0xFF; }
unsigned short getChar(int *pos);
int wideStrLen(unsigned short *str);
bool sameAsTyped(unsigned short *word, int length);
bool checkFirstCharacter(unsigned short *word);
bool addWord(unsigned short *word, int length, int frequency);
bool addWordBigram(unsigned short *word, int length, int frequency);
unsigned short toLowerCase(unsigned short c);
void getWordsRec(int pos, int depth, int maxDepth, bool completion, int frequency,
int inputIndex, int diffs);
int isValidWordRec(int pos, unsigned short *word, int offset, int length);
void registerNextLetter(unsigned short c);
unsigned char *mDict;
void *mAsset;
int *mFrequencies;
int *mBigramFreq;
int mMaxWords;
int mMaxBigrams;
int mMaxWordLength;
unsigned short *mOutputChars;
unsigned short *mBigramChars;
int *mInputCodes;
int mInputLength;
int mMaxAlternatives;
unsigned short mWord[128];
int mSkipPos;
int mMaxEditDistance;
int mFullWordMultiplier;
int mTypedLetterMultiplier;
int mDictSize;
int *mNextLettersFrequencies;
int mNextLettersSize;
int mVersion;
int mBigram;
};
// ----------------------------------------------------------------------------
}; // namespace latinime
#endif // LATINIME_DICTIONARY_H
| 11beeaosama-descrbvbnvbniption | java/jni/src/dictionary.h | C++ | asf20 | 3,832 |
/*
**
** Copyright 2009, The Android Open Source Project
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
#include <stdio.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <string.h>
//#define LOG_TAG "dictionary.cpp"
//#include <cutils/log.h>
#define LOGI
#include "dictionary.h"
#include "basechars.h"
#include "char_utils.h"
#define DEBUG_DICT 0
#define DICTIONARY_VERSION_MIN 200
#define DICTIONARY_HEADER_SIZE 2
#define NOT_VALID_WORD -99
namespace latinime {
Dictionary::Dictionary(void *dict, int typedLetterMultiplier, int fullWordMultiplier, int size)
{
mDict = (unsigned char*) dict;
mTypedLetterMultiplier = typedLetterMultiplier;
mFullWordMultiplier = fullWordMultiplier;
mDictSize = size;
getVersionNumber();
}
Dictionary::~Dictionary()
{
}
int Dictionary::getSuggestions(int *codes, int codesSize, unsigned short *outWords, int *frequencies,
int maxWordLength, int maxWords, int maxAlternatives, int skipPos,
int *nextLetters, int nextLettersSize)
{
int suggWords;
mFrequencies = frequencies;
mOutputChars = outWords;
mInputCodes = codes;
mInputLength = codesSize;
mMaxAlternatives = maxAlternatives;
mMaxWordLength = maxWordLength;
mMaxWords = maxWords;
mSkipPos = skipPos;
mMaxEditDistance = mInputLength < 5 ? 2 : mInputLength / 2;
mNextLettersFrequencies = nextLetters;
mNextLettersSize = nextLettersSize;
if (checkIfDictVersionIsLatest()) {
getWordsRec(DICTIONARY_HEADER_SIZE, 0, mInputLength * 3, false, 1, 0, 0);
} else {
getWordsRec(0, 0, mInputLength * 3, false, 1, 0, 0);
}
// Get the word count
suggWords = 0;
while (suggWords < mMaxWords && mFrequencies[suggWords] > 0) suggWords++;
if (DEBUG_DICT) LOGI("Returning %d words", suggWords);
if (DEBUG_DICT) {
LOGI("Next letters: ");
for (int k = 0; k < nextLettersSize; k++) {
if (mNextLettersFrequencies[k] > 0) {
LOGI("%c = %d,", k, mNextLettersFrequencies[k]);
}
}
LOGI("\n");
}
return suggWords;
}
void
Dictionary::registerNextLetter(unsigned short c)
{
if (c < mNextLettersSize) {
mNextLettersFrequencies[c]++;
}
}
void
Dictionary::getVersionNumber()
{
mVersion = (mDict[0] & 0xFF);
mBigram = (mDict[1] & 0xFF);
LOGI("IN NATIVE SUGGEST Version: %d Bigram : %d \n", mVersion, mBigram);
}
// Checks whether it has the latest dictionary or the old dictionary
bool
Dictionary::checkIfDictVersionIsLatest()
{
return (mVersion >= DICTIONARY_VERSION_MIN) && (mBigram == 1 || mBigram == 0);
}
unsigned short
Dictionary::getChar(int *pos)
{
if (*pos < 0 || *pos >= mDictSize) return 0;
unsigned short ch = (unsigned short) (mDict[(*pos)++] & 0xFF);
// If the code is 255, then actual 16 bit code follows (in big endian)
if (ch == 0xFF) {
ch = ((mDict[*pos] & 0xFF) << 8) | (mDict[*pos + 1] & 0xFF);
(*pos) += 2;
}
return ch;
}
int
Dictionary::getAddress(int *pos)
{
if (*pos < 0 || *pos >= mDictSize) return 0;
int address = 0;
if ((mDict[*pos] & FLAG_ADDRESS_MASK) == 0) {
*pos += 1;
} else {
address += (mDict[*pos] & (ADDRESS_MASK >> 16)) << 16;
address += (mDict[*pos + 1] & 0xFF) << 8;
address += (mDict[*pos + 2] & 0xFF);
*pos += 3;
}
if (address < 0 || address >= mDictSize) return 0;
return address;
}
int
Dictionary::getFreq(int *pos)
{
if (*pos < 0 || *pos >= mDictSize) return 0;
int freq = mDict[(*pos)++] & 0xFF;
if (checkIfDictVersionIsLatest()) {
// skipping bigram
int bigramExist = (mDict[*pos] & FLAG_BIGRAM_READ);
if (bigramExist > 0) {
int nextBigramExist = 1;
while (nextBigramExist > 0) {
(*pos) += 3;
nextBigramExist = (mDict[(*pos)++] & FLAG_BIGRAM_CONTINUED);
}
} else {
(*pos)++;
}
}
return freq;
}
int
Dictionary::wideStrLen(unsigned short *str)
{
if (!str) return 0;
unsigned short *end = str;
while (*end)
end++;
return end - str;
}
bool
Dictionary::addWord(unsigned short *word, int length, int frequency)
{
word[length] = 0;
if (DEBUG_DICT) {
char s[length + 1];
for (int i = 0; i <= length; i++) s[i] = word[i];
LOGI("Found word = %s, freq = %d : \n", s, frequency);
}
// Find the right insertion point
int insertAt = 0;
while (insertAt < mMaxWords) {
if (frequency > mFrequencies[insertAt]
|| (mFrequencies[insertAt] == frequency
&& length < wideStrLen(mOutputChars + insertAt * mMaxWordLength))) {
break;
}
insertAt++;
}
if (insertAt < mMaxWords) {
memmove((char*) mFrequencies + (insertAt + 1) * sizeof(mFrequencies[0]),
(char*) mFrequencies + insertAt * sizeof(mFrequencies[0]),
(mMaxWords - insertAt - 1) * sizeof(mFrequencies[0]));
mFrequencies[insertAt] = frequency;
memmove((char*) mOutputChars + (insertAt + 1) * mMaxWordLength * sizeof(short),
(char*) mOutputChars + (insertAt ) * mMaxWordLength * sizeof(short),
(mMaxWords - insertAt - 1) * sizeof(short) * mMaxWordLength);
unsigned short *dest = mOutputChars + (insertAt ) * mMaxWordLength;
while (length--) {
*dest++ = *word++;
}
*dest = 0; // NULL terminate
if (DEBUG_DICT) LOGI("Added word at %d\n", insertAt);
return true;
}
return false;
}
bool
Dictionary::addWordBigram(unsigned short *word, int length, int frequency)
{
word[length] = 0;
if (DEBUG_DICT) {
char s[length + 1];
for (int i = 0; i <= length; i++) s[i] = word[i];
LOGI("Bigram: Found word = %s, freq = %d : \n", s, frequency);
}
// Find the right insertion point
int insertAt = 0;
while (insertAt < mMaxBigrams) {
if (frequency > mBigramFreq[insertAt]
|| (mBigramFreq[insertAt] == frequency
&& length < wideStrLen(mBigramChars + insertAt * mMaxWordLength))) {
break;
}
insertAt++;
}
LOGI("Bigram: InsertAt -> %d maxBigrams: %d\n", insertAt, mMaxBigrams);
if (insertAt < mMaxBigrams) {
memmove((char*) mBigramFreq + (insertAt + 1) * sizeof(mBigramFreq[0]),
(char*) mBigramFreq + insertAt * sizeof(mBigramFreq[0]),
(mMaxBigrams - insertAt - 1) * sizeof(mBigramFreq[0]));
mBigramFreq[insertAt] = frequency;
memmove((char*) mBigramChars + (insertAt + 1) * mMaxWordLength * sizeof(short),
(char*) mBigramChars + (insertAt ) * mMaxWordLength * sizeof(short),
(mMaxBigrams - insertAt - 1) * sizeof(short) * mMaxWordLength);
unsigned short *dest = mBigramChars + (insertAt ) * mMaxWordLength;
while (length--) {
*dest++ = *word++;
}
*dest = 0; // NULL terminate
if (DEBUG_DICT) LOGI("Bigram: Added word at %d\n", insertAt);
return true;
}
return false;
}
unsigned short
Dictionary::toLowerCase(unsigned short c) {
if (c < sizeof(BASE_CHARS) / sizeof(BASE_CHARS[0])) {
c = BASE_CHARS[c];
}
if (c >='A' && c <= 'Z') {
c |= 32;
} else if (c > 127) {
c = latin_tolower(c);
}
return c;
}
bool
Dictionary::sameAsTyped(unsigned short *word, int length)
{
if (length != mInputLength) {
return false;
}
int *inputCodes = mInputCodes;
while (length--) {
if ((unsigned int) *inputCodes != (unsigned int) *word) {
return false;
}
inputCodes += mMaxAlternatives;
word++;
}
return true;
}
static char QUOTE = '\'';
void
Dictionary::getWordsRec(int pos, int depth, int maxDepth, bool completion, int snr, int inputIndex,
int diffs)
{
// Optimization: Prune out words that are too long compared to how much was typed.
if (depth > maxDepth) {
return;
}
if (diffs > mMaxEditDistance) {
return;
}
int count = getCount(&pos);
int *currentChars = NULL;
if (mInputLength <= inputIndex) {
completion = true;
} else {
currentChars = mInputCodes + (inputIndex * mMaxAlternatives);
}
for (int i = 0; i < count; i++) {
// -- at char
unsigned short c = getChar(&pos);
// -- at flag/add
unsigned short lowerC = toLowerCase(c);
bool terminal = getTerminal(&pos);
int childrenAddress = getAddress(&pos);
// -- after address or flag
int freq = 1;
if (terminal) freq = getFreq(&pos);
// -- after add or freq
// If we are only doing completions, no need to look at the typed characters.
if (completion) {
mWord[depth] = c;
if (terminal) {
addWord(mWord, depth + 1, freq * snr);
if (depth >= mInputLength && mSkipPos < 0) {
registerNextLetter(mWord[mInputLength]);
}
}
if (childrenAddress != 0) {
getWordsRec(childrenAddress, depth + 1, maxDepth,
completion, snr, inputIndex, diffs);
}
} else if ((c == QUOTE && currentChars[0] != QUOTE) || mSkipPos == depth) {
// Skip the ' or other letter and continue deeper
mWord[depth] = c;
if (childrenAddress != 0) {
getWordsRec(childrenAddress, depth + 1, maxDepth, false, snr, inputIndex, diffs);
}
} else {
int j = 0;
while (currentChars[j] > 0) {
if (currentChars[j] == lowerC || currentChars[j] == c) {
int addedWeight = j == 0 ? mTypedLetterMultiplier : 1;
mWord[depth] = c;
if (mInputLength == inputIndex + 1) {
if (terminal) {
if (//INCLUDE_TYPED_WORD_IF_VALID ||
!sameAsTyped(mWord, depth + 1)) {
int finalFreq = freq * snr * addedWeight;
if (mSkipPos < 0) finalFreq *= mFullWordMultiplier;
addWord(mWord, depth + 1, finalFreq);
}
}
if (childrenAddress != 0) {
getWordsRec(childrenAddress, depth + 1,
maxDepth, true, snr * addedWeight, inputIndex + 1,
diffs + (j > 0));
}
} else if (childrenAddress != 0) {
getWordsRec(childrenAddress, depth + 1, maxDepth,
false, snr * addedWeight, inputIndex + 1, diffs + (j > 0));
}
}
j++;
if (mSkipPos >= 0) break;
}
}
}
}
int
Dictionary::getBigramAddress(int *pos, bool advance)
{
if (*pos < 0 || *pos >= mDictSize) return 0;
int address = 0;
address += (mDict[*pos] & 0x3F) << 16;
address += (mDict[*pos + 1] & 0xFF) << 8;
address += (mDict[*pos + 2] & 0xFF);
if (advance) {
*pos += 3;
}
if (address < 0 || address >= mDictSize) return 0;
return address;
}
int
Dictionary::getBigramFreq(int *pos)
{
if (*pos < 0 || *pos >= mDictSize) return 0;
int freq = mDict[(*pos)++] & FLAG_BIGRAM_FREQ;
return freq;
}
int
Dictionary::getBigrams(unsigned short *prevWord, int prevWordLength, int *codes, int codesSize,
unsigned short *bigramChars, int *bigramFreq, int maxWordLength, int maxBigrams,
int maxAlternatives)
{
mBigramFreq = bigramFreq;
mBigramChars = bigramChars;
mInputCodes = codes;
mInputLength = codesSize;
mMaxWordLength = maxWordLength;
mMaxBigrams = maxBigrams;
mMaxAlternatives = maxAlternatives;
if (mBigram == 1 && checkIfDictVersionIsLatest()) {
int pos = isValidWordRec(DICTIONARY_HEADER_SIZE, prevWord, 0, prevWordLength);
LOGI("Pos -> %d\n", pos);
if (pos < 0) {
return 0;
}
int bigramCount = 0;
int bigramExist = (mDict[pos] & FLAG_BIGRAM_READ);
if (bigramExist > 0) {
int nextBigramExist = 1;
while (nextBigramExist > 0 && bigramCount < maxBigrams) {
int bigramAddress = getBigramAddress(&pos, true);
int frequency = (FLAG_BIGRAM_FREQ & mDict[pos]);
// search for all bigrams and store them
searchForTerminalNode(bigramAddress, frequency);
nextBigramExist = (mDict[pos++] & FLAG_BIGRAM_CONTINUED);
bigramCount++;
}
}
return bigramCount;
}
return 0;
}
void
Dictionary::searchForTerminalNode(int addressLookingFor, int frequency)
{
// track word with such address and store it in an array
unsigned short word[mMaxWordLength];
int pos;
int followDownBranchAddress = DICTIONARY_HEADER_SIZE;
bool found = false;
char followingChar = ' ';
int depth = -1;
while(!found) {
bool followDownAddressSearchStop = false;
bool firstAddress = true;
bool haveToSearchAll = true;
if (depth >= 0) {
word[depth] = (unsigned short) followingChar;
}
pos = followDownBranchAddress; // pos start at count
int count = mDict[pos] & 0xFF;
LOGI("count - %d\n",count);
pos++;
for (int i = 0; i < count; i++) {
// pos at data
pos++;
// pos now at flag
if (!getFirstBitOfByte(&pos)) { // non-terminal
if (!followDownAddressSearchStop) {
int addr = getBigramAddress(&pos, false);
if (addr > addressLookingFor) {
followDownAddressSearchStop = true;
if (firstAddress) {
firstAddress = false;
haveToSearchAll = true;
} else if (!haveToSearchAll) {
break;
}
} else {
followDownBranchAddress = addr;
followingChar = (char)(0xFF & mDict[pos-1]);
if (firstAddress) {
firstAddress = false;
haveToSearchAll = false;
}
}
}
pos += 3;
} else if (getFirstBitOfByte(&pos)) { // terminal
if (addressLookingFor == (pos-1)) { // found !!
depth++;
word[depth] = (0xFF & mDict[pos-1]);
found = true;
break;
}
if (getSecondBitOfByte(&pos)) { // address + freq (4 byte)
if (!followDownAddressSearchStop) {
int addr = getBigramAddress(&pos, false);
if (addr > addressLookingFor) {
followDownAddressSearchStop = true;
if (firstAddress) {
firstAddress = false;
haveToSearchAll = true;
} else if (!haveToSearchAll) {
break;
}
} else {
followDownBranchAddress = addr;
followingChar = (char)(0xFF & mDict[pos-1]);
if (firstAddress) {
firstAddress = false;
haveToSearchAll = true;
}
}
}
pos += 4;
} else { // freq only (2 byte)
pos += 2;
}
// skipping bigram
int bigramExist = (mDict[pos] & FLAG_BIGRAM_READ);
if (bigramExist > 0) {
int nextBigramExist = 1;
while (nextBigramExist > 0) {
pos += 3;
nextBigramExist = (mDict[pos++] & FLAG_BIGRAM_CONTINUED);
}
} else {
pos++;
}
}
}
depth++;
if (followDownBranchAddress == 0) {
LOGI("ERROR!!! Cannot find bigram!!");
break;
}
}
if (checkFirstCharacter(word)) {
addWordBigram(word, depth, frequency);
}
}
bool
Dictionary::checkFirstCharacter(unsigned short *word)
{
// Checks whether this word starts with same character or neighboring characters of
// what user typed.
int *inputCodes = mInputCodes;
int maxAlt = mMaxAlternatives;
while (maxAlt > 0) {
if ((unsigned int) *inputCodes == (unsigned int) *word) {
return true;
}
inputCodes++;
maxAlt--;
}
return false;
}
bool
Dictionary::isValidWord(unsigned short *word, int length)
{
if (checkIfDictVersionIsLatest()) {
return (isValidWordRec(DICTIONARY_HEADER_SIZE, word, 0, length) != NOT_VALID_WORD);
} else {
return (isValidWordRec(0, word, 0, length) != NOT_VALID_WORD);
}
}
int
Dictionary::isValidWordRec(int pos, unsigned short *word, int offset, int length) {
// returns address of bigram data of that word
// return -99 if not found
int count = getCount(&pos);
unsigned short currentChar = (unsigned short) word[offset];
for (int j = 0; j < count; j++) {
unsigned short c = getChar(&pos);
int terminal = getTerminal(&pos);
int childPos = getAddress(&pos);
if (c == currentChar) {
if (offset == length - 1) {
if (terminal) {
return (pos+1);
}
} else {
if (childPos != 0) {
int t = isValidWordRec(childPos, word, offset + 1, length);
if (t > 0) {
return t;
}
}
}
}
if (terminal) {
getFreq(&pos);
}
// There could be two instances of each alphabet - upper and lower case. So continue
// looking ...
}
return NOT_VALID_WORD;
}
} // namespace latinime
| 11beeaosama-descrbvbnvbniption | java/jni/src/dictionary.cpp | C++ | asf20 | 19,272 |
APP_ABI := all
| 11beeaosama-descrbvbnvbniption | java/jni/Application.mk | Makefile | asf20 | 15 |
/*
**
** Copyright 2009, The Android Open Source Project
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
#include <stdio.h>
#include <assert.h>
#include <unistd.h>
#include <fcntl.h>
#include <jni.h>
#include "dictionary.h"
// ----------------------------------------------------------------------------
using namespace latinime;
//
// helper function to throw an exception
//
static void throwException(JNIEnv *env, const char* ex, const char* fmt, int data)
{
if (jclass cls = env->FindClass(ex)) {
char msg[1000];
sprintf(msg, fmt, data);
env->ThrowNew(cls, msg);
env->DeleteLocalRef(cls);
}
}
static jint latinime_BinaryDictionary_open
(JNIEnv *env, jobject object, jobject dictDirectBuffer,
jint typedLetterMultiplier, jint fullWordMultiplier, jint size)
{
void *dict = env->GetDirectBufferAddress(dictDirectBuffer);
if (dict == NULL) {
fprintf(stderr, "DICT: Dictionary buffer is null\n");
return 0;
}
Dictionary *dictionary = new Dictionary(dict, typedLetterMultiplier, fullWordMultiplier, size);
return (jint) dictionary;
}
static int latinime_BinaryDictionary_getSuggestions(
JNIEnv *env, jobject object, jint dict, jintArray inputArray, jint arraySize,
jcharArray outputArray, jintArray frequencyArray, jint maxWordLength, jint maxWords,
jint maxAlternatives, jint skipPos, jintArray nextLettersArray, jint nextLettersSize)
{
Dictionary *dictionary = (Dictionary*) dict;
if (dictionary == NULL) return 0;
int *frequencies = env->GetIntArrayElements(frequencyArray, NULL);
int *inputCodes = env->GetIntArrayElements(inputArray, NULL);
jchar *outputChars = env->GetCharArrayElements(outputArray, NULL);
int *nextLetters = nextLettersArray != NULL ? env->GetIntArrayElements(nextLettersArray, NULL)
: NULL;
int count = dictionary->getSuggestions(inputCodes, arraySize, (unsigned short*) outputChars,
frequencies, maxWordLength, maxWords, maxAlternatives, skipPos, nextLetters,
nextLettersSize);
env->ReleaseIntArrayElements(frequencyArray, frequencies, 0);
env->ReleaseIntArrayElements(inputArray, inputCodes, JNI_ABORT);
env->ReleaseCharArrayElements(outputArray, outputChars, 0);
if (nextLetters) {
env->ReleaseIntArrayElements(nextLettersArray, nextLetters, 0);
}
return count;
}
static int latinime_BinaryDictionary_getBigrams
(JNIEnv *env, jobject object, jint dict, jcharArray prevWordArray, jint prevWordLength,
jintArray inputArray, jint inputArraySize, jcharArray outputArray,
jintArray frequencyArray, jint maxWordLength, jint maxBigrams, jint maxAlternatives)
{
Dictionary *dictionary = (Dictionary*) dict;
if (dictionary == NULL) return 0;
jchar *prevWord = env->GetCharArrayElements(prevWordArray, NULL);
int *inputCodes = env->GetIntArrayElements(inputArray, NULL);
jchar *outputChars = env->GetCharArrayElements(outputArray, NULL);
int *frequencies = env->GetIntArrayElements(frequencyArray, NULL);
int count = dictionary->getBigrams((unsigned short*) prevWord, prevWordLength, inputCodes,
inputArraySize, (unsigned short*) outputChars, frequencies, maxWordLength, maxBigrams,
maxAlternatives);
env->ReleaseCharArrayElements(prevWordArray, prevWord, JNI_ABORT);
env->ReleaseIntArrayElements(inputArray, inputCodes, JNI_ABORT);
env->ReleaseCharArrayElements(outputArray, outputChars, 0);
env->ReleaseIntArrayElements(frequencyArray, frequencies, 0);
return count;
}
static jboolean latinime_BinaryDictionary_isValidWord
(JNIEnv *env, jobject object, jint dict, jcharArray wordArray, jint wordLength)
{
Dictionary *dictionary = (Dictionary*) dict;
if (dictionary == NULL) return (jboolean) false;
jchar *word = env->GetCharArrayElements(wordArray, NULL);
jboolean result = dictionary->isValidWord((unsigned short*) word, wordLength);
env->ReleaseCharArrayElements(wordArray, word, JNI_ABORT);
return result;
}
static void latinime_BinaryDictionary_close
(JNIEnv *env, jobject object, jint dict)
{
Dictionary *dictionary = (Dictionary*) dict;
delete (Dictionary*) dict;
}
// ----------------------------------------------------------------------------
static JNINativeMethod gMethods[] = {
{"openNative", "(Ljava/nio/ByteBuffer;III)I",
(void*)latinime_BinaryDictionary_open},
{"closeNative", "(I)V", (void*)latinime_BinaryDictionary_close},
{"getSuggestionsNative", "(I[II[C[IIIII[II)I", (void*)latinime_BinaryDictionary_getSuggestions},
{"isValidWordNative", "(I[CI)Z", (void*)latinime_BinaryDictionary_isValidWord},
{"getBigramsNative", "(I[CI[II[C[IIII)I", (void*)latinime_BinaryDictionary_getBigrams}
};
static int registerNativeMethods(JNIEnv* env, const char* className,
JNINativeMethod* gMethods, int numMethods)
{
jclass clazz;
clazz = env->FindClass(className);
if (clazz == NULL) {
fprintf(stderr,
"Native registration unable to find class '%s'\n", className);
return JNI_FALSE;
}
if (env->RegisterNatives(clazz, gMethods, numMethods) < 0) {
fprintf(stderr, "RegisterNatives failed for '%s'\n", className);
return JNI_FALSE;
}
return JNI_TRUE;
}
static int registerNatives(JNIEnv *env)
{
const char* const kClassPathName = "org/pocketworkstation/pckeyboard/BinaryDictionary";
return registerNativeMethods(env,
kClassPathName, gMethods, sizeof(gMethods) / sizeof(gMethods[0]));
}
/*
* Returns the JNI version on success, -1 on failure.
*/
jint JNI_OnLoad(JavaVM* vm, void* reserved)
{
JNIEnv* env = NULL;
jint result = -1;
if (vm->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK) {
fprintf(stderr, "ERROR: GetEnv failed\n");
goto bail;
}
assert(env != NULL);
if (!registerNatives(env)) {
fprintf(stderr, "ERROR: BinaryDictionary native registration failed\n");
goto bail;
}
/* success -- return valid version number */
result = JNI_VERSION_1_4;
bail:
return result;
}
| 11beeaosama-descrbvbnvbniption | java/jni/jni/org_pocketworkstation_pckeyboard_BinaryDictionary.cpp | C++ | asf20 | 6,786 |
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(LOCAL_PATH)/src
LOCAL_SRC_FILES := \
jni/org_pocketworkstation_pckeyboard_BinaryDictionary.cpp \
src/dictionary.cpp \
src/char_utils.cpp
#ifneq ($(TARGET_ARCH),x86)
#LOCAL_NDK_VERSION := 4
#LOCAL_SDK_VERSION := 8
#endif
LOCAL_MODULE := libjni_pckeyboard
LOCAL_MODULE_TAGS := user
include $(BUILD_SHARED_LIBRARY)
| 11beeaosama-descrbvbnvbniption | java/jni/Android.mk | Makefile | asf20 | 394 |
LOCAL_PATH:= $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE_TAGS := optional
LOCAL_SRC_FILES := $(call all-java-files-under, src)
LOCAL_PACKAGE_NAME := PCKeyboard
LOCAL_CERTIFICATE := shared
LOCAL_JNI_SHARED_LIBRARIES := libjni_pckeyboard
LOCAL_STATIC_JAVA_LIBRARIES := android-common
#LOCAL_AAPT_FLAGS := -0 .dict
LOCAL_SDK_VERSION := current
LOCAL_PROGUARD_FLAG_FILES := proguard.flags
include $(BUILD_PACKAGE)
| 11beeaosama-descrbvbnvbniption | java/Android.mk | Makefile | asf20 | 426 |
#!/bin/bash
getLangsForFiles () {
echo "en" # default language
for F in "$@"
do
find res/ -name "$F"
done \
| sed -n '
s/.*res.[a-z]*-\(..\)-r\(..\).*/\1_\2/p; # yy-rXX => yy_XX
s/.*res.[a-z]*-\(..\)\/.*/\1/p; # yy => yy
'
}
getLangsForDicts () {
ls ../Dicts \
| sed 's/.*-//; s/.dict//'
}
makeStrings () {
Name="$1"
shift
echo " private static final String[] $Name = {"
echo $(
for F in "$@"; do echo "$F"; done \
| sort -u
) \
| sed 's/ /", "/g; s/^/"/; s/$/"/' \
| fmt -w 70 \
| sed 's/^/ /'
echo " };"
echo
}
LOCS=$(getLangsForFiles donottranslate-altchars.xml donottranslate-keymap.xml kbd_qwerty.xml strings.xml)
DICTS=$(getLangsForDicts)
makeStrings KBD_LOCALIZATIONS $LOCS $DICTS
makeStrings KBD_5_ROW $(getLangsForFiles donottranslate-keymap.xml)
makeStrings KBD_4_ROW $(getLangsForFiles kbd_qwerty.xml)
| 11beeaosama-descrbvbnvbniption | java/GetLanguages.sh | Shell | asf20 | 889 |
# Copyright (C) 2010 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
LOCAL_PATH := $(call my-dir)
include $(call all-makefiles-under,$(LOCAL_PATH))
| 11beeaosama-descrbvbnvbniption | Android.mk | Makefile | asf20 | 681 |
Imports System
Imports System.Reflection
Imports System.Runtime.InteropServices
' General Information about an assembly is controlled through the following
' set of attributes. Change these attribute values to modify the information
' associated with an assembly.
' Review the values of the assembly attributes
<Assembly: AssemblyTitle("WindowsApplication1")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("Microsoft")>
<Assembly: AssemblyProduct("WindowsApplication1")>
<Assembly: AssemblyCopyright("Copyright © Microsoft 2011")>
<Assembly: AssemblyTrademark("")>
<Assembly: ComVisible(False)>
'The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("3681c4a5-f636-407f-aa24-9145a35519f5")>
' Version information for an assembly consists of the following four values:
'
' Major Version
' Minor Version
' Build Number
' Revision
'
' You can specify all the values or you can default the Build and Revision Numbers
' by using the '*' as shown below:
' <Assembly: AssemblyVersion("1.0.*")>
<Assembly: AssemblyVersion("1.0.0.0")>
<Assembly: AssemblyFileVersion("1.0.0.0")>
| 08010549-le-thi-yen-nhi-th08-tm-qldsv | trunk/Doancsdl/My Project/AssemblyInfo.vb | Visual Basic .NET | art | 1,209 |
Public Class frpt_bdtk
Private Sub LOPBindingNavigatorSaveItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Me.Validate()
Me.bdslop.EndEdit()
Me.talop.Update(Me.Dslop.LOP)
End Sub
Private Sub frpt_bdtk_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
talop.Fill(Dslop.LOP)
End Sub
Private Sub rpt_bdtk1_InitReport(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rpt_bdtk1.InitReport
rpt_bdtk1.ParameterFields("@tl").CurrentValues.AddValue(cmbtenlop.Text.Trim)
End Sub
Private Sub rpt_bdtk1_RefreshReport(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rpt_bdtk1.RefreshReport
rpt_bdtk1.ParameterFields("@tl").CurrentValues.AddValue(cmbtenlop.Text.Trim)
End Sub
Private Sub btnmanhinh_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnmanhinh.Click
rpt_bdtk1.ParameterFields("@tl").CurrentValues.Clear()
CrystalReportViewer1.RefreshReport()
End Sub
Private Sub btnmayin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnmayin.Click
rpt_bdtk1.ParameterFields("@tl").CurrentValues.Clear()
CrystalReportViewer1.RefreshReport()
CrystalReportViewer1.PrintReport()
End Sub
Private Sub btnthoat_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnthoat.Click
Close()
End Sub
End Class | 08010549-le-thi-yen-nhi-th08-tm-qldsv | trunk/Doancsdl/frpt_bdtk.vb | Visual Basic .NET | art | 1,549 |
/*
12306 Auto Login => A javascript snippet to help you auto login 12306.com.
Copyright (C) 2011 w000.cn
Includes jQuery
Copyright 2011, John Resig
Dual licensed under the MIT or GPL Version 2 licenses.
http://jquery.org/license
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
// ==UserScript==
// @name 12306 Auto refresh
// @author w000.cn@gmail.com
// @namespace https://plus.google.com/107416899831145722597
// @description A javascript snippet to help you auto login 12306.com
// @include *://dynamic.12306.cn/otsweb/*
// @require https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js
// ==/UserScript==
function withjQuery(callback, safe){
if(typeof(jQuery) == "undefined") {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js";
if(safe) {
var cb = document.createElement("script");
cb.type = "text/javascript";
cb.textContent = "jQuery.noConflict();(" + callback.toString() + ")(jQuery);";
script.addEventListener('load', function() {
document.head.appendChild(cb);
});
}
else {
var dollar = undefined;
if(typeof($) != "undefined") dollar = $;
script.addEventListener('load', function() {
jQuery.noConflict();
$ = dollar;
callback(jQuery);
});
}
document.head.appendChild(script);
} else {
callback(jQuery);
}
}
withjQuery(function($){
//alert(document.body.innerHTML);
if (document.body.innerHTML.indexOf("Access Denied") > -1)
{
setTimeout(location.reload(),2000);
}
//notify('网页刷新成功!');
}, true);
| 12306-auto-refresh | trunk/12306Autorefresh.user.js | JavaScript | gpl2 | 2,266 |
//Script by Aneesh of www.bloggerplugins.org
//Released on August 19th August 2009
var relatedTitles = new Array();
var relatedTitlesNum = 0;
var relatedUrls = new Array();
var thumburl = new Array();
function related_results_labels_thumbs(json) {
for (var i = 0; i < json.feed.entry.length; i++) {
var entry = json.feed.entry[i];
relatedTitles[relatedTitlesNum] = entry.title.$t;
try
{thumburl[relatedTitlesNum]=entry.media$thumbnail.url;}
catch (error){
s=entry.content.$t;a=s.indexOf("<img");b=s.indexOf("src=\"",a);c=s.indexOf("\"",b+5);d=s.substr(b+5,c-b-5);if((a!=-1)&&(b!=-1)&&(c!=-1)&&(d!="")){
thumburl[relatedTitlesNum]=d;} else thumburl[relatedTitlesNum]='http://1.bp.blogspot.com/_u4gySN2ZgqE/SosvnavWq0I/AAAAAAAAArk/yL95WlyTqr0/s400/noimage.png';
}
if(relatedTitles[relatedTitlesNum].length>200) relatedTitles[relatedTitlesNum]=relatedTitles[relatedTitlesNum].substring(0, 100)+"...";
for (var k = 0; k < entry.link.length; k++) {
if (entry.link[k].rel == 'alternate') {
relatedUrls[relatedTitlesNum] = entry.link[k].href;
relatedTitlesNum++;
}
}
}
}
function removeRelatedDuplicates_thumbs() {
var tmp = new Array(0);
var tmp2 = new Array(0);
var tmp3 = new Array(0);
for(var i = 0; i < relatedUrls.length; i++) {
if(!contains_thumbs(tmp, relatedUrls[i]))
{
tmp.length += 1;
tmp[tmp.length - 1] = relatedUrls[i];
tmp2.length += 1;
tmp3.length += 1;
tmp2[tmp2.length - 1] = relatedTitles[i];
tmp3[tmp3.length - 1] = thumburl[i];
}
}
relatedTitles = tmp2;
relatedUrls = tmp;
thumburl=tmp3;
}
function contains_thumbs(a, e) {
for(var j = 0; j < a.length; j++) if (a[j]==e) return true;
return false;
}
function printRelatedLabels_thumbs() {
for(var i = 0; i < relatedUrls.length; i++)
{
if((relatedUrls[i]==currentposturl)||(!(relatedTitles[i])))
{
relatedUrls.splice(i,1);
relatedTitles.splice(i,1);
thumburl.splice(i,1);
}
}
var r = Math.floor((relatedTitles.length - 1) * Math.random());
var i = 0;
if(relatedTitles.length>0) document.write('');
document.write('<div style="clear: both;"/>');
while (i < relatedTitles.length && i < 20 && i<maxresults) {
document.write('<div style="background-color:#F2F2F2;padding:3px;border:1px solid silver;width:97px;height:125px;margin:0 11px 10px 0;float:left;">');
document.write('<a style="text-decoration:none;float:left;');
if(i!=0) document.write('border-left:solid 0px #d4eaf2;"');
else document.write('"');
document.write(' href="' + relatedUrls[r] + '"><img alt="Free Ebook Download" title="'+relatedTitles[r]+'" style="width:97px;height:125px;border:0px;" src="'+thumburl[r]+'"/></a></div>');
if (r < relatedTitles.length - 1) {
r++;
} else {
r = 0;
}
i++;
}
document.write('</div>');
} | 1001ebooknet | js/relatedposts-1001ebook.js | JavaScript | asf20 | 2,670 |
//<![CDATA[
$(document).ready(function() {
// change the dimension variable below to be the pixel size you want
var dimension = 199;
// this identifies the PopularPosts2 div element, finds each image in it, and resizes it
$('#Blog1,#related-posts').find('img').each(function(n, image){
var image = $(image);
image.attr({src : image.attr('src').replace(/s\B\d{2,4}-c/,'s' + dimension)});
image.attr('width','auto');
image.attr('height','auto');
});
});
$(document).ready(function() {
// change the dimension variable below to be the pixel size you want
var dimension = 105;
// this identifies the PopularPosts2 div element, finds each image in it, and resizes it
$('#PopularPosts2').find('img').each(function(n, image){
var image = $(image);
image.attr({src : image.attr('src').replace(/s\B\d{2,4}-c/,'s' + dimension)});
image.attr('width','auto');
image.attr('height','auto');
});
});
//]]> | 1001ebooknet | js/imagesize.js | JavaScript | asf20 | 926 |
//<![CDATA[
jQuery(document).ready(function() {
//Set Default State of each portfolio piece
$(".paging").show();
$(".paging a:first").addClass("active");
//Get size of images, how many there are, then determin the size of the image reel.
var imageWidth = $(".sompret").width();
var imageSum = $(".image_reel img").size();
var imageReelWidth = imageWidth * imageSum;
//Adjust the image reel to its new size
$(".image_reel").css({'width' : imageReelWidth});
//Paging + Slider Function
rotate = function(){
var triggerID = $active.attr("rel") - 1; //Get number of times to slide
var image_reelPosition = triggerID * imageWidth; //Determines the distance the image reel needs to slide
$(".paging a").removeClass('active'); //Remove all active class
$active.addClass('active'); //Add active class (the $active is declared in the rotateSwitch function)
$(".crott").stop(true,true).slideUp('slow');
$(".crott").eq( $('.paging a.active').attr("rel") - 1 ).slideDown("slow");
//Slider Animation
$(".image_reel").animate({
left: -image_reelPosition
}, 500 );
};
//Rotation + Timing Event
rotateSwitch = function(){
$(".crott").eq( $('.paging a.active').attr("rel") - 1 ).slideDown("slow");
play = setInterval(function(){ //Set timer - this will repeat itself every 3 seconds
$active = $('.paging a.active').next();
if ( $active.length === 0) { //If paging reaches the end...
$active = $('.paging a:first'); //go back to first
}
rotate(); //Trigger the paging and slider function
}, 10000); //Timer speed in milliseconds (3 seconds)
};
rotateSwitch(); //Run function on launch
//On Click
$(".paging a").click(function() {
$active = $(this); //Activate the clicked paging
//Reset Timer
clearInterval(play); //Stop the rotation
rotate(); //Trigger rotation immediately
rotateSwitch(); // Resume rotation
return false; //Prevent browser jump to link anchor
});
});
//]]> | 1001ebooknet | js/slider1001ebook.js | JavaScript | asf20 | 2,007 |
var tabbedTOC_defaults = {
blogUrl: "http://www.dte.web.id", // Blog URL
containerId: "tabbed-toc", // Container ID
activeTab: 1, // The default active tab index (default: the first tab)
showDates: false, // true to show the post date
showSummaries: false, // true to show the posts summaries
numChars: 200, // Number of summary chars
showThumbnails: false, // true to show the posts thumbnails (Not recommended)
thumbSize: 40, // Thumbnail size
noThumb: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAAA3NCSVQICAjb4U/gAAAADElEQVQImWOor68HAAL+AX7vOF2TAAAAAElFTkSuQmCC", // No thumbnail URL
monthNames: [ // Array of month names
"Januari",
"Februari",
"Maret",
"April",
"Mei",
"Juni",
"Juli",
"Agustus",
"September",
"Oktober",
"November",
"Desember"
],
newTabLink: true, // Open link in new window?
maxResults: 99999, // Maximum posts result
preload: 0, // Load the feed after 0 seconds (option => time in milliseconds || "onload")
sortAlphabetically: true, // `false` to sort posts by date
showNew: false, // `false` to hide the "New!" mark in most recent posts, or define how many recent posts are to be marked
newText: " - <em style='color:red;'>Baru!</em>" // HTML for the "New!" text
};
for (var i in tabbedTOC_defaults) {
tabbedTOC_defaults[i] = (typeof(tabbedTOC[i]) !== undefined && typeof(tabbedTOC[i]) !== 'undefined') ? tabbedTOC[i] : tabbedTOC_defaults[i];
}
function clickTab(pos) {
var a = document.getElementById(tabbedTOC_defaults.containerId),
b = a.getElementsByTagName('ol'),
c = a.getElementsByTagName('ul')[0],
d = c.getElementsByTagName('a');
for (var t = 0; t < b.length; t++) {
b[t].style.display = "none";
b[parseInt(pos, 10)].style.display = "block";
}
for (var u = 0; u < d.length; u++) {
d[u].className = "";
d[parseInt(pos, 10)].className = "active-tab";
}
}
function showTabs(json) {
var total = parseInt(json.feed.openSearch$totalResults.$t,10),
c = tabbedTOC_defaults,
entry = json.feed.entry,
category = json.feed.category,
skeleton = "",
newPosts = [];
for (var g = 0; g < (c.showNew === true ? 5 : c.showNew); g++) {
if (g == entry.length) break;
entry[g].title.$t = entry[g].title.$t + (c.showNew !== false ? c.newText : '');
}
entry = c.sortAlphabetically ? entry.sort(function(a,b) {
return (a.title.$t.localeCompare(b.title.$t));
}) : entry;
category = c.sortAlphabetically ? category.sort(function(a,b) {
return (a.term.localeCompare(b.term));
}) : category;
// Build the tabs skeleton
skeleton = '<span class="divider-layer"></span><ul class="toc-tabs">';
for (var h = 0, cen = category.length; h < cen; h++) {
skeleton += '<li class="toc-tab-item-' + h + '"><a href="javascript:clickTab(' + h + ');">' + category[h].term + '</a></li>';
}
skeleton += '</ul>';
// Bulid the tabs contents skeleton
skeleton += '<div class="toc-content">';
for (var i = 0, cnt = category.length; i < cnt; i++) {
skeleton += '<ol class="panel" data-category="' + category[i].term + '"';
skeleton += (i != (c.activeTab-1)) ? ' style="display:none;"' : '';
skeleton += '>';
for (var j = 0; j < total; j++) {
if (j == entry.length) break;
var link, entries = entry[j],
pub = entries.published.$t, // Get the post date
month = c.monthNames, // Month array from the configuration
title = entries.title.$t, // Get the post title
summary = ("summary" in entries && c.showSummaries === true) ? entries.summary.$t.replace(/<br ?\/?>/g," ").replace(/<.*?>/g,"").replace(/[<>]/g,"").substring(0,c.numChars) + '…' : '', // Get the post summary
img = ("media$thumbnail" in entries && c.showThumbnails === true) ? '<img class="thumbnail" style="width:'+c.thumbSize+'px;height:'+c.thumbSize+'px;" alt="" src="' + entries.media$thumbnail.url.replace(/\/s72(\-c)?\//,"/s"+c.thumbSize+"-c/") + '"/>' : '<img class="thumbnail" style="width:'+c.thumbSize+'px;height:'+c.thumbSize+'px;" alt="" src="' + c.noThumb.replace(/\/s72(\-c)?\//,"/s"+c.thumbSize+"-c/") + '"/>', // Get the post thumbnail
cat = (entries.category) ? entries.category : [], // Post categories
date = (c.showDates) ? '<time datetime="' + pub + '" title="' + pub + '">' + pub.substring(8,10) + ' ' + month[parseInt(pub.substring(5,7),10)-1] + ' ' + pub.substring(0,4) + '</time>' : ''; // Formated published date
for (var k = 0; k < entries.link.length; k++) {
if (entries.link[k].rel == 'alternate') {
link = entries.link[k].href; // Get the post URL
break;
}
}
for (var l = 0, check = cat.length; l < check; l++) {
var target = (c.newTabLink) ? ' target="_blank"' : ''; // Open link in new window?
// Write the list skeleton only if at least one of the post...
// ... has the same category term with one of the current categories term list
if (cat[l].term == category[i].term) {
skeleton += '<li title="' + cat[l].term + '"';
skeleton += (c.showSummaries) ? ' class="bold"' : '';
skeleton += '><a href="' + link + '"' + target + '>' + title + date + '</a>';
skeleton += (c.showSummaries) ? '<span class="summary">' + img + summary + '<span style="display:block;clear:both;"></span></span>' : '';
skeleton += '</li>';
}
}
}
skeleton += '</ol>';
}
skeleton += '</div>';
skeleton += '<div style="clear:both;"></div>';
document.getElementById(c.containerId).innerHTML = skeleton;
clickTab(c.activeTab-1);
}
(function() {
var h = document.getElementsByTagName('head')[0],
s = document.createElement('script');
s.type = 'text/javascript';
s.src = tabbedTOC_defaults.blogUrl + '/feeds/posts/summary?alt=json-in-script&max-results=' + tabbedTOC_defaults.maxResults + '&orderby=published&callback=showTabs';
if (tabbedTOC_defaults.preload !== "onload") {
setTimeout(function() {
h.appendChild(s);
}, tabbedTOC_defaults.preload);
} else {
window.onload = function() {
h.appendChild(s);
};
}
})(); | 1001ebooknet | js/tabbed-toc.js | JavaScript | asf20 | 5,952 |
var bcLoadingImage = "http://1.bp.blogspot.com/-vPivuucfViM/UN8jzBwcZKI/AAAAAAAAHbY/at-JwuUBk_4/s1600/horizontal-loading.gif";
var bcLoadingMessage = "";
var bcArchiveNavText = "View Archive";
var bcArchiveNavPrev = '◄';
var bcArchiveNavNext = '►';
var headDays = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
var headInitial = ["Su","Mo","Tu","We","Th","Fr","Sa"];
// Nothing to configure past this point ----------------------------------
var timeOffset;
var bcBlogID;
var calMonth;
var calDay = 1;
var calYear;
var startIndex;
var callmth;
var bcNav = new Array ();
var bcList = new Array ();
//Initialize Fill Array
var fill = ["","31","28","31","30","31","30","31","31","30","31","30","31"];
function openStatus(){
document.getElementById('calLoadingStatus').style.display = 'block';
document.getElementById('calendarDisplay').innerHTML = '';
}
function closeStatus(){
document.getElementById('calLoadingStatus').style.display = 'none';
}
function bcLoadStatus(){
cls = document.getElementById('calLoadingStatus');
img = document.createElement('img');
img.src = bcLoadingImage;
img.style.verticalAlign = 'middle';
cls.appendChild(img);
txt = document.createTextNode(bcLoadingMessage);
cls.appendChild(txt);
}
function callArchive(mth,yr,nav){
// Check for Leap Years
if (((yr % 4 == 0) && (yr % 100 != 0)) || (yr % 400 == 0)) {
fill[2] = '29';
}
else {
fill[2] = '28';
}
calMonth = mth;
calYear = yr;
if(mth.charAt(0) == 0){
calMonth = mth.substring(1);
}
callmth = mth;
bcNavAll = document.getElementById('bcFootAll');
bcNavPrev = document.getElementById('bcFootPrev');
bcNavNext = document.getElementById('bcFootNext');
bcSelect = document.getElementById('bcSelection');
a = document.createElement('a');
at = document.createTextNode(bcArchiveNavText);
a.href = bcNav[nav];
a.appendChild(at);
bcNavAll.innerHTML = '';
bcNavAll.appendChild(a);
bcNavPrev.innerHTML = '';
bcNavNext.innerHTML = '';
if(nav < bcNav.length -1){
a = document.createElement('a');
a.innerHTML = bcArchiveNavPrev;
bcp = parseInt(nav,10) + 1;
a.href = bcNav[bcp];
a.title = 'Previous Archive';
prevSplit = bcList[bcp].split(',');
a.onclick = function(){bcSelect.options[bcp].selected = true;openStatus();callArchive(prevSplit[0],prevSplit[1],prevSplit[2]);return false;};
bcNavPrev.appendChild(a);
}
if(nav > 0){
a = document.createElement('a');
a.innerHTML = bcArchiveNavNext;
bcn = parseInt(nav,10) - 1;
a.href = bcNav[bcn];
a.title = 'Next Archive';
nextSplit = bcList[bcn].split(',');
a.onclick = function(){bcSelect.options[bcn].selected = true;openStatus();callArchive(nextSplit[0],nextSplit[1],nextSplit[2]);return false;};
bcNavNext.appendChild(a);
}
script = document.createElement('script');
script.src = 'http://www.blogger.com/feeds/'+bcBlogId+'/posts/summary?published-max='+calYear+'-'+callmth+'-'+fill[calMonth]+'T23%3A59%3A59'+timeOffset+'&published-min='+calYear+'-'+callmth+'-01T00%3A00%3A00'+timeOffset+'&max-results=100&orderby=published&alt=json-in-script&callback=cReadArchive';
document.getElementsByTagName('head')[0].appendChild(script);
}
function cReadArchive(root){
// Check for Leap Years
if (((calYear % 4 == 0) && (calYear % 100 != 0)) || (calYear % 400 == 0)) {
fill[2] = '29';
}
else {
fill[2] = '28';
}
closeStatus();
document.getElementById('lastRow').style.display = 'none';
calDis = document.getElementById('calendarDisplay');
var feed = root.feed;
var total = feed.openSearch$totalResults.$t;
var entries = feed.entry || [];
var fillDate = new Array();
var fillTitles = new Array();
fillTitles.length = 32;
var ul = document.createElement('ul');
ul.id = 'calendarUl';
for (var i = 0; i < feed.entry.length; ++i) {
var entry = feed.entry[i];
for (var j = 0; j < entry.link.length; ++j) {
if (entry.link[j].rel == "alternate") {
var link = entry.link[j].href;
}
}
var title = entry.title.$t;
var author = entry.author[0].name.$t;
var date = entry.published.$t;
var summary = entry.summary.$t;
isPublished = date.split('T')[0].split('-')[2];
if(isPublished.charAt(0) == '0'){
isPublished = isPublished.substring(1);
}
fillDate.push(isPublished);
if (fillTitles[isPublished]){
fillTitles[isPublished] = fillTitles[isPublished] + ' | ' + title;
}
else {
fillTitles[isPublished] = title;
}
li = document.createElement('li');
li.style.listType = 'none';
li.innerHTML = '<a href="'+link+'">'+title+'</a>';
ul.appendChild(li);
}
calDis.appendChild(ul);
var val1 = parseInt(calDay, 10)
var valxx = parseInt(calMonth, 10);
var val2 = valxx - 1;
var val3 = parseInt(calYear, 10);
var firstCalDay = new Date(val3,val2,1);
var val0 = firstCalDay.getDay();
startIndex = val0 + 1;
var dayCount = 1;
for (x =1; x < 38; x++){
var cell = document.getElementById('cell'+x);
if( x < startIndex){
cell.innerHTML = ' ';
cell.className = 'firstCell';
}
if( x >= startIndex){
cell.innerHTML = dayCount;
cell.className = 'filledCell';
for(p = 0; p < fillDate.length; p++){
if(dayCount == fillDate[p]){
if(fillDate[p].length == 1){
fillURL = '0'+fillDate[p];
}
else {
fillURL = fillDate[p];
}
cell.className = 'highlightCell';
cell.innerHTML = '<a href="/search?updated-max='+calYear+'-'+callmth+'-'+fillURL+'T23%3A59%3A59'+timeOffset+'&updated-min='+calYear+'-'+callmth+'-'+fillURL+'T00%3A00%3A00'+timeOffset+'" title="'+fillTitles[fillDate[p]].replace(/"/g,'\'')+'">'+dayCount+'</a>';
}
}
if( dayCount > fill[valxx]){
cell.innerHTML = ' ';
cell.className = 'emptyCell';
}
dayCount++;
}
}
visTotal = parseInt(startIndex) + parseInt(fill[valxx]) -1;
if(visTotal >35){
document.getElementById('lastRow').style.display = '';
}
}
function initCal(){
document.getElementById('blogger_calendar').style.display = 'block';
var bcInit = document.getElementById('bloggerCalendarList').getElementsByTagName('a');
var bcCount = document.getElementById('bloggerCalendarList').getElementsByTagName('li');
document.getElementById('bloggerCalendarList').style.display = 'none';
calHead = document.getElementById('bcHead');
tr = document.createElement('tr');
for(t = 0; t < 7; t++){
th = document.createElement('th');
th.abbr = headDays[t];
scope = 'col';
th.title = headDays[t];
th.innerHTML = headInitial[t];
tr.appendChild(th);
}
calHead.appendChild(tr);
for (x = 0; x <bcInit.length;x++){
var stripYear= bcInit[x].href.split('_')[0].split('/')[3];
var stripMonth = bcInit[x].href.split('_')[1];
bcList.push(stripMonth + ','+ stripYear + ',' + x);
bcNav.push(bcInit[x].href);
}
var sel = document.createElement('select');
sel.id = 'bcSelection';
sel.onchange = function(){var cSend = this.options[this.selectedIndex].value.split(',');openStatus();callArchive(cSend[0],cSend[1],cSend[2]);};
q = 0;
for (r = 0; r <bcList.length; r++){
var selText = bcInit[r].innerHTML;
var selCount = bcCount[r].innerHTML.split('> (')[1];
var selValue = bcList[r];
sel.options[q] = new Option(selText + ' ('+selCount,selValue);
q++
}
document.getElementById('bcaption').appendChild(sel);
var m = bcList[0].split(',')[0];
var y = bcList[0].split(',')[1];
callArchive(m,y,'0');
}
function timezoneSet(root){
var feed = root.feed;
var updated = feed.updated.$t;
var id = feed.id.$t;
bcBlogId = id.split('blog-')[1];
upLength = updated.length;
if(updated.charAt(upLength-1) == "Z"){timeOffset = "+07:00";}
else {timeOffset = updated.substring(upLength-6,upLength);}
timeOffset = encodeURIComponent(timeOffset);
} | 1001ebooknet | js/archivecalendar-1001ebook.js | JavaScript | asf20 | 8,618 |
//<![CDATA[
imgr = new Array();
imgr[0] = "http://2.bp.blogspot.com/-uitX7ROPtTU/Tyv-G4NA_uI/AAAAAAAAFBY/NcWLPVnYEnU/s1600/no+image.jpg";
showRandomImg = true;
aBold = true;
summaryPost1 = 80;
summaryTitle = 20;
numposts1 = 10;
function removeHtmlTag(strx,chop){
var s = strx.split("<");
for(var i=0;i<s.length;i++){
if(s[i].indexOf(">")!=-1){
s[i] = s[i].substring(s[i].indexOf(">")+1,s[i].length);
}
}
s = s.join("");
s = s.substring(0,chop-1);
return s;
}
function showrecentposts1(json) {
j = (showRandomImg) ? Math.floor((imgr.length+1)*Math.random()) : 0;
img = new Array();
for (var i = 0; i < numposts1; i++) {
var entry = json.feed.entry[i];
var posttitle = entry.title.$t;
var pcm;
var posturl;
if (i == json.feed.entry.length) break;
for (var k = 0; k < entry.link.length; k++) {
if (entry.link[k].rel == 'alternate') {
posturl = entry.link[k].href;
break;
}
}
for (var k = 0; k < entry.link.length; k++) {
if (entry.link[k].rel == 'replies' && entry.link[k].type == 'text/html') {
pcm = entry.link[k].title.split(" ")[0];
break;
}
}
if ("content" in entry) {
var postcontent = entry.content.$t;}
else
if ("summary" in entry) {
var postcontent = entry.summary.$t;}
else var postcontent = "";
postdate = entry.published.$t;
if(j>imgr.length-1) j=0;
img[i] = imgr[j];
s = postcontent ; a = s.indexOf("<img"); b = s.indexOf("src=\"",a); c = s.indexOf("\"",b+5); d = s.substr(b+5,c-b-5);
if((a!=-1)&&(b!=-1)&&(c!=-1)&&(d!="")) img[i] = d;
//cmtext = (text != 'no') ? '<i><font color="'+acolor+'">('+pcm+' '+text+')</font></i>' : '';
var month = [1,2,3,4,5,6,7,8,9,10,11,12];
var month2 = ["January","February","March","April","May","June","July","August","September","October","November","December"];
var day = postdate.split("-")[2].substring(0,2);
var m = postdate.split("-")[1];
var y = postdate.split("-")[0];
for(var u2=0;u2<month.length;u2++){
if(parseInt(m)==month[u2]) {
m = month2[u2] ; break;
}
}
var daystr = m+ ' ' + day + ' ' + y ;
var trtd = '<div class="crott"><a href="'+posturl+'">'+posttitle+'</a><p>'+removeHtmlTag(postcontent,summaryPost1)+'... </p></div>';
document.write(trtd);
j++;
}
}
function showrecentposts2(json) {
j = (showRandomImg) ? Math.floor((imgr.length+1)*Math.random()) : 0;
img = new Array();
for (var i = 0; i < numposts1 ; i++) {
var entry = json.feed.entry[i];
var posttitle = entry.title.$t;
var pcm;
var posturl;
if (i == json.feed.entry.length) break;
for (var k = 0; k < entry.link.length; k++) {
if (entry.link[k].rel == 'alternate') {
posturl = entry.link[k].href;
break;
}
}
for (var k = 0; k < entry.link.length; k++) {
if (entry.link[k].rel == 'replies' && entry.link[k].type == 'text/html') {
pcm = entry.link[k].title.split(" ")[0];
break;
}
}
if ("content" in entry) {
var postcontent = entry.content.$t;}
else
if ("summary" in entry) {
var postcontent = entry.summary.$t;}
else var postcontent = "";
postdate = entry.published.$t;
if(j>imgr.length-1) j=0;
img[i] = imgr[j];
s = postcontent ; a = s.indexOf("<img"); b = s.indexOf("src=\"",a); c = s.indexOf("\"",b+5); d = s.substr(b+5,c-b-5);
if((a!=-1)&&(b!=-1)&&(c!=-1)&&(d!="")) img[i] = d;
//cmtext = (text != 'no') ? '<i><font color="'+acolor+'">('+pcm+' '+text+')</font></i>' : '';
var month = [1,2,3,4,5,6,7,8,9,10,11,12];
var month2 = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
var day = postdate.split("-")[2].substring(0,2);
var m = postdate.split("-")[1];
var y = postdate.split("-")[0];
for(var u2=0;u2<month.length;u2++){
if(parseInt(m)==month[u2]) {
m = month2[u2] ; break;
}
}
var daystr = day+ ' ' + m + ' ' + y ;
var trtd = '<a href="'+posturl+'"><img src="'+img[i]+'"/></a>';
document.write(trtd);
j++;
}
}
//]]> | 1001ebooknet | js/callslider1001ebook.js | JavaScript | asf20 | 4,019 |
#fblikepop{
background-color:#fff;
display:none;
position:fixed;
top:200px;
_position:absolute; /* hack for IE 6*/
width:450px;
z-index:200;
border:10px solid rgba(82, 82, 82, 0.7);
margin:0pt;
padding:0pt;
color:#333333;
text-align:left;
font-family:arial,sans-serif;
font-size:11px;
}
#fblikepop body{
background:#fff none repeat scroll 0%;
line-height:1;
margin:0pt;
height:100%;
}
.fbflush{
cursor: pointer;
font-size:11px !important;
color:#FFF !important;
text-decoration:none !important;
border:0 !important;
}
#fblikebg{
display:none;
position:fixed;
_position:absolute; /* hack for IE 6*/
height:100%;
width:100%;
top:0;
left:0;
background:#000000;
z-index:100;
}
#fblikepop #popup_head{
border-top:1px solid #3B5998;
border-left:1px solid #3B5998;
border-right:1px solid #3B5998;
background:#6D84B4 none repeat scroll 0 0;
height:30px;
}
#fblikepop #closeable{
float:right;
margin:7px 10px 0 0;
}
#fblikepop h1{
float:left;
color:#FFFFFF !important;
font-size:14px !important;
font-weight:normal !important;
padding:5px 5px 5px 10px !important;
margin:0 !important;
font-family:"Lucida Sans Unicode", "Lucida Grande", sans-serif !important;
}
#fblikepop #actionHolder{
height:30px;
overflow:hidden;
}
#fblikepop #buttonArea{
background:#F2F2F2;
border-top:1px solid #CCCCCC;
padding:10px;
min-height:50px;
}
#fblikepop #buttonArea a{
color:#999999 !important;
text-decoration:none !important;
border:0 !important;
font-size:10px !important;
}
#fblikepop #buttonArea a:hover{
color:#333 !important;
text-decoration:none !important;
border:0 !important;
}
#fblikepop #popupMessage{
text-align:center !important;
font-size:12px !important;
font-weight:normal !important;
padding:8px;
background:#fff !important;
}
#fblikepop #counter-display{
float:right;
font-size:11px !important;
font-weight:normal !important;
margin:5px 0 0 0;
text-align:right;
line-height:16px;
} | 1001ebooknet | css/fbpopup1001ebook.css | CSS | asf20 | 2,067 |
/* Skin for Blogger Tabbed Layout TOC */
#tabbed-toc {
margin:0 auto;
background-color:#224C19;
-webkit-box-shadow:0 1px 3px rgba(0,0,0,.4);
-moz-box-shadow:0 1px 3px rgba(0,0,0,.4);
box-shadow:0 1px 3px rgba(0,0,0,.4);
overflow:hidden;
position:relative;
color:#333;
}
#tabbed-toc .loading {
display:block;
padding:5px 10px;
font:normal bold 10px/normal Helmet,Freesans,Sans-Serif;
color:white;
}
#tabbed-toc ul,
#tabbed-toc ol,
#tabbed-toc li {
margin:0 0;
padding:0 0;
list-style:none;
}
#tabbed-toc .toc-tabs {
width:20%;
float:left;
}
#tabbed-toc .toc-tabs li a {
display:block;
font:normal bold 10px/28px Helmet,Freesans,Sans-Serif;
height:28px;
overflow:hidden;
text-overflow:ellipsis;
color:#ccc;
text-transform:uppercase;
text-decoration:none;
padding:0 12px;
cursor:pointer;
}
#tabbed-toc .toc-tabs li a:hover {
background-color:#153615;
color:white;
}
#tabbed-toc .toc-tabs li a.active-tab {
background-color:#275827;
color:white;
-webkit-box-shadow:-2px 2px 2px rgba(0,0,0,.5);
-moz-box-shadow:-2px 2px 2px rgba(0,0,0,.5);
box-shadow:-2px 2px 2px rgba(0,0,0,.5);
position:relative;
z-index:5;
margin:0 -1px 0 0;
/* cursor:text; */
}
#tabbed-toc .toc-content,
#tabbed-toc .divider-layer {
width:80%;
float:right;
background-color:white;
border-left:5px solid #275827;
-webkit-box-sizing:border-box;
-moz-box-sizing:border-box;
box-sizing:border-box;
}
#tabbed-toc .divider-layer {
float:none;
display:block;
position:absolute;
top:0;
right:0;
bottom:0;
-webkit-box-shadow:0 0 7px rgba(0,0,0,.7);
-moz-box-shadow:0 0 7px rgba(0,0,0,.7);
box-shadow:0 0 7px rgba(0,0,0,.7);
}
#tabbed-toc .panel {
position:relative;
z-index:5;
font:normal normal 10px/normal Helmet,Freesans,Sans-Serif;
}
#tabbed-toc .panel li a {
display:block;
position:relative;
font-weight:bold;
font-size:11px;
color:black;
line-height:20px;
height:20px;
padding:0 12px;
text-decoration:none;
outline:none;
overflow:hidden;
}
#tabbed-toc .panel li time {
display:block;
font-style:italic;
font-weight:normal;
font-size:10px;
color:#666;
float:right;
}
#tabbed-toc .panel li .summary {
display:block;
padding:10px 12px 10px;
font-style:italic;
border-bottom:4px solid #275827;
overflow:hidden;
}
#tabbed-toc .panel li .summary img.thumbnail {
float:left;
display:block;
margin:0 8px 0 0;
padding:4px 4px;
width:72px;
height:72px;
border:1px solid #dcdcdc;
background-color:#fafafa;
}
#tabbed-toc .panel li:nth-child(even) {
background-color:#ebeef4;
}
#tabbed-toc .panel li a:hover,
#tabbed-toc .panel li a:focus,
#tabbed-toc .panel li a:hover time,
#tabbed-toc .panel li.bold a {
background-color:#333;
color:white;
outline:none;
}
#tabbed-toc .panel li.bold a:hover,
#tabbed-toc .panel li.bold a:hover time {
background-color:#222;
}
.toc-tab-item-1,.toc-tab-item-2,.toc-tab-item-3,.toc-tab-item-4,.toc-tab-item-5,.toc-tab-item-6,.toc-tab-item-7,.toc-tab-item-8,.toc-tab-item-9,.toc-tab-item-10,.toc-tab-item-11,.toc-tab-item-12,.toc-tab-item-14,.toc-tab-item-16,.toc-tab-item-18,.toc-tab-item-19,.toc-tab-item-20,.toc-tab-item-22,.toc-tab-item-23,.toc-tab-item-24,.toc-tab-item-26,.toc-tab-item-27,.toc-tab-item-28,.toc-tab-item-29,.toc-tab-item-30,.toc-tab-item-32,.toc-tab-item-33,.toc-tab-item-34,.toc-tab-item-35,.toc-tab-item-36,.toc-tab-item-40,.toc-tab-item-41,.toc-tab-item-42,.toc-tab-item-44,.toc-tab-item-47,.toc-tab-item-48,.toc-tab-item-49,.toc-tab-item-50,.toc-tab-item-51,.toc-tab-item-52,.toc-tab-item-53,.toc-tab-item-54,.toc-tab-item-57,.toc-tab-item-58,.toc-tab-item-59,.toc-tab-item-60,.toc-tab-item-61,.toc-tab-item-62,.toc-tab-item-63,.toc-tab-item-64,.toc-tab-item-65,.toc-tab-item-66,.toc-tab-item-67,.toc-tab-item-68,.toc-tab-item-69,.toc-tab-item-70,.toc-tab-item-71,.toc-tab-item-72,.toc-tab-item-73,.toc-tab-item-74,.toc-tab-item-75,.toc-tab-item-76,.toc-tab-item-77,.toc-tab-item-81,.toc-tab-item-82,.toc-tab-item-83,.toc-tab-item-84,.toc-tab-item-85,.toc-tab-item-86,.toc-tab-item-87,.toc-tab-item-88,.toc-tab-item-89,.toc-tab-item-92,.toc-tab-item-93,.toc-tab-item-94,.toc-tab-item-95,.toc-tab-item-97,.toc-tab-item-99,.toc-tab-item-100,.toc-tab-item-101,.toc-tab-item-102,.toc-tab-item-105,.toc-tab-item-106,.toc-tab-item-107,.toc-tab-item-108,.toc-tab-item-110,.toc-tab-item-112,.toc-tab-item-113,.toc-tab-item-114,.toc-tab-item-116,.toc-tab-item-117,.toc-tab-item-120,.toc-tab-item-121,.toc-tab-item-122,.toc-tab-item-123,.toc-tab-item-124,.toc-tab-item-125,.toc-tab-item-126,.toc-tab-item-127,.toc-tab-item-128,.toc-tab-item-129,.toc-tab-item-130 {display:none} | 1001ebooknet | css/tabbed-toc.css | CSS | asf20 | 4,831 |
ul.w2b_recent_comments {
list-style: none;
margin: 0;
padding: 8px 0 0 0;
}
.w2b_recent_comments li {
background: none;
margin: 0 10px 6px 12px;
padding: 0 0 10px 0;
display: block;
clear: both;
overflow: hidden;
list-style: none;
}
.w2b_recent_comments li .avatarImage {
padding: 3px;
background: #fefefe;
-webkit-box-shadow: 0 1px 1px #ccc;
-moz-box-shadow: 0 1px 1px #ccc;
box-shadow: 0 1px 1px #ccc;
float: left;
margin: 0 8px 0 0;
position: relative;
overflow: hidden;
}
.avatarRound {
-webkit-border-radius: 100px;
-moz-border-radius: 100px;
border-radius: 100px;
}
.w2b_recent_comments a:link, .w2b_recent_comments a:visited {
font-weight: bold;
line-height: 1.9;
}
.w2b_recent_comments li img {
padding: 0px;
position: relative;
overflow: hidden;
display: block;
}
.w2b_recent_comments li span {
margin: 2px 10px 0 0;
color: #666;
display: block;
font-size: 11px;
font-style: italic;
line-height: 1.3;
} | 1001ebooknet | css/recentcomments1001ebook.css | CSS | asf20 | 1,106 |
.post {width:600px;background:#fff url(http://4.bp.blogspot.com/-i1DxbZx-CLA/ToSeO_R8tiI/AAAAAAAAABw/-wUayiAFmyQ/s1600/header-shadow.png) repeat-x top;border:1px solid #ccc;-webkit-border-radius:2px;-moz-border-radius:2px;border-radius:2px;float:left;margin:0 0 10px;padding:0;}
.post h2 {text-shadow: 1px 1px #fff;background-image:-moz-linear-gradient(center top , #FFFFFF, #DDDDDD);color:#444;border-bottom:1px solid #ccc;font-size:15px;font-weight:700;margin:0;
padding:7px 15px 8px 15px;}
.post .post-body {width:576px;background:#fbfbfb;border:1px solid #fff;padding:11px;margin-bottom:0px;}
.post .product_image {width:158px;height:199px;background:#f2f2f2;border:1px solid #ccc;float:left;text-align:center;margin-right:12px;padding:5px;}
.post .item_thumb {height:;width:;}
.post h4 {display:none;visibility:hidden;}
.post img {width:158px;height:199px;border:none;padding:0;}
.post figure {height:199px;width:158px}
.post .product_describe {margin-top:0px;padding-top:3px;height:199px;width:383px;float:left}
.post .product_description {display:none;visibility:hidden;}
.post .about_author {display:none;visibility:hidden;}
.post .reviews {display:none;visibility:hidden;}
.post .google_view {display:none;visibility:hidden;}
.post .download {display:none;visibility:hidden;}
.post a.view_detail {position:relative;right:0px;margin-top:-26px;color:#ddd;font:9px Arial;height:24px;line-height:24px;text-align:center;text-decoration:none;text-shadow:1px 1px 1px #222;text-transform:uppercase;font-weight:400;border-radius:0;border:none;padding:0;}
.post a.view_detail {background:url(http://3.bp.blogspot.com/-pPHbFZl7Aeo/UK326ZLTXzI/AAAAAAAACIE/4hj6oXtANM0/s1600/view+detail+1001+ebook.png) no-repeat;float:right;width:75px;}
.post a.buy {position:relative;bottom:0;left:-85px;margin-top:-18px;color:#ddd;font:9px Arial;height:24px;line-height:24px;text-align:center;text-decoration:none;text-shadow:1px 1px 1px #222;text-transform:uppercase;font-weight:400;border-radius:0;border:none;padding:0;box-shadow:none}
.post a.buy {background:url(http://3.bp.blogspot.com/-KzU1z2KPGQA/T6_x704zrII/AAAAAAAABMc/-N29RAtJwRA/s1600/detail.png) no-repeat;float:right;width:75px;}
a.view_detail:hover {background-position:bottom right;color:#fff;}
.post .buy {position:relative;bottom:0;left:-85px;margin-top:-18px;color:#ddd;font:9px Arial;height:24px;line-height:24px;text-align:center;text-decoration:none;text-shadow:1px 1px 1px #222;text-transform:uppercase;font-weight:400;border-radius:0;border:none;padding:0;box-shadow:none}
.post .buy {background:url(http://3.bp.blogspot.com/-KzU1z2KPGQA/T6_x704zrII/AAAAAAAABMc/-N29RAtJwRA/s1600/detail.png) no-repeat;float:right;width:75px;}
.post a.view_detail:hover {background-position:bottom right;color:#fff;}
.post a.buy:hover {background-position:bottom right;color:#fff;}
.post .buy a:link,.post .buy a:hover {color:#fff;}
/* Grid Style */
.grid {background:#fbfbfb;border:1px solid #ccc;width:192px;height:267px;margin:0 10px 10px 0;padding:0;}
.grid:hover {border:1px solid #999;box-shadow:0 0 4px #888;-moz-box-shadow:0 0 4px #888;-webkit-box-shadow:0 0 4px #888}
.grid h2 {display:none;visibility:hidden;}
.grid .post-body {background:#fbfbfb;width:170px;height:245px;border:1px solid #fff;padding:10px;background-image:-moz-linear-gradient(center top , #FFFFFF, #F3F3F3);Background-image:-webkit-linear-gradient(top, white, #F3F3F3)}
.grid .product_describe {display:none;visibility:hidden;}
.grid .product_description {display:none;visibility:hidden;}
.grid .about_author {display:none;visibility:hidden;}
.grid .reviews {display:none;visibility:hidden;}
.post .google_view {display:none;visibility:hidden;}
.grid .thumbx {width:158px;height:199px;background:#f2f2f2;border:1px solid #ccc;float:left;text-align:center;margin:11px 11px 8px 11px;padding:5px;}
.grid img {width:158px;height:199px;border:none;padding:0}
.grid figure {height:199px;width:158px}
.grid figcaption {font-weight:700;position: absolute;background: black;background: rgba(0,0,0,0.75);color:#f2f2f2;padding:10px 20px;opacity: 0;-webkit-transition: all 0.6s ease;-moz-transition: all 0.6s ease;-o-transition: all 0.6s ease;text-shadow:0 1px 0 #000000;}
.grid .download {display:none;visibility:hidden;}
.grid .like_button {position:static;}
/* View detail and Buy */
.grid a.view_detail {position:relative;left:2px;bottom:0;color:#ddd;font:9px Arial;height:24px;line-height:24px;text-align:center;text-decoration:none;text-shadow:1px 1px 1px #222;text-transform:uppercase;margin:0;font-weight:400;border-radius:0;border:none;padding:0;}
.grid a.view_detail {background:url(http://1.bp.blogspot.com/-2FzDT-9IPZU/UVq6jkEAcUI/AAAAAAAAHVc/aoshS7Xk3bg/s1600/view_detail_1001_ebook.png) no-repeat;float:left;width:75px;}
.grid a.buy {position:relative;left:-6px;bottom:-8px;color:#ddd;font:9px Arial;height:24px;line-height:24px;text-align:center;text-decoration:none;text-shadow:1px 1px 1px #222;text-transform:uppercase;margin:0;font-weight:400;border-radius:0;border:none;padding:0;box-shadow:none}
.grid a.buy {background:url(http://3.bp.blogspot.com/-KzU1z2KPGQA/T6_x704zrII/AAAAAAAABMc/-N29RAtJwRA/s1600/detail.png) no-repeat;float:right;width:75px;}
.grid .buy {position:relative;left:-6px;bottom:-8px;color:#ddd;font:9px Arial;height:24px;line-height:24px;text-align:center;text-decoration:none;text-shadow:1px 1px 1px #222;text-transform:uppercase;margin:0;font-weight:400;border-radius:0;border:none;padding:0;box-shadow:none}
.grid .buy {background:url(http://3.bp.blogspot.com/-KzU1z2KPGQA/T6_x704zrII/AAAAAAAABMc/-N29RAtJwRA/s1600/detail.png) no-repeat;float:right;width:75px;}
.grid a.view_detail:hover {background-position:bottom right;color:#fff;}
.grid a.buy:hover {background-position:bottom right;color:#fff;}
.grid .buy:hover {background-position:bottom right;color:#fff;}
.grid .buy a:link,.grid .buy a:hover {color:#fff;} | 1001ebooknet | css/gridlist1001ebook.css | CSS | asf20 | 5,918 |
/*-----------------------------------------------
Blogger Template Style
Name: Minima
Date: 26 Feb 2004
Updated by: Blogger Team
----------------------------------------------- */
/* Variable definitions
====================
<Variable name="bgcolor" description="Page Background Color"
type="color" default="#fff" value="#eeeeee">
<Variable name="textcolor" description="Text Color"
type="color" default="#444" value="#444444">
<Variable name="linkcolor" description="Link Color"
type="color" default="#58a" value="#4d7c03">
<Variable name="pagetitlecolor" description="Blog Title Color"
type="color" default="#666" value="#71ba00">
<Variable name="descriptioncolor" description="Blog Description Color"
type="color" default="#999" value="#cccccc">
<Variable name="titlecolor" description="Post Title Color"
type="color" default="#c60" value="#000000">
<Variable name="bordercolor" description="Border Color"
type="color" default="#C0C0C0" value="#C0C0C0">
<Variable name="sidebarcolor" description="Sidebar Title Color"
type="color" default="#C0C0C0" value="#C0C0C0">
<Variable name="sidebartextcolor" description="Sidebar Text Color"
type="color" default="#666" value="#666666">
<Variable name="visitedlinkcolor" description="Visited Link Color"
type="color" default="#999" value="#4d7c03">
<Variable name="bodyfont" description="Text Font"
type="font" default="normal normal 100% Georgia, Serif" value="normal normal 12px Arial, Tahoma, Helvetica, FreeSans, sans-serif">
<Variable name="headerfont" description="Sidebar Title Font"
type="font"
default="normal normal 78% 'Trebuchet MS',Trebuchet,Arial,Verdana,Sans-serif" value="normal bold 14px Arial, Tahoma, Helvetica, FreeSans, sans-serif">
<Variable name="pagetitlefont" description="Blog Title Font"
type="font"
default="normal normal 200% Georgia, Serif" value="normal normal 42px Kenia">
<Variable name="descriptionfont" description="Blog Description Font"
type="font"
default="normal normal 78% 'Trebuchet MS', Trebuchet, Arial, Verdana, Sans-serif" value="normal bold 11px Josefin Sans">
<Variable name="postfooterfont" description="Post Footer Font"
type="font"
default="normal normal 78% 'Trebuchet MS', Trebuchet, Arial, Verdana, Sans-serif" value="normal normal 12px Arial, Tahoma, Helvetica, FreeSans, sans-serif">
<Variable name="startSide" description="Side where text starts in blog language"
type="automatic" default="left" value="left">
<Variable name="endSide" description="Side where text ends in blog language"
type="automatic" default="right" value="right">
*/
/* Use this with templates/template-twocol.html */
body{background:#000000 url("http://4.bp.blogspot.com/-JeYqsWlEyU8/UVq6ghCtFeI/AAAAAAAAHUg/CQ0uE-GIgaI/s1600/bg_1001ebook.png") repeat;color:$textcolor;font:12px Arial;text-align:left;margin:0}
a:link{color:#4d7c03;text-decoration:none}
a:visited{color:#4d7c03;text-decoration:none}
a:hover{color:#000000;text-decoration:none;}
a img{border-width:0}
#wrapper{width:1020px;margin-left:auto;margin-right:auto}
#header-wrapper{width:950px;margin-top:38px;margin-right:auto;margin-left:auto}
#header-inner{background-position:center;margin-left:auto;margin-right:auto;}
#header{float:left;border:0 solid $bordercolor;text-align:left;color:$pagetitlecolor;margin-left:12px}
#header2{float:right;width:468px;margin-top:10px;margin-right:15px;text-align:left;color:#555;filter:alpha(opacity=70);opacity:0.9}
.header .widget,.header2 .widget,.sidebar .widget-content,.main-wrapper .widget{margin:0 auto;padding:0}
#header h1{visibility:hidden;line-height:1.2em;text-transform:none;letter-spacing:.1em;font: bold 24px Oswald;text-shadow:0 1px 1px #000;margin:0 auto;padding:5px 5px .15em;color:#aaa;}
#header a{text-decoration:none}
#header a:hover{color:$pagetitlecolor}
#header .description{visibility:hidden;max-width:100%;text-transform:uppercase;letter-spacing:.01em;line-height:1.2em;font:$descriptionfont;color:$descriptioncolor;margin:0 auto;padding:0 5px 5px}
#header img{margin-startside:auto;margin-endside:auto}
.date-header,.post-footer,.feed-links,.linkwithin_logo_0,.linkwithin_logolink_0 {display:none;}
#nav-wrapper{background:url(http://3.bp.blogspot.com/-RrpT0AaU2QQ/TgIehyj7RoI/AAAAAAAAAYI/cPYs2xTA4f4/s320/navbar.gif);width:100%;border-bottom:1px solid #222;margin:0 auto;padding:0 auto;opacity:0.9;}
#navbarmenu{width:950px;height:35px;font:bold 12px Tahoma;color:#777;font-weight:700;margin:0 auto;padding:0}
#navbar p{margin:0;padding:8px 0 0 15px}
#nav{margin:0;padding:0}
#nav li a,#nav li a:link,#nav li a:visited{color:#777;display:block;font-weight:700;text-decoration:none;border-right:1px solid #000;margin:0;padding:10px 15px 11px}
#nav li a:hover,#nav li a:active{background:#000 url(http://2.bp.blogspot.com/-kXspYilhflg/TgIelo03VtI/AAAAAAAAAYQ/iHIX2IGIi2s/s1600/navhov.gif);color:#FFF}
#nav li li a,#nav li li a:link,#nav li li a:visited{width:170px;background:#424242;color:#FFF;float:none;border-bottom:1px solid #000;border-left:1px solid #000;border-right:1px solid #000;margin:0;padding:7px 10px}
#nav li li a:hover,#nav li li a:active{background:#000;color:#FFF;padding:7px 10px}
#nav li ul{z-index:9999;position:absolute;left:-999em;height:auto;width:190px;margin:0;padding:0}
#nav li ul a{width:160px}
#nav li ul ul{margin:-30px 0 0 191px}
#nav li:hover ul ul,#nav li:hover ul ul ul,#nav li.sfhover ul ul,#nav li.sfhover ul ul ul{left:-999em}
#nav li:hover ul,#nav li li:hover ul,#nav li li li:hover ul,#nav li.sfhover ul,#nav li li.sfhover ul,#nav li li li.sfhover ul{left:auto}
#nav li:hover,#nav li.sfhover{position:static}
#nav ul,#nav li{float:left;list-style:none;margin:0;padding:0}
.navtime{width:290px;float:right;margin:0 auto;padding:0 auto}
.topwrap{width:100%;margin:0 auto;padding:0 auto}
.top{background:url(http://3.bp.blogspot.com/-Q_OmuQTlEBU/UVsLP2meD7I/AAAAAAAAHWs/W7zmd0UugWs/s1600/1001ebook_img.png) no-repeat top center;background-position: -10px -10px;width:980px;height:42px;margin:0 auto;padding-bottom:8px}
.topwrap-left{float: left; width: 635px;padding-top:5px;}
.topwrap-left ul{padding-left:7px;color:#666;list-style-type:none;margin:0}
.topwrap-left li{display:inline;margin:0}
.topwrap-left li a{font:bold 13px open sans;float:left;display:block;color:#444;line-height:1.2;padding:4px 8px 5px 8px;}
.topwrap-left li a:visited{color:#444}
.topwrap-left li a:hover{background:#979797;border-radius:10px;-webkit-border-radius:10px;-opera-border-radius:10px;-moz-border-radius:10px;color:#fff;text-decoration:none;-moz-box-shadow:inset 2px 2px 2px #404040;-webkit-box-shadow:inset 2px 2px 2px #404040;box-shadow:inset 2px 2px 2px #404040}
.topsearch{width:290px;float:right;margin:0;padding:3px 12px 0 0}
h1,h2,h3,h4{font-weight:700;font-family:'open sans', cursive;}
h1{font-size:24px;}
h2{font-size:16px;}
h3{font-size:20px;}
h4{font-size:16px;}
.left{float:left;}
.right{float:right;}
.clearfix:after{clear:both;content:"";display:block;font-size:0;height:0;visibility:hidden;}
.clear{clear:both;display:block;font-size:0;height:0;line-height:0;width:100%;margin:0;padding:0;}
.status-msg-wrap{background:#fbfbfb;border:5px solid #ccc;font-size:14px;text-shadow:1px 1px 1px #fff;-webkit-border-radius:5px 5px 5px 5px;-moz-border-radius:5px;-khtml-border-radius:5px 5px 5px 5px;border-radius:5px 5px 5px 5px;padding:5px 10px;margin:10px 14px;width: 544px;}
.status-msg-border,.status-msg-bg{border:none;background:transparent}
.status-msg-body{bottom: 5px;left: 0;padding-left: 10px;padding-right: 10px;right: 0;top: 5px;width: 544px;}
#blog-pager{position:relative;top:0px;background-image:-moz-linear-gradient(center top , #FFFFFF, #DDDDDD);border:1px solid silver;height:23px;width:580px;line-height:22px;border:1px solid #ccc;clear:both;font-family:'Open Sans', Tahoma, sans-serif;font-weight:700;color:#000;font-size:14px;margin:10px 0 20px 0;padding:5px 10px;Background-image:-webkit-linear-gradient(top, white, #DDD)}
#outer-wrapper{position:relative;text-align:left;width:950px;clear:both;background:#f0f0f0 url(http://2.bp.blogspot.com/-ukWl4H73Aa4/UVq6iKI5hqI/AAAAAAAAHVA/g-b0jjhTLkU/s1600/maincol-grad.png) repeat-x top;margin:0 auto}
#content-wrapper{width:918px;clear:both;padding:10px 16px 0 16px}
.main-wrapper{width:615px;float:left;margin-right:0px}
#sidebar-wrapper{width:300px;float:right;margin-bottom:10px;word-wrap:break-word;/* fix for long text breaking sidebar float in IE */
overflow:hidden;/* fix for long non-text content breaking IE sidebar float */
}
#main,#sidebar{margin:0;padding:0}
#sidebartab1{margin:0;padding:0}
#sidebartab2{margin:0;padding:0}
#sidebar2{margin:0 0 8px 0;padding:0}
#sidebar3{margin:0;padding:0}
#sidebar4{margin:0 0 8px 0;padding:0}
#sidebar5{margin:0 0 8px 0;padding:0}
#sidebar6{margin:0px 0 8px 0;padding:0}
#sidebar7{margin:0px 0 8px 0;padding:0}
#BlogArchive1{border-top:0;padding-top:1px}
#BlogArchive1 h2 {display:none;visibility:hidden;}
#ArchiveList{font-size:11px;margin:0 10px 15px 10px}
.BlogArchive #ArchiveList ul {margin-top: 2px}
.BlogArchive #ArchiveList ul li {margin:0 0 2px 0;padding:3px 0 4px 15px}
.BlogArchive #ArchiveList ul.posts li {margin-bottom: 0;margin-top: 2px; padding-bottom: 3px;padding-left: 1.3em;}
ul.isocial{list-style:none;margin:0;padding:5px 20px 0 0}
ul.isocial li{float:right;margin:0 5px;padding:0}
ul.isocial li a{float:right;background-image:url(http://4.bp.blogspot.com/-ZO9bKtIxZMc/UWuOY5V69NI/AAAAAAAAHi8/xT78ctFaMcM/s1600/social+letter+1001+ebook.png);background-position:0 0;background:repeat:no-repeat;display:inline-block;text-indent:-9999px;overflow:hidden;width:24px;height:24px;position:relative}
ul.isocial li a.rss{background-position:0 0}
ul.isocial li a.rss:hover{background-position:0 -25px}
ul.isocial li a.facebook{background-position:-25px 0}
ul.isocial li a.facebook:hover{background-position:-25px -25px}
ul.isocial li a.twitter{background-position:-50px 0}
ul.isocial li a.twitter:hover{background-position:-50px -25px}
ul.isocial li a.google{background-position:-75px 0}
ul.isocial li a.google:hover{background-position:-75px -25px}
ul.isocial li a.youtube{background-position:-100px 0}
ul.isocial li a.youtube:hover{background-position:-100px -25px}
.switch{height:20px;background-image:-moz-linear-gradient(center top , #FFFFFF, #DDDDDD);border:1px solid silver;width:584px;margin:0 0 10px;padding:7px 8px 8px 8px;Background-image:-webkit-linear-gradient(top, white, #DDD)}
.switch-left{width:400px;float:left;line-height:20px;padding-left:5px auto;font:bold 16px Open Sans;color:#444444;text-shadow: 1px 1px #fff}
.switch-right{width:115px;float:right;margin:0 auto;padding-top:3px}
.switch a{background:#fff;border:1px solid #ccc;font-size:11px;padding:3px 8px 3px 25px}
a.grid_view{background:url(http://2.bp.blogspot.com/-7BeF7FZiHo0/T6vZzVSzTzI/AAAAAAAABJs/FlrWN7ZRxmk/s1600/drid.gif) no-repeat 3px center}
a.list_view{background:url(http://1.bp.blogspot.com/-43EW3Gjakwc/T6vZz6K4N_I/AAAAAAAABJ0/hi2LK0zc4JQ/s1600/listed.gif) no-repeat 3px center}
.switch a.active{background-color:#ededed;border:1px solid #ccc;color:#111;cursor:default}
.post h2{text-shadow: 1px 1px #fff;background-image:-moz-linear-gradient(center top , #FFFFFF, #DDDDDD);color:#444;border-bottom:1px solid #ccc;font-size:16px;font-weight:700;margin:0;padding:9px 14px 10px 14px;Background-image:-webkit-linear-gradient(top, white, #DDD)}
.post h4 {color: #289728;font-size: 10pt;padding:5px 8px 3px 9px;margin:0 -8px 10px -8px;background-color:#EBEEF4;border-radius:4px;height: 21px;}
.post{width:600px;background:url(https://lh5.googleusercontent.com/-o3DTpFffrHI/ToUZNoEdRZI/AAAAAAAAAB4/rEq7jJy21MA/h1600/container-bg.png);border:1px solid #ccc;-webkit-border-radius:2px;-moz-border-radius:2px;border-radius:2px;float:left;margin:0 0 10px;padding:0}
.post-body{width:570px;padding:15px 15px 0px 15px}
.comment-link{margin-startside:.6em}
#comments h4{color:#111;font-size:16px;font-family:Tahoma, Arial, Verdana;font-weight:400;margin:0 0 5px;padding:0;letter-spacing: 0.1em}
#comments{width:580px;background:url(https://lh5.googleusercontent.com/-o3DTpFffrHI/ToUZNoEdRZI/AAAAAAAAAB4/rEq7jJy21MA/h1600/container-bg.png);border:1px solid silver;margin:0 0 10px;padding:10px}
.deleted-comment{font-style:italic;color:gray}
.comment-form {clear: both;width:100%;max-width: 100%;}
.tabs-widget{list-style:none;list-style-type:none;height:31px;border-top:1px solid silver;border-left:1px solid silver;margin:0;padding:0;background-color: #FBFBFB}
.tabs-widget ul{border-bottom:0;height:31px}
.tabs-widget li{margin:0;padding:0;float:right;width:148px;background-image:-moz-linear-gradient(center top , #FFFFFF, #DDDDDD);border-right:1px solid silver;Background-image:-webkit-linear-gradient(top, white, #DDD)}
.tabs-widget li:first-child{margin:0;float:left;width:148px;background-image:-moz-linear-gradient(center top , #FFFFFF, #DDDDDD);Background-image:-webkit-linear-gradient(top, white, #DDD)}
.tabs-widget li a{float: left;display: block;height:18px;width:148px;text-align: center;margin: 0;padding: 5px 0 7px 0;border-bottom: 1px solid silver;-moz-font-feature-settings: normal;-moz-font-language-override: normal;-x-system-font: none;font-color: #444;font-family: open sans;font-size: 13px;font-size-adjust: none;font-stretch: normal;font-style: normal;font-variant: normal;font-weight: bold;text-shadow: 1px 1px #FFFFFF;}
.tabs-widget li a:hover{color:#444;text-decoration:none}
.tabs-widget li a.tabs-widget-current{background-color: #fbfbfb;color:#444;text-decoration:none;border-bottom-color:#fbfbfb}
.tabs-widget-content{background:none}
.tabviewsection{margin-top:0px;margin-bottom:8px;}
.sidebar h2{background-image:-moz-linear-gradient(center top , #FFFFFF, #DDDDDD);text-shadow: 1px 1px #fff;letter-spacing:-.001em;font:bold 15px open sans;color:#444;margin:0 0 0;padding:6px 10px 7px 10px;border-bottom:1px solid silver;background-image:-webkit-linear-gradient(top, white, #DDD)}
.sidebar .widget{border:1px solid silver;margin:0 0 8px;background-color: #FBFBFB}
.sidebar a:link,.sidebar a:visited{font: 12px Arial;color:#333;text-decoration:none}
.sidebar a:hover{color:#477503}
.sidebar{font:normal 12px Arial;color:#444;line-height:1.4em}
.sidebar li{border-bottom:1px solid #eee;text-indent:0;line-height:1em;margin:0;padding:3px 0 4px}
.sidebar ul{list-style:none;margin:0;padding:2px 8px}
.footer h2{background:url(http://1.bp.blogspot.com/-P9SH_Wqh8H8/T42Xsi3BLrI/AAAAAAAAAns/CQ8rRk-aAwE/s1600/batas.png) repeat-x scroll bottom;padding-bottom:10px;font:bold 14px Arial;color:#ccc;line-height:1.2em;text-transform:none;letter-spacing:.01em;margin:0 0 3px}
.footer{font:normal 12px Arial;color:#8691a1;line-height:1.3em}
.footer ul{list-style:none;color:#EAE9E8;margin:0;padding:0}
.footer li{background:url(http://4.bp.blogspot.com/-Bt0JYGRHfpk/T7ZpN5RNSQI/AAAAAAAAGJQ/zQtrWVZwgHA/s1600/bullet.png) no-repeat 1px 5px;font:normal 13px Arial;color:#EAE9E8;text-indent:0;line-height:1.1em;margin:0;padding:2px 0 3px 16px}
.footer .widget{margin:0 0 20px;padding:0 auto}
.footer a:link,.footer a:visited{font:normal 11px Arial;color:#999;text-decoration:none}
.footer a:hover{color:#fff;text-decoration:none}
.footerwrap{display:none;visibility:hidden;background:#252525 url(http://1.bp.blogspot.com/-lv6mWIQHI3Y/T7Zs3FSfchI/AAAAAAAAGJc/uh7iXKJPKiQ/s1600/footer-bg.jpg) repeat-x top;width:950px;margin-startside:auto;margin-endside:auto;text-align:center;font:normal normal 12px Arial, Tahoma, Helvetica, FreeSans, sans-serif;margin:0 auto;padding:10px 0}
#footer-wrapper{width:950px;text-align:left;font:normal normal 12px Arial, Tahoma, Helvetica, FreeSans, sans-serif;margin:0 auto;padding:10px 0}
#footer1-wrapper{width:300px;float:left;margin-left:15px;word-wrap:break-word;overflow:hidden}
#footer2-wrapper{width:300px;float:left;margin-left:15px;word-wrap:break-word;overflow:hidden}
#footer3-wrapper{width:300px;float:left;word-wrap:break-word;overflow:hidden}
.creditwrap{background:#333 url(http://3.bp.blogspot.com/-Q_OmuQTlEBU/UVsLP2meD7I/AAAAAAAAHWs/W7zmd0UugWs/s1600/1001ebook_img.png) no-repeat top center;background-position: -29px -108px;width:950px;margin:0 auto;padding:0 auto}
.credit{width:930px;line-height:1.6em;text-align:center;font-family:Arial;font-size:11px;color:#aaa;overflow:hidden;clear:both;margin:0 auto;padding:10px 0}
.credit a:link,.credit a:visited{color:#aaa;text-decoration:none}
.credit a:hover{color:#FFF;text-decoration:none}
.product_image{background:#f2f2f2;border:1px solid #ccc;float:left;text-align:center;margin:0 15px 0 0;padding:5px;width:210px;height:280px}
.product_image img{width:210px;height:280px}
.product_describe {float:right;width:333px;height:292px;color: #3D85C6;margin-top:0px;}
.product_description {float: left;width:100%;padding: 20px 0px 0px 0px; text-align: justify}
.about_author {float:left;width:100%;padding: 25px 0px 0px 0px;text-align: justify}
.reviews {float:left;width:100%;padding: 25px 0px 0px 0px;}
.post blockquote {background-attachment: scroll;background-clip: border-box;background-color: #F3F3F1;background-image: url("http://4.bp.blogspot.com/-li4rr6og6ws/UJQDnLEXYrI/AAAAAAAABp8/G3UtCrjCF-s/s1600/comma-side-orange-1001-ebook.gif");background-origin: padding-box;background-repeat: repeat-y;background-size: auto auto;font-family: Georgia,"Times New Roman",Times,serif;font-style: italic;font-size: 1em;margin: 0px 0px;padding: 20px 20px 15px 45px;}
blockquote {color: #555555;}
.google_view {float:left;margin-left: 235px;margin-top: -35px;}
.like_button{position:absolute;bottom:16px;left:220px;}
.download{position:relative;float:right;height:16px;width: 252px;bottom:-395px;right:12px;background:#acdc54 url(http://2.bp.blogspot.com/-S4AKqSDPUEs/ToSYCWJy4qI/AAAAAAAAABI/conBgqSajOY/s1600/fade.png) repeat-x top left;color:#fff;text-shadow:1px 1px 1px #cbeb8a;font-size:14px;text-align: center;text-transform:uppercase;font-weight:700;border:1px solid #7bac2f;padding:7px 0;border-radius:3px;box-shadow:0 1px 0 rgba(255, 255, 255, 0.4) inset, 0 0 0 1px rgba(255, 255, 255, 0.2) inset, 0 1px 0 rgba(255, 255, 255, 0.5);}
.download2{position:relative;float:right;height:16px;width: 252px;bottom:-395px;right:12px;background:#acdc54 url(http://2.bp.blogspot.com/-S4AKqSDPUEs/ToSYCWJy4qI/AAAAAAAAABI/conBgqSajOY/s1600/fade.png) repeat-x top left;color:#fff;text-shadow:1px 1px 1px #cbeb8a;font-size:14px;text-align: center;text-transform:uppercase;font-weight:700;border:1px solid #7bac2f;padding:7px 0;border-radius:3px;box-shadow:0 1px 0 rgba(255, 255, 255, 0.4) inset, 0 0 0 1px rgba(255, 255, 255, 0.2) inset, 0 1px 0 rgba(255, 255, 255, 0.5);}
.buy{position:relative;float:left;height:16px;width: 252px;bottom:-395px;left:12px;background:#acdc54 url(http://2.bp.blogspot.com/-S4AKqSDPUEs/ToSYCWJy4qI/AAAAAAAAABI/conBgqSajOY/s1600/fade.png) repeat-x top left;color:#fff;text-shadow:1px 1px 1px #cbeb8a;font-size:14px;text-align: center;text-transform:uppercase;font-weight:700;border:1px solid #7bac2f;padding:7px 0;border-radius:3px;box-shadow:0 1px 0 rgba(255, 255, 255, 0.4) inset, 0 0 0 1px rgba(255, 255, 255, 0.2) inset, 0 1px 0 rgba(255, 255, 255, 0.5);}
#searchbar{background:#fff url(http://1.bp.blogspot.com/-Tj311tOuSXw/T40fSwQhb2I/AAAAAAAAAl0/UynjCcmZ9CE/s1600/searchbar.png) repeat-x bottom;width:950px;height:40px;font-size:12px;font-family:Arial, Tahoma, Verdana;color:#616161;font-weight:700;margin:0 auto;padding-top:3px;text-align:center}
#searchbarleft{width:400px;float:left;margin:0;padding:2px 0 0 20px}
#searchbarmiddle{width:200px;float:left;margin:0;padding:1px 0 0}
#searchbarright{width:312px;float:right;margin-top:-2px;padding:0 15px 0 0}
#searchbarform{display:inline;overflow:hidden;margin:10px 0 0}
#searchbarformheader{margin:0}
#cat{background:#fff;width:220px;color:#222;font-family:Arial, Tahoma, Verdana;display:inline;margin:3px;padding:3px 2px 2px;float:right}
.shadow{width:950px; height:8px; background:#fff url(http://3.bp.blogspot.com/-Q_OmuQTlEBU/UVsLP2meD7I/AAAAAAAAHWs/W7zmd0UugWs/s1600/1001ebook_img.png) no-repeat center;background-position: -15px -80px; margin:0 auto}
#fixed {height: 35px;left: 0;top: 0;width: 100%;z-index: 999;position: fixed;}
#fixedinner {background-attachment: scroll;background-clip: border-box;background-color: transparent;background-image: none;background-origin: padding-box;background-position: 0 0;background-repeat: repeat;background-size: auto auto;height: 35px;position: relative;text-align: center;z-index: 999;}
figure {display: block;position: relative;float: left;overflow: hidden;margin: 0;height: 280px;}
figure:hover figcaption {opacity: 1;}
figure:before {position: absolute;font-weight: 800;background: black;background: rgba(255,255,255,0.75);text-shadow: 0 0 5px white;color: black; width: 24px;height: 24px;-webkit-border-radius: 12px;-moz-border-radius: 12px;border-radius: 12px;text-align: center;font-size: 14px;line-height: 24px;-moz-transition: all 0.6s ease;opacity: 0.75;}
figure:hover:before {opacity: 0;}
.cap-bot:before {bottom: 10px; left: 10px;}
.cap-bot figcaption {left: 0;right: 0;bottom: -30%;}
.cap-bot:hover figcaption {bottom: 0;}
.postfooter-box {height:331px;padding:8px 13px;width:570px;margin-bottom:15px}
.facebook-box {border-top: 1px solid #ddd;padding:0;background-color: #F4F6F8;width: 287px;height: 321px;border-top: 1px solid #BECCDB;border-right: 1px solid #BECCDB;border-left: 1px solid #BECCDB;float: left;}
.social-links {background-color: #6D84B4;border-top-color: #DDDDDD;border-top-style: solid;border-top-width: 1px;color: #FFFFFF;height: 45px;margin-top: -5px;margin-left: -1px;padding: 0;width: 289px;}
.social-links .fl {float: left;height: 38px;line-height: 44px;padding:1px 0 0 12px;width: 170px;color:#fff}
.social-links .fl a {color:#fff }
.social-links .fl a:hover{color:#fff}
.social-links .fr {float: right;text-align: right;height: 24px;line-height: 30px;padding: 8px 12px 0 0;width: 95px;}
.buyebook-box {float: left;height: 322px;width: 277px;margin-right: 1px}
.be-ads {background-color: #F4F6F8;border-top: 1px solid silver;border-right: 1px solid silver;border-left: 1px solid silver;height: 250px;padding: 15px;position: relative;width: 250px;z-index: 2;}
.adv {float:left;height: 125px;padding: 5px;width: 125px;}
.adv img:hover {opacity: 0.75;}
.be-button {background-color: #C9CFD6;box-shadow: 0 0 12px rgba(0, 0, 0, 0.3) inset, 0 1px 0 white;height: 50px;margin: 0;width: 282px;}
.download-box {float: right;height: 322px;width: 277px;margin-right: 1px}
.dl-ads {background-color: #F4F6F8;border-top: 1px solid silver;border-right: 1px solid silver;border-left: 1px solid silver;height: 250px;padding: 15px;position: relative;width: 250px;z-index: 2;}
.adv {float:left;height: 125px;padding: 5px;width: 125px;}
.adv img:hover {opacity: 0.75;}
.dl-button {background-color: #C9CFD6;box-shadow: 0 0 12px rgba(0, 0, 0, 0.3) inset, 0 1px 0 white;height: 50px;margin: 0;width: 282px;}
.head-comments {background-color: #EBEEF4;background-color: transparent;padding:7px 7px 25px 7px;margin: 0;position: relative;float:left;line-height:1.4em;}
.iframe-comment {background-color: #F2F2F2;border: 1px solid silver;border-radius: 4px;float: right;font-size: 13px;font-family: open sans;margin: -14px 10px 0 0;padding: 4px 9px 5px 9px;}
img.label_thumb{float:left;border:1px solid #8f8f8f;background:#D2D0D0;margin-right:10px;height:60px;width:60px;padding:2px}
img.label_thumb:hover{background:#f7f6f6}
.label_with_thumbs{float:left;width:100%;min-height:70px;margin:0 5px 2px 0}
ul.label_with_thumbs li{min-height:65px;margin:2px 0;padding:4px 0}
a#scroll-to-top {display:none;background-image: url(http://3.bp.blogspot.com/-JYWkOUe8fdk/UKHLmA4iPmI/AAAAAAAAB6A/l9IadjAc1YU/s1600/return+top.png);background-position: left top;background-repeat: no-repeat;bottom: 10px;height: 99px;position: fixed;right: 10px;width: 18px;cursor:pointer}
a#scroll-to-top:hover {-moz-text-blink: none;-moz-text-decoration-color: -moz-use-text-color;-moz-text-decoration-line: none;-moz-text-decoration-style: solid;background-attachment: scroll;background-clip: border-box;background-color: transparent;background-image: url(http://3.bp.blogspot.com/-JYWkOUe8fdk/UKHLmA4iPmI/AAAAAAAAB6A/l9IadjAc1YU/s1600/return+top.png);background-origin: padding-box;background-position: right top;background-repeat: no-repeat;background-size: auto auto;}
a#home{background-attachment:scroll;background-clip:border-box;background-color:transparent;background-image:url(http://1.bp.blogspot.com/-5bT6ZhC6mkY/UNa5_4FMCuI/AAAAAAAADCE/43qOqvgY2VE/s1600/home1001ebook.png);background-origin:padding-box;background-position:top;background-repeat:no-repeat;background-size:autoauto;top:4px;height:24px;position:fixed;left:64px;width:24px;}
a#home:hover{background-attachment:scroll;background-clip:border-box;background-color:transparent;background-image:url(http://1.bp.blogspot.com/-5bT6ZhC6mkY/UNa5_4FMCuI/AAAAAAAADCE/43qOqvgY2VE/s1600/home1001ebook.png);background-origin:padding-box;background-position:bottom;background-repeat:no-repeat;background-size:autoauto;}
.PopularPosts .item-thumbnail {float: right;margin:0 0 0 10px;}
.PopularPosts .item-thumbnail a{height:105px;width:80px;float:left;background-attachment: scroll;background-clip: border-box;background-color: #000000;background-image: url(http://4.bp.blogspot.com/-JU3LBVknou0/UMUwgPtoPOI/AAAAAAAACp4/xTQZmppO3u4/s1600/darken-bg-small.png);background-origin: padding-box;background-position: center center;background-repeat: no-repeat;background-size: auto auto;}
#PopularPosts2 li img {margin-right:0;padding: 0;border:0;opacity:1;}
#PopularPosts2 li img:hover{opacity:0.45}
#PopularPosts2 h2 {display:none;visibility:hidden;}
#PopularPosts2 {font-size:10px;padding-bottom: 2px;border-top:0;height:380px}
#PopularPosts2 .item-thumbnail{background-color: #F2F2F2;float:left;margin:0 5px 8px 0;padding:4px;border:1px solid #CCC;height:105px;width:80px}
#PopularPosts2 ul{padding: 10px 0 0 9px}
#PopularPosts2 ul li {list-style-image: none;list-style-type: none;display:inline;}
#PopularPosts2 li img{height:105px;width:80px}
/* Start of Post Navigator by MBT (LIGHT Theme) ------ */
#calendarDisplay {display:block;overflow:auto;width:ancho;height:158px;margin-top:7px}
/* div that holds calendar */
#blogger_calendar { margin:0px auto 0px 0px;width:100%;}
/* Table Caption - Holds the Archive Select Menu */
#bcaption {border:1px solid #C7C7C7;padding:2px;margin:10px 0 0;background:#EBEEF4;font:bold 100% Tahoma, Arial, Sans-serif}
/* The Archive Select Menu */
#bcaption select {background:#EBEEF4;border:0 solid #C7C7C7;color:#0080ff;font-weight:bold;text-align:center;width:100%}
/* The Heading Section */
table#bcalendar thead {}
/* Head Entries */
table#bcalendar thead tr th {width:20px;text-align:center;padding:3px;font:bold 110% Tahoma, Arial, Sans-serif;background:#fff;color:#0080ff;}
/* The calendar Table */
table#bcalendar {border:1px solid #C7C7C7;border-top:0; margin:0px 0 0px;width:100%;background:#fff}
/* The Cells in the Calendar */
table#bcalendar tbody tr td {text-align:center; border-radius:4px; padding:3px;color:#666;font:bold 100% Tahoma, Arial, Sans-serif;}
/* Links in Calendar */
table#bcalendar tbody tr td a:link, table#bcalendar tbody tr td a:visited, table#bcalendar tbody tr td a:active {font:bold 100% Tahoma, Arial, Sans-serif;color:green; text-decoration:none;}
table#bcalendar tbody tr td a:hover {color:#0080FF; text-decoration:none;}
/* First Row Empty Cells */
td.firstCell {visibility:visible;}
/* Cells that have a day in them */
td.filledCell {background:#fff;}
/* Cells that are empty, after the first row */
td.emptyCell {visibility:hidden;}
/* Cells with a Link Entry in them */
td.highlightCell {background:#fff}
/* Table Footer Navigation */
table#bcNavigation {width:100%;background:#fff;border:1px solid #C7C7C7;border-top:0;color:#0080ff;font:bold 100% Tahoma, Arial, Sans-serif;}
table#bcNavigation a:link {text-decoration:none;color:#0080ff}
table#bcNavigation a:hover{text-decoration:none}
table#bcNavigation a:visited{text-decoration:none;color:#0080ff}
td#bcFootPrev {width:10px;float:left}
td#bcFootAll{text-align:center;display:none;visibility:hidden}
td#bcFootNext {width:10px;float:right}
ul#calendarUl {margin:5px auto 0!important;}
ul#calendarUl li a:link {}
#calLoadingStatus img {display: block;width: 80px;margin: 10px auto;}
/* End of Post Navigator by MBT (LIGHT Theme) ------ */
#calendarDisplay ul#calendarUl {padding-bottom: 0;padding-left: 30px;padding-right: 0;padding-top: 0;}
#calendarDisplay #calendarUl li {display: list-item;list-style-image: none;list-style-position: outside;list-style-type: decimal;border-bottom-style: none;padding-bottom: 3px;padding-left: 0;padding-right: 10px;padding-top: 0;text-indent: 0;}
#calendarDisplay #calendarUl li a:link,#calendarDisplay #calendarUl li a:visited{font-size: 11px;}
.mbt-email{background:url(http://4.bp.blogspot.com/_MbejYjGokMM/TSeZHmWJ6oI/AAAAAAAAALE/93ELYyzmi64/s1600/email.png) no-repeat 0px 12px;width:235px;padding-left:52px;float:left;font-size:1em;font-weight:bold;margin:0 0 3px 7px;color:#444444;line-height:1.8em}
.mbt-emailsubmit{background:#9B9895;cursor:pointer;color:#fff;border:none;padding:0 4px 0 4px;text-shadow:0 -1px 1px rgba(0,0,0,0.25);-moz-border-radius:2px;-webkit-border-radius:2px;border-radius:2px;font:12px sans-serif;height:24px;font-weight:bold;}
.mbt-emailsubmit:hover{background:#E98313;}
.textarea{padding:2px 5px 2px 5px;margin:6px 0px 6px 2px;background:#f9f9f9;border:1px solid #ccc;resize:none;box-shadow:inset 1px 1px 1px rgba(0,0,0,0.1);-moz-box-shadow:inset 1px 1px 1px rgba(0,0,0,0.1);-webkit-box-shadow:inset 1px 1px 1px rgba(0,0,0,0.1); font-size:12px;width:158px;height:18px;color:#666;}
#support_author {color: #3B5998;display: block;font-size: 13px;font-weight: 600;line-height: 20px;margin-bottom: 0px;margin-left: auto;margin-right: auto;margin-top: 5px;max-width: 600px;padding: 5px 0px;text-align: center;width: 565px;}
#button-share{width:100%;overflow:hidden;text-align:center;padding:10px 0 20px}
#button-share span{position:relative;font-size:11px;color:#fff;margin:12px}
#button-share .share{background:#f9f9f9;position:relative;display:inline-block;float:none;height:40px;line-height:40px;overflow:hidden;width:150px;margin:0 auto;box-shadow:inset 0 0 5px rgba(0,0,0,0.1)}
#button-share .slide-share{z-index:2;display:inline-block;height:40px;line-height:40px;left:0;position:absolute;width:150px;margin:0 auto}
#button-share .slide-share p{font-family:'Racing Sans One';font-weight:400;color:#fff;font-size:18px;left:0;position:absolute;text-align:center;width:100%;margin:0 auto}
#button-share .share .slide-share{transition:all 0.4s ease-in-out}
#button-share .facebook .fb_iframe_widget{display:block;position:absolute;right:20px;top:0;z-index:1}
#button-share .twitter iframe{right:5px;top:10px;z-index:1;display:block;position:absolute}
#button-share .google #___plusone_0{width:90px!important;top:10px;right:10px;position:absolute;display:block;z-index:1}
#button-share .facebook .slide-share{background:#305891}
#button-share .twitter .slide-share{background:#2ca8d2}
#button-share .google .slide-share{background:#dd4b39}
#button-share .facebook:hover .slide-share,#button-share .twitter:hover .slide-share,#button-share .google:hover .slide-share{left:150px;opacity:0.6} | 1001ebooknet | css/1001ebook.css | CSS | asf20 | 31,954 |
//import drasys.or.nonlinear.*;
import gaiatools.numeric.function.Function;
/*
* Utility class for passing around functions
*
* implements the drasys "FunctionI" interface to enable Simpsons method
* outsource.
*/
public abstract class FunctionI extends Function {
public double value(double var) {
return 0;
}
}
| 0lism | trunk/java/Function_old.java | Java | gpl3 | 337 |
import java.util.StringTokenizer;
/**
* Adapted for heliosphere display
* this one for showing flux as a skymap
*/
public class HelioFluxViewer {
public static double AU = 1.49598* Math.pow(10,11); //meters
public HelioFluxViewer (String filename) {
file f = new file(filename);
//int num2 = 101;
double[] xArray = new double[60]; // x is theta
double[] yArray = new double[361]; // y is phi
// set up x and y axes for reading file
for (int i=0; i<xArray.length; i+=1) {
xArray[i]=(double)i+60.0;
}
for (int i=0; i<yArray.length; i+=1) {
yArray[i]=(double)i;
}
double[] zArray = new double[xArray.length*yArray.length];
for (int i=0; i<zArray.length; i++) zArray[i]=0.0;
f.initRead();
String line = ""; //f.readLine(); // garbage - header
int index = 0;
String garbage = "";
while ((line=f.readLine())!=null) {
double x=0;
double y=0;
double num=0;
StringTokenizer st = new StringTokenizer(line);
try {
garbage = st.nextToken();
x = Double.parseDouble(st.nextToken());
y = Double.parseDouble(st.nextToken());
//if (numS.equals("Infinity")) numS="0.001";
num = Double.parseDouble(st.nextToken());
//if (num==0.0) num = 0.001;
//num = num+1.0;
//num = Math.log(num);
}
catch (Exception e) {e.printStackTrace();}
zArray[index]=num;
//System.out.println(index + " " + zArray[index]);
index++;
}
System.out.println("index: " + index + " zArray.length: " + zArray.length);
// get min and max of zarray
double minz = 1000.0;
double maxz = 0.0;
for (int j=0; j<zArray.length; j++) {
if (zArray[j]>maxz) maxz=zArray[j];
if (zArray[j]<minz) minz=zArray[j];
}
System.out.println("minz: "+minz+" maxz: "+maxz);
/* int index = 0;
for (int i=0; i<x.length; i++) {
x[i]=(tpTimes[i]-GOODS)/24.0/60.0/60.0;
for (int j=0; j<y.length; j++) {
y[j]=tpHist[i].label[j];
if (tpHist[i].data[j]==0) z[index]=0.0;
else {
z[index]=tpHist[i].data[j];
//o("nonzero z: " + z[index]);
}
index++;
}
}*/
JColorGraph jcg = new JColorGraph(xArray,yArray,zArray,true);
jcg.fileName = filename;
String unitString = "Counts";
//if (histType == "Flux") unitString = "Diff. Flux (1/cm^2/s/sr/keV)";
//if (histType == "Distribution Function") unitString = "Dist. Function (s^3/km^6)";
//if (histType == "Log Distribution Function") unitString = "log Dist. Function (s^3/km^6)";
jcg.setLabels("Heliosphere Simulation","UniBern 2008",unitString);
jcg.run();
jcg.showIt();
}
public static final void main(String[] args) {
HelioFluxViewer m = new HelioFluxViewer (args[0]);
}
}
| 0lism | trunk/java/HelioFluxViewer.java | Java | gpl3 | 2,745 |
/**
* this routine calculates the distribution function (6D)
* however based on 5D inputs as there is symmetry about inflow axis
*
* NOTE: parameters of distribution must be given in coordinates
* relative to inflow direction for this routine
* Damby & Camm 1957, Mostly from Judge & Wu 1979
*
* Most of the math of the calcuation is in this method!
*
* r = dist. from sun
* theta = angle from inflow
*
*
*/
public double computeReferenceCoords(
double r, double theta, double vr, double vt, double vPsi) {
// we need to make sure that vt is within an appropriate range
// this amounts to assuming no non-hyperbolic trajectories
if (Math.abs(vt) < vtLimit(vr,r)) return 0;
else {
Q = Math.sqrt((1-mu)*G*Ms/r);
//System.out.println(""+(vr*vr+vt*vt-2*Q*Q));
V0 = Math.sqrt(vr*vr + vt*vt - 2*Q*Q);
//System.out.println("computed easy numbers "+Q+" "+V0);
F1 = 2*Vb*V0/(Vtemp*Vtemp) * Math.cos(theta)*(V0 - vr)*(V0 - vr)/(V0*(V0-vr)+Q*Q) -
((Vb*Vb)+(V0*V0)+2*V0*Vb*Math.cos(theta))/(Vtemp*Vtemp);
F2 = 2*V0*Vb*vt/(Vtemp*Vtemp) * Math.sin(theta)*(V0-vr)/ (vr*(V0-vr) + (Q*Q));
//System.out.println("computed F1 & F2 "+F1+" "+F2);
return sp.compute(r,theta,vr,vt)*
N * test1 * Math.exp(F1 + F2*Math.sin(vPsi));
}
}
/**
* This routine does the analytic integration over psi (V psi)
* using the appropriate modified Bessel funciton.
*
* This routine takes coordinates in the reference frame
* Useful for computing density quicker.
*/
public double computeReference2D(double r, double theta, double vr, double vt) {
if (Math.abs(vt) < vtLimit(vr,r)) return 0;
else {
Q = Math.sqrt((1-mu)*G*Ms/r);
V0 = Math.sqrt(vr*vr + vt*vt - 2*Q*Q);
F1 = 2*Vb*V0/(Vtemp*Vtemp) * Math.cos(theta)*(V0 - vr)*(V0 - vr) / (V0*(V0-vr)+Q*Q) -
((Vb*Vb)+(V0*V0)+2*V0*Vb*Math.cos(theta))/(Vtemp*Vtemp);
F2 = 2*V0*Vb/(Vtemp*Vtemp) * Math.sin(theta)*(V0-vr)*vt/ (V0*(V0-vr) + (Q*Q));
return sp.compute(r,theta,vr,vt) * N * test1 *
Math.exp(F1)*Bessel.i0(F2);
}
}
/**
* This tells what the limit on tangential velocity is, based on r and radial velocity
* (returns an absolute value that vt must be greater than)
*/
public double vtLimit(double vr, double r) {
double QQ = Math.sqrt((1-mu)*G*Ms/r);
double t211 = 0;
if ((t211 = 2*QQ*QQ - vr*vr)<0) return 0;
else return Math.sqrt(t211) + 0.01; // this is in m/s so we're OK with this factor
}
/**
* This takes parameters in spherical (heliospheric) coordinates
*
* Does appropriate transformation and calculates computeReferenceCoords(args)
*/
/*public double compute(double r, double theta, double phi,
double vmag, double vtheta, double vphi) {
hpr = new HelioVector(HelioVector.SPHERICAL, r, phi, theta);
hpv = new HelioVector(HelioVector.SPHERICAL, vmag, vphi, vtheta);
//hpin = new HelioVector(HelioVector.Spherical, 1, phi0, theta0); // length doesn't matter here
return computeReferenceCoords(r, hpr.angleToInflow(phi0,theta0),
hpv.cylCoordRad(hpr), hpv.cylCoordTan(hpr), hpv.cylCoordPhi(hpr,hpin));
}*/
/**
* This takes parameters in spherical (heliospheric) coordinates
*
* Does appropriate transformation and calculates computeRefernce2D()
*/
/*public double compute2D(double r, double theta, double phi,
double vmag, double vtheta) {
hpr = new HelioVector(HelioVector.SPHERICAL, r, phi, theta);
hpv = new HelioVector(HelioVector.SPHERICAL, vmag, 0, vtheta);
//hpin = new HelioVector(HelioVector.Spherical, 1, phi0, theta0); // length doesn't matter here
return computeReference2D(r, hpr.angleToInflow(phi0,theta0),
hpv.cylCoordRad(hpr), hpv.cylCoordTan(hpr));
}*/
/**
* This takes coords in a more general frame, as in compute() above
* Returns a 3D function in velocity space, with args. vr, vtheta, vphi
*
*/
public FunctionIII getVelocityDistribution(final double r, final double theta, final double phi) {
return new FunctionIII () {
public double function3(double x, double y, double z) {
return dist(r,theta,phi,x,y,z);
}
};
}
/**
* This takes coords in a more general frame, as in compute() above
* Returns a 2D function in velocity space, with args. vr, vtheta
* (we have analytically integrated the Vpsi coordinate over all angles)
*/
public FunctionII get2DVelocityDistribution(final double r, final double theta, final double phi) {
return new FunctionII () {
public double function2(double x, double y) {
return computeReference2D(r,theta,x,y);
}
};
}
/**
* This takes coords relative to inflow, as in computeRefernceCoords above
* Returns a 3D function in velocity space, with args. vr, vtheta, vphi
*
*/
public FunctionIII getReferenceVelocityDistribution(final double r, final double theta) {
return new FunctionIII () {
public double function3(double x, double y, double z) {
return computeReferenceCoords(r,theta,x,y,z);
}
};
}
/**
* This takes coords in the reference frame.
* Returns a 2D function in velocity space, with args. vr, vtheta.
* The function returned is the analytic integration of all psi (Vpsi)
*/
public FunctionII get2DReferenceVelocityDistribution(final double r, final double theta) {
return new FunctionII () {
public double function2(double x, double y) {
return computeReference2D(r,theta,x,y);
}
};
}
/**
* This returns the density at a point in the heliosphere by doing
* a numerical 3D integration in all velocity space
* See MultipleIntegration.java for details
* (default is at .001 accuracy)
*/
public double density(double r, double theta, double phi) {
MultipleIntegration mi = new MultipleIntegration();
// old fashioned way
double [] lims = new double[6];
lims[0]=-3*Math.pow(10,5);
lims[1]=3*Math.pow(10,5); // m/s
lims[2]=-3*Math.pow(10,5);
lims[3]=3*Math.pow(10,5);
lims[4]=-3*Math.pow(10,5);
lims[5]=3*Math.pow(10,5);
// do the integral over + and then - velocity space to avoid the zero
/*double [] lims = new double[6];
lims[0]=-3*Math.pow(10,5);
lims[1]=0; // m/s
lims[2]=-3*Math.pow(10,5);
lims[3]=0;
lims[4]=-3*Math.pow(10,5);
lims[5]=0;
double [] lims2 = new double[6];
lims2[0]=0;
lims2[1]=3*Math.pow(10,5);
lims2[2]=0;
lims2[3]=3*Math.pow(10,5);
lims2[4]=0;
lims2[5]=3*Math.pow(10,5);*/
return mi.integrate(getVelocityDistribution(r,theta, phi) , lims);
// + mi.integrate(getVelocityDistribution(r,theta, phi) ,lims2);
// the integration routine will give us stats on the operation.
}
/**
* This returns the density at a point in the heliosphere by doing
* a numerical 2D integration, plus the
* analytic integratoin of the PSI coordinate with modified bessel function
* See MultipleIntegration.java for details
* (default is at .001 accuracy)
*/
public double density2D (double r, double theta, double phi) {
MultipleIntegration mi = new MultipleIntegration();
double [] lims = new double[4];
lims[0]=-3*Math.pow(10,7);
lims[1]=3*Math.pow(10,7);
lims[2]=-3*Math.pow(10,7);
lims[3]=3*Math.pow(10,7);
return mi.integrate(get2DReferenceVelocityDistribution(r,theta),lims);
// the integration routine will give us stats on the operation.
}
| 0lism | trunk/java/oldNeutralDistribution.java | Java | gpl3 | 7,546 |
/**
* A "hot" neutral helium model of the LISM
* (gaussian)
*/
public class SimpleHeLISM extends InterstellarMedium {
public static double K = 1.380622 * Math.pow(10,-23); //1.380622E-23 kg/m/s/s/K
public static double Mhe = 4*1.6726231 * Math.pow(10,-27); // 4 * 1.6726231 x 10-24 gm
private double temp, vb, n, vtemp, d;
private double phi0, theta0; // direction of bulk flow - used when converting to GSE
private double norm;
private double factor;
/**
* Default parameters for default constructor
*
*/
public SimpleHeLISM() {
this(28000.0, 0.0, 0.0, 2000.0, 1.5E-7);
}
/**
* Construct an interstellar neutral helium gaussian distribution
*parameters:
* bulk velocity of VLISM
* phi0, phi angle of bulk inflow
* theta0, theta angle of bulk inflow
* temperature, T(VLISM)
* density (VLISM)
* radiationToGravityRation (mu)
* ionization at 1AU (beta0)
*/
public SimpleHeLISM (double bulkVelocity, double phi0, double theta0,
double temperature, double density) {
vb = bulkVelocity;
this.phi0 = phi0;
this.theta0 = theta0;
temp = temperature;
d = density;
factor = -Mhe/2/K/temp;
//average velocity due to heat
vtemp = Math.sqrt(-1/factor);
// don't want to compute this every time...
norm = d*Math.pow(vtemp*Math.sqrt(Math.PI),-3);
/*
// DEBUG HERE
file f = new file("test_dist.txt");
f.initWrite(false);
double minRange = -100000;
double maxRange = 100000;
int steps = 100;
double delta = (maxRange-minRange)/steps;
for (int i=0; i<steps; i++) {
f.write((minRange+i*delta)+"\t"+heliumDist((minRange+i*delta),0,0)+"\t");
f.write(heliumDist(0,(minRange+i*delta),0)+"\t");
f.write(heliumDist(0,0,(minRange+i*delta))+"\n");
}
f.closeWrite();
*/
}
/**
* Returns the phase space density of neutral helium at this velocity
*/
public double heliumDist(double vx, double vy, double vz) {
double r = Math.sqrt((vx-vb)*(vx-vb) + vy*vy + vz*vz);
return norm*Math.exp(factor*r*r);
}
/**
* For testing
*/
public static final void main(String[] args) {
SimpleHeLISM shl = new SimpleHeLISM(27000,0,0,8000,1);
}
}
/*
double temp = 2000;
double density = 1;
double vbulk = 27000;
double norm = Math.sqrt((4*MP/2/PI/KB/temp)*(4*MP/2/PI/KB/temp)*(4*MP/2/PI/KB/temp));
return norm*Math.exp(-4*MP*((v1-vbulk)*(v1-vbulk)+v2*v2+v3*v3)/2/KB/temp);
*/
| 0lism | trunk/java/SimpleHeLISM.java | Java | gpl3 | 2,481 |
//import drasys.or.nonlinear.*;
//import gaiatools.numeric.function.Function;
import flanagan.integration.*;
/*
* Utility class for passing around functions
*
* implements the drasys "FunctionI" interface to enable Simpsons method
* outsource.
*/
public abstract class FunctionI extends Function implements IntegralFunction{
public double function(double x) {
return 0;
}
public double value(double var) {
return function(var);
}
public String toString() {
return "a string";
}
public double ddif(int x, double y) {
return 0.0;
}
public double value(double[] x) {
return 0.0;
}
}
| 0lism | trunk/java/FunctionI.java | Java | gpl3 | 635 |
/**
*
* Use this to calculate the v dist. of int. helium using
* the assumption of isotropic adiabatic cooling
*
*/
public class SemiModel {
public double AU = 1.49598* Math.pow(10,11); //meters
public double NaN = Double.NaN;
public double MAX = Double.MAX_VALUE;
public double U = 440*1000;
public double N0 = Math.pow(10,-6);
public double GAMMA = 3.0/2.0; // energy dependence in eflux ?? - inverse gamma in derivation..
static double beta = 3*Math.pow(10,-8);
static double PI = Math.PI;
public Legendre l;
public int degree = 20;
public double mu_i = 1.0;
public double D = 0.00001;
public double VSW = 400000.0;
public static double v_infinity = 27500.0; //m/s
public static double G = 6.673 * Math.pow(10,-11); // m^3/s^2/kg
public static double Ms = 1.98892 * Math.pow(10,30); // kg
public MultipleIntegration mi;
public double instr_normalization;
public int counter=0;
public SemiModel() {
//mu_i = 0.985; // cos(10 degrees)
//retry with perp
mu_i = 0.1;
l = new Legendre();
mi = new MultipleIntegration();
//for (double v = 0; v<VSW*1.1; v+= VSW/100) {
// System.out.println("v: "+ v + " f: "+ f(v));
//}
FunctionI integrand = new FunctionI () {
public double function(double mu) {
return instr_function(mu);
}
};
instr_normalization = mi.integrate(integrand, -1, 1, 1000);
System.out.println("norm: " + instr_normalization);
System.out.println("predict: " + Math.sqrt(1.0/2.0/Math.PI/13.2/Math.PI*180.0));
}
public double f(double v, double mu) {
//D = d;
//GAMMA = gamma;
double tbr=0.0;
for (int i=0; i<degree; i++) {
tbr += Math.pow(v/VSW,1-GAMMA)*(2.0*i+1)/2.0*l.p(i,mu_i)*l.p(i,mu)*Math.exp(-i*(i+1.0)*D*AU/VSW*(1.0-Math.pow(v/VSW,GAMMA)));
}
tbr*=N(AU*Math.pow(v/VSW,GAMMA));
tbr*=(instr_function(Math.acos(mu))+instr_normalization)/2;
return tbr;
}
/**
* now including instrument function - april 06 - from Aelig thesis
*
*/
public double f(double v) {
final double v_ = v;
FunctionI integrand = new FunctionI () {
public double function(double mu) {
return f(v_,mu);
}
};
double integral = mi.integrate(integrand, -1.0, -0.866, 1000);
return integral;
}
public double f(double norm, double dd, double gamm, double v) {
counter++;
D = dd;
GAMMA = gamm;
return norm*v*f(v*VSW);
}
public double f(double norm, double dd, double v) {
counter++;
D=dd;
return norm*v*f(v*VSW);
}
/**
* From Aelig thesis.. angular calibration..
*/
public double instr_function(double mu) {
double sigma = 13.2*Math.PI/180.0;
double factorAlph = Math.exp(-mu*mu/2.0/sigma/sigma);
return factorAlph; //(factorAlph+1.0d)/2.0d;
}
/**
* The model of interstellar neutral density..
*
* based on cold model, due upwind..
* see Moebius SW&CR homework set #4!
*/
private double N(double r) {
return N0*Math.exp(-beta*AU*AU*Math.sqrt(v_infinity*v_infinity+2.0*G*Ms/r)/G/Ms);
//return N0*Math.exp(-2*beta*AU*AU/r/v_infinity);
}
public static final void main(String[] args) {
SemiModel sm = new SemiModel();
double[] test = new double[20];
double[] test1 = new double[20];
double[] test2 = new double[20];
double[] test3 = new double[20];
double[] test4 = new double[20];
double[] test5 = new double[20];
double[] test6 = new double[20];
double[] dd = {0.0,0.0,0.0,0.0,0.0,0.0}; //4.38e-6,4.6e-6,4.0e-6,3.1e-6,2.6e-6,1.9e-6};
double ddtemp = 4.0e-6;
double[] nn = {1.0,1.0,1.0,1.0,1.0,1.0}; //3.01e12,2.1e11,2.2e11,2.6e11,3.2e11,5.5e11};
double nntemp = 2e11;
double[] gamma = {0.8d, 1.0d, 1.3d, 1.4d, 1.5d, 2.0d};
file f = new file("semi_out_test.dat");
f.initWrite(false);
int index = 0;
for (double w=0.0; w<=1.0; w+=0.02) {
index=0;
f.write(w+"\t");
while (index<6) {
f.write(sm.f(nn[index],dd[index],gamma[index],w)+"\t");
index++;
}
f.write("\n");
}
f.closeWrite();
}
}
| 0lism | trunk/java/SemiModel.java | Java | gpl3 | 4,045 |
import java.util.StringTokenizer;
/**
* Adapted for heliosphere display
*
*/
public class MCAJ_image {
public static double AU = 1.49598* Math.pow(10,11); //meters
public MCAJ_image(String filename) {
file f = new file(filename);
int num2 = 101;
double[] xArray = new double[num2];
double[] yArray = new double[num2];
int in = 0;
for (double pos = -5.0; pos<5.0; pos+=10.0/((double)num2)) {
xArray[in]=pos;
yArray[in]=pos;
in++;
System.out.println("pos: " + pos + " next in: " + in);
}
double[] zArray = new double[num2*num2];
for (int i=0; i<zArray.length; i++) zArray[i]=0;
f.initRead();
String line = f.readLine(); // garbage - header
int index = 0;
while ((line=f.readLine())!=null) {
double x=0;
double y=0;
double num=0;
StringTokenizer st = new StringTokenizer(line);
try {
x = Double.parseDouble(st.nextToken());
y = Double.parseDouble(st.nextToken());
String numS = st.nextToken();
//if (numS.equals("Infinity")) numS="0.001";
num = Double.parseDouble(numS);
if (num==0.0) num = 0.001;
//num = num+1.0;
//num = Math.log(num);
}
catch (Exception e) {e.printStackTrace();}
zArray[index]=num;
index++;
}
System.out.println("index: " + index + " zArray.length: " + zArray.length);
// get min and max of zarray
double minz = 1000.0;
double maxz = 0.0;
for (int j=0; j<zArray.length; j++) {
if (zArray[j]>maxz) maxz=zArray[j];
if (zArray[j]<minz) minz=zArray[j];
}
System.out.println("minz: "+minz+" maxz: "+maxz);
/* int index = 0;
for (int i=0; i<x.length; i++) {
x[i]=(tpTimes[i]-GOODS)/24.0/60.0/60.0;
for (int j=0; j<y.length; j++) {
y[j]=tpHist[i].label[j];
if (tpHist[i].data[j]==0) z[index]=0.0;
else {
z[index]=tpHist[i].data[j];
//o("nonzero z: " + z[index]);
}
index++;
}
}*/
JColorGraph jcg = new JColorGraph(xArray,yArray,zArray,true);
String unitString = "Density";
//if (histType == "Flux") unitString = "Diff. Flux (1/cm^2/s/sr/keV)";
//if (histType == "Distribution Function") unitString = "Dist. Function (s^3/km^6)";
//if (histType == "Log Distribution Function") unitString = "log Dist. Function (s^3/km^6)";
jcg.setLabels("Heliosphere Simulation","UniBern 2008",unitString);
jcg.run();
jcg.showIt();
}
public static final void main(String[] args) {
MCAJ_image m = new MCAJ_image(args[0]);
}
}
| 0lism | trunk/java/MCAJ_image.java | Java | gpl3 | 2,518 |
import java.util.Date;
import java.lang.Math;
public class NTest {
public static void main(String[] args) {
Date d1 = new Date();
//NeutralDistribution nd = new NeutralDistribution( 12, 123, 142);
double AU = 15 * 10^13; // m
SimpleNeutralDistribution snd = new SimpleNeutralDistribution(
25000, 0, 0, 10000, 7*Math.pow(10,-6), 0, 6.8*Math.pow(10,-8));
double q = snd.N(AU, 135*Math.PI/180, 25000);
System.out.println(q+"");
/*double[] array;
array = new double[100000];
for (int i = 1; i<100000; i++) {
array[i] = i;
// double test = nd.distributionFunction(123123, .21, 100+i, 421, .13);
}*/
Date d2 = new Date();
System.out.println(d2.getTime() - d1.getTime()+"");
}
}
| 0lism | trunk/java/NTest.java | Java | gpl3 | 752 |
import SimpleInput;
import SimpleOutput;
public class primeSieve {
// This program implements the Sieve of Eratosthenes
public static void main (String args []) {
// declare basic objects
SimpleInput in = new SimpleInput();
SimpleOutput out = new SimpleOutput();
int M; // size of sieve
int i, number; // indices
// Determine size of sieve
out.println ("Use of the Sieve of Eratosthenes to compute primes");
out.println ("Enter how large an integer to process: ");
M = in.readInt();
// set up sieve
boolean [] crossedOut = new boolean [M+1];
// use size M+1 for elemens 0 through M
for (i = 0; i<= M; i++) // i++ is an abbreviation for i = i + 1
crossedOut[i] = false;
// follow cross-out process
for (number = 2; number < M; number++)
{if (!crossedOut[number])
{ // cross out multiples of number
i = 2*number;
while (i <= M)
{ crossedOut[i] = true;
i = i + number;
}
}
}
// print list of primes
out.println ("The following prime numbers have been found");
int numberOnLine = 0;
for (i = 2; i <= M; i++)
{if (!crossedOut[i])
{
out.print(i + "\t"); // add tab after each number
numberOnLine++;
if (numberOnLine == 8)
{
out.println(); // start a new line every 8 numbers
numberOnLine = 0;
}
}
}
out.println();
}
}
| 0lism | trunk/java/primeSieve.java | Java | gpl3 | 1,642 |
import java.util.Date;
import java.util.Random;
public class MCThread extends Thread {
public boolean finished = false;
private double[] limits;
private int np;
private final FunctionIII f;
public double tbr;
private Random r;
private double w1,w2,w3;
public MCThread(FunctionIII funk, double[] lims, int num) {
limits = lims;
w1 = limits[1]-limits[0];
w2 = limits[3]-limits[2];
w3 = limits[5]-limits[4];
np = num;
f = funk; // do you feel it
tbr = 0;
r = new Random();
}
/**
* Just call the function a certain number of times and add the results together
* this is the dartboard
*/
public void run() {
tbr = 0.0;
double xpoint,ypoint,zpoint;
// System.out.println("widths: " + w1 + " " + w2 + " " + w3);
for (int i=0; i<np; i++) {
// select random point
xpoint = r.nextDouble()*w1 + limits[0];
ypoint = r.nextDouble()*w2 + limits[2];
zpoint = r.nextDouble()*w3 + limits[4];
tbr += f.function3(xpoint,ypoint,zpoint);
}
finished = true;
}
/**
* For testing - use GVLISM
*/
public static final void main(String[] args) {
MultipleIntegration mi = new MultipleIntegration();
final GaussianVLISM gvli = new GaussianVLISM(new HelioVector(HelioVector.CARTESIAN,
-27000.0,0.0,0.0), 100.0, 6000.0);
System.out.println("Created GVLISM" );
FunctionIII distZw = new FunctionIII () {
public double function3(double r, double p, double t) {
HelioVector hv = new HelioVector(HelioVector.SPHERICAL,r,p,t);
return gvli.heliumDist(hv)*r*r*Math.sin(t);
}
};
double[] limitsZw = {0.0,100000.0,0.0,2*Math.PI,0,Math.PI};
Date d1 = new Date();
double ans = mi.mcIntegrate(distZw, limitsZw,5000000);
Date d2 = new Date();
o("5000000 answer: " + ans + " Time: " + (d2.getTime() - d1.getTime()));
d1 = new Date();
ans = mi.mcIntegrate(distZw, limitsZw,5000000,1);
d2 = new Date();
o("5000000,1 answer: " + ans + " Time: " + (d2.getTime() - d1.getTime()));
d1 = new Date();
ans = mi.mcIntegrate(distZw, limitsZw,5000000,2);
d2 = new Date();
o("5000000,2 answer: " + ans + " Time: " + (d2.getTime() - d1.getTime()));
d1 = new Date();
ans = mi.mcIntegrate(distZw, limitsZw,5000000,3);
d2 = new Date();
o("5000000,3 answer: " + ans + " Time: " + (d2.getTime() - d1.getTime()));
System.out.println("answer in spherical coords = " + ans );
}
public static void o(String s) {
System.out.println(s);
}
} | 0lism | trunk/java/MCThread.java | Java | gpl3 | 2,508 |
import java.util.StringTokenizer;
public class IbexFitter {
public CurveFitter cf;
public IBEXLO_09fit ifit;
public IbexFitter() {
file f = new file("first_pass.txt");
int numLines = 926;
numLines=numLines/3;
f.initRead();
double[] x = new double[numLines];
double[] y = new double[numLines];
String line = "";
for (int i=0; i<numLines; i++) {
line = f.readLine();
StringTokenizer st = new StringTokenizer(line);
x[i]=Double.parseDouble(st.nextToken());
//x[i]-=1.0; // IMPORTANT _ SHIFT BY 1.0 TO MOVE TO HELIOCENTRIC FRAME!!
y[i]=Double.parseDouble(st.nextToken());
//System.out.println("row: " + i + " x: " + x[i] + " y: " + y[i]);
line = f.readLine();
line = f.readLine();
}
f.closeRead();
// loop through parameters here
// standard params:
double lamda = 74.7;
double v = 26000.0;
int res = 2;
double lamdaWidth = 15;
double vWidth = 10000;
double lamdaMin = 65.0;
double vMin=21000.0;
double lamdaDelta = lamdaWidth/res;
double vDelta = vWidth/res;
lamda = lamdaMin;
v = vMin;
file outF = new file("testOut.txt");
outF.initWrite(false);
for (int i=0; i<res; i++) {
for (int j=0; j<res; j++) {
System.out.println("starting doFit routine with i=" + i + " j= " + j);
cf = new CurveFitter(x,y,lamda,v);
cf.doFit(CurveFitter.IBEX1);
outF.write(lamda+"\t"+v+"\t");
outF.write(cf.minimum_pub+"\t");
outF.write(cf.bestParams[0]+"\n");
// get values of y and z at minimum
//double[] param = min.getParamValues();
//bestParams = param;
v+=vDelta;
}
lamda+=lamdaDelta;
}
outF.closeWrite();
}
public static final void main(String[] args) {
IbexFitter theMain = new IbexFitter();
}
} | 0lism | trunk/java/IbexFitter.java | Java | gpl3 | 1,816 |
import java.util.StringTokenizer;
public class TwoDPlot {
public CurveFitter cf;
public TwoDPlot() {
file f = new file("second_pass_ascii.txt");
f.initRead();
double[] x = new double[30];
double[] y = new double[30];
double[] z = new double[900];
for (int i=0; i<x.length; i++) x[i]=Double.parseDouble(f.readLine());
for (int i=0; i<y.length; i++) y[i]=Double.parseDouble(f.readLine());
for (int i=0; i<z.length; i++) z[i]=Double.parseDouble(f.readLine());
JColorGraph jcg = new JColorGraph(x,y,z);
String unitString = "log (sum square model error)";
jcg.setLabels("IBEX-LO","2010",unitString);
jcg.run();
jcg.showIt();
}
public static boolean contains(double[] set, double test) {
for (int i=0; i<set.length; i++) {
if (set[i]==test) return true;
}
return false;
}
public static void o(String s) {
System.out.println(s);
}
public static final void main(String[] args) {
TwoDPlot theMain = new TwoDPlot();
}
} | 0lism | trunk/java/2DPlot.java | Java | gpl3 | 1,026 |
import java.util.StringTokenizer;
/**
* Simulating response at IBEX_LO with this class
*
* Create interstellar medium and perform integration
*
*/
public class IBEXLO_09fit {
public int mcN = 100000; // number of iterations per 3D integral
public String outFileName = "lo_fit_09.txt";
public static final double EV = 1.60218 * Math.pow(10, -19);
public static double MP = 1.672621*Math.pow(10.0,-27.0);
public static double AU = 1.49598* Math.pow(10,11); //meters
public static double EARTHSPEED = AU*2.0*3.14/365.0/24.0/3600.0;
// define angles and energies of the instrument here
// H mode (standard) energy bins in eV
public double[] minEnergies = {8.8, 17.6, 35.8, 74.2, 153.5, 330.6, 663.3, 1298.6};
public double[] maxEnergies = {23.2, 46.4, 94.3, 195.8, 404.6, 871.5, 1748.7, 3423.5};
public double[] minSpeedsHe, maxSpeedsHe, minSpeedsO, maxSpeedsO;
// Interstellar mode energies
// { spring min, spring max, fall min, fall max }
public double[] heEnergies = { 73.7, 194.3, 4.4, 11.6 };
public double[] oEnergies = {293.7, 774.3, 18.15, 47.9 };
public double[] heSpeeds;
public double[] oSpeeds;
// O mode efficiencies
// public double heSpringEff = 1.0*Math.pow(10,-7); // this was the original.. now going to adjust to match data including sputtering etc.
public double heSpringEff = 1.0*Math.pow(10,-7)/7.8; // nominal efficiency to "roughly" match data..
public double heFallEff = 1.6*Math.pow(10,-6);
public double oSpringEff = 0.004;
public double oFallEff = 0.001;
// angular acceptance - assume rectangular windows..
// these are half widths, e.g. +- for acceptance
public double spinWidth = 4.0*Math.PI/180.0;
public double hrWidth = 3.5*Math.PI/180.0;
public double lrWidth = 10.0*Math.PI/180.0;
public double eightDays = 8.0*24.0*60.0*60.0;
public double oneHour = 3600.0;
public double upWind = 74.0 * 3.14 / 180.0;
public double downWind = 254.0 * 3.14 / 180.0;
public double startPerp = 180*3.14/180; // SPRING
public double endPerp = 240*3.14/180; // SPRING
//public double startPerp = 260.0*3.14/180.0; // FALL
//public double endPerp = 340.0*3.14/180.0; // FALL
public double he_ion_rate = 6.00*Math.pow(10,-8);
public GaussianVLISM gv1;
// temporarily make them very small
//public double spinWidth = 0.5*Math.PI/180.0;
//public double hrWidth = 0.5*Math.PI/180.0;
//public double lrWidth = 0.5*Math.PI/180.0;
public double activeArea = 100.0/100.0/100.0; // 100 cm^2 in square meters now!!
public file outF;
public MultipleIntegration mi;
public NeutralDistribution ndHe;
public double look_offset=Math.PI;
public double currentLongitude, currentSpeed, currentDens, currentTemp;
public HelioVector bulkHE;
/**
*
*
*
*/
public IBEXLO_09fit() {
// calculate speed ranges with v = sqrt(2E/m)
heSpeeds = new double[heEnergies.length];
oSpeeds = new double[oEnergies.length];
o("calculating speed range");
for (int i=0; i<4; i++) {
heSpeeds[i]=Math.sqrt(2.0*heEnergies[i]/4.0/MP*EV);
oSpeeds[i]=Math.sqrt(2.0*oEnergies[i]/16.0/MP*EV);
System.out.println(heEnergies[i] +" = " + heSpeeds[i] + " , " + oEnergies[i] + " = " + oSpeeds[i]);
}
minSpeedsHe = new double[8];
maxSpeedsHe = new double[8];
minSpeedsO = new double[8];
maxSpeedsO = new double[8];
for (int i=0; i<8; i++) {
minSpeedsHe[i]=Math.sqrt(2.0*minEnergies[i]/4.0/MP*EV);
maxSpeedsHe[i]=Math.sqrt(2.0*maxEnergies[i]/4.0/MP*EV);
minSpeedsO[i]=Math.sqrt(2.0*minEnergies[i]/16.0/MP*EV);
maxSpeedsO[i]=Math.sqrt(2.0*maxEnergies[i]/16.0/MP*EV);
System.out.println(minSpeedsHe[i] +" = " + maxSpeedsHe[i] + " , " + minSpeedsO[i] + " = " + maxSpeedsO[i]);
}
System.out.println(minSpeedsHe[0] + "\t" + maxSpeedsHe[0] +"\t" + heSpeeds[2] + "\t" + heSpeeds[3]);
// BUILD INTERSTERLLAR MEDIUM - helium and oxygen here, primary and secondary oxygen..
//
bulkHE = new HelioVector(HelioVector.SPHERICAL, 26000.0, (74.68)*Math.PI/180.0, 95.5*Math.PI/180.0);
//HelioVector bulkO1 = new HelioVector(HelioVector.SPHERICAL,26000.0, (74+180)*Math.PI/180.0, 95.5*Math.PI/180);
GaussianVLISM gv1 = new GaussianVLISM(bulkHE,0.015*100.0*100.0*100.0,6000.0);
//KappaVLISM gv3 = new KappaVLISM(bulkO1, 0.00005*100*100*100, 6300, 1.6);
ndHe = new NeutralDistribution(gv1, 0.0, he_ion_rate); // mu is 0.0 for he
ndHe.debug=false;
currentLongitude = 74.68;
currentSpeed = 26000.0;
currentDens = 0.015;
currentTemp = 6000.0;
// DONE CREATING MEDIUM
o("earthspeed: " + EARTHSPEED);
mi = new MultipleIntegration();
o("done creating IBEXLO_09 object");
// DONE SETUP
//-
//-
// now lets run the test, see how this is doing
/*
// moving curve fitting routine here for exhaustive and to make scan plots
file ouf = new file("scanResults1.txt");
file f = new file("cleaned_ibex_data.txt");
int numLines = 413;
f.initRead();
double[] x = new double[numLines];
double[] y = new double[numLines];
String line = "";
for (int i=0; i<numLines; i++) {
line = f.readLine();
StringTokenizer st = new StringTokenizer(line);
x[i]=Double.parseDouble(st.nextToken());
//x[i]-=1.0; // IMPORTANT _ SHIFT BY 1.0 TO MOVE TO HELIOCENTRIC FRAME!!
y[i]=Double.parseDouble(st.nextToken());
//System.out.println("row: " + i + " x: " + x[i] + " y: " + y[i]);
}
f.closeRead();
// first scan: V vs Long.
// for (int i=0; i<
*/
// LOAD THE REAL DATA
/* file df = new file("second_pass.txt");
int numLines2 = 918;
df.initRead();
double[] xD = new double[numLines2];
double[] yD = new double[numLines2];
String line = "";
for (int i=0; i<numLines2; i++) {
line = df.readLine();
StringTokenizer st = new StringTokenizer(line);
xD[i]=Double.parseDouble(st.nextToken());
//x[i]-=1.0; // IMPORTANT _ SHIFT BY 1.0 TO MOVE TO HELIOCENTRIC FRAME!!
yD[i]=Double.parseDouble(st.nextToken());
System.out.println("row: " + i + " x: " + xD[i] + " y: " + yD[i]);
//line = f.readLine();
//line = f.readLine();
}
df.closeRead();
// END LOADING REAL DATA
*/
// MAKE SPIN PHASE SIMULATION
file spFile = new file("spin_phase_sim.txt");
spFile.initWrite();
for (int tt = 0; tt<360; tt++) {
// tt is the theta angle
double ans = getRate(40.0, tt*Math.PI/360.0);
spFile. write(tt+"\t"+ans+"\n");
}
spFile.closeWrite();
/*
// MAKE SIMULATION FROM REAL DATA.. STEP WITH TIME AND PARAMS FOR MAKING 2D PARAM PLOT
// loop through parameters here
// standard params:
double lamda = 74.7;
//double temp = 6000.0;
double v = 26000.0;
int res = 30;
double lamdaWidth = 20;
//double tWidth = 10000;
double vWidth = 10000;
double lamdaMin = 65.0;
//double tMin = 1000.0;
double vMin=21000.0;
double lamdaDelta = lamdaWidth/res;
//double tDelta = tWidth/res;
double vDelta = vWidth/res;
lamda = lamdaMin;
//temp=tMin;
v = vMin;
//file outF = new file("testVL_pass2_Out.txt");
//outF.initWrite(false);
for (int i=0; i<res; i++) {
v=vMin;
for (int j=0; j<res; j++) {
file outf = new file("fitP2_vl"+lamda+"_"+v+".txt");
outf.initWrite(false);
setParams(lamda,v,0.015,6000.0);
System.out.println(" now calc for: fitTTT_"+lamda+"_"+v+".txt");
double [] doyD = new double[110];
double [] rateD = new double[110];
in doyIndex = 0;
for (double doy=10.0 ; doy<65.0 ; doy+=0.5) {
outf.write(doy+"\t");
doyD[doyIndex]=doy;
doyIndex++;
//for (double off = 0.0 ; off<=3.0*Math.PI/2.0; off+=Math.PI/2.0) {
//look_offset=off;
look_offset=3.0*Math.PI/2.0;
double rr = getRate(doy);
System.out.println("trying: " + doy + " got "+rr);
outf.write(rr +"\t");
//}
//double rr = getRate(doy);
//System.out.println("trying: " + doy + " got "+rr);
outf.write("\n");
}
outf.closeWrite();
v+=vDelta;
}
//temp+=tDelta;
lamda+=lamdaDelta;
}
//outF.closeWrite();
*/
/*
for (int temptemp = 1000; temptemp<20000; temptemp+=2000) {
file outf = new file("fitB_"+temptemp+"_7468_26000.txt");
outf.initWrite(false);
setParams(74.68,26000,0.015,(double)temptemp);
for (double doy=10.0 ; doy<65.0 ; doy+=0.1) {
outf.write(doy+"\t");
//for (double off = 0.0 ; off<=3.0*Math.PI/2.0; off+=Math.PI/2.0) {
//look_offset=off;
look_offset=3.0*Math.PI/2.0;
double rr = getRate(doy);
System.out.println("trying: " + doy + " got "+rr);
outf.write(rr +"\t");
//}
//double rr = getRate(doy);
//System.out.println("trying: " + doy + " got "+rr);
outf.write("\n");
}
outf.closeWrite();
}
*/
}
// END CONSTRUCTOR
public void setParams(double longitude, double speed, double dens, double temp) {
currentLongitude = longitude;
currentSpeed = speed;
currentDens = dens;
currentTemp = temp;
// BUILD INTERSTERLLAR MEDIUM - helium and oxygen here, primary and secondary oxygen..
//
bulkHE = new HelioVector(HelioVector.SPHERICAL, speed, longitude*Math.PI/180.0, 95.5*Math.PI/180.0);
//HelioVector bulkO1 = new HelioVector(HelioVector.SPHERICAL,26000.0, (74+180)*Math.PI/180.0, 95.5*Math.PI/180);
GaussianVLISM gv1 = new GaussianVLISM(bulkHE,dens*100.0*100.0*100.0,temp);
//KappaVLISM gv3 = new KappaVLISM(bulkO1, 0.00005*100*100*100, 6300, 1.6);
ndHe = new NeutralDistribution(gv1, 0.0, he_ion_rate); // mu is 0.0 for he
ndHe.debug=false;
// DONE CREATING MEDIUM
}
public void setParams(double dens) {
currentDens = dens;
// BUILD INTERSTERLLAR MEDIUM - helium and oxygen here, primary and secondary oxygen..
//
//HelioVector bulkHE = new HelioVector(HelioVector.SPHERICAL, currentSpeed, currentLongitude*Math.PI/180.0, 95.5*Math.PI/180.0);
//HelioVector bulkO1 = new HelioVector(HelioVector.SPHERICAL,26000.0, (74+180)*Math.PI/180.0, 95.5*Math.PI/180);
GaussianVLISM gv1 = new GaussianVLISM(bulkHE,dens*100.0*100.0*100.0,currentTemp);
//KappaVLISM gv3 = new KappaVLISM(bulkO1, 0.00005*100*100*100, 6300, 1.6);
ndHe = new NeutralDistribution(gv1, 0.0, he_ion_rate); // mu is 0.0 for he
ndHe.debug=false;
// DONE CREATING MEDIUM
}
public void setParams(double dens, double temp) {
currentDens = dens;
currentTemp = temp;
// BUILD INTERSTERLLAR MEDIUM - helium and oxygen here, primary and secondary oxygen..
//
//HelioVector bulkHE = new HelioVector(HelioVector.SPHERICAL, currentSpeed, currentLongitude*Math.PI/180.0, 95.5*Math.PI/180.0);
//HelioVector bulkO1 = new HelioVector(HelioVector.SPHERICAL,26000.0, (74+180)*Math.PI/180.0, 95.5*Math.PI/180);
GaussianVLISM gv1 = new GaussianVLISM(bulkHE,dens*100.0*100.0*100.0,temp);
//KappaVLISM gv3 = new KappaVLISM(bulkO1, 0.00005*100*100*100, 6300, 1.6);
ndHe = new NeutralDistribution(gv1, 0.0, he_ion_rate); // mu is 0.0 for he
ndHe.debug=false;
// DONE CREATING MEDIUM
}
public void setParamsN(double dens, double ion) {
currentDens = dens;
currentTemp = temp;
// BUILD INTERSTERLLAR MEDIUM - helium and oxygen here, primary and secondary oxygen..
//
//HelioVector bulkHE = new HelioVector(HelioVector.SPHERICAL, currentSpeed, currentLongitude*Math.PI/180.0, 95.5*Math.PI/180.0);
//HelioVector bulkO1 = new HelioVector(HelioVector.SPHERICAL,26000.0, (74+180)*Math.PI/180.0, 95.5*Math.PI/180);
GaussianVLISM gv1 = new GaussianVLISM(bulkHE,dens*100.0*100.0*100.0,temp);
//KappaVLISM gv3 = new KappaVLISM(bulkO1, 0.00005*100*100*100, 6300, 1.6);
ndHe = new NeutralDistribution(gv1, 0.0, he_ion_rate); // mu is 0.0 for he
ndHe.debug=false;
// DONE CREATING MEDIUM
}
public double getRate(double dens, double doy) {
if ((currentDens!=dens)) {
System.out.println("new params: " + dens);
setParams(dens);
}
return getRate(doy);
}
public double getRate(double dens, double temp, double doy) {
if ((currentDens!=dens)|(currentTemp!=temp)) {
System.out.println("new params: " + dens + " " + temp);
setParams(dens,temp);
}
return getRate(doy);
}
public double getRate(double longitude, double speed, double dens, double temp, double doy) {
if ((currentLongitude!=longitude)|(currentSpeed!=speed)|(currentDens!=dens)|(currentTemp!=temp)) {
System.out.println("new params: " + longitude + " " + speed + " " + dens + " " + temp);
setParams(longitude,speed,dens,temp);
}
return getRate(doy);
}
/* use this to set the look direction in latitude */
double midThe = Math.PI/2.0;
/**
* Use this one to set the look direction in spin phase and then get the rate
*
*/
public double getRate(double doy, double theta) {
midThe = theta;
getRate(doy);
}
/**
* We want to call this from an optimization routine..
*
*/
public double getRate(double doy) {
// spacecraft position .. assume at earth at doy
//double pos = ((doy-80.0)/365.0);
double pos = (doy-265.0)*(360.0/365.0)*Math.PI/180.0;// - Math.PI;
// set look direction
double midPhi = 0.0;
midThe = Math.PI/2.0;
double appogee = 0;
// SET LOOK DIRECTION
// THIS SET IS FOR FIRST PASS
/*if (doy>10 && doy<15.5) {
//orbit 13
appogee = 13.1;
}
else if (doy>15.5 && doy<24.1) {
//orbit 14
appogee = 20.5;
}
else if (doy>24.1 && doy<32.0) {
//orbit 15
appogee = 28.1;
}
else if (doy>32.0 && doy<39.7) {
//orbit 16
appogee = 35.8;
}
else if (doy>39.7 && doy<47.5) {
//orbit 17
appogee = 43.2;
}
else if (doy>47.5 && doy<55.2) {
//orbit 18
appogee = 51.3;
}
else if (doy>55.2 && doy<62.6) {
//orbit 19
appogee = 58.8;
}
else if (doy>62.6 && doy<70.2) {
//orbit 20
appogee = 66.4;
}*/
// SECOND PASS
if (doy>10.5 && doy<18.0) {
//orbit 13
appogee = 14.0;
}
else if (doy>18.0 && doy<25.6) {
//orbit 14
appogee = 21.6;
}
else if (doy>25.6 && doy<33.3) {
//orbit 15
appogee = 29.25;
}
else if (doy>33.3 && doy<40.85) {
//orbit 16
appogee = 36.8;
}
else if (doy>40.85 && doy<48.85) {
//orbit 17
appogee = 44.6;
}
else if (doy>48.85 && doy<56.4) {
//orbit 18
appogee = 52.4;
}
else if (doy>56.4 && doy<64.0) {
//orbit 19
appogee = 60.0;
}
else if (doy>64.0 && doy<71.6) {
//orbit 20
appogee = 67.6;
}
//orbit 21 - apogee= 73.9
//orbit 22 - apogee = 81.8
else {
appogee=doy;
}
//doy = doy-183.0;
//appogee = appogee-183.0;
double he_ans_lr;
midPhi = (appogee-3.0-265.0)*360.0/365.0*Math.PI/180.0 + look_offset;
final double lookPhi = midPhi;
// centered at look diretion.. convert doy+10 (dec 21-jan1) to angle
//midPhi = (appogee+3.0-80.0)*360.0/365.0*Math.PI/180.0 + Math.PI/2;
//midPhi = midPhi;
// here's the now position
final HelioVector posVec = new HelioVector(HelioVector.SPHERICAL, 1*AU, pos, Math.PI/2.0);
final HelioVector scVelVec = new HelioVector(HelioVector.SPHERICAL, EARTHSPEED, pos+Math.PI/2.0, Math.PI/2.0);
// placeholder for zero
//final HelioVector scVelVec = new HelioVector(HelioVector.SPHERICAL, 0.0, pos+Math.PI/2.0, Math.PI/2.0);
FunctionIII he_func = new FunctionIII() { // helium neutral distribution
public double function3(double v, double p, double t) {
double tbr = activeArea*ndHe.dist(posVec, new HelioVector(HelioVector.SPHERICAL,v,p,t).sum(scVelVec) )*v*v*Math.sin(t)*v; // extra v for flux
tbr *= angleResponse(lookPhi,p);
// that is the integrand of our v-space integration
return tbr;
}
};
// set limits for integration - spring only here
//double[] he_lr_lims = { minSpeedsHe[0], maxSpeedsHe[0], midPhi-lrWidth, midPhi+lrWidth, midThe-lrWidth-spinWidth, midThe+lrWidth+spinWidth };
// old limits for including all spin..
double[] he_lr_lims = { minSpeedsHe[1], maxSpeedsHe[7], midPhi-lrWidth, midPhi+lrWidth, 3.0*Math.PI/8.0, 5.0*Math.PI/8.0 };
// new limits for including just a single point in spin phase
double[] he_lr_lims = { minSpeedsHe[1], maxSpeedsHe[7], midPhi-lrWidth, midPhi+lrWidth, midThe-lrWidth, midThe+lrWidth };
he_lr_lims[0]=minSpeedsHe[3]; he_lr_lims[1]=maxSpeedsHe[5]; //, midPhi-lrWidth, midPhi+lrWidth, midThe-lrWidth-spinWidth, midThe+lrWidth+spinWidth };
//PERFORM INTEGRATION
he_ans_lr = 12.0*oneHour *1.0/8.0 *1.0 * mi.mcIntegrate(he_func, he_lr_lims, mcN);
he_ans_lr*=heSpringEff;
return he_ans_lr;
}
public double sigma=6.1;
public double angleResponse(double centerA, double checkA) {
double cA = centerA*180.0/Math.PI;
double chA = checkA*180.0/Math.PI;
double tbr = Math.exp(-(cA-chA)*(cA-chA)/sigma/sigma);
return tbr;
}
public static final void main(String[] args) {
IBEXLO_09fit il = new IBEXLO_09fit();
}
public static void o(String s) {
System.out.println(s);
}
/*
* This is to load a given model from a file and give a proper normalization to match the ibex data
* for using a one parameter (normalization) fit.
*/
public class FitData {
public StringTokenizer st;
public double[] days;
public double[] rates;
public Vector daysV;
public Vector ratesV;
public FitData(String filename) {
daysV = new Vector();
ratesV = new Vector();
file f = new file(filename);
f.initRead();
String line = "";
while ((line=f.readLine())!=null) {
st = new StringTokenizer(line);
daysV.add(st.nextToken());
ratesV.add(st.nextToken());
}
// time to fix the arrays
days = new double[daysV.size()];
rates = new double[daysV.size()];
for (int i=0; i<days.length; i++) {
days[i]=Double.parseDouble((String)daysV.elementAt(i));
rates[i]=Double.parseDouble((String)ratesV.elementAt(i));
}
}
// we are going to interpolate here
public double getRate(double day) {
for (int i=0; i<days.length; i++) {
if (day<days[i]) { // this is where we want to be
return (rates[i]+rates[i+1])/2;
}
}
return 0;
}
}
}
/*
We need to keep track of Earth's Vernal Equinox
and use J2000 Ecliptic Coordinates!!!
March
2009 20 11:44
2010 20 17:32
2011 20 23:21
2012 20 05:14
2013 20 11:02
2014 20 16:57
2015 20 22:45
2016 20 04:30
2017 20 10:28
This gives the location of the current epoch zero ecliptic longitude..
However
/*
/*
Earth peri and aphelion
perihelion aphelion
2007 January 3 20:00 July 7 00:00
2008 January 3 00:00 July 4 08:00
2009 January 4 15:00 July 4 02:00
2010 January 3 00:00 July 6 12:00
2011 January 3 19:00 July 4 15:00
2012 January 5 01:00 July 5 04:00
2013 January 2 05:00 July 5 15:00
2014 January 4 12:00 July 4 00:00
2015 January 4 07:00 July 6 20:00
2016 January 2 23:00 July 4 16:00
2017 January 4 14:00 July 3 20:00
2018 January 3 06:00 July 6 17:00
2019 January 3 05:00 July 4 22:00
2020 January 5 08:00 July 4 12:00
*/ | 0lism | trunk/java/IBEXLO_10fit.java | Java | gpl3 | 19,272 |
import java.lang.Math;
import java.util.Date;
import gaiatools.numeric.integration.Simpson;
//import drasys.or.nonlinear.*; // our friend mr. simpson resides here
/**
* This class should take care of doing multi-dimensional numeric integrations.
* This will be slow!!
*
* Actually not half bad...
*
*
* Lukas Saul
* UNH Physics
* May, 2001
*
* Updated Aug. 2003 - only works with 2D integrals for now...
*
* Updated Aug. 2004 - 3D integrals OK! Did that really take 1 year??
*
* About 2.1 seconds to integrate e^(-x^2-y^2-z^2) !!
*/
public class MultipleIntegration {
private double result;
private Simpson s; // tool to do integrations
/**
* for testing - increments at every 1D integration performed
*/
public long counter, counter2;
/**
* Constructor just sets up the 1D integration routine for running
* after which all integrations may be called.
*/
public MultipleIntegration() {
counter = 0;
counter2 = 0;
result = 0.0;
s=new Simpson();
s.setErrMax(0.001);
// s.setMaxIterations(15);
}
/**
* sets counter to zero
*/
public void reset() {
counter = 0;
}
public void reset2() {
counter2 = 0;
}
/**
* Set accuracy of integration
*/
public void setEpsilon(double d) {
s.setErrMax(d);
}
/**
* Here's the goods, for 3D integrations.
*
* Limits are in order as folows: zlow, zhigh, ylow, yhigh, xlow, xhigh
*
*/
public double integrate(final FunctionIII f, final double[] limits) {
reset();
System.out.println("Called 3D integrator");
System.out.println("Integrating from: \n"+limits[0]+" "+limits[1]+
"\n"+limits[2]+" "+limits[3]+"\n"+limits[4]+" "+limits[5]);
double[] nextLims = new double[4];
for (int i=0; i<4; i++) {
nextLims[i] = limits[i+2];
}
final double[] nextLimits = nextLims;
FunctionI funcII = new FunctionI () {
public double function(double x) {
return integrate(f.getFunctionII(2,x), nextLimits);
}
};
try {
s.setInterval(limits[0],limits[1]);
result=s.getResult(funcII);
//result = integrate(funcII, limits[0], limits[1]);
return result;
// each call to funcII by the integrator does a double integration
}
catch(Exception e) {
e.printStackTrace();
return 0.0;
}
}
/**
* Here's the goods, for 2D integrations
*/
public double integrate(final FunctionII f, final double[] limits) {
//System.out.println("called 2D integrator");
//System.out.println("Integrating from: \n"+limits[0]+" "+limits[1]+
// "\n"+limits[2]+" "+limits[3]);
//reset2();
//if (limits.length!=4) return null;
//System.out.println("called 2D integrator");
FunctionI f1 = new FunctionI() {
public double function(double x) {
return integrate(f.getFunction(1,x),limits[2],limits[3]);
}
};
try{
s.setInterval(limits[0],limits[1]);
result=s.getResult(f1);
//result = integrate(f1, limits[0], limits[1]);
//System.out.println("in2d - result: " + result + " " + counter);
return result;
// each call to f1 by the intgrator does an integration
}
catch (Exception e) {
e.printStackTrace();
return 0.0;
}
}
/**
* Here's the simple goods, for 1D integrations
* courtesy of our friends at drasys.or.nonlinear
*/
public double integrate(final FunctionI f, double lowLimit, double highLimit) {
//System.out.println("Called 1D integrator");
try {
counter2++;
counter++;
if (counter%10000==1) System.out.println("Counter: " + counter);
s.setInterval(lowLimit,highLimit);
return s.getResult(f);
//return s.getResult(f,lowLimit,highLimit);
}
catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* Just for testing only here!!!
*
* seems to work - may 3, 2001
*
* lots more testing for limits of 3d , polar vs. cartesian - Oct. 2004
*/
public static final void main(String[] args) {
MultipleIntegration mi = new MultipleIntegration();
// some functions to integrate!!
FunctionI testf3 = new FunctionI() {
public double value(double x) {
return Math.exp(-x*x);
}
};
FunctionI testf4 = new FunctionI() {
public double value(double x) {
return x*x*x;
}
};
FunctionIII testf = new FunctionIII () {
public double function3(double x, double y, double z) {
return (Math.exp(-(x*x+y*y+z*z)));
}
};
FunctionIII testlims = new FunctionIII () {
public double function3(double x, double y, double z) {
return (x*y*y*z*z*z);
}
};
FunctionIII testfs = new FunctionIII () {
public double function3(double r, double p, double t) {
return (r*r*Math.sin(t)*Math.exp(-(r*r)));
}
};
FunctionII testf2a = new FunctionII () {
public double function2(double x, double y) {
return (Math.exp(-(x*x+y*y)));
}
};
FunctionII testf2b = new FunctionII () {
public double function2(double r, double t) {
return r*Math.exp(-(r*r));
}
};
FunctionII testf2 = testf.getFunctionII(0,0.0);
// these should be the same!! compare z=0 in above.. test here...
System.out.println("test2val: " + testf2.function2(0.1,0.2));
System.out.println("test2aval: " + testf2a.function2(0.1,0.2));
Date d5 = new Date();
double test3 = mi.integrate(testf4,-0.0,2.0);
double test4 = mi.integrate(testf3,-100.0,100.0);
Date d6 = new Date();
System.out.println("Answer x^3 0->2: " + test3);
System.out.println("Answer e^-x^2: " + test4);
System.out.println("answer^2: " + test4*test4);
System.out.println("took: " + (d6.getTime()-d5.getTime()));
System.out.println("1D integrations: " + mi.counter);
double[] lims2 = new double[4];
lims2[0]=-100.0;
lims2[1]=100.0;
lims2[2]=-100.0;
lims2[3]=100.0;
Date d3 = new Date();
double test2 = mi.integrate(testf2,lims2);
Date d4 = new Date();
System.out.println("Answer frm 2d testf2: " + test2);
System.out.println("took: " + (d4.getTime()-d3.getTime()));
System.out.println("1D integrations: " + mi.counter);
d3 = new Date();
test2 = mi.integrate(testf2a,lims2);
d4 = new Date();
System.out.println("Answer frm 2d testf2a: " + test2);
System.out.println("took: " + (d4.getTime()-d3.getTime()));
System.out.println("1D integrations: " + mi.counter);
System.out.println("trying polar 2d now");
lims2 = new double[4];
lims2[0]=0;
lims2[1]=2*Math.PI;
lims2[2]=0;
lims2[3]=10;
d3 = new Date();
double ttest = mi.integrate(testf2b,lims2);
d4 = new Date();
System.out.println("2d polar Answer: " + ttest);
System.out.println("took: " + (d4.getTime()-d3.getTime()));
System.out.println("1D integrations: " + mi.counter);
System.out.println("trying 3d now... ");
// basic limit test here,
double[] lims = new double[6];
lims[0]=0.0;
lims[1]=3.00;
lims[2]=0.0;
lims[3]=1.0;
lims[4]=0.0;
lims[5]=2.0;
Date d1 = new Date();
double test = mi.integrate(testlims,lims);
Date d2 = new Date();
System.out.println("Answer: " + test);
System.out.println("took: " + (d2.getTime()-d1.getTime()));
System.out.println("1D integrations: " + mi.counter);
System.out.println("answer: " + 8*81/2/3/4);
lims = new double[6];
lims[0]=-10.0;
lims[1]=10.00;
lims[2]=-10.0;
lims[3]=10.0;
lims[4]=-10.0;
lims[5]=10.0;
d1 = new Date();
test = mi.integrate(testf,lims);
d2 = new Date();
System.out.println("Answer: " + test);
System.out.println("took: " + (d2.getTime()-d1.getTime()));
System.out.println("1D integrations: " + mi.counter);
System.out.println("test^2/3: " + Math.pow(test,2.0/3.0));
System.out.println("trying 3d now... ");
// 3d Function integration working in spherical coords??
lims = new double[6];
lims[0]=0;
lims[1]=Math.PI;
lims[2]=0;
lims[3]=2*Math.PI;
lims[4]=0;
lims[5]=10.0;
d1 = new Date();
test = mi.integrate(testfs,lims);
d2 = new Date();
System.out.println("Answer: " + test);
System.out.println("took: " + (d2.getTime()-d1.getTime()));
System.out.println("1D integrations: " + mi.counter);
System.out.println("test^2/3: " + Math.pow(test,2.0/3.0));
}
} | 0lism | trunk/java/MultipleIntegrationGaia.java | Java | gpl3 | 8,317 |
//import cern.jet.math.Bessel;
import java.lang.Math;
import java.util.Date;
import drasys.or.nonlinear.*;
public class IntegralTest {
public static void main(String[] args) {
Simpsons s = new Simpsons();
MyF myF = new MyF();
Integration i = new Integration();
i.setMaxError(.001);
//s.setEpsilon(.001);
try {
Date d1 = new Date();
//System.out.println(""+s.getEpsilon());
System.out.println("Simp: "+s.integrate(myF,0.0,Math.PI));
Date d2 = new Date();
System.out.println("" + (d2.getTime() - d1.getTime()));
}
catch(Exception e) {}
i.setFunction(myF);
i.setStartDivision(4);
Date d3 = new Date();
System.out.println("MyGuy: "+i.integrate(0.0,Math.PI)+"");
Date d4 = new Date();
System.out.println("" + (d4.getTime() - d3.getTime()));
/*try {
s.setEpsilon(.000001);
System.out.println(""+s.getEpsilon());
System.out.println(""+s.integrate(myF,1,10));
}
catch(Exception e) {}try {
s.setEpsilon(.5);
System.out.println(""+s.getEpsilon());
System.out.println(""+s.integrate(myF,1,10));
}
catch(Exception e) {}try {
s.setEpsilon(.001);
System.out.println(""+s.getEpsilon());
System.out.println(""+s.integrate(myF,1,10));
}
catch(Exception e) {}try {
s.setEpsilon(.9);
System.out.println(""+s.getEpsilon());
System.out.println(""+s.integrate(myF,1,10));
}
catch(Exception e) {}*/
}
}
class MyF extends Function {
public double function(double x) {
return Math.sin(x);
}
}
| 0lism | trunk/java/IntegralTest.java | Java | gpl3 | 1,547 |
import java.util.Date;
/**
* The usual "hot model" here.. only with one species for now
*
*/
public class GaussianVLISM extends InterstellarMedium {
public HelioVector vBulk;
public double temp, density;
public static double KB = 1.3807*Math.pow(10,-23);
public static double MP = 1.672621*Math.pow(10,-27);
private double Mover2KbT, norm, temp1,temp2,temp3;
public static double NaN = Double.NaN;
/**
* Construct a gaussian VLISM
*/
public GaussianVLISM(HelioVector _vBulk, double _density, double _temp) {
vBulk = _vBulk;
temp = _temp;
density = _density;
//System.out.println("created gaussian vlism with ro: " + density + " temp: " + temp + " bulk: " + vBulk.getR());
// normalization for maxwellian distribution
// trying power of 1/2 to see what the difference is
norm = density*Math.pow(4.0*MP/2.0/Math.PI/KB/temp,3.0/2.0);
//norm = density*Math.sqrt(4.0*MP/2.0/Math.PI/KB/temp);
// argument of exponential requires this factor
Mover2KbT = 4.0*MP/2.0/KB/temp;
}
/**
*
* Pass in a heliovector if you feel like it.. slower?
* probably not..
*/
public double heliumDist(HelioVector v) {
return dist(v.getX(), v.getY(), v.getZ());
}
public double heliumDist(double v1, double v2, double v3) {
return dist(v1,v2,v3);
}
/**
* default - pass in 3 doubles
*/
public double dist(double v1, double v2, double v3) {
if (v1==NaN | v2==NaN | v3==NaN) return 0.0;
temp1 = v1-vBulk.getX(); temp2 = v2-vBulk.getY(); temp3 = v3-vBulk.getZ();
temp1 = temp1*temp1+temp2*temp2+temp3*temp3;
return norm*Math.exp(-Mover2KbT*temp1);
}
public double dist(HelioVector hv) {
return dist(hv.getX(), hv.getY(), hv.getZ());
}
public double protonDist(double v1, double v2, double v3) {
return 0;
}
public double hydrogenDist(double v1, double v2, double v3) {
return 0;
}
public double deuteriumDist(double v1, double v2, double v3) {
return 0;
}
public double electronDist(double v1, double v2, double v3) {
return 0;
}
public double alphaDist(double v1, double v2, double v3) {
return 0;
}
// etcetera...+
/**
* Finally well tested, Aug. 2004
*
* redoing testing w/ monte carlo integration - test MultipleIntegration here now 12/2010
*/
public static final void main(String[] args) {
final GaussianVLISM gvli = new GaussianVLISM(new HelioVector(HelioVector.CARTESIAN,
-27000.0,0.0,0.0), 100.0, 6000.0);
System.out.println("Created GVLISM" );
/*
int res = 100;
file f = new file ("gauss_samp.txt");
f.initWrite(false);
for (double v = -40000; v<10000; v+= 50000/res) {
double dens = gvli.heliumDist(v,0,0);
f.write(v+"\t"+dens+"\n");
}
f.closeWrite();
*/
//System.out.println("Maxwellian VLISM created, norm = " + norm);
MultipleIntegration mi = new MultipleIntegration();
//mi.setEpsilon(0.001);
FunctionIII dist = new FunctionIII () {
public double function3(double x, double y, double z) {
return gvli.heliumDist(x, y, z);
}
};
System.out.println("Test dist: " + dist.function3(20000,0,0));
//double[] limits = new double[6];
//limits[0]=mi.MINUS_INFINITY; limits[1]=mi.PLUS_INFINITY;
//limits[2]=mi.MINUS_INFINITY; limits[3]=mi.PLUS_INFINITY;
//limits[4]=mi.MINUS_INFINITY; limits[5]=mi.PLUS_INFINITY;
double[] limits2 = new double[6];
limits2[0]=-100000.0; limits2[1]=100000.0;
limits2[2]=-100000.0; limits2[3]=100000.0;
limits2[4]=-100000.0; limits2[5]=100000.0;
//double z = mi.integrate(dist,limits2,1000);
//o(" plain integration: " + z);
double z2 = mi.mcIntegrate(dist,limits2,100000);
o(" mc at 100000: " + z2);
double z3 = mi.mcIntegrate(dist,limits2,1000000);
o(" mc at 1000000: " + z3);
//System.out.println("answer: plain, mc1, mc2 = " + z+ " "+ z2 + " " + z3);
FunctionIII distZw = new FunctionIII () {
public double function3(double r, double p, double t) {
HelioVector hv = new HelioVector(HelioVector.SPHERICAL,r,p,t);
return gvli.heliumDist(hv)*r*r*Math.sin(t);
}
};
double[] limitsZw = {0.0,100000.0,0.0,2*Math.PI,0,Math.PI};
double ans = mi.mcIntegrate(distZw, limitsZw,1000000);
System.out.println("answer in spherical coords = " + ans );
}
public static void o(String s) {
System.out.println(s);
}
}
| 0lism | trunk/java/GaussianVLISM.java | Java | gpl3 | 4,395 |
/** This is a wrapper for some static functions I wrote
*
*/
public class LukeMath {
// recursively computes legendre polynomial of order n, argument x
public static double compute(int n,double x) {
if (n == 0) return 1;
else if (n == 1) return x;
return ( (2*n-1)*x*compute(n-1,x) - (n-1)*compute(n-2,x) ) / n;
}
}
// Guess we don't need this stuff...
/*public static long factorial(int m) {
if (m==1) return 1;
else return m*factorial(m-1);
}
}*/// L
/*C*** LEGENDRE POLYNOM P(X) OF ORDER N
C*** EXPLICIT EXPRESSION
POLLEG=0.
NEND=N/2
DO M=0,NEND
N2M2=N*2-M*2
NM2=N-M*2
NM=N-M
TERM=X**NM2*(-1.)**M
TERM=TERM/NFAK(M)*NFAK(N2M2)
TERM=TERM/NFAK(NM)/NFAK(NM2)
POLLEG=POLLEG+TERM
END DO
POLLEG=POLLEG/2**N
RETURN
END
C*/
// I love fortran! | 0lism | trunk/java/LukeMath.java | Java | gpl3 | 895 |