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
#include <cutter.h> #include <nfc/nfc.h> #define NTESTS 10 #define MAX_DEVICE_COUNT 8 #define MAX_TARGET_COUNT 8 /* * This is basically a stress-test to ensure we don't left a device in an * inconsistent state after use. */ void test_access_storm(void); void test_access_storm(void) { int n = NTESTS; nfc_connstring connstrings[MAX_DEVICE_COUNT]; int res = 0; nfc_context *context; nfc_init(&context); size_t ref_device_count = nfc_list_devices(context, connstrings, MAX_DEVICE_COUNT); if (!ref_device_count) cut_omit("No NFC device found"); while (n) { size_t device_count = nfc_list_devices(context, connstrings, MAX_DEVICE_COUNT); cut_assert_equal_int(ref_device_count, device_count, cut_message("device count")); for (volatile size_t i = 0; i < device_count; i++) { nfc_device *device; nfc_target ant[MAX_TARGET_COUNT]; device = nfc_open(context, connstrings[i]); cut_assert_not_null(device, cut_message("nfc_open")); res = nfc_initiator_init(device); cut_assert_equal_int(0, res, cut_message("nfc_initiator_init")); const nfc_modulation nm = { .nmt = NMT_ISO14443A, .nbr = NBR_106, }; res = nfc_initiator_list_passive_targets(device, nm, ant, MAX_TARGET_COUNT); cut_assert_operator_int(res, >= , 0, cut_message("nfc_initiator_list_passive_targets")); nfc_close(device); } n--; } nfc_exit(context); }
1060840728-lvgang
test/test_access_storm.c
C
lgpl
1,447
#include <cutter.h> #include <pthread.h> #include <signal.h> #include <unistd.h> #include "nfc/nfc.h" void test_dep_passive(void); #define INITIATOR 0 #define TARGET 1 pthread_t threads[2]; nfc_context *context; nfc_connstring connstrings[2]; nfc_device *devices[2]; intptr_t result[2]; static void abort_test_by_keypress(int sig) { (void) sig; printf("\033[0;1;31mSIGINT\033[0m"); nfc_abort_command(devices[INITIATOR]); nfc_abort_command(devices[TARGET]); } void cut_setup(void) { nfc_init(&context); size_t n = nfc_list_devices(context, connstrings, 2); if (n < 2) { cut_omit("At least two NFC devices must be plugged-in to run this test"); } devices[TARGET] = nfc_open(context, connstrings[TARGET]); devices[INITIATOR] = nfc_open(context, connstrings[INITIATOR]); signal(SIGINT, abort_test_by_keypress); } void cut_teardown(void) { nfc_close(devices[TARGET]); nfc_close(devices[INITIATOR]); nfc_exit(context); } struct thread_data { nfc_device *device; void *cut_test_context; }; static void * target_thread(void *arg) { intptr_t thread_res = 0; nfc_device *device = ((struct thread_data *) arg)->device; cut_set_current_test_context(((struct thread_data *) arg)->cut_test_context); printf("=========== TARGET %s =========\n", nfc_device_get_name(device)); nfc_target nt = { .nm = { .nmt = NMT_DEP, .nbr = NBR_UNDEFINED }, .nti = { .ndi = { .abtNFCID3 = { 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA }, .szGB = 4, .abtGB = { 0x12, 0x34, 0x56, 0x78 }, .ndm = NDM_PASSIVE, /* These bytes are not used by nfc_target_init: the chip will provide them automatically to the initiator */ .btDID = 0x00, .btBS = 0x00, .btBR = 0x00, .btTO = 0x00, .btPP = 0x01, }, }, }; uint8_t abtRx[1024]; size_t szRx = sizeof(abtRx); int res = nfc_target_init(device, &nt, abtRx, szRx, 0); cut_assert_operator_int(res, > , 0, cut_message("Can't initialize NFC device as target: %s", nfc_strerror(device))); if (res < 0) { thread_res = -1; return (void *) thread_res; } // First pass res = nfc_target_receive_bytes(device, abtRx, sizeof(abtRx), 500); cut_assert_operator_int(res, > , 0, cut_message("Can't receive bytes from initiator: %s", nfc_strerror(device))); const uint8_t abtAttRx[] = "Hello DEP target!"; cut_assert_equal_memory(abtAttRx, sizeof(abtAttRx), abtRx, res, cut_message("Invalid received data")); if (res <= 0) { thread_res = -1; return (void *) thread_res; } const uint8_t abtTx[] = "Hello DEP initiator!"; res = nfc_target_send_bytes(device, abtTx, sizeof(abtTx), 500); cut_assert_operator_int(res, > , 0, cut_message("Can't send bytes to initiator: %s", nfc_strerror(device))); if (res <= 0) { thread_res = -1; return (void *) thread_res; } // Second pass res = nfc_target_receive_bytes(device, abtRx, sizeof(abtRx), 500); cut_assert_operator_int(res, > , 0, cut_message("Can't receive bytes from initiator: %s", nfc_strerror(device))); cut_assert_equal_memory(abtAttRx, sizeof(abtAttRx), abtRx, res, cut_message("Invalid received data")); if (res <= 0) { thread_res = -1; return (void *) thread_res; } res = nfc_target_send_bytes(device, abtTx, sizeof(abtTx), 500); cut_assert_operator_int(res, > , 0, cut_message("Can't send bytes to initiator: %s", nfc_strerror(device))); if (res <= 0) { thread_res = -1; return (void *) thread_res; } // Third pass res = nfc_target_receive_bytes(device, abtRx, sizeof(abtRx), 500); cut_assert_operator_int(res, > , 0, cut_message("Can't receive bytes from initiator: %s", nfc_strerror(device))); cut_assert_equal_memory(abtAttRx, sizeof(abtAttRx), abtRx, res, cut_message("Invalid received data")); if (res <= 0) { thread_res = -1; return (void *) thread_res; } res = nfc_target_send_bytes(device, abtTx, sizeof(abtTx), 500); cut_assert_operator_int(res, > , 0, cut_message("Can't send bytes to initiator: %s", nfc_strerror(device))); if (res <= 0) { thread_res = -1; return (void *) thread_res; } // Fourth pass res = nfc_target_receive_bytes(device, abtRx, sizeof(abtRx), 500); cut_assert_operator_int(res, > , 0, cut_message("Can't receive bytes from initiator: %s", nfc_strerror(device))); cut_assert_equal_memory(abtAttRx, sizeof(abtAttRx), abtRx, res, cut_message("Invalid received data")); if (res <= 0) { thread_res = -1; return (void *) thread_res; } res = nfc_target_send_bytes(device, abtTx, sizeof(abtTx), 500); cut_assert_operator_int(res, > , 0, cut_message("Can't send bytes to initiator: %s", nfc_strerror(device))); if (res <= 0) { thread_res = -1; return (void *) thread_res; } return (void *) thread_res; } static void * initiator_thread(void *arg) { intptr_t thread_res = 0; nfc_device *device = ((struct thread_data *) arg)->device; cut_set_current_test_context(((struct thread_data *) arg)->cut_test_context); /* * Wait some time for the other thread to initialise NFC device as target */ sleep(1); printf("=========== INITIATOR %s =========\n", nfc_device_get_name(device)); int res = nfc_initiator_init(device); cut_assert_equal_int(0, res, cut_message("Can't initialize NFC device as initiator: %s", nfc_strerror(device))); if (res < 0) { thread_res = -1; return (void *) thread_res; } nfc_target nt; // Passive mode / 106Kbps printf("=========== INITIATOR %s (Passive mode / 106Kbps) =========\n", nfc_device_get_name(device)); res = nfc_initiator_select_dep_target(device, NDM_PASSIVE, NBR_106, NULL, &nt, 5000); cut_assert_operator_int(res, > , 0, cut_message("Can't select any DEP target: %s", nfc_strerror(device))); cut_assert_equal_int(NMT_DEP, nt.nm.nmt, cut_message("Invalid target modulation")); cut_assert_equal_int(NBR_106, nt.nm.nbr, cut_message("Invalid target baud rate")); cut_assert_equal_memory("\x11\x22\x33\x44\x55\x66\x77\x88\x99\xAA", 10, nt.nti.ndi.abtNFCID3, 10, cut_message("Invalid target NFCID3")); cut_assert_equal_int(NDM_PASSIVE, nt.nti.ndi.ndm, cut_message("Invalid target DEP mode")); cut_assert_equal_memory("\x12\x34\x56\x78", 4, nt.nti.ndi.abtGB, nt.nti.ndi.szGB, cut_message("Invalid target general bytes")); if (res <= 0) { thread_res = -1; return (void *) thread_res; } const uint8_t abtTx[] = "Hello DEP target!"; uint8_t abtRx[1024]; res = nfc_initiator_transceive_bytes(device, abtTx, sizeof(abtTx), abtRx, sizeof(abtRx), 500); cut_assert_operator_int(res, >= , 0, cut_message("Can't transceive bytes to target: %s", nfc_strerror(device))); const uint8_t abtAttRx[] = "Hello DEP initiator!"; cut_assert_equal_memory(abtAttRx, sizeof(abtAttRx), abtRx, res, cut_message("Invalid received data")); if (res < 0) { thread_res = -1; return (void *) thread_res; } res = nfc_initiator_deselect_target(device); cut_assert_operator_int(res, >= , 0, cut_message("Can't deselect target: %s", nfc_strerror(device))); if (res < 0) { thread_res = -1; return (void *) thread_res; } // Passive mode / 212Kbps (second pass) printf("=========== INITIATOR %s (Passive mode / 212Kbps) =========\n", nfc_device_get_name(device)); res = nfc_initiator_select_dep_target(device, NDM_PASSIVE, NBR_212, NULL, &nt, 1000); cut_assert_operator_int(res, > , 0, cut_message("Can't select any DEP target: %s", nfc_strerror(device))); cut_assert_equal_int(NMT_DEP, nt.nm.nmt, cut_message("Invalid target modulation")); cut_assert_equal_int(NBR_212, nt.nm.nbr, cut_message("Invalid target baud rate")); cut_assert_equal_memory("\x11\x22\x33\x44\x55\x66\x77\x88\x99\xAA", 10, nt.nti.ndi.abtNFCID3, 10, cut_message("Invalid target NFCID3")); cut_assert_equal_int(NDM_PASSIVE, nt.nti.ndi.ndm, cut_message("Invalid target DEP mode")); cut_assert_equal_memory("\x12\x34\x56\x78", 4, nt.nti.ndi.abtGB, nt.nti.ndi.szGB, cut_message("Invalid target general bytes")); if (res <= 0) { thread_res = -1; return (void *) thread_res; } res = nfc_initiator_transceive_bytes(device, abtTx, sizeof(abtTx), abtRx, sizeof(abtRx), 1000); cut_assert_operator_int(res, >= , 0, cut_message("Can't transceive bytes to target: %s", nfc_strerror(device))); cut_assert_equal_memory(abtAttRx, sizeof(abtAttRx), abtRx, res, cut_message("Invalid received data")); if (res < 0) { thread_res = -1; return (void *) thread_res; } res = nfc_initiator_deselect_target(device); cut_assert_operator_int(res, >= , 0, cut_message("Can't deselect target: %s", nfc_strerror(device))); if (res < 0) { thread_res = -1; return (void *) thread_res; } // Passive mode / 212Kbps printf("=========== INITIATOR %s (Passive mode / 212Kbps, second pass) =========\n", nfc_device_get_name(device)); res = nfc_initiator_select_dep_target(device, NDM_PASSIVE, NBR_212, NULL, &nt, 1000); cut_assert_operator_int(res, > , 0, cut_message("Can't select any DEP target: %s", nfc_strerror(device))); cut_assert_equal_int(NMT_DEP, nt.nm.nmt, cut_message("Invalid target modulation")); cut_assert_equal_int(NBR_212, nt.nm.nbr, cut_message("Invalid target baud rate")); cut_assert_equal_memory("\x11\x22\x33\x44\x55\x66\x77\x88\x99\xAA", 10, nt.nti.ndi.abtNFCID3, 10, cut_message("Invalid target NFCID3")); cut_assert_equal_int(NDM_PASSIVE, nt.nti.ndi.ndm, cut_message("Invalid target DEP mode")); cut_assert_equal_memory("\x12\x34\x56\x78", 4, nt.nti.ndi.abtGB, nt.nti.ndi.szGB, cut_message("Invalid target general bytes")); if (res <= 0) { thread_res = -1; return (void *) thread_res; } res = nfc_initiator_transceive_bytes(device, abtTx, sizeof(abtTx), abtRx, sizeof(abtRx), 5000); cut_assert_operator_int(res, >= , 0, cut_message("Can't transceive bytes to target: %s", nfc_strerror(device))); cut_assert_equal_memory(abtAttRx, sizeof(abtAttRx), abtRx, res, cut_message("Invalid received data")); if (res < 0) { thread_res = -1; return (void *) thread_res; } res = nfc_initiator_deselect_target(device); cut_assert_operator_int(res, >= , 0, cut_message("Can't deselect target: %s", nfc_strerror(device))); if (res < 0) { thread_res = -1; return (void *) thread_res; } // Passive mode / 424Kbps printf("=========== INITIATOR %s (Passive mode / 424Kbps) =========\n", nfc_device_get_name(device)); res = nfc_initiator_select_dep_target(device, NDM_PASSIVE, NBR_424, NULL, &nt, 1000); cut_assert_operator_int(res, > , 0, cut_message("Can't select any DEP target: %s", nfc_strerror(device))); cut_assert_equal_int(NMT_DEP, nt.nm.nmt, cut_message("Invalid target modulation")); cut_assert_equal_int(NBR_424, nt.nm.nbr, cut_message("Invalid target baud rate")); cut_assert_equal_memory("\x11\x22\x33\x44\x55\x66\x77\x88\x99\xAA", 10, nt.nti.ndi.abtNFCID3, 10, cut_message("Invalid target NFCID3")); cut_assert_equal_int(NDM_PASSIVE, nt.nti.ndi.ndm, cut_message("Invalid target DEP mode")); cut_assert_equal_memory("\x12\x34\x56\x78", 4, nt.nti.ndi.abtGB, nt.nti.ndi.szGB, cut_message("Invalid target general bytes")); if (res <= 0) { thread_res = -1; return (void *) thread_res; } res = nfc_initiator_transceive_bytes(device, abtTx, sizeof(abtTx), abtRx, sizeof(abtRx), 5000); cut_assert_operator_int(res, >= , 0, cut_message("Can't transceive bytes to target: %s", nfc_strerror(device))); cut_assert_equal_memory(abtAttRx, sizeof(abtAttRx), abtRx, res, cut_message("Invalid received data")); if (res < 0) { thread_res = -1; return (void *) thread_res; } res = nfc_initiator_deselect_target(device); cut_assert_operator_int(res, >= , 0, cut_message("Can't deselect target: %s", nfc_strerror(device))); if (res < 0) { thread_res = -1; return (void *) thread_res; } return (void *) thread_res; } void test_dep_passive(void) { int res; CutTestContext *test_context = cut_get_current_test_context(); struct thread_data target_data = { .device = devices[TARGET], .cut_test_context = test_context, }; if ((res = pthread_create(&(threads[TARGET]), NULL, target_thread, &target_data))) cut_fail("pthread_create() returned %d", res); struct thread_data initiator_data = { .device = devices[INITIATOR], .cut_test_context = test_context, }; if ((res = pthread_create(&(threads[INITIATOR]), NULL, initiator_thread, &initiator_data))) cut_fail("pthread_create() returned %d", res); if ((res = pthread_join(threads[INITIATOR], (void *) &result[INITIATOR]))) cut_fail("pthread_join() returned %d", res); if ((res = pthread_join(threads[TARGET], (void *) &result[TARGET]))) cut_fail("pthread_join() returned %d", res); cut_assert_equal_int(0, result[INITIATOR], cut_message("Unexpected initiator return code")); cut_assert_equal_int(0, result[TARGET], cut_message("Unexpected target return code")); }
1060840728-lvgang
test/test_dep_passive.c
C
lgpl
12,735
#include <cutter.h> #include <nfc/nfc.h> #define MAX_DEVICE_COUNT 1 #define MAX_TARGET_COUNT 1 void test_register_endianness(void); #include "chips/pn53x.h" void test_register_endianness(void) { nfc_connstring connstrings[MAX_DEVICE_COUNT]; int res = 0; nfc_context *context; nfc_init(&context); size_t device_count = nfc_list_devices(context, connstrings, MAX_DEVICE_COUNT); if (!device_count) cut_omit("No NFC device found"); nfc_device *device; device = nfc_open(context, connstrings[0]); cut_assert_not_null(device, cut_message("nfc_open")); uint8_t value; /* Read valid XRAM memory */ res = pn53x_read_register(device, 0xF0FF, &value); cut_assert_equal_int(0, res, cut_message("read register 0xF0FF")); /* Read invalid SFR register */ res = pn53x_read_register(device, 0xFFF0, &value); cut_assert_equal_int(-1, res, cut_message("read register 0xFFF0")); nfc_close(device); nfc_exit(context); }
1060840728-lvgang
test/test_register_endianness.c
C
lgpl
952
#include <cutter.h> #include <nfc/nfc.h> #include "chips/pn53x.h" #define MAX_DEVICE_COUNT 1 #define MAX_TARGET_COUNT 1 void test_register_access(void); void test_register_access(void) { nfc_connstring connstrings[MAX_DEVICE_COUNT]; int res = 0; nfc_context *context; nfc_init(&context); size_t device_count = nfc_list_devices(context, connstrings, MAX_DEVICE_COUNT); if (!device_count) cut_omit("No NFC device found"); nfc_device *device; device = nfc_open(context, connstrings[0]); cut_assert_not_null(device, cut_message("nfc_open")); uint8_t value; /* Set a 0xAA test value in writable register memory to test register access */ res = pn53x_write_register(device, PN53X_REG_CIU_TxMode, 0xFF, 0xAA); cut_assert_equal_int(0, res, cut_message("write register value to 0xAA")); /* Get test value from register memory */ res = pn53x_read_register(device, PN53X_REG_CIU_TxMode, &value); cut_assert_equal_int(0, res, cut_message("read register value")); cut_assert_equal_uint(0xAA, value, cut_message("check register value")); /* Set a 0x55 test value in writable register memory to test register access */ res = pn53x_write_register(device, PN53X_REG_CIU_TxMode, 0xFF, 0x55); cut_assert_equal_int(0, res, cut_message("write register value to 0x55")); /* Get test value from register memory */ res = pn53x_read_register(device, PN53X_REG_CIU_TxMode, &value); cut_assert_equal_int(0, res, cut_message("read register value")); cut_assert_equal_uint(0x55, value, cut_message("check register value")); nfc_close(device); nfc_exit(context); }
1060840728-lvgang
test/test_register_access.c
C
lgpl
1,605
# $Id$ AM_CPPFLAGS = $(CUTTER_CFLAGS) $(LIBNFC_CFLAGS) LIBS = $(CUTTER_LIBS) if WITH_CUTTER TESTS = run-test.sh TESTS_ENVIRONMENT = NO_MAKE=yes CUTTER="$(CUTTER)" cutter_unit_test_libs = \ test_access_storm.la \ test_dep_active.la \ test_device_modes_as_dep.la \ test_dep_passive.la \ test_register_access.la \ test_register_endianness.la if WITH_DEBUG noinst_LTLIBRARIES = $(cutter_unit_test_libs) else check_LTLIBRARIES = $(cutter_unit_test_libs) endif AM_LDFLAGS = -module -rpath $(libdir) -avoid-version -no-undefined test_access_storm_la_SOURCES = test_access_storm.c test_access_storm_la_LIBADD = $(top_builddir)/libnfc/libnfc.la test_dep_active_la_SOURCES = test_dep_active.c test_dep_active_la_LIBADD = $(top_builddir)/libnfc/libnfc.la \ $(top_builddir)/utils/libnfcutils.la test_device_modes_as_dep_la_SOURCES = test_device_modes_as_dep.c test_device_modes_as_dep_la_LIBADD = $(top_builddir)/libnfc/libnfc.la test_dep_passive_la_SOURCES = test_dep_passive.c test_dep_passive_la_LIBADD = $(top_builddir)/libnfc/libnfc.la test_register_access_la_SOURCES = test_register_access.c test_register_access_la_LIBADD = $(top_builddir)/libnfc/libnfc.la test_register_endianness_la_SOURCES = test_register_endianness.c test_register_endianness_la_LIBADD = $(top_builddir)/libnfc/libnfc.la echo-cutter: @echo $(CUTTER) EXTRA_DIST = run-test.sh CLEANFILES = *.gcno endif
1060840728-lvgang
test/Makefile.am
Makefile
lgpl
1,405
#include <cutter.h> #include <pthread.h> #include <signal.h> #include <unistd.h> #include "nfc/nfc.h" #include "../utils/nfc-utils.h" void test_dep_states(void); pthread_t threads[2]; nfc_context *context; nfc_connstring connstrings[2]; nfc_device *first_device, *second_device; intptr_t result[2]; static void abort_test_by_keypress(int sig) { (void) sig; printf("\033[0;1;31mSIGINT\033[0m"); nfc_abort_command(first_device); nfc_abort_command(second_device); } void cut_setup(void) { nfc_init(&context); size_t n = nfc_list_devices(context, connstrings, 2); if (n < 2) { cut_omit("At least two NFC devices must be plugged-in to run this test"); } second_device = nfc_open(context, connstrings[0]); first_device = nfc_open(context, connstrings[1]); signal(SIGINT, abort_test_by_keypress); } void cut_teardown(void) { nfc_close(second_device); nfc_close(first_device); nfc_exit(context); } struct thread_data { nfc_device *device; void *cut_test_context; }; static void * target_thread(void *arg) { intptr_t thread_res = 0; nfc_device *device = ((struct thread_data *) arg)->device; cut_set_current_test_context(((struct thread_data *) arg)->cut_test_context); printf("=========== TARGET %s =========\n", nfc_device_get_name(device)); nfc_target nt; uint8_t abtRx[1024]; // 1) nfc_target_init should take target in idle mode int res = nfc_target_init(device, &nt, abtRx, sizeof(abtRx), 500); cut_assert_operator_int(res, >= , 0, cut_message("Can't initialize NFC device as target: %s", nfc_strerror(device))); if (res < 0) { thread_res = -1; return (void *) thread_res; } // 2) act as target nfc_target nt1 = { .nm = { .nmt = NMT_DEP, .nbr = NBR_UNDEFINED }, .nti = { .ndi = { .abtNFCID3 = { 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA }, .szGB = 4, .abtGB = { 0x12, 0x34, 0x56, 0x78 }, .ndm = NDM_PASSIVE, /* These bytes are not used by nfc_target_init: the chip will provide them automatically to the initiator */ .btDID = 0x00, .btBS = 0x00, .btBR = 0x00, .btTO = 0x00, .btPP = 0x01, }, }, }; sleep(6); res = nfc_target_init(device, &nt1, abtRx, sizeof(abtRx), 0); cut_assert_operator_int(res, > , 0, cut_message("Can't initialize NFC device as target: %s", nfc_strerror(device))); if (res < 0) { thread_res = -1; return (void *) thread_res; } res = nfc_target_receive_bytes(device, abtRx, sizeof(abtRx), 500); cut_assert_operator_int(res, > , 0, cut_message("Can't receive bytes from initiator: %s", nfc_strerror(device))); const uint8_t abtAttRx[] = "Hello DEP target!"; cut_assert_equal_memory(abtAttRx, sizeof(abtAttRx), abtRx, res, cut_message("Invalid received data")); if (res <= 0) { thread_res = -1; return (void *) thread_res; } const uint8_t abtTx[] = "Hello DEP initiator!"; res = nfc_target_send_bytes(device, abtTx, sizeof(abtTx), 500); cut_assert_operator_int(res, > , 0, cut_message("Can't send bytes to initiator: %s", nfc_strerror(device))); if (res <= 0) { thread_res = -1; return (void *) thread_res; } // 3) idle mode sleep(1); nfc_idle(device); return (void *) thread_res; } static void * initiator_thread(void *arg) { intptr_t thread_res = 0; nfc_device *device = ((struct thread_data *) arg)->device; cut_set_current_test_context(((struct thread_data *) arg)->cut_test_context); /* * Wait some time for the other thread to initialise NFC device as target */ sleep(5); printf("=========== INITIATOR %s =========\n", nfc_device_get_name(device)); int res = nfc_initiator_init(device); cut_assert_equal_int(0, res, cut_message("Can't initialize NFC device as initiator: %s", nfc_strerror(device))); if (res < 0) { thread_res = -1; return (void *) thread_res; } // 1) As other device should be in idle mode, nfc_initiator_poll_dep_target should return 0 nfc_target nt; res = nfc_initiator_poll_dep_target(device, NDM_PASSIVE, NBR_106, NULL, &nt, 1000); cut_assert_equal_int(0, res, cut_message("Problem with nfc_idle")); if (res != 0) { thread_res = -1; return (void *) thread_res; } // 2 As other device should be in target mode, nfc_initiator_poll_dep_target should be positive. nfc_target nt1; // Passive mode / 106Kbps printf("=========== INITIATOR %s (Passive mode / 106Kbps) =========\n", nfc_device_get_name(device)); res = nfc_initiator_poll_dep_target(device, NDM_PASSIVE, NBR_106, NULL, &nt1, 5000); cut_assert_operator_int(res, > , 0, cut_message("Can't select any DEP target: %s", nfc_strerror(device))); cut_assert_equal_int(NMT_DEP, nt1.nm.nmt, cut_message("Invalid target modulation")); cut_assert_equal_int(NBR_106, nt1.nm.nbr, cut_message("Invalid target baud rate")); cut_assert_equal_memory("\x11\x22\x33\x44\x55\x66\x77\x88\x99\xAA", 10, nt1.nti.ndi.abtNFCID3, 10, cut_message("Invalid target NFCID3")); cut_assert_equal_int(NDM_PASSIVE, nt1.nti.ndi.ndm, cut_message("Invalid target DEP mode")); cut_assert_equal_memory("\x12\x34\x56\x78", 4, nt1.nti.ndi.abtGB, nt1.nti.ndi.szGB, cut_message("Invalid target general bytes")); if (res <= 0) { thread_res = -1; return (void *) thread_res; } const uint8_t abtTx[] = "Hello DEP target!"; uint8_t abtRx[1024]; res = nfc_initiator_transceive_bytes(device, abtTx, sizeof(abtTx), abtRx, sizeof(abtRx), 500); cut_assert_operator_int(res, >= , 0, cut_message("Can't transceive bytes to target: %s", nfc_strerror(device))); const uint8_t abtAttRx[] = "Hello DEP initiator!"; cut_assert_equal_memory(abtAttRx, sizeof(abtAttRx), abtRx, res, cut_message("Invalid received data")); if (res < 0) { thread_res = -1; return (void *) thread_res; } res = nfc_initiator_deselect_target(device); cut_assert_operator_int(res, >= , 0, cut_message("Can't deselect target: %s", nfc_strerror(device))); if (res < 0) { thread_res = -1; return (void *) thread_res; } // 3) As other device should be in idle mode, nfc_initiator_poll_dep_target should return 0 nfc_target nt2; res = nfc_initiator_poll_dep_target(device, NDM_PASSIVE, NBR_106, NULL, &nt2, 1000); cut_assert_equal_int(0, res, cut_message("Problem with nfc_idle")); if (res != 0) { thread_res = -1; return (void *) thread_res; } return (void *) thread_res; } void test_dep_states(void) { CutTestContext *test_context = cut_get_current_test_context(); struct thread_data target_data = { .device = first_device, .cut_test_context = test_context, }; struct thread_data initiator_data = { .device = second_device, .cut_test_context = test_context, }; for (int i = 0; i < 2; i++) { int res; if ((res = pthread_create(&(threads[1]), NULL, target_thread, &target_data))) cut_fail("pthread_create() returned %d", res); if ((res = pthread_create(&(threads[0]), NULL, initiator_thread, &initiator_data))) cut_fail("pthread_create() returned %d", res); if ((res = pthread_join(threads[0], (void *) &result[0]))) cut_fail("pthread_join() returned %d", res); if ((res = pthread_join(threads[1], (void *) &result[1]))) cut_fail("pthread_join() returned %d", res); cut_assert_equal_int(0, result[0], cut_message("Unexpected initiator return code")); cut_assert_equal_int(0, result[1], cut_message("Unexpected target return code")); // initiator --> target, target --> initiator target_data.device = second_device; initiator_data.device = first_device; } }
1060840728-lvgang
test/test_device_modes_as_dep.c
C
lgpl
7,522
#include <cutter.h> #include <pthread.h> #include <signal.h> #include <unistd.h> #include "nfc/nfc.h" #include "../utils/nfc-utils.h" void test_dep_active(void); #define INITIATOR 0 #define TARGET 1 pthread_t threads[2]; nfc_context *context; nfc_connstring connstrings[2]; nfc_device *devices[2]; intptr_t result[2]; static void abort_test_by_keypress(int sig) { (void) sig; printf("\033[0;1;31mSIGINT\033[0m"); nfc_abort_command(devices[INITIATOR]); nfc_abort_command(devices[TARGET]); } void cut_setup(void) { nfc_init(&context); size_t n = nfc_list_devices(context, connstrings, 2); if (n < 2) { cut_omit("At least two NFC devices must be plugged-in to run this test"); } devices[TARGET] = nfc_open(context, connstrings[TARGET]); devices[INITIATOR] = nfc_open(context, connstrings[INITIATOR]); signal(SIGINT, abort_test_by_keypress); } void cut_teardown(void) { nfc_close(devices[TARGET]); nfc_close(devices[INITIATOR]); nfc_exit(context); } struct thread_data { nfc_device *device; void *cut_test_context; nfc_baud_rate nbr; }; static void * target_thread(void *arg) { intptr_t thread_res = 0; nfc_device *device = ((struct thread_data *) arg)->device; cut_set_current_test_context(((struct thread_data *) arg)->cut_test_context); printf("=========== TARGET %s =========\n", nfc_device_get_name(device)); nfc_target nt = { .nm = { .nmt = NMT_DEP, .nbr = NBR_UNDEFINED }, .nti = { .ndi = { .abtNFCID3 = { 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA }, .szGB = 4, .abtGB = { 0x12, 0x34, 0x56, 0x78 }, .ndm = NDM_ACTIVE, /* These bytes are not used by nfc_target_init: the chip will provide them automatically to the initiator */ .btDID = 0x00, .btBS = 0x00, .btBR = 0x00, .btTO = 0x00, .btPP = 0x01, }, }, }; uint8_t abtRx[1024]; int res = nfc_target_init(device, &nt, abtRx, sizeof(abtRx), 0); cut_assert_operator_int(res, > , 0, cut_message("Can't initialize NFC device as target: %s", nfc_strerror(device))); if (res < 0) { thread_res = -1; return (void *) thread_res; } res = nfc_target_receive_bytes(device, abtRx, sizeof(abtRx), 500); cut_assert_operator_int(res, > , 0, cut_message("Can't receive bytes from initiator: %s", nfc_strerror(device))); const uint8_t abtAttRx[] = "Hello DEP target!"; cut_assert_equal_memory(abtAttRx, sizeof(abtAttRx), abtRx, res, cut_message("Invalid received data")); if (res <= 0) { thread_res = -1; return (void *) thread_res; } const uint8_t abtTx[] = "Hello DEP initiator!"; res = nfc_target_send_bytes(device, abtTx, sizeof(abtTx), 500); cut_assert_operator_int(res, > , 0, cut_message("Can't send bytes to initiator: %s", nfc_strerror(device))); if (res <= 0) { thread_res = -1; return (void *) thread_res; } return (void *) thread_res; } static void * initiator_thread(void *arg) { intptr_t thread_res = 0; nfc_device *device = ((struct thread_data *) arg)->device; cut_set_current_test_context(((struct thread_data *) arg)->cut_test_context); nfc_baud_rate nbr = (((struct thread_data *) arg)->nbr); /* * Wait some time for the other thread to initialise NFC device as target */ sleep(1); printf("=========== INITIATOR %s =========\n", nfc_device_get_name(device)); int res = nfc_initiator_init(device); cut_assert_equal_int(0, res, cut_message("Can't initialize NFC device as initiator: %s", nfc_strerror(device))); if (res < 0) { thread_res = -1; return (void *) thread_res; } nfc_target nt; // Active mode printf("=========== INITIATOR %s (Active mode / %s Kbps) =========\n", nfc_device_get_name(device), str_nfc_baud_rate(nbr)); res = nfc_initiator_select_dep_target(device, NDM_ACTIVE, nbr, NULL, &nt, 1000); cut_assert_operator_int(res, > , 0, cut_message("Can't select any DEP target: %s", nfc_strerror(device))); cut_assert_equal_int(NMT_DEP, nt.nm.nmt, cut_message("Invalid target modulation")); cut_assert_equal_int(nbr, nt.nm.nbr, cut_message("Invalid target baud rate")); cut_assert_equal_memory("\x11\x22\x33\x44\x55\x66\x77\x88\x99\xAA", 10, nt.nti.ndi.abtNFCID3, 10, cut_message("Invalid target NFCID3")); cut_assert_equal_int(NDM_ACTIVE, nt.nti.ndi.ndm, cut_message("Invalid target DEP mode")); cut_assert_equal_memory("\x12\x34\x56\x78", 4, nt.nti.ndi.abtGB, nt.nti.ndi.szGB, cut_message("Invalid target general bytes")); if (res <= 0) { thread_res = -1; return (void *) thread_res; } const uint8_t abtTx[] = "Hello DEP target!"; uint8_t abtRx[1024]; res = nfc_initiator_transceive_bytes(device, abtTx, sizeof(abtTx), abtRx, sizeof(abtRx), 5000); cut_assert_operator_int(res, >= , 0, cut_message("Can't transceive bytes to target: %s", nfc_strerror(device))); const uint8_t abtAttRx[] = "Hello DEP initiator!"; cut_assert_equal_memory(abtAttRx, sizeof(abtAttRx), abtRx, res, cut_message("Invalid received data (as initiator)")); if (res < 0) { thread_res = -1; return (void *) thread_res; } res = nfc_initiator_deselect_target(device); cut_assert_operator_int(res, >= , 0, cut_message("Can't deselect target: %s", nfc_strerror(device))); if (res < 0) { thread_res = -1; return (void *) thread_res; } return (void *) thread_res; } void test_dep_active(void) { nfc_baud_rate nbrs[3] = { NBR_106, NBR_212, NBR_424}; CutTestContext *test_context = cut_get_current_test_context(); struct thread_data target_data = { .device = devices[TARGET], .cut_test_context = test_context, }; struct thread_data initiator_data = { .device = devices[INITIATOR], .cut_test_context = test_context, }; for (int i = 0; i < 3; i++) { initiator_data.nbr = nbrs[i]; int res; if ((res = pthread_create(&(threads[TARGET]), NULL, target_thread, &target_data))) cut_fail("pthread_create() returned %d", res); if ((res = pthread_create(&(threads[INITIATOR]), NULL, initiator_thread, &initiator_data))) cut_fail("pthread_create() returned %d", res); if ((res = pthread_join(threads[INITIATOR], (void *) &result[INITIATOR]))) cut_fail("pthread_join() returned %d", res); if ((res = pthread_join(threads[TARGET], (void *) &result[TARGET]))) cut_fail("pthread_join() returned %d", res); cut_assert_equal_int(0, result[INITIATOR], cut_message("Unexpected initiator return code")); cut_assert_equal_int(0, result[TARGET], cut_message("Unexpected target return code")); } }
1060840728-lvgang
test/test_dep_active.c
C
lgpl
6,508
#!/bin/sh export BASE_DIR="`dirname $0`" if test -z "$NO_MAKE"; then make -C "$BASE_DIR/../" > /dev/null || exit 1 fi if test -z "$CUTTER"; then CUTTER="`make -s -C "$BASE_DIR" echo-cutter`" fi "$CUTTER" --keep-opening-modules -s "$BASE_DIR" "$@" "$BASE_DIR" # ^^^^^^^^^^^^^^^^^^^^^^ # FIXME: Remove this workaround once cutter has been fixed upstream. # Bug report: # http://sourceforge.net/mailarchive/forum.php?thread_name=20100626123941.GA258%40blogreen.org&forum_name=cutter-users-en
1060840728-lvgang
test/run-test.sh
Shell
lgpl
509
#!/bin/bash COMPILER="/Applications/Developer Tools/compiler.jar" SOURCE=./src/jquery.autocomplete.js TARGET=./src/jquery.autocomplete.min.js echo "Minifying ${SOURCE} to ${TARGET} ... " if `java -jar "${COMPILER}" "${SOURCE}" > "${TARGET}"` then echo "Minify succeeded." else echo "Minify failed." rm "${TARGET}" fi
1051691978-clone1
minify
Shell
mit
331
$(document).ready(function () { "use strict"; var $input1; module("Setup jQuery, DOM and autocompleter"); test("Create INPUT tag", function() { $input1 = $('<input type="text" id="input1">'); $('#qunit-fixture').append($input1); $input1 = $("#input1"); equal($input1.attr("id"), "input1"); }); test("Create autocompleter", function() { $input1.autocomplete(); equal($input1.data("autocompleter") instanceof $.Autocompleter, true); }); test("Check default options", function() { var ac = $input1.data("autocompleter"); var defaultOptions = $.fn.autocomplete.defaults; var acOptions = ac.options; $.each(defaultOptions, function(index) { equal(defaultOptions[index], acOptions[index]); }); }); });
1051691978-clone1
test/tests.jquery.autocomplete.js
JavaScript
mit
839
<!DOCTYPE html> <html> <head> <title>QUnit for jquery-autocmplete</title> <!-- jQuery --> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <!-- QUnit --> <link rel="stylesheet" href="http://code.jquery.com/qunit/git/qunit.css" type="text/css" media="screen"/> <script type="text/javascript" src="http://code.jquery.com/qunit/git/qunit.js"></script> <!-- jquery-autocomplete --> <link rel="stylesheet" type="text/css" href="../src/jquery.autocomplete.css"> <script type="text/javascript" src="../src/jquery.autocomplete.js"></script> <!-- Tests --> <script type="text/javascript" src="tests.jquery.autocomplete.js"></script> </head> <body> <h1 id="qunit-header">QUnit for jquery-autocomplete</h1> <h2 id="qunit-banner"></h2> <div id="qunit-testrunner-toolbar"></div> <h2 id="qunit-userAgent"></h2> <ol id="qunit-tests"></ol> <div id="qunit-fixture"></div> </body> </html>
1051691978-clone1
test/index.html
HTML
mit
1,006
.acInput { width: 200px; } .acResults { padding: 0px; border: 1px solid WindowFrame; background-color: Window; overflow: hidden; } .acResults ul { width: 100%; list-style-position: outside; list-style: none; padding: 0; margin: 0; } .acResults li { margin: 0px; padding: 2px 5px; cursor: pointer; display: block; width: 100%; font: menu; font-size: 12px; overflow: hidden; } .acLoading { background : url('indicator.gif') right center no-repeat; } .acSelect { background-color: Highlight; color: HighlightText; }
1051691978-clone1
src/jquery.autocomplete.css
CSS
mit
538
/*! * jQuery Autocompleter * jquery.autocomplete.js * http://code.google.com/p/jquery-autocomplete/ * Copyright 2011, Dylan Verheul * Licensed under the MIT license */ (function($) { "use strict"; /** * Default settings for options */ var defaultOptions = { inputClass: 'acInput', loadingClass: 'acLoading', resultsClass: 'acResults', selectClass: 'acSelect', queryParamName: 'q', limitParamName: 'limit', extraParams: {}, remoteDataType: false, lineSeparator: '\n', cellSeparator: '|', minChars: 2, maxItemsToShow: 10, delay: 400, useCache: true, maxCacheLength: 10, matchSubset: true, matchCase: false, matchInside: true, mustMatch: false, selectFirst: false, selectOnly: false, showResult: null, preventDefaultReturn: true, preventDefaultTab: false, autoFill: false, filterResults: true, sortResults: true, sortFunction: null, onItemSelect: null, onNoMatch: null, onFinish: null, matchStringConverter: null, beforeUseConverter: null, autoWidth: 'min-width' }; /** * Autocompleter Object * @param {jQuery} $elem jQuery object with one input tag * @param {Object=} options Settings * @constructor */ $.Autocompleter = function($elem, options) { /** * Assert parameters */ if (!$elem || !($elem instanceof jQuery) || $elem.length !== 1 || $elem.get(0).tagName.toUpperCase() !== 'INPUT') { throw new Error('Invalid parameter for jquery.Autocompleter, jQuery object with one element with INPUT tag expected.'); } /** * Init options */ this.options = options; /** * Shortcut to self * @type Object * @private */ var self = this; /** * Cached data * @type Object * @private */ this.cacheData_ = {}; /** * Number of cached data items * @type number * @private */ this.cacheLength_ = 0; /** * Class name to mark selected item * @type string * @private */ this.selectClass_ = 'jquery-autocomplete-selected-item'; /** * Handler to activation timeout * @type ?number * @private */ this.keyTimeout_ = null; /** * Last key pressed in the input field (store for behavior) * @type ?number * @private */ this.lastKeyPressed_ = null; /** * Last value processed by the autocompleter * @type ?string * @private */ this.lastProcessedValue_ = null; /** * Last value selected by the user * @type ?string * @private */ this.lastSelectedValue_ = null; /** * Is this autocompleter active? * Set by showResults() if we have results to show * @type boolean * @private */ this.active_ = false; /** * Is it OK to finish on blur? * @type boolean * @private */ this.finishOnBlur_ = true; /** * Sanitize minChars */ this.options.minChars = parseInt(this.options.minChars, 10); if (isNaN(this.options.minChars) || this.options.minChars < 1) { this.options.minChars = defaultOptions.minChars; } /** * Sanitize maxItemsToShow */ this.options.maxItemsToShow = parseInt(this.options.maxItemsToShow, 10); if (isNaN(this.options.maxItemsToShow) || this.options.maxItemsToShow < 1) { this.options.maxItemsToShow = defaultOptions.maxItemsToShow; } /** * Sanitize maxCacheLength */ this.options.maxCacheLength = parseInt(this.options.maxCacheLength, 10); if (isNaN(this.options.maxCacheLength) || this.options.maxCacheLength < 1) { this.options.maxCacheLength = defaultOptions.maxCacheLength; } /** * Init DOM elements repository */ this.dom = {}; /** * Store the input element we're attached to in the repository */ this.dom.$elem = $elem; /** * Switch off the native autocomplete and add the input class */ this.dom.$elem.attr('autocomplete', 'off').addClass(this.options.inputClass); /** * Create DOM element to hold results */ this.dom.$results = $('<div></div>').hide().addClass(this.options.resultsClass).css({ position: 'absolute' }); $('body').append(this.dom.$results); /** * Attach keyboard monitoring to $elem */ $elem.keydown(function(e) { self.lastKeyPressed_ = e.keyCode; switch(self.lastKeyPressed_) { case 38: // up e.preventDefault(); if (self.active_) { self.focusPrev(); } else { self.activate(); } return false; case 40: // down e.preventDefault(); if (self.active_) { self.focusNext(); } else { self.activate(); } return false; case 9: // tab if (self.active_) { self.selectCurrent(); if (self.options.preventDefaultTab) { e.preventDefault(); return false; } } break; case 13: // return if (self.active_) { self.selectCurrent(); if (self.options.preventDefaultReturn) { e.preventDefault(); return false; } } break; case 27: // escape if (self.active_) { e.preventDefault(); self.finish(); return false; } break; default: self.activate(); } }); /** * Finish on blur event */ $elem.blur(function() { if (self.finishOnBlur_) { setTimeout(function() { self.finish(); }, 200); } }); }; /** * Position output DOM elements */ $.Autocompleter.prototype.position = function() { var offset = this.dom.$elem.offset(); this.dom.$results.css({ top: offset.top + this.dom.$elem.outerHeight(), left: offset.left }); }; /** * Read from cache */ $.Autocompleter.prototype.cacheRead = function(filter) { var filterLength, searchLength, search, maxPos, pos; if (this.options.useCache) { filter = String(filter); filterLength = filter.length; if (this.options.matchSubset) { searchLength = 1; } else { searchLength = filterLength; } while (searchLength <= filterLength) { if (this.options.matchInside) { maxPos = filterLength - searchLength; } else { maxPos = 0; } pos = 0; while (pos <= maxPos) { search = filter.substr(0, searchLength); if (this.cacheData_[search] !== undefined) { return this.cacheData_[search]; } pos++; } searchLength++; } } return false; }; /** * Write to cache */ $.Autocompleter.prototype.cacheWrite = function(filter, data) { if (this.options.useCache) { if (this.cacheLength_ >= this.options.maxCacheLength) { this.cacheFlush(); } filter = String(filter); if (this.cacheData_[filter] !== undefined) { this.cacheLength_++; } this.cacheData_[filter] = data; return this.cacheData_[filter]; } return false; }; /** * Flush cache */ $.Autocompleter.prototype.cacheFlush = function() { this.cacheData_ = {}; this.cacheLength_ = 0; }; /** * Call hook * Note that all called hooks are passed the autocompleter object */ $.Autocompleter.prototype.callHook = function(hook, data) { var f = this.options[hook]; if (f && $.isFunction(f)) { return f(data, this); } return false; }; /** * Set timeout to activate autocompleter */ $.Autocompleter.prototype.activate = function() { var self = this; var activateNow = function() { self.activateNow(); }; var delay = parseInt(this.options.delay, 10); if (isNaN(delay) || delay <= 0) { delay = 250; } if (this.keyTimeout_) { clearTimeout(this.keyTimeout_); } this.keyTimeout_ = setTimeout(activateNow, delay); }; /** * Activate autocompleter immediately */ $.Autocompleter.prototype.activateNow = function() { var value = this.beforeUseConverter(this.dom.$elem.val()); if (value !== this.lastProcessedValue_ && value !== this.lastSelectedValue_) { if (value.length >= this.options.minChars) { this.lastProcessedValue_ = value; this.fetchData(value); } } }; /** * Get autocomplete data for a given value */ $.Autocompleter.prototype.fetchData = function(value) { if (this.options.data) { this.filterAndShowResults(this.options.data, value); } else { var self = this; this.fetchRemoteData(value, function(remoteData) { self.filterAndShowResults(remoteData, value); }); } }; /** * Get remote autocomplete data for a given value */ $.Autocompleter.prototype.fetchRemoteData = function(filter, callback) { var data = this.cacheRead(filter); if (data) { callback(data); } else { var self = this; this.dom.$elem.addClass(this.options.loadingClass); var ajaxCallback = function(data) { var parsed = false; if (data !== false) { parsed = self.parseRemoteData(data); self.cacheWrite(filter, parsed); } self.dom.$elem.removeClass(self.options.loadingClass); callback(parsed); }; $.ajax({ url: this.makeUrl(filter), success: ajaxCallback, error: function() { ajaxCallback(false); }, dataType: 'text' }); } }; /** * Create or update an extra parameter for the remote request */ $.Autocompleter.prototype.setExtraParam = function(name, value) { var index = $.trim(String(name)); if (index) { if (!this.options.extraParams) { this.options.extraParams = {}; } if (this.options.extraParams[index] !== value) { this.options.extraParams[index] = value; this.cacheFlush(); } } }; /** * Build the url for a remote request */ $.Autocompleter.prototype.makeUrl = function(param) { var self = this; var url = this.options.url; var params = $.extend({}, this.options.extraParams); // If options.queryParamName === false, append query to url // instead of using a GET parameter if (this.options.queryParamName === false) { url += encodeURIComponent(param); } else { params[this.options.queryParamName] = param; } if (this.options.limitParamName && this.options.maxItemsToShow) { params[this.options.limitParamName] = this.options.maxItemsToShow; } var urlAppend = []; $.each(params, function(index, value) { urlAppend.push(self.makeUrlParam(index, value)); }); if (urlAppend.length) { url += url.indexOf('?') === -1 ? '?' : '&'; url += urlAppend.join('&'); } return url; }; /** * Create partial url for a name/value pair */ $.Autocompleter.prototype.makeUrlParam = function(name, value) { return [name, encodeURIComponent(value)].join('='); }; /** * Parse data received from server */ $.Autocompleter.prototype.parseRemoteData = function(remoteData) { var remoteDataType = this.options.remoteDataType; if (remoteDataType === 'json') { return this.parseRemoteJSON(remoteData); } return this.parseRemoteText(remoteData); }; /** * Parse data received in text format */ $.Autocompleter.prototype.parseRemoteText = function(remoteData) { var results = []; var text = String(remoteData).replace('\r\n', this.options.lineSeparator); var i, j, data, line, lines = text.split(this.options.lineSeparator); var value; for (i = 0; i < lines.length; i++) { line = lines[i].split(this.options.cellSeparator); data = []; for (j = 0; j < line.length; j++) { data.push(decodeURIComponent(line[j])); } value = data.shift(); results.push({ value: value, data: data }); } return results; }; /** * Parse data received in JSON format */ $.Autocompleter.prototype.parseRemoteJSON = function(remoteData) { return $.parseJSON(remoteData); }; /** * Filter results and show them * @param results * @param filter */ $.Autocompleter.prototype.filterAndShowResults = function(results, filter) { this.showResults(this.filterResults(results, filter), filter); }; /** * Filter results * @param results * @param filter */ $.Autocompleter.prototype.filterResults = function(results, filter) { var filtered = []; var value, data, i, result, type, include; var pattern, testValue; for (i = 0; i < results.length; i++) { result = results[i]; type = typeof result; if (type === 'string') { value = result; data = {}; } else if ($.isArray(result)) { value = result[0]; data = result.slice(1); } else if (type === 'object') { value = result.value; data = result.data; } value = String(value); if (value > '') { if (typeof data !== 'object') { data = {}; } if (this.options.filterResults) { pattern = this.matchStringConverter(filter); testValue = this.matchStringConverter(value); if (!this.options.matchCase) { pattern = pattern.toLowerCase(); testValue = testValue.toLowerCase(); } include = testValue.indexOf(pattern); if (this.options.matchInside) { include = include > -1; } else { include = include === 0; } } else { include = true; } if (include) { filtered.push({ value: value, data: data }); } } } if (this.options.sortResults) { filtered = this.sortResults(filtered, filter); } if (this.options.maxItemsToShow > 0 && this.options.maxItemsToShow < filtered.length) { filtered.length = this.options.maxItemsToShow; } return filtered; }; /** * Sort results * @param results * @param filter */ $.Autocompleter.prototype.sortResults = function(results, filter) { var self = this; var sortFunction = this.options.sortFunction; if (!$.isFunction(sortFunction)) { sortFunction = function(a, b, f) { return self.sortValueAlpha(a, b, f); }; } results.sort(function(a, b) { return sortFunction(a, b, filter); }); return results; }; /** * Default sort filter * @param a * @param b */ $.Autocompleter.prototype.sortValueAlpha = function(a, b) { a = String(a.value); b = String(b.value); if (!this.options.matchCase) { a = a.toLowerCase(); b = b.toLowerCase(); } if (a > b) { return 1; } if (a < b) { return -1; } return 0; }; /** * Convert string before matching * @param s * @param a * @param b */ $.Autocompleter.prototype.matchStringConverter = function(s, a, b) { var converter = this.options.matchStringConverter; if ($.isFunction(converter)) { s = converter(s, a, b); } return s; }; /** * Convert string before use * @param s * @param a * @param b */ $.Autocompleter.prototype.beforeUseConverter = function(s, a, b) { var converter = this.options.beforeUseConverter; if ($.isFunction(converter)) { s = converter(s, a, b); } return s; }; /** * Enable finish on blur event */ $.Autocompleter.prototype.enableFinishOnBlur = function() { this.finishOnBlur_ = true; }; /** * Disable finish on blur event */ $.Autocompleter.prototype.disableFinishOnBlur = function() { this.finishOnBlur_ = false; }; /** * Create a results item (LI element) from a result * @param result */ $.Autocompleter.prototype.createItemFromResult = function(result) { var self = this; var $li = $('<li>' + this.showResult(result.value, result.data) + '</li>'); $li.data({value: result.value, data: result.data}) .click(function() { self.selectItem($li); }) .mousedown(self.disableFinishOnBlur) .mouseup(self.enableFinishOnBlur) ; return $li; }; /** * Show all results * @param results * @param filter */ $.Autocompleter.prototype.showResults = function(results, filter) { var numResults = results.length; if (numResults === 0) { return this.finish(); } var self = this; var $ul = $('<ul></ul>'); var i, result, $li, autoWidth, first = false, $first = false; for (i = 0; i < numResults; i++) { result = results[i]; $li = this.createItemFromResult(result); $ul.append($li); if (first === false) { first = String(result.value); $first = $li; $li.addClass(this.options.firstItemClass); } if (i === numResults - 1) { $li.addClass(this.options.lastItemClass); } } // Always recalculate position before showing since window size or // input element location may have changed. this.position(); this.dom.$results.html($ul).show(); if (this.options.autoWidth) { autoWidth = this.dom.$elem.outerWidth() - this.dom.$results.outerWidth() + this.dom.$results.width(); this.dom.$results.css(this.options.autoWidth, autoWidth); } $('li', this.dom.$results).hover( function() { self.focusItem(this); }, function() { /* void */ } ); if (this.autoFill(first, filter) || this.options.selectFirst || (this.options.selectOnly && numResults === 1)) { this.focusItem($first); } this.active_ = true; }; $.Autocompleter.prototype.showResult = function(value, data) { if ($.isFunction(this.options.showResult)) { return this.options.showResult(value, data); } else { return value; } }; $.Autocompleter.prototype.autoFill = function(value, filter) { var lcValue, lcFilter, valueLength, filterLength; if (this.options.autoFill && this.lastKeyPressed_ !== 8) { lcValue = String(value).toLowerCase(); lcFilter = String(filter).toLowerCase(); valueLength = value.length; filterLength = filter.length; if (lcValue.substr(0, filterLength) === lcFilter) { this.dom.$elem.val(value); this.selectRange(filterLength, valueLength); return true; } } return false; }; $.Autocompleter.prototype.focusNext = function() { this.focusMove(+1); }; $.Autocompleter.prototype.focusPrev = function() { this.focusMove(-1); }; $.Autocompleter.prototype.focusMove = function(modifier) { var $items = $('li', this.dom.$results); modifier = parseInt(modifier, 10); for (var i = 0; i < $items.length; i++) { if ($($items[i]).hasClass(this.selectClass_)) { this.focusItem(i + modifier); return; } } this.focusItem(0); }; $.Autocompleter.prototype.focusItem = function(item) { var $item, $items = $('li', this.dom.$results); if ($items.length) { $items.removeClass(this.selectClass_).removeClass(this.options.selectClass); if (typeof item === 'number') { item = parseInt(item, 10); if (item < 0) { item = 0; } else if (item >= $items.length) { item = $items.length - 1; } $item = $($items[item]); } else { $item = $(item); } if ($item) { $item.addClass(this.selectClass_).addClass(this.options.selectClass); } } }; $.Autocompleter.prototype.selectCurrent = function() { var $item = $('li.' + this.selectClass_, this.dom.$results); if ($item.length === 1) { this.selectItem($item); } else { this.finish(); } }; $.Autocompleter.prototype.selectItem = function($li) { var value = $li.data('value'); var data = $li.data('data'); var displayValue = this.displayValue(value, data); var processedDisplayValue = this.beforeUseConverter(displayValue); this.lastProcessedValue_ = processedDisplayValue; this.lastSelectedValue_ = processedDisplayValue; this.dom.$elem.val(displayValue).focus(); this.setCaret(displayValue.length); this.callHook('onItemSelect', { value: value, data: data }); this.finish(); }; $.Autocompleter.prototype.displayValue = function(value, data) { if ($.isFunction(this.options.displayValue)) { return this.options.displayValue(value, data); } return value; }; $.Autocompleter.prototype.finish = function() { if (this.keyTimeout_) { clearTimeout(this.keyTimeout_); } if (this.beforeUseConverter(this.dom.$elem.val()) !== this.lastSelectedValue_) { if (this.options.mustMatch) { this.dom.$elem.val(''); } this.callHook('onNoMatch'); } this.dom.$results.hide(); this.lastKeyPressed_ = null; this.lastProcessedValue_ = null; if (this.active_) { this.callHook('onFinish'); } this.active_ = false; }; $.Autocompleter.prototype.selectRange = function(start, end) { var input = this.dom.$elem.get(0); if (input.setSelectionRange) { input.focus(); input.setSelectionRange(start, end); } else if (this.createTextRange) { var range = this.createTextRange(); range.collapse(true); range.moveEnd('character', end); range.moveStart('character', start); range.select(); } }; $.Autocompleter.prototype.setCaret = function(pos) { this.selectRange(pos, pos); }; /** * jQuery autocomplete plugin */ $.fn.autocomplete = function(options) { var url; if (arguments.length > 1) { url = options; options = arguments[1]; options.url = url; } else if (typeof options === 'string') { url = options; options = { url: url }; } var opts = $.extend({}, $.fn.autocomplete.defaults, options); return this.each(function() { var $this = $(this); $this.data('autocompleter', new $.Autocompleter( $this, $.meta ? $.extend({}, opts, $this.data()) : opts )); }); }; /** * Store default options */ $.fn.autocomplete.defaults = defaultOptions; })(jQuery);
1051691978-clone1
src/jquery.autocomplete.js
JavaScript
mit
26,366
<?php /* * Load sample data */ include 'data.php'; /* * Results array */ $results = array(); /* * Autocomplete formatter */ function autocomplete_format($results) { foreach ($results as $result) { echo $result[0] . '|' . $result[1] . "\n"; } } /* * Search for term if it is given */ if (isset($_GET['q'])) { $q = strtolower($_GET['q']); if ($q) { foreach ($data as $key => $value) { if (strpos(strtolower($key), $q) !== false) { $results[] = array($key, $value); } } } } /* * Output format */ $output = 'autocomplete'; if (isset($_GET['output'])) { $output = strtolower($_GET['output']); } /* * Output results */ if ($output === 'json') { echo json_encode($results); } else { echo autocomplete_format($results); }
1051691978-clone1
demo/search.php
PHP
mit
828
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>jQuery autocompleter</title> <link rel="stylesheet" type="text/css" href="../src/jquery.autocomplete.css"> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <script type="text/javascript" src="../src/jquery.autocomplete.js"></script> <script type="text/javascript"> $(function() { $("#ac1").autocomplete('search.php', { selectFirst: true }); $("#flush").click(function() { var ac = $("#ac1").data('autocompleter'); if (ac && $.isFunction(ac.cacheFlush)) { ac.cacheFlush(); } else { alert('Error flushing cache'); } }); $("#ac2").autocomplete({ url: 'search.php?output=json', sortFunction: function(a, b, filter) { var f = filter.toLowerCase(); var fl = f.length; var a1 = a.value.toLowerCase().substring(0, fl) == f ? '0' : '1'; var a1 = a1 + String(a.data[0]).toLowerCase(); var b1 = b.value.toLowerCase().substring(0, fl) == f ? '0' : '1'; var b1 = b1 + String(b.data[0]).toLowerCase(); if (a1 > b1) { return 1; } if (a1 < b1) { return -1; } return 0; }, showResult: function(value, data) { return '<span style="color:red">' + value + '</span>'; }, onItemSelect: function(item) { var text = 'You selected <b>' + item.value + '</b>'; if (item.data.length) { text += ' <i>' + item.data.join(', ') + '</i>'; } $("#last_selected").html(text); }, mustMatch: true, maxItemsToShow: 5, selectFirst: false, autoFill: false, selectOnly: true, remoteDataType: 'json' }); $("#ac3").autocomplete({ data: [ ['apple', 1], ['apricot', 2], ['pear', 3], ['prume', 4], ['Doyenné du Comice', 5] ] }); $("#ac4").autocomplete({ url: 'search.php', useCache: false, filterResults: false }); $("#toggle").click(function() { $("#hide").toggle(); // To test repositioning }); }); </script> </head> <body> <h1>jQuery autocomplete</h1> <p class="info">This demo is built around a list of English bird names. For example, start typing <i>falcon</i> in one of the boxes below.</p> <fieldset><legend>Debugging &amp; Testing</legend> <p id="hide">HIDE THIS</p> <p><a href="#" id="flush">Fush the cache</a></p> <p><a href="#" id="toggle">Toggle hidden block</a></p> </fieldset> <h2>Demo 1</h2> <form> <input type="text" id="ac1"> </form> <h2>Demo 2 (like demo 1, but sorted on scientific name)</h2> <form> <input type="text" id="ac2"> </form> <p><span id="last_selected"></span></p> <h2>Demo 3 (local data)</h2> <p>Local data contains <i>apricot, apple, pear, prume, Doyenné du Comice</i>.</p> <form> <input type="text" id="ac3"> </form> <h2>Demo 4 (remote data without cache)</h2> <p class="info">This demo is built around a list of English bird names. For example, start typing <i>falcon</i> in one of the boxes below.</p> <form> <input type="text" id="ac4"> </form> <p style="height: 100px" class="spacer">&nbsp;</p> <hr> </body> </html>
1051691978-clone1
demo/index.html
HTML
mit
3,632
<?php $data = array( "Great Bittern" => "Botaurus stellaris", "Little Grebe" => "Tachybaptus ruficollis", "Black-necked Grebe" => "Podiceps nigricollis", "Little Bittern" => "Ixobrychus minutus", "Black-crowned Night Heron" => "Nycticorax nycticorax", "Purple Heron" => "Ardea purpurea", "White Stork" => "Ciconia ciconia", "Spoonbill" => "Platalea leucorodia", "Red-crested Pochard" => "Netta rufina", "Common Eider" => "Somateria mollissima", "Red Kite" => "Milvus milvus", "Hen Harrier" => "Circus cyaneus", "Montagu's Harrier" => "Circus pygargus", "Black Grouse" => "Tetrao tetrix", "Grey Partridge" => "Perdix perdix", "Spotted Crake" => "Porzana porzana", "Corncrake" => "Crex crex", "Common Crane" => "Grus grus", "Avocet" => "Recurvirostra avosetta", "Stone Curlew" => "Burhinus oedicnemus", "Common Ringed Plover" => "Charadrius hiaticula", "Kentish Plover" => "Charadrius alexandrinus", "Ruff" => "Philomachus pugnax", "Common Snipe" => "Gallinago gallinago", "Black-tailed Godwit" => "Limosa limosa", "Common Redshank" => "Tringa totanus", "Sandwich Tern" => "Sterna sandvicensis", "Common Tern" => "Sterna hirundo", "Arctic Tern" => "Sterna paradisaea", "Little Tern" => "Sternula albifrons", "Black Tern" => "Chlidonias niger", "Barn Owl" => "Tyto alba", "Little Owl" => "Athene noctua", "Short-eared Owl" => "Asio flammeus", "European Nightjar" => "Caprimulgus europaeus", "Common Kingfisher" => "Alcedo atthis", "Eurasian Hoopoe" => "Upupa epops", "Eurasian Wryneck" => "Jynx torquilla", "European Green Woodpecker" => "Picus viridis", "Crested Lark" => "Galerida cristata", "White-headed Duck" => "Oxyura leucocephala", "Pale-bellied Brent Goose" => "Branta hrota", "Tawny Pipit" => "Anthus campestris", "Whinchat" => "Saxicola rubetra", "European Stonechat" => "Saxicola rubicola", "Northern Wheatear" => "Oenanthe oenanthe", "Savi's Warbler" => "Locustella luscinioides", "Sedge Warbler" => "Acrocephalus schoenobaenus", "Great Reed Warbler" => "Acrocephalus arundinaceus", "Bearded Reedling" => "Panurus biarmicus", "Red-backed Shrike" => "Lanius collurio", "Great Grey Shrike" => "Lanius excubitor", "Woodchat Shrike" => "Lanius senator", "Common Raven" => "Corvus corax", "Yellowhammer" => "Emberiza citrinella", "Ortolan Bunting" => "Emberiza hortulana", "Corn Bunting" => "Emberiza calandra", "Great Cormorant" => "Phalacrocorax carbo", "Hawfinch" => "Coccothraustes coccothraustes", "Common Shelduck" => "Tadorna tadorna", "Bluethroat" => "Luscinia svecica", "Grey Heron" => "Ardea cinerea", "Barn Swallow" => "Hirundo rustica", "Hooded Crow" => "Corvus cornix", "Dunlin" => "Calidris alpina", "Eurasian Pied Flycatcher" => "Ficedula hypoleuca", "Eurasian Nuthatch" => "Sitta europaea", "Short-toed Tree Creeper" => "Certhia brachydactyla", "Wood Lark" => "Lullula arborea", "Tree Pipit" => "Anthus trivialis", "Eurasian Hobby" => "Falco subbuteo", "Marsh Warbler" => "Acrocephalus palustris", "Wood Sandpiper" => "Tringa glareola", "Tawny Owl" => "Strix aluco", "Lesser Whitethroat" => "Sylvia curruca", "Barnacle Goose" => "Branta leucopsis", "Common Goldeneye" => "Bucephala clangula", "Western Marsh Harrier" => "Circus aeruginosus", "Common Buzzard" => "Buteo buteo", "Sanderling" => "Calidris alba", "Little Gull" => "Larus minutus", "Eurasian Magpie" => "Pica pica", "Willow Warbler" => "Phylloscopus trochilus", "Wood Warbler" => "Phylloscopus sibilatrix", "Great Crested Grebe" => "Podiceps cristatus", "Eurasian Jay" => "Garrulus glandarius", "Common Redstart" => "Phoenicurus phoenicurus", "Blue-headed Wagtail" => "Motacilla flava", "Common Swift" => "Apus apus", "Marsh Tit" => "Poecile palustris", "Goldcrest" => "Regulus regulus", "European Golden Plover" => "Pluvialis apricaria", "Eurasian Bullfinch" => "Pyrrhula pyrrhula", "Common Whitethroat" => "Sylvia communis", "Meadow Pipit" => "Anthus pratensis", "Greylag Goose" => "Anser anser", "Spotted Flycatcher" => "Muscicapa striata", "European Greenfinch" => "Carduelis chloris", "Common Greenshank" => "Tringa nebularia", "Great Spotted Woodpecker" => "Dendrocopos major", "Greater Canada Goose" => "Branta canadensis", "Mistle Thrush" => "Turdus viscivorus", "Great Black-backed Gull" => "Larus marinus", "Goosander" => "Mergus merganser", "Great Egret" => "Casmerodius albus", "Northern Goshawk" => "Accipiter gentilis", "Dunnock" => "Prunella modularis", "Stock Dove" => "Columba oenas", "Common Wood Pigeon" => "Columba palumbus", "Eurasian Woodcock" => "Scolopax rusticola", "House Sparrow" => "Passer domesticus", "Common House Martin" => "Delichon urbicum", "Red Knot" => "Calidris canutus", "Western Jackdaw" => "Corvus monedula", "Brambling" => "Fringilla montifringilla", "Northern Lapwing" => "Vanellus vanellus", "European Reed Warbler" => "Acrocephalus scirpaceus", "Lesser Black-backed Gull" => "Larus fuscus", "Little Egret" => "Egretta garzetta", "Little Stint" => "Calidris minuta", "Common Linnet" => "Carduelis cannabina", "Mute Swan" => "Cygnus olor", "Common Cuckoo" => "Cuculus canorus", "Black-headed Gull" => "Larus ridibundus", "Greater White-fronted Goose" => "Anser albifrons", "Great Tit" => "Parus major", "Redwing" => "Turdus iliacus", "Gadwall" => "Anas strepera", "Fieldfare" => "Turdus pilaris", "Tufted Duck" => "Aythya fuligula", "Crested Tit" => "Lophophanes cristatus", "Willow Tit" => "Poecile montanus", "Eurasian Coot" => "Fulica atra", "Common Blackbird" => "Turdus merula", "Smew" => "Mergus albellus", "Common Sandpiper" => "Actitis hypoleucos", "Sand Martin" => "Riparia riparia", "Purple Sandpiper" => "Calidris maritima", "Northern Pintail" => "Anas acuta", "Blue Tit" => "Cyanistes caeruleus", "European Goldfinch" => "Carduelis carduelis", "Eurasian Whimbrel" => "Numenius phaeopus", "Common Reed Bunting" => "Emberiza schoeniclus", "Eurasian Tree Sparrow" => "Passer montanus", "Rook" => "Corvus frugilegus", "European Robin" => "Erithacus rubecula", "Bar-tailed Godwit" => "Limosa lapponica", "Dark-bellied Brent Goose" => "Branta bernicla", "Eurasian Oystercatcher" => "Haematopus ostralegus", "Eurasian Siskin" => "Carduelis spinus", "Northern Shoveler" => "Anas clypeata", "Eurasian Wigeon" => "Anas penelope", "Eurasian Sparrow Hawk" => "Accipiter nisus", "Icterine Warbler" => "Hippolais icterina", "Common Starling" => "Sturnus vulgaris", "Long-tailed Tit" => "Aegithalos caudatus", "Ruddy Turnstone" => "Arenaria interpres", "Mew Gull" => "Larus canus", "Common Pochard" => "Aythya ferina", "Common Chiffchaff" => "Phylloscopus collybita", "Greater Scaup" => "Aythya marila", "Common Kestrel" => "Falco tinnunculus", "Garden Warbler" => "Sylvia borin", "Eurasian Collared Dove" => "Streptopelia decaocto", "Eurasian Skylark" => "Alauda arvensis", "Common Chaffinch" => "Fringilla coelebs", "Common Moorhen" => "Gallinula chloropus", "Water Pipit" => "Anthus spinoletta", "Mallard" => "Anas platyrhynchos", "Winter Wren" => "Troglodytes troglodytes", "Common Teal" => "Anas crecca", "Green Sandpiper" => "Tringa ochropus", "White Wagtail" => "Motacilla alba", "Eurasian Curlew" => "Numenius arquata", "Song Thrush" => "Turdus philomelos", "European Herring Gull" => "Larus argentatus", "Grey Plover" => "Pluvialis squatarola", "Carrion Crow" => "Corvus corone", "Coal Tit" => "Periparus ater", "Spotted Redshank" => "Tringa erythropus", "Blackcap" => "Sylvia atricapilla", "Egyptian Vulture" => "Neophron percnopterus", "Razorbill" => "Alca torda", "Alpine Swift" => "Apus melba", "Long-legged Buzzard" => "Buteo rufinus", "Audouin's Gull" => "Larus audouinii", "Balearic Shearwater" => "Puffinus mauretanicus", "Upland Sandpiper" => "Bartramia longicauda", "Greater Spotted Eagle" => "Aquila clanga", "Ring Ouzel" => "Turdus torquatus", "Yellow-browed Warbler" => "Phylloscopus inornatus", "Blue Rock Thrush" => "Monticola solitarius", "Buff-breasted Sandpiper" => "Tryngites subruficollis", "Jack Snipe" => "Lymnocryptes minimus", "White-rumped Sandpiper" => "Calidris fuscicollis", "Ruddy Shelduck" => "Tadorna ferruginea", "Cetti's Warbler" => "Cettia cetti", "Citrine Wagtail" => "Motacilla citreola", "Roseate Tern" => "Sterna dougallii", "Black-legged Kittiwake" => "Rissa tridactyla", "Pygmy Cormorant" => "Phalacrocorax pygmeus", "Booted Eagle" => "Aquila pennata", "Lesser White-fronted Goose" => "Anser erythropus", "Little Bunting" => "Emberiza pusilla", "Eleonora's Falcon" => "Falco eleonorae", "European Serin" => "Serinus serinus", "Twite" => "Carduelis flavirostris", "Yellow-legged Gull" => "Larus michahellis", "Gyr Falcon" => "Falco rusticolus", "Greenish Warbler" => "Phylloscopus trochiloides", "Red-necked Phalarope" => "Phalaropus lobatus", "Mealy Redpoll" => "Carduelis flammea", "Glaucous Gull" => "Larus hyperboreus", "Great Skua" => "Stercorarius skua", "Great Bustard" => "Otis tarda", "Velvet Scoter" => "Melanitta fusca", "Pine Grosbeak" => "Pinicola enucleator", "House Crow" => "Corvus splendens", "Hume's Leaf Warbler" => "Phylloscopus humei", "Great Northern Loon" => "Gavia immer", "Long-tailed Duck" => "Clangula hyemalis", "Lapland Longspur" => "Calcarius lapponicus", "Northern Gannet" => "Morus bassanus", "Eastern Imperial Eagle" => "Aquila heliaca", "Little Auk" => "Alle alle", "Lesser Spotted Woodpecker" => "Dendrocopos minor", "Iceland Gull" => "Larus glaucoides", "Parasitic Jaeger" => "Stercorarius parasiticus", "Bewick's Swan" => "Cygnus bewickii", "Little Bustard" => "Tetrax tetrax", "Little Crake" => "Porzana parva", "Baillon's Crake" => "Porzana pusilla", "Long-tailed Jaeger" => "Stercorarius longicaudus", "King Eider" => "Somateria spectabilis", "Greater Short-toed Lark" => "Calandrella brachydactyla", "Houbara Bustard" => "Chlamydotis undulata", "Curlew Sandpiper" => "Calidris ferruginea", "Common Crossbill" => "Loxia curvirostra", "European Shag" => "Phalacrocorax aristotelis", "Horned Grebe" => "Podiceps auritus", "Common Quail" => "Coturnix coturnix", "Bearded Vulture" => "Gypaetus barbatus", "Lanner Falcon" => "Falco biarmicus", "Middle Spotted Woodpecker" => "Dendrocopos medius", "Pomarine Jaeger" => "Stercorarius pomarinus", "Red-breasted Merganser" => "Mergus serrator", "Eurasian Black Vulture" => "Aegypius monachus", "Eurasian Dotterel" => "Charadrius morinellus", "Common Nightingale" => "Luscinia megarhynchos", "Northern willow warbler" => "Phylloscopus trochilus acredula", "Manx Shearwater" => "Puffinus puffinus", "Northern Fulmar" => "Fulmarus glacialis", "Eurasian Eagle Owl" => "Bubo bubo", "Orphean Warbler" => "Sylvia hortensis", "Melodious Warbler" => "Hippolais polyglotta", "Pallas's Leaf Warbler" => "Phylloscopus proregulus", "Atlantic Puffin" => "Fratercula arctica", "Black-throated Loon" => "Gavia arctica", "Bohemian Waxwing" => "Bombycilla garrulus", "Marsh Sandpiper" => "Tringa stagnatilis", "Great Snipe" => "Gallinago media", "Squacco Heron" => "Ardeola ralloides", "Long-eared Owl" => "Asio otus", "Caspian Tern" => "Hydroprogne caspia", "Red-breasted Goose" => "Branta ruficollis", "Red-throated Loon" => "Gavia stellata", "Common Rosefinch" => "Carpodacus erythrinus", "Red-footed Falcon" => "Falco vespertinus", "Ross's Goose" => "Anser rossii", "Red Phalarope" => "Phalaropus fulicarius", "Pied Wagtail" => "Motacilla yarrellii", "Rose-coloured Starling" => "Sturnus roseus", "Rough-legged Buzzard" => "Buteo lagopus", "Saker Falcon" => "Falco cherrug", "European Roller" => "Coracias garrulus", "Short-toed Eagle" => "Circaetus gallicus", "Peregrine Falcon" => "Falco peregrinus", "Merlin" => "Falco columbarius", "Snow Goose" => "Anser caerulescens", "Snowy Owl" => "Bubo scandiacus", "Snow Bunting" => "Plectrophenax nivalis", "Common Grasshopper Warbler" => "Locustella naevia", "Golden Eagle" => "Aquila chrysaetos", "Black-winged Stilt" => "Himantopus himantopus", "Steppe Eagle" => "Aquila nipalensis", "Pallid Harrier" => "Circus macrourus", "European Storm-petrel" => "Hydrobates pelagicus", "Horned Lark" => "Eremophila alpestris", "Eurasian Treecreeper" => "Certhia familiaris", "Taiga Bean Goose" => "Anser fabalis", "Temminck's Stint" => "Calidris temminckii", "Terek Sandpiper" => "Xenus cinereus", "Tundra Bean Goose" => "Anser serrirostris", "European Turtle Dove" => "Streptopelia turtur", "Leach's Storm-petrel" => "Oceanodroma leucorhoa", "Eurasian Griffon Vulture" => "Gyps fulvus", "Paddyfield Warbler" => "Acrocephalus agricola", "Osprey" => "Pandion haliaetus", "Firecrest" => "Regulus ignicapilla", "Water Rail" => "Rallus aquaticus", "European Honey Buzzard" => "Pernis apivorus", "Eurasian Golden Oriole" => "Oriolus oriolus", "Whooper Swan" => "Cygnus cygnus", "Two-barred Crossbill" => "Loxia leucoptera", "White-tailed Eagle" => "Haliaeetus albicilla", "Atlantic Murre" => "Uria aalge", "Garganey" => "Anas querquedula", "Black Redstart" => "Phoenicurus ochruros", "Common Scoter" => "Melanitta nigra", "Rock Pipit" => "Anthus petrosus", "Lesser Spotted Eagle" => "Aquila pomarina", "Cattle Egret" => "Bubulcus ibis", "White-winged Black Tern" => "Chlidonias leucopterus", "Black Stork" => "Ciconia nigra", "Mediterranean Gull" => "Larus melanocephalus", "Black Kite" => "Milvus migrans", "Yellow Wagtail" => "Motacilla flavissima", "Red-necked Grebe" => "Podiceps grisegena", "Gull-billed Tern" => "Gelochelidon nilotica", "Pectoral Sandpiper" => "Calidris melanotos", "Barred Warbler" => "Sylvia nisoria", "Red-throated Pipit" => "Anthus cervinus", "Grey Wagtail" => "Motacilla cinerea", "Richard's Pipit" => "Anthus richardi", "Black Woodpecker" => "Dryocopus martius", "Little Ringed Plover" => "Charadrius dubius", "Whiskered Tern" => "Chlidonias hybrida", "Lesser Redpoll" => "Carduelis cabaret", "Pallas's Bunting" => "Emberiza pallasi", "Ferruginous Duck" => "Aythya nyroca", "Whistling Swan" => "Cygnus columbianus", "Black Brant" => "Branta nigricans", "Marbled Teal" => "Marmaronetta angustirostris", "Canvasback" => "Aythya valisineria", "Redhead" => "Aythya americana", "Lesser Scaup" => "Aythya affinis", "Steller's Eider" => "Polysticta stelleri", "Spectacled Eider" => "Somateria fischeri", "Harlequin Duck" => "Histronicus histrionicus", "Black Scoter" => "Melanitta americana", "Surf Scoter" => "Melanitta perspicillata", "Barrow's Goldeneye" => "Bucephala islandica", "Falcated Duck" => "Anas falcata", "American Wigeon" => "Anas americana", "Blue-winged Teal" => "Anas discors", "American Black Duck" => "Anas rubripes", "Baikal Teal" => "Anas formosa", "Green-Winged Teal" => "Anas carolinensis", "Hazel Grouse" => "Bonasa bonasia", "Rock Partridge" => "Alectoris graeca", "Red-legged Partridge" => "Alectoris rufa", "Yellow-billed Loon" => "Gavia adamsii", "Cory's Shearwater" => "Calonectris borealis", "Madeiran Storm-Petrel" => "Oceanodroma castro", "Great White Pelican" => "Pelecanus onocrotalus", "Dalmatian Pelican" => "Pelecanus crispus", "American Bittern" => "Botaurus lentiginosus", "Glossy Ibis" => "Plegadis falcinellus", "Spanish Imperial Eagle" => "Aquila adalberti", "Lesser Kestrel" => "Falco naumanni", "Houbara Bustard" => "Chlamydotis undulata", "Crab-Plover" => "Dromas ardeola", "Cream-coloured Courser" => "Cursorius cursor", "Collared Pratincole" => "Glareola pratincola", "Black-winged Pratincole" => "Glareola nordmanni", "Killdeer" => "Charadrius vociferus", "Lesser Sand Plover" => "Charadrius mongolus", "Greater Sand Plover" => "Charadrius leschenaultii", "Caspian Plover" => "Charadrius asiaticus", "American Golden Plover" => "Pluvialis dominica", "Pacific Golden Plover" => "Pluvialis fulva", "Sharp-tailed Sandpiper" => "Calidris acuminata", "Broad-billed Sandpiper" => "Limicola falcinellus", "Spoon-Billed Sandpiper" => "Eurynorhynchus pygmaeus", "Short-Billed Dowitcher" => "Limnodromus griseus", "Long-billed Dowitcher" => "Limnodromus scolopaceus", "Hudsonian Godwit" => "Limosa haemastica", "Little Curlew" => "Numenius minutus", "Lesser Yellowlegs" => "Tringa flavipes", "Wilson's Phalarope" => "Phalaropus tricolor", "Pallas's Gull" => "Larus ichthyaetus", "Laughing Gull" => "Larus atricilla", "Franklin's Gull" => "Larus pipixcan", "Bonaparte's Gull" => "Larus philadelphia", "Ring-billed Gull" => "Larus delawarensis", "American Herring Gull" => "Larus smithsonianus", "Caspian Gull" => "Larus cachinnans", "Ivory Gull" => "Pagophila eburnea", "Royal Tern" => "Sterna maxima", "Br¸nnich's Murre" => "Uria lomvia", "Crested Auklet" => "Aethia cristatella", "Parakeet Auklet" => "Cyclorrhynchus psittacula", "Tufted Puffin" => "Lunda cirrhata", "Laughing Dove" => "Streptopelia senegalensis", "Great Spotted Cuckoo" => "Clamator glandarius", "Great Grey Owl" => "Strix nebulosa", "Tengmalm's Owl" => "Aegolius funereus", "Red-Necked Nightjar" => "Caprimulgus ruficollis", "Chimney Swift" => "Chaetura pelagica", "Green Bea-Eater" => "Merops orientalis", "Grey-headed Woodpecker" => "Picus canus", "Lesser Short-Toed Lark" => "Calandrella rufescens", "Eurasian Crag Martin" => "Hirundo rupestris", "Red-rumped Swallow" => "Cecropis daurica", "Blyth's Pipit" => "Anthus godlewskii", "Pechora Pipit" => "Anthus gustavi", "Grey-headed Wagtail" => "Motacilla thunbergi", "Yellow-Headed Wagtail" => "Motacilla lutea", "White-throated Dipper" => "Cinclus cinclus", "Rufous-Tailed Scrub Robin" => "Cercotrichas galactotes", "Thrush Nightingale" => "Luscinia luscinia", "White-throated Robin" => "Irania gutturalis", "Caspian Stonechat" => "Saxicola maura variegata", "Western Black-eared Wheatear" => "Oenanthe hispanica", "Rufous-tailed Rock Thrush" => "Monticola saxatilis", "Red-throated Thrush/Black-throated" => "Turdus ruficollis", "American Robin" => "Turdus migratorius", "Zitting Cisticola" => "Cisticola juncidis", "Lanceolated Warbler" => "Locustella lanceolata", "River Warbler" => "Locustella fluviatilis", "Blyth's Reed Warbler" => "Acrocephalus dumetorum", "Caspian Reed Warbler" => "Acrocephalus fuscus", "Aquatic Warbler" => "Acrocephalus paludicola", "Booted Warbler" => "Acrocephalus caligatus", "Marmora's Warbler" => "Sylvia sarda", "Dartford Warbler" => "Sylvia undata", "Subalpine Warbler" => "Sylvia cantillans", "MÈnÈtries's Warbler" => "Sylvia mystacea", "R¸ppel's Warbler" => "Sylvia rueppelli", "Asian Desert Warbler" => "Sylvia nana", "Western Orphean Warbler" => "Sylvia hortensis hortensis", "Arctic Warbler" => "Phylloscopus borealis", "Radde's Warbler" => "Phylloscopus schwarzi", "Western Bonelli's Warbler" => "Phylloscopus bonelli", "Red-breasted Flycatcher" => "Ficedula parva", "Eurasian Penduline Tit" => "Remiz pendulinus", "Daurian Shrike" => "Lanius isabellinus", "Long-Tailed Shrike" => "Lanius schach", "Lesser Grey Shrike" => "Lanius minor", "Southern Grey Shrike" => "Lanius meridionalis", "Masked Shrike" => "Lanius nubicus", "Spotted Nutcracker" => "Nucifraga caryocatactes", "Daurian Jackdaw" => "Corvus dauuricus", "Purple-Backed Starling" => "Sturnus sturninus", "Red-Fronted Serin" => "Serinus pusillus", "Arctic Redpoll" => "Carduelis hornemanni", "Scottish Crossbill" => "Loxia scotica", "Parrot Crossbill" => "Loxia pytyopsittacus", "Black-faced Bunting" => "Emberiza spodocephala", "Pink-footed Goose" => "Anser brachyrhynchus", "Black-winged Kite" => "Elanus caeruleus", "European Bee-eater" => "Merops apiaster", "Sabine's Gull" => "Larus sabini", "Sooty Shearwater" => "Puffinus griseus", "Lesser Canada Goose" => "Branta hutchinsii", "Ring-necked Duck" => "Aythya collaris", "Greater Flamingo" => "Phoenicopterus roseus", "Iberian Chiffchaff" => "Phylloscopus ibericus", "Ashy-headed Wagtail" => "Motacilla cinereocapilla", "Stilt Sandpiper" => "Calidris himantopus", "Siberian Stonechat" => "Saxicola maurus", "Greater Yellowlegs" => "Tringa melanoleuca", "Forster's Tern" => "Sterna forsteri", "Dusky Warbler" => "Phylloscopus fuscatus", "Cirl Bunting" => "Emberiza cirlus", "Olive-backed Pipit" => "Anthus hodgsoni", "Sociable Lapwing" => "Vanellus gregarius", "Spotted Sandpiper" => "Actitis macularius", "Baird's Sandpiper" => "Calidris bairdii", "Rustic Bunting" => "Emberiza rustica", "Yellow-browed Bunting" => "Emberiza chrysophrys", "Great Shearwater" => "Puffinus gravis", "Bonelli's Eagle" => "Aquila fasciata", "Calandra Lark" => "Melanocorypha calandra", "Sardinian Warbler" => "Sylvia melanocephala", "Ross's Gull" => "Larus roseus", "Yellow-Breasted Bunting" => "Emberiza aureola", "Pine Bunting" => "Emberiza leucocephalos", "Black Guillemot" => "Cepphus grylle", "Pied-billed Grebe" => "Podilymbus podiceps", "Soft-plumaged Petrel" => "Pterodroma mollis", "Bulwer's Petrel" => "Bulweria bulwerii", "White-Faced Storm-Petrel" => "Pelagodroma marina", "Pallas's Fish Eagle" => "Haliaeetus leucoryphus", "Sandhill Crane" => "Grus canadensis", "Macqueenís Bustard" => "Chlamydotis macqueenii", "White-tailed Lapwing" => "Vanellus leucurus", "Great Knot" => "Calidris tenuirostris", "Semipalmated Sandpiper" => "Calidris pusilla", "Red-necked Stint" => "Calidris ruficollis", "Slender-billed Curlew" => "Numenius tenuirostris", "Bridled Tern" => "Onychoprion anaethetus", "Pallas's Sandgrouse" => "Syrrhaptes paradoxus", "European Scops Owl" => "Otus scops", "Northern Hawk Owl" => "Surnia ulula", "White-Throated Needletail" => "Hirundapus caudacutus", "Belted Kingfisher" => "Ceryle alcyon", "Blue-cheeked Bee-eater" => "Merops persicus", "Black-headed Wagtail" => "Motacilla feldegg", "Northern Mockingbird" => "Mimus polyglottos", "Alpine Accentor" => "Prunella collaris", "Red-flanked Bluetail" => "Tarsiger cyanurus", "Isabelline Wheatear" => "Oenanthe isabellina", "Pied Wheatear" => "Oenanthe pleschanka", "Eastern Black-eared Wheatear" => "Oenanthe melanoleuca", "Desert Wheatear" => "Oenanthe deserti", "White's Thrush" => "Zoothera aurea", "Siberian Thrush" => "Zoothera sibirica", "Eyebrowed Thrush" => "Turdus obscurus", "Dusky Thrush" => "Turdus eunomus", "Black-throated Thrush" => "Turdus atrogularis", "Pallas's Grasshopper Warbler" => "Locustella certhiola", "Spectacled Warbler" => "Sylvia conspicillata", "Two-barred Warbler" => "Phylloscopus plumbeitarsus", "Eastern Bonelli's Warbler" => "Phylloscopus orientalis", "Collared Flycatcher" => "Ficedula albicollis", "Wallcreeper" => "Tichodroma muraria", "Turkestan Shrike" => "Lanius phoenicuroides", "Steppe Grey Shrike" => "Lanius pallidirostris", "Spanish Sparrow" => "Passer hispaniolensis", "Red-eyed Vireo" => "Vireo olivaceus", "Myrtle Warbler" => "Dendroica coronata", "White-crowned Sparrow" => "Zonotrichia leucophrys", "White-throated Sparrow" => "Zonotrichia albicollis", "Cretzschmar's Bunting" => "Emberiza caesia", "Chestnut Bunting" => "Emberiza rutila", "Red-headed Bunting" => "Emberiza bruniceps", "Black-headed Bunting" => "Emberiza melanocephala", "Indigo Bunting" => "Passerina cyanea", "Balearic Woodchat Shrike" => "Lanius senator badius", "Demoiselle Crane" => "Grus virgo", "Chough" => "Pyrrhocorax pyrrhocorax", "Red-Billed Chough" => "Pyrrhocorax graculus", "Elegant Tern" => "Sterna elegans", "Chukar" => "Alectoris chukar", "Yellow-Billed Cuckoo" => "Coccyzus americanus", "American Sandwich Tern" => "Sterna sandvicensis acuflavida", "Olive-Tree Warbler" => "Hippolais olivetorum", "Eastern Olivaceous Warbler" => "Acrocephalus pallidus", "Indian Cormorant" => "Phalacrocorax fuscicollis", "Spur-Winged Lapwing" => "Vanellus spinosus", "Yelkouan Shearwater" => "Puffinus yelkouan", "Trumpeter Finch" => "Bucanetes githagineus", "Red Grouse" => "Lagopus scoticus", "Rock Ptarmigan" => "Lagopus mutus", "Long-Tailed Cormorant" => "Phalacrocorax africanus", "Double-crested Cormorant" => "Phalacrocorax auritus", "Magnificent Frigatebird" => "Fregata magnificens", "Naumann's Thrush" => "Turdus naumanni", "Oriental Pratincole" => "Glareola maldivarum", "Bufflehead" => "Bucephala albeola", "Snowfinch" => "Montifrigilla nivalis", "Ural owl" => "Strix uralensis", "Spanish Wagtail" => "Motacilla iberiae", "Song Sparrow" => "Melospiza melodia", "Rock Bunting" => "Emberiza cia", "Siberian Rubythroat" => "Luscinia calliope", "Pallid Swift" => "Apus pallidus", "Eurasian Pygmy Owl" => "Glaucidium passerinum", "Madeira Little Shearwater" => "Puffinus baroli", "House Finch" => "Carpodacus mexicanus", "Green Heron" => "Butorides virescens", "Solitary Sandpiper" => "Tringa solitaria", "Heuglin's Gull" => "Larus heuglini" );
1051691978-clone1
demo/data.php
PHP
mit
26,402
package vcard.io; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteStatement; import android.os.Binder; import android.os.IBinder; import android.provider.Contacts; import android.widget.Toast; public class VCardIO extends Service { static final String DATABASE_NAME = "syncdata.db"; static final String SYNCDATA_TABLE_NAME = "sync"; static final String PERSONID = "person"; static final String SYNCID = "syncid"; private static final int DATABASE_VERSION = 1; private NotificationManager mNM; final Object syncMonitor = "SyncMonitor"; String syncFileName; enum Action { IDLE, IMPORT, EXPORT }; /** * 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 " + SYNCDATA_TABLE_NAME + " (" + PERSONID + " INTEGER PRIMARY KEY," + SYNCID + " TEXT UNIQUE" +");"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // No need to do anything --- this is version 1 } } private DatabaseHelper mOpenHelper; Action mAction; public class LocalBinder extends Binder { VCardIO getService() { return VCardIO.this; } } @Override public IBinder onBind(Intent intent) { return mBinder; } // This is the object that receives interactions from clients. See // RemoteService for a more complete example. private final IBinder mBinder = new LocalBinder(); @Override public void onCreate() { mOpenHelper = new DatabaseHelper(getApplicationContext()); mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE); mAction = Action.IDLE; // Display a notification about us starting. We put an icon in the status bar. showNotification(); } @Override public void onDestroy() { // Cancel the persistent notification. mNM.cancelAll(); synchronized (syncMonitor) { switch (mAction) { case IMPORT: // Tell the user we stopped. Toast.makeText(this, "VCard import aborted ("+syncFileName +")", Toast.LENGTH_SHORT).show(); break; case EXPORT: // Tell the user we stopped. Toast.makeText(this, "VCard export aborted ("+syncFileName +")", Toast.LENGTH_SHORT).show(); break; default: break; } mAction = Action.IDLE; } } /** * Show a notification while this service is running. */ private void showNotification() { // In this sample, we'll use the same text for the ticker and the expanded notification String text = null; String detailedText = ""; synchronized (syncMonitor) { switch (mAction) { case IMPORT: text = (String) getText(R.string.importServiceMsg); detailedText = "Importing VCards from " + syncFileName; break; case EXPORT: text = (String) getText(R.string.exportServiceMsg); detailedText = "Exporting VCards from " + syncFileName; break; default: break; } } if (text == null) { mNM.cancelAll(); } else { // Set the icon, scrolling text and timestamp Notification notification = new Notification(R.drawable.status_icon, text, System.currentTimeMillis()); // The PendingIntent to launch our activity if the user selects this notification PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, App.class), 0); // Set the info for the views that show in the notification panel. notification.setLatestEventInfo(this, "VCard IO", detailedText, contentIntent); // Send the notification. // We use a layout id because it is a unique number. We use it later to cancel. mNM.notify(R.string.app_name, notification); } } public void doImport(final String fileName, final boolean replace, final App app) { try { File vcfFile = new File(fileName); final BufferedReader vcfBuffer = new BufferedReader(new FileReader(fileName)); final long maxlen = vcfFile.length(); // Start lengthy operation in a background thread new Thread(new Runnable() { public void run() { long importStatus = 0; synchronized (syncMonitor) { mAction = Action.IMPORT; syncFileName = fileName; } showNotification(); SQLiteDatabase db = mOpenHelper.getWritableDatabase(); SQLiteStatement querySyncId = db.compileStatement("SELECT " + SYNCID + " FROM " + SYNCDATA_TABLE_NAME + " WHERE " + PERSONID + "=?"); SQLiteStatement queryPersonId = db.compileStatement("SELECT " + PERSONID + " FROM " + SYNCDATA_TABLE_NAME + " WHERE " + SYNCID + "=?"); SQLiteStatement insertSyncId = db.compileStatement("INSERT INTO " + SYNCDATA_TABLE_NAME + " (" + PERSONID + "," + SYNCID + ") VALUES (?,?)"); Contact parseContact = new Contact(querySyncId, queryPersonId, insertSyncId); try { long ret = 0; do { ret = parseContact.parseVCard(vcfBuffer); if (ret >= 0) { parseContact.addContact(getApplicationContext(), 0, replace); importStatus += parseContact.getParseLen(); // Update the progress bar app.updateProgress((int) (100 * importStatus / maxlen)); } } while (ret > 0); db.close(); app.updateProgress(100); synchronized (syncMonitor) { mAction = Action.IDLE; showNotification(); } stopSelf(); } catch (IOException e) { } } }).start(); } catch (FileNotFoundException e) { app.updateStatus("File not found: " + e.getMessage()); } } public void doExport(final String fileName, final App app) { try { final BufferedWriter vcfBuffer = new BufferedWriter(new FileWriter(fileName)); final ContentResolver cResolver = getContentResolver(); final Cursor allContacts = cResolver.query(Contacts.People.CONTENT_URI, null, null, null, null); if (allContacts == null || !allContacts.moveToFirst()) { app.updateStatus("No contacts found"); allContacts.close(); return; } final long maxlen = allContacts.getCount(); // Start lengthy operation in a background thread new Thread(new Runnable() { public void run() { long exportStatus = 0; synchronized (syncMonitor) { mAction = Action.EXPORT; syncFileName = fileName; } showNotification(); SQLiteDatabase db = mOpenHelper.getWritableDatabase(); SQLiteStatement querySyncId = db.compileStatement("SELECT " + SYNCID + " FROM " + SYNCDATA_TABLE_NAME + " WHERE " + PERSONID + "=?"); SQLiteStatement queryPersonId = db.compileStatement("SELECT " + PERSONID + " FROM " + SYNCDATA_TABLE_NAME + " WHERE " + SYNCID + "=?"); SQLiteStatement insertSyncId = db.compileStatement("INSERT INTO " + SYNCDATA_TABLE_NAME + " (" + PERSONID + "," + SYNCID + ") VALUES (?,?)"); Contact parseContact = new Contact(querySyncId, queryPersonId, insertSyncId); try { boolean hasNext = true; do { parseContact.populate(allContacts, cResolver); parseContact.writeVCard(vcfBuffer); ++exportStatus; // Update the progress bar app.updateProgress((int) (100 * exportStatus / maxlen)); hasNext = allContacts.moveToNext(); } while (hasNext); vcfBuffer.close(); db.close(); app.updateProgress(100); synchronized (syncMonitor) { mAction = Action.IDLE; showNotification(); } stopSelf(); } catch (IOException e) { app.updateStatus("Write error: " + e.getMessage()); } } }).start(); } catch (IOException e) { app.updateStatus("Error opening file: " + e.getMessage()); } } }
00piknik00-vardio
src/vcard/io/VCardIO.java
Java
gpl3
9,483
package vcard.io; import java.io.IOException; /** * A Base64 Encoder/Decoder. * * <p> * This class is used to encode and decode data in Base64 format as described in RFC 1521. * * <p> * This is "Open Source" software and released under the <a href="http://www.gnu.org/licenses/lgpl.html">GNU/LGPL</a> license.<br> * It is provided "as is" without warranty of any kind.<br> * Copyright 2003: Christian d'Heureuse, Inventec Informatik AG, Switzerland.<br> * Home page: <a href="http://www.source-code.biz">www.source-code.biz</a><br> * * <p> * Version history:<br> * 2003-07-22 Christian d'Heureuse (chdh): Module created.<br> * 2005-08-11 chdh: Lincense changed from GPL to LGPL.<br> * 2006-11-21 chdh:<br> * &nbsp; Method encode(String) renamed to encodeString(String).<br> * &nbsp; Method decode(String) renamed to decodeString(String).<br> * &nbsp; New method encode(byte[],int) added.<br> * &nbsp; New method decode(String) added.<br> * 2009-02-25 ducktayp:<br> * &nbsp; New method mimeEncode(Appendable, byte[], int, String) for creating mime-compatible output.<br> * &nbsp; New method decodeInPlace(StringBuffer) for whitespace-tolerant decoding without allocating memory.<br> */ public class Base64Coder { // Mapping table from 6-bit nibbles to Base64 characters. private static char[] map1 = new char[64]; static { int i=0; for (char c='A'; c<='Z'; c++) map1[i++] = c; for (char c='a'; c<='z'; c++) map1[i++] = c; for (char c='0'; c<='9'; c++) map1[i++] = c; map1[i++] = '+'; map1[i++] = '/'; } // Mapping table from Base64 characters to 6-bit nibbles. private static byte[] map2 = new byte[128]; static { for (int i=0; i<map2.length; i++) map2[i] = -1; for (int i=0; i<64; i++) map2[map1[i]] = (byte)i; } /** * Encodes a byte array into Base64 format. * A separator is inserted after every linelength chars * @param out an StringBuffer into which output is appended. * @param in an array containing the data bytes to be encoded. * @param linelength number of characters per line * @param sep Separator placed every linelength characters. * */ public static void mimeEncode(Appendable out, byte[] in, int linelength, String sep) throws IOException { int pos = 0; int bits = 0; int val = 0; for (byte b : in) { val <<= 8; val |= ((int) b) & 0xff; bits += 8; if (bits == 24) { for (int i = 0; i < 4; ++i) { out.append((char) map1[(val >>> 18) & 0x3f]); val <<= 6; pos++; if (pos % linelength == 0) { out.append(sep); } } bits = 0; val = 0; } } int pad = (3 - (bits / 8)) % 3; while (bits > 0) { out.append((char) map1[(val >>> 18) & 0x3f]); val <<= 6; bits -= 6; pos++; if (pos % linelength == 0) { out.append(sep); } } while (pad-- > 0) out.append('='); } /** * Decodes data in Base64 format in a StringBuffer. * Whitespace and invalid characters are ignored in the Base64 encoded data; * @param inout a StringBuffer containing the Base64 encoded data; Buffer is modified to contain decoded data (one byte per char) * @return new length of the StringBuffer */ public static int decodeInPlace (StringBuffer inout) { final int n = inout.length(); int pos = 0; // Writer position int val = 0; // Current byte contents int pad = 0; // Number of padding chars int bits = 0; // Number of bits decoded in val for (int i = 0; i < n; ++i) { char ch = inout.charAt(i); switch (ch) { case ' ': case '\t': case '\n': case '\r': continue; // whitespace case '=': // Padding ++pad; ch = 'A'; default: if (ch > 127) continue; // invalid char int ch2 = map2[ch]; if (ch2 < 0) continue; // invalid char // Shift val and put decoded bits into val's MSB val <<= 6; val |= ch2; bits += 6; // If we have 24 bits write them out. if (bits == 24) { bits -= 8 * pad; pad = 0; while (bits > 0) { inout.setCharAt(pos++, (char) ((val >>> 16) & 0xff)); val <<= 8; bits -= 8; } val = 0; } } } inout.setLength(pos); return pos; } // Dummy constructor. private Base64Coder() {} } // end class Base64Coder
00piknik00-vardio
src/vcard/io/Base64Coder.java
Java
gpl3
4,368
package vcard.io; import android.app.Activity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.view.View; import android.view.Window; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class App extends Activity { /** Called when the activity is first created. */ boolean isActive; Handler mHandler = new Handler(); VCardIO mBoundService = null; int mLastProgress; TextView mStatusText = null; CheckBox mReplaceOnImport = null; @Override protected void onPause() { isActive = false; super.onPause(); } @Override protected void onResume() { super.onResume(); isActive = true; updateProgress(mLastProgress); } protected void updateProgress(final int progress) { // Update the progress bar mHandler.post(new Runnable() { public void run() { if (isActive) { setProgress(progress * 100); if (progress == 100) mStatusText.setText("Done"); } else { mLastProgress = progress; } } }); } void updateStatus(final String status) { // Update the progress bar mHandler.post(new Runnable() { public void run() { if (isActive) { mStatusText.setText(status); } } }); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Request the progress bar to be shown in the title requestWindowFeature(Window.FEATURE_PROGRESS); setProgress(10000); // Turn it off for now setContentView(R.layout.main); Button importButton = (Button) findViewById(R.id.ImportButton); Button exportButton = (Button) findViewById(R.id.ExportButton); mStatusText = ((TextView) findViewById(R.id.StatusText)); mReplaceOnImport = ((CheckBox) findViewById(R.id.ReplaceOnImport)); final Intent app = new Intent(App.this, VCardIO.class); OnClickListener listenImport = new OnClickListener() { public void onClick(View v) { // Make sure the service is started. It will continue running // until someone calls stopService(). The Intent we use to find // the service explicitly specifies our service component, because // we want it running in our own process and don't want other // applications to replace it. if (mBoundService != null) { String fileName = ((EditText) findViewById(R.id.ImportFile)).getText().toString(); // Update the progress bar setProgress(0); mStatusText.setText("Importing Contacts..."); // Start the import mBoundService.doImport(fileName, mReplaceOnImport.isChecked(), App.this); } } }; OnClickListener listenExport = new OnClickListener() { public void onClick(View v) { // Make sure the service is started. It will continue running // until someone calls stopService(). The Intent we use to find // the service explicitly specifies our service component, because // we want it running in our own process and don't want other // applications to replace it. if (mBoundService != null) { String fileName = ((EditText) findViewById(R.id.ExportFile)).getText().toString(); // Update the progress bar setProgress(0); mStatusText.setText("Exporting Contacts..."); // Start the import mBoundService.doExport(fileName, App.this); } } }; // Start the service using startService so it won't be stopped when activity is in background. startService(app); bindService(app, mConnection, Context.BIND_AUTO_CREATE); importButton.setOnClickListener(listenImport); exportButton.setOnClickListener(listenExport); } private ServiceConnection mConnection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder service) { // This is called when the connection with the service has been // established, giving us the service object we can use to // interact with the service. Because we have bound to a explicit // service that we know is running in our own process, we can // cast its IBinder to a concrete class and directly access it. mBoundService = ((VCardIO.LocalBinder)service).getService(); // Tell the user about this for our demo. Toast.makeText(App.this, "Connected to VCard IO Service", Toast.LENGTH_SHORT).show(); } public void onServiceDisconnected(ComponentName className) { // This is called when the connection with the service has been // unexpectedly disconnected -- that is, its process crashed. // Because it is running in our same process, we should never // see this happen. mBoundService = null; Toast.makeText(App.this, "Disconnected from VCard IO!", Toast.LENGTH_SHORT).show(); } }; }
00piknik00-vardio
src/vcard/io/App.java
Java
gpl3
5,492
/* * Funambol is a mobile platform developed by Funambol, Inc. * Copyright (C) 2003 - 2007 Funambol, Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by * the Free Software Foundation with the addition of the following permission * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * 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 Affero General Public License * along with this program; if not, see http://www.gnu.org/licenses or write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA. * * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License * version 3, these Appropriate Legal Notices must retain the display of the * "Powered by Funambol" logo. If the display of the logo is not reasonably * feasible for technical reasons, the Appropriate Legal Notices must display * the words "Powered by Funambol". * * 2009-02-25 ducktayp: Modified to parse and format more Vcard fields, including PHOTO. * No attempt was made to preserve compatibility with previous code. * */ package vcard.io; import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import java.util.UUID; import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDoneException; import android.database.sqlite.SQLiteStatement; import android.net.Uri; import android.net.Uri.Builder; import android.provider.Contacts; import android.provider.Contacts.ContactMethodsColumns; import com.funambol.util.Log; import com.funambol.util.QuotedPrintable; import com.funambol.util.StringUtil; /** * A Contact item */ public class Contact { static final String NL = "\r\n"; // Property name for Instant-message addresses static final String IMPROP = "X-IM-NICK"; // Property parameter name for custom labels static final String LABEL_PARAM = "LABEL"; // Property parameter for IM protocol static final String PROTO_PARAM = "PROTO"; // Protocol labels static final String[] PROTO = { "AIM", // ContactMethods.PROTOCOL_AIM = 0 "MSN", // ContactMethods.PROTOCOL_MSN = 1 "YAHOO", // ContactMethods.PROTOCOL_YAHOO = 2 "SKYPE", // ContactMethods.PROTOCOL_SKYPE = 3 "QQ", // ContactMethods.PROTOCOL_QQ = 4 "GTALK", // ContactMethods.PROTOCOL_GOOGLE_TALK = 5 "ICQ", // ContactMethods.PROTOCOL_ICQ = 6 "JABBER" // ContactMethods.PROTOCOL_JABBER = 7 }; long parseLen; static final String BIRTHDAY_FIELD = "Birthday:"; /** * Contact fields declaration */ // Contact identifier String _id; String syncid; // Contact displayed name String displayName; // Contact first name String firstName; // Contact last name String lastName; static class RowData { RowData(int type, String data, boolean preferred, String customLabel) { this.type = type; this.data = data; this.preferred = preferred; this.customLabel = customLabel; auxData = null; } RowData(int type, String data, boolean preferred) { this(type, data, preferred, null); } int type; String data; boolean preferred; String customLabel; String auxData; } static class OrgData { OrgData(int type, String title, String company, String customLabel) { this.type = type; this.title = title; this.company = company; this.customLabel = customLabel; } int type; // Contact title String title; // Contact company name String company; String customLabel; } // Phones dictionary; keys are android Contact Column ids List<RowData> phones; // Emails dictionary; keys are android Contact Column ids List<RowData> emails; // Address dictionary; keys are android Contact Column ids List<RowData> addrs; // Instant message addr dictionary; keys are android Contact Column ids List<RowData> ims; // Organizations list List<OrgData> orgs; // Compressed photo byte[] photo; // Contact note String notes; // Contact's birthday String birthday; Hashtable<String, handleProp> propHandlers; interface handleProp { void parseProp(final String propName, final Vector<String> propVec, final String val); } // Initializer block { reset(); propHandlers = new Hashtable<String, handleProp>(); handleProp simpleValue = new handleProp() { public void parseProp(final String propName, final Vector<String> propVec, final String val) { if (propName.equals("FN")) { displayName = val; } else if (propName.equals("NOTE")) { notes = val; } else if (propName.equals("BDAY")) { birthday = val; } else if (propName.equals("X-IRMC-LUID") || propName.equals("UID")) { syncid = val; } else if (propName.equals("N")) { String[] names = StringUtil.split(val, ";"); // We set only the first given name. // The others are ignored in input and will not be // overridden on the server in output. if (names.length >= 2) { firstName = names[1]; lastName = names[0]; } else { String[] names2 = StringUtil.split(names[0], " "); firstName = names2[0]; if (names2.length > 1) lastName = names2[1]; } } } }; propHandlers.put("FN", simpleValue); propHandlers.put("NOTE", simpleValue); propHandlers.put("BDAY", simpleValue); propHandlers.put("X-IRMC-LUID", simpleValue); propHandlers.put("UID", simpleValue); propHandlers.put("N", simpleValue); handleProp orgHandler = new handleProp() { @Override public void parseProp(String propName, Vector<String> propVec, String val) { String label = null; for (String prop : propVec) { String[] propFields = StringUtil.split(prop, "="); if (propFields[0].equalsIgnoreCase(LABEL_PARAM) && propFields.length > 1) { label = propFields[1]; } } if (propName.equals("TITLE")) { boolean setTitle = false; for (OrgData org : orgs) { if (label == null && org.customLabel != null) continue; if (label != null && !label.equals(org.customLabel)) continue; if (org.title == null) { org.title = val; setTitle = true; break; } } if (!setTitle) { orgs.add(new OrgData(label == null ? ContactMethodsColumns.TYPE_WORK : ContactMethodsColumns.TYPE_CUSTOM, val, null, label)); } } else if (propName.equals("ORG")) { String[] orgFields = StringUtil.split(val, ";"); boolean setCompany = false; for (OrgData org : orgs) { if (label == null && org.customLabel != null) continue; if (label != null && !label.equals(org.customLabel)) continue; if (org.company == null) { org.company = val; setCompany = true; break; } } if (!setCompany) { orgs.add(new OrgData(label == null ? ContactMethodsColumns.TYPE_WORK : ContactMethodsColumns.TYPE_CUSTOM, null, orgFields[0], label)); } } } }; propHandlers.put("ORG", orgHandler); propHandlers.put("TITLE", orgHandler); propHandlers.put("TEL", new handleProp() { public void parseProp(final String propName, final Vector<String> propVec, final String val) { String label = null; int subtype = Contacts.PhonesColumns.TYPE_OTHER; boolean preferred = false; for (String prop : propVec) { if (prop.equalsIgnoreCase("HOME") || prop.equalsIgnoreCase("VOICE")) { if (subtype != Contacts.PhonesColumns.TYPE_FAX_HOME) subtype = Contacts.PhonesColumns.TYPE_HOME; } else if (prop.equalsIgnoreCase("WORK")) { if (subtype == Contacts.PhonesColumns.TYPE_FAX_HOME) { subtype = Contacts.PhonesColumns.TYPE_FAX_WORK; } else subtype = Contacts.PhonesColumns.TYPE_WORK; } else if (prop.equalsIgnoreCase("CELL")) { subtype = Contacts.PhonesColumns.TYPE_MOBILE; } else if (prop.equalsIgnoreCase("FAX")) { if (subtype == Contacts.PhonesColumns.TYPE_WORK) { subtype = Contacts.PhonesColumns.TYPE_FAX_WORK; } else subtype = Contacts.PhonesColumns.TYPE_FAX_HOME; } else if (prop.equalsIgnoreCase("PAGER")) { subtype = Contacts.PhonesColumns.TYPE_PAGER; } else if (prop.equalsIgnoreCase("PREF")) { preferred = true; } else { String[] propFields = StringUtil.split(prop, "="); if (propFields.length > 1 && propFields[0].equalsIgnoreCase(LABEL_PARAM)) { label = propFields[1]; subtype = Contacts.ContactMethodsColumns.TYPE_CUSTOM; } } } phones.add(new RowData(subtype, toCanonicalPhone(val), preferred, label)); } }); propHandlers.put("ADR", new handleProp() { public void parseProp(final String propName, final Vector<String> propVec, final String val) { boolean preferred = false; String label = null; int subtype = Contacts.ContactMethodsColumns.TYPE_WORK; // vCard spec says default is WORK for (String prop : propVec) { if (prop.equalsIgnoreCase("WORK")) { subtype = Contacts.ContactMethodsColumns.TYPE_WORK; } else if (prop.equalsIgnoreCase("HOME")) { subtype = Contacts.ContactMethodsColumns.TYPE_HOME; } else if (prop.equalsIgnoreCase("PREF")) { preferred = true; } else { String[] propFields = StringUtil.split(prop, "="); if (propFields.length > 1 && propFields[0].equalsIgnoreCase(LABEL_PARAM)) { label = propFields[1]; subtype = Contacts.ContactMethodsColumns.TYPE_CUSTOM; } } } String[] addressFields = StringUtil.split(val, ";"); StringBuffer addressBuf = new StringBuffer(val.length()); if (addressFields.length > 2) { addressBuf.append(addressFields[2]); int maxLen = Math.min(7, addressFields.length); for (int i = 3; i < maxLen; ++i) { addressBuf.append(", ").append(addressFields[i]); } } String address = addressBuf.toString(); addrs.add(new RowData(subtype, address, preferred, label)); } }); propHandlers.put("EMAIL", new handleProp() { public void parseProp(final String propName, final Vector<String> propVec, final String val) { boolean preferred = false; String label = null; int subtype = Contacts.ContactMethodsColumns.TYPE_HOME; for (String prop : propVec) { if (prop.equalsIgnoreCase("PREF")) { preferred = true; } else if (prop.equalsIgnoreCase("WORK")) { subtype = Contacts.ContactMethodsColumns.TYPE_WORK; } else { String[] propFields = StringUtil.split(prop, "="); if (propFields.length > 1 && propFields[0].equalsIgnoreCase(LABEL_PARAM)) { label = propFields[1]; subtype = Contacts.ContactMethodsColumns.TYPE_CUSTOM; } } } emails.add(new RowData(subtype, val, preferred, label)); } }); propHandlers.put(IMPROP, new handleProp() { public void parseProp(final String propName, final Vector<String> propVec, final String val) { boolean preferred = false; String label = null; String proto = null; int subtype = Contacts.ContactMethodsColumns.TYPE_HOME; for (String prop : propVec) { if (prop.equalsIgnoreCase("PREF")) { preferred = true; } else if (prop.equalsIgnoreCase("WORK")) { subtype = Contacts.ContactMethodsColumns.TYPE_WORK; } else { String[] propFields = StringUtil.split(prop, "="); if (propFields.length > 1) { if (propFields[0].equalsIgnoreCase(PROTO_PARAM)) { proto = propFields[1]; } else if (propFields[0].equalsIgnoreCase(LABEL_PARAM)) { label = propFields[1]; } } } } RowData newRow = new RowData(subtype, val, preferred, label); newRow.auxData = proto; ims.add(newRow); } }); propHandlers.put("PHOTO", new handleProp() { public void parseProp(final String propName, final Vector<String> propVec, final String val) { boolean isUrl = false; photo = new byte[val.length()]; for (int i = 0; i < photo.length; ++i) photo[i] = (byte) val.charAt(i); for (String prop : propVec) { if (prop.equalsIgnoreCase("VALUE=URL")) { isUrl = true; } } if (isUrl) { // TODO: Deal with photo URLS } } }); } private void reset() { _id = null; syncid = null; parseLen = 0; displayName = null; notes = null; birthday = null; photo = null; firstName = null; lastName = null; if (phones == null) phones = new ArrayList<RowData>(); else phones.clear(); if (emails == null) emails = new ArrayList<RowData>(); else emails.clear(); if (addrs == null) addrs = new ArrayList<RowData>(); else addrs.clear(); if (orgs == null) orgs = new ArrayList<OrgData>(); else orgs.clear(); if (ims == null) ims = new ArrayList<RowData>(); else ims.clear(); } SQLiteStatement querySyncId; SQLiteStatement queryPersonId; SQLiteStatement insertSyncId; // Constructors------------------------------------------------ public Contact(SQLiteStatement querySyncId, SQLiteStatement queryPersionId, SQLiteStatement insertSyncId) { this.querySyncId = querySyncId; this.queryPersonId = queryPersionId; this.insertSyncId = insertSyncId; } public Contact(String vcard, SQLiteStatement querySyncId, SQLiteStatement queryPersionId, SQLiteStatement insertSyncId) { this(querySyncId, queryPersionId, insertSyncId); BufferedReader vcardReader = new BufferedReader(new StringReader(vcard)); try { parseVCard(vcardReader); } catch (IOException e) { e.printStackTrace(); } } public Contact(BufferedReader vcfReader, SQLiteStatement querySyncId, SQLiteStatement queryPersionId, SQLiteStatement insertSyncId) throws IOException { this(querySyncId, queryPersionId, insertSyncId); parseVCard(vcfReader); } public Contact(Cursor peopleCur, ContentResolver cResolver, SQLiteStatement querySyncId, SQLiteStatement queryPersionId, SQLiteStatement insertSyncId) { this(querySyncId, queryPersionId, insertSyncId); populate(peopleCur, cResolver); } final static Pattern[] phonePatterns = { Pattern.compile("[+](1)(\\d\\d\\d)(\\d\\d\\d)(\\d\\d\\d\\d.*)"), Pattern.compile("[+](972)(2|3|4|8|9|50|52|54|57|59|77)(\\d\\d\\d)(\\d\\d\\d\\d.*)"), }; /** * Change the phone to canonical format (with dashes, etc.) if it's in a supported country. * @param phone * @return */ String toCanonicalPhone(String phone) { for (final Pattern phonePattern : phonePatterns) { Matcher m = phonePattern.matcher(phone); if (m.matches()) { return "+" + m.group(1) + "-" + m.group(2) + "-" + m.group(3) + "-" + m.group(4); } } return phone; } /** * Set the person identifier */ public void setId(String id) { _id = id; } /** * Get the person identifier */ public long getId() { return Long.parseLong(_id); } final static Pattern beginPattern = Pattern.compile("BEGIN:VCARD",Pattern.CASE_INSENSITIVE); final static Pattern propPattern = Pattern.compile("([^:]+):(.*)"); final static Pattern propParamPattern = Pattern.compile("([^;=]+)(=([^;]+))?(;|$)"); final static Pattern base64Pattern = Pattern.compile("\\s*([a-zA-Z0-9+/]+={0,2})\\s*$"); final static Pattern namePattern = Pattern.compile("(([^,]+),(.*))|((.*?)\\s+(\\S+))"); // Parse birthday in notes final static Pattern birthdayPattern = Pattern.compile("^" + BIRTHDAY_FIELD + ":\\s*([^;]+)(;\\s*|\\s*$)",Pattern.CASE_INSENSITIVE); /** * Parse the vCard string into the contacts fields */ public long parseVCard(BufferedReader vCard) throws IOException { // Reset the currently read values. reset(); // Find Begin. String line = vCard.readLine(); if (line != null) parseLen += line.length(); else return -1; while (line != null && !beginPattern.matcher(line).matches()) { line = vCard.readLine(); parseLen += line.length(); } if (line == null) return -1; boolean skipRead = false; while (line != null) { if (!skipRead) line = vCard.readLine(); if (line == null) { return 0; } skipRead = false; // do multi-line unfolding (cr lf with whitespace immediately following is removed, joining the two lines). vCard.mark(1); for (int ch = vCard.read(); ch == (int) ' ' || ch == (int) '\t'; ch = vCard.read()) { vCard.reset(); String newLine = vCard.readLine(); if (newLine != null) line += newLine; vCard.mark(1); } vCard.reset(); parseLen += line.length(); // TODO: doesn't include CR LFs Matcher pm = propPattern.matcher(line); if (pm.matches()) { String prop = pm.group(1); String val = pm.group(2); if (prop.equalsIgnoreCase("END") && val.equalsIgnoreCase("VCARD")) { // End of vCard return parseLen; } Matcher ppm = propParamPattern.matcher(prop); if (!ppm.find()) // Doesn't seem to be a valid vCard property continue; String propName = ppm.group(1).toUpperCase(); Vector<String> propVec = new Vector<String>(); String charSet = "UTF-8"; String encoding = ""; while (ppm.find()) { String param = ppm.group(1); String paramVal = ppm.group(3); propVec.add(param + (paramVal != null ? "=" + paramVal : "")); if (param.equalsIgnoreCase("CHARSET")) charSet = paramVal; else if (param.equalsIgnoreCase("ENCODING")) encoding = paramVal; } if (encoding.equalsIgnoreCase("QUOTED-PRINTABLE")) { try { val = QuotedPrintable.decode(val.getBytes(charSet), "UTF-8"); } catch (UnsupportedEncodingException uee) { } } else if (encoding.equalsIgnoreCase("BASE64")) { StringBuffer tmpVal = new StringBuffer(val); do { line = vCard.readLine(); if ((line == null) || (line.length() == 0) || (!base64Pattern.matcher(line).matches())) { //skipRead = true; break; } tmpVal.append(line); } while (true); Base64Coder.decodeInPlace(tmpVal); val = tmpVal.toString(); } handleProp propHandler = propHandlers.get(propName); if (propHandler != null) propHandler.parseProp(propName, propVec, val); } } return 0; } public long getParseLen() { return parseLen; } /** * Format an email as a vCard field. * * @param cardBuff Formatted email will be appended to this buffer * @param email The rowdata containing the actual email data. */ public static void formatEmail(Appendable cardBuff, RowData email) throws IOException { cardBuff.append("EMAIL;INTERNET"); if (email.preferred) cardBuff.append(";PREF"); if (email.customLabel != null) { cardBuff.append(";" + LABEL_PARAM + "="); cardBuff.append(email.customLabel); } switch (email.type) { case Contacts.ContactMethodsColumns.TYPE_WORK: cardBuff.append(";WORK"); break; } if (!StringUtil.isASCII(email.data)) cardBuff.append(";CHARSET=UTF-8"); cardBuff.append(":").append(email.data.trim()).append(NL); } /** * Format a phone as a vCard field. * * @param formatted Formatted phone will be appended to this buffer * @param phone The rowdata containing the actual phone data. */ public static void formatPhone(Appendable formatted, RowData phone) throws IOException { formatted.append("TEL"); if (phone.preferred) formatted.append(";PREF"); if (phone.customLabel != null) { formatted.append(";" + LABEL_PARAM + "="); formatted.append(phone.customLabel); } switch (phone.type) { case Contacts.PhonesColumns.TYPE_HOME: formatted.append(";VOICE"); break; case Contacts.PhonesColumns.TYPE_WORK: formatted.append(";VOICE;WORK"); break; case Contacts.PhonesColumns.TYPE_FAX_WORK: formatted.append(";FAX;WORK"); break; case Contacts.PhonesColumns.TYPE_FAX_HOME: formatted.append(";FAX;HOME"); break; case Contacts.PhonesColumns.TYPE_MOBILE: formatted.append(";CELL"); break; case Contacts.PhonesColumns.TYPE_PAGER: formatted.append(";PAGER"); break; } if (!StringUtil.isASCII(phone.data)) formatted.append(";CHARSET=UTF-8"); formatted.append(":").append(phone.data.trim()).append(NL); } /** * Format a phone as a vCard field. * * @param formatted Formatted phone will be appended to this buffer * @param addr The rowdata containing the actual phone data. */ public static void formatAddr(Appendable formatted, RowData addr) throws IOException { formatted.append("ADR"); if (addr.preferred) formatted.append(";PREF"); if (addr.customLabel != null) { formatted.append(";" + LABEL_PARAM + "="); formatted.append(addr.customLabel); } switch (addr.type) { case Contacts.ContactMethodsColumns.TYPE_HOME: formatted.append(";HOME"); break; case Contacts.PhonesColumns.TYPE_WORK: formatted.append(";WORK"); break; } if (!StringUtil.isASCII(addr.data)) formatted.append(";CHARSET=UTF-8"); formatted.append(":;;").append(addr.data.replace(", ", ";").trim()).append(NL); } /** * Format an IM contact as a vCard field. * * @param formatted Formatted im contact will be appended to this buffer * @param addr The rowdata containing the actual phone data. */ public static void formatIM(Appendable formatted, RowData im) throws IOException { formatted.append(IMPROP); if (im.preferred) formatted.append(";PREF"); if (im.customLabel != null) { formatted.append(";" + LABEL_PARAM + "="); formatted.append(im.customLabel); } switch (im.type) { case Contacts.ContactMethodsColumns.TYPE_HOME: formatted.append(";HOME"); break; case Contacts.ContactMethodsColumns.TYPE_WORK: formatted.append(";WORK"); break; } if (im.auxData != null) { formatted.append(";").append(PROTO_PARAM).append("=").append(im.auxData); } if (!StringUtil.isASCII(im.data)) formatted.append(";CHARSET=UTF-8"); formatted.append(":").append(im.data.trim()).append(NL); } /** * Format Organization fields. * * * * @param formatted Formatted organization info will be appended to this buffer * @param addr The rowdata containing the actual organization data. */ public static void formatOrg(Appendable formatted, OrgData org) throws IOException { if (org.company != null) { formatted.append("ORG"); if (org.customLabel != null) { formatted.append(";" + LABEL_PARAM + "="); formatted.append(org.customLabel); } if (!StringUtil.isASCII(org.company)) formatted.append(";CHARSET=UTF-8"); formatted.append(":").append(org.company.trim()).append(NL); if (org.title == null) formatted.append("TITLE:").append(NL); } if (org.title != null) { if (org.company == null) formatted.append("ORG:").append(NL); formatted.append("TITLE"); if (org.customLabel != null) { formatted.append(";" + LABEL_PARAM + "="); formatted.append(org.customLabel); } if (!StringUtil.isASCII(org.title)) formatted.append(";CHARSET=UTF-8"); formatted.append(":").append(org.title.trim()).append(NL); } } public String toString() { StringWriter out = new StringWriter(); try { writeVCard(out); } catch (IOException e) { // Should never happen } return out.toString(); } /** * Write the contact vCard to an appendable stream. */ public void writeVCard(Appendable vCardBuff) throws IOException { // Start vCard vCardBuff.append("BEGIN:VCARD").append(NL); vCardBuff.append("VERSION:2.1").append(NL); appendField(vCardBuff, "X-IRMC-LUID", syncid); vCardBuff.append("N"); if (!StringUtil.isASCII(lastName) || !StringUtil.isASCII(firstName)) vCardBuff.append(";CHARSET=UTF-8"); vCardBuff.append(":").append((lastName != null) ? lastName.trim() : "") .append(";").append((firstName != null) ? firstName.trim() : "") .append(";").append(";").append(";").append(NL); for (RowData email : emails) { formatEmail(vCardBuff, email); } for (RowData phone : phones) { formatPhone(vCardBuff, phone); } for (OrgData org : orgs) { formatOrg(vCardBuff, org); } for (RowData addr : addrs) { formatAddr(vCardBuff, addr); } for (RowData im : ims) { formatIM(vCardBuff, im); } appendField(vCardBuff, "NOTE", notes); appendField(vCardBuff, "BDAY", birthday); if (photo != null) { appendField(vCardBuff, "PHOTO;TYPE=JPEG;ENCODING=BASE64", " "); Base64Coder.mimeEncode(vCardBuff, photo, 76, NL); vCardBuff.append(NL); vCardBuff.append(NL); } // End vCard vCardBuff.append("END:VCARD").append(NL); } /** * Append the field to the StringBuffer out if not null. */ private static void appendField(Appendable out, String name, String val) throws IOException { if(val != null && val.length() > 0) { out.append(name); if (!StringUtil.isASCII(val)) out.append(";CHARSET=UTF-8"); out.append(":").append(val).append(NL); } } /** * Populate the contact fields from a cursor */ public void populate(Cursor peopleCur, ContentResolver cResolver) { reset(); setPeopleFields(peopleCur); String personID = _id; if (querySyncId != null) { querySyncId.bindString(1, personID); try { syncid = querySyncId.simpleQueryForString(); } catch (SQLiteDoneException e) { if (insertSyncId != null) { // Create a new syncid syncid = UUID.randomUUID().toString(); // Write the new syncid insertSyncId.bindString(1, personID); insertSyncId.bindString(2, syncid); insertSyncId.executeInsert(); } } } Cursor organization = cResolver.query(Contacts.Organizations.CONTENT_URI, null, Contacts.OrganizationColumns.PERSON_ID + "=" + personID, null, null); // Set the organization fields if (organization.moveToFirst()) { do { setOrganizationFields(organization); } while (organization.moveToNext()); } organization.close(); Cursor phones = cResolver.query(Contacts.Phones.CONTENT_URI, null, Contacts.Phones.PERSON_ID + "=" + personID, null, null); // Set all the phone numbers if (phones.moveToFirst()) { do { setPhoneFields(phones); } while (phones.moveToNext()); } phones.close(); Cursor contactMethods = cResolver.query(Contacts.ContactMethods.CONTENT_URI, null, Contacts.ContactMethods.PERSON_ID + "=" + personID, null, null); // Set all the contact methods (emails, addresses, ims) if (contactMethods.moveToFirst()) { do { setContactMethodsFields(contactMethods); } while (contactMethods.moveToNext()); } contactMethods.close(); // Load a photo if one exists. Cursor contactPhoto = cResolver.query(Contacts.Photos.CONTENT_URI, null, Contacts.PhotosColumns.PERSON_ID + "=" + personID, null, null); if (contactPhoto.moveToFirst()) { photo = contactPhoto.getBlob(contactPhoto.getColumnIndex(Contacts.PhotosColumns.DATA)); } contactPhoto.close(); } /** * Retrieve the People fields from a Cursor */ private void setPeopleFields(Cursor cur) { int selectedColumn; // Set the contact id selectedColumn = cur.getColumnIndex(Contacts.People._ID); long nid = cur.getLong(selectedColumn); _id = String.valueOf(nid); // // Get PeopleColumns fields // selectedColumn = cur.getColumnIndex(Contacts.PeopleColumns.NAME); displayName = cur.getString(selectedColumn); if (displayName != null) { Matcher m = namePattern.matcher(displayName); if (m.matches()) { if (m.group(1) != null) { lastName = m.group(2); firstName = m.group(3); } else { firstName = m.group(5); lastName = m.group(6); } } else { firstName = displayName; lastName = ""; } } else { firstName = lastName = ""; } selectedColumn = cur.getColumnIndex(Contacts.People.NOTES); notes = cur.getString(selectedColumn); if (notes != null) { Matcher ppm = birthdayPattern.matcher(notes); if (ppm.find()) { birthday = ppm.group(1); notes = ppm.replaceFirst(""); } } } /** * Retrieve the organization fields from a Cursor */ private void setOrganizationFields(Cursor cur) { int selectedColumn; // // Get Organizations fields // selectedColumn = cur.getColumnIndex(Contacts.OrganizationColumns.COMPANY); String company = cur.getString(selectedColumn); selectedColumn = cur.getColumnIndex(Contacts.OrganizationColumns.TITLE); String title = cur.getString(selectedColumn); selectedColumn = cur.getColumnIndex(Contacts.OrganizationColumns.TYPE); int orgType = cur.getInt(selectedColumn); String customLabel = null; if (orgType == Contacts.ContactMethodsColumns.TYPE_CUSTOM) { selectedColumn = cur .getColumnIndex(Contacts.ContactMethodsColumns.LABEL); customLabel = cur.getString(selectedColumn); } orgs.add(new OrgData(orgType, title, company, customLabel)); } /** * Retrieve the Phone fields from a Cursor */ private void setPhoneFields(Cursor cur) { int selectedColumn; int selectedColumnType; int preferredColumn; int phoneType; String customLabel = null; // // Get PhonesColums fields // selectedColumn = cur.getColumnIndex(Contacts.PhonesColumns.NUMBER); selectedColumnType = cur.getColumnIndex(Contacts.PhonesColumns.TYPE); preferredColumn = cur.getColumnIndex(Contacts.PhonesColumns.ISPRIMARY); phoneType = cur.getInt(selectedColumnType); String phone = cur.getString(selectedColumn); boolean preferred = cur.getInt(preferredColumn) != 0; if (phoneType == Contacts.PhonesColumns.TYPE_CUSTOM) { customLabel = cur.getString(cur.getColumnIndex(Contacts.PhonesColumns.LABEL)); } phones.add(new RowData(phoneType, phone, preferred, customLabel)); } /** * Retrieve the email fields from a Cursor */ private void setContactMethodsFields(Cursor cur) { int selectedColumn; int selectedColumnType; int selectedColumnKind; int selectedColumnPrimary; int selectedColumnLabel; int methodType; int kind; String customLabel = null; String auxData = null; // // Get ContactsMethodsColums fields // selectedColumn = cur .getColumnIndex(Contacts.ContactMethodsColumns.DATA); selectedColumnType = cur .getColumnIndex(Contacts.ContactMethodsColumns.TYPE); selectedColumnKind = cur .getColumnIndex(Contacts.ContactMethodsColumns.KIND); selectedColumnPrimary = cur .getColumnIndex(Contacts.ContactMethodsColumns.ISPRIMARY); kind = cur.getInt(selectedColumnKind); methodType = cur.getInt(selectedColumnType); String methodData = cur.getString(selectedColumn); boolean preferred = cur.getInt(selectedColumnPrimary) != 0; if (methodType == Contacts.ContactMethodsColumns.TYPE_CUSTOM) { selectedColumnLabel = cur .getColumnIndex(Contacts.ContactMethodsColumns.LABEL); customLabel = cur.getString(selectedColumnLabel); } switch (kind) { case Contacts.KIND_EMAIL: emails.add(new RowData(methodType, methodData, preferred, customLabel)); break; case Contacts.KIND_POSTAL: addrs.add(new RowData(methodType, methodData, preferred, customLabel)); break; case Contacts.KIND_IM: RowData newRow = new RowData(methodType, methodData, preferred, customLabel); selectedColumn = cur.getColumnIndex(Contacts.ContactMethodsColumns.AUX_DATA); auxData = cur.getString(selectedColumn); if (auxData != null) { String[] auxFields = StringUtil.split(auxData, ":"); if (auxFields.length > 1) { if (auxFields[0].equalsIgnoreCase("pre")) { int protval = 0; try { protval = Integer.decode(auxFields[1]); } catch (NumberFormatException e) { // Do nothing; protval = 0 } if (protval < 0 || protval >= PROTO.length) protval = 0; newRow.auxData = PROTO[protval]; } else if (auxFields[0].equalsIgnoreCase("custom")) { newRow.auxData = auxFields[1]; } } else { newRow.auxData = auxData; } } ims.add(newRow); break; } } public ContentValues getPeopleCV() { ContentValues cv = new ContentValues(); StringBuffer fullname = new StringBuffer(); if (displayName != null) fullname.append(displayName); else { if (firstName != null) fullname.append(firstName); if (lastName != null) { if (firstName != null) fullname.append(" "); fullname.append(lastName); } } // Use company name if only the company is given. if (fullname.length() == 0 && orgs.size() > 0 && orgs.get(0).company != null) fullname.append(orgs.get(0).company); cv.put(Contacts.People.NAME, fullname.toString()); if (!StringUtil.isNullOrEmpty(_id)) { cv.put(Contacts.People._ID, _id); } StringBuffer allnotes = new StringBuffer(); if (birthday != null) { allnotes.append(BIRTHDAY_FIELD).append(" ").append(birthday); } if (notes != null) { if (birthday != null) { allnotes.append(";\n"); } allnotes.append(notes); } if (allnotes.length() > 0) cv.put(Contacts.People.NOTES, allnotes.toString()); return cv; } public ContentValues getOrganizationCV(OrgData org) { if(StringUtil.isNullOrEmpty(org.company) && StringUtil.isNullOrEmpty(org.title)) { return null; } ContentValues cv = new ContentValues(); cv.put(Contacts.Organizations.COMPANY, org.company); cv.put(Contacts.Organizations.TITLE, org.title); cv.put(Contacts.Organizations.TYPE, org.type); cv.put(Contacts.Organizations.PERSON_ID, _id); if (org.customLabel != null) { cv.put(Contacts.Organizations.LABEL, org.customLabel); } return cv; } public ContentValues getPhoneCV(RowData data) { ContentValues cv = new ContentValues(); cv.put(Contacts.Phones.NUMBER, data.data); cv.put(Contacts.Phones.TYPE, data.type); cv.put(Contacts.Phones.ISPRIMARY, data.preferred ? 1 : 0); cv.put(Contacts.Phones.PERSON_ID, _id); if (data.customLabel != null) { cv.put(Contacts.Phones.LABEL, data.customLabel); } return cv; } public ContentValues getEmailCV(RowData data) { ContentValues cv = new ContentValues(); cv.put(Contacts.ContactMethods.DATA, data.data); cv.put(Contacts.ContactMethods.TYPE, data.type); cv.put(Contacts.ContactMethods.KIND, Contacts.KIND_EMAIL); cv.put(Contacts.ContactMethods.ISPRIMARY, data.preferred ? 1 : 0); cv.put(Contacts.ContactMethods.PERSON_ID, _id); if (data.customLabel != null) { cv.put(Contacts.ContactMethods.LABEL, data.customLabel); } return cv; } public ContentValues getAddressCV(RowData data) { ContentValues cv = new ContentValues(); cv.put(Contacts.ContactMethods.DATA, data.data); cv.put(Contacts.ContactMethods.TYPE, data.type); cv.put(Contacts.ContactMethods.KIND, Contacts.KIND_POSTAL); cv.put(Contacts.ContactMethods.ISPRIMARY, data.preferred ? 1 : 0); cv.put(Contacts.ContactMethods.PERSON_ID, _id); if (data.customLabel != null) { cv.put(Contacts.ContactMethods.LABEL, data.customLabel); } return cv; } public ContentValues getImCV(RowData data) { ContentValues cv = new ContentValues(); cv.put(Contacts.ContactMethods.DATA, data.data); cv.put(Contacts.ContactMethods.TYPE, data.type); cv.put(Contacts.ContactMethods.KIND, Contacts.KIND_IM); cv.put(Contacts.ContactMethods.ISPRIMARY, data.preferred ? 1 : 0); cv.put(Contacts.ContactMethods.PERSON_ID, _id); if (data.customLabel != null) { cv.put(Contacts.ContactMethods.LABEL, data.customLabel); } if (data.auxData != null) { int protoNum = -1; for (int i = 0; i < PROTO.length; ++i) { if (data.auxData.equalsIgnoreCase(PROTO[i])) { protoNum = i; break; } } if (protoNum >= 0) { cv.put(Contacts.ContactMethods.AUX_DATA, "pre:"+protoNum); } else { cv.put(Contacts.ContactMethods.AUX_DATA, "custom:"+data.auxData); } } return cv; } /** * Add a new contact to the Content Resolver * * @param key the row number of the existing contact (if known) * @return The row number of the inserted column */ public long addContact(Context context, long key, boolean replace) { ContentResolver cResolver = context.getContentResolver(); ContentValues pCV = getPeopleCV(); boolean addSyncId = false; boolean replacing = false; if (key <= 0 && syncid != null) { if (queryPersonId != null) try { queryPersonId.bindString(1, syncid); setId(queryPersonId.simpleQueryForString()); key = getId(); } catch(SQLiteDoneException e) { // Couldn't locate syncid, we'll add it; // need to wait until we know what the key is, though. addSyncId = true; } } Uri newContactUri = null; if (key > 0) { newContactUri = ContentUris.withAppendedId(Contacts.People.CONTENT_URI, key); Cursor testit = cResolver.query(newContactUri, null, null, null, null); if (testit == null || testit.getCount() == 0) { newContactUri = null; pCV.put(Contacts.People._ID, key); } if (testit != null) testit.close(); } if (newContactUri == null) { newContactUri = insertContentValues(cResolver, Contacts.People.CONTENT_URI, pCV); if (newContactUri == null) { Log.error("Error adding contact." + " (key: " + key + ")"); return -1; } // Set the contact person id setId(newContactUri.getLastPathSegment()); key = getId(); // Add the new contact to the myContacts group Contacts.People.addToMyContactsGroup(cResolver, key); } else { // update existing Uri if (!replace) return -1; replacing = true; cResolver.update(newContactUri, pCV, null, null); } // We need to add the syncid to the database so // that we'll detect this contact if we try to import // it again. if (addSyncId && insertSyncId != null) { insertSyncId.bindLong(1, key); insertSyncId.bindString(2, syncid); insertSyncId.executeInsert(); } /* * Insert all the new ContentValues */ if (replacing) { // Remove existing phones Uri phones = Uri.withAppendedPath(ContentUris.withAppendedId(Contacts.People.CONTENT_URI, key), Contacts.People.Phones.CONTENT_DIRECTORY); String[] phoneID = {Contacts.People.Phones._ID}; Cursor existingPhones = cResolver.query(phones, phoneID, null, null, null); if (existingPhones != null && existingPhones.moveToFirst()) { int idColumn = existingPhones.getColumnIndex(Contacts.People.Phones._ID); List<Long> ids = new ArrayList<Long>(existingPhones.getCount()); do { ids.add(existingPhones.getLong(idColumn)); } while (existingPhones.moveToNext()); existingPhones.close(); for (Long id : ids) { Uri phone = ContentUris.withAppendedId(Contacts.Phones.CONTENT_URI, id); cResolver.delete(phone, null, null); } } // Remove existing contact methods (emails, addresses, etc.) Uri methods = Uri.withAppendedPath(ContentUris.withAppendedId(Contacts.People.CONTENT_URI, key), Contacts.People.ContactMethods.CONTENT_DIRECTORY); String[] methodID = {Contacts.People.ContactMethods._ID}; Cursor existingMethods = cResolver.query(methods, methodID, null, null, null); if (existingMethods != null && existingMethods.moveToFirst()) { int idColumn = existingMethods.getColumnIndex(Contacts.People.ContactMethods._ID); List<Long> ids = new ArrayList<Long>(existingMethods.getCount()); do { ids.add(existingMethods.getLong(idColumn)); } while (existingMethods.moveToNext()); existingMethods.close(); for (Long id : ids) { Uri method = ContentUris.withAppendedId(Contacts.Phones.CONTENT_URI, id); cResolver.delete(method, null, null); } } } // Phones for (RowData phone : phones) { insertContentValues(cResolver, Contacts.Phones.CONTENT_URI, getPhoneCV(phone)); } // Organizations for (OrgData org : orgs) { insertContentValues(cResolver, Contacts.Organizations.CONTENT_URI, getOrganizationCV(org)); } Builder builder = newContactUri.buildUpon(); builder.appendEncodedPath(Contacts.ContactMethods.CONTENT_URI.getPath()); // Emails for (RowData email : emails) { insertContentValues(cResolver, builder.build(), getEmailCV(email)); } // Addressess for (RowData addr : addrs) { insertContentValues(cResolver, builder.build(), getAddressCV(addr)); } // IMs for (RowData im : ims) { insertContentValues(cResolver, builder.build(), getImCV(im)); } // Photo if (photo != null) { Uri person = ContentUris.withAppendedId(Contacts.People.CONTENT_URI, key); Contacts.People.setPhotoData(cResolver, person, photo); } return key; } /** * Insert a new ContentValues raw into the Android ContentProvider */ private Uri insertContentValues(ContentResolver cResolver, Uri uri, ContentValues cv) { if (cv != null) { return cResolver.insert(uri, cv); } return null; } /** * Get the item content */ public String getContent() { return toString(); } /** * Check if the email string is well formatted */ @SuppressWarnings("unused") private boolean checkEmail(String email) { return (email != null && !"".equals(email) && email.indexOf("@") != -1); } }
00piknik00-vardio
src/vcard/io/Contact.java
Java
gpl3
47,253
/* * Funambol is a mobile platform developed by Funambol, Inc. * Copyright (C) 2003 - 2007 Funambol, Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by * the Free Software Foundation with the addition of the following permission * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * 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 Affero General Public License * along with this program; if not, see http://www.gnu.org/licenses or write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA. * * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License * version 3, these Appropriate Legal Notices must retain the display of the * "Powered by Funambol" logo. If the display of the logo is not reasonably * feasible for technical reasons, the Appropriate Legal Notices must display * the words "Powered by Funambol". */ package com.funambol.util; import java.util.Vector; /** * Utility class useful when dealing with string objects. * This class is a collection of static functions, and the usage is: * * StringUtil.method() * * it is not allowed to create instances of this class */ public class StringUtil { private static final String HT = "\t"; private static final String CRLF = "\r\n"; // This class cannot be instantiated private StringUtil() { } /** * Split the string into an array of strings using one of the separator * in 'sep'. * * @param s the string to tokenize * @param sep a list of separator to use * * @return the array of tokens (an array of size 1 with the original * string if no separator found) */ public static String[] split(String s, String sep) { // convert a String s to an Array, the elements // are delimited by sep Vector<Integer> tokenIndex = new Vector<Integer>(10); int len = s.length(); int i; // Find all characters in string matching one of the separators in 'sep' for (i = 0; i < len; i++) { if (sep.indexOf(s.charAt(i)) != -1 ){ tokenIndex.addElement(new Integer(i)); } } int size = tokenIndex.size(); String[] elements = new String[size+1]; // No separators: return the string as the first element if(size == 0) { elements[0] = s; } else { // Init indexes int start = 0; int end = (tokenIndex.elementAt(0)).intValue(); // Get the first token elements[0] = s.substring(start, end); // Get the mid tokens for (i=1; i<size; i++) { // update indexes start = (tokenIndex.elementAt(i-1)).intValue()+1; end = (tokenIndex.elementAt(i)).intValue(); elements[i] = s.substring(start, end); } // Get last token start = (tokenIndex.elementAt(i-1)).intValue()+1; elements[i] = (start < s.length()) ? s.substring(start) : ""; } return elements; } /** * Split the string into an array of strings using one of the separator * in 'sep'. * * @param list the string array to join * @param sep the separator to use * * @return the joined string */ public static String join(String[] list, String sep) { StringBuffer buffer = new StringBuffer(list[0]); int len = list.length; for (int i = 1; i < len; i++) { buffer.append(sep).append(list[i]); } return buffer.toString(); } /** * Returns the string array * @param stringVec the Vecrot of tring to convert * @return String [] */ public static String[] getStringArray(Vector<String> stringVec){ if(stringVec==null){ return null; } String[] stringArray=new String[stringVec.size()]; for(int i=0;i<stringVec.size();i++){ stringArray[i]=stringVec.elementAt(i); } return stringArray; } /** * Find two consecutive newlines in a string. * @param s - The string to search * @return int: the position of the empty line */ public static int findEmptyLine(String s){ int ret = 0; // Find a newline while( (ret = s.indexOf("\n", ret)) != -1 ){ // Skip carriage returns, if any while(s.charAt(ret) == '\r'){ ret++; } if(s.charAt(ret) == '\n'){ // Okay, it was empty ret ++; break; } } return ret; } /** * Removes unwanted blank characters * @param content * @return String */ public static String removeBlanks(String content){ if(content==null){ return null; } StringBuffer buff = new StringBuffer(); buff.append(content); for(int i = buff.length()-1; i >= 0;i--){ if(' ' == buff.charAt(i)){ buff.deleteCharAt(i); } } return buff.toString(); } /** * Removes unwanted backslashes characters * * @param content The string containing the backslashes to be removed * @return the content without backslashes */ public static String removeBackslashes(String content){ if (content == null) { return null; } StringBuffer buff = new StringBuffer(); buff.append(content); int len = buff.length(); for (int i = len - 1; i >= 0; i--) { if ('\\' == buff.charAt(i)) buff.deleteCharAt(i); } return buff.toString(); } /** * Builds a list of the recipients email addresses each on a different line, * starting just from the second line with an HT ("\t") separator at the * head of the line. This is an implementation of the 'folding' concept from * the RFC 2822 (par. 2.2.3) * * @param recipients * A string containing all recipients comma-separated * @return A string containing the email list of the recipients spread over * more lines, ended by CRLF and beginning from the second with the * WSP defined in the RFC 2822 */ public static String fold(String recipients) { String[] list = StringUtil.split(recipients, ","); StringBuffer buffer = new StringBuffer(); for (int i = 0; i < list.length; i++) { String address = list[i] + (i != list.length - 1 ? "," : ""); buffer.append(i == 0 ? address + CRLF : HT + address + CRLF); } return buffer.toString(); } /** * This method is missing in CLDC 1.0 String implementation */ public static boolean equalsIgnoreCase(String string1, String string2) { // Strings are both null, return true if (string1 == null && string2 == null) { return true; } // One of the two is null, return false if (string1 == null || string2 == null) { return false; } // Both are not null, compare the lowercase strings if ((string1.toLowerCase()).equals(string2.toLowerCase())) { return true; } else { return false; } } /** * Util method for retrieve a boolean primitive type from a String. * Implemented because Boolean class doesn't provide * parseBoolean() method */ public static boolean getBooleanValue(String string) { if ((string == null) || string.equals("")) { return false; } else { if (StringUtil.equalsIgnoreCase(string, "true")) { return true; } else { return false; } } } /** * Removes characters 'c' from the beginning and the end of the string */ public static String trim(String s, char c) { int start = 0; int end = s.length()-1; while(s.charAt(start) == c) { if(++start >= end) { // The string is made by c only return ""; } } while(s.charAt(end) == c) { if(--end <= start) { return ""; } } return s.substring(start, end+1); } /** * Returns true if the given string is null or empty. */ public static boolean isNullOrEmpty(String str) { if (str==null) { return true; } if (str.trim().equals("")) { return true; } return false; } /** * Returns true if the string does not fit in standard ASCII */ public static boolean isASCII(String str) { if (str == null) return true; for (int i = 0; i < str.length(); ++i) { char c = str.charAt(i); if (c < 0 || c > 0x7f) return false; } return true; } }
00piknik00-vardio
src/com/funambol/util/StringUtil.java
Java
gpl3
10,144
/* * Funambol is a mobile platform developed by Funambol, Inc. * Copyright (C) 2003 - 2007 Funambol, Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by * the Free Software Foundation with the addition of the following permission * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * 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 Affero General Public License * along with this program; if not, see http://www.gnu.org/licenses or write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA. * * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License * version 3, these Appropriate Legal Notices must retain the display of the * "Powered by Funambol" logo. If the display of the logo is not reasonably * feasible for technical reasons, the Appropriate Legal Notices must display * the words "Powered by Funambol". */ package com.funambol.util; import java.util.Calendar; import java.util.Date; /** * A utility class providing methods to convert date information contained in * <code>Date</code> objects into RFC2822 and UTC ('Zulu') strings, and to * build <code>Date</code> objects starting from string representations of * dates in RFC2822 and UTC format */ public class MailDateFormatter { /** Format date as: MM/DD */ public static final int FORMAT_MONTH_DAY = 0; /** Format date as: MM/DD/YYYY */ public static final int FORMAT_MONTH_DAY_YEAR = 1; /** Format date as: hh:mm */ public static final int FORMAT_HOURS_MINUTES = 2; /** Format date as: hh:mm:ss */ public static final int FORMAT_HOURS_MINUTES_SECONDS = 3; /** Format date as: DD/MM */ public static final int FORMAT_DAY_MONTH = 4; /** Format date as: DD/MM/YYYY */ public static final int FORMAT_DAY_MONTH_YEAR = 5; /** Device offset, as string */ private static String deviceOffset = "+0000"; /** Device offset, in millis */ private static long millisDeviceOffset = 0; /** Names of the months */ private static String[] monthNames = new String[] { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; /** * Transforms data contained in a <code>Date</code> object (expressed in * UTC) in a string formatted as per RFC2822 in local time (par. 3.3) * * @return A string representing the date contained in the passed * <code>Date</code> object formatted as per RFC 2822 and in local * time */ public static String dateToRfc2822(Date date) { Calendar deviceTime = Calendar.getInstance(); deviceTime.setTime(date); String dayweek = ""; int dayOfWeek = deviceTime.get(Calendar.DAY_OF_WEEK); switch (dayOfWeek) { case 1 : dayweek = "Sun"; break; case 2 : dayweek = "Mon"; break; case 3 : dayweek = "Tue"; break; case 4 : dayweek = "Wed"; break; case 5 : dayweek = "Thu"; break; case 6 : dayweek = "Fri"; break; case 7 : dayweek = "Sat"; break; } int dayOfMonth = deviceTime.get(Calendar.DAY_OF_MONTH); String monthInYear = getMonthName(deviceTime.get(Calendar.MONTH)); int year = deviceTime.get(Calendar.YEAR); int hourOfDay = deviceTime.get(Calendar.HOUR_OF_DAY); int minutes = deviceTime.get(Calendar.MINUTE); int seconds = deviceTime.get(Calendar.SECOND); String rfc = dayweek + ", " + // Tue dayOfMonth + " " + // 7 monthInYear + " " + // Nov year + " " + // 2006 hourOfDay + ":" + minutes + ":" + seconds + " " + // 14:13:26 deviceOffset; //+0200 return rfc; } /** * Converts a <code>Date</code> object into a string in 'Zulu' format * * @param d * A <code>Date</code> object to be converted into a string in * 'Zulu' format * @return A string representing the date contained in the passed * <code>Date</code> object in 'Zulu' format (e.g. * yyyyMMDDThhmmssZ) */ public static String dateToUTC(Date d) { StringBuffer date = new StringBuffer(); Calendar cal = Calendar.getInstance(); cal.setTime(d); date.append(cal.get(Calendar.YEAR)); date.append(printTwoDigits(cal.get(Calendar.MONTH) + 1)) .append(printTwoDigits(cal.get(Calendar.DATE))) .append("T"); date.append(printTwoDigits(cal.get(Calendar.HOUR_OF_DAY))) .append(printTwoDigits(cal.get(Calendar.MINUTE))) .append(printTwoDigits(cal.get(Calendar.SECOND))) .append("Z"); return date.toString(); } /** * A method that returns a string rapresenting a date. * * @param date the date * * @param format the format as one of * FORMAT_MONTH_DAY, * FORMAT_MONTH_DAY_YEAR, * FORMAT_HOURS_MINUTES, * FORMAT_HOURS_MINUTES_SECONDS * FORMAT_DAY_MONTH * FORMAT_DAY_MONTH_YEAR * constants * * @param separator the separator to be used */ public static String getFormattedStringFromDate( Date date, int format, String separator) { Calendar cal=Calendar.getInstance(); cal.setTime(date); StringBuffer ret = new StringBuffer(); switch (format) { case FORMAT_HOURS_MINUTES: //if pm and hour == 0 we want to write 12, not 0 if (cal.get(Calendar.AM_PM)==Calendar.PM && cal.get(Calendar.HOUR) == 0) { ret.append("12"); } else { ret.append(cal.get(Calendar.HOUR)); } ret.append(separator) .append(printTwoDigits(cal.get(Calendar.MINUTE))) .append(getAMPM(cal)); break; case FORMAT_HOURS_MINUTES_SECONDS: //if pm and hour == 0 we want to write 12, not 0 if (cal.get(Calendar.AM_PM)==Calendar.PM && cal.get(Calendar.HOUR) == 0) { ret.append("12"); } else { ret.append(cal.get(Calendar.HOUR)); } ret.append(separator) .append(printTwoDigits(cal.get(Calendar.MINUTE))) .append(separator) .append(cal.get(Calendar.SECOND)) .append(getAMPM(cal)); break; case FORMAT_MONTH_DAY: ret.append(cal.get(Calendar.MONTH)+1) .append(separator) .append(cal.get(Calendar.DAY_OF_MONTH)); break; case FORMAT_DAY_MONTH: ret.append(cal.get(Calendar.DAY_OF_MONTH)) .append(separator) .append(cal.get(Calendar.MONTH)+1); break; case FORMAT_MONTH_DAY_YEAR: ret.append(cal.get(Calendar.MONTH)+1) .append(separator) .append(cal.get(Calendar.DAY_OF_MONTH)) .append(separator) .append(cal.get(Calendar.YEAR)); break; case FORMAT_DAY_MONTH_YEAR: ret.append(cal.get(Calendar.DAY_OF_MONTH)) .append(separator) .append(cal.get(Calendar.MONTH)+1) .append(separator) .append(cal.get(Calendar.YEAR)); break; default: Log.error("getFormattedStringFromDate: invalid format ("+ format+")"); } return ret.toString(); } /** * Returns a localized string representation of Date. */ public static String formatLocalTime(Date d) { int dateFormat = FORMAT_MONTH_DAY_YEAR; int timeFormat = FORMAT_HOURS_MINUTES; if(!System.getProperty("microedition.locale").equals("en")) { dateFormat = FORMAT_DAY_MONTH_YEAR; } return getFormattedStringFromDate(d,dateFormat,"/") +" "+getFormattedStringFromDate(d,timeFormat,":"); } /** * Parses the string in RFC 2822 format and return a <code>Date</code> * object. <p> * Parse strings like: * Thu, 03 May 2007 14:45:38 GMT * Thu, 03 May 2007 14:45:38 GMT+0200 * Thu, 1 Feb 2007 03:57:01 -0800 * Fri, 04 May 2007 13:40:17 PDT * * @param d the date representation to parse * @return a date, if valid, or null on error * */ public static Date parseRfc2822Date(String stringDate) { if (stringDate == null) { return null; } long hourOffset=0; long minOffset=0; Calendar cal = Calendar.getInstance(); try { Log.info("Date original: " + stringDate); // Just skip the weekday if present int start = stringDate.indexOf(','); //put start after ", " start = (start == -1) ? 0 : start + 2; stringDate = stringDate.substring(start).trim(); start = 0; // Get day of month int end = stringDate.indexOf(' ', start); int day =1; try { day = Integer.parseInt(stringDate.substring(start, end)); } catch (NumberFormatException ex) { // some phones (Nokia 6111) have a invalid date format, // something like Tue10 Jul... instead of Tue, 10 // so we try to strip (again) the weekday day = Integer.parseInt(stringDate.substring(start+3, end)); Log.info("Nokia 6111 patch applied."); } cal.set(Calendar.DAY_OF_MONTH,day); // Get month start = end + 1; end = stringDate.indexOf(' ', start); cal.set(Calendar.MONTH, getMonthNumber(stringDate.substring(start, end))); // Get year start = end + 1; end = stringDate.indexOf(' ', start); cal.set(Calendar.YEAR, Integer.parseInt(stringDate.substring(start, end))); // Get hour start = end + 1; end = stringDate.indexOf(':', start); cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(stringDate.substring(start, end).trim())); // Get min start = end + 1; end = stringDate.indexOf(':', start); cal.set(Calendar.MINUTE, Integer.parseInt(stringDate.substring(start, end))); // Get sec start = end + 1; end = stringDate.indexOf(' ', start); cal.set(Calendar.SECOND, Integer.parseInt(stringDate.substring(start, end))); // Get OFFSET start = end +1; end = stringDate.indexOf('\r', start); // Process Timezone, checking first for the actual RFC2822 format, // and then for nthe obsolete syntax. char sign = '+'; String hourDiff = "0"; String minDiff = "0"; String offset = stringDate.substring(start).trim(); if (offset.startsWith("+") || offset.startsWith("-")) { if(offset.length() >= 5 ){ sign = offset.charAt(0); hourDiff = offset.substring(1,3); minDiff = offset.substring(3,5); } else if(offset.length() == 3){ sign = offset.charAt(0); hourDiff = offset.substring(1); minDiff = "00"; } // Convert offset to int hourOffset = Long.parseLong(hourDiff); minOffset = Long.parseLong(minDiff); if(sign == '-') { hourOffset = -hourOffset; } } else if(offset.equals("EDT")){ hourOffset = -4; } else if(offset.equals("EST") || offset.equals("CDT")){ hourOffset = -5; } else if(offset.equals("CST") || offset.equals("MDT")){ hourOffset = -6; } else if(offset.equals("PDT") || offset.equals("MST")){ hourOffset = -7; } else if(offset.equals("PST")){ hourOffset = -8; } else if(offset.equals("GMT") || offset.equals("UT")){ hourOffset = 0; } else if (offset.substring(0,3).equals("GMT") && offset.length() > 3){ sign = offset.charAt(3); hourDiff = offset.substring(4,6); minDiff = offset.substring(6,8); } long millisOffset = (hourOffset * 3600000) + (minOffset * 60000); Date gmtDate = cal.getTime(); long millisDate = gmtDate.getTime(); millisDate -= millisOffset; gmtDate.setTime(millisDate); return gmtDate; } catch (Exception e) { Log.error("Exception in parseRfc2822Date: " + e.toString() + " parsing " + stringDate); e.printStackTrace(); return null; } } /** * Convert the given date (GMT) into the local date. * NOTE: changes the original date too! * Should we change it to a void toLocalDate(Date) that changes the * input date only? */ public static Date getDeviceLocalDate (Date gmtDate){ if (null != gmtDate){ /*long dateInMillis = gmtDate.getTime(); Date deviceDate = new Date(); deviceDate.setTime(dateInMillis+millisDeviceOffset); return deviceDate; **/ gmtDate.setTime(gmtDate.getTime()+millisDeviceOffset); return gmtDate; } else { return null; } } /** * Gets a <code>Date</code> object from a string representing a date in * 'Zulu' format (yyyyMMddTHHmmssZ) * * @param utc * date in 'Zulu' format (yyyyMMddTHHmmssZ) * @return A <code>Date</code> object obtained starting from a time in * milliseconds from the Epoch */ public static Date parseUTCDate(String utc) { int day = 0; int month = 0; int year = 0; int hour = 0; int minute = 0; int second = 0; Calendar calendar = null; day = Integer.parseInt(utc.substring(6, 8)); month = Integer.parseInt(utc.substring(4, 6)); year = Integer.parseInt(utc.substring(0, 4)); hour = Integer.parseInt(utc.substring(9, 11)); minute = Integer.parseInt(utc.substring(11, 13)); second = Integer.parseInt(utc.substring(13, 15)); calendar = Calendar.getInstance(); calendar.set(Calendar.DAY_OF_MONTH, day); calendar.set(Calendar.MONTH, month - 1); calendar.set(Calendar.YEAR, year); calendar.set(Calendar.HOUR_OF_DAY, hour); calendar.set(Calendar.MINUTE, minute); calendar.set(Calendar.SECOND, second); Date date = calendar.getTime(); long dateInMillis = date.getTime(); date.setTime(dateInMillis+millisDeviceOffset); return date; } public static void setTimeZone(String timeZone){ if (timeZone == null || timeZone.length() < 5) { Log.error("setTimeZone: invalid timezone " + timeZone); } try { deviceOffset = timeZone; String hstmz = deviceOffset.substring(1, 3); String mstmz = deviceOffset.substring(3, 5); long hhtmz = Long.parseLong(hstmz); long mmtmz = Long.parseLong(mstmz); millisDeviceOffset = (hhtmz * 3600000) + (mmtmz * 60000); if(deviceOffset.charAt(0)=='-') { millisDeviceOffset *= -1; } } catch(Exception e) { Log.error("setTimeZone: " + e.toString()); e.printStackTrace(); } } //------------------------------------------------------------- Private methods /** * Get the number of the month, given the name. */ private static int getMonthNumber(String name) { for(int i=0, l=monthNames.length; i<l; i++) { if(monthNames[i].equals(name)) { return i; } } return -1; } /** * Get the name of the month, given the number. */ private static String getMonthName(int number) { if(number>0 && number<monthNames.length) { return monthNames[number]; } else return null; } private static String getAMPM(Calendar cal) { return (cal.get(Calendar.AM_PM)==Calendar.AM)?"a":"p"; } /** * Returns a string representation of number with at least 2 digits */ private static String printTwoDigits(int number) { if (number>9) { return String.valueOf(number); } else { return "0"+number; } } }
00piknik00-vardio
src/com/funambol/util/MailDateFormatter.java
Java
gpl3
19,075
/* * Funambol is a mobile platform developed by Funambol, Inc. * Copyright (C) 2003 - 2007 Funambol, Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by * the Free Software Foundation with the addition of the following permission * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * 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 Affero General Public License * along with this program; if not, see http://www.gnu.org/licenses or write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA. * * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License * version 3, these Appropriate Legal Notices must retain the display of the * "Powered by Funambol" logo. If the display of the logo is not reasonably * feasible for technical reasons, the Appropriate Legal Notices must display * the words "Powered by Funambol". */ package com.funambol.util; import java.io.UnsupportedEncodingException; /** * A class containing static methods to perform decoding from <b>quoted * printable</b> content transfer encoding and to encode into */ public class QuotedPrintable { private static byte HT = 0x09; // \t private static byte LF = 0x0A; // \n private static byte CR = 0x0D; // \r /** * A method to decode quoted printable encoded data. * It overrides the same input byte array to save memory. Can be done * because the result is surely smaller than the input. * * @param qp * a byte array to decode. * @return the length of the decoded array. */ public static int decode(byte [] qp) { int qplen = qp.length; int retlen = 0; for (int i=0; i < qplen; i++) { // Handle encoded chars if (qp[i] == '=') { if (qplen - i > 2) { // The sequence can be complete, check it if (qp[i+1] == CR && qp[i+2] == LF) { // soft line break, ignore it i += 2; continue; } else if (isHexDigit(qp[i+1]) && isHexDigit(qp[i+2]) ) { // convert the number into an integer, taking // the ascii digits stored in the array. qp[retlen++]=(byte)(getHexValue(qp[i+1])*16 + getHexValue(qp[i+2])); i += 2; continue; } else { Log.error("decode: Invalid sequence = " + qp[i+1] + qp[i+2]); } } // In all wrong cases leave the original bytes // (see RFC 2045). They can be incomplete sequence, // or a '=' followed by non hex digit. } // RFC 2045 says to exclude control characters mistakenly // present (unencoded) in the encoded stream. // As an exception, we keep unencoded tabs (0x09) if( (qp[i] >= 0x20 && qp[i] <= 0x7f) || qp[i] == HT || qp[i] == CR || qp[i] == LF) { qp[retlen++] = qp[i]; } } return retlen; } private static boolean isHexDigit(byte b) { return ( (b>=0x30 && b<=0x39) || (b>=0x41&&b<=0x46) ); } private static byte getHexValue(byte b) { return (byte)Character.digit((char)b, 16); } /** * * @param qp Byte array to decode * @param enc The character encoding of the returned string * @return The decoded string. */ public static String decode(byte[] qp, String enc) { int len=decode(qp); try { return new String(qp, 0, len, enc); } catch (UnsupportedEncodingException e) { Log.error("qp.decode: "+ enc + " not supported. " + e.toString()); return new String(qp, 0, len); } } /** * A method to encode data in quoted printable * * @param content * The string to be encoded * @return the encoded string. * @throws Exception * public static byte[] encode(String content, String enc) throws Exception { // TODO: to be implemented (has to return a String) throw new Exception("This method is not implemented!"); } */ /** * A method to encode data in quoted printable * * @param content * The string to be encoded * @return the encoded string. * @throws Exception * public static byte[] encode(byte[] content) throws Exception { // TODO: to be implemented (has to return a String) throw new Exception("This method is not implemented!"); } */ }
00piknik00-vardio
src/com/funambol/util/QuotedPrintable.java
Java
gpl3
5,703
/* * Funambol is a mobile platform developed by Funambol, Inc. * Copyright (C) 2003 - 2007 Funambol, Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by * the Free Software Foundation with the addition of the following permission * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * 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 Affero General Public License * along with this program; if not, see http://www.gnu.org/licenses or write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA. * * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License * version 3, these Appropriate Legal Notices must retain the display of the * "Powered by Funambol" logo. If the display of the logo is not reasonably * feasible for technical reasons, the Appropriate Legal Notices must display * the words "Powered by Funambol". */ package com.funambol.util; import com.funambol.storage.DataAccessException; public interface Appender { /** * Initialize Log File */ void initLogFile(); /** * Open Log file */ void openLogFile(); /** * Close Log file */ void closeLogFile(); /** * Delete Log file */ void deleteLogFile(); /** * Append a message to the Log file */ void writeLogMessage(String level, String msg) throws DataAccessException; }
00piknik00-vardio
src/com/funambol/util/Appender.java
Java
gpl3
2,342
/* * Funambol is a mobile platform developed by Funambol, Inc. * Copyright (C) 2003 - 2007 Funambol, Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by * the Free Software Foundation with the addition of the following permission * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * 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 Affero General Public License * along with this program; if not, see http://www.gnu.org/licenses or write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA. * * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License * version 3, these Appropriate Legal Notices must retain the display of the * "Powered by Funambol" logo. If the display of the logo is not reasonably * feasible for technical reasons, the Appropriate Legal Notices must display * the words "Powered by Funambol". */ package com.funambol.util; import com.funambol.storage.DataAccessException; import java.util.Date; /** * Generic Log class */ public class Log { //---------------------------------------------------------------- Constants /** * Log level DISABLED: used to speed up applications using logging features */ public static final int DISABLED = -1; /** * Log level ERROR: used to log error messages. */ public static final int ERROR = 0; /** * Log level INFO: used to log information messages. */ public static final int INFO = 1; /** * Log level DEBUG: used to log debug messages. */ public static final int DEBUG = 2; /** * Log level TRACE: used to trace the program execution. */ public static final int TRACE = 3; private static final int PROFILING = -2; //---------------------------------------------------------------- Variables /** * The default appender is the console */ private static Appender out; /** * The default log level is INFO */ private static int level = INFO; /** * Last time stamp used to dump profiling information */ private static long initialTimeStamp = -1; //------------------------------------------------------------- Constructors /** * This class is static and cannot be intantiated */ private Log(){ } //----------------------------------------------------------- Public methods /** * Initialize log file with a specific log level. * With this implementation of initLog the initialization is skipped. * Only a delete of log is performed. * * @param object the appender object that write log file * @param level the log level */ public static void initLog(Appender object, int level){ setLogLevel(level); out = object; // Delete Log invocation removed to speed up startup initialization. // However if needed the log store will rotate //deleteLog(); if (level > Log.DISABLED) { writeLogMessage(level, "INITLOG","---------"); } } /** * Ititialize log file * @param object the appender object that write log file */ public static void initLog(Appender object){ out = object; out.initLogFile(); } /** * Delete log file * */ public static void deleteLog() { out.deleteLogFile(); } /** * Accessor method to define log level: * @param newlevel log level to be set */ public static void setLogLevel(int newlevel) { level = newlevel; } /** * Accessor method to retrieve log level: * @return actual log level */ public static int getLogLevel() { return level; } /** * ERROR: Error message * @param msg the message to be logged */ public static void error(String msg) { writeLogMessage(ERROR, "ERROR", msg); } /** * ERROR: Error message * @param msg the message to be logged * @param obj the object that send error message */ public static void error(Object obj, String msg) { String message = "["+ obj.getClass().getName() + "] " + msg; writeLogMessage(ERROR, "ERROR", message); } /** * INFO: Information message * @param msg the message to be logged */ public static void info(String msg) { writeLogMessage(INFO, "INFO", msg); } /** * INFO: Information message * @param msg the message to be logged * @param obj the object that send log message */ public static void info(Object obj, String msg) { writeLogMessage(INFO, "INFO", msg); } /** * DEBUG: Debug message * @param msg the message to be logged */ public static void debug(String msg) { writeLogMessage(DEBUG, "DEBUG", msg); } /** * DEBUG: Information message * @param msg the message to be logged * @param obj the object that send log message */ public static void debug(Object obj, String msg) { String message = "["+ obj.getClass().getName() + "] " +msg; writeLogMessage(DEBUG, "DEBUG", message); } /** * TRACE: Debugger mode */ public static void trace(String msg) { writeLogMessage(TRACE, "TRACE", msg); } /** * TRACE: Information message * @param msg the message to be logged * @param obj the object that send log message */ public static void trace(Object obj, String msg) { String message = "["+ obj.getClass().getName() + "] " +msg; writeLogMessage(TRACE, "TRACE", message); } /** * Dump memory statistics at this point. Dump if level >= DEBUG. * * @param msg message to be logged */ public static void memoryStats(String msg) { // Try to force a garbage collection, so we get the real amount of // available memory long available = Runtime.getRuntime().freeMemory(); Runtime.getRuntime().gc(); writeLogMessage(PROFILING, "PROFILING-MEMORY", msg + ":" + available + " [bytes]"); } /** * Dump memory statistics at this point. * * @param obj caller object * @param msg message to be logged */ public static void memoryStats(Object obj, String msg) { // Try to force a garbage collection, so we get the real amount of // available memory Runtime.getRuntime().gc(); long available = Runtime.getRuntime().freeMemory(); writeLogMessage(PROFILING, "PROFILING-MEMORY", obj.getClass().getName() + "::" + msg + ":" + available + " [bytes]"); } /** * Dump time statistics at this point. * * @param msg message to be logged */ public static void timeStats(String msg) { long time = System.currentTimeMillis(); if (initialTimeStamp == -1) { writeLogMessage(PROFILING, "PROFILING-TIME", msg + ": 0 [msec]"); initialTimeStamp = time; } else { long currentTime = time - initialTimeStamp; writeLogMessage(PROFILING, "PROFILING-TIME", msg + ": " + currentTime + "[msec]"); } } /** * Dump time statistics at this point. * * @param obj caller object * @param msg message to be logged */ public static void timeStats(Object obj, String msg) { // Try to force a garbage collection, so we get the real amount of // available memory long time = System.currentTimeMillis(); if (initialTimeStamp == -1) { writeLogMessage(PROFILING, "PROFILING-TIME", obj.getClass().getName() + "::" + msg + ": 0 [msec]"); initialTimeStamp = time; } else { long currentTime = time - initialTimeStamp; writeLogMessage(PROFILING, "PROFILING-TIME", obj.getClass().getName() + "::" + msg + ":" + currentTime + " [msec]"); } } /** * Dump time statistics at this point. * * @param msg message to be logged */ public static void stats(String msg) { memoryStats(msg); timeStats(msg); } /** * Dump time statistics at this point. * * @param obj caller object * @param msg message to be logged */ public static void stats(Object obj, String msg) { memoryStats(obj, msg); timeStats(obj, msg); } private static void writeLogMessage(int msgLevel, String levelMsg, String msg) { if (level >= msgLevel) { try { if (out != null) { out.writeLogMessage(levelMsg, msg); } else { System.out.print(MailDateFormatter.dateToUTC(new Date())); System.out.print(" [" + levelMsg + "] " ); System.out.println(msg); } } catch (DataAccessException ex) { ex.printStackTrace(); } } } }
00piknik00-vardio
src/com/funambol/util/Log.java
Java
gpl3
10,123
/* * Funambol is a mobile platform developed by Funambol, Inc. * Copyright (C) 2003 - 2007 Funambol, Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by * the Free Software Foundation with the addition of the following permission * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * 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 Affero General Public License * along with this program; if not, see http://www.gnu.org/licenses or write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA. * * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License * version 3, these Appropriate Legal Notices must retain the display of the * "Powered by Funambol" logo. If the display of the logo is not reasonably * feasible for technical reasons, the Appropriate Legal Notices must display * the words "Powered by Funambol". */ package com.funambol.storage; /** * Represents a <i>"update"</i> error on device database. */ public class DataAccessException extends Exception { /** * */ private static final long serialVersionUID = -6695128856314376170L; /** * Creates a new instance of <code>DataAccessException</code> * without detail message. */ public DataAccessException() { } /** * Constructs an instance of <p><code>DataAccessException</code></p> * with the specified detail message. * @param msg the detail message. */ public DataAccessException(String msg) { super(msg); } }
00piknik00-vardio
src/com/funambol/storage/DataAccessException.java
Java
gpl3
2,440
/* * Funambol is a mobile platform developed by Funambol, Inc. * Copyright (C) 2003 - 2007 Funambol, Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by * the Free Software Foundation with the addition of the following permission * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * 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 Affero General Public License * along with this program; if not, see http://www.gnu.org/licenses or write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA. * * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License * version 3, these Appropriate Legal Notices must retain the display of the * "Powered by Funambol" logo. If the display of the logo is not reasonably * feasible for technical reasons, the Appropriate Legal Notices must display * the words "Powered by Funambol". */ package com.funambol.storage; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; /** * A simple interface to serialize objects on j2ME platform */ public interface Serializable { /** * Write object fields to the output stream. * @param out Output stream * @throws IOException */ void serialize(DataOutputStream out) throws IOException; /** * Read object field from the input stream. * @param in Input stream * @throws IOException */ void deserialize(DataInputStream in) throws IOException; }
00piknik00-vardio
src/com/funambol/storage/Serializable.java
Java
gpl3
2,415
package controlador; import java.awt.AWTEvent; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.List; import modelo.*; import vista.VentanaProducto; import vista.VentanaDetalleProductoTablaModel; public class ControladorVentanaProducto implements ActionListener{ private VentanaProducto ventanaProducto = new VentanaProducto(); public final List<DetalleProducto> productos = new ArrayList<DetalleProducto>(); private IngredienteDAO ingredienteDAO = new IngredienteDAO(); private ProductoDAO productoDAO = new ProductoDAO(); private CategoriaDAO categoriaDAO = new CategoriaDAO(); private DetalleProducto detProducto; public ControladorVentanaProducto() { super(); ventanaProducto = new VentanaProducto(); ventanaProducto.setLocationRelativeTo(null); ventanaProducto.setVisible(true); ventanaProducto.addListener(this); ingredienteDAO = new IngredienteDAO(); categoriaDAO = new CategoriaDAO(); List<String> milista1 = new ArrayList<String>(); milista1 = ingredienteDAO.consultarDescripcionIngredientes(); ventanaProducto.setCargarComboIngrediente(milista1); List<String> milista2 = new ArrayList<String>(); milista2=categoriaDAO.consultarCategoriasNombre(); ventanaProducto.setCargarComboCategoria(milista2); ventanaProducto.setJtxtcodIngrediente(ingredienteDAO.buscarIngrediente(ventanaProducto.getJcmbIngredientes())); ventanaProducto.setJtxtCodCategoria(categoriaDAO.buscarCategoria(ventanaProducto.getJcmbNombreCategoria())); } public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("Registrar")) RegistrarProducto(); else if(e.getActionCommand().equals("Agregar")){ CargarIngrediente(ventanaProducto.getcodIngrediente(),ventanaProducto.getJcmbIngredientes(),ventanaProducto.getCantidad()); } else if(e.getActionCommand().equals("Consultar")){ BuscarProducto(); } else if(e.getActionCommand().equals("Cancelar")) ventanaProducto.borrarDatos(); else if(e.getActionCommand().equals("Salir")) ventanaProducto.dispose(); if(!(ventanaProducto.getJcmbIngredientes().equals(AWTEvent.MOUSE_EVENT_MASK))){ ventanaProducto.setJtxtcodIngrediente(ingredienteDAO.buscarIngrediente(ventanaProducto.getJcmbIngredientes())); } //Aqui un pequeño problema, que solo hace esto, solo si el if de arriba se cumple...rayos. if(!(ventanaProducto.getJcmbNombreCategoria().equals(AWTEvent.MOUSE_EVENT_MASK))){ ventanaProducto.setJtxtCodCategoria(categoriaDAO.buscarCategoria(ventanaProducto.getJcmbNombreCategoria())); } } public void RegistrarProducto() { try { if( ventanaProducto.getCodProducto().equals("")|| ventanaProducto.getDescripcionProd().equals("")|| ventanaProducto.getCantidad().equals("")|| ventanaProducto.getFechaRegistro().equals("")|| ventanaProducto.getCodCategoria().equals("")) //Deben estar todos los campos llenos para poder registrar el Producto ventanaProducto.mostrarMensaje("Debe llenar todos los campos"); else { productoDAO = new ProductoDAO(); if (productoDAO.consultarProducto(ventanaProducto.getCodProducto()).equals(null)){ String codProducto = ventanaProducto.getCodProducto(); String codCategoria = ventanaProducto.getCodCategoria(); String descripcionProd = ventanaProducto.getDescripcionProd(); String fechaRegistro = ventanaProducto.getFechaRegistro(); float precio = Float.parseFloat(ventanaProducto.getPrecio()); int cantidad = productoDAO.consultarProductos().size() + 1; Producto producto = new Producto(codProducto,descripcionProd,codCategoria,fechaRegistro,precio,cantidad); productoDAO.registrarProducto(producto); DetalleProducto detProducto; for(int i = 0; i < ventanaProducto.getjTableIngredientes().getRowCount(); i++) { String codIng = ventanaProducto.getjTableIngredientes().getValueAt(i,0).toString(); String descIng = ventanaProducto.getjTableIngredientes().getValueAt(i,1).toString(); float cant = Float.parseFloat(ventanaProducto.getjTableIngredientes().getValueAt(i,2).toString()); productoDAO = new ProductoDAO(); detProducto = new DetalleProducto(codProducto,codIng,descIng,cant); productoDAO.registrarDetalleProducto(detProducto); } ventanaProducto.borrarDatos(); ventanaProducto.mostrarMensaje("El Producto se ha registrado exitosamente"); } else ventanaProducto.mostrarMensaje("El Producto ya se encuentra registrado"); } } catch(Exception e) { ventanaProducto.mostrarMensaje("El Producto No se pudo registrar, verifique que los datos sean correctos"); ventanaProducto.borrarDatos(); } } public void BuscarProducto() { if(ventanaProducto.getCodProducto().equals("")){ ventanaProducto.mostrarMensaje("Debe llenar el campo referente al campo codigo del producto"); } else{ String codigo = ventanaProducto.getCodProducto(); if (!productoDAO.consultarProducto(codigo).equals(null)){ String desc = productoDAO.consultarProducto(codigo).getDescripcionProd(); String codCateg = productoDAO.consultarProducto(codigo).getCodCategoria(); String descCateg = categoriaDAO.consultarCategoria(ventanaProducto.getCodCategoria()); ventanaProducto.mostrarMensaje(codCateg); ventanaProducto.mostrarMensaje(descCateg); String prec = String.valueOf(productoDAO.consultarProducto(codigo).getPrecio()); String fec = productoDAO.consultarProducto(codigo).getFechaRegistro(); ventanaProducto.setJtxtDescripcionProd(desc); ventanaProducto.setJtxtfechaRegistro(fec); ventanaProducto.setJtxtCodCategoria(codCateg); ventanaProducto.setJcmbNombreCateg2(descCateg); ventanaProducto.setJtxtPrecio(prec); } else ventanaProducto.mostrarMensaje("Producto no encontrado, por favor verifique"); } } public void CargarIngrediente(String codIng, String desc, String cant){ try { if(ventanaProducto.getCantidad().equals("")|| ventanaProducto.getcodIngrediente().equals("")) { ventanaProducto.mostrarMensaje("Debe llenar los campos referentes al ingrediente a cargar"); } else { try { detProducto = new DetalleProducto(codIng,desc,Float.parseFloat(cant)); productos.add(detProducto); ventanaProducto.setResultados(new VentanaDetalleProductoTablaModel(productos)); ventanaProducto.mostrarMensaje("Ingrediente cargado a la Lista..."); } catch(Exception e) { ventanaProducto.mostrarMensaje("El ingrediente ya se cargo a la lista...Verifque"); } } } catch(Exception e) { ventanaProducto.mostrarMensaje("El Ingrediente No se pudo agregar, verifique que los datos sean correctos"); ventanaProducto.borrarDatos(); } } }
1-1-cuarta-entrega
trunk/ProyectoVentaComidaRapida(NUEVO)/src/controlador/ControladorVentanaProducto.java
Java
asf20
6,796
package controlador; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.List; import modelo.DetalleOrden; import modelo.DetalleOrdenDAO; import vista.VentanaConsultaProducto; import vista.VentanaTablaModeloProducto; public class ControladorDetalleOrden/* implements ActionListener*/{ private VentanaConsultaProducto ventanaConsulta; public ControladorDetalleOrden() { super (); ventanaConsulta = new VentanaConsultaProducto (); ventanaConsulta.setLocationRelativeTo(null); ventanaConsulta.setVisible(true); ventanaConsulta.addListener(ventanaConsulta); } /* public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub if(e.getActionCommand().equals("Salir")) ventanaConsulta.dispose(); else if (e.getActionCommand().equals("Cantidad Ascendente")) { DetalleOrdenDAO detordenDAO = new DetalleOrdenDAO(); List<DetalleOrden> prod = detordenDAO.consultarProductoCantidadAscendente(); this.ventanaConsulta.setResultados(new VentanaTablaModeloProducto(prod)); } else if (e.getActionCommand().equals("Cantidad Descendente")) { DetalleOrdenDAO detordenDAO = new DetalleOrdenDAO(); List<DetalleOrden> prod = detordenDAO.consultarProductoCantidadDescendente(); this.ventanaConsulta.setResultados(new VentanaTablaModeloProducto(prod)); } else if (e.getActionCommand().equals("Monto Ascendente")) { DetalleOrdenDAO detordenDAO = new DetalleOrdenDAO(); List<DetalleOrden> prod = detordenDAO.consultarProductoMontoAscendente(); this.ventanaConsulta.setResultados(new VentanaTablaModeloProducto(prod)); } else if (e.getActionCommand().equals("Monto Descendente")) { DetalleOrdenDAO detordenDAO = new DetalleOrdenDAO(); List<DetalleOrden> prod = detordenDAO.consultarProductoMontoDescendente(); this.ventanaConsulta.setResultados(new VentanaTablaModeloProducto(prod)); } } */ }
1-1-cuarta-entrega
trunk/ProyectoVentaComidaRapida(NUEVO)/src/controlador/ControladorDetalleOrden.java
Java
asf20
1,911
package controlador; import java.awt.AWTEvent; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.List; import vista.VentanaCargaCompra; import modelo.IngredienteDAO; public class ControladorVentanaCompraIngredientes implements ActionListener { private VentanaCargaCompra ventcargacompra; private IngredienteDAO ingredienteDAO = new IngredienteDAO(); public ControladorVentanaCompraIngredientes () { super (); ventcargacompra = new VentanaCargaCompra(); ventcargacompra.setLocationRelativeTo(null); ventcargacompra.setVisible(true); ventcargacompra.addListener(this); ingredienteDAO = new IngredienteDAO(); List<String> milista1 = new ArrayList<String>(); milista1 = ingredienteDAO.consultarDescripcionIngredientes(); ventcargacompra.setcargarComboIngredientes(milista1); ventcargacompra.setJtxtCodIngrediente(ingredienteDAO.buscarIngrediente(ventcargacompra.getJcmbCompraIngredientes())); } public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub if(e.getActionCommand().equals("Salir")) ventcargacompra.dispose(); else if (e.getActionCommand().equals("Actualizar Inventario")) { if(Float.valueOf(ventcargacompra.getCantComprada()) > 0){ IngredienteDAO ingredienteDAO = new IngredienteDAO(); String codigo; codigo = ventcargacompra.getCodIngrediente(); String cantidadComprada = ventcargacompra.getCantComprada(); ingredienteDAO.actualizarInventario(codigo, 0, Float.parseFloat(cantidadComprada)); ventcargacompra.mostrarMensaje("Compra de ingredientes se registro con exito"); } else ventcargacompra.mostrarMensaje("Ingrese una cantidad del ingrediente mayor que cero"); } else if(e.getActionCommand().equals("Salir")) ventcargacompra.dispose(); if(!(ventcargacompra.getJcmbCompraIngredientes().equals(AWTEvent.MOUSE_EVENT_MASK))){ ventcargacompra.setJtxtCodIngrediente(ingredienteDAO.buscarIngrediente(ventcargacompra.getJcmbCompraIngredientes())); } } }
1-1-cuarta-entrega
trunk/ProyectoVentaComidaRapida(NUEVO)/src/controlador/ControladorVentanaCompraIngredientes.java
Java
asf20
2,045
package controlador; import java.awt.AWTEvent; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import modelo.CategoriaDAO; import modelo.Cliente; import modelo.ClienteDAO; import modelo.DetalleProducto; import modelo.Ingrediente; import modelo.IngredienteDAO; import modelo.Producto; import modelo.ProductoDAO; import java.util.ArrayList; import java.util.List; import java.util.Vector; import modelo.*; import vista.VentanaConsultaProducto; import vista.VentanaIngredienteModeloTabla; import vista.VentanaOrden; import vista.VentanaTablaOrdenProducto; public class ControladorVentanaOrden implements ActionListener { private VentanaOrden ventanaOrden; private CategoriaDAO categoriaDAO = new CategoriaDAO(); private ProductoDAO productoDAO = new ProductoDAO(); private OrdenDAO ordenDAO = new OrdenDAO(); private DetalleOrdenDAO detOrdenDAO = new DetalleOrdenDAO(); private DetalleOrden detOrden = new DetalleOrden(); private ClienteDAO clienteDAO = new ClienteDAO(); float valor = 0; float valortotal = 0; public ControladorVentanaOrden() { super(); ventanaOrden = new VentanaOrden(); ventanaOrden.setLocationRelativeTo(null); ventanaOrden.setVisible(true); ventanaOrden.addListener(this); List<String> milista= new ArrayList<String>(); milista=categoriaDAO.consultarCategoriasNombre(); ventanaOrden.setcargarComboCategoria(milista); List<String> milistaproductos= new ArrayList<String>(); milistaproductos= productoDAO.consultarProductosNombre(); ventanaOrden.setcargarComboProducto(milistaproductos); ventanaOrden.setJtxtcodcategoria(categoriaDAO.buscarCategoria(ventanaOrden.getJcmbCategoriaOrden())); ventanaOrden.setcargarComboProducto(milistaproductos); ventanaOrden.setcargarComboProducto(productoDAO.buscarProductosCategoria(ventanaOrden.getJtxtcodcategoria())); ventanaOrden.setJtxtCodProductoOrden(productoDAO.buscarCodProducto(ventanaOrden.getJcmbProductoOrden())); } public void actionPerformed(ActionEvent e) { String actionCommand = e.getActionCommand(); if (actionCommand.equals("Registrar")) { RegistrarCliente(); } else if(e.getActionCommand().equals("Procesar")){ ProcesarOrden(); } else if(actionCommand.equals("Buscar")){ BuscarCliente(); } else if(actionCommand.equals("Cancelar")) ventanaOrden.borrarDatos(); else if(actionCommand.equals("Salir")) ventanaOrden.dispose(); else if(!(ventanaOrden.getJcmbCategoriaOrden().equals(AWTEvent.MOUSE_EVENT_MASK))){ ventanaOrden.setJtxtcodcategoria(categoriaDAO.buscarCategoria(ventanaOrden.getJcmbCategoriaOrden())); ventanaOrden.setcargarComboProducto(productoDAO.buscarProductosCategoria(ventanaOrden.getJtxtcodcategoria())); } else if(!(ventanaOrden.getJcmbCategoriaOrden().equals(AWTEvent.MOUSE_EVENT_MASK))){ ventanaOrden.setJtxtCodProductoOrden(productoDAO.buscarCodProducto(ventanaOrden.getJcmbProductoOrden())); } if (actionCommand.equals("Cargar Productos ")){ ProductoDAO productoDAO = new ProductoDAO(); List<Producto> productos = productoDAO.consultarProductos(); this.ventanaOrden.IngresarProductos(new VentanaTablaOrdenProducto(productos)); for(int i = 0; i < ventanaOrden.getjTableOrdenProducto().getRowCount(); i++){ valor = Float.parseFloat(ventanaOrden.getjTableOrdenProducto().getValueAt(i,2).toString()); valortotal = valortotal + valor; } String nuevovalor =String.valueOf(valortotal); ventanaOrden.setJtxtTotalPagar(nuevovalor); } } public void RegistrarCliente() { try { if( ventanaOrden.getCedulaCli().equals("")|| ventanaOrden.getNombre().equals("")|| ventanaOrden.getApellido().equals("")|| ventanaOrden.getDireccion().equals("")|| ventanaOrden.getTelefono().equals("")) ventanaOrden.mostrarMensaje("Debe llenar todos los campos"); else { if (clienteDAO.buscarCliente(ventanaOrden.getCedulaCli()).equals(null)){ ClienteDAO clienteDAO = new ClienteDAO(); String cedula = ventanaOrden.getCedulaCli(); String nombre = ventanaOrden.getNombre(); String apellido = ventanaOrden.getApellido(); String direccion = ventanaOrden.getDireccion(); String telefono = ventanaOrden.getTelefono(); Cliente cliente = new Cliente(cedula,nombre,apellido,direccion,telefono); clienteDAO.registrarCliente(cliente); ventanaOrden.mostrarMensaje("El cliente se ha registrado exitosamente"); ventanaOrden.CamposNoEditables(); } else ventanaOrden.mostrarMensaje("Cliente ya registrado en nuestra base de datos"); } } catch(Exception e) { ventanaOrden.mostrarMensaje("El Cliente No se pudo registrar, verifique que los datos sean correctos"); ventanaOrden.borrarDatos(); } } public void ProcesarOrden(){ try { if( ventanaOrden.getCodProductoOrden().equals("")|| ventanaOrden.getCodOrden().equals("")|| ventanaOrden.getApellido().equals("")|| ventanaOrden.getCedulaCli().equals("")|| ventanaOrden.getTotalPagar().equals("")|| ventanaOrden.getFechaOrden().equals("")|| ventanaOrden.getTelefono().equals("")){ ventanaOrden.mostrarMensaje("Debe llenar todos los campos"); } else if(ventanaOrden.getTotalPagar().equals("")) ventanaOrden.mostrarMensaje("Debe ingresar por lo menos un producto a la orden"); else { productoDAO = new ProductoDAO(); String codOrden = ventanaOrden.getCodOrden(); String cedulaCli = ventanaOrden.getCedulaCli(); String fechaOrden = ventanaOrden.getFechaOrden(); float totalPagar = Float.parseFloat(ventanaOrden.getTotalPagar()); Orden orden = new Orden(codOrden,cedulaCli,fechaOrden,totalPagar); ordenDAO.registrarOrden(orden); DetalleOrden detOrden; for(int i = 0; i < ventanaOrden.getjTableOrdenProducto().getRowCount(); i++) { String codProducto = ventanaOrden.getjTableOrdenProducto().getValueAt(i,0).toString(); String descProd = ventanaOrden.getjTableOrdenProducto().getValueAt(i,1).toString(); float precio = Float.parseFloat(ventanaOrden.getjTableOrdenProducto().getValueAt(i,2).toString()); int cant = Integer.parseInt(ventanaOrden.getjTableOrdenProducto().getValueAt(i,3).toString()); ordenDAO = new OrdenDAO(); detOrden = new DetalleOrden(codOrden,codProducto,descProd,cant,precio); detOrdenDAO.registrarDetalleOrden(detOrden); } ventanaOrden.borrarDatos(); ventanaOrden.mostrarMensaje("La Orden se ha procesado exitosamente"); } } catch(Exception e) { ventanaOrden.mostrarMensaje("La Orden No se pudo procesar, verifique que los datos sean correctos"); ventanaOrden.borrarDatos(); } } public void BuscarCliente(){ if(ventanaOrden.getCedulaCli().equals("")){ ventanaOrden.mostrarMensaje("Debe llenar el campo referente al campo cedula del cliente"); } else{ String cedula = ventanaOrden.getCedulaCli(); if (!clienteDAO.buscarCliente(cedula).equals(null)){ String nomb = clienteDAO.buscarCliente(cedula).getNombre(); String apell = clienteDAO.buscarCliente(cedula).getApellido(); String dir = clienteDAO.buscarCliente(cedula).getDireccion(); String telf = clienteDAO.buscarCliente(cedula).getTelefono(); ventanaOrden.setJtxtNombreCli(nomb); ventanaOrden.setJtxtApellido(apell); ventanaOrden.setJtxtDireccion(dir); ventanaOrden.setJtxtTelefono(telf); } else ventanaOrden.mostrarMensaje("Cliente no encontrado, por favor verifique"); } } }
1-1-cuarta-entrega
trunk/ProyectoVentaComidaRapida(NUEVO)/src/controlador/ControladorVentanaOrden.java
Java
asf20
7,496
package controlador; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.List; import modelo.Ingrediente; import modelo.IngredienteDAO; import modelo.ProbarMetodosFabricaCreador; import vista.VentanaIngredienteModeloTabla; import vista.VentanaPrincipalMagnifico; public class ControladorVentanaPrincipalMagnifico implements ActionListener { private VentanaPrincipalMagnifico ventanaPrincipal; public ControladorVentanaPrincipalMagnifico() { super(); this.ventanaPrincipal = new VentanaPrincipalMagnifico(); this.ventanaPrincipal.addListener(this); this.ventanaPrincipal.setVisible(true); } @Override public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("Tomar Orden")){ new ControladorVentanaOrden(); } else if(e.getActionCommand().equals("Gestionar Categoria")){ new ControladorCategoria(); } else if (e.getActionCommand().equals("Gestionar Producto")){ new ControladorVentanaProducto(); } else if (e.getActionCommand().equals("Cantidad Disponible de Ingredientes")){ new ControladorIngrediente(); } else if (e.getActionCommand().equals("Venta de Productos")){ new ControladorDetalleOrden(); } else if(e.getActionCommand().equals("Comprar Ingredientes")){ new ControladorVentanaCompraIngredientes(); } else if(e.getActionCommand().equals("Salir")) System.exit(0); } }
1-1-cuarta-entrega
trunk/ProyectoVentaComidaRapida(NUEVO)/src/controlador/ControladorVentanaPrincipalMagnifico.java
Java
asf20
1,849
package controlador; import java.awt.event.ActionListener; import modelo.Categoria; import modelo.CategoriaDAO; import modelo.ProbarMetodosFabricaCreador; import java.awt.event.ActionEvent; import vista.VentanaCategoria; public class ControladorCategoria implements ActionListener { private VentanaCategoria ventanaCategoria; public ControladorCategoria() { super(); this.ventanaCategoria = new VentanaCategoria(); this.ventanaCategoria.setLocationRelativeTo(null); this.ventanaCategoria.setVisible(true); this.ventanaCategoria.addListener(this); new ProbarMetodosFabricaCreador(); } @Override public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("Registrar")){ RegistrarCategoria(); } else if (e.getActionCommand().equals("Buscar")){ ConsultarCategoria(); } else if (e.getActionCommand().equals("Cancelar")){ ventanaCategoria.borrarDatos(); } else if(e.getActionCommand().equals("Salir")) ventanaCategoria.dispose(); } public void RegistrarCategoria(){ try { if(ValidarCampos()==false) ventanaCategoria.mostrarMensaje("Debe llenar todos los campos"); else { CategoriaDAO categoriaDAO = new CategoriaDAO(); if(categoriaDAO.SoloBuscar(ventanaCategoria.getCodCategoria())==false) { Categoria categoria = new Categoria(ventanaCategoria.getCodCategoria(),ventanaCategoria.getDescripcionCateg()); categoriaDAO.registrarCategoria(categoria); ventanaCategoria.mostrarMensaje("La Categoria se ha registrado exitosamente"); ventanaCategoria.borrarDatos(); } else ventanaCategoria.mostrarMensaje("La Categoria ya se encuentra registrada"); } } catch(Exception e) { ventanaCategoria.mostrarMensaje("La Categoria No se pudo registrar, verifique que los datos sean correctos"); ventanaCategoria.borrarDatos(); } } public void ConsultarCategoria(){ if (ventanaCategoria.getCodCategoria().equals("")) { ventanaCategoria.mostrarMensaje("Verifique que el campo codigo no este vacio"); } else{ CategoriaDAO categoriaDAO = new CategoriaDAO(); String valor = categoriaDAO.consultarCategoria(ventanaCategoria.getCodCategoria()); ventanaCategoria.setJtxtDescripcionCateg(valor); if(valor.equals("")) ventanaCategoria.mostrarMensaje("Categoria no encontrada"); } } public boolean ValidarCampos(){ boolean validos = true; if (ventanaCategoria.getCodCategoria().equals("")|| ventanaCategoria.getDescripcionCateg().equals("")){ validos = false; } return validos; } }
1-1-cuarta-entrega
trunk/ProyectoVentaComidaRapida(NUEVO)/src/controlador/ControladorCategoria.java
Java
asf20
2,561
package controlador; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.List; import vista.VentanaConsulta; import vista.VentanaIngredienteModeloTabla; import modelo.Ingrediente; import modelo.IngredienteDAO; public class ControladorIngrediente implements ActionListener { private VentanaConsulta ventanaConsulta; public ControladorIngrediente () { super (); ventanaConsulta = new VentanaConsulta(); ventanaConsulta.setLocationRelativeTo(null); ventanaConsulta.setVisible(true); ventanaConsulta.addListener(this); } public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub if(e.getActionCommand().equals("Salir")) ventanaConsulta.dispose(); else if (e.getActionCommand().equals("Consultar")) { IngredienteDAO ingredienteDAO = new IngredienteDAO(); List<Ingrediente> ingredient = ingredienteDAO.consultarIngredientes(); this.ventanaConsulta.setResultados(new VentanaIngredienteModeloTabla (ingredient)); } } }
1-1-cuarta-entrega
trunk/ProyectoVentaComidaRapida(NUEVO)/src/controlador/ControladorIngrediente.java
Java
asf20
1,299
import controlador.ControladorVentanaPrincipalMagnifico; public class Principal { /* Ingregantes del Equipo #1 Seccion 01 Chaviel Jorge G. CI: 17.943.679 Saez Karol M. CI: 19.854.479 Cuauro Yurbely. CI: 19.679.478 */ public static void main(String[] args) { new ControladorVentanaPrincipalMagnifico(); } }
1-1-cuarta-entrega
trunk/ProyectoVentaComidaRapida(NUEVO)/src/Principal.java
Java
asf20
332
package vista; import javax.swing.table.AbstractTableModel; import modelo.DetalleOrden; import modelo.Producto; import java.util.ArrayList; import java.util.List; public class VentanaTablaOrdenProducto extends AbstractTableModel { private static String[] titulos = {"Codigo Producto", "Descripcion", "Precio (Bs.F)", "Cantidad Solicitada"}; private List<Producto> product = new ArrayList<Producto>(); public VentanaTablaOrdenProducto (List<Producto> productos) { super(); this.product = productos; this.fireTableDataChanged(); } //lo llena con la cantidad de productos que tiene la base de datos @Override public int getRowCount() { // TODO Auto-generated method stub return product.size(); } //Coloca la cantidad de columnas por titulos @Override public int getColumnCount() { return titulos.length; } @Override public Object getValueAt(int rowIndex, int columnIndex) { { Producto productoOrden = product.get(rowIndex); switch (columnIndex) { case 0: return productoOrden.getCodProducto(); case 1: return productoOrden.getDescripcionProd(); case 2: return productoOrden.getPrecio(); case 3: return 99; } return null; } } @Override public String getColumnName(int column) { return titulos[column]; } //para que la columna 4 de la cantidad solicitada por el cliente sea editable y las demás no public boolean isCellEditable(int row, int column) { if (column == 3) return true; return false; } }
1-1-cuarta-entrega
trunk/ProyectoVentaComidaRapida(NUEVO)/src/vista/VentanaTablaOrdenProducto.java
Java
asf20
1,928
package vista; //import com.cloudgarden.layout.AnchorLayout; //import java.awt.BorderLayout; import java.awt.event.ActionListener; import javax.swing.BorderFactory; //import javax.swing.DefaultComboBoxModel; //import javax.swing.GroupLayout; import javax.swing.ImageIcon; import javax.swing.JButton; //import javax.swing.JComponent; import javax.swing.JLabel; //import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; //import javax.swing.LayoutStyle; //import javax.swing.ListModel; import javax.swing.WindowConstants; import javax.swing.border.BevelBorder; //import javax.swing.table.DefaultTableModel; //import javax.swing.table.TableModel; //import javax.swing.SwingUtilities; import javax.swing.table.AbstractTableModel; /** * This code was edited or generated using CloudGarden's Jigloo * SWT/Swing GUI Builder, which is free for non-commercial * use. If Jigloo is being used commercially (ie, by a corporation, * company or business for any purpose whatever) then you * should purchase a license for each developer using Jigloo. * Please visit www.cloudgarden.com for details. * Use of Jigloo implies acceptance of these licensing terms. * A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR * THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED * LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE. */ public class VentanaConsulta extends javax.swing.JFrame { /*{ //Set Look & Feel try { javax.swing.UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel"); } catch(Exception e) { e.printStackTrace(); } }*/ private JPanel jpanConsulta; private JTable jtblConsulta; private JButton jbtnImagen; private JButton jbtnSalir; private JScrollPane jScrollPaneConsulta; private JLabel jlbltitulo; private JButton jbtnConsultar; /** * Auto-generated main method to display this JFrame */ /*public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { VentanaConsulta inst = new VentanaConsulta(); inst.setLocationRelativeTo(null); inst.setVisible(true); } }); }*/ public VentanaConsulta() { super(); initGUI(); } private void initGUI() { try { setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); getContentPane().setLayout(null); getContentPane().setBackground(new java.awt.Color(82,209,232)); { jpanConsulta = new JPanel(); getContentPane().add(jpanConsulta, "Center"); jpanConsulta.setLayout(null); jpanConsulta.setBounds(24, 12, 626, 285); jpanConsulta.setBackground(new java.awt.Color(255,255,255)); { jbtnConsultar = new JButton(); jpanConsulta.add(jbtnConsultar); jbtnConsultar.setText("Consultar"); jbtnConsultar.setBounds(511, 193, 103, 25); jbtnConsultar.setBackground(new java.awt.Color(82,209,232)); jbtnConsultar.setBorder(BorderFactory.createEtchedBorder(BevelBorder.LOWERED)); } { jlbltitulo = new JLabel(); jpanConsulta.add(jlbltitulo); jlbltitulo.setText("Cantidad Disponible de Cada Ingrediente"); jlbltitulo.setBounds(18, 40, 584, 28); jlbltitulo.setBorder(BorderFactory.createEtchedBorder(BevelBorder.LOWERED)); jlbltitulo.setBackground(new java.awt.Color(82,209,232)); } { jScrollPaneConsulta = new JScrollPane(); jpanConsulta.add(jScrollPaneConsulta); jScrollPaneConsulta.setBounds(204, 85, 301, 170); { jtblConsulta = new JTable(); jScrollPaneConsulta.setViewportView(jtblConsulta); jtblConsulta.setPreferredSize(new java.awt.Dimension(276, 168)); /*GroupLayout jTable1Layout = new GroupLayout((JComponent)jtblConsulta); jtblConsulta.setLayout(null); //jtblConsulta.setModel(jTable1Model); jtblConsulta.setBounds(18, 146, 159, 91); jtblConsulta.setPreferredSize(new java.awt.Dimension(215, 156)); jTable1Layout.setVerticalGroup(jTable1Layout.createSequentialGroup()); jTable1Layout.setHorizontalGroup(jTable1Layout.createSequentialGroup());*/ } } { jbtnSalir = new JButton(); jpanConsulta.add(jbtnSalir); jbtnSalir.setText("Salir"); jbtnSalir.setBounds(511, 230, 103, 25); jbtnSalir.setBackground(new java.awt.Color(82,209,232)); jbtnSalir.setBorder(BorderFactory.createEtchedBorder(BevelBorder.LOWERED)); } { jbtnImagen = new JButton(); jbtnImagen.setIcon(new ImageIcon(getClass().getClassLoader().getResource("imagen.jpg"))); jpanConsulta.add(jbtnImagen); jbtnImagen.setBounds(18, 97, 180, 152); jbtnImagen.setBackground(new java.awt.Color(82,209,232)); jbtnImagen.setBorder(BorderFactory.createEtchedBorder(BevelBorder.LOWERED)); } } pack(); this.setSize(670, 339); } catch (Exception e) { //add your error handling code here e.printStackTrace(); } } public void addListener(ActionListener actionListener) { this.jbtnConsultar.addActionListener(actionListener); this.jbtnSalir.addActionListener(actionListener); } public void setResultados(AbstractTableModel abstractTableModel) { jtblConsulta.setModel(abstractTableModel); } }
1-1-cuarta-entrega
trunk/ProyectoVentaComidaRapida(NUEVO)/src/vista/VentanaConsulta.java
Java
asf20
7,812
package vista; import java.util.ArrayList; import java.util.List; import javax.swing.table.AbstractTableModel; import modelo.DetalleOrden; public class VentanaTablaModeloProducto extends AbstractTableModel{ private static String[] titulos = {"Código Producto","Descripción","Cantidad", "Monto"}; private List<DetalleOrden> producto = new ArrayList<DetalleOrden>(); public VentanaTablaModeloProducto(List<DetalleOrden> product) { super(); this.producto = product; this.fireTableDataChanged(); } @Override public int getColumnCount() { return titulos.length; } @Override public int getRowCount() { return producto.size(); } @Override public Object getValueAt(int rowIndex, int columnIndex) { DetalleOrden prod = producto.get(rowIndex); switch (columnIndex) { case 0: return prod.getCodProducto(); case 1: return prod.getDescripcionProd(); case 2: return prod.getCantidadProd(); case 3: return prod.getMonto(); } return null; } @Override public String getColumnName(int column) { return titulos[column]; } }
1-1-cuarta-entrega
trunk/ProyectoVentaComidaRapida(NUEVO)/src/vista/VentanaTablaModeloProducto.java
Java
asf20
1,408
//modificado.. package vista; import java.awt.BorderLayout; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.List; import javax.swing.BorderFactory; import javax.swing.ComboBoxModel; import javax.swing.DefaultComboBoxModel; import javax.swing.GroupLayout; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JInternalFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollBar; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.LayoutStyle; import javax.swing.ListModel; import javax.swing.SwingUtilities; import javax.swing.WindowConstants; import javax.swing.border.BevelBorder; import javax.swing.table.AbstractTableModel; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableModel; import modelo.Categoria; import modelo.DetalleProducto; import modelo.Ingrediente; /** * This code was edited or generated using CloudGarden's Jigloo * SWT/Swing GUI Builder, which is free for non-commercial * use. If Jigloo is being used commercially (ie, by a corporation, * company or business for any purpose whatever) then you * should purchase a license for each developer using Jigloo. * Please visit www.cloudgarden.com for details. * Use of Jigloo implies acceptance of these licensing terms. * A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR * THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED * LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE. */ public class VentanaProducto extends javax.swing.JFrame{ private JPanel jPanel1; private JTextField jtxtfechaRegistro; private JLabel jlblfechaRegistro; private JButton jbtnSalir; private JButton jbtnCancelar; private JButton jbtnAgregar; private JTable jTableIngredientes; private JButton jbtnImagen; private JLabel jlbldetalles; private JLabel jlblcodProducto; private JTextField jtxtcodIngrediente; private JLabel jlblIngrediente; private JTextField jtxtPrecio; private JTextField jtxtCodCategoria; private JButton jbtnRegistrar; private JLabel jlblListaIngredientes; private JComboBox jcmbNombreCategoria; private JScrollBar jScrollBarIngredienteProducto; private JPanel jPanIngredienteProducto; private JLabel jlblNombreCategoria; private JLabel jlblCodigoCategoria; private JLabel jlblCantidad; private JTextField jtxtCantidad; private JComboBox jcmbIngredientes; private JButton jbtnConsultar; private JTextField jtxtDescripcionProd; private JLabel jlblDescripcionProd; private JLabel jlblDatosProducto; private JTextField jtxtCodProducto; /** * Auto-generated main method to display this JFrame */ public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { VentanaProducto instProd = new VentanaProducto(); instProd.setLocationRelativeTo(null); instProd.setVisible(true); } }); } public VentanaProducto() { super(); initGUI(); } private void initGUI() { try { this.setTitle("Gestionar Producto"); getContentPane().setLayout(null); getContentPane().setBackground(new java.awt.Color(82,209,232)); jPanel1 = new JPanel(); getContentPane().add(jPanel1, "Center"); jPanel1.setLayout(null); jPanel1.setBackground(new java.awt.Color(255,255,255)); jPanel1.setBounds(12, 12, 727, 671); { jtxtCodProducto = new JTextField(); } { jlblDescripcionProd = new JLabel(); jlblDescripcionProd.setText("Descripcion:"); } { jtxtDescripcionProd = new JTextField(); } { jlblDatosProducto = new JLabel(); jlblDatosProducto.setText("Datos del Producto"); } { jbtnConsultar = new JButton(); jbtnConsultar.setText("Consultar"); jbtnConsultar.setBounds(636, 91, 76, 21); } { jbtnSalir = new JButton(); jPanel1.add(jbtnSalir); jPanel1.add(jbtnConsultar); jbtnConsultar.setBackground(new java.awt.Color(82,209,232)); jbtnConsultar.setBorder(BorderFactory.createEtchedBorder(BevelBorder.LOWERED)); jPanel1.add(jtxtDescripcionProd); jPanel1.add(jtxtCodProducto); jPanel1.add(jlblDescripcionProd); jlblDescripcionProd.setBounds(312, 131, 82, 14); { jtxtCantidad = new JTextField(); } { jlblCantidad = new JLabel(); jlblCantidad.setText("Cantidad"); } jtxtCodProducto.setBounds(488, 91, 133, 21); jtxtDescripcionProd.setBounds(488, 128, 133, 21); jbtnSalir.setText("Salir"); jbtnSalir.setBounds(449, 601, 82, 27); jbtnSalir.setBackground(new java.awt.Color(82,209,232)); jbtnSalir.setBorder(BorderFactory.createEtchedBorder(BevelBorder.LOWERED)); } { jlblfechaRegistro = new JLabel(); jPanel1.add(jlblfechaRegistro); jPanel1.add(jlblDatosProducto); jlblDatosProducto.setBounds(75, 43, 546, 28); jlblDatosProducto.setBackground(new java.awt.Color(82,209,232)); jlblDatosProducto.setBorder(BorderFactory.createEtchedBorder(BevelBorder.LOWERED)); jlblfechaRegistro.setText("Fecha del Registro:"); jlblfechaRegistro.setBounds(312, 167, 127, 14); } { jtxtfechaRegistro = new JTextField(); jPanel1.add(jtxtfechaRegistro); jtxtfechaRegistro.setBounds(488, 160, 133, 21); } { jcmbIngredientes = new JComboBox(); jPanel1.add(jcmbIngredientes); jPanel1.add(jlblCantidad); jPanel1.add(jtxtCantidad); jtxtCantidad.setBounds(380, 368, 50, 22); { jlblCodigoCategoria = new JLabel(); jPanel1.add(jlblCodigoCategoria); jlblCodigoCategoria.setBounds(312, 201, 158, 14); jlblCodigoCategoria.setText("Nombre de la Categoria:"); } { jlblNombreCategoria = new JLabel(); jPanel1.add(jlblNombreCategoria); jlblNombreCategoria.setText("Código de la Categoría:"); jlblNombreCategoria.setBounds(312, 234, 153, 14); } { jPanIngredienteProducto = new JPanel(); jPanel1.add(jPanIngredienteProducto); jPanIngredienteProducto.setBounds(184, 434, 347, 133); jPanIngredienteProducto.setLayout(null); { jScrollBarIngredienteProducto = new JScrollBar(); jPanIngredienteProducto.add(jScrollBarIngredienteProducto); jScrollBarIngredienteProducto.setBounds(331, 0, 17, 133); } } { jcmbNombreCategoria = new JComboBox(); jPanel1.add(jcmbNombreCategoria); jcmbNombreCategoria.setBounds(488, 193, 133, 22); } { jbtnAgregar = new JButton(); jPanel1.add(jbtnAgregar); jbtnAgregar.setText("Agregar"); jbtnAgregar.setBounds(478, 366, 71, 24); jbtnAgregar.setBackground(new java.awt.Color(82,209,232)); jbtnAgregar.setBorder(BorderFactory.createEtchedBorder(BevelBorder.LOWERED)); } { jlblListaIngredientes = new JLabel(); jPanel1.add(jlblListaIngredientes); jlblListaIngredientes.setText("Listado de Ingredientes del Producto"); jlblListaIngredientes.setBounds(89, 401, 525, 21); jlblListaIngredientes.setBackground(new java.awt.Color(82,209,232)); jlblListaIngredientes.setBorder(BorderFactory.createEtchedBorder(BevelBorder.LOWERED)); } { jbtnRegistrar = new JButton(); jPanel1.add(jbtnRegistrar); jbtnRegistrar.setText("Registrar"); jbtnRegistrar.setBounds(242, 602, 82, 25); jbtnRegistrar.setBackground(new java.awt.Color(82,209,232)); jbtnRegistrar.setBorder(BorderFactory.createEtchedBorder(BevelBorder.LOWERED)); } { jtxtCodCategoria = new JTextField(); jPanel1.add(jtxtCodCategoria); { jtxtPrecio = new JTextField(); jPanel1.add(jtxtPrecio); jtxtPrecio.setBounds(488, 261, 133, 22); } { jlblIngrediente = new JLabel(); jPanel1.add(jlblIngrediente); jlblIngrediente.setText("Precio del Producto:"); jlblIngrediente.setBounds(312, 268, 134, 15); } { jtxtcodIngrediente = new JTextField(); jPanel1.add(jtxtcodIngrediente); { jlblcodProducto = new JLabel(); jPanel1.add(jlblcodProducto); jlblcodProducto.setText("Codigo:"); jlblcodProducto.setBounds(312, 98, 58, 15); } { jlbldetalles = new JLabel(); jPanel1.add(jlbldetalles); jlbldetalles.setText("Detalles del Producto"); jlbldetalles.setBounds(91, 323, 530, 30); jlbldetalles.setBackground(new java.awt.Color(82,209,232)); jlbldetalles.setBorder(BorderFactory.createEtchedBorder(BevelBorder.LOWERED)); } { jbtnCancelar = new JButton(); jPanel1.add(jbtnCancelar); jbtnCancelar.setText("Cancelar"); jbtnCancelar.setBounds(343, 603, 87, 24); jbtnCancelar.setBackground(new java.awt.Color(82,209,232)); jbtnCancelar.setBorder(BorderFactory.createEtchedBorder(BevelBorder.LOWERED)); } { jbtnImagen = new JButton(); jbtnImagen.setIcon(new ImageIcon(getClass().getClassLoader().getResource("imagen.jpg"))); jPanel1.add(jbtnImagen); jbtnImagen.setBounds(75, 95, 188, 160); jbtnImagen.setBackground(new java.awt.Color(82,209,232)); } { jTableIngredientes = new JTable(); jPanel1.add(jTableIngredientes); jTableIngredientes.setBounds(184, 437, 329, 133); } jtxtcodIngrediente.setBounds(562, 434, 44, 22); jtxtcodIngrediente.setVisible(false); jtxtcodIngrediente.setEditable(false); } jtxtCodCategoria.setText("codCateg"); jtxtCodCategoria.setBounds(488, 227, 133, 22); jtxtCodCategoria.setEditable(false); } jlblCantidad.setBounds(278, 371, 65, 15); jcmbIngredientes.setBounds(91, 365, 175, 22); } { this.setSize(759, 725); } } catch(Exception e) { e.printStackTrace(); } } /* public void RemoverProductos(final AbstractTableModel VentanaDetalleProductoTablaModel) { jTableIngredientes.setModel(VentanaDetalleProductoTablaModel); jTableIngredientes.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { int fila = jTableIngredientes.rowAtPoint(e.getPoint()); int columna = jTableIngredientes.columnAtPoint(e.getPoint()); if ((fila > -1) && (columna > -1)) System.out.println(VentanaDetalleProductoTablaModel.getValueAt(fila,columna)); } }); } */ public void addListener(ActionListener actionListener) { this.jcmbIngredientes.addActionListener(actionListener); this.jcmbNombreCategoria.addActionListener(actionListener); this.jbtnConsultar.addActionListener(actionListener); this.jbtnRegistrar.addActionListener(actionListener); this.jbtnCancelar.addActionListener(actionListener); this.jbtnSalir.addActionListener(actionListener); this.jbtnAgregar.addActionListener(actionListener); } public void setCargarComboIngredientes(List<Ingrediente> ingredientes) { ComboBoxModel jcmbIngredientesOrdenModelModel = new DefaultComboBoxModel(ingredientes.toArray()); jcmbIngredientes.setModel(jcmbIngredientesOrdenModelModel); } public void setcargarComboCategoria(List<Categoria> categorias) { ComboBoxModel jcmbCategoriaOrdenModelModel = new DefaultComboBoxModel(categorias.toArray()); jcmbNombreCategoria.setModel(jcmbCategoriaOrdenModelModel); } public String getCantidad() { return jtxtCantidad.getText(); } public void setJtxtCantidad(String jtxtCantidad) { this.jtxtCantidad.setText(jtxtCantidad); } public String getDescripcionProd() { return jtxtDescripcionProd.getText(); } public void setJtxtDescripcionProd(String valor) { this.jtxtDescripcionProd.setText(valor); } public String getFechaRegistro() { return jtxtfechaRegistro.getText(); } public void setJtxtfechaRegistro(String jtxtfechaRegistro) { this.jtxtfechaRegistro.setText(jtxtfechaRegistro); } public String getCodCategoria() { return jtxtCodCategoria.getText(); } public void setJtxtCodCategoria(String valor) { this.jtxtCodCategoria.setText(valor); } public String getCodProducto() { return jtxtCodProducto.getText(); } public void setJtxtCodProducto(String jtxtCodProducto) { this.jtxtCodProducto.setText(jtxtCodProducto); } public String getPrecio() { return jtxtPrecio.getText(); } public void setJtxtPrecio(String jtxtPrecio) { this.jtxtPrecio.setText(jtxtPrecio); } public void setCargarComboIngrediente(List<String> ingredientes) { ComboBoxModel jcmbIngredienteOrdenModelModel = new DefaultComboBoxModel(ingredientes.toArray()); jcmbIngredientes.setModel(jcmbIngredienteOrdenModelModel); } public String getJcmbIngredientes() { return jcmbIngredientes.getSelectedItem().toString(); } public String getJcmbNombreCategoria() { return jcmbNombreCategoria.getSelectedItem().toString(); } public void setCargarComboCategoria(List<String> categorias) { ComboBoxModel jcmbCategoriaOrdenModelModel = new DefaultComboBoxModel(categorias.toArray()); jcmbNombreCategoria.setModel(jcmbCategoriaOrdenModelModel); } public void setJcmbNombreCategoria(JComboBox jcmbNombreCategoria) { this.jcmbNombreCategoria = jcmbNombreCategoria; jcmbNombreCategoria.setBackground(new java.awt.Color(82,209,232)); jcmbNombreCategoria.setBorder(BorderFactory.createEtchedBorder(BevelBorder.LOWERED)); } public void setJcmbNombreCateg2(String valor3){ this.jcmbNombreCategoria.setName(valor3); } public void setJcmbIngredientes(JComboBox jcmbIngredientes) { this.jcmbIngredientes = jcmbIngredientes; jcmbIngredientes.setBackground(new java.awt.Color(82,209,232)); jcmbIngredientes.setBorder(BorderFactory.createEtchedBorder(BevelBorder.LOWERED)); } public String getcodIngrediente() { return jtxtcodIngrediente.getText(); } public void setJtxtcodIngrediente(String valor){ this.jtxtcodIngrediente.setText(valor); } public JTable getjTableIngredientes() { return jTableIngredientes; } public void mostrarMensaje(String mensaje) { JOptionPane.showMessageDialog(this, mensaje); } public void borrarDatos(){ jtxtfechaRegistro.setText(""); jtxtCodProducto.setText(""); jtxtDescripcionProd.setText(""); jtxtCodCategoria.setText(""); jtxtfechaRegistro.setText(""); jtxtCantidad.setText(""); jtxtPrecio.setText(""); } public void setResultados(AbstractTableModel abstractTableModel) { jTableIngredientes.setModel(abstractTableModel); } }
1-1-cuarta-entrega
trunk/ProyectoVentaComidaRapida(NUEVO)/src/vista/VentanaProducto.java
Java
asf20
14,784
package vista; import java.awt.event.ActionListener; import java.util.List; import javax.swing.BorderFactory; import javax.swing.ComboBoxModel; import javax.swing.DefaultComboBoxModel; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JTextField; import javax.swing.WindowConstants; import javax.swing.border.BevelBorder; import javax.swing.SwingUtilities; /** * This code was edited or generated using CloudGarden's Jigloo * SWT/Swing GUI Builder, which is free for non-commercial * use. If Jigloo is being used commercially (ie, by a corporation, * company or business for any purpose whatever) then you * should purchase a license for each developer using Jigloo. * Please visit www.cloudgarden.com for details. * Use of Jigloo implies acceptance of these licensing terms. * A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR * THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED * LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE. */ public class VentanaCargaCompra extends javax.swing.JFrame { private JComboBox jcmbCompraIngredientes; private JTextField jtxtCompraIngrediente; private JLabel jlblCompraIngrediente; private JButton jbtnSalir; private JTextField jtxtCodIngrediente; private JButton jbtnImagen; private JButton jbtnComptaIngrediente; /** * Auto-generated main method to display this JFrame */ public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { VentanaCargaCompra inst = new VentanaCargaCompra(); inst.setLocationRelativeTo(null); inst.setVisible(true); } }); } public VentanaCargaCompra() { super(); initGUI(); } private void initGUI() { try { setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); getContentPane().setLayout(null); getContentPane().setBackground(new java.awt.Color(255,255,255)); this.setTitle("Compras: Actualizar Existencia de Ingredientes"); { ComboBoxModel jcmbCompraIngredientesModel = new DefaultComboBoxModel( new String[] { "", "Item Two" }); jcmbCompraIngredientes = new JComboBox(); getContentPane().add(jcmbCompraIngredientes); //jcmbCompraIngredientes.setModel(jcmbCompraIngredientesModel); jcmbCompraIngredientes.setBounds(237, 18, 184, 21); } { jbtnComptaIngrediente = new JButton(); getContentPane().add(jbtnComptaIngrediente); jbtnComptaIngrediente.setText("Actualizar Inventario"); jbtnComptaIngrediente.setBounds(254, 119, 149, 21); jbtnComptaIngrediente.setBackground(new java.awt.Color(82,209,232)); } { jtxtCompraIngrediente = new JTextField(); getContentPane().add(jtxtCompraIngrediente); jtxtCompraIngrediente.setText("00"); jtxtCompraIngrediente.setBounds(291, 86, 69, 21); } { jlblCompraIngrediente = new JLabel(); getContentPane().add(jlblCompraIngrediente); jlblCompraIngrediente.setText("Cantidad Comprada:"); jlblCompraIngrediente.setBounds(254, 66, 149, 14); } { jbtnImagen = new JButton(); jbtnImagen.setIcon(new ImageIcon(getClass().getClassLoader().getResource("imagen.jpg"))); getContentPane().add(jbtnImagen); jbtnImagen.setBounds(18, 18, 193, 158); jbtnImagen.setBackground(new java.awt.Color(82,209,232)); jbtnImagen.setBorder(BorderFactory.createEtchedBorder(BevelBorder.LOWERED)); } { jtxtCodIngrediente = new JTextField(); getContentPane().add(jtxtCodIngrediente); jtxtCodIngrediente.setBounds(249, 176, 33, 21); jtxtCodIngrediente.setVisible(false); jtxtCodIngrediente.setEditable(false); } { jbtnSalir = new JButton(); getContentPane().add(jbtnSalir); jbtnSalir.setText("Salir"); jbtnSalir.setBounds(291, 155, 69, 21); jbtnSalir.setBackground(new java.awt.Color(82,209,232)); } pack(); this.setSize(461, 240); } catch (Exception e) { //add your error handling code here e.printStackTrace(); } } public void addListener(ActionListener actionListener) { this.jbtnComptaIngrediente.addActionListener(actionListener); this.jbtnImagen.addActionListener(actionListener); this.jcmbCompraIngredientes.addActionListener(actionListener); this.jbtnSalir.addActionListener(actionListener); } public void setcargarComboIngredientes(List ingredientes) { ComboBoxModel jcmbCategoriaOrdenModelModel = new DefaultComboBoxModel(ingredientes.toArray()); jcmbCompraIngredientes.setModel(jcmbCategoriaOrdenModelModel); } public String getJcmbCompraIngredientes() { return jcmbCompraIngredientes.getSelectedItem().toString(); } public String getCantComprada() { return jtxtCompraIngrediente.getText(); } public void setJtxtCompraIngrediente(String jtxtCompraIngrediente) { this.jtxtCompraIngrediente.setText(jtxtCompraIngrediente); } public String getCodIngrediente() { return jtxtCodIngrediente.getText(); } public void setJtxtCodIngrediente(String jtxtCodIngrediente) { this.jtxtCodIngrediente.setText(jtxtCodIngrediente); } public void mostrarMensaje(String mensaje) { JOptionPane.showMessageDialog(this, mensaje); } }
1-1-cuarta-entrega
trunk/ProyectoVentaComidaRapida(NUEVO)/src/vista/VentanaCargaCompra.java
Java
asf20
7,278
package vista; import java.util.ArrayList; import java.util.List; import javax.swing.table.AbstractTableModel; import modelo.Ingrediente; public class VentanaIngredienteModeloTabla extends AbstractTableModel{ private static String[] titulos = {"Código","Descripción", "Existencia"}; private List<Ingrediente> ingredientes = new ArrayList<Ingrediente>(); public VentanaIngredienteModeloTabla(List<Ingrediente> ingrediente) { super(); this.ingredientes = ingrediente; this.fireTableDataChanged(); } @Override public int getColumnCount() { return titulos.length; } @Override public int getRowCount() { return ingredientes.size(); } @Override public Object getValueAt(int rowIndex, int columnIndex) { Ingrediente ingrediente = ingredientes.get(rowIndex); switch (columnIndex) { case 0: return ingrediente.getCodIngrediente(); case 1: return ingrediente.getDescripcionIng(); case 2: return ingrediente.getExistencia(); } return null; } @Override public String getColumnName(int column) { return titulos[column]; } }
1-1-cuarta-entrega
trunk/ProyectoVentaComidaRapida(NUEVO)/src/vista/VentanaIngredienteModeloTabla.java
Java
asf20
1,411
package vista; import java.util.ArrayList; import java.util.List; import javax.swing.table.AbstractTableModel; import modelo.DetalleProducto; public class VentanaDetalleProductoTablaModel extends AbstractTableModel { private static String[] titulos = {"CodIngrediente","Ingrediente","Cantidad"}; private List<DetalleProducto> listaIngred = new ArrayList<DetalleProducto>(); public VentanaDetalleProductoTablaModel(List<DetalleProducto> listaIngred) { super(); this.listaIngred = listaIngred; this.fireTableDataChanged(); } @Override public int getColumnCount() { return titulos.length; } @Override public int getRowCount() { return listaIngred.size(); } @Override public Object getValueAt(int rowIndex, int columnIndex) { DetalleProducto detProducto = listaIngred.get(rowIndex); switch (columnIndex) { case 0: return detProducto.getCodIngrediente(); case 1: return detProducto.getDescripcionIng(); case 2: return detProducto.getCantidadIng(); } return null; } @Override public String getColumnName(int column) { return titulos[column]; } //Para que los campos de la columna cantidad de la tabla sean modificables public boolean isCellEditable(int row, int column) { if (column == 3) return true; return false; } public void setValueAt(Object value, int row, int column) { DetalleProducto detProducto = listaIngred.get(row); switch (column) { case 0: detProducto.setCodIngrediente((String)value); break; case 1: detProducto.setDescripcionIng((String)value); break; case 2: detProducto.setCantidadIng(Float.parseFloat((String)value)); break; default: System.out.println("Indice Invalido"); } fireTableCellUpdated(row, column); } }
1-1-cuarta-entrega
trunk/ProyectoVentaComidaRapida(NUEVO)/src/vista/VentanaDetalleProductoTablaModel.java
Java
asf20
2,322
package vista; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.LinkedList; import java.util.ListIterator; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.SwingUtilities; import javax.swing.WindowConstants; import javax.swing.border.BevelBorder; import javax.swing.table.AbstractTableModel; import modelo.Coleccion; import modelo.DetalleOrden; /** * This code was edited or generated using CloudGarden's Jigloo * SWT/Swing GUI Builder, which is free for non-commercial * use. If Jigloo is being used commercially (ie, by a corporation, * company or business for any purpose whatever) then you * should purchase a license for each developer using Jigloo. * Please visit www.cloudgarden.com for details. * Use of Jigloo implies acceptance of these licensing terms. * A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR * THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED * LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE. */ public class VentanaConsultaProducto extends javax.swing.JFrame implements ActionListener{ private JPanel jpanConsulta; private JTable jtblConsulta; private JButton jbtnCantidadDescentente; private JButton jbtnCantidadAscendente; private JButton jbtnDescendente; private JButton jbtnAscendente; private JButton jbtnImagen; private JButton jbtnSalir; private JScrollPane jScrollPaneConsulta; private JLabel jlbltitulo; Coleccion coleccion = new Coleccion(); DetalleOrden detOrden = new DetalleOrden(); private LinkedList<DetalleOrden> listaCantOrdenadas = new LinkedList<DetalleOrden>(); private LinkedList<DetalleOrden> listaMontosOrdenados = new LinkedList<DetalleOrden>(); /** * Auto-generated main method to display this JFrame */ public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { VentanaConsultaProducto instConsulta = new VentanaConsultaProducto(); instConsulta.setLocationRelativeTo(null); instConsulta.setVisible(true); instConsulta.addListener(instConsulta); } }); } public VentanaConsultaProducto() { super(); initGUI(); } private void initGUI() { try { setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); getContentPane().setLayout(null); getContentPane().setBackground(new java.awt.Color(82,209,232)); { jpanConsulta = new JPanel(); getContentPane().add(jpanConsulta, "Center"); jpanConsulta.setLayout(null); jpanConsulta.setBounds(12, 12, 813, 285); jpanConsulta.setBackground(new java.awt.Color(255,255,255)); { jlbltitulo = new JLabel(); jpanConsulta.add(jlbltitulo); jlbltitulo.setText("Consulta de Venta de Productos"); jlbltitulo.setBounds(18, 40, 771, 28); jlbltitulo.setBorder(BorderFactory.createEtchedBorder(BevelBorder.LOWERED)); jlbltitulo.setBackground(new java.awt.Color(82,209,232)); } { jScrollPaneConsulta = new JScrollPane(); jpanConsulta.add(jScrollPaneConsulta); jScrollPaneConsulta.setBounds(204, 85, 423, 170); { jtblConsulta = new JTable(); jScrollPaneConsulta.setViewportView(jtblConsulta); jtblConsulta.setPreferredSize(new java.awt.Dimension(326, 168)); } } { jbtnSalir = new JButton(); jpanConsulta.add(jbtnSalir); jbtnSalir.setText("Salir"); jbtnSalir.setBounds(669, 230, 103, 25); jbtnSalir.setBackground(new java.awt.Color(82,209,232)); jbtnSalir.setBorder(BorderFactory.createEtchedBorder(BevelBorder.LOWERED)); } { jbtnImagen = new JButton(); jbtnImagen.setIcon(new ImageIcon(getClass().getClassLoader().getResource("imagen.jpg"))); jpanConsulta.add(jbtnImagen); jbtnImagen.setBounds(18, 97, 180, 152); jbtnImagen.setBackground(new java.awt.Color(82,209,232)); jbtnImagen.setBorder(BorderFactory.createEtchedBorder(BevelBorder.LOWERED)); } { jbtnAscendente = new JButton(); jpanConsulta.add(jbtnAscendente); jbtnAscendente.setText("Monto Ascendente"); jbtnAscendente.setBounds(633, 157, 168, 22); jbtnAscendente.setBackground(new java.awt.Color(82,209,232)); jbtnAscendente.setBorder(BorderFactory.createEtchedBorder(BevelBorder.LOWERED)); } { jbtnDescendente = new JButton(); jpanConsulta.add(jbtnDescendente); jbtnDescendente.setText("Monto Descendente"); jbtnDescendente.setBounds(633, 191, 168, 22); jbtnDescendente.setBackground(new java.awt.Color(82,209,232)); jbtnDescendente.setBorder(BorderFactory.createEtchedBorder(BevelBorder.LOWERED)); } { jbtnCantidadAscendente = new JButton(); jpanConsulta.add(jbtnCantidadAscendente); jbtnCantidadAscendente.setText("Cantidad Ascendente"); jbtnCantidadAscendente.setBounds(634, 90, 168, 22); jbtnCantidadAscendente.setBackground(new java.awt.Color(82,209,232)); } { jbtnCantidadDescentente = new JButton(); jpanConsulta.add(jbtnCantidadDescentente); jbtnCantidadDescentente.setText("Cantidad Descendente"); jbtnCantidadDescentente.setBounds(634, 123, 168, 22); jbtnCantidadDescentente.setBackground(new java.awt.Color(82,209,232)); } } pack(); this.setSize(847, 339); } catch (Exception e) { //add your error handling code here e.printStackTrace(); } } public void addListener(ActionListener actionListener) { this.jbtnCantidadAscendente.addActionListener(actionListener); this.jbtnCantidadDescentente.addActionListener(actionListener); this.jbtnAscendente.addActionListener(actionListener); this.jbtnDescendente.addActionListener(actionListener); this.jbtnSalir.addActionListener(actionListener); } public void setResultados(AbstractTableModel abstractTableModel) { jtblConsulta.setModel(abstractTableModel); } public void actionPerformed (ActionEvent e) { //PATRON ITERATOR String seleccion = e.getActionCommand(); //Para empesar se ordenan ambas listas (Por defecto estaran ordenadas ascendentemente) //porque las consultas se hacen order by monto o order by cantidadprod //tambien se pudo haber hecho con un Collections.sort(listas,new clase abstracta que ordena); if ("Salir".equals(seleccion))//item Salir { dispose(); } else if ("Cantidad Ascendente".equals(seleccion))//item Ascendente { //Iteramos desde el primer registro de la lista que ya esta ascendetemente //conseguimos el iterador para recorrer la lista ascendentemente ListIterator ascendente = coleccion.miIteratorCantidad(0); listaCantOrdenadas.clear(); while (ascendente.hasNext()) //recorremos la lista ascendentemente mientras existan elementos { detOrden = (DetalleOrden)ascendente.next(); listaCantOrdenadas.add(detOrden); } setResultados(new VentanaTablaModeloProducto(listaCantOrdenadas)); } else if ("Cantidad Descendente".equals(seleccion))//item descendente { //Iteramos desde el ultimo registro de la lista para //conseguir que el iterador recorra la lista descendentemente ListIterator descendente = coleccion.miIteratorCantidad(coleccion.getMilistacantidades().size()); listaCantOrdenadas.clear(); while (descendente.hasPrevious()) //recorremos la lista descendentemente mientras existan elementos { detOrden = (DetalleOrden)descendente.previous(); listaCantOrdenadas.add(detOrden); } setResultados(new VentanaTablaModeloProducto(listaCantOrdenadas)); } else if ("Monto Ascendente".equals(seleccion))//item Ascendente { //Iteramos desde el primer registro de la lista que ya esta ascendetemente //conseguimos el iterador para recorrer la lista ascendentemente ListIterator ascendente = coleccion.miIteratorMonto(0); listaMontosOrdenados.clear(); while (ascendente.hasNext()) //recorremos la lista ascendentemente mientras existan elementos { detOrden = (DetalleOrden)ascendente.next(); listaMontosOrdenados.add(detOrden); } setResultados(new VentanaTablaModeloProducto(listaMontosOrdenados)); } else if ("Monto Descendente".equals(seleccion))//item descendente { //Iteramos desde el ultimo registro de la lista para //conseguir que el iterador recorra la lista descendentemente ListIterator descendente = coleccion.miIteratorMonto(coleccion.getMilistamontos().size()); listaMontosOrdenados.clear(); while (descendente.hasPrevious()) //recorremos la lista descendentemente mientras existan elementos { detOrden = (DetalleOrden)descendente.previous(); listaMontosOrdenados.add(detOrden); } setResultados(new VentanaTablaModeloProducto(listaMontosOrdenados)); } }//actionPerformed(ActionEvent) }
1-1-cuarta-entrega
trunk/ProyectoVentaComidaRapida(NUEVO)/src/vista/VentanaConsultaProducto.java
Java
asf20
8,838
package vista; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFormattedTextField; import javax.swing.JPanel; import javax.swing.JSeparator; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.JTextPane; import javax.swing.ImageIcon; import javax.swing.WindowConstants; import javax.swing.border.BevelBorder; import javax.swing.border.LineBorder; import javax.swing.table.DefaultTableModel; import javax.swing.SwingUtilities; /** * This code was edited or generated using CloudGarden's Jigloo * SWT/Swing GUI Builder, which is free for non-commercial * use. If Jigloo is being used commercially (ie, by a corporation, * company or business for any purpose whatever) then you * should purchase a license for each developer using Jigloo. * Please visit www.cloudgarden.com for details. * Use of Jigloo implies acceptance of these licensing terms. * A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR * THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED * LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE. */ public class VentanaPrincipalMagnifico extends javax.swing.JFrame { private JPanel jPanVentanaPM; private JButton jbtnCompraIngrediente; private JButton jbtnImagen; private JButton jButton1; private JButton jbtnIngredientesCantidad; private JButton jbtn; private JSeparator jSeparator4; private JTextField jTextFieldSeleccioneListado; private JTextField jTextFieldBienvenido; private JSeparator jSeparator3; private JButton jbtnSalir; private JSeparator jSeparator2; private JSeparator jSeparator1; private JButton jbtnRegistrarCategoria; private JButton jbtnRegistrarProducto; private JButton jbtnOrden; private JButton jbtnImagenPrincipal; /** * Auto-generated main method to display this JFrame */ public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { VentanaPrincipalMagnifico inst = new VentanaPrincipalMagnifico(); inst.setLocationRelativeTo(null); inst.setVisible(true); } }); } public VentanaPrincipalMagnifico() { super(); initGUI(); } private void initGUI() { try { setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); getContentPane().setLayout(null); getContentPane().setBackground(new java.awt.Color(82,209,232)); { jPanVentanaPM = new JPanel(); getContentPane().add(jPanVentanaPM); jPanVentanaPM.setBounds(12, 12, 518, 509); jPanVentanaPM.setLayout(null); jPanVentanaPM.setBackground(new java.awt.Color(255,255,255)); jPanVentanaPM.setBorder(new LineBorder(new java.awt.Color(0,0,0), 1, false)); { jbtnImagenPrincipal = new JButton(); jPanVentanaPM.add(jbtnImagenPrincipal); jbtnImagenPrincipal.setBounds(38, 80, 203, 191); jbtnImagenPrincipal.setBorder(BorderFactory.createEtchedBorder(BevelBorder.LOWERED)); jbtnImagenPrincipal.setOpaque(false); jbtnImagenPrincipal.setIcon(new ImageIcon(getClass().getClassLoader().getResource("imagen.jpg"))); jbtnImagenPrincipal.setBackground(new java.awt.Color(82,209,232)); } { jbtnOrden = new JButton(); jPanVentanaPM.add(jbtnOrden); jbtnOrden.setText("Tomar Orden"); jbtnOrden.setBounds(272, 88, 204, 34); jbtnOrden.setBackground(new java.awt.Color(82,209,232)); jbtnOrden.setFont(new java.awt.Font("Dialog",0,14)); jbtnOrden.setForeground(new java.awt.Color(0,0,0)); jbtnOrden.setBorder(BorderFactory.createEtchedBorder(BevelBorder.LOWERED)); } { jbtnRegistrarProducto = new JButton(); jPanVentanaPM.add(jbtnRegistrarProducto); jbtnRegistrarProducto.setText("Gestionar Producto"); jbtnRegistrarProducto.setBounds(272, 175, 204, 35); jbtnRegistrarProducto.setBackground(new java.awt.Color(82,209,232)); jbtnRegistrarProducto.setForeground(new java.awt.Color(0,0,0)); jbtnRegistrarProducto.setBorder(BorderFactory.createEtchedBorder(BevelBorder.LOWERED)); jbtnRegistrarProducto.setFont(new java.awt.Font("Dialog",0,14)); } { jbtnRegistrarCategoria = new JButton(); jPanVentanaPM.add(jbtnRegistrarCategoria); jbtnRegistrarCategoria.setText("Gestionar Categoria"); jbtnRegistrarCategoria.setBounds(272, 129, 204, 35); jbtnRegistrarCategoria.setBackground(new java.awt.Color(82,209,232)); jbtnRegistrarCategoria.setForeground(new java.awt.Color(0,0,0)); jbtnRegistrarCategoria.setBorder(BorderFactory.createEtchedBorder(BevelBorder.LOWERED)); jbtnRegistrarCategoria.setFont(new java.awt.Font("Dialog",0,14)); } { jSeparator1 = new JSeparator(); jPanVentanaPM.add(jSeparator1); jSeparator1.setBounds(32, 285, 449, 12); jSeparator1.setBackground(new java.awt.Color(82,209,232)); } { jSeparator2 = new JSeparator(); jPanVentanaPM.add(jSeparator2); jSeparator2.setBackground(new java.awt.Color(97,200,221)); jSeparator2.setBounds(38, 65, 443, 17); } { jbtnSalir = new JButton(); jPanVentanaPM.add(jbtnSalir); jbtnSalir.setText("Salir"); jbtnSalir.setBounds(406, 461, 57, 22); jbtnSalir.setBackground(new java.awt.Color(82,209,232)); jbtnSalir.setBorder(BorderFactory.createEtchedBorder(BevelBorder.LOWERED)); } { jSeparator3 = new JSeparator(); jPanVentanaPM.add(jSeparator3); jSeparator3.setBackground(new java.awt.Color(82,209,232)); jSeparator3.setBounds(32, 322, 449, 8); } { jTextFieldBienvenido = new JTextField(); jPanVentanaPM.add(jTextFieldBienvenido); jTextFieldBienvenido.setText("Bienvenido al Sistema De Servicio de Comida Rápida"); jTextFieldBienvenido.setBounds(17, 19, 476, 40); jTextFieldBienvenido.setBackground(new java.awt.Color(82,209,232)); jTextFieldBienvenido.setBorder(BorderFactory.createEtchedBorder(BevelBorder.LOWERED)); jTextFieldBienvenido.setFont(new java.awt.Font("Century Schoolbook L",0,18)); jTextFieldBienvenido.setEditable(false); } { jTextFieldSeleccioneListado = new JTextField(); jPanVentanaPM.add(jTextFieldSeleccioneListado); jTextFieldSeleccioneListado.setText("Seleccione el Listado"); jTextFieldSeleccioneListado.setBounds(32, 292, 444, 22); jTextFieldSeleccioneListado.setBackground(new java.awt.Color(82,209,232)); jTextFieldSeleccioneListado.setBorder(BorderFactory.createEtchedBorder(BevelBorder.LOWERED)); } { jSeparator4 = new JSeparator(); jPanVentanaPM.add(jSeparator4); jSeparator4.setBackground(new java.awt.Color(82,209,232)); jSeparator4.setBounds(32, 438, 449, 5); } { jbtn = new JButton(); jPanVentanaPM.add(jbtn); jbtn.setText("Venta de Productos"); jbtn.setBounds(178, 330, 292, 22); jbtn.setBackground(new java.awt.Color(82,209,232)); jbtn.setBorder(BorderFactory.createEtchedBorder(BevelBorder.LOWERED)); } { jbtnIngredientesCantidad = new JButton(); jPanVentanaPM.add(jbtnIngredientesCantidad); jbtnIngredientesCantidad.setText("Cantidad Disponible de Ingredientes"); jbtnIngredientesCantidad.setBounds(178, 365, 292, 22); jbtnIngredientesCantidad.setBackground(new java.awt.Color(82,209,232)); jbtnIngredientesCantidad.setBorder(BorderFactory.createEtchedBorder(BevelBorder.LOWERED)); } { jButton1 = new JButton(); jPanVentanaPM.add(jButton1); jButton1.setText("Ingredientes más Usados"); jButton1.setBounds(178, 404, 292, 22); jButton1.setBackground(new java.awt.Color(82,209,232)); jButton1.setBorder(BorderFactory.createEtchedBorder(BevelBorder.LOWERED)); } { jbtnImagen = new JButton(); jbtnImagen.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images.jpeg"))); jPanVentanaPM.add(jbtnImagen); jbtnImagen.setBounds(38, 330, 113, 102); jbtnImagen.setBorder(BorderFactory.createEtchedBorder(BevelBorder.LOWERED)); jbtnImagen.setBackground(new java.awt.Color(82,209,232)); } { jbtnCompraIngrediente = new JButton(); jPanVentanaPM.add(jbtnCompraIngrediente); jbtnCompraIngrediente.setText("Comprar Ingredientes"); jbtnCompraIngrediente.setBounds(272, 222, 204, 37); jbtnCompraIngrediente.setBackground(new java.awt.Color(82,209,232)); jbtnCompraIngrediente.setForeground(new java.awt.Color(0,0,0)); jbtnCompraIngrediente.setFont(new java.awt.Font("Dialog",0,14)); } } pack(); this.setSize(544, 563); } catch (Exception e) { //add your error handling code here e.printStackTrace(); } } public void addListener(ActionListener actionListener) { this.jbtnOrden.addActionListener(actionListener); this.jbtnIngredientesCantidad.addActionListener(actionListener); this.jbtnRegistrarProducto.addActionListener(actionListener); this.jbtn.addActionListener(actionListener); this.jButton1.addActionListener(actionListener); this.jbtnSalir.addActionListener(actionListener); this.jbtnRegistrarCategoria.addActionListener(actionListener); this.jbtnCompraIngrediente.addActionListener(actionListener); } }
1-1-cuarta-entrega
trunk/ProyectoVentaComidaRapida(NUEVO)/src/vista/VentanaPrincipalMagnifico.java
Java
asf20
14,472
package vista; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.GridBagLayout; import java.awt.GridLayout; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JEditorPane; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.JTextPane; import javax.swing.SwingUtilities; import javax.swing.border.BevelBorder; import modelo.ProbarMetodosFabricaCreador; /** * This code was edited or generated using CloudGarden's Jigloo * SWT/Swing GUI Builder, which is free for non-commercial * use. If Jigloo is being used commercially (ie, by a corporation, * company or business for any purpose whatever) then you * should purchase a license for each developer using Jigloo. * Please visit www.cloudgarden.com for details. * Use of Jigloo implies acceptance of these licensing terms. * A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR * THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED * LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE. */ public class VentanaCategoria extends javax.swing.JFrame{ private JPanel jPanCategoria; private JLabel jlblCodCategoria; private JButton jbtnRegistrar; private JButton jbtnImagen; private JButton jbtnBuscar; private JButton jbtnCancelar; private JButton jbtnSalir; private JTextField jtxtDescripcionCateg; private JTextField jtxtCodigoCateg; private JLabel jlblDatosCategoria; private JLabel jlblDescripcionCateg; /** * Auto-generated main method to display this JFrame */ public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { VentanaCategoria instCateg = new VentanaCategoria(); instCateg.setLocationRelativeTo(null); new ProbarMetodosFabricaCreador(); instCateg.setVisible(true); } }); } public VentanaCategoria() { super(); initGUI(); } private void initGUI() { try { getContentPane().setLayout(null); { this.setTitle("Gestión de Categorias"); getContentPane().setBackground(new java.awt.Color(82,209,232)); jPanCategoria = new JPanel(); getContentPane().add(jPanCategoria); jPanCategoria.setLayout(null); jPanCategoria.setBackground(new java.awt.Color(255,255,255)); jPanCategoria.setBounds(7, 12, 568, 244); { jlblCodCategoria = new JLabel(); jlblCodCategoria.setText("Código Categoría"); } { jbtnRegistrar = new JButton(); jbtnRegistrar.setLayout(null); jbtnRegistrar.setText("Registrar"); } { jbtnCancelar = new JButton(); jbtnCancelar.setLayout(null); jbtnCancelar.setText("Cancelar"); } { jbtnSalir = new JButton(); jbtnSalir.setLayout(null); jbtnSalir.setText("Salir"); } { jlblDescripcionCateg = new JLabel(); jlblDescripcionCateg.setText("Descripción"); } { jlblDatosCategoria = new JLabel(); jlblDatosCategoria.setText("Datos de la Categoria"); } { jbtnBuscar = new JButton(); jbtnBuscar.setText("Buscar"); } { jtxtCodigoCateg = new JTextField(); jPanCategoria.add(jtxtCodigoCateg); jtxtCodigoCateg.setBounds(369, 70, 107, 21); } { jtxtDescripcionCateg = new JTextField(); jPanCategoria.add(jtxtDescripcionCateg); jPanCategoria.add(jbtnCancelar, "DEFAULT_WIDTH"); jPanCategoria.add(jbtnSalir, "DEFAULT_WIDTH"); jPanCategoria.add(jbtnRegistrar, "DEFAULT_WIDTH"); jPanCategoria.add(jlblDescripcionCateg, "DEFAULT_WIDTH"); jPanCategoria.add(jlblCodCategoria, "DEFAULT_WIDTH"); jPanCategoria.add(jlblDatosCategoria, "DEFAULT_WIDTH"); jPanCategoria.add(jbtnBuscar); jbtnBuscar.setBounds(482, 70, 59, 21); jbtnBuscar.setBackground(new java.awt.Color(82,209,232)); jbtnBuscar.setBorder(BorderFactory.createEtchedBorder(BevelBorder.LOWERED)); { jbtnImagen = new JButton(); jPanCategoria.add(jbtnImagen); jbtnImagen.setIcon(new ImageIcon(getClass().getClassLoader().getResource("imagen.jpg"))); jbtnImagen.setBounds(21, 45, 183, 162); jbtnImagen.setBackground(new java.awt.Color(82,209,232)); jbtnImagen.setBorder(BorderFactory.createEtchedBorder(BevelBorder.LOWERED)); } jlblDatosCategoria.setBounds(21, 18, 523, 21); jlblDatosCategoria.setBorder(BorderFactory.createEtchedBorder(BevelBorder.LOWERED)); jlblDatosCategoria.setBackground(new java.awt.Color(82,209,232)); jlblCodCategoria.setBounds(232, 70, 125, 21); jlblDescripcionCateg.setBounds(232, 100, 109, 14); jbtnRegistrar.setBounds(276, 137, 71, 30); jbtnRegistrar.setBackground(new java.awt.Color(82,209,232)); jbtnRegistrar.setBorder(BorderFactory.createEtchedBorder(BevelBorder.LOWERED)); jbtnSalir.setBounds(469, 139, 68, 27); jbtnSalir.setBackground(new java.awt.Color(82,209,232)); jbtnSalir.setBorder(BorderFactory.createEtchedBorder(BevelBorder.LOWERED)); jbtnCancelar.setBounds(374, 137, 69, 30); jbtnCancelar.setBackground(new java.awt.Color(82,209,232)); jbtnCancelar.setBorder(BorderFactory.createEtchedBorder(BevelBorder.LOWERED)); jtxtDescripcionCateg.setBounds(369, 97, 172, 21); } } { this.setSize(595, 293); } } catch(Exception e) { e.printStackTrace(); } } public void addListener(ActionListener actionListener){ this.jbtnBuscar.addActionListener(actionListener); this.jbtnCancelar.addActionListener(actionListener); this.jbtnRegistrar.addActionListener(actionListener); this.jbtnSalir.addActionListener(actionListener); } public void mostrarMensaje(String mensaje) { JOptionPane.showMessageDialog(this, mensaje); } public String getDescripcionCateg() { return jtxtDescripcionCateg.getText(); } public void setJtxtDescripcionCateg(String valor) { this.jtxtDescripcionCateg.setText(valor); } public String getCodCategoria() { return jtxtCodigoCateg.getText(); } public void setJtxtCodigoCateg(JTextField jtxtCodigoCateg) { this.jtxtCodigoCateg = jtxtCodigoCateg; } public void borrarDatos() { jtxtCodigoCateg.setText(""); jtxtDescripcionCateg.setText(""); } }
1-1-cuarta-entrega
trunk/ProyectoVentaComidaRapida(NUEVO)/src/vista/VentanaCategoria.java
Java
asf20
9,774
package vista; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.List; import javax.swing.BorderFactory; import javax.swing.ComboBoxModel; import javax.swing.DefaultComboBoxModel; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFormattedTextField; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSeparator; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.SwingConstants; import javax.swing.WindowConstants; import javax.swing.border.BevelBorder; import javax.swing.table.AbstractTableModel; import javax.swing.SwingUtilities; /** * This code was edited or generated using CloudGarden's Jigloo * SWT/Swing GUI Builder, which is free for non-commercial * use. If Jigloo is being used commercially (ie, by a corporation, * company or business for any purpose whatever) then you * should purchase a license for each developer using Jigloo. * Please visit www.cloudgarden.com for details. * Use of Jigloo implies acceptance of these licensing terms. * A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR * THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED * LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE. */ public class VentanaOrden extends javax.swing.JFrame { private JPanel jPanOrden; private JButton jbtnRegistrar; private JLabel jlblCategoria; private JSeparator jSeparator3; private JTextField jtxtTelefono; private JLabel jlblTelefono; private JTextField jtxtDireccion; private JLabel jlblDireccion; private JSeparator jSeparator2; private JSeparator jSeparator1; private JFormattedTextField jFormTxtPedido; private JButton jbtnBuscar; private JLabel jLabel1; private JTextField jtxtCedula; private JTextField jtxtApellido; private JTextField jtxtTotalPagar; private JLabel jlbApellido; private JButton jbtnImagen; private JButton jbtnIngresarProductoTabla; private JButton jbtnSalir; private JButton jbtnCancelar; private JTable jTableOrdenProducto; private JScrollPane jScrollPaneOrdenProducto; private JSeparator jSeparator5; private JSeparator jSeparator4; private JComboBox jcmbCategoriaOrden; private JTextField jtxtNombreCli; private JLabel lblNombreCli; private JFormattedTextField jFormtxtCliente; private JTextField jtxtCodOrden; private JLabel jlblCodOrden; private JTextField jtxtCodProductoOrden; private JComboBox jcmbProductoOrden; private JTextField jtxtcodcategoria; private JLabel jlblSelecProducto; private JLabel jlblfechaorden; private JTextField jtxtFechaOrden; private JButton jbtnProcesar; private JLabel jlbltotalpagar; /** * Auto-generated main method to display this JFrame */ public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { VentanaOrden inst = new VentanaOrden(); inst.setLocationRelativeTo(null); inst.setVisible(true); } }); } public VentanaOrden() { super(); initGUI(); } private void initGUI() { try { setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); getContentPane().setLayout(null); getContentPane().setBackground(new java.awt.Color(82,209,232)); { jPanOrden = new JPanel(); getContentPane().add(jPanOrden); jPanOrden.setBounds(12, 12, 550, 753); jPanOrden.setLayout(null); jPanOrden.setBackground(new java.awt.Color(255,255,255)); { jlblCodOrden = new JLabel(); jPanOrden.add(jlblCodOrden); jlblCodOrden.setText("Nro. Orden:"); jlblCodOrden.setBounds(333, 103, 84, 20); } { jtxtCodOrden = new JTextField(); jPanOrden.add(jtxtCodOrden); jtxtCodOrden.setBounds(417, 103, 73, 21); } { jFormtxtCliente = new JFormattedTextField(); jPanOrden.add(jFormtxtCliente); jFormtxtCliente.setText("Nuestro Cliente"); jFormtxtCliente.setBounds(12, 160, 505, 21); jFormtxtCliente.setBackground(new java.awt.Color(82,209,232)); jFormtxtCliente.setEditable(false); } { lblNombreCli = new JLabel(); jPanOrden.add(lblNombreCli); lblNombreCli.setText("Nombre:"); lblNombreCli.setBounds(12, 232, 86, 14); } { jtxtNombreCli = new JTextField(); jPanOrden.add(jtxtNombreCli); jtxtNombreCli.setBounds(116, 229, 122, 21); } { jlbApellido = new JLabel(); jPanOrden.add(jlbApellido); jlbApellido.setText("Apellido:"); jlbApellido.setBounds(12, 261, 86, 14); } { jtxtApellido = new JTextField(); jPanOrden.add(jtxtApellido); jtxtApellido.setBounds(116, 258, 122, 21); } { jtxtCedula = new JTextField(); jPanOrden.add(jtxtCedula); jtxtCedula.setBounds(116, 199, 122, 21); } { jbtnRegistrar = new JButton(); jPanOrden.add(jbtnRegistrar); jbtnRegistrar.setText("Registrar"); jbtnRegistrar.setBounds(305, 245, 80, 22); jbtnRegistrar.setBackground(new java.awt.Color(82,209,232)); jbtnRegistrar.setBorder(BorderFactory.createEtchedBorder(BevelBorder.LOWERED)); } { jLabel1 = new JLabel(); jPanOrden.add(jLabel1); jLabel1.setText("C.I:"); jLabel1.setBounds(12, 202, 92, 14); } { jbtnBuscar = new JButton(); jPanOrden.add(jbtnBuscar); jbtnBuscar.setText("Buscar"); jbtnBuscar.setBounds(305, 204, 80, 22); jbtnBuscar.setBackground(new java.awt.Color(82,209,232)); jbtnBuscar.setBorder(BorderFactory.createEtchedBorder(BevelBorder.LOWERED)); } { jFormTxtPedido = new JFormattedTextField(); jPanOrden.add(jFormTxtPedido); jFormTxtPedido.setText("Orden de Nuestro Cliente"); jFormTxtPedido.setBounds(12, 383, 505, 22); jFormTxtPedido.setBackground(new java.awt.Color(82,209,232)); jFormTxtPedido.setEditable(false); } { jSeparator1 = new JSeparator(); jPanOrden.add(jSeparator1); jSeparator1.setBounds(12, 372, 512, 11); jSeparator1.setBackground(new java.awt.Color(28,209,232)); } { jSeparator2 = new JSeparator(); jPanOrden.add(jSeparator2); jSeparator2.setBounds(12, 143, 512, 11); jSeparator2.setBackground(new java.awt.Color(28,209,232)); } { jlblDireccion = new JLabel(); jPanOrden.add(jlblDireccion); jlblDireccion.setText("Dirección:"); jlblDireccion.setBounds(12, 295, 85, 15); } { jtxtDireccion = new JTextField(); jPanOrden.add(jtxtDireccion); jtxtDireccion.setBounds(115, 292, 123, 22); } { jlblTelefono = new JLabel(); jPanOrden.add(jlblTelefono); jlblTelefono.setText("Telefono:"); jlblTelefono.setBounds(12, 329, 85, 15); } { jtxtTelefono = new JTextField(); jPanOrden.add(jtxtTelefono); jtxtTelefono.setBounds(115, 326, 123, 22); } { jSeparator3 = new JSeparator(); jPanOrden.add(jSeparator3); jSeparator3.setBounds(277, 196, 22, 164); jSeparator3.setOrientation(SwingConstants.VERTICAL); jSeparator3.setBackground(new java.awt.Color(28,209,232)); } { jlblCategoria = new JLabel(); jPanOrden.add(jlblCategoria); jlblCategoria.setText("Seleccione la categoría:"); jlblCategoria.setBounds(60, 426, 193, 15); } { jcmbCategoriaOrden = new JComboBox(); jPanOrden.add(jcmbCategoriaOrden); jcmbCategoriaOrden.setBounds(60, 448, 171, 22); jcmbCategoriaOrden.setBackground(new java.awt.Color(82,209,232)); jcmbCategoriaOrden.setBorder(BorderFactory.createEtchedBorder(BevelBorder.LOWERED)); } { jSeparator4 = new JSeparator(); jPanOrden.add(jSeparator4); jSeparator4.setBounds(12, 417, 512, 3); jSeparator4.setBackground(new java.awt.Color(28,209,232)); } { jSeparator5 = new JSeparator(); jPanOrden.add(jSeparator5); jSeparator5.setBounds(12, 187, 512, 10); jSeparator5.setBackground(new java.awt.Color(28,209,232)); } { //Instanciamos el contenedor de la tabla jScrollPaneOrdenProducto = new JScrollPane(); jPanOrden.add(jScrollPaneOrdenProducto); jScrollPaneOrdenProducto.setBounds(73, 528, 418, 119); } { jbtnCancelar = new JButton(); jPanOrden.add(jbtnCancelar); jbtnCancelar.setText("Cancelar"); jbtnCancelar.setBounds(334, 706, 69, 22); jbtnCancelar.setBackground(new java.awt.Color(82,209,232)); } { jbtnSalir = new JButton(); jPanOrden.add(jbtnSalir); jbtnSalir.setText("Salir"); jbtnSalir.setBounds(420, 706, 72, 22); jbtnSalir.setBackground(new java.awt.Color(82,209,232)); } { jbtnIngresarProductoTabla = new JButton(); jPanOrden.add(jbtnIngresarProductoTabla); jbtnIngresarProductoTabla.setText("Cargar Productos "); jbtnIngresarProductoTabla.setBounds(238, 495, 147, 22); jbtnIngresarProductoTabla.setBackground(new java.awt.Color(82,209,232)); jbtnIngresarProductoTabla.setBorder(BorderFactory.createEtchedBorder(BevelBorder.LOWERED)); } { jcmbProductoOrden = new JComboBox(); jPanOrden.add(jcmbProductoOrden); jcmbProductoOrden.setBounds(61, 495, 165, 22); jcmbProductoOrden.setBackground(new java.awt.Color(82,209,232)); jcmbProductoOrden.setBorder(BorderFactory.createEtchedBorder(BevelBorder.LOWERED)); } { jlblSelecProducto = new JLabel(); jPanOrden.add(jlblSelecProducto); jlblSelecProducto.setText("Seleccione el producto:"); jlblSelecProducto.setBounds(61, 474, 159, 15); } { jtxtcodcategoria = new JTextField(); jPanOrden.add(jtxtcodcategoria); jtxtcodcategoria.setBounds(223, 406, 55, 22); jtxtcodcategoria.setEditable(false); jtxtcodcategoria.setVisible(false); } { jtxtCodProductoOrden = new JTextField(); jPanOrden.add(jtxtCodProductoOrden); jtxtCodProductoOrden.setBounds(410, 449, 55, 22); jtxtCodProductoOrden.setVisible(false); jtxtCodProductoOrden.setEditable(false); } { jlbltotalpagar = new JLabel(); jPanOrden.add(jlbltotalpagar); jlbltotalpagar.setText("Total a Pagar (BsF):"); jlbltotalpagar.setBounds(287, 660, 124, 14); } { jtxtTotalPagar = new JTextField(); jPanOrden.add(jtxtTotalPagar); jtxtTotalPagar.setBounds(423, 657, 69, 21); jtxtTotalPagar.setEditable(false); } { jbtnImagen = new JButton(); jbtnImagen.setIcon(new ImageIcon(getClass().getClassLoader().getResource("imagen.jpg"))); jPanOrden.add(jbtnImagen); jbtnImagen.setBounds(36, 6, 181, 132); jbtnImagen.setBackground(new java.awt.Color(82,209,232)); jbtnImagen.setBorder(BorderFactory.createEtchedBorder(BevelBorder.LOWERED)); } { //Instanciamos la tabla en donde aparecen los productos jTableOrdenProducto = new JTable(); //jPanOrden.add(jTableOrdenProducto); jTableOrdenProducto.setBounds(48, 535, 459, 102); //agregamos una tabla al contenedor con un scroll jScrollPaneOrdenProducto.add(jTableOrdenProducto); } { jbtnProcesar = new JButton(); jPanOrden.add(jbtnProcesar); jbtnProcesar.setText("Procesar"); jbtnProcesar.setBounds(403, 496, 108, 21); jbtnProcesar.setBackground(new java.awt.Color(82,209,232)); } { jtxtFechaOrden = new JTextField(); jPanOrden.add(jtxtFechaOrden); jtxtFechaOrden.setBounds(417, 71, 73, 21); } { jlblfechaorden = new JLabel(); jPanOrden.add(jlblfechaorden); jlblfechaorden.setText("Fecha:"); jlblfechaorden.setBounds(333, 74, 63, 14); } { jbtnCancelar = new JButton(); jPanOrden.add(jbtnCancelar); jbtnCancelar.setText("Cancelar"); jbtnCancelar.setBounds(305, 289, 80, 21); jbtnCancelar.setBackground(new java.awt.Color(82,209,232)); jbtnCancelar.setBorder(BorderFactory.createEtchedBorder(BevelBorder.LOWERED)); } } pack(); this.setSize(578, 813); } catch (Exception e) { //add your error handling code here e.printStackTrace(); } } //Ingresa los producto de la clase que hereda de AbstractTableModel public void IngresarProductos(AbstractTableModel abstractTableModel) { jTableOrdenProducto.setModel(abstractTableModel); jTableOrdenProducto.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { int fila = jTableOrdenProducto.rowAtPoint(e.getPoint()); int columna = jTableOrdenProducto.columnAtPoint(e.getPoint()); if ((fila > -1) && (columna > -1)); // System.out.println(modelo.getValueAt(fila,columna)); } }); } public void addListener(ActionListener actionListener) { this.jcmbCategoriaOrden.addActionListener(actionListener); this.jcmbProductoOrden.addActionListener(actionListener); this.jbtnBuscar.addActionListener(actionListener); this.jbtnRegistrar.addActionListener(actionListener); this.jbtnCancelar.addActionListener(actionListener); this.jbtnIngresarProductoTabla.addActionListener(actionListener); this.jbtnSalir.addActionListener(actionListener); this.jbtnProcesar.addActionListener(actionListener); this.jbtnCancelar.addActionListener(actionListener); } public void setcargarComboCategoria(List<String> categorias) { ComboBoxModel jcmbCategoriaOrdenModelModel = new DefaultComboBoxModel(categorias.toArray()); jcmbCategoriaOrden.setModel(jcmbCategoriaOrdenModelModel); } public void setcargarComboProducto(List<String> productos) { ComboBoxModel jcmbProductoOrdenModelModel = new DefaultComboBoxModel(productos.toArray()); jcmbProductoOrden.setModel(jcmbProductoOrdenModelModel); } public void setJtxtTelefono(String jtxtTelefono) { this.jtxtTelefono.setText(jtxtTelefono); } public String getTelefono() { return jtxtTelefono.getText(); } public String getDireccion() { return jtxtDireccion.getText(); } public String getCedulaCli() { return jtxtCedula.getText(); } public String getApellido() { return jtxtApellido.getText(); } public String getNombre() { return jtxtNombreCli.getText(); } public String getCodOrden() { return jtxtCodOrden.getText(); } public void setJtxtCodOrden(String jtxtCodOrden) { this.jtxtCodOrden.setText(jtxtCodOrden); } public String getCodProductoOrden() { return jtxtCodProductoOrden.getText(); } public void setJtxtCodProductoOrden(String valor3) { this.jtxtCodProductoOrden.setText(valor3); } public String getJtxtcodcategoria() { return jtxtcodcategoria.getText(); } public void setJtxtcodcategoria(String valor0) { this.jtxtcodcategoria.setText(valor0); } public void setJtxtDireccion(String jtxtDireccion) { this.jtxtDireccion.setText(jtxtDireccion); } public void setJtxtCedula(String jtxtCedula) { this.jtxtCedula.setText(jtxtCedula); } public void setJtxtApellido(String jtxtApellido) { this.jtxtApellido.setText(jtxtApellido); } public String getTotalPagar() { return jtxtTotalPagar.getText(); } public void setJtxtTotalPagar(String jtxtTotalPagar) { this.jtxtTotalPagar.setText(jtxtTotalPagar); } public void setJtxtNombreCli(String jtxtNombreCli) { this.jtxtNombreCli.setText(jtxtNombreCli); } public String getFechaOrden() { return jtxtFechaOrden.getText(); } public void setJtxtFechaOrden(String jtxtFechaOrden) { this.jtxtFechaOrden.setText(jtxtFechaOrden); } public JTable getjTableOrdenProducto() { return jTableOrdenProducto; } //Para retornar el texto del comboo!!! public String getJcmbCategoriaOrden() { return jcmbCategoriaOrden.getSelectedItem().toString(); } public String getJcmbProductoOrden() { return jcmbProductoOrden.getSelectedItem().toString(); } public void mostrarMensaje(String mensaje) { JOptionPane.showMessageDialog(this, mensaje); } public void borrarDatos (){ jtxtCedula.setText(""); jtxtNombreCli.setText(""); jtxtApellido.setText(""); jtxtDireccion.setText(""); jtxtTelefono.setText(""); jtxtCodOrden.setText(""); jtxtFechaOrden.setText(""); jtxtCedula.setEditable(true); jtxtNombreCli.setEditable(true); jtxtApellido.setEditable(true); jtxtDireccion.setEditable(true); jtxtTelefono.setEditable(true); } public void CamposNoEditables(){ jtxtCedula.setEditable(false); jtxtNombreCli.setEditable(false); jtxtApellido.setEditable(false); jtxtDireccion.setEditable(false); jtxtTelefono.setEditable(false); } }
1-1-cuarta-entrega
trunk/ProyectoVentaComidaRapida(NUEVO)/src/vista/VentanaOrden.java
Java
asf20
25,489
package modelo; //Entidad que asocia a producto con ingrediente public class DetalleProducto { private String codProducto, codIngrediente,descripcionIng; float cantidadIng; //Constructor con parametros public DetalleProducto(String codProducto, String codIngrediente, String descripcionIng, float cantidadIng) { super(); this.codProducto = codProducto; this.codIngrediente = codIngrediente; this.descripcionIng = descripcionIng; this.cantidadIng = cantidadIng; } //Constructor usado para instanciar un detalleProducto a la tabla de ingredientes public DetalleProducto(String codIngrediente, String descripcionIng, float cantidadIng) { super(); this.codIngrediente = codIngrediente; this.descripcionIng = descripcionIng; this.cantidadIng = cantidadIng; } //Getters y Setters public String getCodProducto() { return codProducto; } public void setCodProducto(String codProducto) { this.codProducto = codProducto; } public String getCodIngrediente() { return codIngrediente; } public void setCodIngrediente(String codIngrediente) { this.codIngrediente = codIngrediente; } public float getCantidadIng() { return cantidadIng; } public void setCantidadIng(float cantidadIng) { this.cantidadIng = cantidadIng; } public String getDescripcionIng() { return descripcionIng; } public void setDescripcionIng(String descripcionIng) { this.descripcionIng = descripcionIng; } }
1-1-cuarta-entrega
trunk/ProyectoVentaComidaRapida(NUEVO)/src/modelo/DetalleProducto.java
Java
asf20
1,907
package modelo; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public class ProductoDAO { public ProductoDAO() { super(); } public void registrarProducto(Producto producto) { String tiraSQL = "INSERT INTO producto "+"(codproducto,descripcionprod,codcategoria,fecharegistro,precio,cantidad) "+ "VALUES "+ "('"+producto.getCodProducto()+"','"+producto.getDescripcionProd()+"','"+producto.getCodCategoria() +"','"+producto.getFechaRegistro()+"','"+producto.getPrecio()+"','"+ producto.getCantidad()+"')"; Conexion.ejecutar(tiraSQL); } public List<Producto> consultarProductos() { List<Producto> productos = new ArrayList<Producto>(); String tiraSQL = "SELECT * FROM producto"; ResultSet resultSet = Conexion.consultar(tiraSQL); try { while (resultSet.next()) { String codProducto = resultSet.getString("codproducto"); String descripcionProducto = resultSet.getString("descripcionprod"); String codCategoria = resultSet.getString("codcategoria"); String fechaRegistro = resultSet.getString("fecharegistro"); int cantidad = Integer.parseInt(resultSet.getString("cantidad")); float precio = resultSet.getFloat("precio"); Producto producto = new Producto(codProducto, descripcionProducto, codCategoria,fechaRegistro, precio,cantidad); productos.add(producto); } } catch (SQLException e) { e.printStackTrace(); } return productos; } public void registrarDetalleProducto(DetalleProducto detProducto){ String tiraSQL = "INSERT INTO detalleproducto "+"(codproducto,codingrediente,descripcioning,cantidading) "+ "VALUES "+ "('"+detProducto.getCodProducto()+"','"+ detProducto.getCodIngrediente() +"','"+detProducto.getDescripcionIng() +"','"+ detProducto.getCantidadIng() +"')"; Conexion.ejecutar(tiraSQL); } public List<String> buscarProductosCategoria(String codCateg) { List<String> descripcionesProd = new ArrayList<String>(); String descripcionProd = ""; String tiraSQL = "SELECT descripcionprod FROM producto where codcategoria = '"+codCateg+"'"; ResultSet resultSet = Conexion.consultar(tiraSQL); try { while (resultSet.next()) { descripcionProd = resultSet.getString("descripcionprod"); descripcionesProd.add(descripcionProd); } } catch (SQLException e) { e.printStackTrace(); } return descripcionesProd; } public List<String> consultarProductosNombre() { List<String> productos = new ArrayList<String>(); String tiraSQL = "SELECT * From producto"; ResultSet resultSet = Conexion.consultar(tiraSQL); try { while (resultSet.next()) { String descripcionProd = resultSet.getString("descripcionprod"); productos.add(descripcionProd); } } catch (SQLException e) { e.printStackTrace(); } return productos; } public String buscarCodProducto(String descProd){ boolean encontrado = false; String codProducto = ""; String descripcionProd; String tiraSQL = "SELECT codproducto,descripcionprod FROM producto"; ResultSet resultSet = Conexion.consultar(tiraSQL); try { while (resultSet.next() && encontrado == false ) { //Mientras el resulSet tengo otro dato haga. descripcionProd = resultSet.getString("descripcionprod"); if(descProd.compareTo(descripcionProd) == 0) { encontrado = true; codProducto = resultSet.getString("codproducto"); } } } catch (SQLException e) { e.printStackTrace(); } return codProducto; } public Producto consultarProducto(String codigo) { Producto producto = new Producto(); boolean encontrado = false; String tiraSQL = "SELECT * FROM producto where codproducto = '" + codigo + "'"; ResultSet resultSet = Conexion.consultar(tiraSQL); try { while (resultSet.next() && encontrado == false) { String codProducto = resultSet.getString("codproducto"); String descripcionProducto = resultSet.getString("descripcionprod"); String fechaRegistro = resultSet.getString("fecharegistro"); String codCateg = resultSet.getString("codcategoria"); float precio = resultSet.getFloat("precio"); int cantidad = Integer.parseInt(resultSet.getString("cantidad")); if(codigo.compareTo(codProducto) == 0){ encontrado = true; producto = new Producto(codProducto,descripcionProducto, codCateg, fechaRegistro,precio,cantidad); } } } catch (SQLException e) { e.printStackTrace(); } return producto; } }
1-1-cuarta-entrega
trunk/ProyectoVentaComidaRapida(NUEVO)/src/modelo/ProductoDAO.java
Java
asf20
6,415
package modelo; import java.sql.*; public class Conexion { // La descripcion del driver de la BD private static String driver = "org.postgresql.Driver"; // La direccion URL de la BD private static String url = "jdbc:postgresql://localhost:5432/"; // El nombre de la BD private static String bd = "BD1-1"; // EL login del usuario para conectarse al servidor de BD private static String usuario = "postgres"; // EL password del usuario para conectarse al servidor de BD private static String password = "87997872"; private static Connection conexion; /** * Metodo utilizado para Obtener una conexion a BD * @return Un objeto tipo Connection que representa una conexion a la BD */ private static Connection getConexion() { try{ if (conexion == null || conexion.isClosed()) { // Cargo el driver en memoria Class.forName(driver); // Establezco la conexion conexion=DriverManager.getConnection(url+bd,usuario,password); } } catch(SQLException e){ e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return conexion; } /** * Metodo consultar * @param String tiraSQL * @return ResultSet */ public static ResultSet consultar(String tiraSQL) { getConexion(); ResultSet resultado = null; try { Statement sentencia= conexion.createStatement(); resultado = sentencia.executeQuery(tiraSQL); } catch(Exception e) { e.printStackTrace(); } try { conexion.close(); } catch( SQLException e ) { e.printStackTrace(); } return resultado; } /** * Metodo ejecutar * @param String TiraSQL * @return boolean */ public static boolean ejecutar(String tiraSQL) { getConexion(); boolean ok = false; try { Statement sentencia = conexion.createStatement(); int i = sentencia.executeUpdate(tiraSQL); if (i > 0) { ok = true; } sentencia.close (); } catch(Exception e) { e.printStackTrace(); } try { conexion.close(); } catch( SQLException e ) { e.printStackTrace(); } return ok; } }
1-1-cuarta-entrega
trunk/ProyectoVentaComidaRapida(NUEVO)/src/modelo/Conexion.java
Java
asf20
2,671
package modelo; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public class OrdenDAO { public OrdenDAO() { super(); } public void registrarOrden(Orden orden) { String tiraSQL = "INSERT INTO orden "+"(codorden,cedulacli,fechaorden,totalpagar) "+ "VALUES "+ "('"+orden.getCodOrden()+"','"+orden.getCedulaCli()+"','"+orden.getFechaOrd() +"','"+orden.getTotalPagar()+"')"; Conexion.ejecutar(tiraSQL); } }
1-1-cuarta-entrega
trunk/ProyectoVentaComidaRapida(NUEVO)/src/modelo/OrdenDAO.java
Java
asf20
685
package modelo; import java.util.Vector; public class Orden { private String codOrden, cedulaCli, fechaOrd; private float totalPagar; //Vector de Producto para permitir el manejo de la disponibilidad del producto a ordenar. Vector <Producto> producto = new Vector <Producto>(); public Orden(String codOrden, String cedulaCli, String fechaOrd, float totalPagar) { super(); this.codOrden = codOrden; this.cedulaCli = cedulaCli; this.fechaOrd = fechaOrd; this.totalPagar = totalPagar; } //Getters y Setters public String getCodOrden() { return codOrden; } public void setCodOrden(String codOrden) { this.codOrden = codOrden; } public String getCedulaCli() { return cedulaCli; } public void setCedulaCli(String cedulaCli) { this.cedulaCli = cedulaCli; } public String getFechaOrd() { return fechaOrd; } public void setFechaOrd(String fechaOrd) { this.fechaOrd = fechaOrd; } public float getTotalPagar() { return totalPagar; } public void setTotalPagar(float totalPagar) { this.totalPagar = totalPagar; } public Vector<Producto> getProducto() { return producto; } public void setProducto(Vector<Producto> producto) { this.producto = producto; } //Métodos }
1-1-cuarta-entrega
trunk/ProyectoVentaComidaRapida(NUEVO)/src/modelo/Orden.java
Java
asf20
1,694
package modelo; import javax.swing.JOptionPane; import vista.VentanaCategoria; abstract class Creador { VentanaCategoria ventanaCategoria = new VentanaCategoria(); public static Creador metodoFabrica(String tipo){ if(tipo.equals("Salir")) return new Mensaje(); return null; } public String toString() { return "Creador"; } } class Mensaje extends Creador { int confirmacion; public String toString() { if(JOptionPane.showConfirmDialog(null, "¿Realmente Desea Salir?", "Confirmar Salida", JOptionPane.YES_NO_OPTION)==0); ventanaCategoria.dispose(); return null; } public int getConfirmacion() { int j = JOptionPane.showConfirmDialog(null, "¿Realmente Desea Salir?", "Confirmar Salida", JOptionPane.YES_NO_OPTION); return j; } }
1-1-cuarta-entrega
trunk/ProyectoVentaComidaRapida(NUEVO)/src/modelo/Creador.java
Java
asf20
771
package modelo; import java.util.Vector; public class Producto { private String codProducto, descripcionProd, codCategoria, fechaRegistro; private float precio; int cantidad; /*Vector de ingrediente para llevar el control de la cantidad y * descripción de ingredientes que contiene cada producto*/ Vector <DetalleProducto> ingredientes = new Vector <DetalleProducto>(); //Constructor public Producto() { super(); // TODO Auto-generated constructor stub } public Producto(String codProducto, String descripcionProd, String codCategoria, String fechaRegistro, float precio, int cantidad) { super(); this.codProducto = codProducto; this.descripcionProd = descripcionProd; this.codCategoria = codCategoria; this.fechaRegistro = fechaRegistro; this.precio = precio; this.cantidad = cantidad; } //constructor usado para llenar con productos la tabla de detalleOrden public Producto(String codProducto, String descripcionProd, float precio, int cantidad) { super(); this.codProducto = codProducto; this.descripcionProd = descripcionProd; this.precio = precio; this.cantidad = cantidad; } //Getters y Setters public String getCodProducto() { return codProducto; } public void setCodProducto(String codProducto) { this.codProducto = codProducto; } public String getDescripcionProd() { return descripcionProd; } public void setDescripcionProd(String descripcionProducto) { this.descripcionProd = descripcionProducto; } public String getCodCategoria() { return codCategoria; } public void setCodCategoria(String codCategoria) { this.codCategoria = codCategoria; } public String getFechaRegistro() { return fechaRegistro; } public void setFechaRegistro(String fechaRegistro) { this.fechaRegistro = fechaRegistro; } public float getPrecio() { return precio; } public void setPrecio(float precio) { this.precio = precio; } public int getCantidad() { return cantidad; } public void setCantidad(int cantidad) { this.cantidad = cantidad; } }
1-1-cuarta-entrega
trunk/ProyectoVentaComidaRapida(NUEVO)/src/modelo/Producto.java
Java
asf20
2,761
package modelo; import java.util.ArrayList; import java.util.List; import java.util.ListIterator; import modelo.DetalleOrdenDAO; //PATRON ITERATOR public class Coleccion{ private DetalleOrdenDAO detOrdenDAO = new DetalleOrdenDAO(); List<DetalleOrden> milistamontos = new ArrayList<DetalleOrden>(); List<DetalleOrden> milistacantidades = new ArrayList<DetalleOrden>(); /********************************************************************/ public Coleccion() { milistamontos = detOrdenDAO.consultarProductoMonto(); milistacantidades = detOrdenDAO.consultarProductoCantidad(); }//Coleccion public List<DetalleOrden> getMilistamontos() { return milistamontos; } public List<DetalleOrden> getMilistacantidades() { return milistacantidades; } public ListIterator miIteratorMonto(int index) { return milistamontos.listIterator(index); }//miIteratorMonto public ListIterator miIteratorCantidad(int index) { return milistacantidades.listIterator(index); }//miIteratorCantidad }
1-1-cuarta-entrega
trunk/ProyectoVentaComidaRapida(NUEVO)/src/modelo/Coleccion.java
Java
asf20
1,010
package modelo; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import vista.VentanaCategoria; public class ProbarMetodosFabricaCreador implements ActionListener{ private VentanaCategoria ventanaCategoria; public ProbarMetodosFabricaCreador() { super(); ventanaCategoria = new VentanaCategoria(); ventanaCategoria.addListener(this); Creador a = Creador.metodoFabrica("Salir"); a.toString(); } @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub if(e.getActionCommand().equals("Salir")){ } } }
1-1-cuarta-entrega
trunk/ProyectoVentaComidaRapida(NUEVO)/src/modelo/ProbarMetodosFabricaCreador.java
Java
asf20
583
package modelo; public class Ingrediente { private String codIngrediente, descripcionIng; private float existencia; //Faltaba el constructor con parametros public Ingrediente(String codIngrediente, String descripcionIng, float existencia) { super(); this.codIngrediente = codIngrediente; this.descripcionIng = descripcionIng; this.existencia = existencia; } public Ingrediente(String descripcionIng,float existencia) { super(); this.descripcionIng = descripcionIng; this.existencia = existencia; } //Getters y Setters public String getCodIngrediente() { return codIngrediente; } public void setCodIngrediente(String codIngrediente) { this.codIngrediente = codIngrediente; } public String getDescripcionIng() { return descripcionIng; } public void setDescripcionIng(String descripcionIng) { this.descripcionIng = descripcionIng; } public float getExistencia() { return existencia; } public void setExistencia(float existencia) { this.existencia = existencia; } //Métodos //Actualiza la existencia public void comprarIngrediente(){ } }
1-1-cuarta-entrega
trunk/ProyectoVentaComidaRapida(NUEVO)/src/modelo/Ingrediente.java
Java
asf20
1,518
package modelo; public class DetalleOrden { private String codOrden, codProducto,descripcionProd; int cantidadProd; float monto; public DetalleOrden() { super(); } public DetalleOrden(String codOrden,String codProducto, String descripcionProd, int cantidadProd, float monto) { super(); this.codProducto = codProducto; this.codOrden = codOrden; this.descripcionProd = descripcionProd; this.cantidadProd = cantidadProd; this.monto = monto; } //Constructor usado para instanciar un detalleOrden a la tabla de producto public DetalleOrden(String codProducto, String descripcionProd,float monto, int cantidadProd) { super(); this.codProducto = codProducto; this.descripcionProd = descripcionProd; this.monto = monto; this.cantidadProd = cantidadProd; } public String getCodProducto() { return codProducto; } public void setCodProducto(String codProducto) { this.codProducto = codProducto; } public String getCodOrden() { return codOrden; } public void setCodOrden(String codOrden) { this.codOrden = codOrden; } public String getDescripcionProd() { return descripcionProd; } public float getMonto() { return monto; } public void setMonto(float monto) { this.monto = monto; } public void setDescripcionProd(String descripcionProd) { this.descripcionProd = descripcionProd; } public int getCantidadProd () { return cantidadProd; } public void setCantidadProd(int cantidad) { this.cantidadProd = cantidad; } }
1-1-cuarta-entrega
trunk/ProyectoVentaComidaRapida(NUEVO)/src/modelo/DetalleOrden.java
Java
asf20
2,098
/* * 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")); } }
09bicsekanjam-clone
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)); } }
09bicsekanjam-clone
tests/src/com/android/inputmethod/latin/SuggestPerformanceTests.java
Java
asf20
4,654
/* * 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 } }
09bicsekanjam-clone
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.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}, }; }
09bicsekanjam-clone
tests/src/com/android/inputmethod/latin/SuggestHelper.java
Java
asf20
10,798
/* * 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"; }
09bicsekanjam-clone
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)
09bicsekanjam-clone
tests/Android.mk
Makefile
asf20
379
# 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 # ************************************************
09bicsekanjam-clone
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. LOCAL_PATH := $(call my-dir) include $(call all-makefiles-under,$(LOCAL_PATH))
09bicsekanjam-clone
Android.mk
Makefile
asf20
681
#!/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)
09bicsekanjam-clone
java/GetLanguages.sh
Shell
asf20
889
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); } }
09bicsekanjam-clone
java/src/org/pocketworkstation/pckeyboard/AutoSummaryEditTextPreference.java
Java
asf20
708
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); } } }
09bicsekanjam-clone
java/src/org/pocketworkstation/pckeyboard/NotificationReceiver.java
Java
asf20
856
/* * 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; } }
09bicsekanjam-clone
java/src/org/pocketworkstation/pckeyboard/MiniKeyboardKeyDetector.java
Java
asf20
2,159
/** * */ 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(); } }
09bicsekanjam-clone
java/src/org/pocketworkstation/pckeyboard/AutoSummaryListPreference.java
Java
asf20
1,411
/* * Copyright (C) 2008-2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.pocketworkstation.pckeyboard; import org.xmlpull.v1.XmlPullParserException; import android.content.Context; import android.content.res.Resources; import android.content.res.TypedArray; import android.content.res.XmlResourceParser; import android.graphics.drawable.Drawable; import android.text.TextUtils; import android.util.Log; import android.util.TypedValue; import android.util.Xml; import android.util.DisplayMetrics; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Set; import java.util.StringTokenizer; /** * Loads an XML description of a keyboard and stores the attributes of the keys. A keyboard * consists of rows of keys. * <p>The layout file for a keyboard contains XML that looks like the following snippet:</p> * <pre> * &lt;Keyboard * android:keyWidth="%10p" * android:keyHeight="50px" * android:horizontalGap="2px" * android:verticalGap="2px" &gt; * &lt;Row android:keyWidth="32px" &gt; * &lt;Key android:keyLabel="A" /&gt; * ... * &lt;/Row&gt; * ... * &lt;/Keyboard&gt; * </pre> * @attr ref android.R.styleable#Keyboard_keyWidth * @attr ref android.R.styleable#Keyboard_keyHeight * @attr ref android.R.styleable#Keyboard_horizontalGap * @attr ref android.R.styleable#Keyboard_verticalGap */ public class Keyboard { static final String TAG = "Keyboard"; public final static char DEAD_KEY_PLACEHOLDER = 0x25cc; // dotted small circle public final static String DEAD_KEY_PLACEHOLDER_STRING = Character.toString(DEAD_KEY_PLACEHOLDER); // Keyboard XML Tags private static final String TAG_KEYBOARD = "Keyboard"; private static final String TAG_ROW = "Row"; private static final String TAG_KEY = "Key"; public static final int EDGE_LEFT = 0x01; public static final int EDGE_RIGHT = 0x02; public static final int EDGE_TOP = 0x04; public static final int EDGE_BOTTOM = 0x08; public static final int KEYCODE_SHIFT = -1; public static final int KEYCODE_MODE_CHANGE = -2; public static final int KEYCODE_CANCEL = -3; public static final int KEYCODE_DONE = -4; public static final int KEYCODE_DELETE = -5; public static final int KEYCODE_ALT_SYM = -6; // Backwards compatible setting to avoid having to change all the kbd_qwerty files public static final int DEFAULT_LAYOUT_ROWS = 4; public static final int DEFAULT_LAYOUT_COLUMNS = 10; // Flag values for popup key contents. Keep in sync with strings.xml values. public static final int POPUP_ADD_SHIFT = 1; public static final int POPUP_ADD_CASE = 2; public static final int POPUP_ADD_SELF = 4; public static final int POPUP_DISABLE = 256; public static final int POPUP_AUTOREPEAT = 512; /** Horizontal gap default for all rows */ private float mDefaultHorizontalGap; private float mHorizontalPad; private float mVerticalPad; /** Default key width */ private float mDefaultWidth; /** Default key height */ private int mDefaultHeight; /** Default gap between rows */ private int mDefaultVerticalGap; public static final int SHIFT_OFF = 0; public static final int SHIFT_ON = 1; public static final int SHIFT_LOCKED = 2; public static final int SHIFT_CAPS = 3; public static final int SHIFT_CAPS_LOCKED = 4; /** Is the keyboard in the shifted state */ private int mShiftState = SHIFT_OFF; /** Key instance for the shift key, if present */ private Key mShiftKey; private Key mAltKey; private Key mCtrlKey; 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 + ")"; } }
09bicsekanjam-clone
java/src/org/pocketworkstation/pckeyboard/Keyboard.java
Java
asf20
53,837
/* * 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; } }
09bicsekanjam-clone
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 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; } }
09bicsekanjam-clone
java/src/org/pocketworkstation/pckeyboard/ProximityKeyDetector.java
Java
asf20
3,229
/* * 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; } }
09bicsekanjam-clone
java/src/org/pocketworkstation/pckeyboard/WordComposer.java
Java
asf20
6,622
/* * 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; } }
09bicsekanjam-clone
java/src/org/pocketworkstation/pckeyboard/DeadAccentSequence.java
Java
asf20
30,433
/* * 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); } } }
09bicsekanjam-clone
java/src/org/pocketworkstation/pckeyboard/SwipeTracker.java
Java
asf20
4,721
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(); } }
09bicsekanjam-clone
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.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; } }
09bicsekanjam-clone
java/src/org/pocketworkstation/pckeyboard/Tutorial.java
Java
asf20
9,032
/* * 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() { } }
09bicsekanjam-clone
java/src/org/pocketworkstation/pckeyboard/Dictionary.java
Java
asf20
5,095
/* * 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); } } }
09bicsekanjam-clone
java/src/org/pocketworkstation/pckeyboard/LatinKeyboardView.java
Java
asf20
27,100
/* * 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? } }
09bicsekanjam-clone
java/src/org/pocketworkstation/pckeyboard/Main.java
Java
asf20
3,648
/* * 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; } } }
09bicsekanjam-clone
java/src/org/pocketworkstation/pckeyboard/AutoDictionary.java
Java
asf20
10,249
/* * 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; } }
09bicsekanjam-clone
java/src/org/pocketworkstation/pckeyboard/LatinKeyboardBaseView.java
Java
asf20
73,824
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(); } }
09bicsekanjam-clone
java/src/org/pocketworkstation/pckeyboard/SeekBarPreference.java
Java
asf20
5,599
/* * 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(); } }
09bicsekanjam-clone
java/src/org/pocketworkstation/pckeyboard/SharedPreferencesCompat.java
Java
asf20
1,699
/* * 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; } } }
09bicsekanjam-clone
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 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); }
09bicsekanjam-clone
java/src/org/pocketworkstation/pckeyboard/KeyDetector.java
Java
asf20
3,832
/* * 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; } } }
09bicsekanjam-clone
java/src/org/pocketworkstation/pckeyboard/LatinKeyboard.java
Java
asf20
39,247
/* * 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; } }
09bicsekanjam-clone
java/src/org/pocketworkstation/pckeyboard/LatinIME.java
Java
asf20
146,087
/* * 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/", "🙌"); } }
09bicsekanjam-clone
java/src/org/pocketworkstation/pckeyboard/ComposeSequence.java
Java
asf20
27,394
/* * 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 } }
09bicsekanjam-clone
java/src/org/pocketworkstation/pckeyboard/ComposeBase.java
Java
asf20
4,179
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); } }
09bicsekanjam-clone
java/src/org/pocketworkstation/pckeyboard/GlobalKeyboardSettings.java
Java
asf20
11,072
/* * 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) { } }
09bicsekanjam-clone
java/src/org/pocketworkstation/pckeyboard/LatinImeLogger.java
Java
asf20
1,907
/* * 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); } } }
09bicsekanjam-clone
java/src/org/pocketworkstation/pckeyboard/TextEntryState.java
Java
asf20
9,061
/* * 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" : ""))); } }
09bicsekanjam-clone
java/src/org/pocketworkstation/pckeyboard/PointerTracker.java
Java
asf20
23,344
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); } }
09bicsekanjam-clone
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.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); } } }
09bicsekanjam-clone
java/src/org/pocketworkstation/pckeyboard/PrefScreenView.java
Java
asf20
2,050
/* * 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"); } } }
09bicsekanjam-clone
java/src/org/pocketworkstation/pckeyboard/ContactsDictionary.java
Java
asf20
5,606
/* * 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); } }
09bicsekanjam-clone
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 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; } } }
09bicsekanjam-clone
java/src/org/pocketworkstation/pckeyboard/KeyboardSwitcher.java
Java
asf20
28,168