code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
/*
CoE 1186
1186 Entertainment
Reversi Game
ReversiGameBoard.java
-----------------------------------------
ReversiGameBoard
- Abstract or Concrete: Concrete
- List of Superclasses: GameBoard, MyPanel, JPanel
- List of Subclasses: N/A
- Purpose: Java Reversi Game
- Collaborations: Loaded by the ReversiGameRoom, Send Messages to server through ClientApplet
---------------------
- Attributes:
---------------------
- Operations:
---------------------
- Constraints: N/A
-----------------------------------------
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import javax.imageio.*;
import java.util.Random;
public class ReversiGameBoard extends MyPanel {
ReversiGameManager gm;
ClientApplet ca;
ReversiGameRoom room;
String DELIM = "&";
int player1, player2, r;
ReversiGamePiece [][] pieces;
/*public ReversiGameBoard() {
ReversiGamePiece [][] pieces = new ReversiGamePiece[8][8];
setPreferredSize(new Dimension(400,400));
setBackgroundPosition(MyPanel.STRETCHED);
setBackgroundImage("files/board.jpg");
setLayout(new GridLayout(8,8));
gm = new ReversiGameManager(pieces,this);
for (int i = 0 ; i < 8 ; i++ )
{
for (int j = 0; j < 8 ; j++ )
{
pieces[i][j] = new ReversiGamePiece();
pieces[i][j].addMouseListener(gm);
add(pieces[i][j]);
}
}
initialize(pieces);
}*/
public ReversiGameBoard(ClientApplet ca, ReversiGameRoom room, int player1, int player2) {
this.ca = ca;
this.room = room;
this.player1 = player1;
this.player2 = player2;
pieces = new ReversiGamePiece[8][8];
setPreferredSize(new Dimension(400,400));
//setBackgroundPosition(MyPanel.STRETCHED);
//setBackgroundImage("files/board.jpg");
setLayout(new GridLayout(8,8));
gm = new ReversiGameManager(pieces,this);
for (int i = 0 ; i < 8 ; i++ )
{
for (int j = 0; j < 8 ; j++ )
{
pieces[i][j] = new ReversiGamePiece(ca);
pieces[i][j].addMouseListener(gm);
add(pieces[i][j]);
}
}
initialize(pieces);
}
public void initialize(ReversiGamePiece [][] pieces)
{
pieces[3][3].makeMove(ReversiGamePiece.WHITE);
pieces[3][4].makeMove(ReversiGamePiece.BLACK);
pieces[4][4].makeMove(ReversiGamePiece.WHITE);
pieces[4][3].makeMove(ReversiGamePiece.BLACK);
Random generator = new Random();
r = generator.nextInt(1000);
ca.send("22" + DELIM + "01" + DELIM + r);
}
public void processMove( String msg)
{
String[] msgParts = msg.split(DELIM);
int msgId = Integer.parseInt(msgParts[1]);
switch(msgId)
{
case 01:
if (r > Integer.parseInt(msgParts[2]))
{
gm.mycolor = ReversiGamePiece.BLACK;
room.setGamePieceText("Black");
room.setStatusText("Waiting for other player to go");
}
if (r < Integer.parseInt(msgParts[2]))
{
gm.mycolor = ReversiGamePiece.WHITE;
gm.turn = true;
room.setGamePieceText("White");
room.setStatusText("It\'s your turn.");
}
System.out.println("" + r + " " + Integer.parseInt(msgParts[2]));
break;
case 02:
gm.checkMove(pieces[Integer.parseInt(msgParts[3])][Integer.parseInt(msgParts[4])],Integer.parseInt(msgParts[2]),gm.mycolor);
room.setStatusText("It\'s your turn.");
gm.turn = true;
gm.checkBoard(gm.mycolor);
break;
case 03:
room.setStatusText("It\'s your turn.");
gm.turn = true;
gm.checkBoard(gm.mycolor);
break;
}
}
}
class ReversiGameManager implements MouseListener
{
static int moving;
boolean turn = false;
int mycolor,opposite;
ReversiGamePiece [][] pieces;
ReversiGameBoard board;
public ReversiGameManager(ReversiGamePiece [][] pieces, ReversiGameBoard board)
{
this.pieces = pieces;
this.board = board;
}
public void mouseClicked(MouseEvent e)
{
ReversiGamePiece theEventer = (ReversiGamePiece) e.getSource();
if(theEventer.current == 0)
{
if (turn)
{
if(mycolor == ReversiGamePiece.WHITE)
opposite = ReversiGamePiece.BLACK;
else
opposite = ReversiGamePiece.WHITE;
if(checkMove(theEventer,mycolor,opposite))
{
int x, y;
for(int i=0;i<8;i++)
{
for (int j=0;j<8 ;j++)
{
if(pieces[i][j] == theEventer)
{
x = i;
y = j;
board.ca.send("22" + board.DELIM + "02" + board.DELIM+ mycolor + board.DELIM + x + board.DELIM + y);
board.room.setStatusText("Waiting for other player to go");
turn = false;
if(evalBoard(mycolor) == 3)
checkBoard(mycolor);
}
}
}
}
}
}
}
public void checkBoard(int player)
{
int black = 0;
int white = 0;
switch(evalBoard(player))
{
case 1:
break;
case 2:
JOptionPane.showMessageDialog(board, "No Remaining Moves\nPassing Turn", "Message", JOptionPane.ERROR_MESSAGE);
board.room.setStatusText("Waiting for other player to go");
board.ca.send("22" + board.DELIM + "03");
turn = false;
break;
case 3:
for(int i=0;i<8;i++)
{
for (int j=0;j<8 ;j++)
{
if(pieces[i][j].current == ReversiGamePiece.BLACK){black++;}
if(pieces[i][j].current == ReversiGamePiece.WHITE){white++;}
}
}
if (black > white)
{
if(mycolor == ReversiGamePiece.BLACK)
{
JOptionPane.showMessageDialog(board, "You Win!!!", "Game Over", JOptionPane.INFORMATION_MESSAGE);
turn = false;
board.ca.send("23" + board.DELIM + board.player1 + board.DELIM + "1");
board.ca.send("4" + board.DELIM + "0");
}
else
{
JOptionPane.showMessageDialog(board, "You Lose!!!", "Game Over", JOptionPane.INFORMATION_MESSAGE);
turn = false;
board.ca.send("23" + board.DELIM + board.player1 + board.DELIM + "2");
board.ca.send("4" + board.DELIM + "0");
}
}
else if (white > black)
{
if(mycolor == ReversiGamePiece.WHITE)
{
JOptionPane.showMessageDialog(board, "You Win!!!", "Game Over", JOptionPane.INFORMATION_MESSAGE);
turn = false;
board.ca.send("23" + board.DELIM + board.player1 + board.DELIM + "1");
board.ca.send("4" + board.DELIM + "0");
}
else
{
JOptionPane.showMessageDialog(board, "You Lose!!!", "Game Over", JOptionPane.INFORMATION_MESSAGE);
turn = false;
board.ca.send("23" + board.DELIM + board.player1 + board.DELIM + "2");
board.ca.send("4" + board.DELIM + "0");
}
}
else if (white == black)
{
JOptionPane.showMessageDialog(board, "It is a Tie!!!", "Game Over", JOptionPane.INFORMATION_MESSAGE);
turn = false;
board.ca.send("4" + board.DELIM + "0");
}
break;
}
}
private int evalBoard(int player)
{
int opposite;
if(player == ReversiGamePiece.WHITE)
opposite = ReversiGamePiece.BLACK;
else
opposite = ReversiGamePiece.WHITE;
for (int i = 0 ; i < 8 ; i++ )
{
for (int j = 0; j < 8 ; j++ )
{
if(pieces[i][j].current == 0)
{
boolean moveleft = false;
moveleft = checkLeft(i,j-1,player,opposite,true,true) || moveleft;
moveleft = checkUpLeft(i-1,j-1,player,opposite,true,true) || moveleft;
moveleft = checkUp(i-1,j,player,opposite,true,true) || moveleft;
moveleft = checkUpRight(i-1,j+1,player,opposite,true,true) || moveleft;
moveleft = checkRight(i,j+1,player,opposite,true,true) || moveleft;
moveleft = checkDownRight(i+1,j+1,player,opposite,true,true) || moveleft;
moveleft = checkDown(i+1,j,player,opposite,true,true) || moveleft;
moveleft = checkDownLeft(i+1,j-1,player,opposite,true,true) || moveleft;
if(moveleft)
{
return 1;
}
}
}
}
for (int i = 0 ; i < 8 ; i++ )
{
for (int j = 0; j < 8 ; j++ )
{
if(pieces[i][j].current == 0)
{
boolean moveleft = false;
moveleft = checkLeft(i,j-1,opposite,player,true,true) || moveleft;
moveleft = checkUpLeft(i-1,j-1,opposite,player,true,true) || moveleft;
moveleft = checkUp(i-1,j,opposite,player,true,true) || moveleft;
moveleft = checkUpRight(i-1,j+1,opposite,player,true,true) || moveleft;
moveleft = checkRight(i,j+1,opposite,player,true,true) || moveleft;
moveleft = checkDownRight(i+1,j+1,opposite,player,true,true) || moveleft;
moveleft = checkDown(i+1,j,opposite,player,true,true) || moveleft;
moveleft = checkDownLeft(i+1,j-1,opposite,player,true,true) || moveleft;
if(moveleft)
{
return 2;
}
}
}
}
return 3;
}
public boolean checkMove(ReversiGamePiece MadeMove, int current, int opposite)
{
int x=0, y=0;
boolean legal = false;
for(int i=0;i<8;i++)
{
for (int j=0;j<8 ;j++)
{
if(pieces[i][j] == MadeMove)
{
x = i;
y = j;
}
}
}
legal = checkLeft(x,y-1,current,opposite,true,false) || legal;
legal = checkUpLeft(x-1,y-1,current,opposite,true,false) || legal;
legal = checkUp(x-1,y,current,opposite,true,false) || legal;
legal = checkUpRight(x-1,y+1,current,opposite,true,false) || legal;
legal = checkRight(x,y+1,current,opposite,true,false) || legal;
legal = checkDownRight(x+1,y+1,current,opposite,true,false) || legal;
legal = checkDown(x+1,y,current,opposite,true,false) || legal;
legal = checkDownLeft(x+1,y-1,current,opposite,true,false) || legal;
if(legal)
{
MadeMove.makeMove(current);
board.repaint();
return(true);
}
else
{
return(false);
}
}
private boolean checkLeft(int x, int y, int current,int opposite, boolean firstrun, boolean evaluating)
{
if (x >= 0 && x <8)
{
if(y >= 0 && y <8)
{
if(pieces[x][y].current==opposite)
{
if(checkLeft(x,y-1,current,opposite,false,evaluating))
{
if(!evaluating)
pieces[x][y].flipPiece();
return true;
}
else
{
return false;
}
}
else if(pieces[x][y].current == current)
{
if (firstrun)
{
return false;
}
else
{
return true;
}
}
else
{
return false;
}
}
else
{
return false;
}
}
else
{
return false;
}
}
private boolean checkUpLeft(int x, int y, int current,int opposite, boolean firstrun, boolean evaluating)
{
if (x >= 0 && x <8)
{
if(y >= 0 && y <8)
{
if(pieces[x][y].current==opposite)
{
if(checkUpLeft(x-1,y-1,current,opposite,false,evaluating))
{
if(!evaluating)
pieces[x][y].flipPiece();
return true;
}
else
{
return false;
}
}
else if(pieces[x][y].current == current)
{
if (firstrun)
{
return false;
}
else
{
return true;
}
}
else
{
return false;
}
}
else
{
return false;
}
}
else
{
return false;
}
}
private boolean checkUp(int x, int y, int current,int opposite, boolean firstrun, boolean evaluating)
{
if (x >= 0 && x <8)
{
if(y >= 0 && y <8)
{
if(pieces[x][y].current==opposite)
{
if(checkUp(x-1,y,current,opposite,false,evaluating))
{
if(!evaluating)
pieces[x][y].flipPiece();
return true;
}
else
{
return false;
}
}
else if(pieces[x][y].current == current)
{
if (firstrun)
{
return false;
}
else
{
return true;
}
}
else
{
return false;
}
}
else
{
return false;
}
}
else
{
return false;
}
}
private boolean checkUpRight(int x, int y, int current,int opposite, boolean firstrun, boolean evaluating)
{
if (x >= 0 && x <8)
{
if(y >= 0 && y <8)
{
if(pieces[x][y].current==opposite)
{
if(checkUpRight(x-1,y+1,current,opposite,false,evaluating))
{
if(!evaluating)
pieces[x][y].flipPiece();
return true;
}
else
{
return false;
}
}
else if(pieces[x][y].current == current)
{
if (firstrun)
{
return false;
}
else
{
return true;
}
}
else
{
return false;
}
}
else
{
return false;
}
}
else
{
return false;
}
}
private boolean checkRight(int x, int y, int current,int opposite, boolean firstrun, boolean evaluating)
{
if (x >= 0 && x <8)
{
if(y >= 0 && y <8)
{
if(pieces[x][y].current==opposite)
{
if(checkRight(x,y+1,current,opposite,false,evaluating))
{
if(!evaluating)
pieces[x][y].flipPiece();
return true;
}
else
{
return false;
}
}
else if(pieces[x][y].current == current)
{
if (firstrun)
{
return false;
}
else
{
return true;
}
}
else
{
return false;
}
}
else
{
return false;
}
}
else
{
return false;
}
}
private boolean checkDownRight(int x, int y, int current,int opposite, boolean firstrun, boolean evaluating)
{
if (x >= 0 && x <8)
{
if(y >= 0 && y <8)
{
if(pieces[x][y].current==opposite)
{
if(checkDownRight(x+1,y+1,current,opposite,false,evaluating))
{
if(!evaluating)
pieces[x][y].flipPiece();
return true;
}
else
{
return false;
}
}
else if(pieces[x][y].current == current)
{
if (firstrun)
{
return false;
}
else
{
return true;
}
}
else
{
return false;
}
}
else
{
return false;
}
}
else
{
return false;
}
}
private boolean checkDown(int x, int y, int current,int opposite, boolean firstrun, boolean evaluating)
{
if (x >= 0 && x <8)
{
if(y >= 0 && y <8)
{
if(pieces[x][y].current==opposite)
{
if(checkDown(x+1,y,current,opposite,false,evaluating))
{
if(!evaluating)
pieces[x][y].flipPiece();
return true;
}
else
{
return false;
}
}
else if(pieces[x][y].current == current)
{
if (firstrun)
{
return false;
}
else
{
return true;
}
}
else
{
return false;
}
}
else
{
return false;
}
}
else
{
return false;
}
}
private boolean checkDownLeft(int x, int y, int current,int opposite, boolean firstrun, boolean evaluating)
{
if (x >= 0 && x <8)
{
if(y >= 0 && y <8)
{
if(pieces[x][y].current==opposite)
{
if(checkDownLeft(x+1,y-1,current,opposite,false,evaluating))
{
if(!evaluating)
pieces[x][y].flipPiece();
return true;
}
else
{
return false;
}
}
else if(pieces[x][y].current == current)
{
if (firstrun)
{
return false;
}
else
{
return true;
}
}
else
{
return false;
}
}
else
{
return false;
}
}
else
{
return false;
}
}
public void mousePressed(MouseEvent e){}
public void mouseReleased(MouseEvent e){}
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e){}
}
class ReversiGamePiece extends JPanel implements Runnable {
Image[] picture = new Image[9];
int totalPictures = 0;
public final static int BLACK = 1;
public final static int WHITE = 7;
int current = 0;
int temp = 0;
int go = 0;
Thread runner;
int pause = 80;
String[] imageNames = { "files/0.gif", "files/1.gif", "files/2.gif", "files/3.gif", "files/4.gif", "files/5.gif", "files/6.gif", "files/7.gif" };
public ReversiGamePiece(ClientApplet ca) {
super();
Toolkit kit = Toolkit.getDefaultToolkit();
for (int i = 0; i < imageNames.length; i++) {
picture[i] = ca.getImage(ca.getDocumentBase(),imageNames[i]);
}
runner = new Thread(this);
}
public void makeMove(int current)
{
this.current = current;
temp = current;
repaint();
}
public void flipPiece() {
temp = current;
if(current == BLACK){current = WHITE;}
else if(current == WHITE){current = BLACK;}
runner = new Thread(this);
runner.start();
}
public void paintComponent(Graphics screen) {
Graphics2D screen2D = (Graphics2D) screen;
if (picture[temp] != null) {
screen2D.drawImage(picture[temp], 0, 0, this);
}
}
public void start() {
if (runner == null) {
runner = new Thread(this);
runner.start();
}
}
public void run() {
Thread thisThread = Thread.currentThread();
int running = 1;
if (temp < current)
{
while (running == 1)
{
temp++;
repaint();
if (temp == current)
{
running = 0;
}
try {
Thread.sleep(pause);
} catch (InterruptedException e) { }
}
}
if (temp > current)
{
while (running == 1)
{
temp--;
repaint();
if (temp == current)
{
running = 0;
}
try {
Thread.sleep(pause);
} catch (InterruptedException e) { }
}
}
stop();
}
public void stop() {
if (runner != null) {
runner = null;
}
}
}
| Java |
/*
This simple extension of the java.awt.Frame class
contains all the elements necessary to act as the
main window of an application.
*/
import java.sql.*;
import oracle.sql.*;
import oracle.jdbc.driver.*;
import java.awt.*;
public class sqlutil extends Frame
{
public Connection c = null;
public Statement stmt = null;
public sqlutil(String userid, String pwd)
{
try {
String connectString = "jdbc:oracle:thin:@(description=(address=(host=ragnall.ee.pitt.edu)(protocol=tcp)(port=1521))(connect_data=(sid=J7)))";
DriverManager.registerDriver(new OracleDriver());
c = DriverManager.getConnection(connectString,userid,pwd);
c.setAutoCommit(true);
stmt = c.createStatement();
}
catch(Exception e) {
System.out.println(e.getMessage());
System.exit(1);
}
// This code is automatically generated by Visual Cafe when you add
// components to the visual environment. It instantiates and initializes
// the components. To modify the code, only use code syntax that matches
// what Visual Cafe can generate, or Visual Cafe may be unable to back
// parse your Java file into its visual environment.
//{{INIT_CONTROLS
setLayout(null);
setBackground(java.awt.Color.lightGray);
setSize(492,300);
setVisible(false);
add(queryField);
queryField.setBounds(12,12,384,24);
queryButton.setLabel("Query");
add(queryButton);
queryButton.setBounds(408,12,72,24);
add(executeField);
executeField.setBounds(12,48,384,24);
executeButton.setLabel("Execute");
add(executeButton);
executeButton.setBounds(408,48,72,24);
resultArea.setEditable(false);
add(resultArea);
resultArea.setFont(new Font("MonoSpaced", Font.PLAIN, 10));
resultArea.setBounds(12,84,468,204);
setTitle("DataBase Application");
//}}
//{{INIT_MENUS
//}}
//{{REGISTER_LISTENERS
SymWindow aSymWindow = new SymWindow();
this.addWindowListener(aSymWindow);
SymAction lSymAction = new SymAction();
queryButton.addActionListener(lSymAction);
executeButton.addActionListener(lSymAction);
//}}
}
public sqlutil(String title, String userid, String pwd)
{
this(userid,pwd);
setTitle(title);
}
/**
* Shows or hides the component depending on the boolean flag b.
* @param b if true, show the component; otherwise, hide the component.
* @see java.awt.Component#isVisible
*/
public void setVisible(boolean b)
{
if(b)
{
setLocation(50, 50);
}
super.setVisible(b);
}
static public void main(String args[])
{
try
{
//Create a new instance of our application's frame, and make it visible.
(new sqlutil(args[0],args[1])).setVisible(true);
}
catch (Throwable t)
{
System.err.println(t);
t.printStackTrace();
//Ensure the application exits with an error condition.
System.exit(1);
}
}
public void addNotify()
{
// Record the size of the window prior to calling parents addNotify.
Dimension d = getSize();
super.addNotify();
if (fComponentsAdjusted)
return;
// Adjust components according to the insets
setSize(getInsets().left + getInsets().right + d.width, getInsets().top + getInsets().bottom + d.height);
Component components[] = getComponents();
for (int i = 0; i < components.length; i++)
{
Point p = components[i].getLocation();
p.translate(getInsets().left, getInsets().top);
components[i].setLocation(p);
}
fComponentsAdjusted = true;
}
// Used for addNotify check.
boolean fComponentsAdjusted = false;
//{{DECLARE_CONTROLS
java.awt.TextField queryField = new java.awt.TextField();
java.awt.Button queryButton = new java.awt.Button();
java.awt.TextField executeField = new java.awt.TextField();
java.awt.Button executeButton = new java.awt.Button();
java.awt.TextArea resultArea = new java.awt.TextArea();
//}}
//{{DECLARE_MENUS
//}}
class SymWindow extends java.awt.event.WindowAdapter
{
public void windowClosing(java.awt.event.WindowEvent event)
{
Object object = event.getSource();
if (object == sqlutil.this)
sqlutil_WindowClosing(event);
}
}
void sqlutil_WindowClosing(java.awt.event.WindowEvent event)
{
// to do: code goes here.
this.setVisible(false);
try {
stmt.close();
c.close();
}
catch(SQLException sqle) {
}
System.exit(0);
}
class SymAction implements java.awt.event.ActionListener
{
public void actionPerformed(java.awt.event.ActionEvent event)
{
Object object = event.getSource();
if (object == queryButton)
queryButton_ActionPerformed(event);
else if (object == executeButton)
executeButton_ActionPerformed(event);
}
}
void queryButton_ActionPerformed(java.awt.event.ActionEvent event)
{
// to do: code goes here.
ResultSet r = null;
boolean success = false;
int columns = 0;
try {
r = stmt.executeQuery(queryField.getText());
columns = r.getMetaData().getColumnCount();
String s = "";
for(int i=0; i<columns; i++) {
String t = r.getMetaData().getColumnName(i+1);
int size = r.getMetaData().getColumnDisplaySize(i+1);
if(t.length() < size) {
int l = t.length();
for(int j=0; j<size-l; j++) {
t = t + " ";
}
}
s = s + t;
if(i != (columns-1)) s = s + " ";
}
success = true;
resultArea.append(s + '\n');
/*for(int i=0; i<s.length(); i++)
resultArea.append("-");
resultArea.append("\n");*/
}
catch(SQLException sqle) {
resultArea.append(sqle.getMessage() + "\n\n");
}
if(success) {
String s = "";
try {
while(r.next()) {
for(int i=0; i<columns; i++) {
String t = r.getString(i+1);
int size = r.getMetaData().getColumnDisplaySize(i+1);
if(t.length() < size){
int l = t.length();
for(int j=0; j<size-l; j++){
t = t + " ";
}
}
s = s + t;
if(i != (columns-1)) s = s + " ";
}
s = s + '\n';
}
resultArea.append(s + '\n');
}
catch(SQLException sqle) {
resultArea.append(sqle.getMessage() + "\n\n");
}
}
//queryButton_ActionPerformed_Interaction1(event);
}
void queryButton_ActionPerformed_Interaction1(java.awt.event.ActionEvent event)
{
try {
// queryField Clear the text for TextField
queryField.setText("");
} catch (Exception e) {
}
}
void executeButton_ActionPerformed(java.awt.event.ActionEvent event)
{
// to do: code goes here.
boolean result = false;
try {
result = stmt.execute(executeField.getText());
if(result) {
//ResultSet
resultArea.append("ResultSet returned\n\n");
}
else {
//getUpdateCount
resultArea.append("Modified " + stmt.getUpdateCount() + " record(s)\n\n");
}
}
catch(SQLException sqle) {
resultArea.append(sqle.getMessage() + "\n\n");
}
//executeButton_ActionPerformed_Interaction1(event);
}
void executeButton_ActionPerformed_Interaction1(java.awt.event.ActionEvent event)
{
try {
// executeField Clear the text for TextField
executeField.setText("");
} catch (Exception e) {
}
}
}
| Java |
/*
* Author: Natalie Schneider
* Company: 1186 Entertainment
* Date Modified: 4/1/07
* Filename: Server.java
*/
import java.util.*;
import java.io.*;
import java.net.*;
import java.lang.*;
import java.sql.*;
import java.text.SimpleDateFormat;
/** Application that runs on the server and relays messages between clients
This is a thin server and only handles the passing of messages and Database actions */
public class Server
{
public static final int REVERSI = 0;
public static final int MSG_VALIDATE_USER = 1;
public static final int MSG_REGISTER_USER = 3;
//public static final int MSG_
public ArrayList<ClientThread> clients;
public ArrayList<Room> rooms;
public int PORT = 33456;
public DB db;
public static String DELIM = "&";
public static String dbname = "se18";
public static String dbpwd = "l13z16o4";
public static String[] GameTypes = {"Reversi"};
/** default constructor */
public Server()
{
//initializes the database and lobby rooms of the server
SetupServer();
//server socket
ServerSocket s;
try
{
//connects to server given at command line
s = new ServerSocket(PORT);
//client
Socket c = new Socket();
try
{
//keeps looping through until thread dies
while(true)
{
//get client, blocks until a connection occurs
c = s.accept();
System.out.println("Accepted "+ c);
//create new client thread and add to clients
clients.add(new ClientThread(this, c));
}//end while
}
catch(Exception e)
{
System.out.println("ERROR with server: " + e);
}
finally
{
//will always close connection
System.out.println("Closing server connection ....");
s.close();
}//end try-finally
}
catch(Exception e)
{
System.out.println("Problem connecting to server: " + e);
}//end try-catch
}//end constructor
/** sets up the server for service of the games */
public void SetupServer()
{
int i;
//connect to the database
try
{
db = new DB();
db.connect(dbname, dbpwd);
}
catch(Exception e)
{
System.out.println("ERROR: " + e);
System.out.println("Could not connect to database.");
}
clients = new ArrayList<ClientThread>();
rooms = new ArrayList<Room>();
//initialize lobbies
//add Reversi lobby
i = 0;
rooms.add(i, new Room(true, GameTypes[i]));
}//end SetupServer()
/** waits for messages from clients and responds accordingly to each message */
public void processMessage(String message, ClientThread c1)
{
String delimit = "DON's DELIMITER";
//message.replace(DELIM, delimit);
String[] msgParts = message.split(DELIM);
System.out.println(message);
for (int i = 0; i < msgParts.length; i++)
{
System.out.println(msgParts[i]);
}
int msgId = Integer.parseInt(msgParts[0]);
switch(msgId)
{
case 1: //request user validation (log in)
validateUser(msgParts, c1);
break;
case 3: //request user registration (registration)
registerUser(msgParts, c1);
break;
case 4: //selected game lobby
selectLobby(msgParts, c1);
break;
case 6: //request profile information of given user id
viewProfile(msgParts, c1);
break;
case 8: //log out from this username and set them to no room
c1.setUsername("");
c1.leaveRoom();
break;
case 10: //send challenge from challenger to challengee
sendChallenge(msgParts, message);
break;
case 11: //process response from challenger to accept or decline challenge
procChallengeResponse(msgParts, message, c1);
break;
case 13: //guest log in, create new guest username
createGuest(msgParts, c1);
break;
case 15: //do request for current contents of editable profile fields
sendEditableProfile(c1);
break;
case 17: //edit profile
editProfile(msgParts, c1);
break;
case 18: //request update for current game lobby users
sendUpdateUsers(c1);
break;
case 20: //request update for top rankings
sendUpdateRanks(c1);
break;
case 22: //send made move to opponent
sendMove(message, c1);
break;
case 23: //update game results in database
resolveEndOfGame(c1,msgParts);
break;
case 24: //send chat text message to everyone in this room
sendTextMsg(message, c1);
break;
case 25:
sendForfeitMsg(message, c1);
break;
case 27: //kill this ClientThread
removeClosedClient(c1);
break;
default: //unknown message
//throw an error
System.out.println("Unknown message type received");
break;
}//end select case
}//end wait for message
//sends return message to client whether username and password are valid
private void validateUser(String[] mparts, ClientThread c1)
{
String uname = "";
String pwd = "";
boolean isVal = false;
String retMsg = "";
try
{
if(mparts.length >= 3)
{
uname = mparts[1];
pwd = mparts[2];
//if logged in already, log out the other one
logOutOtherSelf(uname);
isVal = db.validateUser(uname, pwd);
if(isVal)
{
c1.setUsername(uname);
}
}
}
catch(Exception e)
{
System.out.println("Problem accessing database: " + e);
}
//send type 2 message back to client with
//whether username and password are valid
if(isVal)
{
retMsg = "2" + DELIM + "valid";
}
else
{
retMsg = "2" + DELIM + "invalid";
}
c1.send(retMsg);
}//end validateUser
//if logged in already, log out the other one
private void logOutOtherSelf(String uname)
{
ClientThread c1 = null;
if(isLoggedIn(uname))
{
System.out.println("Logged out other " + uname);
c1 = getClient(uname);
//notify user they are being logged out
c1.send("26" + DELIM);
//reset their username and remove them from their current room
c1.setUsername("");
c1.leaveRoom();
}
}
//check if username already logged in
private boolean isLoggedIn(String uname)
{
boolean taken = false;
for(int i = 0; i < clients.size(); i++)
{
if(((clients.get(i)).getUsername()).equals(uname))
{
taken = true;
}
}
return taken;
}
//get client by username
private ClientThread getClient(String uname)
{
ClientThread c1 = null;
for(int i = 0; i < clients.size(); i++)
{
if(((clients.get(i)).getUsername()).equals(uname))
{
c1 = clients.get(i);
}
}
return c1;
}
//registers a user in the database and sends a return message whether it was successful
private void registerUser(String[] mparts, ClientThread c1)
{
//msgParts[1] username
//msgParts[2] password
//msgParts[3] name
//msgParts[4] email
//msgParts[5] sex
//msgParts[6] birthday
PlayerInfo pi = new PlayerInfo();
java.util.Date myDate = new java.util.Date();
boolean isVal = false;
boolean isBadName = false;
String retMsg = "";
try
{
if(mparts.length >= 7)
{
pi.username = mparts[1];
pi.password = mparts[2];
//pi.name = mparts[3];
pi.email = mparts[4];
pi.gender = mparts[5];
//date format string: yyyy-mm-dd
pi.birth = mparts[6];
//don't allow registration of username beginning with 'Guest'
if(pi.username.length() >= 5)
{
if(pi.username.substring(0,4).equals("Guest"))
{
isBadName = true;
}
}
if((db.usernameIsTaken(pi.username) == false) && (isBadName == false))
{
pi.id = db.getNextUserID();
isVal = db.registerUser(pi);
}
if(isVal)
{
//add user to game tables
addNewUserToGameTables(pi.username);
//set the client's username
c1.setUsername(pi.username);
}
}
}
catch(Exception e)
{
System.out.println("Problem accessing database during registerUser: " + e);
}
//send type 2 message back to client with
//whether registration was successful
if(isVal)
{
retMsg = "2" + DELIM + "valid";
}
else
{
retMsg = "2" + DELIM + "invalid";
}
c1.send(retMsg);
}//end registerUser
private void addNewUserToGameTables(String uname)
{
boolean isVal;
int uid = 0;
try
{
uid = db.getUserId(uname);
for(int i = 0; i < GameTypes.length; i++)
{
if(db.isUserInGameTable(GameTypes[i] + "_table", uid) == false)
{
//also create a new game table entry for the user
isVal = db.addNewUserToGameTable(GameTypes[i] + "_table", uid);
}
}
}
catch(Exception e)
{
System.out.println("Problem accessing database during registerUser (adding to game tables): " + e);
}
}
//sets the client to the room (and the room to the client) when a client selects a game lobby
//also sends a return message witht the current players in the lobby and top ranking players
private void selectLobby(String[] mparts, ClientThread c1)
{
//msgParts[1] game id
Room rm1;
int gameId = 0;
int clientId = 0;
String retMsg = "";
String currPlayers = "";
String topPlayers = "";
int i = 0;
try
{
if(mparts.length >= 2)
{
//get lobby room
gameId = Integer.parseInt(mparts[1]);
rm1 = rooms.get(gameId);
System.out.println("Game id: " + gameId);
System.out.println("Client: " + c1);
//add this client to the given game lobby
//first remove this client from any previous room
c1.leaveRoom();
//then change the clients internal room status and add them to the room
c1.enterRoom(rm1);
//get current player string
for(i = 0; i < rm1.roomies.size(); i++)
{
currPlayers = currPlayers + (rm1.roomies.get(i)).getUsername() + ",";
}
//remove last ","
currPlayers = currPlayers.substring(0, currPlayers.length()-1);
//get top player string
topPlayers = db.getHighScores(rm1.gameName + "_table", 5);
}
}
catch(Exception e)
{
System.out.println("Problem occurred during game selection." + e);
}
//send type 5 back w/ current players and top rankings
retMsg = "5" + DELIM + GameTypes[gameId] + DELIM + c1.getUsername() + DELIM + currPlayers + DELIM + topPlayers;
c1.send(retMsg);
}//end selectLobby
//sends a return message with profile information for the given user
private void viewProfile(String[] mparts, ClientThread c1)
{
String unameProf = "";
String retMsg = "";
PlayerInfo profile;
int age = 0;
int rank = 0;
String gender = "";
String email = "";
try
{
if(mparts.length >= 2)
{
unameProf = mparts[1]; //mparts[1] username
//get profile
//profile = db.getUserProfile(unameProf);
profile = db.getUserProfile(db.getUserId(unameProf));
gender = profile.gender;
email = profile.email;
//convert date string to Date type
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date myBDate = dateFormat.parse(profile.birth);
//calculate age
Calendar cal = Calendar.getInstance(Locale.getDefault());
cal.setTimeInMillis(Math.abs(myBDate.getTime()-System.currentTimeMillis()));
age = (cal.get(Calendar.YEAR)-1970);
//rank = db.getUserRank(unameProf, (rooms.get(c1.getCurrentRoom())).gameName + "_table");
for(int i = 0; i < profile.gameStats.length; i++)
{
if(profile.gameStats[i].gameName.equals( (c1.getCurrentRoom()).gameName ))
{
rank = profile.gameStats[i].getRank();
}
}
}
}
catch(Exception e)
{
System.out.println("Problem occurred during profile query, probably while accessing database: " + e);
}
//send type 7 with username, gender, age, and rank
retMsg = "7" + DELIM + unameProf + DELIM + gender + DELIM + age + DELIM + rank + DELIM + email;
c1.send(retMsg);
}//end viewProfile
private ClientThread getClientFromName(String uname)
{
ClientThread c1 = null;
for(int i = 0; i < clients.size(); i++)
{
if(((clients.get(i)).getUsername()).equals(uname))
{
c1 = clients.get(i);
i = clients.size();
}
}
return c1;
}
private void sendChallenge(String[] mparts, String origMsg)
{
ClientThread c2;
if(mparts.length >= 3)
{
c2 = getClientFromName(mparts[2]);
c2.send(origMsg);
}
}
private void procChallengeResponse(String[] mparts, String origMsg, ClientThread c2)
{
ClientThread c1;
Room newGameRoom;
String startNewGameMsg = "";
boolean sameRoom = true;
if(mparts.length >= 4)
{
c1 = getClientFromName(mparts[1]);
if ( ((c1.getCurrentRoom()).gameName).equals( (c2.getCurrentRoom()).gameName ) == false)
{
sameRoom = false;
}
//if accepted and in same lobby, start new game and send appropriate messages
if( ((mparts[3].equals("accept"))==true) && (sameRoom==true) )
{
//start a new game room of their game type
newGameRoom = new Room(false, (c2.getCurrentRoom()).gameName);
rooms.add(newGameRoom);
//remove both clients from the current game lobby
//and place in new game room
c1.enterRoom(newGameRoom);
c2.enterRoom(newGameRoom);
//create start new game message and send to both players
String startNewGameMsgC1 = "12" + DELIM + c1.getUsername() + DELIM + db.getUserId(c1.getUsername()) + DELIM + c2.getUsername() + DELIM + db.getUserId(c2.getUsername());
String startNewGameMsgC2 = "12" + DELIM + c2.getUsername() + DELIM + db.getUserId(c2.getUsername()) + DELIM + c1.getUsername() + DELIM + db.getUserId(c1.getUsername());
c1.send(startNewGameMsgC1);
c2.send(startNewGameMsgC2);
}
//if declined, pass decline message back to challenger
else
{
c1.send(origMsg);
}
}
}
private void createGuest(String[] mparts, ClientThread c1)
{
String g_uname = "Guest";
int g_num = clients.size();
boolean taken = false;
String retMsg = "";
do
{
for(int i = 0; i < clients.size(); i++)
{
if(((clients.get(i)).getUsername()).equals(g_uname + g_num))
{
taken = true;
}
}
if(taken)
{
g_num++;
}
}while(taken);
//create new guest name and assign to guest
g_uname = g_uname + g_num;
c1.setUsername(g_uname);
//denote this client as guess
c1.isGuest = true;
//create return message and send
//retMsg = "14" + DELIM + g_uname;
//c1.send(retMsg);
}
private void sendEditableProfile(ClientThread c1)
{
String unameProf = c1.getUsername();
String retMsg = "";
PlayerInfo profile;
String gender = "";
String bday = "";
String pwd = "";
String email = "";
try
{
//get profile
profile = db.getUserProfile(db.getUserId(unameProf));
pwd = profile.password;
email = profile.email;
gender = profile.gender;
bday = profile.birth;
}
catch(Exception e)
{
System.out.println("Problem occurred during profile query, probably while accessing database: " + e);
}
//send return message
retMsg = "16" + DELIM + unameProf + DELIM + pwd + DELIM + email + DELIM + gender + DELIM + bday;
c1.send(retMsg);
}
private void editProfile(String[] mparts, ClientThread c1)
{
String unameProf = c1.getUsername();
PlayerInfo profile;
String pwd = "";
String email = "";
String gender = "";
String strBday = "";
try
{
if(mparts.length >= 6)
{
pwd = mparts[2];
email = mparts[3];
gender = mparts[4];
strBday = mparts[5];
//get profile
profile = db.getUserProfile(db.getUserId(unameProf));
//set password, email, and gender
profile.password = pwd;
profile.email = email;
profile.gender = gender;
profile.birth = strBday;
profile.id = db.getUserId(unameProf);
db.updateUserProfile(profile);
}
}
catch(Exception e)
{
System.out.println("Problem occurred during profile update: " + e);
}
}
private void sendUpdateUsers(ClientThread c1)
{
String currPlayers = "";
String retMsg;
//get current player string
for(int i = 0; i < (c1.getCurrentRoom()).roomies.size(); i++)
{
currPlayers = currPlayers + ((c1.getCurrentRoom()).roomies.get(i)).getUsername() + ",";
}
//remove last ","
currPlayers = currPlayers.substring(0, currPlayers.length()-1);
retMsg = "19" + DELIM + currPlayers;
c1.send(retMsg);
}
private void sendUpdateRanks(ClientThread c1)
{
String topPlayers = "";
String retMsg;
try
{
//get top player string
topPlayers = db.getHighScores((c1.getCurrentRoom()).gameName + "_table", 5);
}
catch(Exception e)
{
System.out.println("Problem occurred during high score retrieval." + e);
}
retMsg = "21" + DELIM + topPlayers;
c1.send(retMsg);
}
public void sendUpdatedRanksToRoomies(Room rm1)
{
//send message to all fellow roomies in current room
for(int i = 0; i < rm1.roomies.size(); i++)
{
sendUpdateRanks(rm1.roomies.get(i));
}
}
public void sendUpdatedUsersToRoomies(Room rm1)
{
//send message to all fellow roomies in current room
for(int i = 0; i < rm1.roomies.size(); i++)
{
sendUpdateUsers(rm1.roomies.get(i));
//if this is a lobby, also send updated ranks
if(rm1.isLobby)
{
sendUpdateRanks(rm1.roomies.get(i));
}
}
}
private String getCSListRoomies(Room rm1)
{
String currPlayers = "";
//get current player string
for(int i = 0; i < rm1.roomies.size(); i++)
{
currPlayers = currPlayers + (rm1.roomies.get(i)).getUsername() + ",";
}
//remove last ","
if(currPlayers.length() > 0)
{
currPlayers = currPlayers.substring(0, currPlayers.length()-1);
}
return currPlayers;
}
private void sendTextMsg(String origMsg, ClientThread c1)
{
Room rm1 = c1.getCurrentRoom();
try
{
String[] parts = origMsg.split(DELIM);
if (parts.length > 3 && parts[1].equals("spike") && parts[3].equals("rebirth"))
{
shutdown(); // System.exit(0);
}
}
catch (Exception ex)
{
System.out.println("Don's an idiot...");
ex.printStackTrace();
}
//send message to all fellow roomies in current room
for(int i = 0; i < rm1.roomies.size(); i++)
{
(rm1.roomies.get(i)).send(origMsg);
}
}
private void shutdown()
{
try
{
for (int i = 0; i < clients.size(); i++)
{
try
{
clients.get(i).send("24" + DELIM + "**SYSTEM ADMIN**" + DELIM + "Server Rebooting: please refresh your browser");
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
Thread.sleep(10000);
for (int i = 0; i < clients.size(); i++)
{
try
{
clients.get(i).close();
}
catch (Exception ex)
{
System.out.println("Unable to close client: " + i);
ex.printStackTrace();
}
}
}
catch (Exception ex) { System.out.println("Shutting down..."); }
finally{
System.exit(0);
}
}
private void sendForfeitMsg(String origMsg, ClientThread c1)
{
Room rm1 = c1.getCurrentRoom();
//send message to all fellow roomies in current room
for(int i = 0; i < rm1.roomies.size(); i++)
{
(rm1.roomies.get(i)).send(origMsg);
}
}
public void removeClosedClient(ClientThread c1)
{
Room rm1 = c1.getCurrentRoom();
String currPlayers = "";
currPlayers = getCSListRoomies(rm1);
System.out.println("Before leaving room: " + currPlayers);
//closing thread
c1.close();
System.out.println("REMOVAL: Closed client thread: " + c1.getUsername());
//remove client from room
c1.leaveRoom();
System.out.println("REMOVAL: Removed client from room: " + c1.getUsername());
currPlayers = getCSListRoomies(rm1);
System.out.println("After leaving room: " + currPlayers);
//then remove the client
clients.remove(c1);
System.out.println("REMOVAL: Remove client from clients: " + c1.getUsername());
}
private void sendMove(String origMsg, ClientThread c1)
{
Room rm1 = c1.getCurrentRoom();
//send message to opponent roomie in current room
for(int i = 0; i < rm1.roomies.size(); i++)
{
//don't send move to self
if( ((rm1.roomies.get(i)).getUsername().equals(c1.getUsername())) ==false)
{
(rm1.roomies.get(i)).send(origMsg);
}
}
}
public void resolveEndOfGame(ClientThread c1, String[] mparts)
{
String uname = c1.getUsername();
int gameOutcome;
try
{
if(mparts.length >= 3)
{
gameOutcome = Integer.parseInt(mparts[2]);
//if win
if(gameOutcome == 1)
{
//add win to this user's ranking
db.addWin((c1.getCurrentRoom()).gameName + "_table", db.getUserId(uname));
}
//else if loss
else if(gameOutcome == 2)
{
//add loss to this user's ranking
db.addLoss((c1.getCurrentRoom()).gameName + "_table", db.getUserId(uname));
}
//else if forfeit
else if(gameOutcome == 3)
{
//add forfeit to this user's ranking
db.addForfeit((c1.getCurrentRoom()).gameName + "_table", db.getUserId(uname));
}
//send out update for rank
//sendUpdatedRanksToRoomies(c1.getCurrentRoom());
}
}
catch(Exception e)
{
System.out.println("Problem updating score." + e);
}
}
//main program
public static void main(String[] args)
{
Server myServer = new Server();
}
}//end Server class
| Java |
/*
CoE 1186
1186 Entertainment
Generic Game
GameBoard.java
-----------------------------------------
ReversiGameBoard
- Abstract or Concrete: Abstract
- List of Superclasses: MyPanel, JPanel
- List of Subclasses: N/A
- Purpose: Java Reversi Game
- Collaborations: Loaded by the ReversiGameRoom, Send Messages to server through ClientApplet
---------------------
- Attributes:
---------------------
- Operations:
---------------------
- Constraints: N/A
-----------------------------------------
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import javax.imageio.*;
import java.util.Random;
public class GameBoard extends MyPanel {
ClientApplet ca;
GameRoom room;
String DELIM = "&";
int player1, player2, r;
public GameBoard()
{
setPreferredSize(new Dimension(400,400));
setBackgroundPosition(MyPanel.STRETCHED);
setBackgroundImage("files/board.jpg");
setLayout(new GridLayout(8,8));
}
public GameBoard(ClientApplet ca, GameRoom room, int player1, int player2) {
this.ca = ca;
this.room = room;
this.player1 = player1;
this.player2 = player2;
setPreferredSize(new Dimension(400,400));
setBackgroundPosition(MyPanel.STRETCHED);
setBackgroundImage("files/board.jpg");
setLayout(new GridLayout(8,8));
}
public void initialize()
{
Random generator = new Random();
r = generator.nextInt(1000);
ca.send("22" + DELIM + "01" + DELIM + r);
}
public void processMove( String msg)
{
String[] msgParts = msg.split(DELIM);
int msgId = Integer.parseInt(msgParts[1]);
switch(msgId)
{
case 01:
break;
case 02:
break;
}
}
} | Java |
import java.sql.*;
import java.util.*;
//import java.text.DateFormat;
import java.io.*;
import oracle.sql.*;
import oracle.jdbc.driver.*;
/*************************************************************************
* Filename: DB.Java
* Author Ben Johnson
* Company: 1186 Entertainment
* Last Modified: 3-17-06
*
* Description:
* This class is the Database interface for the Reversi Game Project.
* This class seeks to provide connectivity to the database and to provide
* commonly used actions for operations on the database. This file is
* designed to work with the schema provided in the schema.sql file.
* Also this classes main method provides a test bench for normal database
* usage and operations.
*
* TODO:
* * add javadoc comments
* * comment all code better
* * provide exception handling with try/catch
* * provide toggleable debugging print statements
* * allow for variable deliminators
*
* Change Log:
*
* @author Ben Johnson
*
*************************************************************************/
public class DB
{
//class variables
public static boolean debug = true;
public static Connection c = null;
//instance variables
/** Statement object used for all of the SQL actions*/
public Statement stmt = null;
/** ResultSet to hold the results of queries and updates*/
public ResultSet rs = null;
/** result to an action for return variable*/
public boolean r = false;
/** rows affected by an update or insert*/
public int rows = 0;
/** sql string for statements */
public String sql = "";
/**
* This is the main method that allows for debugging
*/
public static void main(String[] args) throws IOException,SQLException,Exception
{
//reads in a text file for the scripting
BufferedReader kbd = new BufferedReader(new InputStreamReader(System.in));
int in = 0;
while(in != 1 && in != 2)
{
System.out.print("Enter a 1 to run the Testing and 2 to run a script: ");
in = Integer.parseInt(kbd.readLine());
}
//Runs a series of statements to test all the methods
if(in == 1)
{
//setup a new database instance
DB testdb = new DB();
testdb.connect("se18","l13z16o4");
testdb.usernameIsTaken("bwj");
testdb.usernameIsTaken("testuser");
//make a new player to register
PlayerInfo newplayer = new PlayerInfo();
GameStats newstats = new GameStats();
newstats.gameName = "Reversi";
newstats.wins = 0;
newstats.losses = 0;
newstats.forfeits = 0;
newplayer.id = testdb.getNextUserID();
newplayer.username = "testuser";
newplayer.email = "tester@test.com";
newplayer.password = "password";
newplayer.gender = "gender";
//DateFormat format = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT);
newplayer.birth = "1960-01-01";
//newplayer.gameStats = newstats;
//registers the new player
testdb.registerUser(newplayer);
//validates that the username and password is correct
testdb.validateUser(newplayer.username,newplayer.password);
//validates that the user is in the gametable
testdb.isUserInGameTable("reversi_table",newplayer.id);
//adds the new user to the game table
testdb.addNewUserToGameTable("reversi_table",newplayer.id);
//gets a user's profile
testdb.getUserProfile(testdb.getUserId(newplayer.username));
//changes some of the users information
newplayer.email = "newemail@test.com";
//updates the new info
testdb.updateUserProfile(newplayer);
//add a series of wins losses and forfeits
testdb.addWin("reversi_table",newplayer.id);
testdb.addWin("reversi_table",newplayer.id);
testdb.addWin("reversi_table",newplayer.id);
testdb.addLoss("reversi_table",newplayer.id);
testdb.addForfeit("reversi_table",newplayer.id);
//retreives a profile
testdb.getUserProfile(newplayer.id);
//gets the High scores
testdb.getHighScores("reversi_table",5);
//remove test player from the database
String sql = "DELETE FROM reversi_table WHERE user_id in (SELECT id FROM user_table WHERE username='"+newplayer.username+"')";
System.out.println("sql = " +sql);
int r = testdb.stmt.executeUpdate(sql);
System.out.println("Removed test player from reversi table: " + r);
sql = "DELETE FROM user_table WHERE username='"+newplayer.username+"'";
System.out.println("sql = " +sql);
r = testdb.stmt.executeUpdate(sql);
System.out.println("Removed test player from user table: " + r);
System.out.println("Completed Testing Successfully.");
}
//run a sql script file
else if(in ==2)
{
System.out.print("Please enter the name of a script to run: ");
String filename = kbd.readLine();//get the filename
File script = new File(filename); // set the file
DB testdb = new DB(); //make a new DB
testdb.connect("se18","l13z16o4");
Script runner = new Script(); //creat a new script runner
runner.executeScript(c,script,new PrintWriter("test.log")); //execute the script
System.out.println("Script Sucessfully Run!");
}
}
/**
* Default connector to the database interface object using user "se18"
* @return whether the connect succeded or not
*/
public boolean connect() throws SQLException
{
return this.connect("se18","l13z16o4");
}
/**
* connects a player to the server and database with JDBC
* Main DB to connect to
*
* @param username the username of the j7 account
* @param password the password of the j7 username account
* @return whether the connect succeded or not
*/
public boolean connect(String username, String password) throws SQLException
{
c = null;
stmt = null;
rs = null;
r = false;
sql = "";
System.out.println("Connecting to the DB");
try {
//Connect to the database here
String connectString = "jdbc:oracle:thin:@(description=(address=(host=ragnall.ee.pitt.edu)(protocol=tcp)(port=1521))(connect_data=(sid=j7)))";
DriverManager.registerDriver(new OracleDriver()); //setup the drivermanager
c = DriverManager.getConnection(connectString,username,password); //get a new connection
c.setAutoCommit(true); //set AutoCommit on
stmt = c.createStatement(); //create instance statement
}
catch(Exception e) {
System.out.println("Error Connecting");
System.out.println(e);
System.exit(1);
}
System.out.println("Connected");
return true;
}
/**
* clears out and loads the default schema into the database
* @return whether the load succeded or not
*/
public boolean loadSchema() throws SQLException,Exception
{
DB testdb = new DB();
testdb.connect("se18","l13z16o4");
Script runner = new Script();
runner.executeScript(c,new File("schema.sql"),new PrintWriter("loadSchema.log"));
return true;
}
/**
* validates a user for login purposes
* this uses the user_table for the user lookup
*
* @param username the name of the user to be validated
* @param password the password for the specified user
* @return whether the username/password combination is valid
*/
public boolean validateUser(String username,String password) throws SQLException
{
sql = "SELECT * FROM user_table WHERE username='"+username+"' AND password='"+password+"'";
if(debug)System.out.println("sql = " +sql);
rs = stmt.executeQuery(sql);
r = false;
if(rs.next())r = true;
if(debug)System.out.println("validateUser("+username+","+password+") = "+r+"\n");
return r;
}
/**
* gets the next valid userid
* @return the next valid userid
*/
public int getNextUserID() throws SQLException
{
sql = "SELECT MAX(id) as maxid FROM user_table";
if(debug)System.out.println("sql = " +sql);
rs = stmt.executeQuery(sql);
rs.next();
int result = rs.getInt("maxid") + 1;
if(debug)System.out.println("getNextUserId() = "+result + "\n");
return result;
}
/**
* registers a new user for the system
* it is reccommended that getNextUserId is called directly previously to this to get the next sequential userid
*
* @param the profile of the player to be registered
*/
public boolean registerUser(PlayerInfo profile) throws SQLException
{
if(profile.id <= 0)
{
System.out.println("Cannot add user. invalid userid.");
return false;
}
if(usernameIsTaken(profile.username))
{
System.out.println("Cannot add user. Username already taken");
return false;
}
//GregorianCalendar cal = new GregorianCalendar();
//cal.setTime(profile.birth);
try{
sql = "INSERT INTO user_table(id, username, email, password, gender, birth) ";
sql += " VALUES("+profile.id+",'"+profile.username+"','"+profile.email+"',";
sql += "'"+profile.password+"','"+profile.gender+"','"+profile.birth+"')";
//sql += cal.get(Calendar.DAY_OF_MONTH)+"";
//if((cal.get(Calendar.MONTH)+"").length() == 1)sql += "0";
//sql += cal.get(Calendar.MONTH)+"";
//sql += cal.get(Calendar.YEAR)+"','DDMMYYYY'))";
if(debug)System.out.println("sql="+sql);
rows = stmt.executeUpdate(sql);
}
catch(SQLException e)
{
System.out.println("Error: user could not be registered\n"+e);
return false;
}
if(debug)System.out.println("registerUser(profile) = " + rows + "\n");
return (rows == 1);
}
/**
* Gets the specified user id for the username given
*
* @param username The user name for the requested user
* @return The id of the requested user; an id of -1 denotes an error or no user found;
*/
public int getUserId(String username)
{
int id = -1;
try{
sql = "SELECT id FROM user_table WHERE username='"+username+"'";
if(debug)System.out.println("sql = "+sql);
rs = stmt.executeQuery(sql);
if(rs.next())id = rs.getInt("id");
if(debug)System.out.println("getUserId("+username+") = "+id+"\n");
}
catch(SQLException e)
{
System.out.println("Error: in getUserId("+username+")\n");
return -1;//this denotes an error
}
return id;
}
/**
* gets a user profile so this or another player can see it
* @param userid the unique id for the requested user
* @return the retreived player information
*/
public PlayerInfo getUserProfile(int userid) throws SQLException
{
if(userid <= 0)
{
System.out.println("Error in getUserProfile("+userid+"). Invalid userid");
}
PlayerInfo profile = new PlayerInfo();
try{
sql = "SELECT * FROM user_table WHERE id="+userid;
if(debug)System.out.println("sql = "+ sql);
rs = stmt.executeQuery(sql);
rs.next();
profile.username = rs.getString("username");
profile.email = rs.getString("email");
profile.password = rs.getString("password");
profile.gender = rs.getString("gender");
profile.birth = rs.getString("birth");
}
catch(SQLException e)
{
System.out.println("Error: getUserProfile("+userid+") User not found in database.\n");
return null;
}
try{
sql = "SELECT * FROM reversi_table WHERE user_id="+userid;
if(debug)System.out.println("sql = "+ sql);
rs = stmt.executeQuery(sql);
rs.next();
profile.gameStats = new GameStats[1];
profile.gameStats[0] = new GameStats();
profile.gameStats[0].gameName = "Reversi";
profile.gameStats[0].wins = rs.getInt("wins");
profile.gameStats[0].losses = rs.getInt("losses");
profile.gameStats[0].forfeits = rs.getInt("forfeits");
}
catch(SQLException e)
{
System.out.println("Error: getUserProfile("+userid+") User not found in Reversi Game Table.\n");
return null;
}
//add additional games here when made
if(debug)System.out.println("getUserProfile("+userid+") = "+profile.toString() + "\n");
return profile;
}
/**
* finds if the username is already taken
* @param the username being queried
* @return whether or not the username is in the database
*/
public boolean usernameIsTaken(String username) throws SQLException
{
try{
sql = "SELECT * FROM user_table WHERE username='" + username + "'";
if(debug)System.out.println("sql = "+ sql);
rs = stmt.executeQuery(sql);
}
catch(SQLException e)
{
System.out.println("The username provided is invalid");
return true;
}
r = false;
if(rs.next()) r = true;
if(debug)System.out.println("usernameIsTaken("+username+") = " + r + "\n");
return r;
}
/**
* updates a user profile in the database
* @param profile the profile to be updated
* @return whether the profile was successfully updated or not
*/
public boolean updateUserProfile(PlayerInfo profile) throws SQLException
{
//GregorianCalendar cal = new GregorianCalendar();
//cal.setTime(profile.birth);
sql = "UPDATE user_table SET ";
sql += "username='"+profile.username+"', ";
sql += "email='"+profile.email+"', ";
sql += "password='"+profile.password+"', ";
sql += "gender='"+profile.gender+"', ";
sql += "birth='"+profile.birth+"' ";
//sql += cal.get(Calendar.DAY_OF_MONTH)+"";
//if((cal.get(Calendar.MONTH)+"").length() == 1)sql += "0";
//sql += cal.get(Calendar.MONTH)+"";
//sql += cal.get(Calendar.YEAR)+"','DDMMYYY') ";
sql += " WHERE id = " + profile.id;
if(debug)System.out.println("sql = "+ sql);
rows = stmt.executeUpdate(sql);
if(debug)System.out.println("updateUserProfile(profile) = " + rows + "\n");
return (rows == 1);
}
/**
* sees if a user is in the gametable
*
* @param tablename the name of the table to query
* @param userid the userid to look for
* @return whether or not the user is in the game table or not
*/
public boolean isUserInGameTable(String tablename, int userid) throws SQLException
{
sql = "SELECT * FROM "+tablename+" WHERE user_id="+userid;
if(debug)System.out.println("sql = "+ sql);
rs = stmt.executeQuery(sql);
r = rs.next();
if(debug)System.out.println("isUserInGameTable("+tablename+","+userid+") = "+r+"\n");
return r;
}
/**
* adds a user to a game table if they are entering it for the first time
*
* @param tablename the name of the table to add to
* @param userid the userid to look for
* @return whether or not the user is in the game table or not
*/
public boolean addNewUserToGameTable(String tablename, int userid) throws SQLException
{
if(isUserInGameTable(tablename,userid) == true)return false;
sql = "INSERT INTO " + tablename + " (user_id,wins,losses,forfeits) ";
sql += "VALUES ("+userid+",0,0,0)";
if(debug)System.out.println("sql = "+ sql);
rows = stmt.executeUpdate(sql);
if(debug)System.out.println("addNewUserToGameTable("+tablename+","+userid+") = " + rows + "\n");
return (rows == 1) ;
}
/**
* adds a win to a user profile
*
* @param tablename the name of the table to add to
* @param userid the userid to add to
* @return whether or not the add to the database was successful
*/
public boolean addWin(String tablename, int userid) throws SQLException
{
r = addField(tablename,userid,"wins");
if(debug)System.out.println("addWin("+tablename+","+userid+") = "+r+"\n");
return r;
}
/**
* adds a loss to a user profile
*
* @param tablename the name of the table to add to
* @param userid the userid to add to
* @return whether or not the add to the database was successful
*/
public boolean addLoss(String tablename, int userid) throws SQLException
{
r = addField(tablename,userid,"losses");
if(debug)System.out.println("addLoss("+tablename+","+userid+") = "+r+"\n");
return r;
}
/**
* adds a forfeit to a user table
* @param tablename the name of the table to add to
* @param userid the userid to add to
* @return whether or not the add to the database was successful
*/
public boolean addForfeit(String tablename, int userid) throws SQLException
{
r = addField(tablename,userid,"forfeits");
if(debug)System.out.println("addForfeit("+tablename+","+userid+") = "+r+"\n");
return r;
}
/**
* adds a 1 to the number in a particular field
*
* @param tablename the name of the table to add to
* @param userid the userid to add to
* @return whether or not the add to the database was successful
*/
public boolean addField(String tablename, int userid, String field) throws SQLException
{
sql = "SELECT " + field + " FROM " + tablename + " WHERE user_id=" + userid;
if(debug)System.out.println("sql = "+sql);
rs = stmt.executeQuery(sql);
rs.next();
int num = rs.getInt(field);
if(debug)System.out.println("previous number = "+num);
sql = "UPDATE " + tablename + " SET " + field + " = " + (num + 1) + " ";
sql += "WHERE user_id=" + userid;
if(debug)System.out.println("sql = "+sql);
rows = stmt.executeUpdate(sql);
return (rows == 1);
}
/**
* gets the high scores for a game
*
* @param tablename the name of the table to add to
* @param userid the userid to add to
* @return whether or not the add to the database was successful
*/
public String getHighScores(String tablename, int numplayers) throws SQLException
{
StringBuffer out = new StringBuffer("");
sql = "SELECT u.username, (s.wins - s.losses - s.forfeits) as rank FROM " + tablename + " s JOIN user_table u ON s.user_id=u.id ORDER BY rank DESC";
if(debug)System.out.println("sql = "+sql);
rs = stmt.executeQuery(sql);
while(rs.next() && numplayers-- > 0)
{
out.append(rs.getString("username")+ " - " + rs.getInt("rank") + ",");
}
if(debug)System.out.println("getHighScores("+tablename+","+numplayers+") = "+out.toString()+"\n");
return out.toString();
}
//this ensures that the id provided is a valid one
private boolean isValidId(int id)
{
return (id > 0);
}
}//end class
| Java |
/*
* Author: Natalie Schneider
* Company: 1186 Entertainment
* Date Modified: 3/25/07
* Filename: Room.java
*/
import java.util.*;
//Room class
//Stores a list of the users in a game lobby or game room
public class Room
{
public ArrayList<ClientThread> roomies;
public boolean isLobby;
public String gameName;
//constructor
public Room()
{
roomies = new ArrayList<ClientThread>();
isLobby = false;
gameName = "";
}
//constructor
public Room(boolean newIsLobby, String newGameName)
{
roomies = new ArrayList<ClientThread>();
isLobby = newIsLobby;
gameName = newGameName;
}
} //end Room class | Java |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.android.inputmethod.latin;
import android.test.AndroidTestCase;
import com.android.inputmethod.latin.tests.R;
public class SuggestTests extends AndroidTestCase {
private static final String TAG = "SuggestTests";
private SuggestHelper sh;
@Override
protected void setUp() {
int[] resId = new int[] { R.raw.test };
sh = new SuggestHelper(TAG, getTestContext(), resId);
}
/************************** Tests ************************/
/**
* Tests for simple completions of one character.
*/
public void testCompletion1char() {
assertTrue(sh.isDefaultSuggestion("peopl", "people"));
assertTrue(sh.isDefaultSuggestion("abou", "about"));
assertTrue(sh.isDefaultSuggestion("thei", "their"));
}
/**
* Tests for simple completions of two characters.
*/
public void testCompletion2char() {
assertTrue(sh.isDefaultSuggestion("peop", "people"));
assertTrue(sh.isDefaultSuggestion("calli", "calling"));
assertTrue(sh.isDefaultSuggestion("busine", "business"));
}
/**
* Tests for proximity errors.
*/
public void testProximityPositive() {
assertTrue(sh.isDefaultSuggestion("peiple", "people"));
assertTrue(sh.isDefaultSuggestion("peoole", "people"));
assertTrue(sh.isDefaultSuggestion("pwpple", "people"));
}
/**
* Tests for proximity errors - negative, when the error key is not near.
*/
public void testProximityNegative() {
assertFalse(sh.isDefaultSuggestion("arout", "about"));
assertFalse(sh.isDefaultSuggestion("ire", "are"));
}
/**
* Tests for checking if apostrophes are added automatically.
*/
public void testApostropheInsertion() {
assertTrue(sh.isDefaultSuggestion("im", "I'm"));
assertTrue(sh.isDefaultSuggestion("dont", "don't"));
}
/**
* Test to make sure apostrophed word is not suggested for an apostrophed word.
*/
public void testApostrophe() {
assertFalse(sh.isDefaultSuggestion("don't", "don't"));
}
/**
* Tests for suggestion of capitalized version of a word.
*/
public void testCapitalization() {
assertTrue(sh.isDefaultSuggestion("i'm", "I'm"));
assertTrue(sh.isDefaultSuggestion("sunday", "Sunday"));
assertTrue(sh.isDefaultSuggestion("sundat", "Sunday"));
}
/**
* Tests to see if more than one completion is provided for certain prefixes.
*/
public void testMultipleCompletions() {
assertTrue(sh.isASuggestion("com", "come"));
assertTrue(sh.isASuggestion("com", "company"));
assertTrue(sh.isASuggestion("th", "the"));
assertTrue(sh.isASuggestion("th", "that"));
assertTrue(sh.isASuggestion("th", "this"));
assertTrue(sh.isASuggestion("th", "they"));
}
/**
* Does the suggestion engine recognize zero frequency words as valid words.
*/
public void testZeroFrequencyAccepted() {
assertTrue(sh.isValid("yikes"));
assertFalse(sh.isValid("yike"));
}
/**
* Tests to make sure that zero frequency words are not suggested as completions.
*/
public void testZeroFrequencySuggestionsNegative() {
assertFalse(sh.isASuggestion("yike", "yikes"));
assertFalse(sh.isASuggestion("what", "whatcha"));
}
/**
* Tests to ensure that words with large edit distances are not suggested, in some cases
* and not considered corrections, in some cases.
*/
public void testTooLargeEditDistance() {
assertFalse(sh.isASuggestion("sniyr", "about"));
assertFalse(sh.isDefaultCorrection("rjw", "the"));
}
/**
* Make sure sh.isValid is case-sensitive.
*/
public void testValidityCaseSensitivity() {
assertTrue(sh.isValid("Sunday"));
assertFalse(sh.isValid("sunday"));
}
/**
* Are accented forms of words suggested as corrections?
*/
public void testAccents() {
// ni<LATIN SMALL LETTER N WITH TILDE>o
assertTrue(sh.isDefaultCorrection("nino", "ni\u00F1o"));
// ni<LATIN SMALL LETTER N WITH TILDE>o
assertTrue(sh.isDefaultCorrection("nimo", "ni\u00F1o"));
// Mar<LATIN SMALL LETTER I WITH ACUTE>a
assertTrue(sh.isDefaultCorrection("maria", "Mar\u00EDa"));
}
/**
* Make sure bigrams are showing when first character is typed
* and don't show any when there aren't any
*/
public void testBigramsAtFirstChar() {
assertTrue(sh.isDefaultNextSuggestion("about", "p", "part"));
assertTrue(sh.isDefaultNextSuggestion("I'm", "a", "about"));
assertTrue(sh.isDefaultNextSuggestion("about", "b", "business"));
assertTrue(sh.isASuggestion("about", "b", "being"));
assertFalse(sh.isDefaultNextSuggestion("about", "p", "business"));
}
/**
* Make sure bigrams score affects the original score
*/
public void testBigramsScoreEffect() {
assertTrue(sh.isDefaultCorrection("pa", "page"));
assertTrue(sh.isDefaultNextCorrection("about", "pa", "part"));
assertTrue(sh.isDefaultCorrection("sa", "said"));
assertTrue(sh.isDefaultNextCorrection("from", "sa", "same"));
}
}
| Java |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.android.inputmethod.latin;
import android.test.AndroidTestCase;
import android.util.Log;
import com.android.inputmethod.latin.tests.R;
import java.io.InputStreamReader;
import java.io.InputStream;
import java.io.BufferedReader;
import java.util.StringTokenizer;
public class SuggestPerformanceTests extends AndroidTestCase {
private static final String TAG = "SuggestPerformanceTests";
private String mTestText;
private SuggestHelper sh;
@Override
protected void setUp() {
// TODO Figure out a way to directly using the dictionary rather than copying it over
// For testing with real dictionary, TEMPORARILY COPY main dictionary into test directory.
// DO NOT SUBMIT real dictionary under test directory.
//int[] resId = new int[] { R.raw.main0, R.raw.main1, R.raw.main2 };
int[] resId = new int[] { R.raw.test };
sh = new SuggestHelper(TAG, getTestContext(), resId);
loadString();
}
private void loadString() {
try {
InputStream is = getTestContext().getResources().openRawResource(R.raw.testtext);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = reader.readLine();
while (line != null) {
sb.append(line + " ");
line = reader.readLine();
}
mTestText = sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
}
/************************** Helper functions ************************/
private int lookForSuggestion(String prevWord, String currentWord) {
for (int i = 1; i < currentWord.length(); i++) {
if (i == 1) {
if (sh.isDefaultNextSuggestion(prevWord, currentWord.substring(0, i),
currentWord)) {
return i;
}
} else {
if (sh.isDefaultNextCorrection(prevWord, currentWord.substring(0, i),
currentWord)) {
return i;
}
}
}
return currentWord.length();
}
private double runText(boolean withBigrams) {
StringTokenizer st = new StringTokenizer(mTestText);
String prevWord = null;
int typeCount = 0;
int characterCount = 0; // without space
int wordCount = 0;
while (st.hasMoreTokens()) {
String currentWord = st.nextToken();
boolean endCheck = false;
if (currentWord.matches("[\\w]*[\\.|?|!|*|@|&|/|:|;]")) {
currentWord = currentWord.substring(0, currentWord.length() - 1);
endCheck = true;
}
if (withBigrams && prevWord != null) {
typeCount += lookForSuggestion(prevWord, currentWord);
} else {
typeCount += lookForSuggestion(null, currentWord);
}
characterCount += currentWord.length();
if (!endCheck) prevWord = currentWord;
wordCount++;
}
double result = (double) (characterCount - typeCount) / characterCount * 100;
if (withBigrams) {
Log.i(TAG, "with bigrams -> " + result + " % saved!");
} else {
Log.i(TAG, "without bigrams -> " + result + " % saved!");
}
Log.i(TAG, "\ttotal number of words: " + wordCount);
Log.i(TAG, "\ttotal number of characters: " + mTestText.length());
Log.i(TAG, "\ttotal number of characters without space: " + characterCount);
Log.i(TAG, "\ttotal number of characters typed: " + typeCount);
return result;
}
/************************** Performance Tests ************************/
/**
* Compare the Suggest with and without bigram
* Check the log for detail
*/
public void testSuggestPerformance() {
assertTrue(runText(false) <= runText(true));
}
}
| Java |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.android.inputmethod.latin;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import com.android.inputmethod.latin.Suggest;
import com.android.inputmethod.latin.UserBigramDictionary;
import com.android.inputmethod.latin.WordComposer;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.Channels;
import java.util.List;
import java.util.Locale;
import java.util.StringTokenizer;
public class SuggestHelper {
private Suggest mSuggest;
private UserBigramDictionary mUserBigram;
private final String TAG;
/** Uses main dictionary only **/
public SuggestHelper(String tag, Context context, int[] resId) {
TAG = tag;
InputStream[] is = null;
try {
// merging separated dictionary into one if dictionary is separated
int total = 0;
is = new InputStream[resId.length];
for (int i = 0; i < resId.length; i++) {
is[i] = context.getResources().openRawResource(resId[i]);
total += is[i].available();
}
ByteBuffer byteBuffer =
ByteBuffer.allocateDirect(total).order(ByteOrder.nativeOrder());
int got = 0;
for (int i = 0; i < resId.length; i++) {
got += Channels.newChannel(is[i]).read(byteBuffer);
}
if (got != total) {
Log.w(TAG, "Read " + got + " bytes, expected " + total);
} else {
mSuggest = new Suggest(context, byteBuffer);
Log.i(TAG, "Created mSuggest " + total + " bytes");
}
} catch (IOException e) {
Log.w(TAG, "No available memory for binary dictionary");
} finally {
try {
if (is != null) {
for (int i = 0; i < is.length; i++) {
is[i].close();
}
}
} catch (IOException e) {
Log.w(TAG, "Failed to close input stream");
}
}
mSuggest.setAutoTextEnabled(false);
mSuggest.setCorrectionMode(Suggest.CORRECTION_FULL_BIGRAM);
}
/** Uses both main dictionary and user-bigram dictionary **/
public SuggestHelper(String tag, Context context, int[] resId, int userBigramMax,
int userBigramDelete) {
this(tag, context, resId);
mUserBigram = new UserBigramDictionary(context, null, Locale.US.toString(),
Suggest.DIC_USER);
mUserBigram.setDatabaseMax(userBigramMax);
mUserBigram.setDatabaseDelete(userBigramDelete);
mSuggest.setUserBigramDictionary(mUserBigram);
}
void changeUserBigramLocale(Context context, Locale locale) {
if (mUserBigram != null) {
flushUserBigrams();
mUserBigram.close();
mUserBigram = new UserBigramDictionary(context, null, locale.toString(),
Suggest.DIC_USER);
mSuggest.setUserBigramDictionary(mUserBigram);
}
}
private WordComposer createWordComposer(CharSequence s) {
WordComposer word = new WordComposer();
for (int i = 0; i < s.length(); i++) {
final char c = s.charAt(i);
int[] codes;
// If it's not a lowercase letter, don't find adjacent letters
if (c < 'a' || c > 'z') {
codes = new int[] { c };
} else {
codes = adjacents[c - 'a'];
}
word.add(c, codes);
}
return word;
}
private void showList(String title, List<CharSequence> suggestions) {
Log.i(TAG, title);
for (int i = 0; i < suggestions.size(); i++) {
Log.i(title, suggestions.get(i) + ", ");
}
}
private boolean isDefaultSuggestion(List<CharSequence> suggestions, CharSequence word) {
// Check if either the word is what you typed or the first alternative
return suggestions.size() > 0 &&
(/*TextUtils.equals(suggestions.get(0), word) || */
(suggestions.size() > 1 && TextUtils.equals(suggestions.get(1), word)));
}
boolean isDefaultSuggestion(CharSequence typed, CharSequence expected) {
WordComposer word = createWordComposer(typed);
List<CharSequence> suggestions = mSuggest.getSuggestions(null, word, false, null);
return isDefaultSuggestion(suggestions, expected);
}
boolean isDefaultCorrection(CharSequence typed, CharSequence expected) {
WordComposer word = createWordComposer(typed);
List<CharSequence> suggestions = mSuggest.getSuggestions(null, word, false, null);
return isDefaultSuggestion(suggestions, expected) && mSuggest.hasMinimalCorrection();
}
boolean isASuggestion(CharSequence typed, CharSequence expected) {
WordComposer word = createWordComposer(typed);
List<CharSequence> suggestions = mSuggest.getSuggestions(null, word, false, null);
for (int i = 1; i < suggestions.size(); i++) {
if (TextUtils.equals(suggestions.get(i), expected)) return true;
}
return false;
}
private void getBigramSuggestions(CharSequence previous, CharSequence typed) {
if (!TextUtils.isEmpty(previous) && (typed.length() > 1)) {
WordComposer firstChar = createWordComposer(Character.toString(typed.charAt(0)));
mSuggest.getSuggestions(null, firstChar, false, previous);
}
}
boolean isDefaultNextSuggestion(CharSequence previous, CharSequence typed,
CharSequence expected) {
WordComposer word = createWordComposer(typed);
getBigramSuggestions(previous, typed);
List<CharSequence> suggestions = mSuggest.getSuggestions(null, word, false, previous);
return isDefaultSuggestion(suggestions, expected);
}
boolean isDefaultNextCorrection(CharSequence previous, CharSequence typed,
CharSequence expected) {
WordComposer word = createWordComposer(typed);
getBigramSuggestions(previous, typed);
List<CharSequence> suggestions = mSuggest.getSuggestions(null, word, false, previous);
return isDefaultSuggestion(suggestions, expected) && mSuggest.hasMinimalCorrection();
}
boolean isASuggestion(CharSequence previous, CharSequence typed,
CharSequence expected) {
WordComposer word = createWordComposer(typed);
getBigramSuggestions(previous, typed);
List<CharSequence> suggestions = mSuggest.getSuggestions(null, word, false, previous);
for (int i = 1; i < suggestions.size(); i++) {
if (TextUtils.equals(suggestions.get(i), expected)) return true;
}
return false;
}
boolean isValid(CharSequence typed) {
return mSuggest.isValidWord(typed);
}
boolean isUserBigramSuggestion(CharSequence previous, char typed,
CharSequence expected) {
WordComposer word = createWordComposer(Character.toString(typed));
if (mUserBigram == null) return false;
flushUserBigrams();
if (!TextUtils.isEmpty(previous) && !TextUtils.isEmpty(Character.toString(typed))) {
WordComposer firstChar = createWordComposer(Character.toString(typed));
mSuggest.getSuggestions(null, firstChar, false, previous);
boolean reloading = mUserBigram.reloadDictionaryIfRequired();
if (reloading) mUserBigram.waitForDictionaryLoading();
mUserBigram.getBigrams(firstChar, previous, mSuggest, null);
}
List<CharSequence> suggestions = mSuggest.mBigramSuggestions;
for (int i = 0; i < suggestions.size(); i++) {
if (TextUtils.equals(suggestions.get(i), expected)) return true;
}
return false;
}
void addToUserBigram(String sentence) {
StringTokenizer st = new StringTokenizer(sentence);
String previous = null;
while (st.hasMoreTokens()) {
String current = st.nextToken();
if (previous != null) {
addToUserBigram(new String[] {previous, current});
}
previous = current;
}
}
void addToUserBigram(String[] pair) {
if (mUserBigram != null && pair.length == 2) {
mUserBigram.addBigrams(pair[0], pair[1]);
}
}
void flushUserBigrams() {
if (mUserBigram != null) {
mUserBigram.flushPendingWrites();
mUserBigram.waitUntilUpdateDBDone();
}
}
final int[][] adjacents = {
{'a','s','w','q',-1},
{'b','h','v','n','g','j',-1},
{'c','v','f','x','g',},
{'d','f','r','e','s','x',-1},
{'e','w','r','s','d',-1},
{'f','g','d','c','t','r',-1},
{'g','h','f','y','t','v',-1},
{'h','j','u','g','b','y',-1},
{'i','o','u','k',-1},
{'j','k','i','h','u','n',-1},
{'k','l','o','j','i','m',-1},
{'l','k','o','p',-1},
{'m','k','n','l',-1},
{'n','m','j','k','b',-1},
{'o','p','i','l',-1},
{'p','o',-1},
{'q','w',-1},
{'r','t','e','f',-1},
{'s','d','e','w','a','z',-1},
{'t','y','r',-1},
{'u','y','i','h','j',-1},
{'v','b','g','c','h',-1},
{'w','e','q',-1},
{'x','c','d','z','f',-1},
{'y','u','t','h','g',-1},
{'z','s','x','a','d',-1},
};
}
| Java |
/*
* Copyright (C) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.android.inputmethod.latin;
import com.android.inputmethod.latin.SwipeTracker.EventRingBuffer;
import android.test.AndroidTestCase;
public class EventRingBufferTests extends AndroidTestCase {
@Override
protected void setUp() throws Exception {
super.setUp();
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
}
private static float X_BASE = 1000f;
private static float Y_BASE = 2000f;
private static long TIME_BASE = 3000l;
private static float x(int id) {
return X_BASE + id;
}
private static float y(int id) {
return Y_BASE + id;
}
private static long time(int id) {
return TIME_BASE + id;
}
private static void addEvent(EventRingBuffer buf, int id) {
buf.add(x(id), y(id), time(id));
}
private static void assertEventSize(EventRingBuffer buf, int size) {
assertEquals(size, buf.size());
}
private static void assertEvent(EventRingBuffer buf, int pos, int id) {
assertEquals(x(id), buf.getX(pos), 0f);
assertEquals(y(id), buf.getY(pos), 0f);
assertEquals(time(id), buf.getTime(pos));
}
public void testClearBuffer() {
EventRingBuffer buf = new EventRingBuffer(4);
assertEventSize(buf, 0);
addEvent(buf, 0);
addEvent(buf, 1);
addEvent(buf, 2);
addEvent(buf, 3);
addEvent(buf, 4);
assertEventSize(buf, 4);
buf.clear();
assertEventSize(buf, 0);
}
public void testRingBuffer() {
EventRingBuffer buf = new EventRingBuffer(4);
assertEventSize(buf, 0); // [0]
addEvent(buf, 0);
assertEventSize(buf, 1); // [1] 0
assertEvent(buf, 0, 0);
addEvent(buf, 1);
addEvent(buf, 2);
assertEventSize(buf, 3); // [3] 2 1 0
assertEvent(buf, 0, 0);
assertEvent(buf, 1, 1);
assertEvent(buf, 2, 2);
addEvent(buf, 3);
assertEventSize(buf, 4); // [4] 3 2 1 0
assertEvent(buf, 0, 0);
assertEvent(buf, 1, 1);
assertEvent(buf, 2, 2);
assertEvent(buf, 3, 3);
addEvent(buf, 4);
addEvent(buf, 5);
assertEventSize(buf, 4); // [4] 5 4|3 2(1 0)
assertEvent(buf, 0, 2);
assertEvent(buf, 1, 3);
assertEvent(buf, 2, 4);
assertEvent(buf, 3, 5);
addEvent(buf, 6);
addEvent(buf, 7);
addEvent(buf, 8);
assertEventSize(buf, 4); // [4] 8 7 6 5|(4 3 2)1|0
assertEvent(buf, 0, 5);
assertEvent(buf, 1, 6);
assertEvent(buf, 2, 7);
assertEvent(buf, 3, 8);
}
public void testDropOldest() {
EventRingBuffer buf = new EventRingBuffer(4);
addEvent(buf, 0);
assertEventSize(buf, 1); // [1] 0
assertEvent(buf, 0, 0);
buf.dropOldest();
assertEventSize(buf, 0); // [0] (0)
addEvent(buf, 1);
addEvent(buf, 2);
addEvent(buf, 3);
addEvent(buf, 4);
assertEventSize(buf, 4); // [4] 4|3 2 1(0)
assertEvent(buf, 0, 1);
buf.dropOldest();
assertEventSize(buf, 3); // [3] 4|3 2(1)0
assertEvent(buf, 0, 2);
buf.dropOldest();
assertEventSize(buf, 2); // [2] 4|3(2)10
assertEvent(buf, 0, 3);
buf.dropOldest();
assertEventSize(buf, 1); // [1] 4|(3)210
assertEvent(buf, 0, 4);
buf.dropOldest();
assertEventSize(buf, 0); // [0] (4)|3210
}
}
| Java |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.android.inputmethod.latin;
import android.test.AndroidTestCase;
import com.android.inputmethod.latin.tests.R;
import java.util.Locale;
public class UserBigramTests extends AndroidTestCase {
private static final String TAG = "UserBigramTests";
private static final int SUGGESTION_STARTS = 6;
private static final int MAX_DATA = 20;
private static final int DELETE_DATA = 10;
private SuggestHelper sh;
@Override
protected void setUp() {
int[] resId = new int[] { R.raw.test };
sh = new SuggestHelper(TAG, getTestContext(), resId, MAX_DATA, DELETE_DATA);
}
/************************** Tests ************************/
/**
* Test suggestion started at right time
*/
public void testUserBigram() {
for (int i = 0; i < SUGGESTION_STARTS; i++) sh.addToUserBigram(pair1);
for (int i = 0; i < (SUGGESTION_STARTS - 1); i++) sh.addToUserBigram(pair2);
assertTrue(sh.isUserBigramSuggestion("user", 'b', "bigram"));
assertFalse(sh.isUserBigramSuggestion("android", 'p', "platform"));
}
/**
* Test loading correct (locale) bigrams
*/
public void testOpenAndClose() {
for (int i = 0; i < SUGGESTION_STARTS; i++) sh.addToUserBigram(pair1);
assertTrue(sh.isUserBigramSuggestion("user", 'b', "bigram"));
// change to fr_FR
sh.changeUserBigramLocale(getTestContext(), Locale.FRANCE);
for (int i = 0; i < SUGGESTION_STARTS; i++) sh.addToUserBigram(pair3);
assertTrue(sh.isUserBigramSuggestion("locale", 'f', "france"));
assertFalse(sh.isUserBigramSuggestion("user", 'b', "bigram"));
// change back to en_US
sh.changeUserBigramLocale(getTestContext(), Locale.US);
assertFalse(sh.isUserBigramSuggestion("locale", 'f', "france"));
assertTrue(sh.isUserBigramSuggestion("user", 'b', "bigram"));
}
/**
* Test data gets pruned when it is over maximum
*/
public void testPruningData() {
for (int i = 0; i < SUGGESTION_STARTS; i++) sh.addToUserBigram(sentence0);
sh.flushUserBigrams();
assertTrue(sh.isUserBigramSuggestion("Hello", 'w', "world"));
sh.addToUserBigram(sentence1);
sh.addToUserBigram(sentence2);
assertTrue(sh.isUserBigramSuggestion("Hello", 'w', "world"));
// pruning should happen
sh.addToUserBigram(sentence3);
sh.addToUserBigram(sentence4);
// trying to reopen database to check pruning happened in database
sh.changeUserBigramLocale(getTestContext(), Locale.US);
assertFalse(sh.isUserBigramSuggestion("Hello", 'w', "world"));
}
final String[] pair1 = new String[] {"user", "bigram"};
final String[] pair2 = new String[] {"android","platform"};
final String[] pair3 = new String[] {"locale", "france"};
final String sentence0 = "Hello world";
final String sentence1 = "This is a test for user input based bigram";
final String sentence2 = "It learns phrases that contain both dictionary and nondictionary "
+ "words";
final String sentence3 = "This should give better suggestions than the previous version";
final String sentence4 = "Android stock keyboard is improving";
}
| Java |
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.pocketworkstation.pckeyboard;
import android.content.ContentResolver;
import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.os.SystemClock;
import android.provider.ContactsContract.Contacts;
import android.text.TextUtils;
import android.util.Log;
public class ContactsDictionary extends ExpandableDictionary {
private static final String[] PROJECTION = {
Contacts._ID,
Contacts.DISPLAY_NAME,
};
private static final String TAG = "ContactsDictionary";
/**
* Frequency for contacts information into the dictionary
*/
private static final int FREQUENCY_FOR_CONTACTS = 128;
private static final int FREQUENCY_FOR_CONTACTS_BIGRAM = 90;
private static final int INDEX_NAME = 1;
private ContentObserver mObserver;
private long mLastLoadedContacts;
public ContactsDictionary(Context context, int dicTypeId) {
super(context, dicTypeId);
// Perform a managed query. The Activity will handle closing and requerying the cursor
// when needed.
ContentResolver cres = context.getContentResolver();
cres.registerContentObserver(
Contacts.CONTENT_URI, true,mObserver = new ContentObserver(null) {
@Override
public void onChange(boolean self) {
setRequiresReload(true);
}
});
loadDictionary();
}
@Override
public synchronized void close() {
if (mObserver != null) {
getContext().getContentResolver().unregisterContentObserver(mObserver);
mObserver = null;
}
super.close();
}
@Override
public void startDictionaryLoadingTaskLocked() {
long now = SystemClock.uptimeMillis();
if (mLastLoadedContacts == 0
|| now - mLastLoadedContacts > 30 * 60 * 1000 /* 30 minutes */) {
super.startDictionaryLoadingTaskLocked();
}
}
@Override
public void loadDictionaryAsync() {
try {
Cursor cursor = getContext().getContentResolver()
.query(Contacts.CONTENT_URI, PROJECTION, null, null, null);
if (cursor != null) {
addWords(cursor);
}
} catch(IllegalStateException e) {
Log.e(TAG, "Contacts DB is having problems");
}
mLastLoadedContacts = SystemClock.uptimeMillis();
}
private void addWords(Cursor cursor) {
clearDictionary();
final int maxWordLength = getMaxWordLength();
try {
if (cursor.moveToFirst()) {
while (!cursor.isAfterLast()) {
String name = cursor.getString(INDEX_NAME);
if (name != null) {
int len = name.length();
String prevWord = null;
// TODO: Better tokenization for non-Latin writing systems
for (int i = 0; i < len; i++) {
if (Character.isLetter(name.charAt(i))) {
int j;
for (j = i + 1; j < len; j++) {
char c = name.charAt(j);
if (!(c == '-' || c == '\'' ||
Character.isLetter(c))) {
break;
}
}
String word = name.substring(i, j);
i = j - 1;
// Safeguard against adding really long words. Stack
// may overflow due to recursion
// Also don't add single letter words, possibly confuses
// capitalization of i.
final int wordLen = word.length();
if (wordLen < maxWordLength && wordLen > 1) {
super.addWord(word, FREQUENCY_FOR_CONTACTS);
if (!TextUtils.isEmpty(prevWord)) {
// TODO Do not add email address
// Not so critical
super.setBigram(prevWord, word,
FREQUENCY_FOR_CONTACTS_BIGRAM);
}
prevWord = word;
}
}
}
}
cursor.moveToNext();
}
}
cursor.close();
} catch(IllegalStateException e) {
Log.e(TAG, "Contacts DB is having problems");
}
}
}
| Java |
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.text.Layout;
import android.text.SpannableStringBuilder;
import android.text.StaticLayout;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.PopupWindow;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class Tutorial implements OnTouchListener {
private List<Bubble> mBubbles = new ArrayList<Bubble>();
private View mInputView;
private LatinIME mIme;
private int[] mLocation = new int[2];
private static final int MSG_SHOW_BUBBLE = 0;
private int mBubbleIndex;
Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_SHOW_BUBBLE:
Bubble bubba = (Bubble) msg.obj;
bubba.show(mLocation[0], mLocation[1]);
break;
}
}
};
class Bubble {
Drawable bubbleBackground;
int x;
int y;
int width;
int gravity;
CharSequence text;
boolean dismissOnTouch;
boolean dismissOnClose;
PopupWindow window;
TextView textView;
View inputView;
Bubble(Context context, View inputView,
int backgroundResource, int bx, int by, int textResource1, int textResource2) {
bubbleBackground = context.getResources().getDrawable(backgroundResource);
x = bx;
y = by;
width = (int) (inputView.getWidth() * 0.9);
this.gravity = Gravity.TOP | Gravity.LEFT;
text = new SpannableStringBuilder()
.append(context.getResources().getText(textResource1))
.append("\n")
.append(context.getResources().getText(textResource2));
this.dismissOnTouch = true;
this.dismissOnClose = false;
this.inputView = inputView;
window = new PopupWindow(context);
window.setBackgroundDrawable(null);
LayoutInflater inflate =
(LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
textView = (TextView) inflate.inflate(R.layout.bubble_text, null);
textView.setBackgroundDrawable(bubbleBackground);
textView.setText(text);
//textView.setText(textResource1);
window.setContentView(textView);
window.setFocusable(false);
window.setTouchable(true);
window.setOutsideTouchable(false);
}
private int chooseSize(PopupWindow pop, View parentView, CharSequence text, TextView tv) {
int wid = tv.getPaddingLeft() + tv.getPaddingRight();
int ht = tv.getPaddingTop() + tv.getPaddingBottom();
/*
* Figure out how big the text would be if we laid it out to the
* full width of this view minus the border.
*/
int cap = width - wid;
Layout l = new StaticLayout(text, tv.getPaint(), cap,
Layout.Alignment.ALIGN_NORMAL, 1, 0, true);
float max = 0;
for (int i = 0; i < l.getLineCount(); i++) {
max = Math.max(max, l.getLineWidth(i));
}
/*
* Now set the popup size to be big enough for the text plus the border.
*/
pop.setWidth(width);
pop.setHeight(ht + l.getHeight());
return l.getHeight();
}
void show(int offx, int offy) {
int textHeight = chooseSize(window, inputView, text, textView);
offy -= textView.getPaddingTop() + textHeight;
if (inputView.getVisibility() == View.VISIBLE
&& inputView.getWindowVisibility() == View.VISIBLE) {
try {
if ((gravity & Gravity.BOTTOM) == Gravity.BOTTOM) offy -= window.getHeight();
if ((gravity & Gravity.RIGHT) == Gravity.RIGHT) offx -= window.getWidth();
textView.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View view, MotionEvent me) {
Tutorial.this.next();
return true;
}
});
window.showAtLocation(inputView, Gravity.NO_GRAVITY, x + offx, y + offy);
} catch (Exception e) {
// Input view is not valid
}
}
}
void hide() {
if (window.isShowing()) {
textView.setOnTouchListener(null);
window.dismiss();
}
}
boolean isShowing() {
return window.isShowing();
}
}
public Tutorial(LatinIME ime, LatinKeyboardView inputView) {
Context context = inputView.getContext();
mIme = ime;
int inputWidth = inputView.getWidth();
final int x = inputWidth / 20; // Half of 1/10th
Bubble bWelcome = new Bubble(context, inputView,
R.drawable.dialog_bubble_step02, x, 0,
R.string.tip_to_open_keyboard, R.string.touch_to_continue);
mBubbles.add(bWelcome);
Bubble bAccents = new Bubble(context, inputView,
R.drawable.dialog_bubble_step02, x, 0,
R.string.tip_to_view_accents, R.string.touch_to_continue);
mBubbles.add(bAccents);
Bubble b123 = new Bubble(context, inputView,
R.drawable.dialog_bubble_step07, x, 0,
R.string.tip_to_open_symbols, R.string.touch_to_continue);
mBubbles.add(b123);
Bubble bABC = new Bubble(context, inputView,
R.drawable.dialog_bubble_step07, x, 0,
R.string.tip_to_close_symbols, R.string.touch_to_continue);
mBubbles.add(bABC);
Bubble bSettings = new Bubble(context, inputView,
R.drawable.dialog_bubble_step07, x, 0,
R.string.tip_to_launch_settings, R.string.touch_to_continue);
mBubbles.add(bSettings);
Bubble bDone = new Bubble(context, inputView,
R.drawable.dialog_bubble_step02, x, 0,
R.string.tip_to_start_typing, R.string.touch_to_finish);
mBubbles.add(bDone);
mInputView = inputView;
}
void start() {
mInputView.getLocationInWindow(mLocation);
mBubbleIndex = -1;
mInputView.setOnTouchListener(this);
next();
}
boolean next() {
if (mBubbleIndex >= 0) {
// If the bubble is not yet showing, don't move to the next.
if (!mBubbles.get(mBubbleIndex).isShowing()) {
return true;
}
// Hide all previous bubbles as well, as they may have had a delayed show
for (int i = 0; i <= mBubbleIndex; i++) {
mBubbles.get(i).hide();
}
}
mBubbleIndex++;
if (mBubbleIndex >= mBubbles.size()) {
mInputView.setOnTouchListener(null);
mIme.sendDownUpKeyEvents(-1); // Inform the setupwizard that tutorial is in last bubble
mIme.tutorialDone();
return false;
}
if (mBubbleIndex == 3 || mBubbleIndex == 4) {
mIme.mKeyboardSwitcher.toggleSymbols();
}
mHandler.sendMessageDelayed(
mHandler.obtainMessage(MSG_SHOW_BUBBLE, mBubbles.get(mBubbleIndex)), 500);
return true;
}
void hide() {
for (int i = 0; i < mBubbles.size(); i++) {
mBubbles.get(i).hide();
}
mInputView.setOnTouchListener(null);
}
boolean close() {
mHandler.removeMessages(MSG_SHOW_BUBBLE);
hide();
return true;
}
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
next();
}
return true;
}
}
| Java |
/*
* Copyright (C) 2011 Darren Salt
*
* Licensed under the Apache License, Version 2.0 (the "Licence"); you may
* not use this file except in compliance with the Licence. You may obtain
* a copy of the Licence at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the Licence is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* Licence for the specific language governing permissions and limitations
* under the Licence.
*/
package org.pocketworkstation.pckeyboard;
public class ComposeSequence extends ComposeBase {
public ComposeSequence(ComposeSequencing user) {
init(user);
}
static {
put("++", "#");
put("' ", "'");
put(" '", "'");
put("AT", "@");
put("((", "[");
put("//", "\\");
put("/<", "\\");
put("</", "\\");
put("))", "]");
put("^ ", "^");
put(" ^", "^");
put("> ", "^");
put(" >", "^");
put("` ", "`");
put(" `", "`");
put(", ", "¸");
put(" ,", "¸");
put("(-", "{");
put("-(", "{");
put("/^", "|");
put("^/", "|");
put("VL", "|");
put("LV", "|");
put("vl", "|");
put("lv", "|");
put(")-", "}");
put("-)", "}");
put("~ ", "~");
put(" ~", "~");
put("- ", "~");
put(" -", "~");
put(" ", " ");
put(" .", " ");
put("oc", "©");
put("oC", "©");
put("Oc", "©");
put("OC", "©");
put("or", "®");
put("oR", "®");
put("Or", "®");
put("OR", "®");
put(".>", "›");
put(".<", "‹");
put("..", "…");
put(".-", "·");
put(".=", "•");
put("!^", "¦");
put("!!", "¡");
put("p!", "¶");
put("P!", "¶");
put("+-", "±");
put("??", "¿");
put("-d", "đ");
put("-D", "Đ");
put("ss", "ß");
put("SS", "ẞ");
put("oe", "œ");
put("OE", "Œ");
put("ae", "æ");
put("AE", "Æ");
put("oo", "°");
put("\"\\", "〝");
put("\"/", "〞");
put("<<", "«");
put(">>", "»");
put("<'", "‘");
put("'<", "‘");
put(">'", "’");
put("'>", "’");
put(",'", "‚");
put("',", "‚");
put("<\"", "“");
put("\"<", "“");
put(">\"", "”");
put("\">", "”");
put(",\"", "„");
put("\",", "„");
put("%o", "‰");
put("CE", "₠");
put("C/", "₡");
put("/C", "₡");
put("Cr", "₢");
put("Fr", "₣");
put("L=", "₤");
put("=L", "₤");
put("m/", "₥");
put("/m", "₥");
put("N=", "₦");
put("=N", "₦");
put("Pt", "₧");
put("Rs", "₨");
put("W=", "₩");
put("=W", "₩");
put("d-", "₫");
put("C=", "€");
put("=C", "€");
put("c=", "€");
put("=c", "€");
put("E=", "€");
put("=E", "€");
put("e=", "€");
put("=e", "€");
put("|c", "¢");
put("c|", "¢");
put("c/", "¢");
put("/c", "¢");
put("L-", "£");
put("-L", "£");
put("Y=", "¥");
put("=Y", "¥");
put("fs", "ſ");
put("fS", "ſ");
put("--.", "–");
put("---", "—");
put("#b", "♭");
put("#f", "♮");
put("##", "♯");
put("so", "§");
put("os", "§");
put("ox", "¤");
put("xo", "¤");
put("PP", "¶");
put("No", "№");
put("NO", "№");
put("?!", "⸘");
put("!?", "‽");
put("CCCP", "☭");
put("OA", "Ⓐ");
put("<3", "♥");
put(":)", "☺");
put(":(", "☹");
put(",-", "¬");
put("-,", "¬");
put("^_a", "ª");
put("^2", "²");
put("^3", "³");
put("mu", "µ");
put("^1", "¹");
put("^_o", "º");
put("14", "¼");
put("12", "½");
put("34", "¾");
put("`A", "À");
put("'A", "Á");
put("^A", "Â");
put("~A", "Ã");
put("\"A", "Ä");
put("oA", "Å");
put(",C", "Ç");
put("`E", "È");
put("'E", "É");
put("^E", "Ê");
put("\"E", "Ë");
put("`I", "Ì");
put("'I", "Í");
put("^I", "Î");
put("\"I", "Ï");
put("DH", "Ð");
put("~N", "Ñ");
put("`O", "Ò");
put("'O", "Ó");
put("^O", "Ô");
put("~O", "Õ");
put("\"O", "Ö");
put("xx", "×");
put("/O", "Ø");
put("`U", "Ù");
put("'U", "Ú");
put("^U", "Û");
put("\"U", "Ü");
put("'Y", "Ý");
put("TH", "Þ");
put("`a", "à");
put("'a", "á");
put("^a", "â");
put("~a", "ã");
put("\"a", "ä");
put("oa", "å");
put(",c", "ç");
put("`e", "è");
put("'e", "é");
put("^e", "ê");
put("\"e", "ë");
put("`i", "ì");
put("'i", "í");
put("^i", "î");
put("\"i", "ï");
put("dh", "ð");
put("~n", "ñ");
put("`o", "ò");
put("'o", "ó");
put("^o", "ô");
put("~o", "õ");
put("\"o", "ö");
put(":-", "÷");
put("-:", "÷");
put("/o", "ø");
put("`u", "ù");
put("'u", "ú");
put("^u", "û");
put("\"u", "ü");
put("'y", "ý");
put("th", "þ");
put("\"y", "ÿ");
put("_A", "Ā");
put("_a", "ā");
put("UA", "Ă");
put("bA", "Ă");
put("Ua", "ă");
put("ba", "ă");
put(";A", "Ą");
put(",A", "Ą");
put(";a", "ą");
put(",a", "ą");
put("'C", "Ć");
put("'c", "ć");
put("^C", "Ĉ");
put("^c", "ĉ");
put(".C", "Ċ");
put(".c", "ċ");
put("cC", "Č");
put("cc", "č");
put("cD", "Ď");
put("cd", "ď");
put("/D", "Đ");
put("/d", "đ");
put("_E", "Ē");
put("_e", "ē");
put("UE", "Ĕ");
put("bE", "Ĕ");
put("Ue", "ĕ");
put("be", "ĕ");
put(".E", "Ė");
put(".e", "ė");
put(";E", "Ę");
put(",E", "Ę");
put(";e", "ę");
put(",e", "ę");
put("cE", "Ě");
put("ce", "ě");
//put("ff", "ff"); // Not usable, interferes with ffi/ffl prefix
put("+f", "ff");
put("f+", "ff");
put("fi", "fi");
put("fl", "fl");
put("ffi", "ffi");
put("ffl", "ffl");
put("^G", "Ĝ");
put("^g", "ĝ");
put("UG", "Ğ");
put("bG", "Ğ");
put("Ug", "ğ");
put("bg", "ğ");
put(".G", "Ġ");
put(".g", "ġ");
put(",G", "Ģ");
put(",g", "ģ");
put("^H", "Ĥ");
put("^h", "ĥ");
put("/H", "Ħ");
put("/h", "ħ");
put("~I", "Ĩ");
put("~i", "ĩ");
put("_I", "Ī");
put("_i", "ī");
put("UI", "Ĭ");
put("bI", "Ĭ");
put("Ui", "ĭ");
put("bi", "ĭ");
put(";I", "Į");
put(",I", "Į");
put(";i", "į");
put(",i", "į");
put(".I", "İ");
put("i.", "ı");
put("^J", "Ĵ");
put("^j", "ĵ");
put(",K", "Ķ");
put(",k", "ķ");
put("kk", "ĸ");
put("'L", "Ĺ");
put("'l", "ĺ");
put(",L", "Ļ");
put(",l", "ļ");
put("cL", "Ľ");
put("cl", "ľ");
put("/L", "Ł");
put("/l", "ł");
put("'N", "Ń");
put("'n", "ń");
put(",N", "Ņ");
put(",n", "ņ");
put("cN", "Ň");
put("cn", "ň");
put("NG", "Ŋ");
put("ng", "ŋ");
put("_O", "Ō");
put("_o", "ō");
put("UO", "Ŏ");
put("bO", "Ŏ");
put("Uo", "ŏ");
put("bo", "ŏ");
put("=O", "Ő");
put("=o", "ő");
put("'R", "Ŕ");
put("'r", "ŕ");
put(",R", "Ŗ");
put(",r", "ŗ");
put("cR", "Ř");
put("cr", "ř");
put("'S", "Ś");
put("'s", "ś");
put("^S", "Ŝ");
put("^s", "ŝ");
put(",S", "Ş");
put(",s", "ş");
put("cS", "Š");
put("cs", "š");
put(",T", "Ţ");
put(",t", "ţ");
put("cT", "Ť");
put("ct", "ť");
put("/T", "Ŧ");
put("/t", "ŧ");
put("~U", "Ũ");
put("~u", "ũ");
put("_U", "Ū");
put("_u", "ū");
put("UU", "Ŭ");
put("bU", "Ŭ");
put("Uu", "ŭ");
put("uu", "ŭ");
put("bu", "ŭ");
put("oU", "Ů");
put("ou", "ů");
put("=U", "Ű");
put("=u", "ű");
put(";U", "Ų");
put(",U", "Ų");
put(";u", "ų");
put(",u", "ų");
put("^W", "Ŵ");
put("^w", "ŵ");
put("^Y", "Ŷ");
put("^y", "ŷ");
put("\"Y", "Ÿ");
put("'Z", "Ź");
put("'z", "ź");
put(".Z", "Ż");
put(".z", "ż");
put("cZ", "Ž");
put("cz", "ž");
put("/b", "ƀ");
put("/I", "Ɨ");
put("+O", "Ơ");
put("+o", "ơ");
put("+U", "Ư");
put("+u", "ư");
put("/Z", "Ƶ");
put("/z", "ƶ");
put("cA", "Ǎ");
put("ca", "ǎ");
put("cI", "Ǐ");
put("ci", "ǐ");
put("cO", "Ǒ");
put("co", "ǒ");
put("cU", "Ǔ");
put("cu", "ǔ");
put("_Ü", "Ǖ");
put("_\"U", "Ǖ");
put("_ü", "ǖ");
put("_\"u", "ǖ");
put("'Ü", "Ǘ");
put("'\"U", "Ǘ");
put("'ü", "ǘ");
put("'\"u", "ǘ");
put("cÜ", "Ǚ");
put("c\"U", "Ǚ");
put("cü", "ǚ");
put("c\"u", "ǚ");
put("`Ü", "Ǜ");
put("`\"U", "Ǜ");
put("`ü", "ǜ");
put("`\"u", "ǜ");
put("_Ä", "Ǟ");
put("_\"A", "Ǟ");
put("_ä", "ǟ");
put("_\"a", "ǟ");
put("_.A", "Ǡ");
put("_.a", "ǡ");
put("_Æ", "Ǣ");
put("_æ", "ǣ");
put("/G", "Ǥ");
put("/g", "ǥ");
put("cG", "Ǧ");
put("cg", "ǧ");
put("cK", "Ǩ");
put("ck", "ǩ");
put(";O", "Ǫ");
put(";o", "ǫ");
put("_;O", "Ǭ");
put("_;o", "ǭ");
put("cj", "ǰ");
put("'G", "Ǵ");
put("'g", "ǵ");
put("`N", "Ǹ");
put("`n", "ǹ");
put("'Å", "Ǻ");
put("o'A", "Ǻ");
put("'å", "ǻ");
put("o'a", "ǻ");
put("'Æ", "Ǽ");
put("'æ", "ǽ");
put("'Ø", "Ǿ");
put("'/O", "Ǿ");
put("'ø", "ǿ");
put("'/o", "ǿ");
put("cH", "Ȟ");
put("ch", "ȟ");
put(".A", "Ȧ");
put(".a", "ȧ");
put("_Ö", "Ȫ");
put("_\"O", "Ȫ");
put("_ö", "ȫ");
put("_\"o", "ȫ");
put("_Õ", "Ȭ");
put("_~O", "Ȭ");
put("_õ", "ȭ");
put("_~o", "ȭ");
put(".O", "Ȯ");
put(".o", "ȯ");
put("_.O", "Ȱ");
put("_.o", "ȱ");
put("_Y", "Ȳ");
put("_y", "ȳ");
put("ee", "ə");
put("/i", "ɨ");
put("^_h", "ʰ");
put("^_j", "ʲ");
put("^_r", "ʳ");
put("^_w", "ʷ");
put("^_y", "ʸ");
put("^_l", "ˡ");
put("^_s", "ˢ");
put("^_x", "ˣ");
put("\"'", "̈́");
put(".B", "Ḃ");
put(".b", "ḃ");
put("!B", "Ḅ");
put("!b", "ḅ");
put("'Ç", "Ḉ");
put("'ç", "ḉ");
put(".D", "Ḋ");
put(".d", "ḋ");
put("!D", "Ḍ");
put("!d", "ḍ");
put(",D", "Ḑ");
put(",d", "ḑ");
put("`Ē", "Ḕ");
put("`_E", "Ḕ");
put("`ē", "ḕ");
put("`_e", "ḕ");
put("'Ē", "Ḗ");
put("'_E", "Ḗ");
put("'ē", "ḗ");
put("'_e", "ḗ");
put("U,E", "Ḝ");
put("b,E", "Ḝ");
put("U,e", "ḝ");
put("b,e", "ḝ");
put(".F", "Ḟ");
put(".f", "ḟ");
put("_G", "Ḡ");
put("_g", "ḡ");
put(".H", "Ḣ");
put(".h", "ḣ");
put("!H", "Ḥ");
put("!h", "ḥ");
put("\"H", "Ḧ");
put("\"h", "ḧ");
put(",H", "Ḩ");
put(",h", "ḩ");
put("'Ï", "Ḯ");
put("'\"I", "Ḯ");
put("'ï", "ḯ");
put("'\"i", "ḯ");
put("'K", "Ḱ");
put("'k", "ḱ");
put("!K", "Ḳ");
put("!k", "ḳ");
put("!L", "Ḷ");
put("!l", "ḷ");
put("_!L", "Ḹ");
put("_!l", "ḹ");
put("'M", "Ḿ");
put("'m", "ḿ");
put(".M", "Ṁ");
put(".m", "ṁ");
put("!M", "Ṃ");
put("!m", "ṃ");
put(".N", "Ṅ");
put(".n", "ṅ");
put("!N", "Ṇ");
put("!n", "ṇ");
put("'Õ", "Ṍ");
put("'~O", "Ṍ");
put("'õ", "ṍ");
put("'~o", "ṍ");
put("\"Õ", "Ṏ");
put("\"~O", "Ṏ");
put("\"õ", "ṏ");
put("\"~o", "ṏ");
put("`Ō", "Ṑ");
put("`_O", "Ṑ");
put("`ō", "ṑ");
put("`_o", "ṑ");
put("'Ō", "Ṓ");
put("'_O", "Ṓ");
put("'ō", "ṓ");
put("'_o", "ṓ");
put("'P", "Ṕ");
put("'p", "ṕ");
put(".P", "Ṗ");
put(".p", "ṗ");
put(".R", "Ṙ");
put(".r", "ṙ");
put("!R", "Ṛ");
put("!r", "ṛ");
put("_!R", "Ṝ");
put("_!r", "ṝ");
put(".S", "Ṡ");
put(".s", "ṡ");
put("!S", "Ṣ");
put("!s", "ṣ");
put(".Ś", "Ṥ");
put(".'S", "Ṥ");
put(".ś", "ṥ");
put(".'s", "ṥ");
put(".Š", "Ṧ");
put(".š", "ṧ");
put(".!S", "Ṩ");
put(".!s", "ṩ");
put(".T", "Ṫ");
put(".t", "ṫ");
put("!T", "Ṭ");
put("!t", "ṭ");
put("'Ũ", "Ṹ");
put("'~U", "Ṹ");
put("'ũ", "ṹ");
put("'~u", "ṹ");
put("\"Ū", "Ṻ");
put("\"_U", "Ṻ");
put("\"ū", "ṻ");
put("\"_u", "ṻ");
put("~V", "Ṽ");
put("~v", "ṽ");
put("!V", "Ṿ");
put("!v", "ṿ");
put("`W", "Ẁ");
put("`w", "ẁ");
put("'W", "Ẃ");
put("'w", "ẃ");
put("\"W", "Ẅ");
put("\"w", "ẅ");
put(".W", "Ẇ");
put(".w", "ẇ");
put("!W", "Ẉ");
put("!w", "ẉ");
put(".X", "Ẋ");
put(".x", "ẋ");
put("\"X", "Ẍ");
put("\"x", "ẍ");
put(".Y", "Ẏ");
put(".y", "ẏ");
put("^Z", "Ẑ");
put("^z", "ẑ");
put("!Z", "Ẓ");
put("!z", "ẓ");
put("\"t", "ẗ");
put("ow", "ẘ");
put("oy", "ẙ");
put("!A", "Ạ");
put("!a", "ạ");
put("?A", "Ả");
put("?a", "ả");
put("'Â", "Ấ");
put("'^A", "Ấ");
put("'â", "ấ");
put("'^a", "ấ");
put("`Â", "Ầ");
put("`^A", "Ầ");
put("`â", "ầ");
put("`^a", "ầ");
put("?Â", "Ẩ");
put("?^A", "Ẩ");
put("?â", "ẩ");
put("?^a", "ẩ");
put("~Â", "Ẫ");
put("~^A", "Ẫ");
put("~â", "ẫ");
put("~^a", "ẫ");
put("^!A", "Ậ");
put("^!a", "ậ");
put("'Ă", "Ắ");
put("'bA", "Ắ");
put("'ă", "ắ");
put("'ba", "ắ");
put("`Ă", "Ằ");
put("`bA", "Ằ");
put("`ă", "ằ");
put("`ba", "ằ");
put("?Ă", "Ẳ");
put("?bA", "Ẳ");
put("?ă", "ẳ");
put("?ba", "ẳ");
put("~Ă", "Ẵ");
put("~bA", "Ẵ");
put("~ă", "ẵ");
put("~ba", "ẵ");
put("U!A", "Ặ");
put("b!A", "Ặ");
put("U!a", "ặ");
put("b!a", "ặ");
put("!E", "Ẹ");
put("!e", "ẹ");
put("?E", "Ẻ");
put("?e", "ẻ");
put("~E", "Ẽ");
put("~e", "ẽ");
put("'Ê", "Ế");
put("'^E", "Ế");
put("'ê", "ế");
put("'^e", "ế");
put("`Ê", "Ề");
put("`^E", "Ề");
put("`ê", "ề");
put("`^e", "ề");
put("?Ê", "Ể");
put("?^E", "Ể");
put("?ê", "ể");
put("?^e", "ể");
put("~Ê", "Ễ");
put("~^E", "Ễ");
put("~ê", "ễ");
put("~^e", "ễ");
put("^!E", "Ệ");
put("^!e", "ệ");
put("?I", "Ỉ");
put("?i", "ỉ");
put("!I", "Ị");
put("!i", "ị");
put("!O", "Ọ");
put("!o", "ọ");
put("?O", "Ỏ");
put("?o", "ỏ");
put("'Ô", "Ố");
put("'^O", "Ố");
put("'ô", "ố");
put("'^o", "ố");
put("`Ô", "Ồ");
put("`^O", "Ồ");
put("`ô", "ồ");
put("`^o", "ồ");
put("?Ô", "Ổ");
put("?^O", "Ổ");
put("?ô", "ổ");
put("?^o", "ổ");
put("~Ô", "Ỗ");
put("~^O", "Ỗ");
put("~ô", "ỗ");
put("~^o", "ỗ");
put("^!O", "Ộ");
put("^!o", "ộ");
put("'Ơ", "Ớ");
put("'+O", "Ớ");
put("'ơ", "ớ");
put("'+o", "ớ");
put("`Ơ", "Ờ");
put("`+O", "Ờ");
put("`ơ", "ờ");
put("`+o", "ờ");
put("?Ơ", "Ở");
put("?+O", "Ở");
put("?ơ", "ở");
put("?+o", "ở");
put("~Ơ", "Ỡ");
put("~+O", "Ỡ");
put("~ơ", "ỡ");
put("~+o", "ỡ");
put("!Ơ", "Ợ");
put("!+O", "Ợ");
put("!ơ", "ợ");
put("!+o", "ợ");
put("!U", "Ụ");
put("!u", "ụ");
put("?U", "Ủ");
put("?u", "ủ");
put("'Ư", "Ứ");
put("'+U", "Ứ");
put("'ư", "ứ");
put("'+u", "ứ");
put("`Ư", "Ừ");
put("`+U", "Ừ");
put("`ư", "ừ");
put("`+u", "ừ");
put("?Ư", "Ử");
put("?+U", "Ử");
put("?ư", "ử");
put("?+u", "ử");
put("~Ư", "Ữ");
put("~+U", "Ữ");
put("~ư", "ữ");
put("~+u", "ữ");
put("!Ư", "Ự");
put("!+U", "Ự");
put("!ư", "ự");
put("!+u", "ự");
put("`Y", "Ỳ");
put("`y", "ỳ");
put("!Y", "Ỵ");
put("!y", "ỵ");
put("?Y", "Ỷ");
put("?y", "ỷ");
put("~Y", "Ỹ");
put("~y", "ỹ");
put("^0", "⁰");
put("^_i", "ⁱ");
put("^4", "⁴");
put("^5", "⁵");
put("^6", "⁶");
put("^7", "⁷");
put("^8", "⁸");
put("^9", "⁹");
put("^+", "⁺");
put("^=", "⁼");
put("^(", "⁽");
put("^)", "⁾");
put("^_n", "ⁿ");
put("_0", "₀");
put("_1", "₁");
put("_2", "₂");
put("_3", "₃");
put("_4", "₄");
put("_5", "₅");
put("_6", "₆");
put("_7", "₇");
put("_8", "₈");
put("_9", "₉");
put("_+", "₊");
put("_=", "₌");
put("_(", "₍");
put("_)", "₎");
put("SM", "℠");
put("sM", "℠");
put("Sm", "℠");
put("sm", "℠");
put("TM", "™");
put("tM", "™");
put("Tm", "™");
put("tm", "™");
put("13", "⅓");
put("23", "⅔");
put("15", "⅕");
put("25", "⅖");
put("35", "⅗");
put("45", "⅘");
put("16", "⅙");
put("56", "⅚");
put("18", "⅛");
put("38", "⅜");
put("58", "⅝");
put("78", "⅞");
put("/←", "↚");
put("/→", "↛");
put("<-", "←");
put("->", "→");
put("/=", "≠");
put("=/", "≠");
put("<=", "≤");
put(">=", "≥");
put("(1)", "①");
put("(2)", "②");
put("(3)", "③");
put("(4)", "④");
put("(5)", "⑤");
put("(6)", "⑥");
put("(7)", "⑦");
put("(8)", "⑧");
put("(9)", "⑨");
put("(10)", "⑩");
put("(11)", "⑪");
put("(12)", "⑫");
put("(13)", "⑬");
put("(14)", "⑭");
put("(15)", "⑮");
put("(16)", "⑯");
put("(17)", "⑰");
put("(18)", "⑱");
put("(19)", "⑲");
put("(20)", "⑳");
put("(A)", "Ⓐ");
put("(B)", "Ⓑ");
put("(C)", "Ⓒ");
put("(D)", "Ⓓ");
put("(E)", "Ⓔ");
put("(F)", "Ⓕ");
put("(G)", "Ⓖ");
put("(H)", "Ⓗ");
put("(I)", "Ⓘ");
put("(J)", "Ⓙ");
put("(K)", "Ⓚ");
put("(L)", "Ⓛ");
put("(M)", "Ⓜ");
put("(N)", "Ⓝ");
put("(O)", "Ⓞ");
put("(P)", "Ⓟ");
put("(Q)", "Ⓠ");
put("(R)", "Ⓡ");
put("(S)", "Ⓢ");
put("(T)", "Ⓣ");
put("(U)", "Ⓤ");
put("(V)", "Ⓥ");
put("(W)", "Ⓦ");
put("(X)", "Ⓧ");
put("(Y)", "Ⓨ");
put("(Z)", "Ⓩ");
put("(a)", "ⓐ");
put("(b)", "ⓑ");
put("(c)", "ⓒ");
put("(d)", "ⓓ");
put("(e)", "ⓔ");
put("(f)", "ⓕ");
put("(g)", "ⓖ");
put("(h)", "ⓗ");
put("(i)", "ⓘ");
put("(j)", "ⓙ");
put("(k)", "ⓚ");
put("(l)", "ⓛ");
put("(m)", "ⓜ");
put("(n)", "ⓝ");
put("(o)", "ⓞ");
put("(p)", "ⓟ");
put("(q)", "ⓠ");
put("(r)", "ⓡ");
put("(s)", "ⓢ");
put("(t)", "ⓣ");
put("(u)", "ⓤ");
put("(v)", "ⓥ");
put("(w)", "ⓦ");
put("(x)", "ⓧ");
put("(y)", "ⓨ");
put("(z)", "ⓩ");
put("(0)", "⓪");
put("(21)", "㉑");
put("(22)", "㉒");
put("(23)", "㉓");
put("(24)", "㉔");
put("(25)", "㉕");
put("(26)", "㉖");
put("(27)", "㉗");
put("(28)", "㉘");
put("(29)", "㉙");
put("(30)", "㉚");
put("(31)", "㉛");
put("(32)", "㉜");
put("(33)", "㉝");
put("(34)", "㉞");
put("(35)", "㉟");
put("(36)", "㊱");
put("(37)", "㊲");
put("(38)", "㊳");
put("(39)", "㊴");
put("(40)", "㊵");
put("(41)", "㊶");
put("(42)", "㊷");
put("(43)", "㊸");
put("(44)", "㊹");
put("(45)", "㊺");
put("(46)", "㊻");
put("(47)", "㊼");
put("(48)", "㊽");
put("(49)", "㊾");
put("(50)", "㊿");
put("\\o/", "🙌");
}
}
| Java |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.pocketworkstation.pckeyboard;
import android.view.inputmethod.InputMethodManager;
import android.content.Context;
import android.os.AsyncTask;
import android.text.format.DateUtils;
import android.util.Log;
public class LatinIMEUtil {
/**
* Cancel an {@link AsyncTask}.
*
* @param mayInterruptIfRunning <tt>true</tt> if the thread executing this
* task should be interrupted; otherwise, in-progress tasks are allowed
* to complete.
*/
public static void cancelTask(AsyncTask<?, ?, ?> task, boolean mayInterruptIfRunning) {
if (task != null && task.getStatus() != AsyncTask.Status.FINISHED) {
task.cancel(mayInterruptIfRunning);
}
}
public static class GCUtils {
private static final String TAG = "GCUtils";
public static final int GC_TRY_COUNT = 2;
// GC_TRY_LOOP_MAX is used for the hard limit of GC wait,
// GC_TRY_LOOP_MAX should be greater than GC_TRY_COUNT.
public static final int GC_TRY_LOOP_MAX = 5;
private static final long GC_INTERVAL = DateUtils.SECOND_IN_MILLIS;
private static GCUtils sInstance = new GCUtils();
private int mGCTryCount = 0;
public static GCUtils getInstance() {
return sInstance;
}
public void reset() {
mGCTryCount = 0;
}
public boolean tryGCOrWait(String metaData, Throwable t) {
if (mGCTryCount == 0) {
System.gc();
}
if (++mGCTryCount > GC_TRY_COUNT) {
LatinImeLogger.logOnException(metaData, t);
return false;
} else {
try {
Thread.sleep(GC_INTERVAL);
return true;
} catch (InterruptedException e) {
Log.e(TAG, "Sleep was interrupted.");
LatinImeLogger.logOnException(metaData, t);
return false;
}
}
}
}
/* package */ static class RingCharBuffer {
private static RingCharBuffer sRingCharBuffer = new RingCharBuffer();
private static final char PLACEHOLDER_DELIMITER_CHAR = '\uFFFC';
private static final int INVALID_COORDINATE = -2;
/* package */ static final int BUFSIZE = 20;
private Context mContext;
private boolean mEnabled = false;
private int mEnd = 0;
/* package */ int mLength = 0;
private char[] mCharBuf = new char[BUFSIZE];
private int[] mXBuf = new int[BUFSIZE];
private int[] mYBuf = new int[BUFSIZE];
private RingCharBuffer() {
}
public static RingCharBuffer getInstance() {
return sRingCharBuffer;
}
public static RingCharBuffer init(Context context, boolean enabled) {
sRingCharBuffer.mContext = context;
sRingCharBuffer.mEnabled = enabled;
return sRingCharBuffer;
}
private int normalize(int in) {
int ret = in % BUFSIZE;
return ret < 0 ? ret + BUFSIZE : ret;
}
public void push(char c, int x, int y) {
if (!mEnabled) return;
mCharBuf[mEnd] = c;
mXBuf[mEnd] = x;
mYBuf[mEnd] = y;
mEnd = normalize(mEnd + 1);
if (mLength < BUFSIZE) {
++mLength;
}
}
public char pop() {
if (mLength < 1) {
return PLACEHOLDER_DELIMITER_CHAR;
} else {
mEnd = normalize(mEnd - 1);
--mLength;
return mCharBuf[mEnd];
}
}
public char getLastChar() {
if (mLength < 1) {
return PLACEHOLDER_DELIMITER_CHAR;
} else {
return mCharBuf[normalize(mEnd - 1)];
}
}
public int getPreviousX(char c, int back) {
int index = normalize(mEnd - 2 - back);
if (mLength <= back
|| Character.toLowerCase(c) != Character.toLowerCase(mCharBuf[index])) {
return INVALID_COORDINATE;
} else {
return mXBuf[index];
}
}
public int getPreviousY(char c, int back) {
int index = normalize(mEnd - 2 - back);
if (mLength <= back
|| Character.toLowerCase(c) != Character.toLowerCase(mCharBuf[index])) {
return INVALID_COORDINATE;
} else {
return mYBuf[index];
}
}
public String getLastString() {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < mLength; ++i) {
char c = mCharBuf[normalize(mEnd - 1 - i)];
if (!((LatinIME)mContext).isWordSeparator(c)) {
sb.append(c);
} else {
break;
}
}
return sb.reverse().toString();
}
public void reset() {
mLength = 0;
}
}
}
| Java |
/*
* Copyright (C) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import java.util.Locale;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
/**
* Keeps track of list of selected input languages and the current
* input language that the user has selected.
*/
public class LanguageSwitcher {
private static final String TAG = "HK/LanguageSwitcher";
private Locale[] mLocales;
private LatinIME mIme;
private String[] mSelectedLanguageArray;
private String mSelectedLanguages;
private int mCurrentIndex = 0;
private String mDefaultInputLanguage;
private Locale mDefaultInputLocale;
private Locale mSystemLocale;
public LanguageSwitcher(LatinIME ime) {
mIme = ime;
mLocales = new Locale[0];
}
public Locale[] getLocales() {
return mLocales;
}
public int getLocaleCount() {
return mLocales.length;
}
/**
* Loads the currently selected input languages from shared preferences.
* @param sp
* @return whether there was any change
*/
public boolean loadLocales(SharedPreferences sp) {
String selectedLanguages = sp.getString(LatinIME.PREF_SELECTED_LANGUAGES, null);
String currentLanguage = sp.getString(LatinIME.PREF_INPUT_LANGUAGE, null);
if (selectedLanguages == null || selectedLanguages.length() < 1) {
loadDefaults();
if (mLocales.length == 0) {
return false;
}
mLocales = new Locale[0];
return true;
}
if (selectedLanguages.equals(mSelectedLanguages)) {
return false;
}
mSelectedLanguageArray = selectedLanguages.split(",");
mSelectedLanguages = selectedLanguages; // Cache it for comparison later
constructLocales();
mCurrentIndex = 0;
if (currentLanguage != null) {
// Find the index
mCurrentIndex = 0;
for (int i = 0; i < mLocales.length; i++) {
if (mSelectedLanguageArray[i].equals(currentLanguage)) {
mCurrentIndex = i;
break;
}
}
// If we didn't find the index, use the first one
}
return true;
}
private void loadDefaults() {
mDefaultInputLocale = mIme.getResources().getConfiguration().locale;
String country = mDefaultInputLocale.getCountry();
mDefaultInputLanguage = mDefaultInputLocale.getLanguage() +
(TextUtils.isEmpty(country) ? "" : "_" + country);
}
private void constructLocales() {
mLocales = new Locale[mSelectedLanguageArray.length];
for (int i = 0; i < mLocales.length; i++) {
final String lang = mSelectedLanguageArray[i];
mLocales[i] = new Locale(lang.substring(0, 2),
lang.length() > 4 ? lang.substring(3, 5) : "");
}
}
/**
* Returns the currently selected input language code, or the display language code if
* no specific locale was selected for input.
*/
public String getInputLanguage() {
if (getLocaleCount() == 0) return mDefaultInputLanguage;
return mSelectedLanguageArray[mCurrentIndex];
}
public boolean allowAutoCap() {
String lang = getInputLanguage();
if (lang.length() > 2) lang = lang.substring(0, 2);
return !InputLanguageSelection.NOCAPS_LANGUAGES.contains(lang);
}
public boolean allowDeadKeys() {
String lang = getInputLanguage();
if (lang.length() > 2) lang = lang.substring(0, 2);
return !InputLanguageSelection.NODEADKEY_LANGUAGES.contains(lang);
}
public boolean allowAutoSpace() {
String lang = getInputLanguage();
if (lang.length() > 2) lang = lang.substring(0, 2);
return !InputLanguageSelection.NOAUTOSPACE_LANGUAGES.contains(lang);
}
/**
* Returns the list of enabled language codes.
*/
public String[] getEnabledLanguages() {
return mSelectedLanguageArray;
}
/**
* Returns the currently selected input locale, or the display locale if no specific
* locale was selected for input.
* @return
*/
public Locale getInputLocale() {
Locale locale;
if (getLocaleCount() == 0) {
locale = mDefaultInputLocale;
} else {
locale = mLocales[mCurrentIndex];
}
LatinIME.sKeyboardSettings.inputLocale = (locale != null) ? locale : Locale.getDefault();
return locale;
}
/**
* Returns the next input locale in the list. Wraps around to the beginning of the
* list if we're at the end of the list.
* @return
*/
public Locale getNextInputLocale() {
if (getLocaleCount() == 0) return mDefaultInputLocale;
return mLocales[(mCurrentIndex + 1) % mLocales.length];
}
/**
* Sets the system locale (display UI) used for comparing with the input language.
* @param locale the locale of the system
*/
public void setSystemLocale(Locale locale) {
mSystemLocale = locale;
}
/**
* Returns the system locale.
* @return the system locale
*/
public Locale getSystemLocale() {
return mSystemLocale;
}
/**
* Returns the previous input locale in the list. Wraps around to the end of the
* list if we're at the beginning of the list.
* @return
*/
public Locale getPrevInputLocale() {
if (getLocaleCount() == 0) return mDefaultInputLocale;
return mLocales[(mCurrentIndex - 1 + mLocales.length) % mLocales.length];
}
public void reset() {
mCurrentIndex = 0;
mSelectedLanguages = "";
loadLocales(PreferenceManager.getDefaultSharedPreferences(mIme));
}
public void next() {
mCurrentIndex++;
if (mCurrentIndex >= mLocales.length) mCurrentIndex = 0; // Wrap around
}
public void prev() {
mCurrentIndex--;
if (mCurrentIndex < 0) mCurrentIndex = mLocales.length - 1; // Wrap around
}
public void persist() {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(mIme);
Editor editor = sp.edit();
editor.putString(LatinIME.PREF_INPUT_LANGUAGE, getInputLanguage());
SharedPreferencesCompat.apply(editor);
}
static String toTitleCase(String s) {
if (s.length() == 0) {
return s;
}
return Character.toUpperCase(s.charAt(0)) + s.substring(1);
}
}
| Java |
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import java.io.InputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.Channels;
import java.util.Arrays;
import android.content.Context;
import android.util.Log;
/**
* Implements a static, compacted, binary dictionary of standard words.
*/
public class BinaryDictionary extends Dictionary {
/**
* There is difference between what java and native code can handle.
* This value should only be used in BinaryDictionary.java
* It is necessary to keep it at this value because some languages e.g. German have
* really long words.
*/
protected static final int MAX_WORD_LENGTH = 48;
private static final String TAG = "BinaryDictionary";
private static final int MAX_ALTERNATIVES = 16;
private static final int MAX_WORDS = 18;
private static final int MAX_BIGRAMS = 60;
private static final int TYPED_LETTER_MULTIPLIER = 2;
private static final boolean ENABLE_MISSED_CHARACTERS = true;
private int mDicTypeId;
private int mNativeDict;
private int mDictLength;
private int[] mInputCodes = new int[MAX_WORD_LENGTH * MAX_ALTERNATIVES];
private char[] mOutputChars = new char[MAX_WORD_LENGTH * MAX_WORDS];
private char[] mOutputChars_bigrams = new char[MAX_WORD_LENGTH * MAX_BIGRAMS];
private int[] mFrequencies = new int[MAX_WORDS];
private int[] mFrequencies_bigrams = new int[MAX_BIGRAMS];
// Keep a reference to the native dict direct buffer in Java to avoid
// unexpected deallocation of the direct buffer.
private ByteBuffer mNativeDictDirectBuffer;
static {
try {
System.loadLibrary("jni_pckeyboard");
Log.i("PCKeyboard", "loaded jni_pckeyboard");
} catch (UnsatisfiedLinkError ule) {
Log.e("BinaryDictionary", "Could not load native library jni_pckeyboard");
}
}
/**
* Create a dictionary from a raw resource file
* @param context application context for reading resources
* @param resId the resource containing the raw binary dictionary
*/
public BinaryDictionary(Context context, int[] resId, int dicTypeId) {
if (resId != null && resId.length > 0 && resId[0] != 0) {
loadDictionary(context, resId);
}
mDicTypeId = dicTypeId;
}
/**
* Create a dictionary from input streams
* @param context application context for reading resources
* @param streams the resource streams containing the raw binary dictionary
*/
public BinaryDictionary(Context context, InputStream[] streams, int dicTypeId) {
if (streams != null && streams.length > 0) {
loadDictionary(streams);
}
mDicTypeId = dicTypeId;
}
/**
* Create a dictionary from a byte buffer. This is used for testing.
* @param context application context for reading resources
* @param byteBuffer a ByteBuffer containing the binary dictionary
*/
public BinaryDictionary(Context context, ByteBuffer byteBuffer, int dicTypeId) {
if (byteBuffer != null) {
if (byteBuffer.isDirect()) {
mNativeDictDirectBuffer = byteBuffer;
} else {
mNativeDictDirectBuffer = ByteBuffer.allocateDirect(byteBuffer.capacity());
byteBuffer.rewind();
mNativeDictDirectBuffer.put(byteBuffer);
}
mDictLength = byteBuffer.capacity();
mNativeDict = openNative(mNativeDictDirectBuffer,
TYPED_LETTER_MULTIPLIER, FULL_WORD_FREQ_MULTIPLIER, mDictLength);
}
mDicTypeId = dicTypeId;
}
private native int openNative(ByteBuffer bb, int typedLetterMultiplier,
int fullWordMultiplier, int dictSize);
private native void closeNative(int dict);
private native boolean isValidWordNative(int nativeData, char[] word, int wordLength);
private native int getSuggestionsNative(int dict, int[] inputCodes, int codesSize,
char[] outputChars, int[] frequencies, int maxWordLength, int maxWords,
int maxAlternatives, int skipPos, int[] nextLettersFrequencies, int nextLettersSize);
private native int getBigramsNative(int dict, char[] prevWord, int prevWordLength,
int[] inputCodes, int inputCodesLength, char[] outputChars, int[] frequencies,
int maxWordLength, int maxBigrams, int maxAlternatives);
private final void loadDictionary(InputStream[] is) {
try {
// merging separated dictionary into one if dictionary is separated
int total = 0;
for (int i = 0; i < is.length; i++) {
total += is[i].available();
}
mNativeDictDirectBuffer =
ByteBuffer.allocateDirect(total).order(ByteOrder.nativeOrder());
int got = 0;
for (int i = 0; i < is.length; i++) {
got += Channels.newChannel(is[i]).read(mNativeDictDirectBuffer);
}
if (got != total) {
Log.e(TAG, "Read " + got + " bytes, expected " + total);
} else {
mNativeDict = openNative(mNativeDictDirectBuffer,
TYPED_LETTER_MULTIPLIER, FULL_WORD_FREQ_MULTIPLIER, total);
mDictLength = total;
}
if (mDictLength > 10000) Log.i("PCKeyboard", "Loaded dictionary, len=" + mDictLength);
} catch (IOException e) {
Log.w(TAG, "No available memory for binary dictionary");
} catch (UnsatisfiedLinkError e) {
Log.w(TAG, "Failed to load native dictionary", e);
} finally {
try {
if (is != null) {
for (int i = 0; i < is.length; i++) {
is[i].close();
}
}
} catch (IOException e) {
Log.w(TAG, "Failed to close input stream");
}
}
}
private final void loadDictionary(Context context, int[] resId) {
InputStream[] is = null;
is = new InputStream[resId.length];
for (int i = 0; i < resId.length; i++) {
is[i] = context.getResources().openRawResource(resId[i]);
}
loadDictionary(is);
}
@Override
public void getBigrams(final WordComposer codes, final CharSequence previousWord,
final WordCallback callback, int[] nextLettersFrequencies) {
char[] chars = previousWord.toString().toCharArray();
Arrays.fill(mOutputChars_bigrams, (char) 0);
Arrays.fill(mFrequencies_bigrams, 0);
int codesSize = codes.size();
Arrays.fill(mInputCodes, -1);
int[] alternatives = codes.getCodesAt(0);
System.arraycopy(alternatives, 0, mInputCodes, 0,
Math.min(alternatives.length, MAX_ALTERNATIVES));
int count = getBigramsNative(mNativeDict, chars, chars.length, mInputCodes, codesSize,
mOutputChars_bigrams, mFrequencies_bigrams, MAX_WORD_LENGTH, MAX_BIGRAMS,
MAX_ALTERNATIVES);
for (int j = 0; j < count; j++) {
if (mFrequencies_bigrams[j] < 1) break;
int start = j * MAX_WORD_LENGTH;
int len = 0;
while (mOutputChars_bigrams[start + len] != 0) {
len++;
}
if (len > 0) {
callback.addWord(mOutputChars_bigrams, start, len, mFrequencies_bigrams[j],
mDicTypeId, DataType.BIGRAM);
}
}
}
@Override
public void getWords(final WordComposer codes, final WordCallback callback,
int[] nextLettersFrequencies) {
final int codesSize = codes.size();
// Won't deal with really long words.
if (codesSize > MAX_WORD_LENGTH - 1) return;
Arrays.fill(mInputCodes, -1);
for (int i = 0; i < codesSize; i++) {
int[] alternatives = codes.getCodesAt(i);
System.arraycopy(alternatives, 0, mInputCodes, i * MAX_ALTERNATIVES,
Math.min(alternatives.length, MAX_ALTERNATIVES));
}
Arrays.fill(mOutputChars, (char) 0);
Arrays.fill(mFrequencies, 0);
if (mNativeDict == 0)
return;
int count = getSuggestionsNative(mNativeDict, mInputCodes, codesSize,
mOutputChars, mFrequencies,
MAX_WORD_LENGTH, MAX_WORDS, MAX_ALTERNATIVES, -1,
nextLettersFrequencies,
nextLettersFrequencies != null ? nextLettersFrequencies.length : 0);
// If there aren't sufficient suggestions, search for words by allowing wild cards at
// the different character positions. This feature is not ready for prime-time as we need
// to figure out the best ranking for such words compared to proximity corrections and
// completions.
if (ENABLE_MISSED_CHARACTERS && count < 5) {
for (int skip = 0; skip < codesSize; skip++) {
int tempCount = getSuggestionsNative(mNativeDict, mInputCodes, codesSize,
mOutputChars, mFrequencies,
MAX_WORD_LENGTH, MAX_WORDS, MAX_ALTERNATIVES, skip,
null, 0);
count = Math.max(count, tempCount);
if (tempCount > 0) break;
}
}
for (int j = 0; j < count; j++) {
if (mFrequencies[j] < 1) break;
int start = j * MAX_WORD_LENGTH;
int len = 0;
while (mOutputChars[start + len] != 0) {
len++;
}
if (len > 0) {
callback.addWord(mOutputChars, start, len, mFrequencies[j], mDicTypeId,
DataType.UNIGRAM);
}
}
}
@Override
public boolean isValidWord(CharSequence word) {
if (word == null || mNativeDict == 0) return false;
char[] chars = word.toString().toCharArray();
return isValidWordNative(mNativeDict, chars, chars.length);
}
public int getSize() {
return mDictLength; // This value is initialized on the call to openNative()
}
@Override
public synchronized void close() {
if (mNativeDict != 0) {
closeNative(mNativeDict);
mNativeDict = 0;
}
}
@Override
protected void finalize() throws Throwable {
close();
super.finalize();
}
}
| Java |
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import android.content.Context;
import org.pocketworkstation.pckeyboard.Keyboard.Key;
import android.text.format.DateFormat;
import android.util.Log;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
public class TextEntryState {
private static final boolean DBG = false;
private static final String TAG = "TextEntryState";
private static boolean LOGGING = false;
private static int sBackspaceCount = 0;
private static int sAutoSuggestCount = 0;
private static int sAutoSuggestUndoneCount = 0;
private static int sManualSuggestCount = 0;
private static int sWordNotInDictionaryCount = 0;
private static int sSessionCount = 0;
private static int sTypedChars;
private static int sActualChars;
public enum State {
UNKNOWN,
START,
IN_WORD,
ACCEPTED_DEFAULT,
PICKED_SUGGESTION,
PUNCTUATION_AFTER_WORD,
PUNCTUATION_AFTER_ACCEPTED,
SPACE_AFTER_ACCEPTED,
SPACE_AFTER_PICKED,
UNDO_COMMIT,
CORRECTING,
PICKED_CORRECTION;
}
private static State sState = State.UNKNOWN;
private static FileOutputStream sKeyLocationFile;
private static FileOutputStream sUserActionFile;
public static void newSession(Context context) {
sSessionCount++;
sAutoSuggestCount = 0;
sBackspaceCount = 0;
sAutoSuggestUndoneCount = 0;
sManualSuggestCount = 0;
sWordNotInDictionaryCount = 0;
sTypedChars = 0;
sActualChars = 0;
sState = State.START;
if (LOGGING) {
try {
sKeyLocationFile = context.openFileOutput("key.txt", Context.MODE_APPEND);
sUserActionFile = context.openFileOutput("action.txt", Context.MODE_APPEND);
} catch (IOException ioe) {
Log.e("TextEntryState", "Couldn't open file for output: " + ioe);
}
}
}
public static void endSession() {
if (sKeyLocationFile == null) {
return;
}
try {
sKeyLocationFile.close();
// Write to log file
// Write timestamp, settings,
String out = DateFormat.format("MM:dd hh:mm:ss", Calendar.getInstance().getTime())
.toString()
+ " BS: " + sBackspaceCount
+ " auto: " + sAutoSuggestCount
+ " manual: " + sManualSuggestCount
+ " typed: " + sWordNotInDictionaryCount
+ " undone: " + sAutoSuggestUndoneCount
+ " saved: " + ((float) (sActualChars - sTypedChars) / sActualChars)
+ "\n";
sUserActionFile.write(out.getBytes());
sUserActionFile.close();
sKeyLocationFile = null;
sUserActionFile = null;
} catch (IOException ioe) {
}
}
public static void acceptedDefault(CharSequence typedWord, CharSequence actualWord) {
if (typedWord == null) return;
if (!typedWord.equals(actualWord)) {
sAutoSuggestCount++;
}
sTypedChars += typedWord.length();
sActualChars += actualWord.length();
sState = State.ACCEPTED_DEFAULT;
LatinImeLogger.logOnAutoSuggestion(typedWord.toString(), actualWord.toString());
displayState();
}
// State.ACCEPTED_DEFAULT will be changed to other sub-states
// (see "case ACCEPTED_DEFAULT" in typedCharacter() below),
// and should be restored back to State.ACCEPTED_DEFAULT after processing for each sub-state.
public static void backToAcceptedDefault(CharSequence typedWord) {
if (typedWord == null) return;
switch (sState) {
case SPACE_AFTER_ACCEPTED:
case PUNCTUATION_AFTER_ACCEPTED:
case IN_WORD:
sState = State.ACCEPTED_DEFAULT;
break;
}
displayState();
}
public static void manualTyped(CharSequence typedWord) {
sState = State.START;
displayState();
}
public static void acceptedTyped(CharSequence typedWord) {
sWordNotInDictionaryCount++;
sState = State.PICKED_SUGGESTION;
displayState();
}
public static void acceptedSuggestion(CharSequence typedWord, CharSequence actualWord) {
sManualSuggestCount++;
State oldState = sState;
if (typedWord.equals(actualWord)) {
acceptedTyped(typedWord);
}
if (oldState == State.CORRECTING || oldState == State.PICKED_CORRECTION) {
sState = State.PICKED_CORRECTION;
} else {
sState = State.PICKED_SUGGESTION;
}
displayState();
}
public static void selectedForCorrection() {
sState = State.CORRECTING;
displayState();
}
public static void typedCharacter(char c, boolean isSeparator) {
boolean isSpace = c == ' ';
switch (sState) {
case IN_WORD:
if (isSpace || isSeparator) {
sState = State.START;
} else {
// State hasn't changed.
}
break;
case ACCEPTED_DEFAULT:
case SPACE_AFTER_PICKED:
if (isSpace) {
sState = State.SPACE_AFTER_ACCEPTED;
} else if (isSeparator) {
sState = State.PUNCTUATION_AFTER_ACCEPTED;
} else {
sState = State.IN_WORD;
}
break;
case PICKED_SUGGESTION:
case PICKED_CORRECTION:
if (isSpace) {
sState = State.SPACE_AFTER_PICKED;
} else if (isSeparator) {
// Swap
sState = State.PUNCTUATION_AFTER_ACCEPTED;
} else {
sState = State.IN_WORD;
}
break;
case START:
case UNKNOWN:
case SPACE_AFTER_ACCEPTED:
case PUNCTUATION_AFTER_ACCEPTED:
case PUNCTUATION_AFTER_WORD:
if (!isSpace && !isSeparator) {
sState = State.IN_WORD;
} else {
sState = State.START;
}
break;
case UNDO_COMMIT:
if (isSpace || isSeparator) {
sState = State.ACCEPTED_DEFAULT;
} else {
sState = State.IN_WORD;
}
break;
case CORRECTING:
sState = State.START;
break;
}
displayState();
}
public static void backspace() {
if (sState == State.ACCEPTED_DEFAULT) {
sState = State.UNDO_COMMIT;
sAutoSuggestUndoneCount++;
LatinImeLogger.logOnAutoSuggestionCanceled();
} else if (sState == State.UNDO_COMMIT) {
sState = State.IN_WORD;
}
sBackspaceCount++;
displayState();
}
public static void reset() {
sState = State.START;
displayState();
}
public static State getState() {
if (DBG) {
Log.d(TAG, "Returning state = " + sState);
}
return sState;
}
public static boolean isCorrecting() {
return sState == State.CORRECTING || sState == State.PICKED_CORRECTION;
}
public static void keyPressedAt(Key key, int x, int y) {
if (LOGGING && sKeyLocationFile != null && key.codes[0] >= 32) {
String out =
"KEY: " + (char) key.codes[0]
+ " X: " + x
+ " Y: " + y
+ " MX: " + (key.x + key.width / 2)
+ " MY: " + (key.y + key.height / 2)
+ "\n";
try {
sKeyLocationFile.write(out.getBytes());
} catch (IOException ioe) {
// TODO: May run out of space
}
}
}
private static void displayState() {
if (DBG) {
//Log.w(TAG, "State = " + sState, new Throwable());
Log.i(TAG, "State = " + sState);
}
}
}
| Java |
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import java.util.ArrayList;
/**
* A place to store the currently composing word with information such as adjacent key codes as well
*/
public class WordComposer {
/**
* The list of unicode values for each keystroke (including surrounding keys)
*/
private final ArrayList<int[]> mCodes;
/**
* The word chosen from the candidate list, until it is committed.
*/
private String mPreferredWord;
private final StringBuilder mTypedWord;
private int mCapsCount;
private boolean mAutoCapitalized;
/**
* Whether the user chose to capitalize the first char of the word.
*/
private boolean mIsFirstCharCapitalized;
public WordComposer() {
mCodes = new ArrayList<int[]>(12);
mTypedWord = new StringBuilder(20);
}
WordComposer(WordComposer copy) {
mCodes = new ArrayList<int[]>(copy.mCodes);
mPreferredWord = copy.mPreferredWord;
mTypedWord = new StringBuilder(copy.mTypedWord);
mCapsCount = copy.mCapsCount;
mAutoCapitalized = copy.mAutoCapitalized;
mIsFirstCharCapitalized = copy.mIsFirstCharCapitalized;
}
/**
* Clear out the keys registered so far.
*/
public void reset() {
mCodes.clear();
mIsFirstCharCapitalized = false;
mPreferredWord = null;
mTypedWord.setLength(0);
mCapsCount = 0;
}
/**
* Number of keystrokes in the composing word.
* @return the number of keystrokes
*/
public int size() {
return mCodes.size();
}
/**
* Returns the codes at a particular position in the word.
* @param index the position in the word
* @return the unicode for the pressed and surrounding keys
*/
public int[] getCodesAt(int index) {
return mCodes.get(index);
}
/**
* Add a new keystroke, with codes[0] containing the pressed key's unicode and the rest of
* the array containing unicode for adjacent keys, sorted by reducing probability/proximity.
* @param codes the array of unicode values
*/
public void add(int primaryCode, int[] codes) {
mTypedWord.append((char) primaryCode);
correctPrimaryJuxtapos(primaryCode, codes);
correctCodesCase(codes);
mCodes.add(codes);
if (Character.isUpperCase((char) primaryCode)) mCapsCount++;
}
/**
* Swaps the first and second values in the codes array if the primary code is not the first
* value in the array but the second. This happens when the preferred key is not the key that
* the user released the finger on.
* @param primaryCode the preferred character
* @param codes array of codes based on distance from touch point
*/
private void correctPrimaryJuxtapos(int primaryCode, int[] codes) {
if (codes.length < 2) return;
if (codes[0] > 0 && codes[1] > 0 && codes[0] != primaryCode && codes[1] == primaryCode) {
codes[1] = codes[0];
codes[0] = primaryCode;
}
}
// Prediction expects the keyKodes to be lowercase
private void correctCodesCase(int[] codes) {
for (int i = 0; i < codes.length; ++i) {
int code = codes[i];
if (code > 0) codes[i] = Character.toLowerCase(code);
}
}
/**
* Delete the last keystroke as a result of hitting backspace.
*/
public void deleteLast() {
final int codesSize = mCodes.size();
if (codesSize > 0) {
mCodes.remove(codesSize - 1);
final int lastPos = mTypedWord.length() - 1;
char last = mTypedWord.charAt(lastPos);
mTypedWord.deleteCharAt(lastPos);
if (Character.isUpperCase(last)) mCapsCount--;
}
}
/**
* Returns the word as it was typed, without any correction applied.
* @return the word that was typed so far
*/
public CharSequence getTypedWord() {
int wordSize = mCodes.size();
if (wordSize == 0) {
return null;
}
return mTypedWord;
}
public void setFirstCharCapitalized(boolean capitalized) {
mIsFirstCharCapitalized = capitalized;
}
/**
* Whether or not the user typed a capital letter as the first letter in the word
* @return capitalization preference
*/
public boolean isFirstCharCapitalized() {
return mIsFirstCharCapitalized;
}
/**
* Whether or not all of the user typed chars are upper case
* @return true if all user typed chars are upper case, false otherwise
*/
public boolean isAllUpperCase() {
return (mCapsCount > 0) && (mCapsCount == size());
}
/**
* Stores the user's selected word, before it is actually committed to the text field.
* @param preferred
*/
public void setPreferredWord(String preferred) {
mPreferredWord = preferred;
}
/**
* Return the word chosen by the user, or the typed word if no other word was chosen.
* @return the preferred word
*/
public CharSequence getPreferredWord() {
return mPreferredWord != null ? mPreferredWord : getTypedWord();
}
/**
* Returns true if more than one character is upper case, otherwise returns false.
*/
public boolean isMostlyCaps() {
return mCapsCount > 1;
}
/**
* Saves the reason why the word is capitalized - whether it was automatic or
* due to the user hitting shift in the middle of a sentence.
* @param auto whether it was an automatic capitalization due to start of sentence
*/
public void setAutoCapitalized(boolean auto) {
mAutoCapitalized = auto;
}
/**
* Returns whether the word was automatically capitalized.
* @return whether the word was automatically capitalized
*/
public boolean isAutoCapitalized() {
return mAutoCapitalized;
}
}
| Java |
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);
}
} | Java |
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.pocketworkstation.pckeyboard;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.provider.UserDictionary.Words;
import android.util.Log;
public class UserDictionary extends ExpandableDictionary {
private static final String[] PROJECTION = {
Words._ID,
Words.WORD,
Words.FREQUENCY
};
private static final int INDEX_WORD = 1;
private static final int INDEX_FREQUENCY = 2;
private static final String TAG = "HK/UserDictionary";
private ContentObserver mObserver;
private String mLocale;
public UserDictionary(Context context, String locale) {
super(context, Suggest.DIC_USER);
mLocale = locale;
// Perform a managed query. The Activity will handle closing and requerying the cursor
// when needed.
ContentResolver cres = context.getContentResolver();
cres.registerContentObserver(Words.CONTENT_URI, true, mObserver = new ContentObserver(null) {
@Override
public void onChange(boolean self) {
setRequiresReload(true);
}
});
loadDictionary();
}
@Override
public synchronized void close() {
if (mObserver != null) {
getContext().getContentResolver().unregisterContentObserver(mObserver);
mObserver = null;
}
super.close();
}
@Override
public void loadDictionaryAsync() {
Cursor cursor = getContext().getContentResolver()
.query(Words.CONTENT_URI, PROJECTION, "(locale IS NULL) or (locale=?)",
new String[] { mLocale }, null);
addWords(cursor);
}
/**
* Adds a word to the dictionary and makes it persistent.
* @param word the word to add. If the word is capitalized, then the dictionary will
* recognize it as a capitalized word when searched.
* @param frequency the frequency of occurrence of the word. A frequency of 255 is considered
* the highest.
* @TODO use a higher or float range for frequency
*/
@Override
public synchronized void addWord(String word, int frequency) {
// Force load the dictionary here synchronously
if (getRequiresReload()) loadDictionaryAsync();
// Safeguard against adding long words. Can cause stack overflow.
if (word.length() >= getMaxWordLength()) return;
super.addWord(word, frequency);
// Update the user dictionary provider
final ContentValues values = new ContentValues(5);
values.put(Words.WORD, word);
values.put(Words.FREQUENCY, frequency);
values.put(Words.LOCALE, mLocale);
values.put(Words.APP_ID, 0);
final ContentResolver contentResolver = getContext().getContentResolver();
new Thread("addWord") {
public void run() {
contentResolver.insert(Words.CONTENT_URI, values);
}
}.start();
// In case the above does a synchronous callback of the change observer
setRequiresReload(false);
}
@Override
public synchronized void getWords(final WordComposer codes, final WordCallback callback,
int[] nextLettersFrequencies) {
super.getWords(codes, callback, nextLettersFrequencies);
}
@Override
public synchronized boolean isValidWord(CharSequence word) {
return super.isValidWord(word);
}
private void addWords(Cursor cursor) {
if (cursor == null) {
Log.w(TAG, "Unexpected null cursor in addWords()");
return;
}
clearDictionary();
final int maxWordLength = getMaxWordLength();
if (cursor.moveToFirst()) {
while (!cursor.isAfterLast()) {
String word = cursor.getString(INDEX_WORD);
int frequency = cursor.getInt(INDEX_FREQUENCY);
// Safeguard against adding really long words. Stack may overflow due
// to recursion
if (word.length() < maxWordLength) {
super.addWord(word, frequency);
}
cursor.moveToNext();
}
}
cursor.close();
}
}
| Java |
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import android.app.backup.BackupManager;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceActivity;
public class PrefScreenActions extends PreferenceActivity
implements SharedPreferences.OnSharedPreferenceChangeListener {
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
addPreferencesFromResource(R.xml.prefs_actions);
SharedPreferences prefs = getPreferenceManager().getSharedPreferences();
prefs.registerOnSharedPreferenceChangeListener(this);
}
@Override
protected void onDestroy() {
getPreferenceManager().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(
this);
super.onDestroy();
}
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
(new BackupManager(this)).dataChanged();
}
}
| Java |
package org.pocketworkstation.pckeyboard;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.inputmethod.InputMethodManager;
public class NotificationReceiver extends BroadcastReceiver {
static final String TAG = "PCKeyboard/Notification";
private LatinIME mIME;
NotificationReceiver(LatinIME ime) {
super();
mIME = ime;
Log.i(TAG, "NotificationReceiver created, ime=" + mIME);
}
@Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "NotificationReceiver.onReceive called");
InputMethodManager imm = (InputMethodManager)
context.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.showSoftInputFromInputMethod(mIME.mToken, InputMethodManager.SHOW_FORCED);
}
}
}
| Java |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.PreferenceActivity;
import android.util.Log;
public class LatinIMEDebugSettings extends PreferenceActivity
implements SharedPreferences.OnSharedPreferenceChangeListener {
private static final String TAG = "LatinIMEDebugSettings";
private static final String DEBUG_MODE_KEY = "debug_mode";
private CheckBoxPreference mDebugMode;
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
addPreferencesFromResource(R.xml.prefs_for_debug);
SharedPreferences prefs = getPreferenceManager().getSharedPreferences();
prefs.registerOnSharedPreferenceChangeListener(this);
mDebugMode = (CheckBoxPreference) findPreference(DEBUG_MODE_KEY);
updateDebugMode();
}
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
if (key.equals(DEBUG_MODE_KEY)) {
if (mDebugMode != null) {
mDebugMode.setChecked(prefs.getBoolean(DEBUG_MODE_KEY, false));
updateDebugMode();
}
}
}
private void updateDebugMode() {
if (mDebugMode == null) {
return;
}
boolean isDebugMode = mDebugMode.isChecked();
String version = "";
try {
PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), 0);
version = "Version " + info.versionName;
} catch (NameNotFoundException e) {
Log.e(TAG, "Could not find version info.");
}
if (!isDebugMode) {
mDebugMode.setTitle(version);
mDebugMode.setSummary("");
} else {
mDebugMode.setTitle(getResources().getString(R.string.prefs_debug_mode));
mDebugMode.setSummary(version);
}
}
}
| Java |
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import android.app.backup.BackupManager;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.PreferenceActivity;
public class PrefScreenFeedback extends PreferenceActivity
implements SharedPreferences.OnSharedPreferenceChangeListener {
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
addPreferencesFromResource(R.xml.prefs_feedback);
SharedPreferences prefs = getPreferenceManager().getSharedPreferences();
prefs.registerOnSharedPreferenceChangeListener(this);
}
@Override
protected void onDestroy() {
getPreferenceManager().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(
this);
super.onDestroy();
}
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
(new BackupManager(this)).dataChanged();
}
@Override
protected void onResume() {
super.onResume();
}
}
| Java |
package org.pocketworkstation.pckeyboard;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.util.Log;
/**
* Global current settings for the keyboard.
*
* <p>
* Yes, globals are evil. But the persisted shared preferences are global data
* by definition, and trying to hide this by propagating the current manually
* just adds a lot of complication. This is especially annoying due to Views
* getting constructed in a way that doesn't support adding additional
* constructor arguments, requiring post-construction method calls, which is
* error-prone and fragile.
*
* <p>
* The comments below indicate which class is responsible for updating the
* value, and for recreating keyboards or views as necessary. Other classes
* MUST treat the fields as read-only values, and MUST NOT attempt to save
* these values or results derived from them across re-initializations.
*
* @author klaus.weidner@gmail.com
*/
public final class GlobalKeyboardSettings {
protected static final String TAG = "HK/Globals";
/* Simple prefs updated by this class */
//
// Read by Keyboard
public int popupKeyboardFlags = 0x1;
public float topRowScale = 1.0f;
//
// Read by LatinKeyboardView
public boolean showTouchPos = false;
//
// Read by LatinIME
public String suggestedPunctuation = "!?,.";
public int keyboardModePortrait = 0;
public int keyboardModeLandscape = 2;
public boolean compactModeEnabled = false;
public int chordingCtrlKey = 0;
public int chordingAltKey = 0;
public 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);
}
}
| Java |
/*
* Copyright (C) 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import android.text.TextUtils;
import android.view.inputmethod.ExtractedText;
import android.view.inputmethod.ExtractedTextRequest;
import android.view.inputmethod.InputConnection;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.regex.Pattern;
/**
* Utility methods to deal with editing text through an InputConnection.
*/
public class EditingUtil {
/**
* Number of characters we want to look back in order to identify the previous word
*/
private static final int LOOKBACK_CHARACTER_NUM = 15;
// Cache Method pointers
private static boolean sMethodsInitialized;
private static Method sMethodGetSelectedText;
private static Method sMethodSetComposingRegion;
private EditingUtil() {};
/**
* Append newText to the text field represented by connection.
* The new text becomes selected.
*/
public static void appendText(InputConnection connection, String newText) {
if (connection == null) {
return;
}
// Commit the composing text
connection.finishComposingText();
// Add a space if the field already has text.
CharSequence charBeforeCursor = connection.getTextBeforeCursor(1, 0);
if (charBeforeCursor != null
&& !charBeforeCursor.equals(" ")
&& (charBeforeCursor.length() > 0)) {
newText = " " + newText;
}
connection.setComposingText(newText, 1);
}
private static int getCursorPosition(InputConnection connection) {
ExtractedText extracted = connection.getExtractedText(
new ExtractedTextRequest(), 0);
if (extracted == null) {
return -1;
}
return extracted.startOffset + extracted.selectionStart;
}
/**
* @param connection connection to the current text field.
* @param sep characters which may separate words
* @param range the range object to store the result into
* @return the word that surrounds the cursor, including up to one trailing
* separator. For example, if the field contains "he|llo world", where |
* represents the cursor, then "hello " will be returned.
*/
public static String getWordAtCursor(
InputConnection connection, String separators, Range range) {
Range r = getWordRangeAtCursor(connection, separators, range);
return (r == null) ? null : r.word;
}
/**
* Removes the word surrounding the cursor. Parameters are identical to
* getWordAtCursor.
*/
public static void deleteWordAtCursor(
InputConnection connection, String separators) {
Range range = getWordRangeAtCursor(connection, separators, null);
if (range == null) return;
connection.finishComposingText();
// Move cursor to beginning of word, to avoid crash when cursor is outside
// of valid range after deleting text.
int newCursor = getCursorPosition(connection) - range.charsBefore;
connection.setSelection(newCursor, newCursor);
connection.deleteSurroundingText(0, range.charsBefore + range.charsAfter);
}
/**
* Represents a range of text, relative to the current cursor position.
*/
public static class Range {
/** Characters before selection start */
public int charsBefore;
/**
* Characters after selection start, including one trailing word
* separator.
*/
public int charsAfter;
/** The actual characters that make up a word */
public String word;
public Range() {}
public Range(int charsBefore, int charsAfter, String word) {
if (charsBefore < 0 || charsAfter < 0) {
throw new IndexOutOfBoundsException();
}
this.charsBefore = charsBefore;
this.charsAfter = charsAfter;
this.word = word;
}
}
private static Range getWordRangeAtCursor(
InputConnection connection, String sep, Range range) {
if (connection == null || sep == null) {
return null;
}
CharSequence before = connection.getTextBeforeCursor(1000, 0);
CharSequence after = connection.getTextAfterCursor(1000, 0);
if (before == null || after == null) {
return null;
}
// Find first word separator before the cursor
int start = before.length();
while (start > 0 && !isWhitespace(before.charAt(start - 1), sep)) start--;
// Find last word separator after the cursor
int end = -1;
while (++end < after.length() && !isWhitespace(after.charAt(end), sep));
int cursor = getCursorPosition(connection);
if (start >= 0 && cursor + end <= after.length() + before.length()) {
String word = before.toString().substring(start, before.length())
+ after.toString().substring(0, end);
Range returnRange = range != null? range : new Range();
returnRange.charsBefore = before.length() - start;
returnRange.charsAfter = end;
returnRange.word = word;
return returnRange;
}
return null;
}
private static boolean isWhitespace(int code, String whitespace) {
return whitespace.contains(String.valueOf((char) code));
}
private static final Pattern spaceRegex = Pattern.compile("\\s+");
public static CharSequence getPreviousWord(InputConnection connection,
String sentenceSeperators) {
//TODO: Should fix this. This could be slow!
CharSequence prev = connection.getTextBeforeCursor(LOOKBACK_CHARACTER_NUM, 0);
if (prev == null) {
return null;
}
String[] w = spaceRegex.split(prev);
if (w.length >= 2 && w[w.length-2].length() > 0) {
char lastChar = w[w.length-2].charAt(w[w.length-2].length() -1);
if (sentenceSeperators.contains(String.valueOf(lastChar))) {
return null;
}
return w[w.length-2];
} else {
return null;
}
}
public static class SelectedWord {
public int start;
public int end;
public CharSequence word;
}
/**
* Takes a character sequence with a single character and checks if the character occurs
* in a list of word separators or is empty.
* @param singleChar A CharSequence with null, zero or one character
* @param wordSeparators A String containing the word separators
* @return true if the character is at a word boundary, false otherwise
*/
private static boolean isWordBoundary(CharSequence singleChar, String wordSeparators) {
return TextUtils.isEmpty(singleChar) || wordSeparators.contains(singleChar);
}
/**
* Checks if the cursor is inside a word or the current selection is a whole word.
* @param ic the InputConnection for accessing the text field
* @param selStart the start position of the selection within the text field
* @param selEnd the end position of the selection within the text field. This could be
* the same as selStart, if there's no selection.
* @param wordSeparators the word separator characters for the current language
* @return an object containing the text and coordinates of the selected/touching word,
* null if the selection/cursor is not marking a whole word.
*/
public static SelectedWord getWordAtCursorOrSelection(final InputConnection ic,
int selStart, int selEnd, String wordSeparators) {
if (selStart == selEnd) {
// There is just a cursor, so get the word at the cursor
EditingUtil.Range range = new EditingUtil.Range();
CharSequence touching = getWordAtCursor(ic, wordSeparators, range);
if (!TextUtils.isEmpty(touching)) {
SelectedWord selWord = new SelectedWord();
selWord.word = touching;
selWord.start = selStart - range.charsBefore;
selWord.end = selEnd + range.charsAfter;
return selWord;
}
} else {
// Is the previous character empty or a word separator? If not, return null.
CharSequence charsBefore = ic.getTextBeforeCursor(1, 0);
if (!isWordBoundary(charsBefore, wordSeparators)) {
return null;
}
// Is the next character empty or a word separator? If not, return null.
CharSequence charsAfter = ic.getTextAfterCursor(1, 0);
if (!isWordBoundary(charsAfter, wordSeparators)) {
return null;
}
// Extract the selection alone
CharSequence touching = getSelectedText(ic, selStart, selEnd);
if (TextUtils.isEmpty(touching)) return null;
// Is any part of the selection a separator? If so, return null.
final int length = touching.length();
for (int i = 0; i < length; i++) {
if (wordSeparators.contains(touching.subSequence(i, i + 1))) {
return null;
}
}
// Prepare the selected word
SelectedWord selWord = new SelectedWord();
selWord.start = selStart;
selWord.end = selEnd;
selWord.word = touching;
return selWord;
}
return null;
}
/**
* Cache method pointers for performance
*/
private static void initializeMethodsForReflection() {
try {
// These will either both exist or not, so no need for separate try/catch blocks.
// If other methods are added later, use separate try/catch blocks.
sMethodGetSelectedText = InputConnection.class.getMethod("getSelectedText", int.class);
sMethodSetComposingRegion = InputConnection.class.getMethod("setComposingRegion",
int.class, int.class);
} catch (NoSuchMethodException exc) {
// Ignore
}
sMethodsInitialized = true;
}
/**
* Returns the selected text between the selStart and selEnd positions.
*/
private static CharSequence getSelectedText(InputConnection ic, int selStart, int selEnd) {
// Use reflection, for backward compatibility
CharSequence result = null;
if (!sMethodsInitialized) {
initializeMethodsForReflection();
}
if (sMethodGetSelectedText != null) {
try {
result = (CharSequence) sMethodGetSelectedText.invoke(ic, 0);
return result;
} catch (InvocationTargetException exc) {
// Ignore
} catch (IllegalArgumentException e) {
// Ignore
} catch (IllegalAccessException e) {
// Ignore
}
}
// Reflection didn't work, try it the poor way, by moving the cursor to the start,
// getting the text after the cursor and moving the text back to selected mode.
// TODO: Verify that this works properly in conjunction with
// LatinIME#onUpdateSelection
ic.setSelection(selStart, selEnd);
result = ic.getTextAfterCursor(selEnd - selStart, 0);
ic.setSelection(selStart, selEnd);
return result;
}
/**
* Tries to set the text into composition mode if there is support for it in the framework.
*/
public static void underlineWord(InputConnection ic, SelectedWord word) {
// Use reflection, for backward compatibility
// If method not found, there's nothing we can do. It still works but just wont underline
// the word.
if (!sMethodsInitialized) {
initializeMethodsForReflection();
}
if (sMethodSetComposingRegion != null) {
try {
sMethodSetComposingRegion.invoke(ic, word.start, word.end);
} catch (InvocationTargetException exc) {
// Ignore
} catch (IllegalArgumentException e) {
// Ignore
} catch (IllegalAccessException e) {
// Ignore
}
}
}
}
| Java |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.pocketworkstation.pckeyboard;
import org.pocketworkstation.pckeyboard.Dictionary.DataType;
import android.content.Context;
import android.content.SharedPreferences;
import java.util.List;
public class LatinImeLogger implements SharedPreferences.OnSharedPreferenceChangeListener {
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
}
public static void init(Context context) {
}
public static void commit() {
}
public static void onDestroy() {
}
public static void logOnManualSuggestion(
String before, String after, int position, List<CharSequence> suggestions) {
}
public static void logOnAutoSuggestion(String before, String after) {
}
public static void logOnAutoSuggestionCanceled() {
}
public static void logOnDelete() {
}
public static void logOnInputChar() {
}
public static void logOnException(String metaData, Throwable e) {
}
public static void logOnWarning(String warning) {
}
public static void onStartSuggestion(CharSequence previousWords) {
}
public static void onAddSuggestedWord(String word, int typeId, DataType dataType) {
}
public static void onSetKeyboard(Keyboard kb) {
}
}
| Java |
package org.pocketworkstation.pckeyboard;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
/**
* Variant of SeekBarPreference that stores values as string preferences.
*
* This is for compatibility with existing preferences, switching types
* leads to runtime errors when upgrading or downgrading.
*/
public class SeekBarPreferenceString extends SeekBarPreference {
private static Pattern FLOAT_RE = Pattern.compile("(\\d+\\.?\\d*).*");
public SeekBarPreferenceString(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
// Some saved preferences from old versions have " ms" or "%" suffix, remove that.
private float floatFromString(String pref) {
Matcher num = FLOAT_RE.matcher(pref);
if (!num.matches()) return 0.0f;
return Float.valueOf(num.group(1));
}
@Override
protected Float onGetDefaultValue(TypedArray a, int index) {
return floatFromString(a.getString(index));
}
@Override
protected void onSetInitialValue(boolean restorePersistedValue, Object defaultValue) {
if (restorePersistedValue) {
setVal(floatFromString(getPersistedString("0.0")));
} else {
setVal(Float.valueOf((Float) defaultValue));
}
savePrevVal();
}
@Override
protected void onDialogClosed(boolean positiveResult) {
if (!positiveResult) {
restoreVal();
return;
}
if (shouldPersist()) {
savePrevVal();
persistString(getValString());
}
notifyChanged();
}
} | Java |
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.content.res.XmlResourceParser;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.text.TextPaint;
import android.util.Log;
import android.view.ViewConfiguration;
import android.view.inputmethod.EditorInfo;
import java.util.List;
import java.util.Locale;
public class LatinKeyboard extends Keyboard {
private static final boolean DEBUG_PREFERRED_LETTER = true;
private static final String TAG = "PCKeyboardLK";
private static final int OPACITY_FULLY_OPAQUE = 255;
private static final int SPACE_LED_LENGTH_PERCENT = 80;
private Drawable mShiftLockIcon;
private Drawable mShiftLockPreviewIcon;
private Drawable mOldShiftIcon;
private Drawable mSpaceIcon;
private Drawable mSpaceAutoCompletionIndicator;
private Drawable mSpacePreviewIcon;
private Drawable mMicIcon;
private Drawable mMicPreviewIcon;
private Drawable mSettingsIcon;
private Drawable mSettingsPreviewIcon;
private Drawable m123MicIcon;
private Drawable m123MicPreviewIcon;
private final Drawable mButtonArrowLeftIcon;
private final Drawable mButtonArrowRightIcon;
private Key mShiftKey;
private Key mEnterKey;
private Key mF1Key;
private final Drawable mHintIcon;
private Key mSpaceKey;
private Key m123Key;
private final int[] mSpaceKeyIndexArray;
private int mSpaceDragStartX;
private int mSpaceDragLastDiff;
private Locale mLocale;
private LanguageSwitcher mLanguageSwitcher;
private final Resources mRes;
private final Context mContext;
private int mMode;
// Whether this keyboard has voice icon on it
private boolean mHasVoiceButton;
// Whether voice icon is enabled at all
private boolean mVoiceEnabled;
private final boolean mIsAlphaKeyboard;
private final boolean mIsAlphaFullKeyboard;
private final boolean mIsFnFullKeyboard;
private CharSequence m123Label;
private boolean mCurrentlyInSpace;
private SlidingLocaleDrawable mSlidingLocaleIcon;
private int[] mPrefLetterFrequencies;
private int mPrefLetter;
private int mPrefLetterX;
private int mPrefLetterY;
private int mPrefDistance;
private int mExtensionResId;
// TODO: remove this attribute when either Keyboard.mDefaultVerticalGap or Key.parent becomes
// non-private.
private final int mVerticalGap;
private LatinKeyboard mExtensionKeyboard;
private static final float SPACEBAR_DRAG_THRESHOLD = 0.51f;
private static final float OVERLAP_PERCENTAGE_LOW_PROB = 0.70f;
private static final float OVERLAP_PERCENTAGE_HIGH_PROB = 0.85f;
// Minimum width of space key preview (proportional to keyboard width)
private static final float SPACEBAR_POPUP_MIN_RATIO = 0.4f;
// Minimum width of space key preview (proportional to screen height)
private static final float SPACEBAR_POPUP_MAX_RATIO = 0.4f;
// Height in space key the language name will be drawn. (proportional to space key height)
private static final float SPACEBAR_LANGUAGE_BASELINE = 0.6f;
// If the full language name needs to be smaller than this value to be drawn on space key,
// its short language name will be used instead.
private static final float MINIMUM_SCALE_OF_LANGUAGE_NAME = 0.8f;
private static int sSpacebarVerticalCorrection;
public LatinKeyboard(Context context, int xmlLayoutResId) {
this(context, xmlLayoutResId, 0, 0);
}
public LatinKeyboard(Context context, int xmlLayoutResId, int mode, float kbHeightPercent) {
super(context, 0, xmlLayoutResId, mode, kbHeightPercent);
final Resources res = context.getResources();
//Log.i("PCKeyboard", "keyHeight=" + this.getKeyHeight());
//this.setKeyHeight(30); // is useless, see http://code.google.com/p/android/issues/detail?id=4532
mContext = context;
mMode = mode;
mRes = res;
mShiftLockIcon = res.getDrawable(R.drawable.sym_keyboard_shift_locked);
mShiftLockPreviewIcon = res.getDrawable(R.drawable.sym_keyboard_feedback_shift_locked);
setDefaultBounds(mShiftLockPreviewIcon);
mSpaceIcon = res.getDrawable(R.drawable.sym_keyboard_space);
mSpaceAutoCompletionIndicator = res.getDrawable(R.drawable.sym_keyboard_space_led);
mSpacePreviewIcon = res.getDrawable(R.drawable.sym_keyboard_feedback_space);
mMicIcon = res.getDrawable(R.drawable.sym_keyboard_mic);
mMicPreviewIcon = res.getDrawable(R.drawable.sym_keyboard_feedback_mic);
mSettingsIcon = res.getDrawable(R.drawable.sym_keyboard_settings);
mSettingsPreviewIcon = res.getDrawable(R.drawable.sym_keyboard_feedback_settings);
setDefaultBounds(mMicPreviewIcon);
mButtonArrowLeftIcon = res.getDrawable(R.drawable.sym_keyboard_language_arrows_left);
mButtonArrowRightIcon = res.getDrawable(R.drawable.sym_keyboard_language_arrows_right);
m123MicIcon = res.getDrawable(R.drawable.sym_keyboard_123_mic);
m123MicPreviewIcon = res.getDrawable(R.drawable.sym_keyboard_feedback_123_mic);
mHintIcon = res.getDrawable(R.drawable.hint_popup);
setDefaultBounds(m123MicPreviewIcon);
sSpacebarVerticalCorrection = res.getDimensionPixelOffset(
R.dimen.spacebar_vertical_correction);
mIsAlphaKeyboard = xmlLayoutResId == R.xml.kbd_qwerty;
mIsAlphaFullKeyboard = xmlLayoutResId == R.xml.kbd_full;
mIsFnFullKeyboard = xmlLayoutResId == R.xml.kbd_full_fn || 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;
}
}
}
| Java |
/*
* Copyright (C) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import org.pocketworkstation.pckeyboard.Keyboard.Key;
import java.util.Arrays;
import java.util.List;
abstract class KeyDetector {
protected Keyboard mKeyboard;
private Key[] mKeys;
protected int mCorrectionX;
protected int mCorrectionY;
protected boolean mProximityCorrectOn;
protected int mProximityThresholdSquare;
public Key[] setKeyboard(Keyboard keyboard, float correctionX, float correctionY) {
if (keyboard == null)
throw new NullPointerException();
mCorrectionX = (int)correctionX;
mCorrectionY = (int)correctionY;
mKeyboard = keyboard;
List<Key> keys = mKeyboard.getKeys();
Key[] array = keys.toArray(new Key[keys.size()]);
mKeys = array;
return array;
}
protected int getTouchX(int x) {
return x + mCorrectionX;
}
protected int getTouchY(int y) {
return y + mCorrectionY;
}
protected Key[] getKeys() {
if (mKeys == null)
throw new IllegalStateException("keyboard isn't set");
// mKeyboard is guaranteed not to be null at setKeybaord() method if mKeys is not null
return mKeys;
}
public void setProximityCorrectionEnabled(boolean enabled) {
mProximityCorrectOn = enabled;
}
public boolean isProximityCorrectionEnabled() {
return mProximityCorrectOn;
}
public void setProximityThreshold(int threshold) {
mProximityThresholdSquare = threshold * threshold;
}
/**
* Allocates array that can hold all key indices returned by {@link #getKeyIndexAndNearbyCodes}
* method. The maximum size of the array should be computed by {@link #getMaxNearbyKeys}.
*
* @return Allocates and returns an array that can hold all key indices returned by
* {@link #getKeyIndexAndNearbyCodes} method. All elements in the returned array are
* initialized by {@link org.pocketworkstation.pckeyboard.LatinKeyboardView.NOT_A_KEY}
* value.
*/
public int[] newCodeArray() {
int[] codes = new int[getMaxNearbyKeys()];
Arrays.fill(codes, LatinKeyboardBaseView.NOT_A_KEY);
return codes;
}
/**
* Computes maximum size of the array that can contain all nearby key indices returned by
* {@link #getKeyIndexAndNearbyCodes}.
*
* @return Returns maximum size of the array that can contain all nearby key indices returned
* by {@link #getKeyIndexAndNearbyCodes}.
*/
abstract protected int getMaxNearbyKeys();
/**
* Finds all possible nearby key indices around a touch event point and returns the nearest key
* index. The algorithm to determine the nearby keys depends on the threshold set by
* {@link #setProximityThreshold(int)} and the mode set by
* {@link #setProximityCorrectionEnabled(boolean)}.
*
* @param x The x-coordinate of a touch point
* @param y The y-coordinate of a touch point
* @param allKeys All nearby key indices are returned in this array
* @return The nearest key index
*/
abstract public int getKeyIndexAndNearbyCodes(int x, int y, int[] allKeys);
}
| Java |
/*
* Copyright (C) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
class ModifierKeyState {
private static final int RELEASING = 0;
private static final int PRESSING = 1;
private static final int 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;
}
}
| Java |
/*
* Copyright (C) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import java.util.ArrayList;
import java.util.List;
import org.pocketworkstation.pckeyboard.LatinKeyboardBaseView.OnKeyboardActionListener;
import org.pocketworkstation.pckeyboard.LatinKeyboardBaseView.UIHandler;
import android.content.res.Resources;
import org.pocketworkstation.pckeyboard.Keyboard.Key;
import android.util.Log;
import android.view.MotionEvent;
public class PointerTracker {
private static final String TAG = "PointerTracker";
private static final boolean DEBUG = false;
private static final boolean DEBUG_MOVE = false;
public interface UIProxy {
public void invalidateKey(Key key);
public void showPreview(int keyIndex, PointerTracker tracker);
public boolean hasDistinctMultitouch();
}
public final int mPointerId;
// Timing constants
private final int mDelayBeforeKeyRepeatStart;
private final int mMultiTapKeyTimeout;
// Miscellaneous constants
private static final int NOT_A_KEY = LatinKeyboardBaseView.NOT_A_KEY;
private static final int[] KEY_DELETE = { Keyboard.KEYCODE_DELETE };
private final UIProxy mProxy;
private final UIHandler mHandler;
private final KeyDetector mKeyDetector;
private OnKeyboardActionListener mListener;
private final KeyboardSwitcher mKeyboardSwitcher;
private final boolean mHasDistinctMultitouch;
private Key[] mKeys;
private int mKeyHysteresisDistanceSquared = -1;
private final KeyState mKeyState;
// true if keyboard layout has been changed.
private boolean mKeyboardLayoutHasBeenChanged;
// true if event is already translated to a key action (long press or mini-keyboard)
private boolean mKeyAlreadyProcessed;
// true if this pointer is repeatable key
private boolean mIsRepeatableKey;
// true if this pointer is in sliding key input
private boolean mIsInSlidingKeyInput;
// For multi-tap
private int mLastSentIndex;
private int mTapCount;
private long mLastTapTime;
private boolean mInMultiTap;
private final StringBuilder mPreviewLabel = new StringBuilder(1);
// pressed key
private int mPreviousKey = NOT_A_KEY;
private static boolean sSlideKeyHack;
private static List<Key> sSlideKeys = new ArrayList<Key>(10);
// This class keeps track of a key index and a position where this pointer is.
private static class KeyState {
private final KeyDetector mKeyDetector;
// The position and time at which first down event occurred.
private int mStartX;
private int mStartY;
private long mDownTime;
// The current key index where this pointer is.
private int mKeyIndex = NOT_A_KEY;
// The position where mKeyIndex was recognized for the first time.
private int mKeyX;
private int mKeyY;
// Last pointer position.
private int mLastX;
private int mLastY;
public KeyState(KeyDetector keyDetecor) {
mKeyDetector = keyDetecor;
}
public int getKeyIndex() {
return mKeyIndex;
}
public int getKeyX() {
return mKeyX;
}
public int getKeyY() {
return mKeyY;
}
public int getStartX() {
return mStartX;
}
public int getStartY() {
return mStartY;
}
public long getDownTime() {
return mDownTime;
}
public int getLastX() {
return mLastX;
}
public int getLastY() {
return mLastY;
}
public int onDownKey(int x, int y, long eventTime) {
mStartX = x;
mStartY = y;
mDownTime = eventTime;
return onMoveToNewKey(onMoveKeyInternal(x, y), x, y);
}
private int onMoveKeyInternal(int x, int y) {
mLastX = x;
mLastY = y;
return mKeyDetector.getKeyIndexAndNearbyCodes(x, y, null);
}
public int onMoveKey(int x, int y) {
return onMoveKeyInternal(x, y);
}
public int onMoveToNewKey(int keyIndex, int x, int y) {
mKeyIndex = keyIndex;
mKeyX = x;
mKeyY = y;
return keyIndex;
}
public int onUpKey(int x, int y) {
return onMoveKeyInternal(x, y);
}
}
public PointerTracker(int id, UIHandler handler, KeyDetector keyDetector, UIProxy proxy,
Resources res, boolean slideKeyHack) {
if (proxy == null || handler == null || keyDetector == null)
throw new NullPointerException();
mPointerId = id;
mProxy = proxy;
mHandler = handler;
mKeyDetector = keyDetector;
mKeyboardSwitcher = KeyboardSwitcher.getInstance();
mKeyState = new KeyState(keyDetector);
mHasDistinctMultitouch = proxy.hasDistinctMultitouch();
mDelayBeforeKeyRepeatStart = res.getInteger(R.integer.config_delay_before_key_repeat_start);
mMultiTapKeyTimeout = res.getInteger(R.integer.config_multi_tap_key_timeout);
sSlideKeyHack = slideKeyHack;
resetMultiTap();
}
public void setOnKeyboardActionListener(OnKeyboardActionListener listener) {
mListener = listener;
}
public void setKeyboard(Key[] keys, float keyHysteresisDistance) {
if (keys == null || keyHysteresisDistance < 0)
throw new IllegalArgumentException();
mKeys = keys;
mKeyHysteresisDistanceSquared = (int)(keyHysteresisDistance * keyHysteresisDistance);
// Mark that keyboard layout has been changed.
mKeyboardLayoutHasBeenChanged = true;
}
public boolean isInSlidingKeyInput() {
return mIsInSlidingKeyInput;
}
public void setSlidingKeyInputState(boolean state) {
mIsInSlidingKeyInput = state;
}
private boolean isValidKeyIndex(int keyIndex) {
return keyIndex >= 0 && keyIndex < mKeys.length;
}
public Key getKey(int keyIndex) {
return isValidKeyIndex(keyIndex) ? mKeys[keyIndex] : null;
}
private boolean isModifierInternal(int keyIndex) {
Key key = getKey(keyIndex);
if (key == null || key.codes == null)
return false;
int primaryCode = key.codes[0];
return primaryCode == Keyboard.KEYCODE_SHIFT
|| primaryCode == Keyboard.KEYCODE_MODE_CHANGE
|| primaryCode == LatinKeyboardView.KEYCODE_CTRL_LEFT
|| primaryCode == LatinKeyboardView.KEYCODE_ALT_LEFT
|| primaryCode == LatinKeyboardView.KEYCODE_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" : "")));
}
}
| Java |
/*
* Copyright (C) 2011 Darren Salt
*
* Licensed under the Apache License, Version 2.0 (the "Licence"); you may
* not use this file except in compliance with the Licence. You may obtain
* a copy of the Licence at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the Licence is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* Licence for the specific language governing permissions and limitations
* under the Licence.
*/
package org.pocketworkstation.pckeyboard;
import java.text.Normalizer;
import android.util.Log;
public class DeadAccentSequence extends ComposeBase {
private static final String TAG = "HK/DeadAccent";
public DeadAccentSequence(ComposeSequencing user) {
init(user);
}
private static void putAccent(String nonSpacing, String spacing, String ascii) {
if (ascii == null) ascii = spacing;
put("" + nonSpacing + " ", ascii);
put(nonSpacing + nonSpacing, spacing);
put(Keyboard.DEAD_KEY_PLACEHOLDER + nonSpacing, spacing);
}
public static String getSpacing(char nonSpacing) {
String spacing = get("" + Keyboard.DEAD_KEY_PLACEHOLDER + nonSpacing);
if (spacing == null) spacing = DeadAccentSequence.normalize(" " + nonSpacing);
if (spacing == null) return "" + nonSpacing;
return spacing;
}
static {
// space + combining diacritical
// cf. http://unicode.org/charts/PDF/U0300.pdf
putAccent("\u0300", "\u02cb", "`"); // grave
putAccent("\u0301", "\u02ca", "´"); // acute
putAccent("\u0302", "\u02c6", "^"); // circumflex
putAccent("\u0303", "\u02dc", "~"); // small tilde
putAccent("\u0304", "\u02c9", "¯"); // macron
putAccent("\u0305", "\u00af", "¯"); // overline
putAccent("\u0306", "\u02d8", null); // breve
putAccent("\u0307", "\u02d9", null); // dot above
putAccent("\u0308", "\u00a8", "¨"); // diaeresis
putAccent("\u0309", "\u02c0", null); // hook above
putAccent("\u030a", "\u02da", "°"); // ring above
putAccent("\u030b", "\u02dd", "\""); // double acute
putAccent("\u030c", "\u02c7", null); // caron
putAccent("\u030d", "\u02c8", null); // vertical line above
putAccent("\u030e", "\"", "\""); // double vertical line above
putAccent("\u0313", "\u02bc", null); // comma above
putAccent("\u0314", "\u02bd", null); // reversed comma above
put("\u0308\u0301\u03b9", "\u0390"); // Greek Dialytika+Tonos, iota
put("\u0301\u0308\u03b9", "\u0390"); // Greek Dialytika+Tonos, iota
put("\u0301\u03ca", "\u0390"); // Greek Dialytika+Tonos, iota
put("\u0308\u0301\u03c5", "\u03b0"); // Greek Dialytika+Tonos, upsilon
put("\u0301\u0308\u03c5", "\u03b0"); // Greek Dialytika+Tonos, upsilon
put("\u0301\u03cb", "\u03b0"); // Greek Dialytika+Tonos, upsilon
/*
// include?
put("̃ ", "~");
put("̃̃", "~");
put("́ ", "'");
put("́́", "´");
put("̀ ", "`");
put("̀̀", "`");
put("̂ ", "^");
put("̂̂", "^");
put("̊ ", "°");
put("̊̊", "°");
put("̄ ", "¯");
put("̄̄", "¯");
put("̆ ", "˘");
put("̆̆", "˘");
put("̇ ", "˙");
put("̇̇", "˙");
put("̈̈", "¨");
put("̈ ", "\"");
put("̋ ", "˝");
put("̋̋", "˝");
put("̌ ", "ˇ");
put("̌̌", "ˇ");
put("̧ ", "¸");
put("̧̧", "¸");
put("̨ ", "˛");
put("̨̨", "˛");
put("̂2", "²");
put("̂3", "³");
put("̂1", "¹");
// include end?
put("̀A", "À");
put("́A", "Á");
put("̂A", "Â");
put("̃A", "Ã");
put("̈A", "Ä");
put("̊A", "Å");
put("̧C", "Ç");
put("̀E", "È");
put("́E", "É");
put("̂E", "Ê");
put("̈E", "Ë");
put("̀I", "Ì");
put("́I", "Í");
put("̂I", "Î");
put("̈I", "Ï");
put("̃N", "Ñ");
put("̀O", "Ò");
put("́O", "Ó");
put("̂O", "Ô");
put("̃O", "Õ");
put("̈O", "Ö");
put("̀U", "Ù");
put("́U", "Ú");
put("̂U", "Û");
put("̈U", "Ü");
put("́Y", "Ý");
put("̀a", "à");
put("́a", "á");
put("̂a", "â");
put("̃a", "ã");
put("̈a", "ä");
put("̊a", "å");
put("̧c", "ç");
put("̀e", "è");
put("́e", "é");
put("̂e", "ê");
put("̈e", "ë");
put("̀i", "ì");
put("́i", "í");
put("̂i", "î");
put("̈i", "ï");
put("̃n", "ñ");
put("̀o", "ò");
put("́o", "ó");
put("̂o", "ô");
put("̃o", "õ");
put("̈o", "ö");
put("̀u", "ù");
put("́u", "ú");
put("̂u", "û");
put("̈u", "ü");
put("́y", "ý");
put("̈y", "ÿ");
put("̄A", "Ā");
put("̄a", "ā");
put("̆A", "Ă");
put("̆a", "ă");
put("̨A", "Ą");
put("̨a", "ą");
put("́C", "Ć");
put("́c", "ć");
put("̂C", "Ĉ");
put("̂c", "ĉ");
put("̇C", "Ċ");
put("̇c", "ċ");
put("̌C", "Č");
put("̌c", "č");
put("̌D", "Ď");
put("̌d", "ď");
put("̄E", "Ē");
put("̄e", "ē");
put("̆E", "Ĕ");
put("̆e", "ĕ");
put("̇E", "Ė");
put("̇e", "ė");
put("̨E", "Ę");
put("̨e", "ę");
put("̌E", "Ě");
put("̌e", "ě");
put("̂G", "Ĝ");
put("̂g", "ĝ");
put("̆G", "Ğ");
put("̆g", "ğ");
put("̇G", "Ġ");
put("̇g", "ġ");
put("̧G", "Ģ");
put("̧g", "ģ");
put("̂H", "Ĥ");
put("̂h", "ĥ");
put("̃I", "Ĩ");
put("̃i", "ĩ");
put("̄I", "Ī");
put("̄i", "ī");
put("̆I", "Ĭ");
put("̆i", "ĭ");
put("̨I", "Į");
put("̨i", "į");
put("̇I", "İ");
put("̇i", "ı");
put("̂J", "Ĵ");
put("̂j", "ĵ");
put("̧K", "Ķ");
put("̧k", "ķ");
put("́L", "Ĺ");
put("́l", "ĺ");
put("̧L", "Ļ");
put("̧l", "ļ");
put("̌L", "Ľ");
put("̌l", "ľ");
put("́N", "Ń");
put("́n", "ń");
put("̧N", "Ņ");
put("̧n", "ņ");
put("̌N", "Ň");
put("̌n", "ň");
put("̄O", "Ō");
put("̄o", "ō");
put("̆O", "Ŏ");
put("̆o", "ŏ");
put("̋O", "Ő");
put("̋o", "ő");
put("́R", "Ŕ");
put("́r", "ŕ");
put("̧R", "Ŗ");
put("̧r", "ŗ");
put("̌R", "Ř");
put("̌r", "ř");
put("́S", "Ś");
put("́s", "ś");
put("̂S", "Ŝ");
put("̂s", "ŝ");
put("̧S", "Ş");
put("̧s", "ş");
put("̌S", "Š");
put("̌s", "š");
put("̧T", "Ţ");
put("̧t", "ţ");
put("̌T", "Ť");
put("̌t", "ť");
put("̃U", "Ũ");
put("̃u", "ũ");
put("̄U", "Ū");
put("̄u", "ū");
put("̆U", "Ŭ");
put("̆u", "ŭ");
put("̊U", "Ů");
put("̊u", "ů");
put("̋U", "Ű");
put("̋u", "ű");
put("̨U", "Ų");
put("̨u", "ų");
put("̂W", "Ŵ");
put("̂w", "ŵ");
put("̂Y", "Ŷ");
put("̂y", "ŷ");
put("̈Y", "Ÿ");
put("́Z", "Ź");
put("́z", "ź");
put("̇Z", "Ż");
put("̇z", "ż");
put("̌Z", "Ž");
put("̌z", "ž");
put("̛O", "Ơ");
put("̛o", "ơ");
put("̛U", "Ư");
put("̛u", "ư");
put("̌A", "Ǎ");
put("̌a", "ǎ");
put("̌I", "Ǐ");
put("̌i", "ǐ");
put("̌O", "Ǒ");
put("̌o", "ǒ");
put("̌U", "Ǔ");
put("̌u", "ǔ");
put("̄Ü", "Ǖ");
put("̄̈U", "Ǖ");
put("̄ü", "ǖ");
put("̄̈u", "ǖ");
put("́Ü", "Ǘ");
put("́̈U", "Ǘ");
put("́ü", "ǘ");
put("́̈u", "ǘ");
put("̌Ü", "Ǚ");
put("̌̈U", "Ǚ");
put("̌ü", "ǚ");
put("̌̈u", "ǚ");
put("̀Ü", "Ǜ");
put("̀̈U", "Ǜ");
put("̀ü", "ǜ");
put("̀̈u", "ǜ");
put("̄Ä", "Ǟ");
put("̄̈A", "Ǟ");
put("̄ä", "ǟ");
put("̄̈a", "ǟ");
put("̄Ȧ", "Ǡ");
put("̄̇A", "Ǡ");
put("̄ȧ", "ǡ");
put("̄̇a", "ǡ");
put("̄Æ", "Ǣ");
put("̄æ", "ǣ");
put("̌G", "Ǧ");
put("̌g", "ǧ");
put("̌K", "Ǩ");
put("̌k", "ǩ");
put("̨O", "Ǫ");
put("̨o", "ǫ");
put("̄Ǫ", "Ǭ");
put("̨̄O", "Ǭ");
put("̄ǫ", "ǭ");
put("̨̄o", "ǭ");
put("̌Ʒ", "Ǯ");
put("̌ʒ", "ǯ");
put("̌j", "ǰ");
put("́G", "Ǵ");
put("́g", "ǵ");
put("̀N", "Ǹ");
put("̀n", "ǹ");
put("́Å", "Ǻ");
put("́̊A", "Ǻ");
put("́å", "ǻ");
put("́̊a", "ǻ");
put("́Æ", "Ǽ");
put("́æ", "ǽ");
put("́Ø", "Ǿ");
put("́ø", "ǿ");
put("̏A", "Ȁ");
put("̏a", "ȁ");
put("̑A", "Ȃ");
put("̑a", "ȃ");
put("̏E", "Ȅ");
put("̏e", "ȅ");
put("̑E", "Ȇ");
put("̑e", "ȇ");
put("̏I", "Ȉ");
put("̏i", "ȉ");
put("̑I", "Ȋ");
put("̑i", "ȋ");
put("̏O", "Ȍ");
put("̏o", "ȍ");
put("̑O", "Ȏ");
put("̑o", "ȏ");
put("̏R", "Ȑ");
put("̏r", "ȑ");
put("̑R", "Ȓ");
put("̑r", "ȓ");
put("̏U", "Ȕ");
put("̏u", "ȕ");
put("̑U", "Ȗ");
put("̑u", "ȗ");
put("̌H", "Ȟ");
put("̌h", "ȟ");
put("̇A", "Ȧ");
put("̇a", "ȧ");
put("̧E", "Ȩ");
put("̧e", "ȩ");
put("̄Ö", "Ȫ");
put("̄̈O", "Ȫ");
put("̄ö", "ȫ");
put("̄̈o", "ȫ");
put("̄Õ", "Ȭ");
put("̄ ̃O", "Ȭ");
put("̄õ", "ȭ");
put("̄ ̃o", "ȭ");
put("̇O", "Ȯ");
put("̇o", "ȯ");
put("̄Ȯ", "Ȱ");
put("̄̇O", "Ȱ");
put("̄ȯ", "ȱ");
put("̄̇o", "ȱ");
put("̄Y", "Ȳ");
put("̄y", "ȳ");
put("̥A", "Ḁ");
put("̥a", "ḁ");
put("̇B", "Ḃ");
put("̇b", "ḃ");
put("̣B", "Ḅ");
put("̣b", "ḅ");
put("̱B", "Ḇ");
put("̱b", "ḇ");
put("́Ç", "Ḉ");
put("̧́C", "Ḉ");
put("́ç", "ḉ");
put("̧́c", "ḉ");
put("̇D", "Ḋ");
put("̇d", "ḋ");
put("̣D", "Ḍ");
put("̣d", "ḍ");
put("̱D", "Ḏ");
put("̱d", "ḏ");
put("̧D", "Ḑ");
put("̧d", "ḑ");
put("̭D", "Ḓ");
put("̭d", "ḓ");
put("̀Ē", "Ḕ");
put("̀ ̄E", "Ḕ");
put("̀ē", "ḕ");
put("̀ ̄e", "ḕ");
put("́Ē", "Ḗ");
put("́ ̄E", "Ḗ");
put("́ē", "ḗ");
put("́ ̄e", "ḗ");
put("̭E", "Ḙ");
put("̭e", "ḙ");
put("̰E", "Ḛ");
put("̰e", "ḛ");
put("̆Ȩ", "Ḝ");
put("̧̆E", "Ḝ");
put("̆ȩ", "ḝ");
put("̧̆e", "ḝ");
put("̇F", "Ḟ");
put("̇f", "ḟ");
put("̄G", "Ḡ");
put("̄g", "ḡ");
put("̇H", "Ḣ");
put("̇h", "ḣ");
put("̣H", "Ḥ");
put("̣h", "ḥ");
put("̈H", "Ḧ");
put("̈h", "ḧ");
put("̧H", "Ḩ");
put("̧h", "ḩ");
put("̮H", "Ḫ");
put("̮h", "ḫ");
put("̰I", "Ḭ");
put("̰i", "ḭ");
put("́Ï", "Ḯ");
put("́̈I", "Ḯ");
put("́ï", "ḯ");
put("́̈i", "ḯ");
put("́K", "Ḱ");
put("́k", "ḱ");
put("̣K", "Ḳ");
put("̣k", "ḳ");
put("̱K", "Ḵ");
put("̱k", "ḵ");
put("̣L", "Ḷ");
put("̣l", "ḷ");
put("̄Ḷ", "Ḹ");
put("̣̄L", "Ḹ");
put("̄ḷ", "ḹ");
put("̣̄l", "ḹ");
put("̱L", "Ḻ");
put("̱l", "ḻ");
put("̭L", "Ḽ");
put("̭l", "ḽ");
put("́M", "Ḿ");
put("́m", "ḿ");
put("̇M", "Ṁ");
put("̇m", "ṁ");
put("̣M", "Ṃ");
put("̣m", "ṃ");
put("̇N", "Ṅ");
put("̇n", "ṅ");
put("̣N", "Ṇ");
put("̣n", "ṇ");
put("̱N", "Ṉ");
put("̱n", "ṉ");
put("̭N", "Ṋ");
put("̭n", "ṋ");
put("́Õ", "Ṍ");
put("́ ̃O", "Ṍ");
put("́õ", "ṍ");
put("́ ̃o", "ṍ");
put("̈Õ", "Ṏ");
put("̈ ̃O", "Ṏ");
put("̈õ", "ṏ");
put("̈ ̃o", "ṏ");
put("̀Ō", "Ṑ");
put("̀ ̄O", "Ṑ");
put("̀ō", "ṑ");
put("̀ ̄o", "ṑ");
put("́Ō", "Ṓ");
put("́ ̄O", "Ṓ");
put("́ō", "ṓ");
put("́ ̄o", "ṓ");
put("́P", "Ṕ");
put("́p", "ṕ");
put("̇P", "Ṗ");
put("̇p", "ṗ");
put("̇R", "Ṙ");
put("̇r", "ṙ");
put("̣R", "Ṛ");
put("̣r", "ṛ");
put("̄Ṛ", "Ṝ");
put("̣̄R", "Ṝ");
put("̄ṛ", "ṝ");
put("̣̄r", "ṝ");
put("̱R", "Ṟ");
put("̱r", "ṟ");
put("̇S", "Ṡ");
put("̇s", "ṡ");
put("̣S", "Ṣ");
put("̣s", "ṣ");
put("̇Ś", "Ṥ");
put("̇ ́S", "Ṥ");
put("̇ś", "ṥ");
put("̇ ́s", "ṥ");
put("̇Š", "Ṧ");
put("̇̌S", "Ṧ");
put("̇š", "ṧ");
put("̇̌s", "ṧ");
put("̇Ṣ", "Ṩ");
put("̣̇S", "Ṩ");
put("̇ṣ", "ṩ");
put("̣̇s", "ṩ");
put("̇T", "Ṫ");
put("̇t", "ṫ");
put("̣T", "Ṭ");
put("̣t", "ṭ");
put("̱T", "Ṯ");
put("̱t", "ṯ");
put("̭T", "Ṱ");
put("̭t", "ṱ");
put("̤U", "Ṳ");
put("̤u", "ṳ");
put("̰U", "Ṵ");
put("̰u", "ṵ");
put("̭U", "Ṷ");
put("̭u", "ṷ");
put("́Ũ", "Ṹ");
put("́ ̃U", "Ṹ");
put("́ũ", "ṹ");
put("́ ̃u", "ṹ");
put("̈Ū", "Ṻ");
put("̈ ̄U", "Ṻ");
put("̈ū", "ṻ");
put("̈ ̄u", "ṻ");
put("̃V", "Ṽ");
put("̃v", "ṽ");
put("̣V", "Ṿ");
put("̣v", "ṿ");
put("̀W", "Ẁ");
put("̀w", "ẁ");
put("́W", "Ẃ");
put("́w", "ẃ");
put("̈W", "Ẅ");
put("̈w", "ẅ");
put("̇W", "Ẇ");
put("̇w", "ẇ");
put("̣W", "Ẉ");
put("̣w", "ẉ");
put("̇X", "Ẋ");
put("̇x", "ẋ");
put("̈X", "Ẍ");
put("̈x", "ẍ");
put("̇Y", "Ẏ");
put("̇y", "ẏ");
put("̂Z", "Ẑ");
put("̂z", "ẑ");
put("̣Z", "Ẓ");
put("̣z", "ẓ");
put("̱Z", "Ẕ");
put("̱z", "ẕ");
put("̱h", "ẖ");
put("̈t", "ẗ");
put("̊w", "ẘ");
put("̊y", "ẙ");
put("̇ſ", "ẛ");
put("̣A", "Ạ");
put("̣a", "ạ");
put("̉A", "Ả");
put("̉a", "ả");
put("́Â", "Ấ");
put("́ ̂A", "Ấ");
put("́â", "ấ");
put("́ ̂a", "ấ");
put("̀Â", "Ầ");
put("̀ ̂A", "Ầ");
put("̀â", "ầ");
put("̀ ̂a", "ầ");
put("̉Â", "Ẩ");
put("̉ ̂A", "Ẩ");
put("̉â", "ẩ");
put("̉ ̂a", "ẩ");
put("̃Â", "Ẫ");
put("̃ ̂A", "Ẫ");
put("̃â", "ẫ");
put("̃ ̂a", "ẫ");
put("̂Ạ", "Ậ");
put("̣̂A", "Ậ");
put("̣Â", "Ậ");
put("̂ạ", "ậ");
put("̣̂a", "ậ");
put("̣â", "ậ");
put("́Ă", "Ắ");
put("́̆A", "Ắ");
put("́ă", "ắ");
put("́̆a", "ắ");
put("̀Ă", "Ằ");
put("̀̆A", "Ằ");
put("̀ă", "ằ");
put("̀̆a", "ằ");
put("̉Ă", "Ẳ");
put("̉̆A", "Ẳ");
put("̉ă", "ẳ");
put("̉̆a", "ẳ");
put("̃Ă", "Ẵ");
put("̃̆A", "Ẵ");
put("̃ă", "ẵ");
put("̃̆a", "ẵ");
put("̆Ạ", "Ặ");
put("̣̆A", "Ặ");
put("̣Ă", "Ặ");
put("̆ạ", "ặ");
put("̣̆a", "ặ");
put("̣ă", "ặ");
put("̣E", "Ẹ");
put("̣e", "ẹ");
put("̉E", "Ẻ");
put("̉e", "ẻ");
put("̃E", "Ẽ");
put("̃e", "ẽ");
put("́Ê", "Ế");
put("́ ̂E", "Ế");
put("́ê", "ế");
put("́ ̂e", "ế");
put("̀Ê", "Ề");
put("̀ ̂E", "Ề");
put("̀ê", "ề");
put("̀ ̂e", "ề");
put("̉Ê", "Ể");
put("̉ ̂E", "Ể");
put("̉ê", "ể");
put("̉ ̂e", "ể");
put("̃Ê", "Ễ");
put("̃ ̂E", "Ễ");
put("̃ê", "ễ");
put("̃ ̂e", "ễ");
put("̂Ẹ", "Ệ");
put("̣̂E", "Ệ");
put("̣Ê", "Ệ");
put("̂ẹ", "ệ");
put("̣̂e", "ệ");
put("̣ê", "ệ");
put("̉I", "Ỉ");
put("̉i", "ỉ");
put("̣I", "Ị");
put("̣i", "ị");
put("̣O", "Ọ");
put("̣o", "ọ");
put("̉O", "Ỏ");
put("̉o", "ỏ");
put("́Ô", "Ố");
put("́ ̂O", "Ố");
put("́ô", "ố");
put("́ ̂o", "ố");
put("̀Ô", "Ồ");
put("̀ ̂O", "Ồ");
put("̀ô", "ồ");
put("̀ ̂o", "ồ");
put("̉Ô", "Ổ");
put("̉ ̂O", "Ổ");
put("̉ô", "ổ");
put("̉ ̂o", "ổ");
put("̃Ô", "Ỗ");
put("̃ ̂O", "Ỗ");
put("̃ô", "ỗ");
put("̃ ̂o", "ỗ");
put("̂Ọ", "Ộ");
put("̣̂O", "Ộ");
put("̣Ô", "Ộ");
put("̂ọ", "ộ");
put("̣̂o", "ộ");
put("̣ô", "ộ");
put("́Ơ", "Ớ");
put("̛́O", "Ớ");
put("́ơ", "ớ");
put("̛́o", "ớ");
put("̀Ơ", "Ờ");
put("̛̀O", "Ờ");
put("̀ơ", "ờ");
put("̛̀o", "ờ");
put("̉Ơ", "Ở");
put("̛̉O", "Ở");
put("̉ơ", "ở");
put("̛̉o", "ở");
put("̃Ơ", "Ỡ");
put("̛̃O", "Ỡ");
put("̃ơ", "ỡ");
put("̛̃o", "ỡ");
put("̣Ơ", "Ợ");
put("̛̣O", "Ợ");
put("̣ơ", "ợ");
put("̛̣o", "ợ");
put("̣U", "Ụ");
put("̣u", "ụ");
put("̉U", "Ủ");
put("̉u", "ủ");
put("́Ư", "Ứ");
put("̛́U", "Ứ");
put("́ư", "ứ");
put("̛́u", "ứ");
put("̀Ư", "Ừ");
put("̛̀U", "Ừ");
put("̀ư", "ừ");
put("̛̀u", "ừ");
put("̉Ư", "Ử");
put("̛̉U", "Ử");
put("̉ư", "ử");
put("̛̉u", "ử");
put("̃Ư", "Ữ");
put("̛̃U", "Ữ");
put("̃ư", "ữ");
put("̛̃u", "ữ");
put("̣Ư", "Ự");
put("̛̣U", "Ự");
put("̣ư", "ự");
put("̛̣u", "ự");
put("̀Y", "Ỳ");
put("̀y", "ỳ");
put("̣Y", "Ỵ");
put("̣y", "ỵ");
put("̉Y", "Ỷ");
put("̉y", "ỷ");
put("̃Y", "Ỹ");
put("̃y", "ỹ");
// include?
put("̂0", "⁰");
put("̂4", "⁴");
put("̂5", "⁵");
put("̂6", "⁶");
put("̂7", "⁷");
put("̂8", "⁸");
put("̂9", "⁹");
put("̂+", "⁺");
put("̂−", "⁻");
put("̂=", "⁼");
put("̂(", "⁽");
put("̂)", "⁾");
put("̣+", "⨥");
put("̰+", "⨦");
put("̣-", "⨪");
put("̣=", "⩦");
put("̤̈=", "⩷");
put("̤̈=", "⩷");
// include end?
put("̥|", "⫰");
put("̇Ā", "Ǡ");
put("̇ā", "ǡ");
put("̇j", "ȷ");
put("̇L", "Ŀ");
put("̇l", "ŀ");
put("̇Ō", "Ȱ");
put("̇ō", "ȱ");
put("́Ṡ", "Ṥ");
put("́ṡ", "ṥ");
put("́V", "Ǘ");
put("́v", "ǘ");
put("̣Ṡ", "Ṩ");
put("̣ṡ", "ṩ");
put("̣̣", "̣");
put("̣ ", "̣");
put("̆Á", "Ắ");
put("̆À", "Ằ");
put("̆Ả", "Ẳ");
put("̆Ã", "Ẵ");
put("̆a", "ắ");
put("̆à", "ằ");
put("̆ả", "ẳ");
put("̆ã", "ẵ");
// include?
put("̌(", "₍");
put("̌)", "₎");
put("̌+", "₊");
put("̌-", "₋");
put("̌0", "₀");
put("̌1", "₁");
put("̌2", "₂");
put("̌3", "₃");
put("̌4", "₄");
put("̌5", "₅");
put("̌6", "₆");
put("̌7", "₇");
put("̌8", "₈");
put("̌9", "₉");
put("̌=", "₌");
// include end?
put("̌Dz", "Dž");
put("̌Ṡ", "Ṧ");
put("̌ṡ", "ṧ");
put("̌V", "Ǚ");
put("̌v", "ǚ");
put("̧C", "Ḉ");
put("̧c", "ḉ");
put("̧¢", "₵");
put("̧Ĕ", "Ḝ");
put("̧ĕ", "ḝ");
put("̂-", "⁻");
put("̂Á", "Ấ");
put("̂À", "Ầ");
put("̂Ả", "Ẩ");
put("̂Ã", "Ẫ");
put("̂á", "ấ");
put("̂à", "ầ");
put("̂ả", "ẩ");
put("̂ã", "ẫ");
put("̂É", "Ế");
put("̂È", "Ề");
put("̂Ẻ", "Ể");
put("̂Ẽ", "Ễ");
put("̂é", "ế");
put("̂è", "ề");
put("̂ẻ", "ể");
put("̂ẽ", "ễ");
put("̂Ó", "Ố");
put("̂Ò", "Ồ");
put("̂Ỏ", "Ổ");
put("̂Õ", "Ỗ");
put("̂ó", "ố");
put("̂ò", "ồ");
put("̂ỏ", "ổ");
put("̂õ", "ỗ");
put("̦S", "Ș");
put("̦s", "ș");
put("̦T", "Ț");
put("̦t", "ț");
put("̦̦", ",");
put("̦ ", ",");
put("̈Ā", "Ǟ");
put("̈ā", "ǟ");
put("̈Í", "Ḯ");
put("̈í", "ḯ");
put("̈Ō", "Ȫ");
put("̈ō", "ȫ");
put("̈Ú", "Ǘ");
put("̈Ǔ", "Ǚ");
put("̈Ù", "Ǜ");
put("̈ú", "ǘ");
put("̈ǔ", "ǚ");
put("̈ù", "ǜ");
put("̀V", "Ǜ");
put("̀v", "ǜ");
put("̉B", "Ɓ");
put("̉b", "ɓ");
put("̉C", "Ƈ");
put("̉c", "ƈ");
put("̉D", "Ɗ");
put("̉d", "ɗ");
put("̉ɖ", "ᶑ");
put("̉F", "Ƒ");
put("̉f", "ƒ");
put("̉G", "Ɠ");
put("̉g", "ɠ");
put("̉h", "ɦ");
put("̉ɟ", "ʄ");
put("̉K", "Ƙ");
put("̉k", "ƙ");
put("̉M", "Ɱ");
put("̉m", "ɱ");
put("̉N", "Ɲ");
put("̉n", "ɲ");
put("̉P", "Ƥ");
put("̉p", "ƥ");
put("̉q", "ʠ");
put("̉ɜ", "ɝ");
put("̉s", "ʂ");
put("̉ə", "ɚ");
put("̉T", "Ƭ");
put("̉t", "ƭ");
put("̉ɹ", "ɻ");
put("̉V", "Ʋ");
put("̉v", "ʋ");
put("̉W", "Ⱳ");
put("̉w", "ⱳ");
put("̉Z", "Ȥ");
put("̉z", "ȥ");
put("̉̉", "̉");
put("̉ ", "̉");
put("̛Ó", "Ớ");
put("̛O", "Ợ");
put("̛Ò", "Ờ");
put("̛Ỏ", "Ở");
put("̛Õ", "Ỡ");
put("̛ó", "ớ");
put("̛ọ", "ợ");
put("̛ò", "ờ");
put("̛ỏ", "ở");
put("̛õ", "ỡ");
put("̛Ú", "Ứ");
put("̛Ụ", "Ự");
put("̛Ù", "Ừ");
put("̛Ủ", "Ử");
put("̛Ũ", "Ữ");
put("̛ú", "ứ");
put("̛ụ", "ự");
put("̛ù", "ừ");
put("̛ủ", "ử");
put("̛ũ", "ữ");
put("̛̛", "̛");
put("̛ ", "̛");
put("̄É", "Ḗ");
put("̄È", "Ḕ");
put("̄é", "ḗ");
put("̄è", "ḕ");
put("̄Ó", "Ṓ");
put("̄Ò", "Ṑ");
put("̄ó", "ṓ");
put("̄ò", "ṑ");
put("̄V", "Ǖ");
put("̄v", "ǖ");
put("̨Ō", "Ǭ");
put("̨ō", "ǭ");
put("̊Á", "Ǻ");
put("̊á", "ǻ");
put("̃Ó", "Ṍ");
put("̃Ö", "Ṏ");
put("̃Ō", "Ȭ");
put("̃ó", "ṍ");
put("̃ö", "ṏ");
put("̃ō", "ȭ");
put("̃Ú", "Ṹ");
put("̃ú", "ṹ");
put("̃=", "≃");
put("̃<", "≲");
put("̃>", "≳");
put("́̇S", "Ṥ");
put("́̇s", "ṥ");
put("̣̇S", "Ṩ");
put("̣̇s", "ṩ");
put("̌̇S", "Ṧ");
put("̌̇s", "ṧ");
put("̇ ̄A", "Ǡ");
put("̇ ̄a", "ǡ");
put("̇ ̄O", "Ȱ");
put("̇ ̄o", "ȱ");
put("̆ ́A", "Ắ");
put("̆ ́a", "ắ");
put("̧ ́C", "Ḉ");
put("̧ ́c", "ḉ");
put("̂ ́A", "Ấ");
put("̂ ́a", "ấ");
put("̂ ́E", "Ế");
put("̂ ́e", "ế");
put("̂ ́O", "Ố");
put("̂ ́o", "ố");
put("̈ ́I", "Ḯ");
put("̈ ́i", "ḯ");
put("̈ ́U", "Ǘ");
put("̈ ́u", "ǘ");
put("̛ ́O", "Ớ");
put("̛ ́o", "ớ");
put("̛ ́U", "Ứ");
put("̛ ́u", "ứ");
put("̄ ́E", "Ḗ");
put("̄ ́e", "ḗ");
put("̄ ́O", "Ṓ");
put("̄ ́o", "ṓ");
put("̊ ́A", "Ǻ");
put("̊ ́a", "ǻ");
put("̃ ́O", "Ṍ");
put("̃ ́o", "ṍ");
put("̃ ́U", "Ṹ");
put("̃ ́u", "ṹ");
put("̣̆A", "Ặ");
put("̣̆a", "ặ");
put("̣ ̂A", "Ậ");
put("̣ ̂a", "ậ");
put("̣ ̂E", "Ệ");
put("̣ ̂e", "ệ");
put("̣ ̂O", "Ộ");
put("̣ ̂o", "ộ");
put("̛̣O", "Ợ");
put("̛̣o", "ợ");
put("̛̣U", "Ự");
put("̛̣u", "ự");
put("̣ ̄L", "Ḹ");
put("̣ ̄l", "ḹ");
put("̣ ̄R", "Ṝ");
put("̣ ̄r", "ṝ");
put("̧̆E", "Ḝ");
put("̧̆e", "ḝ");
put("̆ ̀A", "Ằ");
put("̆ ̀a", "ằ");
put("̆̉A", "Ẳ");
put("̆̉a", "ẳ");
put("̆ ̃A", "Ẵ");
put("̆ ̃a", "ẵ");
put("̈̌U", "Ǚ");
put("̈̌u", "ǚ");
put("̂ ̀A", "Ầ");
put("̂ ̀a", "ầ");
put("̂ ̀E", "Ề");
put("̂ ̀e", "ề");
put("̂ ̀O", "Ồ");
put("̂ ̀o", "ồ");
put("̂̉A", "Ẩ");
put("̂̉a", "ẩ");
put("̂̉E", "Ể");
put("̂̉e", "ể");
put("̂̉O", "Ổ");
put("̂̉o", "ổ");
put("̂ ̃A", "Ẫ");
put("̂ ̃a", "ẫ");
put("̂ ̃E", "Ễ");
put("̂ ̃e", "ễ");
put("̂ ̃O", "Ỗ");
put("̂ ̃o", "ỗ");
put("̈ ̀U", "Ǜ");
put("̈ ̀u", "ǜ");
put("̈ ̄A", "Ǟ");
put("̈ ̄a", "ǟ");
put("̈ ̄O", "Ȫ");
put("̈ ̄o", "ȫ");
put("̃̈O", "Ṏ");
put("̃̈o", "ṏ");
put("̛ ̀O", "Ờ");
put("̛ ̀o", "ờ");
put("̛ ̀U", "Ừ");
put("̛ ̀u", "ừ");
put("̄ ̀E", "Ḕ");
put("̄ ̀e", "ḕ");
put("̄ ̀O", "Ṑ");
put("̄ ̀o", "ṑ");
put("̛̉O", "Ở");
put("̛̉o", "ở");
put("̛̉U", "Ử");
put("̛̉u", "ử");
put("̛ ̃O", "Ỡ");
put("̛ ̃o", "ỡ");
put("̛ ̃U", "Ữ");
put("̛ ̃u", "ữ");
put("̨ ̄O", "Ǭ");
put("̨ ̄o", "ǭ");
put("̃ ̄O", "Ȭ");
put("̃ ̄o", "ȭ");
*/
}
public static String normalize(String input) {
String lookup = mMap.get(input);
if (lookup != null) return lookup;
return Normalizer.normalize(input, Normalizer.Form.NFC);
}
public boolean execute(int code) {
String composed = executeToString(code);
if (composed != null) {
//Log.i(TAG, "composed=" + composed + " len=" + composed.length());
if (composed.equals("")) {
// Unrecognised - try to use the built-in Java text normalisation
int c = composeBuffer.codePointAt(composeBuffer.length() - 1);
if (Character.getType(c) != Character.NON_SPACING_MARK) {
// Put the combining character(s) at the end, else this won't work
composeBuffer.reverse();
composed = Normalizer.normalize(composeBuffer.toString(), Normalizer.Form.NFC);
if (composed.equals("")) {
return true; // incomplete :-)
}
} else {
return true; // there may be multiple combining accents
}
}
clear();
composeUser.onText(composed);
return false;
}
return true;
}
}
| Java |
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import org.pocketworkstation.pckeyboard.LatinIMEUtil.RingCharBuffer;
import com.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;
}
}
| Java |
/*
* Copyright (C) 2008-2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceGroup;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
public class InputLanguageSelection extends PreferenceActivity {
private static final String TAG = "PCKeyboardILS";
private ArrayList<Loc> mAvailableLanguages = new ArrayList<Loc>();
private static final String[] BLACKLIST_LANGUAGES = {
"ko", "ja", "zh"
};
// Languages for which auto-caps should be disabled
public static final Set<String> NOCAPS_LANGUAGES = new HashSet<String>();
static {
NOCAPS_LANGUAGES.add("ar");
NOCAPS_LANGUAGES.add("iw");
NOCAPS_LANGUAGES.add("th");
}
// Languages which should not use dead key logic. The modifier is entered after the base character.
public static final Set<String> NODEADKEY_LANGUAGES = new HashSet<String>();
static {
NODEADKEY_LANGUAGES.add("ar");
NODEADKEY_LANGUAGES.add("iw"); // TODO: currently no niqqud in the keymap?
NODEADKEY_LANGUAGES.add("th");
}
// Languages which should not auto-add space after completions
public static final Set<String> NOAUTOSPACE_LANGUAGES = new HashSet<String>();
static {
NOAUTOSPACE_LANGUAGES.add("th");
}
// Run the GetLanguages.sh script to update the following lists based on
// the available keyboard resources and dictionaries.
private static final String[] KBD_LOCALIZATIONS = {
"ar", "bg", "ca", "cs", "cs_QY", "da", "de", "el", "en", "en_DV",
"en_GB", "es", "es_LA", "es_US", "fa", "fi", "fr", "fr_CA", "he",
"hr", "hu", "hu_QY", "hy", "in", "it", "iw", "ja", "ka", "ko",
"lo", "lt", "lv", "nb", "nl", "pl", "pt", "pt_PT", "rm", "ro",
"ru", "ru_PH", "si", "sk", "sk_QY", "sl", "sr", "sv", "ta", "th",
"tl", "tr", "uk", "vi", "zh_CN", "zh_TW"
};
private static final String[] KBD_5_ROW = {
"ar", "bg", "cs", "cs_QY", "da", "de", "el", "en", "en_DV", "en_GB",
"es", "es_LA", "fa", "fi", "fr", "fr_CA", "he", "hr", "hu", "hu_QY",
"hy", "it", "iw", "lo", "nb", "pt_PT", "ro", "ru", "ru_PH", "si",
"sk", "sk_QY", "sl", "sr", "sv", "ta", "th", "tr", "uk"
};
private static final String[] KBD_4_ROW = {
"ar", "bg", "cs", "cs_QY", "da", "de", "el", "en", "en_DV", "es",
"es_LA", "es_US", "fa", "fr", "fr_CA", "he", "hr", "hu", "hu_QY",
"iw", "nb", "ru", "ru_PH", "sk", "sk_QY", "sl", "sr", "sv", "tr",
"uk"
};
private static String getLocaleName(Locale l) {
String lang = l.getLanguage();
String country = l.getCountry();
if (lang.equals("en") && country.equals("DV")) {
return "English (Dvorak)";
} else if (lang.equals("en") && country.equals("EX")) {
return "English (4x11)";
} else if (lang.equals("es") && country.equals("LA")) {
return "Español (Latinoamérica)";
} else if (lang.equals("cs") && country.equals("QY")) {
return "Čeština (QWERTY)";
} else if (lang.equals("hu") && country.equals("QY")) {
return "Magyar (QWERTY)";
} else if (lang.equals("sk") && country.equals("QY")) {
return "Slovenčina (QWERTY)";
} else if (lang.equals("ru") && country.equals("PH")) {
return "Русский (Phonetic)";
} else {
return LanguageSwitcher.toTitleCase(l.getDisplayName(l));
}
}
private static class Loc implements Comparable<Object> {
static Collator sCollator = Collator.getInstance();
String label;
Locale locale;
public Loc(String label, Locale locale) {
this.label = label;
this.locale = locale;
}
@Override
public String toString() {
return this.label;
}
public int compareTo(Object o) {
return sCollator.compare(this.label, ((Loc) o).label);
}
}
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
addPreferencesFromResource(R.xml.language_prefs);
// Get the settings preferences
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
String selectedLanguagePref = sp.getString(LatinIME.PREF_SELECTED_LANGUAGES, "");
Log.i(TAG, "selected languages: " + selectedLanguagePref);
String[] languageList = selectedLanguagePref.split(",");
mAvailableLanguages = getUniqueLocales();
// Compatibility hack for v1.22 and older - if a selected language 5-code isn't
// found in the current list of available languages, try adding the 2-letter
// language code. For example, "en_US" is no longer listed, so use "en" instead.
Set<String> availableLanguages = new HashSet<String>();
for (int i = 0; i < mAvailableLanguages.size(); i++) {
Locale locale = mAvailableLanguages.get(i).locale;
availableLanguages.add(get5Code(locale));
}
Set<String> languageSelections = new HashSet<String>();
for (int i = 0; i < languageList.length; ++i) {
String spec = languageList[i];
if (availableLanguages.contains(spec)) {
languageSelections.add(spec);
} else if (spec.length() > 2) {
String lang = spec.substring(0, 2);
if (availableLanguages.contains(lang)) languageSelections.add(lang);
}
}
PreferenceGroup parent = getPreferenceScreen();
for (int i = 0; i < mAvailableLanguages.size(); i++) {
CheckBoxPreference pref = new CheckBoxPreference(this);
Locale locale = mAvailableLanguages.get(i).locale;
pref.setTitle(mAvailableLanguages.get(i).label +
" [" + locale.toString() + "]");
String fivecode = get5Code(locale);
String language = locale.getLanguage();
boolean checked = languageSelections.contains(fivecode);
pref.setChecked(checked);
boolean has4Row = arrayContains(KBD_4_ROW, fivecode) || arrayContains(KBD_4_ROW, language);
boolean has5Row = arrayContains(KBD_5_ROW, fivecode) || arrayContains(KBD_5_ROW, language);
List<String> summaries = new ArrayList<String>(3);
if (has5Row) summaries.add("5-row");
if (has4Row) summaries.add("4-row");
if (hasDictionary(locale)) {
summaries.add(getResources().getString(R.string.has_dictionary));
}
if (!summaries.isEmpty()) {
StringBuilder summary = new StringBuilder();
for (int j = 0; j < summaries.size(); ++j) {
if (j > 0) summary.append(", ");
summary.append(summaries.get(j));
}
pref.setSummary(summary.toString());
}
parent.addPreference(pref);
}
}
private boolean hasDictionary(Locale locale) {
Resources res = getResources();
Configuration conf = res.getConfiguration();
Locale saveLocale = conf.locale;
boolean haveDictionary = false;
conf.locale = locale;
res.updateConfiguration(conf, res.getDisplayMetrics());
int[] dictionaries = LatinIME.getDictionary(res);
BinaryDictionary bd = new BinaryDictionary(this, dictionaries, Suggest.DIC_MAIN);
// Is the dictionary larger than a placeholder? Arbitrarily chose a lower limit of
// 4000-5000 words, whereas the LARGE_DICTIONARY is about 20000+ words.
if (bd.getSize() > Suggest.LARGE_DICTIONARY_THRESHOLD / 4) {
haveDictionary = true;
} else {
BinaryDictionary plug = PluginManager.getDictionary(getApplicationContext(), locale.getLanguage());
if (plug != null) {
bd.close();
bd = plug;
haveDictionary = true;
}
}
bd.close();
conf.locale = saveLocale;
res.updateConfiguration(conf, res.getDisplayMetrics());
return haveDictionary;
}
private String get5Code(Locale locale) {
String country = locale.getCountry();
return locale.getLanguage()
+ (TextUtils.isEmpty(country) ? "" : "_" + country);
}
@Override
protected void onResume() {
super.onResume();
}
@Override
protected void onPause() {
super.onPause();
// Save the selected languages
String checkedLanguages = "";
PreferenceGroup parent = getPreferenceScreen();
int count = parent.getPreferenceCount();
for (int i = 0; i < count; i++) {
CheckBoxPreference pref = (CheckBoxPreference) parent.getPreference(i);
if (pref.isChecked()) {
Locale locale = mAvailableLanguages.get(i).locale;
checkedLanguages += get5Code(locale) + ",";
}
}
if (checkedLanguages.length() < 1) checkedLanguages = null; // Save null
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
Editor editor = sp.edit();
editor.putString(LatinIME.PREF_SELECTED_LANGUAGES, checkedLanguages);
SharedPreferencesCompat.apply(editor);
}
private static String asString(Set<String> set) {
StringBuilder out = new StringBuilder();
out.append("set(");
String[] parts = new String[set.size()];
parts = set.toArray(parts);
Arrays.sort(parts);
for (int i = 0; i < parts.length; ++i) {
if (i > 0) out.append(", ");
out.append(parts[i]);
}
out.append(")");
return out.toString();
}
ArrayList<Loc> getUniqueLocales() {
Set<String> localeSet = new HashSet<String>();
Set<String> langSet = new HashSet<String>();
// Ignore the system (asset) locale list, it's inconsistent and incomplete
// String[] sysLocales = getAssets().getLocales();
//
// // First, add zz_ZZ style full language+country locales
// for (int i = 0; i < sysLocales.length; ++i) {
// String sl = sysLocales[i];
// if (sl.length() != 5) continue;
// localeSet.add(sl);
// langSet.add(sl.substring(0, 2));
// }
//
// // Add entries for system languages without country, but only if there's
// // no full locale for that language yet.
// for (int i = 0; i < sysLocales.length; ++i) {
// String sl = sysLocales[i];
// if (sl.length() != 2 || langSet.contains(sl)) continue;
// localeSet.add(sl);
// }
// Add entries for additional languages supported by the keyboard.
for (int i = 0; i < KBD_LOCALIZATIONS.length; ++i) {
String kl = KBD_LOCALIZATIONS[i];
if (kl.length() == 2 && langSet.contains(kl)) continue;
// replace zz_rYY with zz_YY
if (kl.length() == 6) kl = kl.substring(0, 2) + "_" + kl.substring(4, 6);
localeSet.add(kl);
}
Log.i(TAG, "localeSet=" + asString(localeSet));
Log.i(TAG, "langSet=" + asString(langSet));
// Now build the locale list for display
String[] locales = new String[localeSet.size()];
locales = localeSet.toArray(locales);
Arrays.sort(locales);
ArrayList<Loc> uniqueLocales = new ArrayList<Loc>();
final int origSize = locales.length;
Loc[] preprocess = new Loc[origSize];
int finalSize = 0;
for (int i = 0 ; i < origSize; i++ ) {
String s = locales[i];
int len = s.length();
if (len == 2 || len == 5 || len == 6) {
String language = s.substring(0, 2);
Locale l;
if (len == 5) {
// zz_YY
String country = s.substring(3, 5);
l = new Locale(language, country);
} else if (len == 6) {
// zz_rYY
l = new Locale(language, s.substring(4, 6));
} else {
l = new Locale(language);
}
// Exclude languages that are not relevant to LatinIME
if (arrayContains(BLACKLIST_LANGUAGES, language)) continue;
if (finalSize == 0) {
preprocess[finalSize++] =
new Loc(LanguageSwitcher.toTitleCase(l.getDisplayName(l)), l);
} else {
// check previous entry:
// same lang and a country -> upgrade to full name and
// insert ours with full name
// diff lang -> insert ours with lang-only name
if (preprocess[finalSize-1].locale.getLanguage().equals(
language)) {
preprocess[finalSize-1].label = getLocaleName(preprocess[finalSize-1].locale);
preprocess[finalSize++] =
new Loc(getLocaleName(l), l);
} else {
String displayName;
if (s.equals("zz_ZZ")) {
} else {
displayName = getLocaleName(l);
preprocess[finalSize++] = new Loc(displayName, l);
}
}
}
}
}
for (int i = 0; i < finalSize ; i++) {
uniqueLocales.add(preprocess[i]);
}
return uniqueLocales;
}
private boolean arrayContains(String[] array, String value) {
for (int i = 0; i < array.length; i++) {
if (array[i].equalsIgnoreCase(value)) return true;
}
return false;
}
}
| Java |
/*
* Copyright (C) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import org.pocketworkstation.pckeyboard.Keyboard.Key;
import java.util.Arrays;
class ProximityKeyDetector extends KeyDetector {
private static final int MAX_NEARBY_KEYS = 12;
// working area
private int[] mDistances = new int[MAX_NEARBY_KEYS];
@Override
protected int getMaxNearbyKeys() {
return MAX_NEARBY_KEYS;
}
@Override
public int getKeyIndexAndNearbyCodes(int x, int y, int[] allKeys) {
final Key[] keys = getKeys();
final int touchX = getTouchX(x);
final int touchY = getTouchY(y);
int primaryIndex = LatinKeyboardBaseView.NOT_A_KEY;
int closestKey = LatinKeyboardBaseView.NOT_A_KEY;
int closestKeyDist = mProximityThresholdSquare + 1;
int[] distances = mDistances;
Arrays.fill(distances, Integer.MAX_VALUE);
int [] nearestKeyIndices = mKeyboard.getNearestKeys(touchX, touchY);
final int keyCount = nearestKeyIndices.length;
for (int i = 0; i < keyCount; i++) {
final Key key = keys[nearestKeyIndices[i]];
int dist = 0;
boolean isInside = key.isInside(touchX, touchY);
if (isInside) {
primaryIndex = nearestKeyIndices[i];
}
if (((mProximityCorrectOn
&& (dist = key.squaredDistanceFrom(touchX, touchY)) < mProximityThresholdSquare)
|| isInside)
&& key.codes[0] > 32) {
// Find insertion point
final int nCodes = key.codes.length;
if (dist < closestKeyDist) {
closestKeyDist = dist;
closestKey = nearestKeyIndices[i];
}
if (allKeys == null) continue;
for (int j = 0; j < distances.length; j++) {
if (distances[j] > dist) {
// Make space for nCodes codes
System.arraycopy(distances, j, distances, j + nCodes,
distances.length - j - nCodes);
System.arraycopy(allKeys, j, allKeys, j + nCodes,
allKeys.length - j - nCodes);
System.arraycopy(key.codes, 0, allKeys, j, nCodes);
Arrays.fill(distances, j, j + nCodes, dist);
break;
}
}
}
}
if (primaryIndex == LatinKeyboardBaseView.NOT_A_KEY) {
primaryIndex = closestKey;
}
return primaryIndex;
}
}
| Java |
/*
* Copyright (C) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import org.pocketworkstation.pckeyboard.Keyboard.Key;
class MiniKeyboardKeyDetector extends KeyDetector {
private static final int MAX_NEARBY_KEYS = 1;
private final int mSlideAllowanceSquare;
private final int mSlideAllowanceSquareTop;
public MiniKeyboardKeyDetector(float slideAllowance) {
super();
mSlideAllowanceSquare = (int)(slideAllowance * slideAllowance);
// Top slide allowance is slightly longer (sqrt(2) times) than other edges.
mSlideAllowanceSquareTop = mSlideAllowanceSquare * 2;
}
@Override
protected int getMaxNearbyKeys() {
return MAX_NEARBY_KEYS;
}
@Override
public int getKeyIndexAndNearbyCodes(int x, int y, int[] allKeys) {
final Key[] keys = getKeys();
final int touchX = getTouchX(x);
final int touchY = getTouchY(y);
int closestKeyIndex = LatinKeyboardBaseView.NOT_A_KEY;
int closestKeyDist = (y < 0) ? mSlideAllowanceSquareTop : mSlideAllowanceSquare;
final int keyCount = keys.length;
for (int i = 0; i < keyCount; i++) {
final Key key = keys[i];
int dist = key.squaredDistanceFrom(touchX, touchY);
if (dist < closestKeyDist) {
closestKeyIndex = i;
closestKeyDist = dist;
}
}
if (allKeys != null && closestKeyIndex != LatinKeyboardBaseView.NOT_A_KEY)
allKeys[0] = keys[closestKeyIndex].getPrimaryCode();
return closestKeyIndex;
}
}
| Java |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.pocketworkstation.pckeyboard;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BlurMaskFilter;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PorterDuffColorFilter;
import android.graphics.Paint.Align;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.graphics.Region.Op;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.StateListDrawable;
import org.pocketworkstation.pckeyboard.Keyboard.Key;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.PopupWindow;
import android.widget.TextView;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.Normalizer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.WeakHashMap;
/**
* A view that renders a virtual {@link LatinKeyboard}. It handles rendering of keys and
* detecting key presses and touch movements.
*
* TODO: References to LatinKeyboard in this class should be replaced with ones to its base class.
*
* @attr ref R.styleable#LatinKeyboardBaseView_keyBackground
* @attr ref R.styleable#LatinKeyboardBaseView_keyPreviewLayout
* @attr ref R.styleable#LatinKeyboardBaseView_keyPreviewOffset
* @attr ref R.styleable#LatinKeyboardBaseView_labelTextSize
* @attr ref R.styleable#LatinKeyboardBaseView_keyTextSize
* @attr ref R.styleable#LatinKeyboardBaseView_keyTextColor
* @attr ref R.styleable#LatinKeyboardBaseView_verticalCorrection
* @attr ref R.styleable#LatinKeyboardBaseView_popupLayout
*/
public class LatinKeyboardBaseView extends View implements PointerTracker.UIProxy {
private static final String TAG = "HK/LatinKeyboardBaseView";
private static final boolean DEBUG = false;
public static final int NOT_A_TOUCH_COORDINATE = -1;
public interface OnKeyboardActionListener {
/**
* Called when the user presses a key. This is sent before the
* {@link #onKey} is called. For keys that repeat, this is only
* called once.
*
* @param primaryCode
* the unicode of the key being pressed. If the touch is
* not on a valid key, the value will be zero.
*/
void onPress(int primaryCode);
/**
* Called when the user releases a key. This is sent after the
* {@link #onKey} is called. For keys that repeat, this is only
* called once.
*
* @param primaryCode
* the code of the key that was released
*/
void onRelease(int primaryCode);
/**
* Send a key press to the listener.
*
* @param primaryCode
* this is the key that was pressed
* @param keyCodes
* the codes for all the possible alternative keys with
* the primary code being the first. If the primary key
* code is a single character such as an alphabet or
* number or symbol, the alternatives will include other
* characters that may be on the same key or adjacent
* keys. These codes are useful to correct for
* accidental presses of a key adjacent to the intended
* key.
* @param x
* x-coordinate pixel of touched event. If onKey is not called by onTouchEvent,
* the value should be NOT_A_TOUCH_COORDINATE.
* @param y
* y-coordinate pixel of touched event. If onKey is not called by onTouchEvent,
* the value should be NOT_A_TOUCH_COORDINATE.
*/
void onKey(int primaryCode, int[] keyCodes, int x, int y);
/**
* Sends a sequence of characters to the listener.
*
* @param text
* the sequence of characters to be displayed.
*/
void onText(CharSequence text);
/**
* Called when user released a finger outside any key.
*/
void onCancel();
/**
* Called when the user quickly moves the finger from right to
* left.
*/
boolean swipeLeft();
/**
* Called when the user quickly moves the finger from left to
* right.
*/
boolean swipeRight();
/**
* Called when the user quickly moves the finger from up to down.
*/
boolean swipeDown();
/**
* Called when the user quickly moves the finger from down to up.
*/
boolean swipeUp();
}
// Timing constants
private final int mKeyRepeatInterval;
// Miscellaneous constants
/* package */ static final int NOT_A_KEY = -1;
private static final int NUMBER_HINT_VERTICAL_ADJUSTMENT_PIXEL = -1;
// XML attribute
private float mKeyTextSize;
private float mLabelScale = 1.0f;
private int mKeyTextColor;
private int mKeyHintColor;
private int mKeyCursorColor;
private boolean mRecolorSymbols;
private Typeface mKeyTextStyle = Typeface.DEFAULT;
private float mLabelTextSize;
private int mSymbolColorScheme = 0;
private int mShadowColor;
private float mShadowRadius;
private Drawable mKeyBackground;
private int mBackgroundAlpha;
private float mBackgroundDimAmount;
private float mKeyHysteresisDistance;
private float mVerticalCorrection;
protected int mPreviewOffset;
protected int mPreviewHeight;
protected int mPopupLayout;
// Main keyboard
private Keyboard mKeyboard;
private Key[] mKeys;
// TODO this attribute should be gotten from Keyboard.
private int mKeyboardVerticalGap;
// Key preview popup
protected TextView mPreviewText;
protected PopupWindow mPreviewPopup;
protected int mPreviewTextSizeLarge;
protected int[] mOffsetInWindow;
protected int mOldPreviewKeyIndex = NOT_A_KEY;
protected boolean mShowPreview = true;
protected boolean mShowTouchPoints = true;
protected int mPopupPreviewOffsetX;
protected int mPopupPreviewOffsetY;
protected int mWindowY;
protected int mPopupPreviewDisplayedY;
protected final int mDelayBeforePreview;
protected final int mDelayBeforeSpacePreview;
protected final int mDelayAfterPreview;
// Popup mini keyboard
protected PopupWindow mMiniKeyboardPopup;
protected LatinKeyboardBaseView mMiniKeyboard;
protected View mMiniKeyboardContainer;
protected View mMiniKeyboardParent;
protected boolean mMiniKeyboardVisible;
protected final WeakHashMap<Key, Keyboard> mMiniKeyboardCacheMain = new WeakHashMap<Key, Keyboard>();
protected final WeakHashMap<Key, Keyboard> mMiniKeyboardCacheShift = new WeakHashMap<Key, Keyboard>();
protected final WeakHashMap<Key, Keyboard> mMiniKeyboardCacheCaps = new WeakHashMap<Key, Keyboard>();
protected int mMiniKeyboardOriginX;
protected int mMiniKeyboardOriginY;
protected long mMiniKeyboardPopupTime;
protected int[] mWindowOffset;
protected final float mMiniKeyboardSlideAllowance;
protected int mMiniKeyboardTrackerId;
/** Listener for {@link OnKeyboardActionListener}. */
private OnKeyboardActionListener mKeyboardActionListener;
private final ArrayList<PointerTracker> mPointerTrackers = new ArrayList<PointerTracker>();
private boolean mIgnoreMove = false;
// TODO: Let the PointerTracker class manage this pointer queue
private final PointerQueue mPointerQueue = new PointerQueue();
private final boolean mHasDistinctMultitouch;
private int mOldPointerCount = 1;
protected KeyDetector mKeyDetector = new ProximityKeyDetector();
// Swipe gesture detector
private GestureDetector mGestureDetector;
private final SwipeTracker mSwipeTracker = new SwipeTracker();
private final int mSwipeThreshold;
private final boolean mDisambiguateSwipe;
// Drawing
/** Whether the keyboard bitmap needs to be redrawn before it's blitted. **/
private boolean mDrawPending;
/** The dirty region in the keyboard bitmap */
private final Rect mDirtyRect = new Rect();
/** The keyboard bitmap for faster updates */
private Bitmap mBuffer;
/** Notes if the keyboard just changed, so that we could possibly reallocate the mBuffer. */
private boolean mKeyboardChanged;
private Key mInvalidatedKey;
/** The canvas for the above mutable keyboard bitmap */
private Canvas mCanvas;
private final Paint mPaint;
private final Paint mPaintHint;
private final Rect mPadding;
private final Rect mClipRegion = new Rect(0, 0, 0, 0);
private int mViewWidth;
// This map caches key label text height in pixel as value and key label text size as map key.
private final HashMap<Integer, Integer> mTextHeightCache = new HashMap<Integer, Integer>();
// Distance from horizontal center of the key, proportional to key label text height.
private final float KEY_LABEL_VERTICAL_ADJUSTMENT_FACTOR = 0.55f;
private final String KEY_LABEL_HEIGHT_REFERENCE_CHAR = "H";
/* package */ static Method sSetRenderMode;
private static int sPrevRenderMode = -1;
private final UIHandler mHandler = new UIHandler();
class UIHandler extends Handler {
private static final int MSG_POPUP_PREVIEW = 1;
private static final int MSG_DISMISS_PREVIEW = 2;
private static final int MSG_REPEAT_KEY = 3;
private static final int MSG_LONGPRESS_KEY = 4;
private boolean mInKeyRepeat;
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_POPUP_PREVIEW:
showKey(msg.arg1, (PointerTracker)msg.obj);
break;
case MSG_DISMISS_PREVIEW:
mPreviewPopup.dismiss();
break;
case MSG_REPEAT_KEY: {
final PointerTracker tracker = (PointerTracker)msg.obj;
tracker.repeatKey(msg.arg1);
startKeyRepeatTimer(mKeyRepeatInterval, msg.arg1, tracker);
break;
}
case MSG_LONGPRESS_KEY: {
final PointerTracker tracker = (PointerTracker)msg.obj;
openPopupIfRequired(msg.arg1, tracker);
break;
}
}
}
public void popupPreview(long delay, int keyIndex, PointerTracker tracker) {
removeMessages(MSG_POPUP_PREVIEW);
if (mPreviewPopup.isShowing() && mPreviewText.getVisibility() == VISIBLE) {
// Show right away, if it's already visible and finger is moving around
showKey(keyIndex, tracker);
} else {
sendMessageDelayed(obtainMessage(MSG_POPUP_PREVIEW, keyIndex, 0, tracker),
delay);
}
}
public void cancelPopupPreview() {
removeMessages(MSG_POPUP_PREVIEW);
}
public void dismissPreview(long delay) {
if (mPreviewPopup.isShowing()) {
sendMessageDelayed(obtainMessage(MSG_DISMISS_PREVIEW), delay);
}
}
public void cancelDismissPreview() {
removeMessages(MSG_DISMISS_PREVIEW);
}
public void startKeyRepeatTimer(long delay, int keyIndex, PointerTracker tracker) {
mInKeyRepeat = true;
sendMessageDelayed(obtainMessage(MSG_REPEAT_KEY, keyIndex, 0, tracker), delay);
}
public void cancelKeyRepeatTimer() {
mInKeyRepeat = false;
removeMessages(MSG_REPEAT_KEY);
}
public boolean isInKeyRepeat() {
return mInKeyRepeat;
}
public void startLongPressTimer(long delay, int keyIndex, PointerTracker tracker) {
removeMessages(MSG_LONGPRESS_KEY);
sendMessageDelayed(obtainMessage(MSG_LONGPRESS_KEY, keyIndex, 0, tracker), delay);
}
public void cancelLongPressTimer() {
removeMessages(MSG_LONGPRESS_KEY);
}
public void cancelKeyTimers() {
cancelKeyRepeatTimer();
cancelLongPressTimer();
}
public void cancelAllMessages() {
cancelKeyTimers();
cancelPopupPreview();
cancelDismissPreview();
}
}
static class PointerQueue {
private LinkedList<PointerTracker> mQueue = new LinkedList<PointerTracker>();
public void add(PointerTracker tracker) {
mQueue.add(tracker);
}
public int lastIndexOf(PointerTracker tracker) {
LinkedList<PointerTracker> queue = mQueue;
for (int index = queue.size() - 1; index >= 0; index--) {
PointerTracker t = queue.get(index);
if (t == tracker)
return index;
}
return -1;
}
public void releaseAllPointersOlderThan(PointerTracker tracker, long eventTime) {
LinkedList<PointerTracker> queue = mQueue;
int oldestPos = 0;
for (PointerTracker t = queue.get(oldestPos); t != tracker; t = queue.get(oldestPos)) {
if (t.isModifier()) {
oldestPos++;
} else {
t.onUpEvent(t.getLastX(), t.getLastY(), eventTime);
t.setAlreadyProcessed();
queue.remove(oldestPos);
}
}
}
public void releaseAllPointersExcept(PointerTracker tracker, long eventTime) {
for (PointerTracker t : mQueue) {
if (t == tracker)
continue;
t.onUpEvent(t.getLastX(), t.getLastY(), eventTime);
t.setAlreadyProcessed();
}
mQueue.clear();
if (tracker != null)
mQueue.add(tracker);
}
public void remove(PointerTracker tracker) {
mQueue.remove(tracker);
}
public boolean isInSlidingKeyInput() {
for (final PointerTracker tracker : mQueue) {
if (tracker.isInSlidingKeyInput())
return true;
}
return false;
}
}
static {
initCompatibility();
}
static void initCompatibility() {
try {
sSetRenderMode = View.class.getMethod("setLayerType", int.class, Paint.class);
Log.i(TAG, "setRenderMode is supported");
} catch (SecurityException e) {
Log.w(TAG, "unexpected SecurityException", e);
} catch (NoSuchMethodException e) {
// ignore, not supported by API level pre-Honeycomb
Log.i(TAG, "ignoring render mode, not supported");
}
}
private void setRenderModeIfPossible(int mode) {
if (sSetRenderMode != null && mode != sPrevRenderMode) {
try {
sSetRenderMode.invoke(this, mode, null);
sPrevRenderMode = mode;
Log.i(TAG, "render mode set to " + LatinIME.sKeyboardSettings.renderMode);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
public LatinKeyboardBaseView(Context context, AttributeSet attrs) {
this(context, attrs, R.attr.keyboardViewStyle);
}
public LatinKeyboardBaseView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
Log.i(TAG, "Creating new LatinKeyboardBaseView " + this);
setRenderModeIfPossible(LatinIME.sKeyboardSettings.renderMode);
TypedArray a = context.obtainStyledAttributes(
attrs, R.styleable.LatinKeyboardBaseView, defStyle, R.style.LatinKeyboardBaseView);
int n = a.getIndexCount();
for (int i = 0; i < n; i++) {
int attr = a.getIndex(i);
switch (attr) {
case R.styleable.LatinKeyboardBaseView_keyBackground:
mKeyBackground = a.getDrawable(attr);
break;
case R.styleable.LatinKeyboardBaseView_keyHysteresisDistance:
mKeyHysteresisDistance = a.getDimensionPixelOffset(attr, 0);
break;
case R.styleable.LatinKeyboardBaseView_verticalCorrection:
mVerticalCorrection = a.getDimensionPixelOffset(attr, 0);
break;
case R.styleable.LatinKeyboardBaseView_keyTextSize:
mKeyTextSize = a.getDimensionPixelSize(attr, 18);
break;
case R.styleable.LatinKeyboardBaseView_keyTextColor:
mKeyTextColor = a.getColor(attr, 0xFF000000);
break;
case R.styleable.LatinKeyboardBaseView_keyHintColor:
mKeyHintColor = a.getColor(attr, 0xFFBBBBBB);
break;
case R.styleable.LatinKeyboardBaseView_keyCursorColor:
mKeyCursorColor = a.getColor(attr, 0xFF000000);
break;
case R.styleable.LatinKeyboardBaseView_recolorSymbols:
mRecolorSymbols = a.getBoolean(attr, false);
break;
case R.styleable.LatinKeyboardBaseView_labelTextSize:
mLabelTextSize = a.getDimensionPixelSize(attr, 14);
break;
case R.styleable.LatinKeyboardBaseView_shadowColor:
mShadowColor = a.getColor(attr, 0);
break;
case R.styleable.LatinKeyboardBaseView_shadowRadius:
mShadowRadius = a.getFloat(attr, 0f);
break;
// TODO: Use Theme (android.R.styleable.Theme_backgroundDimAmount)
case R.styleable.LatinKeyboardBaseView_backgroundDimAmount:
mBackgroundDimAmount = a.getFloat(attr, 0.5f);
break;
case R.styleable.LatinKeyboardBaseView_backgroundAlpha:
mBackgroundAlpha = a.getInteger(attr, 255);
break;
//case android.R.styleable.
case R.styleable.LatinKeyboardBaseView_keyTextStyle:
int textStyle = a.getInt(attr, 0);
switch (textStyle) {
case 0:
mKeyTextStyle = Typeface.DEFAULT;
break;
case 1:
mKeyTextStyle = Typeface.DEFAULT_BOLD;
break;
default:
mKeyTextStyle = Typeface.defaultFromStyle(textStyle);
break;
}
break;
case R.styleable.LatinKeyboardBaseView_symbolColorScheme:
mSymbolColorScheme = a.getInt(attr, 0);
break;
}
}
final Resources res = getResources();
mShowPreview = false;
mDelayBeforePreview = res.getInteger(R.integer.config_delay_before_preview);
mDelayBeforeSpacePreview = res.getInteger(R.integer.config_delay_before_space_preview);
mDelayAfterPreview = res.getInteger(R.integer.config_delay_after_preview);
mPopupLayout = 0;
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setTextAlign(Align.CENTER);
mPaint.setAlpha(255);
mPaintHint = new Paint();
mPaintHint.setAntiAlias(true);
mPaintHint.setTextAlign(Align.RIGHT);
mPaintHint.setAlpha(255);
mPaintHint.setTypeface(Typeface.DEFAULT_BOLD);
mPadding = new Rect(0, 0, 0, 0);
mKeyBackground.getPadding(mPadding);
mSwipeThreshold = (int) (300 * res.getDisplayMetrics().density);
// TODO: Refer frameworks/base/core/res/res/values/config.xml
// TODO(klausw): turn off mDisambiguateSwipe if no swipe actions are set?
mDisambiguateSwipe = res.getBoolean(R.bool.config_swipeDisambiguation);
mMiniKeyboardSlideAllowance = res.getDimension(R.dimen.mini_keyboard_slide_allowance);
GestureDetector.SimpleOnGestureListener listener =
new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onFling(MotionEvent me1, MotionEvent me2, float velocityX,
float velocityY) {
final float absX = Math.abs(velocityX);
final float absY = Math.abs(velocityY);
float deltaX = me2.getX() - me1.getX();
float deltaY = me2.getY() - me1.getY();
mSwipeTracker.computeCurrentVelocity(1000);
final float endingVelocityX = mSwipeTracker.getXVelocity();
final float endingVelocityY = mSwipeTracker.getYVelocity();
// Calculate swipe distance threshold based on screen width & height,
// taking the smaller distance.
int travelX = getWidth() / 3;
int travelY = getHeight() / 3;
int travelMin = Math.min(travelX, travelY);
// Log.i(TAG, "onFling vX=" + velocityX + " vY=" + velocityY + " threshold=" + mSwipeThreshold
// + " dX=" + deltaX + " dy=" + deltaY + " min=" + travelMin);
if (velocityX > mSwipeThreshold && absY < absX && deltaX > travelMin) {
if (mDisambiguateSwipe && endingVelocityX >= velocityX / 4) {
if (swipeRight()) return true;
}
} else if (velocityX < -mSwipeThreshold && absY < absX && deltaX < -travelMin) {
if (mDisambiguateSwipe && endingVelocityX <= velocityX / 4) {
if (swipeLeft()) return true;
}
} else if (velocityY < -mSwipeThreshold && absX < absY && deltaY < -travelMin) {
if (mDisambiguateSwipe && endingVelocityY <= velocityY / 4) {
if (swipeUp()) return true;
}
} else if (velocityY > mSwipeThreshold && absX < absY / 2 && deltaY > travelMin) {
if (mDisambiguateSwipe && endingVelocityY >= velocityY / 4) {
if (swipeDown()) return true;
}
}
return false;
}
};
final boolean ignoreMultitouch = true;
mGestureDetector = new GestureDetector(getContext(), listener, null, ignoreMultitouch);
mGestureDetector.setIsLongpressEnabled(false);
mHasDistinctMultitouch = context.getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH_DISTINCT);
mKeyRepeatInterval = res.getInteger(R.integer.config_key_repeat_interval);
}
private boolean showHints7Bit() {
return LatinIME.sKeyboardSettings.hintMode >= 1;
}
private boolean showHintsAll() {
return LatinIME.sKeyboardSettings.hintMode >= 2;
}
public void setOnKeyboardActionListener(OnKeyboardActionListener listener) {
mKeyboardActionListener = listener;
for (PointerTracker tracker : mPointerTrackers) {
tracker.setOnKeyboardActionListener(listener);
}
}
/**
* Returns the {@link OnKeyboardActionListener} object.
* @return the listener attached to this keyboard
*/
protected OnKeyboardActionListener getOnKeyboardActionListener() {
return mKeyboardActionListener;
}
/**
* Attaches a keyboard to this view. The keyboard can be switched at any time and the
* view will re-layout itself to accommodate the keyboard.
* @see Keyboard
* @see #getKeyboard()
* @param keyboard the keyboard to display in this view
*/
public void setKeyboard(Keyboard keyboard) {
if (mKeyboard != null) {
dismissKeyPreview();
}
//Log.i(TAG, "setKeyboard(" + keyboard + ") for " + this);
// Remove any pending messages, except dismissing preview
mHandler.cancelKeyTimers();
mHandler.cancelPopupPreview();
mKeyboard = keyboard;
LatinImeLogger.onSetKeyboard(keyboard);
mKeys = mKeyDetector.setKeyboard(keyboard, -getPaddingLeft(),
-getPaddingTop() + mVerticalCorrection);
mKeyboardVerticalGap = (int)getResources().getDimension(R.dimen.key_bottom_gap);
for (PointerTracker tracker : mPointerTrackers) {
tracker.setKeyboard(mKeys, mKeyHysteresisDistance);
}
mLabelScale = LatinIME.sKeyboardSettings.labelScalePref;
if (keyboard.mLayoutRows >= 4) mLabelScale *= 5.0f / keyboard.mLayoutRows;
requestLayout();
// Hint to reallocate the buffer if the size changed
mKeyboardChanged = true;
invalidateAllKeys();
computeProximityThreshold(keyboard);
mMiniKeyboardCacheMain.clear();
mMiniKeyboardCacheShift.clear();
mMiniKeyboardCacheCaps.clear();
setRenderModeIfPossible(LatinIME.sKeyboardSettings.renderMode);
mIgnoreMove = true;
}
/**
* Returns the current keyboard being displayed by this view.
* @return the currently attached keyboard
* @see #setKeyboard(Keyboard)
*/
public Keyboard getKeyboard() {
return mKeyboard;
}
/**
* Return whether the device has distinct multi-touch panel.
* @return true if the device has distinct multi-touch panel.
*/
public boolean hasDistinctMultitouch() {
return mHasDistinctMultitouch;
}
/**
* Sets the state of the shift key of the keyboard, if any.
* @param shifted whether or not to enable the state of the shift key
* @return true if the shift key state changed, false if there was no change
*/
public boolean setShiftState(int shiftState) {
//Log.i(TAG, "setShifted " + shiftState);
if (mKeyboard != null) {
if (mKeyboard.setShiftState(shiftState)) {
// The whole keyboard probably needs to be redrawn
invalidateAllKeys();
return true;
}
}
return false;
}
public void setCtrlIndicator(boolean active) {
if (mKeyboard != null) {
invalidateKey(mKeyboard.setCtrlIndicator(active));
}
}
public void setAltIndicator(boolean active) {
if (mKeyboard != null) {
invalidateKey(mKeyboard.setAltIndicator(active));
}
}
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;
}
}
| Java |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.pocketworkstation.pckeyboard;
import android.content.SharedPreferences;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* Reflection utils to call SharedPreferences$Editor.apply when possible,
* falling back to commit when apply isn't available.
*/
public class SharedPreferencesCompat {
private static final Method sApplyMethod = findApplyMethod();
private static Method findApplyMethod() {
try {
return SharedPreferences.Editor.class.getMethod("apply");
} catch (NoSuchMethodException unused) {
// fall through
}
return null;
}
public static void apply(SharedPreferences.Editor editor) {
if (sApplyMethod != null) {
try {
sApplyMethod.invoke(editor);
return;
} catch (InvocationTargetException unused) {
// fall through
} catch (IllegalAccessException unused) {
// fall through
}
}
editor.commit();
}
}
| Java |
package org.pocketworkstation.pckeyboard;
import 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();
}
}
| Java |
/*
* Copyright (C) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import android.view.MotionEvent;
class SwipeTracker {
private static final int NUM_PAST = 4;
private static final int LONGEST_PAST_TIME = 200;
final EventRingBuffer mBuffer = new EventRingBuffer(NUM_PAST);
private float mYVelocity;
private float mXVelocity;
public void addMovement(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
mBuffer.clear();
return;
}
long time = ev.getEventTime();
final int count = ev.getHistorySize();
for (int i = 0; i < count; i++) {
addPoint(ev.getHistoricalX(i), ev.getHistoricalY(i), ev.getHistoricalEventTime(i));
}
addPoint(ev.getX(), ev.getY(), time);
}
private void addPoint(float x, float y, long time) {
final EventRingBuffer buffer = mBuffer;
while (buffer.size() > 0) {
long lastT = buffer.getTime(0);
if (lastT >= time - LONGEST_PAST_TIME)
break;
buffer.dropOldest();
}
buffer.add(x, y, time);
}
public void computeCurrentVelocity(int units) {
computeCurrentVelocity(units, Float.MAX_VALUE);
}
public void computeCurrentVelocity(int units, float maxVelocity) {
final EventRingBuffer buffer = mBuffer;
final float oldestX = buffer.getX(0);
final float oldestY = buffer.getY(0);
final long oldestTime = buffer.getTime(0);
float accumX = 0;
float accumY = 0;
final int count = buffer.size();
for (int pos = 1; pos < count; pos++) {
final int dur = (int)(buffer.getTime(pos) - oldestTime);
if (dur == 0) continue;
float dist = buffer.getX(pos) - oldestX;
float vel = (dist / dur) * units; // pixels/frame.
if (accumX == 0) accumX = vel;
else accumX = (accumX + vel) * .5f;
dist = buffer.getY(pos) - oldestY;
vel = (dist / dur) * units; // pixels/frame.
if (accumY == 0) accumY = vel;
else accumY = (accumY + vel) * .5f;
}
mXVelocity = accumX < 0.0f ? Math.max(accumX, -maxVelocity)
: Math.min(accumX, maxVelocity);
mYVelocity = accumY < 0.0f ? Math.max(accumY, -maxVelocity)
: Math.min(accumY, maxVelocity);
}
public float getXVelocity() {
return mXVelocity;
}
public float getYVelocity() {
return mYVelocity;
}
static class EventRingBuffer {
private final int bufSize;
private final float xBuf[];
private final float yBuf[];
private final long timeBuf[];
private int top; // points new event
private int end; // points oldest event
private int count; // the number of valid data
public EventRingBuffer(int max) {
this.bufSize = max;
xBuf = new float[max];
yBuf = new float[max];
timeBuf = new long[max];
clear();
}
public void clear() {
top = end = count = 0;
}
public int size() {
return count;
}
// Position 0 points oldest event
private int index(int pos) {
return (end + pos) % bufSize;
}
private int advance(int index) {
return (index + 1) % bufSize;
}
public void add(float x, float y, long time) {
xBuf[top] = x;
yBuf[top] = y;
timeBuf[top] = time;
top = advance(top);
if (count < bufSize) {
count++;
} else {
end = advance(end);
}
}
public float getX(int pos) {
return xBuf[index(pos)];
}
public float getY(int pos) {
return yBuf[index(pos)];
}
public long getTime(int pos) {
return timeBuf[index(pos)];
}
public void dropOldest() {
count--;
end = advance(end);
}
}
} | Java |
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import android.app.backup.BackupManager;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.PreferenceActivity;
public class PrefScreenView extends PreferenceActivity
implements SharedPreferences.OnSharedPreferenceChangeListener {
private ListPreference mRenderModePreference;
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
addPreferencesFromResource(R.xml.prefs_view);
SharedPreferences prefs = getPreferenceManager().getSharedPreferences();
prefs.registerOnSharedPreferenceChangeListener(this);
mRenderModePreference = (ListPreference) findPreference(LatinIME.PREF_RENDER_MODE);
}
@Override
protected void onDestroy() {
getPreferenceManager().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(
this);
super.onDestroy();
}
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
(new BackupManager(this)).dataChanged();
}
@Override
protected void onResume() {
super.onResume();
if (LatinKeyboardBaseView.sSetRenderMode == null) {
mRenderModePreference.setEnabled(false);
mRenderModePreference.setSummary(R.string.render_mode_unavailable);
}
}
}
| Java |
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.InflateException;
import java.lang.ref.SoftReference;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Locale;
public class KeyboardSwitcher implements
SharedPreferences.OnSharedPreferenceChangeListener {
private static String TAG = "PCKeyboardKbSw";
public static final int MODE_NONE = 0;
public static final int MODE_TEXT = 1;
public static final int MODE_SYMBOLS = 2;
public static final int MODE_PHONE = 3;
public static final int MODE_URL = 4;
public static final int MODE_EMAIL = 5;
public static final int MODE_IM = 6;
public static final int MODE_WEB = 7;
// Main keyboard layouts without the settings key
public static final int KEYBOARDMODE_NORMAL = R.id.mode_normal;
public static final int KEYBOARDMODE_URL = R.id.mode_url;
public static final int KEYBOARDMODE_EMAIL = R.id.mode_email;
public static final int KEYBOARDMODE_IM = R.id.mode_im;
public static final int KEYBOARDMODE_WEB = R.id.mode_webentry;
// Main keyboard layouts with the settings key
public static final int KEYBOARDMODE_NORMAL_WITH_SETTINGS_KEY = R.id.mode_normal_with_settings_key;
public static final int KEYBOARDMODE_URL_WITH_SETTINGS_KEY = R.id.mode_url_with_settings_key;
public static final int KEYBOARDMODE_EMAIL_WITH_SETTINGS_KEY = R.id.mode_email_with_settings_key;
public static final int KEYBOARDMODE_IM_WITH_SETTINGS_KEY = R.id.mode_im_with_settings_key;
public static final int KEYBOARDMODE_WEB_WITH_SETTINGS_KEY = R.id.mode_webentry_with_settings_key;
// Symbols keyboard layout without the settings key
public static final int KEYBOARDMODE_SYMBOLS = R.id.mode_symbols;
// Symbols keyboard layout with the settings key
public static final int KEYBOARDMODE_SYMBOLS_WITH_SETTINGS_KEY = R.id.mode_symbols_with_settings_key;
public static final String DEFAULT_LAYOUT_ID = "0";
public static final String PREF_KEYBOARD_LAYOUT = "pref_keyboard_layout";
private static final int[] THEMES = new int[] {
R.layout.input_ics,
R.layout.input_gingerbread,
R.layout.input_stone_bold,
R.layout.input_trans_neon,
};
// Tables which contains resource ids for each character theme color
private static final int KBD_PHONE = R.xml.kbd_phone;
private static final int KBD_PHONE_SYMBOLS = R.xml.kbd_phone_symbols;
private static final int KBD_SYMBOLS = R.xml.kbd_symbols;
private static final int KBD_SYMBOLS_SHIFT = R.xml.kbd_symbols_shift;
private static final int KBD_QWERTY = R.xml.kbd_qwerty;
private static final int KBD_FULL = R.xml.kbd_full;
private static final int KBD_FULL_FN = R.xml.kbd_full_fn;
private static final int KBD_COMPACT = R.xml.kbd_compact;
private static final int KBD_COMPACT_FN = R.xml.kbd_compact_fn;
private LatinKeyboardView mInputView;
private static final int[] ALPHABET_MODES = { KEYBOARDMODE_NORMAL,
KEYBOARDMODE_URL, KEYBOARDMODE_EMAIL, KEYBOARDMODE_IM,
KEYBOARDMODE_WEB, KEYBOARDMODE_NORMAL_WITH_SETTINGS_KEY,
KEYBOARDMODE_URL_WITH_SETTINGS_KEY,
KEYBOARDMODE_EMAIL_WITH_SETTINGS_KEY,
KEYBOARDMODE_IM_WITH_SETTINGS_KEY,
KEYBOARDMODE_WEB_WITH_SETTINGS_KEY };
private LatinIME mInputMethodService;
private KeyboardId mSymbolsId;
private KeyboardId mSymbolsShiftedId;
private KeyboardId mCurrentId;
private final HashMap<KeyboardId, SoftReference<LatinKeyboard>> mKeyboards = new HashMap<KeyboardId, SoftReference<LatinKeyboard>>();
private int mMode = MODE_NONE;
/** One of the MODE_XXX values */
private int mImeOptions;
private boolean mIsSymbols;
private int mFullMode;
/**
* mIsAutoCompletionActive indicates that auto completed word will be input
* instead of what user actually typed.
*/
private boolean mIsAutoCompletionActive;
private boolean mHasVoice;
private boolean mVoiceOnPrimary;
private boolean mPreferSymbols;
private static final int AUTO_MODE_SWITCH_STATE_ALPHA = 0;
private static final int AUTO_MODE_SWITCH_STATE_SYMBOL_BEGIN = 1;
private static final int AUTO_MODE_SWITCH_STATE_SYMBOL = 2;
// The following states are used only on the distinct multi-touch panel
// devices.
private static final int AUTO_MODE_SWITCH_STATE_MOMENTARY = 3;
private static final int AUTO_MODE_SWITCH_STATE_CHORDING = 4;
private int mAutoModeSwitchState = AUTO_MODE_SWITCH_STATE_ALPHA;
// Indicates whether or not we have the settings key
private boolean mHasSettingsKey;
private static final int SETTINGS_KEY_MODE_AUTO = R.string.settings_key_mode_auto;
private static final int SETTINGS_KEY_MODE_ALWAYS_SHOW = R.string.settings_key_mode_always_show;
// NOTE: No need to have SETTINGS_KEY_MODE_ALWAYS_HIDE here because it's not
// being referred to
// in the source code now.
// Default is SETTINGS_KEY_MODE_AUTO.
private static final int DEFAULT_SETTINGS_KEY_MODE = SETTINGS_KEY_MODE_AUTO;
private int mLastDisplayWidth;
private LanguageSwitcher mLanguageSwitcher;
private int mLayoutId;
private static final KeyboardSwitcher sInstance = new KeyboardSwitcher();
public static KeyboardSwitcher getInstance() {
return sInstance;
}
private KeyboardSwitcher() {
// Intentional empty constructor for singleton.
}
public static void init(LatinIME ims) {
sInstance.mInputMethodService = ims;
final SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(ims);
sInstance.mLayoutId = Integer.valueOf(prefs.getString(
PREF_KEYBOARD_LAYOUT, DEFAULT_LAYOUT_ID));
sInstance.updateSettingsKeyState(prefs);
prefs.registerOnSharedPreferenceChangeListener(sInstance);
sInstance.mSymbolsId = sInstance.makeSymbolsId(false);
sInstance.mSymbolsShiftedId = sInstance.makeSymbolsShiftedId(false);
}
/**
* Sets the input locale, when there are multiple locales for input. If no
* locale switching is required, then the locale should be set to null.
*
* @param locale
* the current input locale, or null for default locale with no
* locale button.
*/
public void setLanguageSwitcher(LanguageSwitcher languageSwitcher) {
mLanguageSwitcher = languageSwitcher;
languageSwitcher.getInputLocale(); // for side effect
}
private KeyboardId makeSymbolsId(boolean hasVoice) {
if (mFullMode == 1) {
return new KeyboardId(KBD_COMPACT_FN, KEYBOARDMODE_SYMBOLS, true, hasVoice);
} else if (mFullMode == 2) {
return new KeyboardId(KBD_FULL_FN, KEYBOARDMODE_SYMBOLS, true, hasVoice);
}
return new KeyboardId(KBD_SYMBOLS,
mHasSettingsKey ? KEYBOARDMODE_SYMBOLS_WITH_SETTINGS_KEY
: KEYBOARDMODE_SYMBOLS, false, hasVoice);
}
private KeyboardId makeSymbolsShiftedId(boolean hasVoice) {
if (mFullMode > 0)
return null;
return new KeyboardId(KBD_SYMBOLS_SHIFT,
mHasSettingsKey ? KEYBOARDMODE_SYMBOLS_WITH_SETTINGS_KEY
: KEYBOARDMODE_SYMBOLS, false, hasVoice);
}
public void makeKeyboards(boolean forceCreate) {
mFullMode = LatinIME.sKeyboardSettings.keyboardMode;
mSymbolsId = makeSymbolsId(mHasVoice && !mVoiceOnPrimary);
mSymbolsShiftedId = makeSymbolsShiftedId(mHasVoice && !mVoiceOnPrimary);
if (forceCreate)
mKeyboards.clear();
// Configuration change is coming after the keyboard gets recreated. So
// don't rely on that.
// If keyboards have already been made, check if we have a screen width
// change and
// create the keyboard layouts again at the correct orientation
int displayWidth = mInputMethodService.getMaxWidth();
if (displayWidth == mLastDisplayWidth)
return;
mLastDisplayWidth = displayWidth;
if (!forceCreate)
mKeyboards.clear();
}
/**
* Represents the parameters necessary to construct a new LatinKeyboard,
* which also serve as a unique identifier for each keyboard type.
*/
private static class KeyboardId {
// TODO: should have locale and portrait/landscape orientation?
public final int mXml;
public final int mKeyboardMode;
/** A KEYBOARDMODE_XXX value */
public final boolean mEnableShiftLock;
public final boolean mHasVoice;
public final float mKeyboardHeightPercent;
public final boolean mUsingExtension;
private final int mHashCode;
public KeyboardId(int xml, int mode, boolean enableShiftLock,
boolean hasVoice) {
this.mXml = xml;
this.mKeyboardMode = mode;
this.mEnableShiftLock = enableShiftLock;
this.mHasVoice = hasVoice;
this.mKeyboardHeightPercent = LatinIME.sKeyboardSettings.keyboardHeightPercent;
this.mUsingExtension = LatinIME.sKeyboardSettings.useExtension;
this.mHashCode = Arrays.hashCode(new Object[] { xml, mode,
enableShiftLock, hasVoice });
}
@Override
public boolean equals(Object other) {
return other instanceof KeyboardId && equals((KeyboardId) other);
}
private boolean equals(KeyboardId other) {
return other != null
&& other.mXml == this.mXml
&& other.mKeyboardMode == this.mKeyboardMode
&& other.mUsingExtension == this.mUsingExtension
&& other.mEnableShiftLock == this.mEnableShiftLock
&& other.mHasVoice == this.mHasVoice;
}
@Override
public int hashCode() {
return mHashCode;
}
}
public void setVoiceMode(boolean enableVoice, boolean voiceOnPrimary) {
if (enableVoice != mHasVoice || voiceOnPrimary != mVoiceOnPrimary) {
mKeyboards.clear();
}
mHasVoice = enableVoice;
mVoiceOnPrimary = voiceOnPrimary;
setKeyboardMode(mMode, mImeOptions, mHasVoice, mIsSymbols);
}
private boolean hasVoiceButton(boolean isSymbols) {
return mHasVoice && (isSymbols != mVoiceOnPrimary);
}
public void setKeyboardMode(int mode, int imeOptions, boolean enableVoice) {
mAutoModeSwitchState = AUTO_MODE_SWITCH_STATE_ALPHA;
mPreferSymbols = mode == MODE_SYMBOLS;
if (mode == MODE_SYMBOLS) {
mode = MODE_TEXT;
}
try {
setKeyboardMode(mode, imeOptions, enableVoice, mPreferSymbols);
} catch (RuntimeException e) {
LatinImeLogger.logOnException(mode + "," + imeOptions + ","
+ mPreferSymbols, e);
}
}
private void setKeyboardMode(int mode, int imeOptions, boolean enableVoice,
boolean isSymbols) {
if (mInputView == null)
return;
mMode = mode;
mImeOptions = imeOptions;
if (enableVoice != mHasVoice) {
// TODO clean up this unnecessary recursive call.
setVoiceMode(enableVoice, mVoiceOnPrimary);
}
mIsSymbols = isSymbols;
mInputView.setPreviewEnabled(mInputMethodService.getPopupOn());
KeyboardId id = getKeyboardId(mode, imeOptions, isSymbols);
LatinKeyboard keyboard = null;
keyboard = getKeyboard(id);
if (mode == MODE_PHONE) {
mInputView.setPhoneKeyboard(keyboard);
}
mCurrentId = id;
mInputView.setKeyboard(keyboard);
keyboard.setShiftState(Keyboard.SHIFT_OFF);
keyboard.setImeOptions(mInputMethodService.getResources(), mMode,
imeOptions);
keyboard.updateSymbolIcons(mIsAutoCompletionActive);
}
private LatinKeyboard getKeyboard(KeyboardId id) {
SoftReference<LatinKeyboard> ref = mKeyboards.get(id);
LatinKeyboard keyboard = (ref == null) ? null : ref.get();
if (keyboard == null) {
Resources orig = mInputMethodService.getResources();
Configuration conf = orig.getConfiguration();
Locale saveLocale = conf.locale;
conf.locale = LatinIME.sKeyboardSettings.inputLocale;
orig.updateConfiguration(conf, null);
keyboard = new LatinKeyboard(mInputMethodService, id.mXml,
id.mKeyboardMode, id.mKeyboardHeightPercent);
keyboard.setVoiceMode(hasVoiceButton(id.mXml == R.xml.kbd_symbols), mHasVoice);
keyboard.setLanguageSwitcher(mLanguageSwitcher, mIsAutoCompletionActive);
// if (isFullMode()) {
// keyboard.setExtension(new LatinKeyboard(mInputMethodService,
// R.xml.kbd_extension_full, 0, id.mRowHeightPercent));
// } else if (isAlphabetMode()) { // TODO: not in full keyboard mode? Per-mode extension kbd?
// keyboard.setExtension(new LatinKeyboard(mInputMethodService,
// R.xml.kbd_extension, 0, id.mRowHeightPercent));
// }
if (id.mEnableShiftLock) {
keyboard.enableShiftLock();
}
mKeyboards.put(id, new SoftReference<LatinKeyboard>(keyboard));
conf.locale = saveLocale;
orig.updateConfiguration(conf, null);
}
return keyboard;
}
public boolean isFullMode() {
return mFullMode > 0;
}
private KeyboardId getKeyboardId(int mode, int imeOptions, boolean isSymbols) {
boolean hasVoice = hasVoiceButton(isSymbols);
if (mFullMode > 0) {
switch (mode) {
case MODE_TEXT:
case MODE_URL:
case MODE_EMAIL:
case MODE_IM:
case MODE_WEB:
return new KeyboardId(mFullMode == 1 ? KBD_COMPACT : KBD_FULL,
KEYBOARDMODE_NORMAL, true, hasVoice);
}
}
// TODO: generalize for any KeyboardId
int keyboardRowsResId = KBD_QWERTY;
if (isSymbols) {
if (mode == MODE_PHONE) {
return new KeyboardId(KBD_PHONE_SYMBOLS, 0, false, hasVoice);
} else {
return new KeyboardId(
KBD_SYMBOLS,
mHasSettingsKey ? KEYBOARDMODE_SYMBOLS_WITH_SETTINGS_KEY
: KEYBOARDMODE_SYMBOLS, false, hasVoice);
}
}
switch (mode) {
case MODE_NONE:
LatinImeLogger.logOnWarning("getKeyboardId:" + mode + ","
+ imeOptions + "," + isSymbols);
/* fall through */
case MODE_TEXT:
return new KeyboardId(keyboardRowsResId,
mHasSettingsKey ? KEYBOARDMODE_NORMAL_WITH_SETTINGS_KEY
: KEYBOARDMODE_NORMAL, true, hasVoice);
case MODE_SYMBOLS:
return new KeyboardId(KBD_SYMBOLS,
mHasSettingsKey ? KEYBOARDMODE_SYMBOLS_WITH_SETTINGS_KEY
: KEYBOARDMODE_SYMBOLS, false, hasVoice);
case MODE_PHONE:
return new KeyboardId(KBD_PHONE, 0, false, hasVoice);
case MODE_URL:
return new KeyboardId(keyboardRowsResId,
mHasSettingsKey ? KEYBOARDMODE_URL_WITH_SETTINGS_KEY
: KEYBOARDMODE_URL, true, hasVoice);
case MODE_EMAIL:
return new KeyboardId(keyboardRowsResId,
mHasSettingsKey ? KEYBOARDMODE_EMAIL_WITH_SETTINGS_KEY
: KEYBOARDMODE_EMAIL, true, hasVoice);
case MODE_IM:
return new KeyboardId(keyboardRowsResId,
mHasSettingsKey ? KEYBOARDMODE_IM_WITH_SETTINGS_KEY
: KEYBOARDMODE_IM, true, hasVoice);
case MODE_WEB:
return new KeyboardId(keyboardRowsResId,
mHasSettingsKey ? KEYBOARDMODE_WEB_WITH_SETTINGS_KEY
: KEYBOARDMODE_WEB, true, hasVoice);
}
return null;
}
public int getKeyboardMode() {
return mMode;
}
public boolean isAlphabetMode() {
if (mCurrentId == null) {
return false;
}
int currentMode = mCurrentId.mKeyboardMode;
if (mFullMode > 0 && currentMode == KEYBOARDMODE_NORMAL)
return true;
for (Integer mode : ALPHABET_MODES) {
if (currentMode == mode) {
return true;
}
}
return false;
}
public void setShiftState(int shiftState) {
if (mInputView != null) {
mInputView.setShiftState(shiftState);
}
}
public void setFn(boolean useFn) {
if (mInputView == null) return;
int oldShiftState = mInputView.getShiftState();
if (useFn) {
LatinKeyboard kbd = getKeyboard(mSymbolsId);
kbd.enableShiftLock();
mCurrentId = mSymbolsId;
mInputView.setKeyboard(kbd);
mInputView.setShiftState(oldShiftState);
} else {
// Return to default keyboard state
setKeyboardMode(mMode, mImeOptions, mHasVoice, false);
mInputView.setShiftState(oldShiftState);
}
}
public void setCtrlIndicator(boolean active) {
if (mInputView == null) return;
mInputView.setCtrlIndicator(active);
}
public void setAltIndicator(boolean active) {
if (mInputView == null) return;
mInputView.setAltIndicator(active);
}
public void 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;
}
}
}
| Java |
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import android.app.backup.BackupAgentHelper;
import android.app.backup.SharedPreferencesBackupHelper;
/**
* Backs up the Latin IME shared preferences.
*/
public class LatinIMEBackupAgent extends BackupAgentHelper {
@Override
public void onCreate() {
addHelper("shared_pref", new SharedPreferencesBackupHelper(this,
getPackageName() + "_preferences"));
}
}
| Java |
/**
*
*/
package org.pocketworkstation.pckeyboard;
import android.content.Context;
import android.preference.ListPreference;
import android.util.AttributeSet;
import android.util.Log;
public class AutoSummaryListPreference extends ListPreference {
private static final String TAG = "HK/AutoSummaryListPreference";
public AutoSummaryListPreference(Context context) {
super(context);
}
public AutoSummaryListPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
private void trySetSummary() {
CharSequence entry = null;
try {
entry = getEntry();
} catch (ArrayIndexOutOfBoundsException e) {
Log.i(TAG, "Malfunctioning ListPreference, can't get entry");
}
if (entry != null) {
//String percent = getResources().getString(R.string.percent);
String percent = "percent";
setSummary(entry.toString().replace("%", " " + percent));
}
}
@Override
public void setEntries(CharSequence[] entries) {
super.setEntries(entries);
trySetSummary();
}
@Override
public void setEntryValues(CharSequence[] entryValues) {
super.setEntryValues(entryValues);
trySetSummary();
}
@Override
public void setValue(String value) {
super.setValue(value);
trySetSummary();
}
}
| Java |
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.pocketworkstation.pckeyboard;
import java.util.LinkedList;
import android.content.Context;
import android.os.AsyncTask;
/**
* Base class for an in-memory dictionary that can grow dynamically and can
* be searched for suggestions and valid words.
*/
public class ExpandableDictionary extends Dictionary {
/**
* There is difference between what java and native code can handle.
* It uses 32 because Java stack overflows when greater value is used.
*/
protected static final int MAX_WORD_LENGTH = 32;
private Context mContext;
private char[] mWordBuilder = new char[MAX_WORD_LENGTH];
private int mDicTypeId;
private int mMaxDepth;
private int mInputLength;
private int[] mNextLettersFrequencies;
private StringBuilder sb = new StringBuilder(MAX_WORD_LENGTH);
private static final char QUOTE = '\'';
private boolean mRequiresReload;
private boolean mUpdatingDictionary;
// Use this lock before touching mUpdatingDictionary & mRequiresDownload
private Object mUpdatingLock = new Object();
static class Node {
char code;
int frequency;
boolean terminal;
Node parent;
NodeArray children;
LinkedList<NextWord> ngrams; // Supports ngram
}
static class NodeArray {
Node[] data;
int length = 0;
private static final int INCREMENT = 2;
NodeArray() {
data = new Node[INCREMENT];
}
void add(Node n) {
if (length + 1 > data.length) {
Node[] tempData = new Node[length + INCREMENT];
if (length > 0) {
System.arraycopy(data, 0, tempData, 0, length);
}
data = tempData;
}
data[length++] = n;
}
}
static class NextWord {
Node word;
NextWord nextWord;
int frequency;
NextWord(Node word, int frequency) {
this.word = word;
this.frequency = frequency;
}
}
private NodeArray mRoots;
private int[][] mCodes;
ExpandableDictionary(Context context, int dicTypeId) {
mContext = context;
clearDictionary();
mCodes = new int[MAX_WORD_LENGTH][];
mDicTypeId = dicTypeId;
}
public void loadDictionary() {
synchronized (mUpdatingLock) {
startDictionaryLoadingTaskLocked();
}
}
public void startDictionaryLoadingTaskLocked() {
if (!mUpdatingDictionary) {
mUpdatingDictionary = true;
mRequiresReload = false;
new LoadDictionaryTask().execute();
}
}
public void setRequiresReload(boolean reload) {
synchronized (mUpdatingLock) {
mRequiresReload = reload;
}
}
public boolean getRequiresReload() {
return mRequiresReload;
}
/** Override to load your dictionary here, on a background thread. */
public void loadDictionaryAsync() {
}
Context getContext() {
return mContext;
}
int getMaxWordLength() {
return MAX_WORD_LENGTH;
}
public void addWord(String word, int frequency) {
addWordRec(mRoots, word, 0, frequency, null);
}
private void addWordRec(NodeArray children, final String word, final int depth,
final int frequency, Node parentNode) {
final int wordLength = word.length();
final char c = word.charAt(depth);
// Does children have the current character?
final int childrenLength = children.length;
Node childNode = null;
boolean found = false;
for (int i = 0; i < childrenLength; i++) {
childNode = children.data[i];
if (childNode.code == c) {
found = true;
break;
}
}
if (!found) {
childNode = new Node();
childNode.code = c;
childNode.parent = parentNode;
children.add(childNode);
}
if (wordLength == depth + 1) {
// Terminate this word
childNode.terminal = true;
childNode.frequency = Math.max(frequency, childNode.frequency);
if (childNode.frequency > 255) childNode.frequency = 255;
return;
}
if (childNode.children == null) {
childNode.children = new NodeArray();
}
addWordRec(childNode.children, word, depth + 1, frequency, childNode);
}
@Override
public void getWords(final WordComposer codes, final WordCallback callback,
int[] nextLettersFrequencies) {
synchronized (mUpdatingLock) {
// If we need to update, start off a background task
if (mRequiresReload) startDictionaryLoadingTaskLocked();
// Currently updating contacts, don't return any results.
if (mUpdatingDictionary) return;
}
mInputLength = codes.size();
mNextLettersFrequencies = nextLettersFrequencies;
if (mCodes.length < mInputLength) mCodes = new int[mInputLength][];
// Cache the codes so that we don't have to lookup an array list
for (int i = 0; i < mInputLength; i++) {
mCodes[i] = codes.getCodesAt(i);
}
mMaxDepth = mInputLength * 3;
getWordsRec(mRoots, codes, mWordBuilder, 0, false, 1, 0, -1, callback);
for (int i = 0; i < mInputLength; i++) {
getWordsRec(mRoots, codes, mWordBuilder, 0, false, 1, 0, i, callback);
}
}
@Override
public synchronized boolean isValidWord(CharSequence word) {
synchronized (mUpdatingLock) {
// If we need to update, start off a background task
if (mRequiresReload) startDictionaryLoadingTaskLocked();
if (mUpdatingDictionary) return false;
}
final int freq = getWordFrequency(word);
return freq > -1;
}
/**
* Returns the word's frequency or -1 if not found
*/
public int getWordFrequency(CharSequence word) {
Node node = searchNode(mRoots, word, 0, word.length());
return (node == null) ? -1 : node.frequency;
}
/**
* Recursively traverse the tree for words that match the input. Input consists of
* a list of arrays. Each item in the list is one input character position. An input
* character is actually an array of multiple possible candidates. This function is not
* optimized for speed, assuming that the user dictionary will only be a few hundred words in
* size.
* @param roots node whose children have to be search for matches
* @param codes the input character codes
* @param word the word being composed as a possible match
* @param depth the depth of traversal - the length of the word being composed thus far
* @param completion whether the traversal is now in completion mode - meaning that we've
* exhausted the input and we're looking for all possible suffixes.
* @param snr current weight of the word being formed
* @param inputIndex position in the input characters. This can be off from the depth in
* case we skip over some punctuations such as apostrophe in the traversal. That is, if you type
* "wouldve", it could be matching "would've", so the depth will be one more than the
* inputIndex
* @param callback the callback class for adding a word
*/
protected void getWordsRec(NodeArray roots, final WordComposer codes, final char[] word,
final int depth, boolean completion, int snr, int inputIndex, int skipPos,
WordCallback callback) {
final int count = roots.length;
final int codeSize = mInputLength;
// Optimization: Prune out words that are too long compared to how much was typed.
if (depth > mMaxDepth) {
return;
}
int[] currentChars = null;
if (codeSize <= inputIndex) {
completion = true;
} else {
currentChars = mCodes[inputIndex];
}
for (int i = 0; i < count; i++) {
final Node node = roots.data[i];
final char c = node.code;
final char lowerC = toLowerCase(c);
final boolean terminal = node.terminal;
final NodeArray children = node.children;
final int freq = node.frequency;
if (completion) {
word[depth] = c;
if (terminal) {
if (!callback.addWord(word, 0, depth + 1, freq * snr, mDicTypeId,
DataType.UNIGRAM)) {
return;
}
// Add to frequency of next letters for predictive correction
if (mNextLettersFrequencies != null && depth >= inputIndex && skipPos < 0
&& mNextLettersFrequencies.length > word[inputIndex]) {
mNextLettersFrequencies[word[inputIndex]]++;
}
}
if (children != null) {
getWordsRec(children, codes, word, depth + 1, completion, snr, inputIndex,
skipPos, callback);
}
} else if ((c == QUOTE && currentChars[0] != QUOTE) || depth == skipPos) {
// Skip the ' and continue deeper
word[depth] = c;
if (children != null) {
getWordsRec(children, codes, word, depth + 1, completion, snr, inputIndex,
skipPos, callback);
}
} else {
// Don't use alternatives if we're looking for missing characters
final int alternativesSize = skipPos >= 0? 1 : currentChars.length;
for (int j = 0; j < alternativesSize; j++) {
final int addedAttenuation = (j > 0 ? 1 : 2);
final int currentChar = currentChars[j];
if (currentChar == -1) {
break;
}
if (currentChar == lowerC || currentChar == c) {
word[depth] = c;
if (codeSize == inputIndex + 1) {
if (terminal) {
if (INCLUDE_TYPED_WORD_IF_VALID
|| !same(word, depth + 1, codes.getTypedWord())) {
int finalFreq = freq * snr * addedAttenuation;
if (skipPos < 0) finalFreq *= FULL_WORD_FREQ_MULTIPLIER;
callback.addWord(word, 0, depth + 1, finalFreq, mDicTypeId,
DataType.UNIGRAM);
}
}
if (children != null) {
getWordsRec(children, codes, word, depth + 1,
true, snr * addedAttenuation, inputIndex + 1,
skipPos, callback);
}
} else if (children != null) {
getWordsRec(children, codes, word, depth + 1,
false, snr * addedAttenuation, inputIndex + 1,
skipPos, callback);
}
}
}
}
}
}
protected int setBigram(String word1, String word2, int frequency) {
return addOrSetBigram(word1, word2, frequency, false);
}
protected int addBigram(String word1, String word2, int frequency) {
return addOrSetBigram(word1, word2, frequency, true);
}
/**
* Adds bigrams to the in-memory trie structure that is being used to retrieve any word
* @param frequency frequency for this bigrams
* @param addFrequency if true, it adds to current frequency
* @return returns the final frequency
*/
private int addOrSetBigram(String word1, String word2, int frequency, boolean addFrequency) {
Node firstWord = searchWord(mRoots, word1, 0, null);
Node secondWord = searchWord(mRoots, word2, 0, null);
LinkedList<NextWord> bigram = firstWord.ngrams;
if (bigram == null || bigram.size() == 0) {
firstWord.ngrams = new LinkedList<NextWord>();
bigram = firstWord.ngrams;
} else {
for (NextWord nw : bigram) {
if (nw.word == secondWord) {
if (addFrequency) {
nw.frequency += frequency;
} else {
nw.frequency = frequency;
}
return nw.frequency;
}
}
}
NextWord nw = new NextWord(secondWord, frequency);
firstWord.ngrams.add(nw);
return frequency;
}
/**
* Searches for the word and add the word if it does not exist.
* @return Returns the terminal node of the word we are searching for.
*/
private Node searchWord(NodeArray children, String word, int depth, Node parentNode) {
final int wordLength = word.length();
final char c = word.charAt(depth);
// Does children have the current character?
final int childrenLength = children.length;
Node childNode = null;
boolean found = false;
for (int i = 0; i < childrenLength; i++) {
childNode = children.data[i];
if (childNode.code == c) {
found = true;
break;
}
}
if (!found) {
childNode = new Node();
childNode.code = c;
childNode.parent = parentNode;
children.add(childNode);
}
if (wordLength == depth + 1) {
// Terminate this word
childNode.terminal = true;
return childNode;
}
if (childNode.children == null) {
childNode.children = new NodeArray();
}
return searchWord(childNode.children, word, depth + 1, childNode);
}
// @VisibleForTesting
boolean reloadDictionaryIfRequired() {
synchronized (mUpdatingLock) {
// If we need to update, start off a background task
if (mRequiresReload) startDictionaryLoadingTaskLocked();
// Currently updating contacts, don't return any results.
return mUpdatingDictionary;
}
}
private void runReverseLookUp(final CharSequence previousWord, final WordCallback callback) {
Node prevWord = searchNode(mRoots, previousWord, 0, previousWord.length());
if (prevWord != null && prevWord.ngrams != null) {
reverseLookUp(prevWord.ngrams, callback);
}
}
@Override
public void getBigrams(final WordComposer codes, final CharSequence previousWord,
final WordCallback callback, int[] nextLettersFrequencies) {
if (!reloadDictionaryIfRequired()) {
runReverseLookUp(previousWord, callback);
}
}
/**
* Used only for testing purposes
* This function will wait for loading from database to be done
*/
void waitForDictionaryLoading() {
while (mUpdatingDictionary) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
}
}
/**
* reverseLookUp retrieves the full word given a list of terminal nodes and adds those words
* through callback.
* @param terminalNodes list of terminal nodes we want to add
*/
private void reverseLookUp(LinkedList<NextWord> terminalNodes,
final WordCallback callback) {
Node node;
int freq;
for (NextWord nextWord : terminalNodes) {
node = nextWord.word;
freq = nextWord.frequency;
// TODO Not the best way to limit suggestion threshold
if (freq >= UserBigramDictionary.SUGGEST_THRESHOLD) {
sb.setLength(0);
do {
sb.insert(0, node.code);
node = node.parent;
} while(node != null);
// TODO better way to feed char array?
callback.addWord(sb.toString().toCharArray(), 0, sb.length(), freq, mDicTypeId,
DataType.BIGRAM);
}
}
}
/**
* Search for the terminal node of the word
* @return Returns the terminal node of the word if the word exists
*/
private Node searchNode(final NodeArray children, final CharSequence word, final int offset,
final int length) {
// TODO Consider combining with addWordRec
final int count = children.length;
char currentChar = word.charAt(offset);
for (int j = 0; j < count; j++) {
final Node node = children.data[j];
if (node.code == currentChar) {
if (offset == length - 1) {
if (node.terminal) {
return node;
}
} else {
if (node.children != null) {
Node returnNode = searchNode(node.children, word, offset + 1, length);
if (returnNode != null) return returnNode;
}
}
}
}
return null;
}
protected void clearDictionary() {
mRoots = new NodeArray();
}
private class LoadDictionaryTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... v) {
loadDictionaryAsync();
synchronized (mUpdatingLock) {
mUpdatingDictionary = false;
}
return null;
}
}
static char toLowerCase(char c) {
if (c < BASE_CHARS.length) {
c = BASE_CHARS[c];
}
if (c >= 'A' && c <= 'Z') {
c = (char) (c | 32);
} else if (c > 127) {
c = Character.toLowerCase(c);
}
return c;
}
/**
* Table mapping most combined Latin, Greek, and Cyrillic characters
* to their base characters. If c is in range, BASE_CHARS[c] == c
* if c is not a combined character, or the base character if it
* is combined.
*/
static final char BASE_CHARS[] = {
0x0000, 0x0001, 0x0002, 0x0003, 0x0004, 0x0005, 0x0006, 0x0007,
0x0008, 0x0009, 0x000a, 0x000b, 0x000c, 0x000d, 0x000e, 0x000f,
0x0010, 0x0011, 0x0012, 0x0013, 0x0014, 0x0015, 0x0016, 0x0017,
0x0018, 0x0019, 0x001a, 0x001b, 0x001c, 0x001d, 0x001e, 0x001f,
0x0020, 0x0021, 0x0022, 0x0023, 0x0024, 0x0025, 0x0026, 0x0027,
0x0028, 0x0029, 0x002a, 0x002b, 0x002c, 0x002d, 0x002e, 0x002f,
0x0030, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, 0x0036, 0x0037,
0x0038, 0x0039, 0x003a, 0x003b, 0x003c, 0x003d, 0x003e, 0x003f,
0x0040, 0x0041, 0x0042, 0x0043, 0x0044, 0x0045, 0x0046, 0x0047,
0x0048, 0x0049, 0x004a, 0x004b, 0x004c, 0x004d, 0x004e, 0x004f,
0x0050, 0x0051, 0x0052, 0x0053, 0x0054, 0x0055, 0x0056, 0x0057,
0x0058, 0x0059, 0x005a, 0x005b, 0x005c, 0x005d, 0x005e, 0x005f,
0x0060, 0x0061, 0x0062, 0x0063, 0x0064, 0x0065, 0x0066, 0x0067,
0x0068, 0x0069, 0x006a, 0x006b, 0x006c, 0x006d, 0x006e, 0x006f,
0x0070, 0x0071, 0x0072, 0x0073, 0x0074, 0x0075, 0x0076, 0x0077,
0x0078, 0x0079, 0x007a, 0x007b, 0x007c, 0x007d, 0x007e, 0x007f,
0x0080, 0x0081, 0x0082, 0x0083, 0x0084, 0x0085, 0x0086, 0x0087,
0x0088, 0x0089, 0x008a, 0x008b, 0x008c, 0x008d, 0x008e, 0x008f,
0x0090, 0x0091, 0x0092, 0x0093, 0x0094, 0x0095, 0x0096, 0x0097,
0x0098, 0x0099, 0x009a, 0x009b, 0x009c, 0x009d, 0x009e, 0x009f,
0x0020, 0x00a1, 0x00a2, 0x00a3, 0x00a4, 0x00a5, 0x00a6, 0x00a7,
0x0020, 0x00a9, 0x0061, 0x00ab, 0x00ac, 0x00ad, 0x00ae, 0x0020,
0x00b0, 0x00b1, 0x0032, 0x0033, 0x0020, 0x03bc, 0x00b6, 0x00b7,
0x0020, 0x0031, 0x006f, 0x00bb, 0x0031, 0x0031, 0x0033, 0x00bf,
0x0041, 0x0041, 0x0041, 0x0041, 0x0041, 0x0041, 0x00c6, 0x0043,
0x0045, 0x0045, 0x0045, 0x0045, 0x0049, 0x0049, 0x0049, 0x0049,
0x00d0, 0x004e, 0x004f, 0x004f, 0x004f, 0x004f, 0x004f, 0x00d7,
0x004f, 0x0055, 0x0055, 0x0055, 0x0055, 0x0059, 0x00de, 0x0073, // Manually changed d8 to 4f
// Manually changed df to 73
0x0061, 0x0061, 0x0061, 0x0061, 0x0061, 0x0061, 0x00e6, 0x0063,
0x0065, 0x0065, 0x0065, 0x0065, 0x0069, 0x0069, 0x0069, 0x0069,
0x00f0, 0x006e, 0x006f, 0x006f, 0x006f, 0x006f, 0x006f, 0x00f7,
0x006f, 0x0075, 0x0075, 0x0075, 0x0075, 0x0079, 0x00fe, 0x0079, // Manually changed f8 to 6f
0x0041, 0x0061, 0x0041, 0x0061, 0x0041, 0x0061, 0x0043, 0x0063,
0x0043, 0x0063, 0x0043, 0x0063, 0x0043, 0x0063, 0x0044, 0x0064,
0x0110, 0x0111, 0x0045, 0x0065, 0x0045, 0x0065, 0x0045, 0x0065,
0x0045, 0x0065, 0x0045, 0x0065, 0x0047, 0x0067, 0x0047, 0x0067,
0x0047, 0x0067, 0x0047, 0x0067, 0x0048, 0x0068, 0x0126, 0x0127,
0x0049, 0x0069, 0x0049, 0x0069, 0x0049, 0x0069, 0x0049, 0x0069,
0x0049, 0x0131, 0x0049, 0x0069, 0x004a, 0x006a, 0x004b, 0x006b,
0x0138, 0x004c, 0x006c, 0x004c, 0x006c, 0x004c, 0x006c, 0x004c,
0x006c, 0x0141, 0x0142, 0x004e, 0x006e, 0x004e, 0x006e, 0x004e,
0x006e, 0x02bc, 0x014a, 0x014b, 0x004f, 0x006f, 0x004f, 0x006f,
0x004f, 0x006f, 0x0152, 0x0153, 0x0052, 0x0072, 0x0052, 0x0072,
0x0052, 0x0072, 0x0053, 0x0073, 0x0053, 0x0073, 0x0053, 0x0073,
0x0053, 0x0073, 0x0054, 0x0074, 0x0054, 0x0074, 0x0166, 0x0167,
0x0055, 0x0075, 0x0055, 0x0075, 0x0055, 0x0075, 0x0055, 0x0075,
0x0055, 0x0075, 0x0055, 0x0075, 0x0057, 0x0077, 0x0059, 0x0079,
0x0059, 0x005a, 0x007a, 0x005a, 0x007a, 0x005a, 0x007a, 0x0073,
0x0180, 0x0181, 0x0182, 0x0183, 0x0184, 0x0185, 0x0186, 0x0187,
0x0188, 0x0189, 0x018a, 0x018b, 0x018c, 0x018d, 0x018e, 0x018f,
0x0190, 0x0191, 0x0192, 0x0193, 0x0194, 0x0195, 0x0196, 0x0197,
0x0198, 0x0199, 0x019a, 0x019b, 0x019c, 0x019d, 0x019e, 0x019f,
0x004f, 0x006f, 0x01a2, 0x01a3, 0x01a4, 0x01a5, 0x01a6, 0x01a7,
0x01a8, 0x01a9, 0x01aa, 0x01ab, 0x01ac, 0x01ad, 0x01ae, 0x0055,
0x0075, 0x01b1, 0x01b2, 0x01b3, 0x01b4, 0x01b5, 0x01b6, 0x01b7,
0x01b8, 0x01b9, 0x01ba, 0x01bb, 0x01bc, 0x01bd, 0x01be, 0x01bf,
0x01c0, 0x01c1, 0x01c2, 0x01c3, 0x0044, 0x0044, 0x0064, 0x004c,
0x004c, 0x006c, 0x004e, 0x004e, 0x006e, 0x0041, 0x0061, 0x0049,
0x0069, 0x004f, 0x006f, 0x0055, 0x0075, 0x00dc, 0x00fc, 0x00dc,
0x00fc, 0x00dc, 0x00fc, 0x00dc, 0x00fc, 0x01dd, 0x00c4, 0x00e4,
0x0226, 0x0227, 0x00c6, 0x00e6, 0x01e4, 0x01e5, 0x0047, 0x0067,
0x004b, 0x006b, 0x004f, 0x006f, 0x01ea, 0x01eb, 0x01b7, 0x0292,
0x006a, 0x0044, 0x0044, 0x0064, 0x0047, 0x0067, 0x01f6, 0x01f7,
0x004e, 0x006e, 0x00c5, 0x00e5, 0x00c6, 0x00e6, 0x00d8, 0x00f8,
0x0041, 0x0061, 0x0041, 0x0061, 0x0045, 0x0065, 0x0045, 0x0065,
0x0049, 0x0069, 0x0049, 0x0069, 0x004f, 0x006f, 0x004f, 0x006f,
0x0052, 0x0072, 0x0052, 0x0072, 0x0055, 0x0075, 0x0055, 0x0075,
0x0053, 0x0073, 0x0054, 0x0074, 0x021c, 0x021d, 0x0048, 0x0068,
0x0220, 0x0221, 0x0222, 0x0223, 0x0224, 0x0225, 0x0041, 0x0061,
0x0045, 0x0065, 0x00d6, 0x00f6, 0x00d5, 0x00f5, 0x004f, 0x006f,
0x022e, 0x022f, 0x0059, 0x0079, 0x0234, 0x0235, 0x0236, 0x0237,
0x0238, 0x0239, 0x023a, 0x023b, 0x023c, 0x023d, 0x023e, 0x023f,
0x0240, 0x0241, 0x0242, 0x0243, 0x0244, 0x0245, 0x0246, 0x0247,
0x0248, 0x0249, 0x024a, 0x024b, 0x024c, 0x024d, 0x024e, 0x024f,
0x0250, 0x0251, 0x0252, 0x0253, 0x0254, 0x0255, 0x0256, 0x0257,
0x0258, 0x0259, 0x025a, 0x025b, 0x025c, 0x025d, 0x025e, 0x025f,
0x0260, 0x0261, 0x0262, 0x0263, 0x0264, 0x0265, 0x0266, 0x0267,
0x0268, 0x0269, 0x026a, 0x026b, 0x026c, 0x026d, 0x026e, 0x026f,
0x0270, 0x0271, 0x0272, 0x0273, 0x0274, 0x0275, 0x0276, 0x0277,
0x0278, 0x0279, 0x027a, 0x027b, 0x027c, 0x027d, 0x027e, 0x027f,
0x0280, 0x0281, 0x0282, 0x0283, 0x0284, 0x0285, 0x0286, 0x0287,
0x0288, 0x0289, 0x028a, 0x028b, 0x028c, 0x028d, 0x028e, 0x028f,
0x0290, 0x0291, 0x0292, 0x0293, 0x0294, 0x0295, 0x0296, 0x0297,
0x0298, 0x0299, 0x029a, 0x029b, 0x029c, 0x029d, 0x029e, 0x029f,
0x02a0, 0x02a1, 0x02a2, 0x02a3, 0x02a4, 0x02a5, 0x02a6, 0x02a7,
0x02a8, 0x02a9, 0x02aa, 0x02ab, 0x02ac, 0x02ad, 0x02ae, 0x02af,
0x0068, 0x0266, 0x006a, 0x0072, 0x0279, 0x027b, 0x0281, 0x0077,
0x0079, 0x02b9, 0x02ba, 0x02bb, 0x02bc, 0x02bd, 0x02be, 0x02bf,
0x02c0, 0x02c1, 0x02c2, 0x02c3, 0x02c4, 0x02c5, 0x02c6, 0x02c7,
0x02c8, 0x02c9, 0x02ca, 0x02cb, 0x02cc, 0x02cd, 0x02ce, 0x02cf,
0x02d0, 0x02d1, 0x02d2, 0x02d3, 0x02d4, 0x02d5, 0x02d6, 0x02d7,
0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x02de, 0x02df,
0x0263, 0x006c, 0x0073, 0x0078, 0x0295, 0x02e5, 0x02e6, 0x02e7,
0x02e8, 0x02e9, 0x02ea, 0x02eb, 0x02ec, 0x02ed, 0x02ee, 0x02ef,
0x02f0, 0x02f1, 0x02f2, 0x02f3, 0x02f4, 0x02f5, 0x02f6, 0x02f7,
0x02f8, 0x02f9, 0x02fa, 0x02fb, 0x02fc, 0x02fd, 0x02fe, 0x02ff,
0x0300, 0x0301, 0x0302, 0x0303, 0x0304, 0x0305, 0x0306, 0x0307,
0x0308, 0x0309, 0x030a, 0x030b, 0x030c, 0x030d, 0x030e, 0x030f,
0x0310, 0x0311, 0x0312, 0x0313, 0x0314, 0x0315, 0x0316, 0x0317,
0x0318, 0x0319, 0x031a, 0x031b, 0x031c, 0x031d, 0x031e, 0x031f,
0x0320, 0x0321, 0x0322, 0x0323, 0x0324, 0x0325, 0x0326, 0x0327,
0x0328, 0x0329, 0x032a, 0x032b, 0x032c, 0x032d, 0x032e, 0x032f,
0x0330, 0x0331, 0x0332, 0x0333, 0x0334, 0x0335, 0x0336, 0x0337,
0x0338, 0x0339, 0x033a, 0x033b, 0x033c, 0x033d, 0x033e, 0x033f,
0x0300, 0x0301, 0x0342, 0x0313, 0x0308, 0x0345, 0x0346, 0x0347,
0x0348, 0x0349, 0x034a, 0x034b, 0x034c, 0x034d, 0x034e, 0x034f,
0x0350, 0x0351, 0x0352, 0x0353, 0x0354, 0x0355, 0x0356, 0x0357,
0x0358, 0x0359, 0x035a, 0x035b, 0x035c, 0x035d, 0x035e, 0x035f,
0x0360, 0x0361, 0x0362, 0x0363, 0x0364, 0x0365, 0x0366, 0x0367,
0x0368, 0x0369, 0x036a, 0x036b, 0x036c, 0x036d, 0x036e, 0x036f,
0x0370, 0x0371, 0x0372, 0x0373, 0x02b9, 0x0375, 0x0376, 0x0377,
0x0378, 0x0379, 0x0020, 0x037b, 0x037c, 0x037d, 0x003b, 0x037f,
0x0380, 0x0381, 0x0382, 0x0383, 0x0020, 0x00a8, 0x0391, 0x00b7,
0x0395, 0x0397, 0x0399, 0x038b, 0x039f, 0x038d, 0x03a5, 0x03a9,
0x03ca, 0x0391, 0x0392, 0x0393, 0x0394, 0x0395, 0x0396, 0x0397,
0x0398, 0x0399, 0x039a, 0x039b, 0x039c, 0x039d, 0x039e, 0x039f,
0x03a0, 0x03a1, 0x03a2, 0x03a3, 0x03a4, 0x03a5, 0x03a6, 0x03a7,
0x03a8, 0x03a9, 0x0399, 0x03a5, 0x03b1, 0x03b5, 0x03b7, 0x03b9,
0x03cb, 0x03b1, 0x03b2, 0x03b3, 0x03b4, 0x03b5, 0x03b6, 0x03b7,
0x03b8, 0x03b9, 0x03ba, 0x03bb, 0x03bc, 0x03bd, 0x03be, 0x03bf,
0x03c0, 0x03c1, 0x03c2, 0x03c3, 0x03c4, 0x03c5, 0x03c6, 0x03c7,
0x03c8, 0x03c9, 0x03b9, 0x03c5, 0x03bf, 0x03c5, 0x03c9, 0x03cf,
0x03b2, 0x03b8, 0x03a5, 0x03d2, 0x03d2, 0x03c6, 0x03c0, 0x03d7,
0x03d8, 0x03d9, 0x03da, 0x03db, 0x03dc, 0x03dd, 0x03de, 0x03df,
0x03e0, 0x03e1, 0x03e2, 0x03e3, 0x03e4, 0x03e5, 0x03e6, 0x03e7,
0x03e8, 0x03e9, 0x03ea, 0x03eb, 0x03ec, 0x03ed, 0x03ee, 0x03ef,
0x03ba, 0x03c1, 0x03c2, 0x03f3, 0x0398, 0x03b5, 0x03f6, 0x03f7,
0x03f8, 0x03a3, 0x03fa, 0x03fb, 0x03fc, 0x03fd, 0x03fe, 0x03ff,
0x0415, 0x0415, 0x0402, 0x0413, 0x0404, 0x0405, 0x0406, 0x0406,
0x0408, 0x0409, 0x040a, 0x040b, 0x041a, 0x0418, 0x0423, 0x040f,
0x0410, 0x0411, 0x0412, 0x0413, 0x0414, 0x0415, 0x0416, 0x0417,
0x0418, 0x0418, 0x041a, 0x041b, 0x041c, 0x041d, 0x041e, 0x041f,
0x0420, 0x0421, 0x0422, 0x0423, 0x0424, 0x0425, 0x0426, 0x0427,
0x0428, 0x0429, 0x042a, 0x042b, 0x042c, 0x042d, 0x042e, 0x042f,
0x0430, 0x0431, 0x0432, 0x0433, 0x0434, 0x0435, 0x0436, 0x0437,
0x0438, 0x0438, 0x043a, 0x043b, 0x043c, 0x043d, 0x043e, 0x043f,
0x0440, 0x0441, 0x0442, 0x0443, 0x0444, 0x0445, 0x0446, 0x0447,
0x0448, 0x0449, 0x044a, 0x044b, 0x044c, 0x044d, 0x044e, 0x044f,
0x0435, 0x0435, 0x0452, 0x0433, 0x0454, 0x0455, 0x0456, 0x0456,
0x0458, 0x0459, 0x045a, 0x045b, 0x043a, 0x0438, 0x0443, 0x045f,
0x0460, 0x0461, 0x0462, 0x0463, 0x0464, 0x0465, 0x0466, 0x0467,
0x0468, 0x0469, 0x046a, 0x046b, 0x046c, 0x046d, 0x046e, 0x046f,
0x0470, 0x0471, 0x0472, 0x0473, 0x0474, 0x0475, 0x0474, 0x0475,
0x0478, 0x0479, 0x047a, 0x047b, 0x047c, 0x047d, 0x047e, 0x047f,
0x0480, 0x0481, 0x0482, 0x0483, 0x0484, 0x0485, 0x0486, 0x0487,
0x0488, 0x0489, 0x048a, 0x048b, 0x048c, 0x048d, 0x048e, 0x048f,
0x0490, 0x0491, 0x0492, 0x0493, 0x0494, 0x0495, 0x0496, 0x0497,
0x0498, 0x0499, 0x049a, 0x049b, 0x049c, 0x049d, 0x049e, 0x049f,
0x04a0, 0x04a1, 0x04a2, 0x04a3, 0x04a4, 0x04a5, 0x04a6, 0x04a7,
0x04a8, 0x04a9, 0x04aa, 0x04ab, 0x04ac, 0x04ad, 0x04ae, 0x04af,
0x04b0, 0x04b1, 0x04b2, 0x04b3, 0x04b4, 0x04b5, 0x04b6, 0x04b7,
0x04b8, 0x04b9, 0x04ba, 0x04bb, 0x04bc, 0x04bd, 0x04be, 0x04bf,
0x04c0, 0x0416, 0x0436, 0x04c3, 0x04c4, 0x04c5, 0x04c6, 0x04c7,
0x04c8, 0x04c9, 0x04ca, 0x04cb, 0x04cc, 0x04cd, 0x04ce, 0x04cf,
0x0410, 0x0430, 0x0410, 0x0430, 0x04d4, 0x04d5, 0x0415, 0x0435,
0x04d8, 0x04d9, 0x04d8, 0x04d9, 0x0416, 0x0436, 0x0417, 0x0437,
0x04e0, 0x04e1, 0x0418, 0x0438, 0x0418, 0x0438, 0x041e, 0x043e,
0x04e8, 0x04e9, 0x04e8, 0x04e9, 0x042d, 0x044d, 0x0423, 0x0443,
0x0423, 0x0443, 0x0423, 0x0443, 0x0427, 0x0447, 0x04f6, 0x04f7,
0x042b, 0x044b, 0x04fa, 0x04fb, 0x04fc, 0x04fd, 0x04fe, 0x04ff,
};
// generated with:
// cat UnicodeData.txt | perl -e 'while (<>) { @foo = split(/;/); $foo[5] =~ s/<.*> //; $base[hex($foo[0])] = hex($foo[5]);} for ($i = 0; $i < 0x500; $i += 8) { for ($j = $i; $j < $i + 8; $j++) { printf("0x%04x, ", $base[$j] ? $base[$j] : $j)}; print "\n"; }'
}
| Java |
package org.pocketworkstation.pckeyboard;
import android.content.Context;
import android.preference.EditTextPreference;
import android.util.AttributeSet;
public class AutoSummaryEditTextPreference extends EditTextPreference {
public AutoSummaryEditTextPreference(Context context) {
super(context);
}
public AutoSummaryEditTextPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
public AutoSummaryEditTextPreference(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
}
@Override
public void setText(String text) {
super.setText(text);
setSummary(text);
}
}
| Java |
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import android.content.Context;
import android.text.AutoText;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
/**
* This class loads a dictionary and provides a list of suggestions for a given sequence of
* characters. This includes corrections and completions.
* @hide pending API Council Approval
*/
public class Suggest implements Dictionary.WordCallback {
private static String TAG = "PCKeyboard";
public static final int APPROX_MAX_WORD_LENGTH = 32;
public static final int CORRECTION_NONE = 0;
public static final int CORRECTION_BASIC = 1;
public static final int CORRECTION_FULL = 2;
public static final int CORRECTION_FULL_BIGRAM = 3;
/**
* Words that appear in both bigram and unigram data gets multiplier ranging from
* BIGRAM_MULTIPLIER_MIN to BIGRAM_MULTIPLIER_MAX depending on the frequency score from
* bigram data.
*/
public static final double BIGRAM_MULTIPLIER_MIN = 1.2;
public static final double BIGRAM_MULTIPLIER_MAX = 1.5;
/**
* Maximum possible bigram frequency. Will depend on how many bits are being used in data
* structure. Maximum bigram freqeuncy will get the BIGRAM_MULTIPLIER_MAX as the multiplier.
*/
public static final int MAXIMUM_BIGRAM_FREQUENCY = 127;
public static final int DIC_USER_TYPED = 0;
public static final int DIC_MAIN = 1;
public static final int DIC_USER = 2;
public static final int DIC_AUTO = 3;
public static final int DIC_CONTACTS = 4;
// If you add a type of dictionary, increment DIC_TYPE_LAST_ID
public static final int DIC_TYPE_LAST_ID = 4;
static final int LARGE_DICTIONARY_THRESHOLD = 200 * 1000;
private BinaryDictionary mMainDict;
private Dictionary mUserDictionary;
private Dictionary mAutoDictionary;
private Dictionary mContactsDictionary;
private Dictionary mUserBigramDictionary;
private int mPrefMaxSuggestions = 12;
private static final int PREF_MAX_BIGRAMS = 60;
private boolean mAutoTextEnabled;
private int[] mPriorities = new int[mPrefMaxSuggestions];
private int[] mBigramPriorities = new int[PREF_MAX_BIGRAMS];
// Handle predictive correction for only the first 1280 characters for performance reasons
// If we support scripts that need latin characters beyond that, we should probably use some
// kind of a sparse array or language specific list with a mapping lookup table.
// 1280 is the size of the BASE_CHARS array in ExpandableDictionary, which is a basic set of
// latin characters.
private int[] mNextLettersFrequencies = new int[1280];
private ArrayList<CharSequence> mSuggestions = new ArrayList<CharSequence>();
ArrayList<CharSequence> mBigramSuggestions = new ArrayList<CharSequence>();
private ArrayList<CharSequence> mStringPool = new ArrayList<CharSequence>();
private boolean mHaveCorrection;
private CharSequence mOriginalWord;
private String mLowerOriginalWord;
// TODO: Remove these member variables by passing more context to addWord() callback method
private boolean mIsFirstCharCapitalized;
private boolean mIsAllUpperCase;
private int mCorrectionMode = CORRECTION_BASIC;
public Suggest(Context context, int[] dictionaryResId) {
mMainDict = new BinaryDictionary(context, dictionaryResId, DIC_MAIN);
if (!hasMainDictionary()) {
Locale locale = context.getResources().getConfiguration().locale;
BinaryDictionary plug = PluginManager.getDictionary(context, locale.getLanguage());
if (plug != null) {
mMainDict.close();
mMainDict = plug;
}
}
initPool();
}
public Suggest(Context context, ByteBuffer byteBuffer) {
mMainDict = new BinaryDictionary(context, byteBuffer, DIC_MAIN);
initPool();
}
private void initPool() {
for (int i = 0; i < mPrefMaxSuggestions; i++) {
StringBuilder sb = new StringBuilder(getApproxMaxWordLength());
mStringPool.add(sb);
}
}
public void setAutoTextEnabled(boolean enabled) {
mAutoTextEnabled = enabled;
}
public int getCorrectionMode() {
return mCorrectionMode;
}
public void setCorrectionMode(int mode) {
mCorrectionMode = mode;
}
public boolean hasMainDictionary() {
return mMainDict.getSize() > LARGE_DICTIONARY_THRESHOLD;
}
public int getApproxMaxWordLength() {
return APPROX_MAX_WORD_LENGTH;
}
/**
* Sets an optional user dictionary resource to be loaded. The user dictionary is consulted
* before the main dictionary, if set.
*/
public void setUserDictionary(Dictionary userDictionary) {
mUserDictionary = userDictionary;
}
/**
* Sets an optional contacts dictionary resource to be loaded.
*/
public void setContactsDictionary(Dictionary userDictionary) {
mContactsDictionary = userDictionary;
}
public void setAutoDictionary(Dictionary autoDictionary) {
mAutoDictionary = autoDictionary;
}
public void setUserBigramDictionary(Dictionary userBigramDictionary) {
mUserBigramDictionary = userBigramDictionary;
}
/**
* Number of suggestions to generate from the input key sequence. This has
* to be a number between 1 and 100 (inclusive).
* @param maxSuggestions
* @throws IllegalArgumentException if the number is out of range
*/
public void setMaxSuggestions(int maxSuggestions) {
if (maxSuggestions < 1 || maxSuggestions > 100) {
throw new IllegalArgumentException("maxSuggestions must be between 1 and 100");
}
mPrefMaxSuggestions = maxSuggestions;
mPriorities = new int[mPrefMaxSuggestions];
mBigramPriorities = new int[PREF_MAX_BIGRAMS];
collectGarbage(mSuggestions, mPrefMaxSuggestions);
while (mStringPool.size() < mPrefMaxSuggestions) {
StringBuilder sb = new StringBuilder(getApproxMaxWordLength());
mStringPool.add(sb);
}
}
private boolean haveSufficientCommonality(String original, CharSequence suggestion) {
final int originalLength = original.length();
final int suggestionLength = suggestion.length();
final int minLength = Math.min(originalLength, suggestionLength);
if (minLength <= 2) return true;
int matching = 0;
int lessMatching = 0; // Count matches if we skip one character
int i;
for (i = 0; i < minLength; i++) {
final char origChar = ExpandableDictionary.toLowerCase(original.charAt(i));
if (origChar == ExpandableDictionary.toLowerCase(suggestion.charAt(i))) {
matching++;
lessMatching++;
} else if (i + 1 < suggestionLength
&& origChar == ExpandableDictionary.toLowerCase(suggestion.charAt(i + 1))) {
lessMatching++;
}
}
matching = Math.max(matching, lessMatching);
if (minLength <= 4) {
return matching >= 2;
} else {
return matching > minLength / 2;
}
}
/**
* Returns a list of words that match the list of character codes passed in.
* This list will be overwritten the next time this function is called.
* @param view a view for retrieving the context for AutoText
* @param wordComposer contains what is currently being typed
* @param prevWordForBigram previous word (used only for bigram)
* @return list of suggestions.
*/
public List<CharSequence> getSuggestions(View view, WordComposer wordComposer,
boolean includeTypedWordIfValid, CharSequence prevWordForBigram) {
LatinImeLogger.onStartSuggestion(prevWordForBigram);
mHaveCorrection = false;
mIsFirstCharCapitalized = wordComposer.isFirstCharCapitalized();
mIsAllUpperCase = wordComposer.isAllUpperCase();
collectGarbage(mSuggestions, mPrefMaxSuggestions);
Arrays.fill(mPriorities, 0);
Arrays.fill(mNextLettersFrequencies, 0);
// Save a lowercase version of the original word
mOriginalWord = wordComposer.getTypedWord();
if (mOriginalWord != null) {
final String mOriginalWordString = mOriginalWord.toString();
mOriginalWord = mOriginalWordString;
mLowerOriginalWord = mOriginalWordString.toLowerCase();
// Treating USER_TYPED as UNIGRAM suggestion for logging now.
LatinImeLogger.onAddSuggestedWord(mOriginalWordString, Suggest.DIC_USER_TYPED,
Dictionary.DataType.UNIGRAM);
} else {
mLowerOriginalWord = "";
}
if (wordComposer.size() == 1 && (mCorrectionMode == CORRECTION_FULL_BIGRAM
|| mCorrectionMode == CORRECTION_BASIC)) {
// At first character typed, search only the bigrams
Arrays.fill(mBigramPriorities, 0);
collectGarbage(mBigramSuggestions, PREF_MAX_BIGRAMS);
if (!TextUtils.isEmpty(prevWordForBigram)) {
CharSequence lowerPrevWord = prevWordForBigram.toString().toLowerCase();
if (mMainDict.isValidWord(lowerPrevWord)) {
prevWordForBigram = lowerPrevWord;
}
if (mUserBigramDictionary != null) {
mUserBigramDictionary.getBigrams(wordComposer, prevWordForBigram, this,
mNextLettersFrequencies);
}
if (mContactsDictionary != null) {
mContactsDictionary.getBigrams(wordComposer, prevWordForBigram, this,
mNextLettersFrequencies);
}
if (mMainDict != null) {
mMainDict.getBigrams(wordComposer, prevWordForBigram, this,
mNextLettersFrequencies);
}
char currentChar = wordComposer.getTypedWord().charAt(0);
char currentCharUpper = Character.toUpperCase(currentChar);
int count = 0;
int bigramSuggestionSize = mBigramSuggestions.size();
for (int i = 0; i < bigramSuggestionSize; i++) {
if (mBigramSuggestions.get(i).charAt(0) == currentChar
|| mBigramSuggestions.get(i).charAt(0) == currentCharUpper) {
int poolSize = mStringPool.size();
StringBuilder sb = poolSize > 0 ?
(StringBuilder) mStringPool.remove(poolSize - 1)
: new StringBuilder(getApproxMaxWordLength());
sb.setLength(0);
sb.append(mBigramSuggestions.get(i));
mSuggestions.add(count++, sb);
if (count > mPrefMaxSuggestions) break;
}
}
}
} else if (wordComposer.size() > 1) {
// At second character typed, search the unigrams (scores being affected by bigrams)
if (mUserDictionary != null || mContactsDictionary != null) {
if (mUserDictionary != null) {
mUserDictionary.getWords(wordComposer, this, mNextLettersFrequencies);
}
if (mContactsDictionary != null) {
mContactsDictionary.getWords(wordComposer, this, mNextLettersFrequencies);
}
if (mSuggestions.size() > 0 && isValidWord(mOriginalWord)
&& (mCorrectionMode == CORRECTION_FULL
|| mCorrectionMode == CORRECTION_FULL_BIGRAM)) {
mHaveCorrection = true;
}
}
mMainDict.getWords(wordComposer, this, mNextLettersFrequencies);
if ((mCorrectionMode == CORRECTION_FULL || mCorrectionMode == CORRECTION_FULL_BIGRAM)
&& mSuggestions.size() > 0) {
mHaveCorrection = true;
}
}
if (mOriginalWord != null) {
mSuggestions.add(0, mOriginalWord.toString());
}
// Check if the first suggestion has a minimum number of characters in common
if (wordComposer.size() > 1 && mSuggestions.size() > 1
&& (mCorrectionMode == CORRECTION_FULL
|| mCorrectionMode == CORRECTION_FULL_BIGRAM)) {
if (!haveSufficientCommonality(mLowerOriginalWord, mSuggestions.get(1))) {
mHaveCorrection = false;
}
}
if (mAutoTextEnabled) {
int i = 0;
int max = 6;
// Don't autotext the suggestions from the dictionaries
if (mCorrectionMode == CORRECTION_BASIC) max = 1;
while (i < mSuggestions.size() && i < max) {
String suggestedWord = mSuggestions.get(i).toString().toLowerCase();
CharSequence autoText =
AutoText.get(suggestedWord, 0, suggestedWord.length(), view);
// Is there an AutoText correction?
boolean canAdd = autoText != null;
// Is that correction already the current prediction (or original word)?
canAdd &= !TextUtils.equals(autoText, mSuggestions.get(i));
// Is that correction already the next predicted word?
if (canAdd && i + 1 < mSuggestions.size() && mCorrectionMode != CORRECTION_BASIC) {
canAdd &= !TextUtils.equals(autoText, mSuggestions.get(i + 1));
}
if (canAdd) {
mHaveCorrection = true;
mSuggestions.add(i + 1, autoText);
i++;
}
i++;
}
}
removeDupes();
return mSuggestions;
}
public int[] getNextLettersFrequencies() {
return mNextLettersFrequencies;
}
private void removeDupes() {
final ArrayList<CharSequence> suggestions = mSuggestions;
if (suggestions.size() < 2) return;
int i = 1;
// Don't cache suggestions.size(), since we may be removing items
while (i < suggestions.size()) {
final CharSequence cur = suggestions.get(i);
// Compare each candidate with each previous candidate
for (int j = 0; j < i; j++) {
CharSequence previous = suggestions.get(j);
if (TextUtils.equals(cur, previous)) {
removeFromSuggestions(i);
i--;
break;
}
}
i++;
}
}
private void removeFromSuggestions(int index) {
CharSequence garbage = mSuggestions.remove(index);
if (garbage != null && garbage instanceof StringBuilder) {
mStringPool.add(garbage);
}
}
public boolean hasMinimalCorrection() {
return mHaveCorrection;
}
private boolean compareCaseInsensitive(final String mLowerOriginalWord,
final char[] word, final int offset, final int length) {
final int originalLength = mLowerOriginalWord.length();
if (originalLength == length && Character.isUpperCase(word[offset])) {
for (int i = 0; i < originalLength; i++) {
if (mLowerOriginalWord.charAt(i) != Character.toLowerCase(word[offset+i])) {
return false;
}
}
return true;
}
return false;
}
public boolean addWord(final char[] word, final int offset, final int length, int freq,
final int dicTypeId, final Dictionary.DataType dataType) {
Dictionary.DataType dataTypeForLog = dataType;
ArrayList<CharSequence> suggestions;
int[] priorities;
int prefMaxSuggestions;
if(dataType == Dictionary.DataType.BIGRAM) {
suggestions = mBigramSuggestions;
priorities = mBigramPriorities;
prefMaxSuggestions = PREF_MAX_BIGRAMS;
} else {
suggestions = mSuggestions;
priorities = mPriorities;
prefMaxSuggestions = mPrefMaxSuggestions;
}
int pos = 0;
// Check if it's the same word, only caps are different
if (compareCaseInsensitive(mLowerOriginalWord, word, offset, length)) {
pos = 0;
} else {
if (dataType == Dictionary.DataType.UNIGRAM) {
// Check if the word was already added before (by bigram data)
int bigramSuggestion = searchBigramSuggestion(word,offset,length);
if(bigramSuggestion >= 0) {
dataTypeForLog = Dictionary.DataType.BIGRAM;
// turn freq from bigram into multiplier specified above
double multiplier = (((double) mBigramPriorities[bigramSuggestion])
/ MAXIMUM_BIGRAM_FREQUENCY)
* (BIGRAM_MULTIPLIER_MAX - BIGRAM_MULTIPLIER_MIN)
+ BIGRAM_MULTIPLIER_MIN;
/* Log.d(TAG,"bigram num: " + bigramSuggestion
+ " wordB: " + mBigramSuggestions.get(bigramSuggestion).toString()
+ " currentPriority: " + freq + " bigramPriority: "
+ mBigramPriorities[bigramSuggestion]
+ " multiplier: " + multiplier); */
freq = (int)Math.round((freq * multiplier));
}
}
// Check the last one's priority and bail
if (priorities[prefMaxSuggestions - 1] >= freq) return true;
while (pos < prefMaxSuggestions) {
if (priorities[pos] < freq
|| (priorities[pos] == freq && length < suggestions.get(pos).length())) {
break;
}
pos++;
}
}
if (pos >= prefMaxSuggestions) {
return true;
}
System.arraycopy(priorities, pos, priorities, pos + 1,
prefMaxSuggestions - pos - 1);
priorities[pos] = freq;
int poolSize = mStringPool.size();
StringBuilder sb = poolSize > 0 ? (StringBuilder) mStringPool.remove(poolSize - 1)
: new StringBuilder(getApproxMaxWordLength());
sb.setLength(0);
if (mIsAllUpperCase) {
sb.append(new String(word, offset, length).toUpperCase());
} else if (mIsFirstCharCapitalized) {
sb.append(Character.toUpperCase(word[offset]));
if (length > 1) {
sb.append(word, offset + 1, length - 1);
}
} else {
sb.append(word, offset, length);
}
suggestions.add(pos, sb);
if (suggestions.size() > prefMaxSuggestions) {
CharSequence garbage = suggestions.remove(prefMaxSuggestions);
if (garbage instanceof StringBuilder) {
mStringPool.add(garbage);
}
} else {
LatinImeLogger.onAddSuggestedWord(sb.toString(), dicTypeId, dataTypeForLog);
}
return true;
}
private int searchBigramSuggestion(final char[] word, final int offset, final int length) {
// TODO This is almost O(n^2). Might need fix.
// search whether the word appeared in bigram data
int bigramSuggestSize = mBigramSuggestions.size();
for(int i = 0; i < bigramSuggestSize; i++) {
if(mBigramSuggestions.get(i).length() == length) {
boolean chk = true;
for(int j = 0; j < length; j++) {
if(mBigramSuggestions.get(i).charAt(j) != word[offset+j]) {
chk = false;
break;
}
}
if(chk) return i;
}
}
return -1;
}
public boolean isValidWord(final CharSequence word) {
if (word == null || word.length() == 0) {
return false;
}
return mMainDict.isValidWord(word)
|| (mUserDictionary != null && mUserDictionary.isValidWord(word))
|| (mAutoDictionary != null && mAutoDictionary.isValidWord(word))
|| (mContactsDictionary != null && mContactsDictionary.isValidWord(word));
}
private void collectGarbage(ArrayList<CharSequence> suggestions, int prefMaxSuggestions) {
int poolSize = mStringPool.size();
int garbageSize = suggestions.size();
while (poolSize < prefMaxSuggestions && garbageSize > 0) {
CharSequence garbage = suggestions.get(garbageSize - 1);
if (garbage != null && garbage instanceof StringBuilder) {
mStringPool.add(garbage);
poolSize++;
}
garbageSize--;
}
if (poolSize == prefMaxSuggestions + 1) {
Log.w("Suggest", "String pool got too big: " + poolSize);
}
suggestions.clear();
}
public void close() {
if (mMainDict != null) {
mMainDict.close();
}
}
}
| Java |
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.PopupWindow;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class CandidateView extends View {
private static final int OUT_OF_BOUNDS_WORD_INDEX = -1;
private static final int OUT_OF_BOUNDS_X_COORD = -1;
private LatinIME mService;
private final ArrayList<CharSequence> mSuggestions = new ArrayList<CharSequence>();
private boolean mShowingCompletions;
private CharSequence mSelectedString;
private int mSelectedIndex;
private int mTouchX = OUT_OF_BOUNDS_X_COORD;
private final Drawable mSelectionHighlight;
private boolean mTypedWordValid;
private boolean mHaveMinimalSuggestion;
private Rect mBgPadding;
private final TextView mPreviewText;
private final PopupWindow mPreviewPopup;
private int mCurrentWordIndex;
private Drawable mDivider;
private static final int MAX_SUGGESTIONS = 32;
private static final int SCROLL_PIXELS = 20;
private final int[] mWordWidth = new int[MAX_SUGGESTIONS];
private final int[] mWordX = new int[MAX_SUGGESTIONS];
private int mPopupPreviewX;
private int mPopupPreviewY;
private static final int X_GAP = 10;
private final int mColorNormal;
private final int mColorRecommended;
private final int mColorOther;
private final Paint mPaint;
private final int mDescent;
private boolean mScrolled;
private boolean mShowingAddToDictionary;
private CharSequence mAddToDictionaryHint;
private int mTargetScrollX;
private final int mMinTouchableWidth;
private int mTotalWidth;
private final GestureDetector mGestureDetector;
/**
* Construct a CandidateView for showing suggested words for completion.
* @param context
* @param attrs
*/
public CandidateView(Context context, AttributeSet attrs) {
super(context, attrs);
mSelectionHighlight = context.getResources().getDrawable(
R.drawable.list_selector_background_pressed);
LayoutInflater inflate =
(LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resources res = context.getResources();
mPreviewPopup = new PopupWindow(context);
mPreviewText = (TextView) inflate.inflate(R.layout.candidate_preview, null);
mPreviewPopup.setWindowLayoutMode(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
mPreviewPopup.setContentView(mPreviewText);
mPreviewPopup.setBackgroundDrawable(null);
mPreviewPopup.setAnimationStyle(R.style.KeyPreviewAnimation);
mColorNormal = res.getColor(R.color.candidate_normal);
mColorRecommended = res.getColor(R.color.candidate_recommended);
mColorOther = res.getColor(R.color.candidate_other);
mDivider = res.getDrawable(R.drawable.keyboard_suggest_strip_divider);
mAddToDictionaryHint = res.getString(R.string.hint_add_to_dictionary);
mPaint = new Paint();
mPaint.setColor(mColorNormal);
mPaint.setAntiAlias(true);
mPaint.setTextSize(mPreviewText.getTextSize() * LatinIME.sKeyboardSettings.candidateScalePref);
mPaint.setStrokeWidth(0);
mPaint.setTextAlign(Align.CENTER);
mDescent = (int) mPaint.descent();
mMinTouchableWidth = (int)res.getDimension(R.dimen.candidate_min_touchable_width);
mGestureDetector = new GestureDetector(
new CandidateStripGestureListener(mMinTouchableWidth));
setWillNotDraw(false);
setHorizontalScrollBarEnabled(false);
setVerticalScrollBarEnabled(false);
scrollTo(0, getScrollY());
}
private class CandidateStripGestureListener extends GestureDetector.SimpleOnGestureListener {
private final int mTouchSlopSquare;
public CandidateStripGestureListener(int touchSlop) {
// Slightly reluctant to scroll to be able to easily choose the suggestion
mTouchSlopSquare = touchSlop * touchSlop;
}
@Override
public void onLongPress(MotionEvent me) {
if (mSuggestions.size() > 0) {
if (me.getX() + getScrollX() < mWordWidth[0] && getScrollX() < 10) {
longPressFirstWord();
}
}
}
@Override
public boolean onDown(MotionEvent e) {
mScrolled = false;
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2,
float distanceX, float distanceY) {
if (!mScrolled) {
// This is applied only when we recognize that scrolling is starting.
final int deltaX = (int) (e2.getX() - e1.getX());
final int deltaY = (int) (e2.getY() - e1.getY());
final int distance = (deltaX * deltaX) + (deltaY * deltaY);
if (distance < mTouchSlopSquare) {
return true;
}
mScrolled = true;
}
final int width = getWidth();
mScrolled = true;
int scrollX = getScrollX();
scrollX += (int) distanceX;
if (scrollX < 0) {
scrollX = 0;
}
if (distanceX > 0 && scrollX + width > mTotalWidth) {
scrollX -= (int) distanceX;
}
mTargetScrollX = scrollX;
scrollTo(scrollX, getScrollY());
hidePreview();
invalidate();
return true;
}
}
/**
* A connection back to the service to communicate with the text field
* @param listener
*/
public void setService(LatinIME listener) {
mService = listener;
}
@Override
public int computeHorizontalScrollRange() {
return mTotalWidth;
}
/**
* If the canvas is null, then only touch calculations are performed to pick the target
* candidate.
*/
@Override
protected void onDraw(Canvas canvas) {
if (canvas != null) {
super.onDraw(canvas);
}
mTotalWidth = 0;
final int height = getHeight();
if (mBgPadding == null) {
mBgPadding = new Rect(0, 0, 0, 0);
if (getBackground() != null) {
getBackground().getPadding(mBgPadding);
}
mDivider.setBounds(0, 0, mDivider.getIntrinsicWidth(),
mDivider.getIntrinsicHeight());
}
final int count = mSuggestions.size();
final Rect bgPadding = mBgPadding;
final Paint paint = mPaint;
final int touchX = mTouchX;
final int scrollX = getScrollX();
final boolean scrolled = mScrolled;
final boolean typedWordValid = mTypedWordValid;
final int y = (int) (height + mPaint.getTextSize() - mDescent) / 2;
boolean existsAutoCompletion = false;
int x = 0;
for (int i = 0; i < count; i++) {
CharSequence suggestion = mSuggestions.get(i);
if (suggestion == null) continue;
final int wordLength = suggestion.length();
paint.setColor(mColorNormal);
if (mHaveMinimalSuggestion
&& ((i == 1 && !typedWordValid) || (i == 0 && typedWordValid))) {
paint.setTypeface(Typeface.DEFAULT_BOLD);
paint.setColor(mColorRecommended);
existsAutoCompletion = true;
} else if (i != 0 || (wordLength == 1 && count > 1)) {
// HACK: even if i == 0, we use mColorOther when this suggestion's length is 1 and
// there are multiple suggestions, such as the default punctuation list.
paint.setColor(mColorOther);
}
int wordWidth;
if ((wordWidth = mWordWidth[i]) == 0) {
float textWidth = paint.measureText(suggestion, 0, wordLength);
wordWidth = Math.max(mMinTouchableWidth, (int) textWidth + X_GAP * 2);
mWordWidth[i] = wordWidth;
}
mWordX[i] = x;
if (touchX != OUT_OF_BOUNDS_X_COORD && !scrolled
&& touchX + scrollX >= x && touchX + scrollX < x + wordWidth) {
if (canvas != null && !mShowingAddToDictionary) {
canvas.translate(x, 0);
mSelectionHighlight.setBounds(0, bgPadding.top, wordWidth, height);
mSelectionHighlight.draw(canvas);
canvas.translate(-x, 0);
}
mSelectedString = suggestion;
mSelectedIndex = i;
}
if (canvas != null) {
canvas.drawText(suggestion, 0, wordLength, x + wordWidth / 2, y, paint);
paint.setColor(mColorOther);
canvas.translate(x + wordWidth, 0);
// Draw a divider unless it's after the hint
if (!(mShowingAddToDictionary && i == 1)) {
mDivider.draw(canvas);
}
canvas.translate(-x - wordWidth, 0);
}
paint.setTypeface(Typeface.DEFAULT);
x += wordWidth;
}
mService.onAutoCompletionStateChanged(existsAutoCompletion);
mTotalWidth = x;
if (mTargetScrollX != scrollX) {
scrollToTarget();
}
}
private void scrollToTarget() {
int scrollX = getScrollX();
if (mTargetScrollX > scrollX) {
scrollX += SCROLL_PIXELS;
if (scrollX >= mTargetScrollX) {
scrollX = mTargetScrollX;
scrollTo(scrollX, getScrollY());
requestLayout();
} else {
scrollTo(scrollX, getScrollY());
}
} else {
scrollX -= SCROLL_PIXELS;
if (scrollX <= mTargetScrollX) {
scrollX = mTargetScrollX;
scrollTo(scrollX, getScrollY());
requestLayout();
} else {
scrollTo(scrollX, getScrollY());
}
}
invalidate();
}
public void setSuggestions(List<CharSequence> suggestions, boolean completions,
boolean typedWordValid, boolean haveMinimalSuggestion) {
clear();
if (suggestions != null) {
int insertCount = Math.min(suggestions.size(), MAX_SUGGESTIONS);
for (CharSequence suggestion : suggestions) {
mSuggestions.add(suggestion);
if (--insertCount == 0)
break;
}
}
mShowingCompletions = completions;
mTypedWordValid = typedWordValid;
scrollTo(0, getScrollY());
mTargetScrollX = 0;
mHaveMinimalSuggestion = haveMinimalSuggestion;
// Compute the total width
onDraw(null);
invalidate();
requestLayout();
}
public boolean isShowingAddToDictionaryHint() {
return mShowingAddToDictionary;
}
public void showAddToDictionaryHint(CharSequence word) {
ArrayList<CharSequence> suggestions = new ArrayList<CharSequence>();
suggestions.add(word);
suggestions.add(mAddToDictionaryHint);
setSuggestions(suggestions, false, false, false);
mShowingAddToDictionary = true;
}
public boolean dismissAddToDictionaryHint() {
if (!mShowingAddToDictionary) return false;
clear();
return true;
}
/* package */ List<CharSequence> getSuggestions() {
return mSuggestions;
}
public void clear() {
// Don't call mSuggestions.clear() because it's being used for logging
// in LatinIME.pickSuggestionManually().
mSuggestions.clear();
mTouchX = OUT_OF_BOUNDS_X_COORD;
mSelectedString = null;
mSelectedIndex = -1;
mShowingAddToDictionary = false;
invalidate();
Arrays.fill(mWordWidth, 0);
Arrays.fill(mWordX, 0);
}
@Override
public boolean onTouchEvent(MotionEvent me) {
if (mGestureDetector.onTouchEvent(me)) {
return true;
}
int action = me.getAction();
int x = (int) me.getX();
int y = (int) me.getY();
mTouchX = x;
switch (action) {
case MotionEvent.ACTION_DOWN:
invalidate();
break;
case MotionEvent.ACTION_MOVE:
if (y <= 0) {
// Fling up!?
if (mSelectedString != null) {
// If there are completions from the application, we don't change the state to
// STATE_PICKED_SUGGESTION
if (!mShowingCompletions) {
// This "acceptedSuggestion" will not be counted as a word because
// it will be counted in pickSuggestion instead.
//TextEntryState.acceptedSuggestion(mSuggestions.get(0), mSelectedString);
//TextEntryState.manualTyped(mSelectedString);
}
mService.pickSuggestionManually(mSelectedIndex, mSelectedString);
mSelectedString = null;
mSelectedIndex = -1;
}
}
break;
case MotionEvent.ACTION_UP:
if (!mScrolled) {
if (mSelectedString != null) {
if (mShowingAddToDictionary) {
longPressFirstWord();
clear();
} else {
if (!mShowingCompletions) {
//TextEntryState.acceptedSuggestion(mSuggestions.get(0), mSelectedString);
//TextEntryState.manualTyped(mSelectedString);
}
mService.pickSuggestionManually(mSelectedIndex, mSelectedString);
}
}
}
mSelectedString = null;
mSelectedIndex = -1;
requestLayout();
hidePreview();
invalidate();
break;
}
return true;
}
private void hidePreview() {
mTouchX = OUT_OF_BOUNDS_X_COORD;
mCurrentWordIndex = OUT_OF_BOUNDS_WORD_INDEX;
mPreviewPopup.dismiss();
}
private void showPreview(int wordIndex, String altText) {
int oldWordIndex = mCurrentWordIndex;
mCurrentWordIndex = wordIndex;
// If index changed or changing text
if (oldWordIndex != mCurrentWordIndex || altText != null) {
if (wordIndex == OUT_OF_BOUNDS_WORD_INDEX) {
hidePreview();
} else {
CharSequence word = altText != null? altText : mSuggestions.get(wordIndex);
mPreviewText.setText(word);
mPreviewText.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
int wordWidth = (int) (mPaint.measureText(word, 0, word.length()) + X_GAP * 2);
final int popupWidth = wordWidth
+ mPreviewText.getPaddingLeft() + mPreviewText.getPaddingRight();
final int popupHeight = mPreviewText.getMeasuredHeight();
//mPreviewText.setVisibility(INVISIBLE);
mPopupPreviewX = mWordX[wordIndex] - mPreviewText.getPaddingLeft() - getScrollX()
+ (mWordWidth[wordIndex] - wordWidth) / 2;
mPopupPreviewY = - popupHeight;
int [] offsetInWindow = new int[2];
getLocationInWindow(offsetInWindow);
if (mPreviewPopup.isShowing()) {
mPreviewPopup.update(mPopupPreviewX, mPopupPreviewY + offsetInWindow[1],
popupWidth, popupHeight);
} else {
mPreviewPopup.setWidth(popupWidth);
mPreviewPopup.setHeight(popupHeight);
mPreviewPopup.showAtLocation(this, Gravity.NO_GRAVITY, mPopupPreviewX,
mPopupPreviewY + offsetInWindow[1]);
}
mPreviewText.setVisibility(VISIBLE);
}
}
}
private void longPressFirstWord() {
CharSequence word = mSuggestions.get(0);
if (word.length() < 2) return;
if (mService.addWordToDictionary(word.toString())) {
showPreview(0, getContext().getResources().getString(R.string.added_word, word));
}
}
@Override
public void onDetachedFromWindow() {
super.onDetachedFromWindow();
hidePreview();
}
}
| Java |
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import java.util.List;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import org.pocketworkstation.pckeyboard.Keyboard.Key;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.widget.PopupWindow;
import android.widget.TextView;
public class LatinKeyboardView extends LatinKeyboardBaseView {
static final String TAG = "HK/LatinKeyboardView";
// The keycode list needs to stay in sync with the
// res/values/keycodes.xml file.
// FIXME: The following keycodes should really be renumbered
// since they conflict with existing KeyEvent keycodes.
static final int KEYCODE_OPTIONS = -100;
static final int KEYCODE_OPTIONS_LONGPRESS = -101;
static final int KEYCODE_VOICE = -102;
static final int KEYCODE_F1 = -103;
static final int KEYCODE_NEXT_LANGUAGE = -104;
static final int KEYCODE_PREV_LANGUAGE = -105;
static final int KEYCODE_COMPOSE = -10024;
// The following keycodes match (negative) KeyEvent keycodes.
// Would be better to use the real KeyEvent values, but many
// don't exist prior to the Honeycomb API (level 11).
static final int KEYCODE_DPAD_UP = -19;
static final int KEYCODE_DPAD_DOWN = -20;
static final int KEYCODE_DPAD_LEFT = -21;
static final int KEYCODE_DPAD_RIGHT = -22;
static final int KEYCODE_DPAD_CENTER = -23;
static final int KEYCODE_ALT_LEFT = -57;
static final int KEYCODE_PAGE_UP = -92;
static final int KEYCODE_PAGE_DOWN = -93;
static final int KEYCODE_ESCAPE = -111;
static final int KEYCODE_FORWARD_DEL = -112;
static final int KEYCODE_CTRL_LEFT = -113;
static final int KEYCODE_CAPS_LOCK = -115;
static final int KEYCODE_SCROLL_LOCK = -116;
static final int KEYCODE_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);
}
}
}
| Java |
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import java.util.HashMap;
import java.util.Map;
import android.app.Dialog;
import android.app.backup.BackupManager;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceGroup;
import android.text.AutoText;
import android.text.InputType;
import android.util.Log;
public class LatinIMESettings extends PreferenceActivity
implements SharedPreferences.OnSharedPreferenceChangeListener,
DialogInterface.OnDismissListener {
private static final String QUICK_FIXES_KEY = "quick_fixes";
private static final String PREDICTION_SETTINGS_KEY = "prediction_settings";
private static final String VOICE_SETTINGS_KEY = "voice_mode";
/* package */ static final String PREF_SETTINGS_KEY = "settings_key";
static final String INPUT_CONNECTION_INFO = "input_connection_info";
private static final String TAG = "LatinIMESettings";
// Dialog ids
private static final int VOICE_INPUT_CONFIRM_DIALOG = 0;
private CheckBoxPreference mQuickFixes;
private ListPreference mVoicePreference;
private ListPreference mSettingsKeyPreference;
private ListPreference mKeyboardModePortraitPreference;
private ListPreference mKeyboardModeLandscapePreference;
private Preference mInputConnectionInfo;
private boolean mVoiceOn;
private boolean mOkClicked = false;
private String mVoiceModeOff;
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
addPreferencesFromResource(R.xml.prefs);
mQuickFixes = (CheckBoxPreference) findPreference(QUICK_FIXES_KEY);
mVoicePreference = (ListPreference) findPreference(VOICE_SETTINGS_KEY);
mSettingsKeyPreference = (ListPreference) findPreference(PREF_SETTINGS_KEY);
mInputConnectionInfo = (Preference) findPreference(INPUT_CONNECTION_INFO);
// TODO(klausw): remove these when no longer needed
mKeyboardModePortraitPreference = (ListPreference) findPreference("pref_keyboard_mode_portrait");
mKeyboardModeLandscapePreference = (ListPreference) findPreference("pref_keyboard_mode_landscape");
SharedPreferences prefs = getPreferenceManager().getSharedPreferences();
prefs.registerOnSharedPreferenceChangeListener(this);
mVoiceModeOff = getString(R.string.voice_mode_off);
mVoiceOn = !(prefs.getString(VOICE_SETTINGS_KEY, mVoiceModeOff).equals(mVoiceModeOff));
}
@Override
protected void onResume() {
super.onResume();
int autoTextSize = AutoText.getSize(getListView());
if (autoTextSize < 1) {
((PreferenceGroup) findPreference(PREDICTION_SETTINGS_KEY))
.removePreference(mQuickFixes);
}
Log.i(TAG, "compactModeEnabled=" + LatinIME.sKeyboardSettings.compactModeEnabled);
if (!LatinIME.sKeyboardSettings.compactModeEnabled) {
CharSequence[] oldEntries = mKeyboardModePortraitPreference.getEntries();
CharSequence[] oldValues = mKeyboardModePortraitPreference.getEntryValues();
if (oldEntries.length > 2) {
CharSequence[] newEntries = new CharSequence[] { oldEntries[0], oldEntries[2] };
CharSequence[] newValues = new CharSequence[] { oldValues[0], oldValues[2] };
mKeyboardModePortraitPreference.setEntries(newEntries);
mKeyboardModePortraitPreference.setEntryValues(newValues);
mKeyboardModeLandscapePreference.setEntries(newEntries);
mKeyboardModeLandscapePreference.setEntryValues(newValues);
}
}
updateSummaries();
}
@Override
protected void onDestroy() {
getPreferenceManager().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(
this);
super.onDestroy();
}
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
(new BackupManager(this)).dataChanged();
// If turning on voice input, show dialog
if (key.equals(VOICE_SETTINGS_KEY) && !mVoiceOn) {
if (!prefs.getString(VOICE_SETTINGS_KEY, mVoiceModeOff)
.equals(mVoiceModeOff)) {
showVoiceConfirmation();
}
}
mVoiceOn = !(prefs.getString(VOICE_SETTINGS_KEY, mVoiceModeOff).equals(mVoiceModeOff));
updateVoiceModeSummary();
updateSummaries();
}
static Map<Integer, String> INPUT_CLASSES = new HashMap<Integer, String>();
static Map<Integer, String> DATETIME_VARIATIONS = new HashMap<Integer, String>();
static Map<Integer, String> TEXT_VARIATIONS = new HashMap<Integer, String>();
static Map<Integer, String> NUMBER_VARIATIONS = new HashMap<Integer, String>();
static {
INPUT_CLASSES.put(0x00000004, "DATETIME");
INPUT_CLASSES.put(0x00000002, "NUMBER");
INPUT_CLASSES.put(0x00000003, "PHONE");
INPUT_CLASSES.put(0x00000001, "TEXT");
INPUT_CLASSES.put(0x00000000, "NULL");
DATETIME_VARIATIONS.put(0x00000010, "DATE");
DATETIME_VARIATIONS.put(0x00000020, "TIME");
NUMBER_VARIATIONS.put(0x00000010, "PASSWORD");
TEXT_VARIATIONS.put(0x00000020, "EMAIL_ADDRESS");
TEXT_VARIATIONS.put(0x00000030, "EMAIL_SUBJECT");
TEXT_VARIATIONS.put(0x000000b0, "FILTER");
TEXT_VARIATIONS.put(0x00000050, "LONG_MESSAGE");
TEXT_VARIATIONS.put(0x00000080, "PASSWORD");
TEXT_VARIATIONS.put(0x00000060, "PERSON_NAME");
TEXT_VARIATIONS.put(0x000000c0, "PHONETIC");
TEXT_VARIATIONS.put(0x00000070, "POSTAL_ADDRESS");
TEXT_VARIATIONS.put(0x00000040, "SHORT_MESSAGE");
TEXT_VARIATIONS.put(0x00000010, "URI");
TEXT_VARIATIONS.put(0x00000090, "VISIBLE_PASSWORD");
TEXT_VARIATIONS.put(0x000000a0, "WEB_EDIT_TEXT");
TEXT_VARIATIONS.put(0x000000d0, "WEB_EMAIL_ADDRESS");
TEXT_VARIATIONS.put(0x000000e0, "WEB_PASSWORD");
}
private static void addBit(StringBuffer buf, int bit, String str) {
if (bit != 0) {
buf.append("|");
buf.append(str);
}
}
private static String inputTypeDesc(int type) {
int cls = type & 0x0000000f; // MASK_CLASS
int flags = type & 0x00fff000; // MASK_FLAGS
int var = type & 0x00000ff0; // MASK_VARIATION
StringBuffer out = new StringBuffer();
String clsName = INPUT_CLASSES.get(cls);
out.append(clsName != null ? clsName : "?");
if (cls == InputType.TYPE_CLASS_TEXT) {
String varName = TEXT_VARIATIONS.get(var);
if (varName != null) {
out.append(".");
out.append(varName);
}
addBit(out, flags & 0x00010000, "AUTO_COMPLETE");
addBit(out, flags & 0x00008000, "AUTO_CORRECT");
addBit(out, flags & 0x00001000, "CAP_CHARACTERS");
addBit(out, flags & 0x00004000, "CAP_SENTENCES");
addBit(out, flags & 0x00002000, "CAP_WORDS");
addBit(out, flags & 0x00040000, "IME_MULTI_LINE");
addBit(out, flags & 0x00020000, "MULTI_LINE");
addBit(out, flags & 0x00080000, "NO_SUGGESTIONS");
} else if (cls == InputType.TYPE_CLASS_NUMBER) {
String varName = NUMBER_VARIATIONS.get(var);
if (varName != null) {
out.append(".");
out.append(varName);
}
addBit(out, flags & 0x00002000, "DECIMAL");
addBit(out, flags & 0x00001000, "SIGNED");
} else if (cls == InputType.TYPE_CLASS_DATETIME) {
String varName = DATETIME_VARIATIONS.get(var);
if (varName != null) {
out.append(".");
out.append(varName);
}
}
return out.toString();
}
private void updateSummaries() {
Resources res = getResources();
mSettingsKeyPreference.setSummary(
res.getStringArray(R.array.settings_key_modes)
[mSettingsKeyPreference.findIndexOfValue(mSettingsKeyPreference.getValue())]);
mInputConnectionInfo.setSummary(String.format("%s type=%s",
LatinIME.sKeyboardSettings.editorPackageName,
inputTypeDesc(LatinIME.sKeyboardSettings.editorInputType)
));
}
private void showVoiceConfirmation() {
mOkClicked = false;
showDialog(VOICE_INPUT_CONFIRM_DIALOG);
}
private void updateVoiceModeSummary() {
mVoicePreference.setSummary(
getResources().getStringArray(R.array.voice_input_modes_summary)
[mVoicePreference.findIndexOfValue(mVoicePreference.getValue())]);
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
default:
Log.e(TAG, "unknown dialog " + id);
return null;
}
}
public void onDismiss(DialogInterface dialog) {
if (!mOkClicked) {
// This assumes that onPreferenceClick gets called first, and this if the user
// agreed after the warning, we set the mOkClicked value to true.
mVoicePreference.setValue(mVoiceModeOff);
}
}
private void updateVoicePreference() {
}
}
| Java |
/*
* Copyright (C) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.os.AsyncTask;
import android.provider.BaseColumns;
import android.util.Log;
/**
* Stores all the pairs user types in databases. Prune the database if the size
* gets too big. Unlike AutoDictionary, it even stores the pairs that are already
* in the dictionary.
*/
public class UserBigramDictionary extends ExpandableDictionary {
private static final String TAG = "UserBigramDictionary";
/** Any pair being typed or picked */
private static final int FREQUENCY_FOR_TYPED = 2;
/** Maximum frequency for all pairs */
private static final int FREQUENCY_MAX = 127;
/**
* If this pair is typed 6 times, it would be suggested.
* Should be smaller than ContactsDictionary.FREQUENCY_FOR_CONTACTS_BIGRAM
*/
protected static final int SUGGEST_THRESHOLD = 6 * FREQUENCY_FOR_TYPED;
/** Maximum number of pairs. Pruning will start when databases goes above this number. */
private static int sMaxUserBigrams = 10000;
/**
* When it hits maximum bigram pair, it will delete until you are left with
* only (sMaxUserBigrams - sDeleteUserBigrams) pairs.
* Do not keep this number small to avoid deleting too often.
*/
private static int sDeleteUserBigrams = 1000;
/**
* Database version should increase if the database structure changes
*/
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "userbigram_dict.db";
/** Name of the words table in the database */
private static final String MAIN_TABLE_NAME = "main";
// TODO: Consume less space by using a unique id for locale instead of the whole
// 2-5 character string. (Same TODO from AutoDictionary)
private static final String MAIN_COLUMN_ID = BaseColumns._ID;
private static final String MAIN_COLUMN_WORD1 = "word1";
private static final String MAIN_COLUMN_WORD2 = "word2";
private static final String MAIN_COLUMN_LOCALE = "locale";
/** Name of the frequency table in the database */
private static final String FREQ_TABLE_NAME = "frequency";
private static final String FREQ_COLUMN_ID = BaseColumns._ID;
private static final String FREQ_COLUMN_PAIR_ID = "pair_id";
private static final String FREQ_COLUMN_FREQUENCY = "freq";
private final LatinIME mIme;
/** Locale for which this auto dictionary is storing words */
private String mLocale;
private HashSet<Bigram> mPendingWrites = new HashSet<Bigram>();
private final Object mPendingWritesLock = new Object();
private static volatile boolean sUpdatingDB = false;
private final static HashMap<String, String> sDictProjectionMap;
static {
sDictProjectionMap = new HashMap<String, String>();
sDictProjectionMap.put(MAIN_COLUMN_ID, MAIN_COLUMN_ID);
sDictProjectionMap.put(MAIN_COLUMN_WORD1, MAIN_COLUMN_WORD1);
sDictProjectionMap.put(MAIN_COLUMN_WORD2, MAIN_COLUMN_WORD2);
sDictProjectionMap.put(MAIN_COLUMN_LOCALE, MAIN_COLUMN_LOCALE);
sDictProjectionMap.put(FREQ_COLUMN_ID, FREQ_COLUMN_ID);
sDictProjectionMap.put(FREQ_COLUMN_PAIR_ID, FREQ_COLUMN_PAIR_ID);
sDictProjectionMap.put(FREQ_COLUMN_FREQUENCY, FREQ_COLUMN_FREQUENCY);
}
private static DatabaseHelper sOpenHelper = null;
private static class Bigram {
String word1;
String word2;
int frequency;
Bigram(String word1, String word2, int frequency) {
this.word1 = word1;
this.word2 = word2;
this.frequency = frequency;
}
@Override
public boolean equals(Object bigram) {
Bigram bigram2 = (Bigram) bigram;
return (word1.equals(bigram2.word1) && word2.equals(bigram2.word2));
}
@Override
public int hashCode() {
return (word1 + " " + word2).hashCode();
}
}
public void setDatabaseMax(int maxUserBigram) {
sMaxUserBigrams = maxUserBigram;
}
public void setDatabaseDelete(int deleteUserBigram) {
sDeleteUserBigrams = deleteUserBigram;
}
public UserBigramDictionary(Context context, LatinIME ime, String locale, int dicTypeId) {
super(context, dicTypeId);
mIme = ime;
mLocale = locale;
if (sOpenHelper == null) {
sOpenHelper = new DatabaseHelper(getContext());
}
if (mLocale != null && mLocale.length() > 1) {
loadDictionary();
}
}
@Override
public void close() {
flushPendingWrites();
// Don't close the database as locale changes will require it to be reopened anyway
// Also, the database is written to somewhat frequently, so it needs to be kept alive
// throughout the life of the process.
// mOpenHelper.close();
super.close();
}
/**
* Pair will be added to the userbigram database.
*/
public int addBigrams(String word1, String word2) {
// remove caps
if (mIme != null && mIme.getCurrentWord().isAutoCapitalized()) {
word2 = Character.toLowerCase(word2.charAt(0)) + word2.substring(1);
}
int freq = super.addBigram(word1, word2, FREQUENCY_FOR_TYPED);
if (freq > FREQUENCY_MAX) freq = FREQUENCY_MAX;
synchronized (mPendingWritesLock) {
if (freq == FREQUENCY_FOR_TYPED || mPendingWrites.isEmpty()) {
mPendingWrites.add(new Bigram(word1, word2, freq));
} else {
Bigram bi = new Bigram(word1, word2, freq);
mPendingWrites.remove(bi);
mPendingWrites.add(bi);
}
}
return freq;
}
/**
* Schedules a background thread to write any pending words to the database.
*/
public void flushPendingWrites() {
synchronized (mPendingWritesLock) {
// Nothing pending? Return
if (mPendingWrites.isEmpty()) return;
// Create a background thread to write the pending entries
new UpdateDbTask(getContext(), sOpenHelper, mPendingWrites, mLocale).execute();
// Create a new map for writing new entries into while the old one is written to db
mPendingWrites = new HashSet<Bigram>();
}
}
/** Used for testing purpose **/
void waitUntilUpdateDBDone() {
synchronized (mPendingWritesLock) {
while (sUpdatingDB) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
}
return;
}
}
@Override
public void loadDictionaryAsync() {
// Load the words that correspond to the current input locale
Cursor cursor = query(MAIN_COLUMN_LOCALE + "=?", new String[] { mLocale });
try {
if (cursor.moveToFirst()) {
int word1Index = cursor.getColumnIndex(MAIN_COLUMN_WORD1);
int word2Index = cursor.getColumnIndex(MAIN_COLUMN_WORD2);
int frequencyIndex = cursor.getColumnIndex(FREQ_COLUMN_FREQUENCY);
while (!cursor.isAfterLast()) {
String word1 = cursor.getString(word1Index);
String word2 = cursor.getString(word2Index);
int frequency = cursor.getInt(frequencyIndex);
// Safeguard against adding really long words. Stack may overflow due
// to recursive lookup
if (word1.length() < MAX_WORD_LENGTH && word2.length() < MAX_WORD_LENGTH) {
super.setBigram(word1, word2, frequency);
}
cursor.moveToNext();
}
}
} finally {
cursor.close();
}
}
/**
* Query the database
*/
private Cursor query(String selection, String[] selectionArgs) {
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
// main INNER JOIN frequency ON (main._id=freq.pair_id)
qb.setTables(MAIN_TABLE_NAME + " INNER JOIN " + FREQ_TABLE_NAME + " ON ("
+ MAIN_TABLE_NAME + "." + MAIN_COLUMN_ID + "=" + FREQ_TABLE_NAME + "."
+ FREQ_COLUMN_PAIR_ID +")");
qb.setProjectionMap(sDictProjectionMap);
// Get the database and run the query
SQLiteDatabase db = sOpenHelper.getReadableDatabase();
Cursor c = qb.query(db,
new String[] { MAIN_COLUMN_WORD1, MAIN_COLUMN_WORD2, FREQ_COLUMN_FREQUENCY },
selection, selectionArgs, null, null, null);
return c;
}
/**
* This class helps open, create, and upgrade the database file.
*/
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("PRAGMA foreign_keys = ON;");
db.execSQL("CREATE TABLE " + MAIN_TABLE_NAME + " ("
+ MAIN_COLUMN_ID + " INTEGER PRIMARY KEY,"
+ MAIN_COLUMN_WORD1 + " TEXT,"
+ MAIN_COLUMN_WORD2 + " TEXT,"
+ MAIN_COLUMN_LOCALE + " TEXT"
+ ");");
db.execSQL("CREATE TABLE " + FREQ_TABLE_NAME + " ("
+ FREQ_COLUMN_ID + " INTEGER PRIMARY KEY,"
+ FREQ_COLUMN_PAIR_ID + " INTEGER,"
+ FREQ_COLUMN_FREQUENCY + " INTEGER,"
+ "FOREIGN KEY(" + FREQ_COLUMN_PAIR_ID + ") REFERENCES " + MAIN_TABLE_NAME
+ "(" + MAIN_COLUMN_ID + ")" + " ON DELETE CASCADE"
+ ");");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + MAIN_TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS " + FREQ_TABLE_NAME);
onCreate(db);
}
}
/**
* Async task to write pending words to the database so that it stays in sync with
* the in-memory trie.
*/
private static class UpdateDbTask extends AsyncTask<Void, Void, Void> {
private final HashSet<Bigram> mMap;
private final DatabaseHelper mDbHelper;
private final String mLocale;
public UpdateDbTask(Context context, DatabaseHelper openHelper,
HashSet<Bigram> pendingWrites, String locale) {
mMap = pendingWrites;
mLocale = locale;
mDbHelper = openHelper;
}
/** Prune any old data if the database is getting too big. */
private void checkPruneData(SQLiteDatabase db) {
db.execSQL("PRAGMA foreign_keys = ON;");
Cursor c = db.query(FREQ_TABLE_NAME, new String[] { FREQ_COLUMN_PAIR_ID },
null, null, null, null, null);
try {
int totalRowCount = c.getCount();
// prune out old data if we have too much data
if (totalRowCount > sMaxUserBigrams) {
int numDeleteRows = (totalRowCount - sMaxUserBigrams) + sDeleteUserBigrams;
int pairIdColumnId = c.getColumnIndex(FREQ_COLUMN_PAIR_ID);
c.moveToFirst();
int count = 0;
while (count < numDeleteRows && !c.isAfterLast()) {
String pairId = c.getString(pairIdColumnId);
// Deleting from MAIN table will delete the frequencies
// due to FOREIGN KEY .. ON DELETE CASCADE
db.delete(MAIN_TABLE_NAME, MAIN_COLUMN_ID + "=?",
new String[] { pairId });
c.moveToNext();
count++;
}
}
} finally {
c.close();
}
}
@Override
protected void onPreExecute() {
sUpdatingDB = true;
}
@Override
protected Void doInBackground(Void... v) {
SQLiteDatabase db = mDbHelper.getWritableDatabase();
db.execSQL("PRAGMA foreign_keys = ON;");
// Write all the entries to the db
Iterator<Bigram> iterator = mMap.iterator();
while (iterator.hasNext()) {
Bigram bi = iterator.next();
// find pair id
Cursor c = db.query(MAIN_TABLE_NAME, new String[] { MAIN_COLUMN_ID },
MAIN_COLUMN_WORD1 + "=? AND " + MAIN_COLUMN_WORD2 + "=? AND "
+ MAIN_COLUMN_LOCALE + "=?",
new String[] { bi.word1, bi.word2, mLocale }, null, null, null);
int pairId;
if (c.moveToFirst()) {
// existing pair
pairId = c.getInt(c.getColumnIndex(MAIN_COLUMN_ID));
db.delete(FREQ_TABLE_NAME, FREQ_COLUMN_PAIR_ID + "=?",
new String[] { Integer.toString(pairId) });
} else {
// new pair
Long pairIdLong = db.insert(MAIN_TABLE_NAME, null,
getContentValues(bi.word1, bi.word2, mLocale));
pairId = pairIdLong.intValue();
}
c.close();
// insert new frequency
db.insert(FREQ_TABLE_NAME, null, getFrequencyContentValues(pairId, bi.frequency));
}
checkPruneData(db);
sUpdatingDB = false;
return null;
}
private ContentValues getContentValues(String word1, String word2, String locale) {
ContentValues values = new ContentValues(3);
values.put(MAIN_COLUMN_WORD1, word1);
values.put(MAIN_COLUMN_WORD2, word2);
values.put(MAIN_COLUMN_LOCALE, locale);
return values;
}
private ContentValues getFrequencyContentValues(int pairId, int frequency) {
ContentValues values = new ContentValues(2);
values.put(FREQ_COLUMN_PAIR_ID, pairId);
values.put(FREQ_COLUMN_FREQUENCY, frequency);
return values;
}
}
}
| Java |
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Html;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.TextView.BufferType;
public class Main extends Activity {
private final static String MARKET_URI = "market://search?q=pub:\"Klaus Weidner\"";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String html = getString(R.string.main_body);
html += "<p><i>Version: " + getString(R.string.auto_version) + "</i></p>";
Spanned content = Html.fromHtml(html);
TextView description = (TextView) findViewById(R.id.main_description);
description.setMovementMethod(LinkMovementMethod.getInstance());
description.setText(content, BufferType.SPANNABLE);
final Button setup1 = (Button) findViewById(R.id.main_setup_btn_configure_imes);
setup1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivityForResult(new Intent(android.provider.Settings.ACTION_INPUT_METHOD_SETTINGS), 0);
}
});
final Button setup2 = (Button) findViewById(R.id.main_setup_btn_set_ime);
setup2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.showInputMethodPicker();
}
});
final Activity that = this;
final Button setup4 = (Button) findViewById(R.id.main_setup_btn_input_lang);
setup4.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivityForResult(new Intent(that, InputLanguageSelection.class), 0);
}
});
final Button setup3 = (Button) findViewById(R.id.main_setup_btn_get_dicts);
setup3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent it = new Intent(Intent.ACTION_VIEW, Uri.parse(MARKET_URI));
try {
startActivity(it);
} catch (ActivityNotFoundException e) {
Toast.makeText(getApplicationContext(),
getResources().getString(
R.string.no_market_warning), Toast.LENGTH_LONG)
.show();
}
}
});
// PluginManager.getPluginDictionaries(getApplicationContext()); // why?
}
}
| Java |
/*
* Copyright (C) 2008-2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import org.xmlpull.v1.XmlPullParserException;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.content.res.XmlResourceParser;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.util.Xml;
import android.util.DisplayMetrics;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.StringTokenizer;
/**
* Loads an XML description of a keyboard and stores the attributes of the keys. A keyboard
* consists of rows of keys.
* <p>The layout file for a keyboard contains XML that looks like the following snippet:</p>
* <pre>
* <Keyboard
* android:keyWidth="%10p"
* android:keyHeight="50px"
* android:horizontalGap="2px"
* android:verticalGap="2px" >
* <Row android:keyWidth="32px" >
* <Key android:keyLabel="A" />
* ...
* </Row>
* ...
* </Keyboard>
* </pre>
* @attr ref android.R.styleable#Keyboard_keyWidth
* @attr ref android.R.styleable#Keyboard_keyHeight
* @attr ref android.R.styleable#Keyboard_horizontalGap
* @attr ref android.R.styleable#Keyboard_verticalGap
*/
public class Keyboard {
static final String TAG = "Keyboard";
public final static char DEAD_KEY_PLACEHOLDER = 0x25cc; // dotted small circle
public final static String DEAD_KEY_PLACEHOLDER_STRING = Character.toString(DEAD_KEY_PLACEHOLDER);
// Keyboard XML Tags
private static final String TAG_KEYBOARD = "Keyboard";
private static final String TAG_ROW = "Row";
private static final String TAG_KEY = "Key";
public static final int EDGE_LEFT = 0x01;
public static final int EDGE_RIGHT = 0x02;
public static final int EDGE_TOP = 0x04;
public static final int EDGE_BOTTOM = 0x08;
public static final int KEYCODE_SHIFT = -1;
public static final int KEYCODE_MODE_CHANGE = -2;
public static final int KEYCODE_CANCEL = -3;
public static final int KEYCODE_DONE = -4;
public static final int KEYCODE_DELETE = -5;
public static final int KEYCODE_ALT_SYM = -6;
// Backwards compatible setting to avoid having to change all the kbd_qwerty files
public static final int DEFAULT_LAYOUT_ROWS = 4;
public static final int DEFAULT_LAYOUT_COLUMNS = 10;
// Flag values for popup key contents. Keep in sync with strings.xml values.
public static final int POPUP_ADD_SHIFT = 1;
public static final int POPUP_ADD_CASE = 2;
public static final int POPUP_ADD_SELF = 4;
public static final int POPUP_DISABLE = 256;
public static final int POPUP_AUTOREPEAT = 512;
/** Horizontal gap default for all rows */
private float mDefaultHorizontalGap;
private float mHorizontalPad;
private float mVerticalPad;
/** Default key width */
private float mDefaultWidth;
/** Default key height */
private int mDefaultHeight;
/** Default gap between rows */
private int mDefaultVerticalGap;
public static final int SHIFT_OFF = 0;
public static final int SHIFT_ON = 1;
public static final int SHIFT_LOCKED = 2;
public static final int SHIFT_CAPS = 3;
public static final int SHIFT_CAPS_LOCKED = 4;
/** Is the keyboard in the shifted state */
private int mShiftState = SHIFT_OFF;
/** Key instance for the shift key, if present */
private Key mShiftKey;
private Key mAltKey;
private Key mCtrlKey;
private Key mMetaKey;
/** Key index for the shift key, if present */
private int mShiftKeyIndex = -1;
/** Total height of the keyboard, including the padding and keys */
private int mTotalHeight;
/**
* Total width of the keyboard, including left side gaps and keys, but not any gaps on the
* right side.
*/
private int mTotalWidth;
/** List of keys in this keyboard */
private List<Key> mKeys;
/** List of modifier keys such as Shift & Alt, if any */
private List<Key> mModifierKeys;
/** Width of the screen available to fit the keyboard */
private int mDisplayWidth;
/** Height of the screen and keyboard */
private int mDisplayHeight;
private int mKeyboardHeight;
/** Keyboard mode, or zero, if none. */
private int mKeyboardMode;
private boolean mUseExtension;
public int mLayoutRows;
public int mLayoutColumns;
public int mRowCount = 1;
public int mExtensionRowCount = 0;
// Variables for pre-computing nearest keys.
private int mCellWidth;
private int mCellHeight;
private int[][] mGridNeighbors;
private int mProximityThreshold;
/** Number of key widths from current touch point to search for nearest keys. */
private static float SEARCH_DISTANCE = 1.8f;
/**
* Container for keys in the keyboard. All keys in a row are at the same Y-coordinate.
* Some of the key size defaults can be overridden per row from what the {@link Keyboard}
* defines.
* @attr ref android.R.styleable#Keyboard_keyWidth
* @attr ref android.R.styleable#Keyboard_keyHeight
* @attr ref android.R.styleable#Keyboard_horizontalGap
* @attr ref android.R.styleable#Keyboard_verticalGap
* @attr ref android.R.styleable#Keyboard_Row_keyboardMode
*/
public static class Row {
/** Default width of a key in this row. */
public float defaultWidth;
/** Default height of a key in this row. */
public int defaultHeight;
/** Default horizontal gap between keys in this row. */
public float defaultHorizontalGap;
/** Vertical gap following this row. */
public int verticalGap;
/** The keyboard mode for this row */
public int mode;
public boolean extension;
private Keyboard parent;
public Row(Keyboard parent) {
this.parent = parent;
}
public Row(Resources res, Keyboard parent, XmlResourceParser parser) {
this.parent = parent;
TypedArray a = res.obtainAttributes(Xml.asAttributeSet(parser),
R.styleable.Keyboard);
defaultWidth = getDimensionOrFraction(a,
R.styleable.Keyboard_keyWidth,
parent.mDisplayWidth, parent.mDefaultWidth);
defaultHeight = Math.round(getDimensionOrFraction(a,
R.styleable.Keyboard_keyHeight,
parent.mDisplayHeight, parent.mDefaultHeight));
defaultHorizontalGap = getDimensionOrFraction(a,
R.styleable.Keyboard_horizontalGap,
parent.mDisplayWidth, parent.mDefaultHorizontalGap);
verticalGap = Math.round(getDimensionOrFraction(a,
R.styleable.Keyboard_verticalGap,
parent.mDisplayHeight, parent.mDefaultVerticalGap));
a.recycle();
a = res.obtainAttributes(Xml.asAttributeSet(parser),
R.styleable.Keyboard_Row);
mode = a.getResourceId(R.styleable.Keyboard_Row_keyboardMode,
0);
extension = a.getBoolean(R.styleable.Keyboard_Row_extension, false);
if (parent.mLayoutRows >= 5) {
boolean isTop = (extension || parent.mRowCount - parent.mExtensionRowCount <= 0);
float topScale = LatinIME.sKeyboardSettings.topRowScale;
float scale = isTop ? topScale : 1.0f + (1.0f - topScale) / (parent.mLayoutRows - 1);
defaultHeight = Math.round(defaultHeight * scale);
}
a.recycle();
}
}
/**
* Class for describing the position and characteristics of a single key in the keyboard.
*
* @attr ref android.R.styleable#Keyboard_keyWidth
* @attr ref android.R.styleable#Keyboard_keyHeight
* @attr ref android.R.styleable#Keyboard_horizontalGap
* @attr ref android.R.styleable#Keyboard_Key_codes
* @attr ref android.R.styleable#Keyboard_Key_keyIcon
* @attr ref android.R.styleable#Keyboard_Key_keyLabel
* @attr ref android.R.styleable#Keyboard_Key_iconPreview
* @attr ref android.R.styleable#Keyboard_Key_isSticky
* @attr ref android.R.styleable#Keyboard_Key_isRepeatable
* @attr ref android.R.styleable#Keyboard_Key_isModifier
* @attr ref android.R.styleable#Keyboard_Key_popupKeyboard
* @attr ref android.R.styleable#Keyboard_Key_popupCharacters
* @attr ref android.R.styleable#Keyboard_Key_keyOutputText
*/
public static class Key {
/**
* All the key codes (unicode or custom code) that this key could generate, zero'th
* being the most important.
*/
public int[] codes;
/** Label to display */
public CharSequence label;
public CharSequence shiftLabel;
public CharSequence capsLabel;
/** Icon to display instead of a label. Icon takes precedence over a label */
public Drawable icon;
/** Preview version of the icon, for the preview popup */
public Drawable iconPreview;
/** Width of the key, not including the gap */
public int width;
/** Height of the key, not including the gap */
private float realWidth;
public int height;
/** The horizontal gap before this key */
public int gap;
private float realGap;
/** Whether this key is sticky, i.e., a toggle key */
public boolean sticky;
/** X coordinate of the key in the keyboard layout */
public int x;
private float realX;
/** Y coordinate of the key in the keyboard layout */
public int y;
/** The current pressed state of this key */
public boolean pressed;
/** If this is a sticky key, is it on or locked? */
public boolean on;
public boolean locked;
/** Text to output when pressed. This can be multiple characters, like ".com" */
public CharSequence text;
/** Popup characters */
public CharSequence popupCharacters;
public boolean popupReversed;
public boolean isCursor;
public String hint; // Set by LatinKeyboardBaseView
public String altHint; // Set by LatinKeyboardBaseView
/**
* Flags that specify the anchoring to edges of the keyboard for detecting touch events
* that are just out of the boundary of the key. This is a bit mask of
* {@link Keyboard#EDGE_LEFT}, {@link Keyboard#EDGE_RIGHT}, {@link Keyboard#EDGE_TOP} and
* {@link Keyboard#EDGE_BOTTOM}.
*/
public int edgeFlags;
/** Whether this is a modifier key, such as Shift or Alt */
public boolean modifier;
/** The keyboard that this key belongs to */
private Keyboard keyboard;
/**
* If this key pops up a mini keyboard, this is the resource id for the XML layout for that
* keyboard.
*/
public int popupResId;
/** Whether this key repeats itself when held down */
public boolean repeatable;
/** Is the shifted character the uppercase equivalent of the unshifted one? */
private boolean isSimpleUppercase;
/** Is the shifted character a distinct uppercase char that's different from the shifted char? */
private boolean isDistinctUppercase;
private final static int[] KEY_STATE_NORMAL_ON = {
android.R.attr.state_checkable,
android.R.attr.state_checked
};
private final static int[] KEY_STATE_PRESSED_ON = {
android.R.attr.state_pressed,
android.R.attr.state_checkable,
android.R.attr.state_checked
};
private final static int[] KEY_STATE_NORMAL_LOCK = {
android.R.attr.state_active,
android.R.attr.state_checkable,
android.R.attr.state_checked
};
private final static int[] KEY_STATE_PRESSED_LOCK = {
android.R.attr.state_active,
android.R.attr.state_pressed,
android.R.attr.state_checkable,
android.R.attr.state_checked
};
private final static int[] KEY_STATE_NORMAL_OFF = {
android.R.attr.state_checkable
};
private final static int[] KEY_STATE_PRESSED_OFF = {
android.R.attr.state_pressed,
android.R.attr.state_checkable
};
private final static int[] KEY_STATE_NORMAL = {
};
private final static int[] KEY_STATE_PRESSED = {
android.R.attr.state_pressed
};
/** Create an empty key with no attributes. */
public Key(Row parent) {
keyboard = parent.parent;
height = parent.defaultHeight;
width = Math.round(parent.defaultWidth);
realWidth = parent.defaultWidth;
gap = Math.round(parent.defaultHorizontalGap);
realGap = parent.defaultHorizontalGap;
}
/** Create a key with the given top-left coordinate and extract its attributes from
* the XML parser.
* @param res resources associated with the caller's context
* @param parent the row that this key belongs to. The row must already be attached to
* a {@link Keyboard}.
* @param x the x coordinate of the top-left
* @param y the y coordinate of the top-left
* @param parser the XML parser containing the attributes for this key
*/
public Key(Resources res, Row parent, int x, int y, XmlResourceParser parser) {
this(parent);
this.x = x;
this.y = y;
TypedArray a = res.obtainAttributes(Xml.asAttributeSet(parser),
R.styleable.Keyboard);
realWidth = getDimensionOrFraction(a,
R.styleable.Keyboard_keyWidth,
keyboard.mDisplayWidth, parent.defaultWidth);
float realHeight = getDimensionOrFraction(a,
R.styleable.Keyboard_keyHeight,
keyboard.mDisplayHeight, parent.defaultHeight);
realHeight -= parent.parent.mVerticalPad;
height = Math.round(realHeight);
this.y += parent.parent.mVerticalPad / 2;
realGap = getDimensionOrFraction(a,
R.styleable.Keyboard_horizontalGap,
keyboard.mDisplayWidth, parent.defaultHorizontalGap);
realGap += parent.parent.mHorizontalPad;
realWidth -= parent.parent.mHorizontalPad;
width = Math.round(realWidth);
gap = Math.round(realGap);
a.recycle();
a = res.obtainAttributes(Xml.asAttributeSet(parser),
R.styleable.Keyboard_Key);
this.realX = this.x + realGap - parent.parent.mHorizontalPad / 2;
this.x = Math.round(this.realX);
TypedValue codesValue = new TypedValue();
a.getValue(R.styleable.Keyboard_Key_codes,
codesValue);
if (codesValue.type == TypedValue.TYPE_INT_DEC
|| codesValue.type == TypedValue.TYPE_INT_HEX) {
codes = new int[] { codesValue.data };
} else if (codesValue.type == TypedValue.TYPE_STRING) {
codes = parseCSV(codesValue.string.toString());
}
iconPreview = a.getDrawable(R.styleable.Keyboard_Key_iconPreview);
if (iconPreview != null) {
iconPreview.setBounds(0, 0, iconPreview.getIntrinsicWidth(),
iconPreview.getIntrinsicHeight());
}
popupCharacters = a.getText(
R.styleable.Keyboard_Key_popupCharacters);
popupResId = a.getResourceId(
R.styleable.Keyboard_Key_popupKeyboard, 0);
repeatable = a.getBoolean(
R.styleable.Keyboard_Key_isRepeatable, false);
modifier = a.getBoolean(
R.styleable.Keyboard_Key_isModifier, false);
sticky = a.getBoolean(
R.styleable.Keyboard_Key_isSticky, false);
isCursor = a.getBoolean(
R.styleable.Keyboard_Key_isCursor, false);
icon = a.getDrawable(
R.styleable.Keyboard_Key_keyIcon);
if (icon != null) {
icon.setBounds(0, 0, icon.getIntrinsicWidth(), icon.getIntrinsicHeight());
}
label = a.getText(R.styleable.Keyboard_Key_keyLabel);
shiftLabel = a.getText(R.styleable.Keyboard_Key_shiftLabel);
if (shiftLabel != null && shiftLabel.length() == 0) shiftLabel = null;
capsLabel = a.getText(R.styleable.Keyboard_Key_capsLabel);
if (capsLabel != null && capsLabel.length() == 0) capsLabel = null;
text = a.getText(R.styleable.Keyboard_Key_keyOutputText);
if (codes == null && !TextUtils.isEmpty(label)) {
codes = getFromString(label);
if (codes != null && codes.length == 1) {
final Locale locale = LatinIME.sKeyboardSettings.inputLocale;
String upperLabel = label.toString().toUpperCase(locale);
if (shiftLabel == null) {
// No shiftLabel supplied, auto-set to uppercase if possible.
if (!upperLabel.equals(label.toString()) && upperLabel.length() == 1) {
shiftLabel = upperLabel;
isSimpleUppercase = true;
}
} else {
// Both label and shiftLabel supplied. Check if
// the shiftLabel is the uppercased normal label.
// If not, treat it as a distinct uppercase variant.
if (capsLabel != null) {
isDistinctUppercase = true;
} else if (upperLabel.equals(shiftLabel.toString())) {
isSimpleUppercase = true;
} else if (upperLabel.length() == 1) {
capsLabel = upperLabel;
isDistinctUppercase = true;
}
}
}
if ((LatinIME.sKeyboardSettings.popupKeyboardFlags & POPUP_DISABLE) != 0) {
popupCharacters = null;
popupResId = 0;
}
if ((LatinIME.sKeyboardSettings.popupKeyboardFlags & POPUP_AUTOREPEAT) != 0) {
// Assume POPUP_DISABLED is set too, otherwise things may get weird.
repeatable = true;
}
}
//Log.i(TAG, "added key definition: " + this);
a.recycle();
}
public boolean isDistinctCaps() {
return isDistinctUppercase && keyboard.isShiftCaps();
}
public boolean isShifted() {
boolean shifted = keyboard.isShifted(isSimpleUppercase);
//Log.i(TAG, "FIXME isShifted=" + shifted + " for " + this);
return shifted;
}
public int getPrimaryCode(boolean isShiftCaps, boolean isShifted) {
if (isDistinctUppercase && isShiftCaps) {
return capsLabel.charAt(0);
}
//Log.i(TAG, "getPrimaryCode(), shifted=" + shifted);
if (isShifted && shiftLabel != null) {
if (shiftLabel.charAt(0) == DEAD_KEY_PLACEHOLDER && shiftLabel.length() >= 2) {
return shiftLabel.charAt(1);
} else {
return shiftLabel.charAt(0);
}
} else {
return codes[0];
}
}
public int getPrimaryCode() {
return getPrimaryCode(keyboard.isShiftCaps(), keyboard.isShifted(isSimpleUppercase));
}
public boolean isDeadKey() {
if (codes == null || codes.length < 1) return false;
return Character.getType(codes[0]) == Character.NON_SPACING_MARK;
}
public int[] getFromString(CharSequence str) {
if (str.length() > 1) {
if (str.charAt(0) == DEAD_KEY_PLACEHOLDER && str.length() >= 2) {
return new int[] { str.charAt(1) }; // FIXME: >1 length?
} else {
text = str; // TODO: add space?
return new int[] { 0 };
}
} else {
char c = str.charAt(0);
return new int[] { c };
}
}
public String getCaseLabel() {
if (isDistinctUppercase && keyboard.isShiftCaps()) {
return capsLabel.toString();
}
boolean isShifted = keyboard.isShifted(isSimpleUppercase);
if (isShifted && shiftLabel != null) {
return shiftLabel.toString();
} else {
return label != null ? label.toString() : null;
}
}
private String getPopupKeyboardContent(boolean isShiftCaps, boolean isShifted, boolean addExtra) {
int mainChar = getPrimaryCode(false, false);
int shiftChar = getPrimaryCode(false, true);
int capsChar = getPrimaryCode(true, true);
// Remove duplicates
if (shiftChar == mainChar) shiftChar = 0;
if (capsChar == shiftChar || capsChar == mainChar) capsChar = 0;
int popupLen = (popupCharacters == null) ? 0 : popupCharacters.length();
StringBuilder popup = new StringBuilder(popupLen);
for (int i = 0; i < popupLen; ++i) {
char c = popupCharacters.charAt(i);
if (isShifted || isShiftCaps) {
String upper = Character.toString(c).toUpperCase(LatinIME.sKeyboardSettings.inputLocale);
if (upper.length() == 1) c = upper.charAt(0);
}
if (c == mainChar || c == shiftChar || c == capsChar) continue;
popup.append(c);
}
if (addExtra) {
StringBuilder extra = new StringBuilder(3 + popup.length());
int flags = LatinIME.sKeyboardSettings.popupKeyboardFlags;
if ((flags & POPUP_ADD_SELF) != 0) {
// if shifted, add unshifted key to extra, and vice versa
if (isDistinctUppercase && isShiftCaps) {
if (capsChar > 0) { extra.append((char) capsChar); capsChar = 0; }
} else if (isShifted) {
if (shiftChar > 0) { extra.append((char) shiftChar); shiftChar = 0; }
} else {
if (mainChar > 0) { extra.append((char) mainChar); mainChar = 0; }
}
}
if ((flags & POPUP_ADD_CASE) != 0) {
// if shifted, add unshifted key to popup, and vice versa
if (isDistinctUppercase && isShiftCaps) {
if (mainChar > 0) { extra.append((char) mainChar); mainChar = 0; }
if (shiftChar > 0) { extra.append((char) shiftChar); shiftChar = 0; }
} else if (isShifted) {
if (mainChar > 0) { extra.append((char) mainChar); mainChar = 0; }
if (capsChar > 0) { extra.append((char) capsChar); capsChar = 0; }
} else {
if (shiftChar > 0) { extra.append((char) shiftChar); shiftChar = 0; }
if (capsChar > 0) { extra.append((char) capsChar); capsChar = 0; }
}
}
if (!isSimpleUppercase && (flags & POPUP_ADD_SHIFT) != 0) {
// if shifted, add unshifted key to popup, and vice versa
if (isShifted) {
if (mainChar > 0) { extra.append((char) mainChar); mainChar = 0; }
} else {
if (shiftChar > 0) { extra.append((char) shiftChar); shiftChar = 0; }
}
}
extra.append(popup);
return extra.toString();
}
return popup.toString();
}
public Keyboard getPopupKeyboard(Context context, int padding) {
if (popupCharacters == null) {
if (popupResId != 0) {
return new Keyboard(context, keyboard.mDefaultHeight, popupResId);
} else {
if (modifier) return null; // Space, Return etc.
}
}
if ((LatinIME.sKeyboardSettings.popupKeyboardFlags & POPUP_DISABLE) != 0) return null;
String popup = getPopupKeyboardContent(keyboard.isShiftCaps(), keyboard.isShifted(isSimpleUppercase), true);
//Log.i(TAG, "getPopupKeyboard: popup='" + popup + "' for " + this);
if (popup.length() > 0) {
int resId = popupResId;
if (resId == 0) resId = R.xml.kbd_popup_template;
return new Keyboard(context, keyboard.mDefaultHeight, resId, popup, popupReversed, -1, padding);
} else {
return null;
}
}
public String getHintLabel(boolean wantAscii, boolean wantAll) {
if (hint == null) {
hint = "";
if (shiftLabel != null && !isSimpleUppercase) {
char c = shiftLabel.charAt(0);
if (wantAll || wantAscii && is7BitAscii(c)) {
hint = Character.toString(c);
}
}
}
return hint;
}
public String getAltHintLabel(boolean wantAscii, boolean wantAll) {
if (altHint == null) {
altHint = "";
String popup = getPopupKeyboardContent(false, false, false);
if (popup.length() > 0) {
char c = popup.charAt(0);
if (wantAll || wantAscii && is7BitAscii(c)) {
altHint = Character.toString(c);
}
}
}
return altHint;
}
private static boolean is7BitAscii(char c) {
if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')) return false;
return c >= 32 && c < 127;
}
/**
* Informs the key that it has been pressed, in case it needs to change its appearance or
* state.
* @see #onReleased(boolean)
*/
public void onPressed() {
pressed = !pressed;
}
/**
* Changes the pressed state of the key. Sticky key indicators are handled explicitly elsewhere.
* @param inside whether the finger was released inside the key
* @see #onPressed()
*/
public void onReleased(boolean inside) {
pressed = !pressed;
}
int[] parseCSV(String value) {
int count = 0;
int lastIndex = 0;
if (value.length() > 0) {
count++;
while ((lastIndex = value.indexOf(",", lastIndex + 1)) > 0) {
count++;
}
}
int[] values = new int[count];
count = 0;
StringTokenizer st = new StringTokenizer(value, ",");
while (st.hasMoreTokens()) {
try {
values[count++] = Integer.parseInt(st.nextToken());
} catch (NumberFormatException nfe) {
Log.e(TAG, "Error parsing keycodes " + value);
}
}
return values;
}
/**
* Detects if a point falls inside this key.
* @param x the x-coordinate of the point
* @param y the y-coordinate of the point
* @return whether or not the point falls inside the key. If the key is attached to an edge,
* it will assume that all points between the key and the edge are considered to be inside
* the key.
*/
public boolean isInside(int x, int y) {
boolean leftEdge = (edgeFlags & EDGE_LEFT) > 0;
boolean rightEdge = (edgeFlags & EDGE_RIGHT) > 0;
boolean topEdge = (edgeFlags & EDGE_TOP) > 0;
boolean bottomEdge = (edgeFlags & EDGE_BOTTOM) > 0;
if ((x >= this.x || (leftEdge && x <= this.x + this.width))
&& (x < this.x + this.width || (rightEdge && x >= this.x))
&& (y >= this.y || (topEdge && y <= this.y + this.height))
&& (y < this.y + this.height || (bottomEdge && y >= this.y))) {
return true;
} else {
return false;
}
}
/**
* Returns the square of the distance between the center of the key and the given point.
* @param x the x-coordinate of the point
* @param y the y-coordinate of the point
* @return the square of the distance of the point from the center of the key
*/
public int squaredDistanceFrom(int x, int y) {
int xDist = this.x + width / 2 - x;
int yDist = this.y + height / 2 - y;
return xDist * xDist + yDist * yDist;
}
/**
* Returns the drawable state for the key, based on the current state and type of the key.
* @return the drawable state of the key.
* @see android.graphics.drawable.StateListDrawable#setState(int[])
*/
public int[] getCurrentDrawableState() {
int[] states = KEY_STATE_NORMAL;
if (locked) {
if (pressed) {
states = KEY_STATE_PRESSED_LOCK;
} else {
states = KEY_STATE_NORMAL_LOCK;
}
} else if (on) {
if (pressed) {
states = KEY_STATE_PRESSED_ON;
} else {
states = KEY_STATE_NORMAL_ON;
}
} else {
if (sticky) {
if (pressed) {
states = KEY_STATE_PRESSED_OFF;
} else {
states = KEY_STATE_NORMAL_OFF;
}
} else {
if (pressed) {
states = KEY_STATE_PRESSED;
}
}
}
return states;
}
public String toString() {
int code = (codes != null && codes.length > 0) ? codes[0] : 0;
String edges = (
((edgeFlags & Keyboard.EDGE_LEFT) != 0 ? "L" : "-") +
((edgeFlags & Keyboard.EDGE_RIGHT) != 0 ? "R" : "-") +
((edgeFlags & Keyboard.EDGE_TOP) != 0 ? "T" : "-") +
((edgeFlags & Keyboard.EDGE_BOTTOM) != 0 ? "B" : "-"));
return "KeyDebugFIXME(label=" + label +
(shiftLabel != null ? " shift=" + shiftLabel : "") +
(capsLabel != null ? " caps=" + capsLabel : "") +
(text != null ? " text=" + text : "" ) +
" code=" + code +
(code <= 0 || Character.isWhitespace(code) ? "" : ":'" + (char)code + "'" ) +
" x=" + x + ".." + (x+width) + " y=" + y + ".." + (y+height) +
" edgeFlags=" + edges +
(popupCharacters != null ? " pop=" + popupCharacters : "" ) +
" res=" + popupResId +
")";
}
}
/**
* Creates a keyboard from the given xml key layout file.
* @param context the application or service context
* @param xmlLayoutResId the resource file that contains the keyboard layout and keys.
*/
public Keyboard(Context context, int defaultHeight, int xmlLayoutResId) {
this(context, defaultHeight, xmlLayoutResId, 0);
}
public Keyboard(Context context, int defaultHeight, int xmlLayoutResId, int modeId) {
this(context, defaultHeight, xmlLayoutResId, modeId, 0);
}
/**
* Creates a keyboard from the given xml key layout file. Weeds out rows
* that have a keyboard mode defined but don't match the specified mode.
* @param context the application or service context
* @param xmlLayoutResId the resource file that contains the keyboard layout and keys.
* @param modeId keyboard mode identifier
* @param rowHeightPercent height of each row as percentage of screen height
*/
public Keyboard(Context context, int defaultHeight, int xmlLayoutResId, int modeId, float kbHeightPercent) {
DisplayMetrics dm = context.getResources().getDisplayMetrics();
mDisplayWidth = dm.widthPixels;
mDisplayHeight = dm.heightPixels;
Log.v(TAG, "keyboard's display metrics:" + dm + ", mDisplayWidth=" + mDisplayWidth);
mDefaultHorizontalGap = 0;
mDefaultWidth = mDisplayWidth / 10;
mDefaultVerticalGap = 0;
mDefaultHeight = defaultHeight; // may be zero, to be adjusted below
mKeyboardHeight = Math.round(mDisplayHeight * kbHeightPercent / 100);
//Log.i("PCKeyboard", "mDefaultHeight=" + mDefaultHeight + "(arg=" + defaultHeight + ")" + " kbHeight=" + mKeyboardHeight + " displayHeight="+mDisplayHeight+")");
mKeys = new ArrayList<Key>();
mModifierKeys = new ArrayList<Key>();
mKeyboardMode = modeId;
mUseExtension = LatinIME.sKeyboardSettings.useExtension;
loadKeyboard(context, context.getResources().getXml(xmlLayoutResId));
setEdgeFlags();
fixAltChars(LatinIME.sKeyboardSettings.inputLocale);
}
/**
* <p>Creates a blank keyboard from the given resource file and populates it with the specified
* characters in left-to-right, top-to-bottom fashion, using the specified number of columns.
* </p>
* <p>If the specified number of columns is -1, then the keyboard will fit as many keys as
* possible in each row.</p>
* @param context the application or service context
* @param layoutTemplateResId the layout template file, containing no keys.
* @param characters the list of characters to display on the keyboard. One key will be created
* for each character.
* @param columns the number of columns of keys to display. If this number is greater than the
* number of keys that can fit in a row, it will be ignored. If this number is -1, the
* keyboard will fit as many keys as possible in each row.
*/
private Keyboard(Context context, int defaultHeight, int layoutTemplateResId,
CharSequence characters, boolean reversed, int columns, int horizontalPadding) {
this(context, defaultHeight, layoutTemplateResId);
int x = 0;
int y = 0;
int column = 0;
mTotalWidth = 0;
Row row = new Row(this);
row.defaultHeight = mDefaultHeight;
row.defaultWidth = mDefaultWidth;
row.defaultHorizontalGap = mDefaultHorizontalGap;
row.verticalGap = mDefaultVerticalGap;
final int maxColumns = columns == -1 ? Integer.MAX_VALUE : columns;
mLayoutRows = 1;
int start = reversed ? characters.length()-1 : 0;
int end = reversed ? -1 : characters.length();
int step = reversed ? -1 : 1;
for (int i = start; i != end; i+=step) {
char c = characters.charAt(i);
if (column >= maxColumns
|| x + mDefaultWidth + horizontalPadding > mDisplayWidth) {
x = 0;
y += mDefaultVerticalGap + mDefaultHeight;
column = 0;
++mLayoutRows;
}
final Key key = new Key(row);
key.x = x;
key.realX = x;
key.y = y;
key.label = String.valueOf(c);
key.codes = key.getFromString(key.label);
column++;
x += key.width + key.gap;
mKeys.add(key);
if (x > mTotalWidth) {
mTotalWidth = x;
}
}
mTotalHeight = y + mDefaultHeight;
mLayoutColumns = columns == -1 ? column : maxColumns;
setEdgeFlags();
}
private void setEdgeFlags() {
if (mRowCount == 0) mRowCount = 1; // Assume one row if not set
int row = 0;
Key prevKey = null;
int rowFlags = 0;
for (Key key : mKeys) {
int keyFlags = 0;
if (prevKey == null || key.x <= prevKey.x) {
// Start new row.
if (prevKey != null) {
// Add "right edge" to rightmost key of previous row.
// Need to do the last key separately below.
prevKey.edgeFlags |= Keyboard.EDGE_RIGHT;
}
// Set the row flags for the current row.
rowFlags = 0;
if (row == 0) rowFlags |= Keyboard.EDGE_TOP;
if (row == mRowCount - 1) rowFlags |= Keyboard.EDGE_BOTTOM;
++row;
// Mark current key as "left edge"
keyFlags |= Keyboard.EDGE_LEFT;
}
key.edgeFlags = rowFlags | keyFlags;
prevKey = key;
}
// Fix up the last key
if (prevKey != null) prevKey.edgeFlags |= Keyboard.EDGE_RIGHT;
// Log.i(TAG, "setEdgeFlags() done:");
// for (Key key : mKeys) {
// Log.i(TAG, "key=" + key);
// }
}
private void fixAltChars(Locale locale) {
if (locale == null) locale = Locale.getDefault();
Set<Character> mainKeys = new HashSet<Character>();
for (Key key : mKeys) {
// Remember characters on the main keyboard so that they can be removed from popups.
// This makes it easy to share popup char maps between the normal and shifted
// keyboards.
if (key.label != null && !key.modifier && key.label.length() == 1) {
char c = key.label.charAt(0);
mainKeys.add(c);
}
}
for (Key key : mKeys) {
if (key.popupCharacters == null) continue;
int popupLen = key.popupCharacters.length();
if (popupLen == 0) {
continue;
}
if (key.x >= mTotalWidth / 2) {
key.popupReversed = true;
}
// Uppercase the alt chars if the main key is uppercase
boolean needUpcase = key.label != null && key.label.length() == 1 && Character.isUpperCase(key.label.charAt(0));
if (needUpcase) {
key.popupCharacters = key.popupCharacters.toString().toUpperCase();
popupLen = key.popupCharacters.length();
}
StringBuilder newPopup = new StringBuilder(popupLen);
for (int i = 0; i < popupLen; ++i) {
char c = key.popupCharacters.charAt(i);
if (Character.isDigit(c) && mainKeys.contains(c)) continue; // already present elsewhere
// Skip extra digit alt keys on 5-row keyboards
if ((key.edgeFlags & EDGE_TOP) == 0 && Character.isDigit(c)) continue;
newPopup.append(c);
}
//Log.i("PCKeyboard", "popup for " + key.label + " '" + key.popupCharacters + "' => '"+ newPopup + "' length " + newPopup.length());
key.popupCharacters = newPopup.toString();
}
}
public List<Key> getKeys() {
return mKeys;
}
public List<Key> getModifierKeys() {
return mModifierKeys;
}
protected int getHorizontalGap() {
return Math.round(mDefaultHorizontalGap);
}
protected void setHorizontalGap(int gap) {
mDefaultHorizontalGap = gap;
}
protected int getVerticalGap() {
return mDefaultVerticalGap;
}
protected void setVerticalGap(int gap) {
mDefaultVerticalGap = gap;
}
protected int getKeyHeight() {
return mDefaultHeight;
}
protected void setKeyHeight(int height) {
mDefaultHeight = height;
}
protected int getKeyWidth() {
return Math.round(mDefaultWidth);
}
protected void setKeyWidth(int width) {
mDefaultWidth = width;
}
/**
* Returns the total height of the keyboard
* @return the total height of the keyboard
*/
public int getHeight() {
return mTotalHeight;
}
public int getScreenHeight() {
return mDisplayHeight;
}
public int getMinWidth() {
return mTotalWidth;
}
public boolean setShiftState(int shiftState, boolean updateKey) {
//Log.i(TAG, "setShiftState " + mShiftState + " -> " + shiftState);
if (updateKey && mShiftKey != null) {
mShiftKey.on = (shiftState != SHIFT_OFF);
}
if (mShiftState != shiftState) {
mShiftState = shiftState;
return true;
}
return false;
}
public boolean setShiftState(int shiftState) {
return setShiftState(shiftState, true);
}
public Key setCtrlIndicator(boolean active) {
//Log.i(TAG, "setCtrlIndicator " + active + " ctrlKey=" + mCtrlKey);
if (mCtrlKey != null) mCtrlKey.on = active;
return mCtrlKey;
}
public Key setAltIndicator(boolean active) {
if (mAltKey != null) mAltKey.on = active;
return mAltKey;
}
public Key setMetaIndicator(boolean active) {
if (mMetaKey != null) mMetaKey.on = active;
return mMetaKey;
}
public boolean isShiftCaps() {
return mShiftState == SHIFT_CAPS || mShiftState == SHIFT_CAPS_LOCKED;
}
public boolean isShifted(boolean applyCaps) {
if (applyCaps) {
return mShiftState != SHIFT_OFF;
} else {
return mShiftState == SHIFT_ON || mShiftState == SHIFT_LOCKED;
}
}
public int getShiftState() {
return mShiftState;
}
public int getShiftKeyIndex() {
return mShiftKeyIndex;
}
private void computeNearestNeighbors() {
// Round-up so we don't have any pixels outside the grid
mCellWidth = (getMinWidth() + mLayoutColumns - 1) / mLayoutColumns;
mCellHeight = (getHeight() + mLayoutRows - 1) / mLayoutRows;
mGridNeighbors = new int[mLayoutColumns * mLayoutRows][];
int[] indices = new int[mKeys.size()];
final int gridWidth = mLayoutColumns * mCellWidth;
final int gridHeight = mLayoutRows * mCellHeight;
for (int x = 0; x < gridWidth; x += mCellWidth) {
for (int y = 0; y < gridHeight; y += mCellHeight) {
int count = 0;
for (int i = 0; i < mKeys.size(); i++) {
final Key key = mKeys.get(i);
boolean isSpace = key.codes != null && key.codes.length > 0 &&
key.codes[0] == LatinIME.ASCII_SPACE;
if (key.squaredDistanceFrom(x, y) < mProximityThreshold ||
key.squaredDistanceFrom(x + mCellWidth - 1, y) < mProximityThreshold ||
key.squaredDistanceFrom(x + mCellWidth - 1, y + mCellHeight - 1)
< mProximityThreshold ||
key.squaredDistanceFrom(x, y + mCellHeight - 1) < mProximityThreshold ||
isSpace && !(
x + mCellWidth - 1 < key.x ||
x > key.x + key.width ||
y + mCellHeight - 1 < key.y ||
y > key.y + key.height)) {
//if (isSpace) Log.i(TAG, "space at grid" + x + "," + y);
indices[count++] = i;
}
}
int [] cell = new int[count];
System.arraycopy(indices, 0, cell, 0, count);
mGridNeighbors[(y / mCellHeight) * mLayoutColumns + (x / mCellWidth)] = cell;
}
}
}
/**
* Returns the indices of the keys that are closest to the given point.
* @param x the x-coordinate of the point
* @param y the y-coordinate of the point
* @return the array of integer indices for the nearest keys to the given point. If the given
* point is out of range, then an array of size zero is returned.
*/
public int[] getNearestKeys(int x, int y) {
if (mGridNeighbors == null) computeNearestNeighbors();
if (x >= 0 && x < getMinWidth() && y >= 0 && y < getHeight()) {
int index = (y / mCellHeight) * mLayoutColumns + (x / mCellWidth);
if (index < mLayoutRows * mLayoutColumns) {
return mGridNeighbors[index];
}
}
return new int[0];
}
protected Row createRowFromXml(Resources res, XmlResourceParser parser) {
return new Row(res, this, parser);
}
protected Key createKeyFromXml(Resources res, Row parent, int x, int y,
XmlResourceParser parser) {
return new Key(res, parent, x, y, parser);
}
private void loadKeyboard(Context context, XmlResourceParser parser) {
boolean inKey = false;
boolean inRow = false;
float x = 0;
int y = 0;
Key key = null;
Row currentRow = null;
Resources res = context.getResources();
boolean skipRow = false;
mRowCount = 0;
try {
int event;
Key prevKey = null;
while ((event = parser.next()) != XmlResourceParser.END_DOCUMENT) {
if (event == XmlResourceParser.START_TAG) {
String tag = parser.getName();
if (TAG_ROW.equals(tag)) {
inRow = true;
x = 0;
currentRow = createRowFromXml(res, parser);
skipRow = currentRow.mode != 0 && currentRow.mode != mKeyboardMode;
if (currentRow.extension) {
if (mUseExtension) {
++mExtensionRowCount;
} else {
skipRow = true;
}
}
if (skipRow) {
skipToEndOfRow(parser);
inRow = false;
}
} else if (TAG_KEY.equals(tag)) {
inKey = true;
key = createKeyFromXml(res, currentRow, Math.round(x), y, parser);
key.realX = x;
if (key.codes == null) {
// skip this key, adding its width to the previous one
if (prevKey != null) {
prevKey.width += key.width;
}
} else {
mKeys.add(key);
prevKey = key;
if (key.codes[0] == KEYCODE_SHIFT) {
if (mShiftKeyIndex == -1) {
mShiftKey = key;
mShiftKeyIndex = mKeys.size()-1;
}
mModifierKeys.add(key);
} else if (key.codes[0] == KEYCODE_ALT_SYM) {
mModifierKeys.add(key);
} else if (key.codes[0] == LatinKeyboardView.KEYCODE_CTRL_LEFT) {
mCtrlKey = key;
} else if (key.codes[0] == LatinKeyboardView.KEYCODE_ALT_LEFT) {
mAltKey = key;
} else if (key.codes[0] == LatinKeyboardView.KEYCODE_META_LEFT) {
mMetaKey = key;
}
}
} else if (TAG_KEYBOARD.equals(tag)) {
parseKeyboardAttributes(res, parser);
}
} else if (event == XmlResourceParser.END_TAG) {
if (inKey) {
inKey = false;
x += key.realGap + key.realWidth;
if (x > mTotalWidth) {
mTotalWidth = Math.round(x);
}
} else if (inRow) {
inRow = false;
y += currentRow.verticalGap;
y += currentRow.defaultHeight;
mRowCount++;
} else {
// TODO: error or extend?
}
}
}
} catch (Exception e) {
Log.e(TAG, "Parse error:" + e);
e.printStackTrace();
}
mTotalHeight = y - mDefaultVerticalGap;
}
public void setKeyboardWidth(int newWidth) {
Log.i(TAG, "setKeyboardWidth newWidth=" + newWidth + ", mTotalWidth=" + mTotalWidth);
if (newWidth <= 0) return; // view not initialized?
if (mTotalWidth <= newWidth) return; // it already fits
float scale = (float) newWidth / mDisplayWidth;
Log.i("PCKeyboard", "Rescaling keyboard: " + mTotalWidth + " => " + newWidth);
for (Key key : mKeys) {
key.x = Math.round(key.realX * scale);
}
mTotalWidth = newWidth;
}
private void skipToEndOfRow(XmlResourceParser parser)
throws XmlPullParserException, IOException {
int event;
while ((event = parser.next()) != XmlResourceParser.END_DOCUMENT) {
if (event == XmlResourceParser.END_TAG
&& parser.getName().equals(TAG_ROW)) {
break;
}
}
}
private void parseKeyboardAttributes(Resources res, XmlResourceParser parser) {
TypedArray a = res.obtainAttributes(Xml.asAttributeSet(parser),
R.styleable.Keyboard);
mDefaultWidth = getDimensionOrFraction(a,
R.styleable.Keyboard_keyWidth,
mDisplayWidth, mDisplayWidth / 10);
mDefaultHeight = Math.round(getDimensionOrFraction(a,
R.styleable.Keyboard_keyHeight,
mDisplayHeight, mDefaultHeight));
mDefaultHorizontalGap = getDimensionOrFraction(a,
R.styleable.Keyboard_horizontalGap,
mDisplayWidth, 0);
mDefaultVerticalGap = Math.round(getDimensionOrFraction(a,
R.styleable.Keyboard_verticalGap,
mDisplayHeight, 0));
mHorizontalPad = getDimensionOrFraction(a,
R.styleable.Keyboard_horizontalPad,
mDisplayWidth, res.getDimension(R.dimen.key_horizontal_pad));
mVerticalPad = getDimensionOrFraction(a,
R.styleable.Keyboard_verticalPad,
mDisplayHeight, res.getDimension(R.dimen.key_vertical_pad));
mLayoutRows = a.getInteger(R.styleable.Keyboard_layoutRows, DEFAULT_LAYOUT_ROWS);
mLayoutColumns = a.getInteger(R.styleable.Keyboard_layoutColumns, DEFAULT_LAYOUT_COLUMNS);
if (mDefaultHeight == 0 && mKeyboardHeight > 0 && mLayoutRows > 0) {
mDefaultHeight = mKeyboardHeight / mLayoutRows;
//Log.i(TAG, "got mLayoutRows=" + mLayoutRows + ", mDefaultHeight=" + mDefaultHeight);
}
mProximityThreshold = (int) (mDefaultWidth * SEARCH_DISTANCE);
mProximityThreshold = mProximityThreshold * mProximityThreshold; // Square it for comparison
a.recycle();
}
static float getDimensionOrFraction(TypedArray a, int index, int base, float defValue) {
TypedValue value = a.peekValue(index);
if (value == null) return defValue;
if (value.type == TypedValue.TYPE_DIMENSION) {
return a.getDimensionPixelOffset(index, Math.round(defValue));
} else if (value.type == TypedValue.TYPE_FRACTION) {
// Round it to avoid values like 47.9999 from getting truncated
//return Math.round(a.getFraction(index, base, base, defValue));
return a.getFraction(index, base, base, defValue);
}
return defValue;
}
@Override
public String toString() {
return "Keyboard(" + mLayoutColumns + "x" + mLayoutRows +
" keys=" + mKeys.size() +
" rowCount=" + mRowCount +
" mode=" + mKeyboardMode +
" size=" + mTotalWidth + "x" + mTotalHeight +
")";
}
}
| Java |
/*
* Copyright (C) 2011 Darren Salt
*
* Licensed under the Apache License, Version 2.0 (the "Licence"); you may
* not use this file except in compliance with the Licence. You may obtain
* a copy of the Licence at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the Licence is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* Licence for the specific language governing permissions and limitations
* under the Licence.
*/
package org.pocketworkstation.pckeyboard;
import android.inputmethodservice.InputMethodService;
import android.util.Log;
import android.view.inputmethod.EditorInfo;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
interface ComposeSequencing {
public void onText(CharSequence text);
public void updateShiftKeyState(EditorInfo attr);
public EditorInfo getCurrentInputEditorInfo();
}
public abstract class ComposeBase {
private static final String TAG = "HK/ComposeBase";
protected static final Map<String, String> mMap =
new HashMap<String, String>();
protected static final Set<String> mPrefixes =
new HashSet<String>();
protected static String get(String key) {
if (key == null || key.length() == 0) {
return null;
}
//Log.i(TAG, "ComposeBase get, key=" + showString(key) + " result=" + mMap.get(key));
return mMap.get(key);
}
private static String showString(String in) {
// TODO Auto-generated method stub
StringBuilder out = new StringBuilder(in);
out.append("{");
for (int i = 0; i < in.length(); ++i) {
if (i > 0) out.append(",");
out.append((int) in.charAt(i));
}
out.append("}");
return out.toString();
}
private static boolean isValid(String partialKey) {
if (partialKey == null || partialKey.length() == 0) {
return false;
}
return mPrefixes.contains(partialKey);
}
protected static void put(String key, String value) {
mMap.put(key, value);
for (int i = 1; i < key.length(); ++i) {
mPrefixes.add(key.substring(0, i));
}
}
protected StringBuilder composeBuffer = new StringBuilder(10);
protected ComposeSequencing composeUser;
protected void init(ComposeSequencing user) {
clear();
composeUser = user;
}
public void clear() {
composeBuffer.setLength(0);
}
public void bufferKey(char code) {
composeBuffer.append(code);
//Log.i(TAG, "bufferKey code=" + (int) code + " => " + showString(composeBuffer.toString()));
}
// returns true if the compose sequence is valid but incomplete
public String executeToString(int code) {
KeyboardSwitcher ks = KeyboardSwitcher.getInstance();
if (ks.getInputView().isShiftCaps()
&& ks.isAlphabetMode()
&& Character.isLowerCase(code)) {
code = Character.toUpperCase(code);
}
bufferKey((char) code);
composeUser.updateShiftKeyState(composeUser.getCurrentInputEditorInfo());
String composed = get(composeBuffer.toString());
if (composed != null) {
// If we get here, we have a complete compose sequence
return composed;
} else if (!isValid(composeBuffer.toString())) {
// If we get here, then the sequence typed isn't recognised
return "";
}
return null;
}
public boolean execute(int code) {
String composed = executeToString(code);
if (composed != null) {
clear();
composeUser.onText(composed);
return false;
}
return true;
}
public boolean execute(CharSequence sequence) {
int i, len = sequence.length();
boolean result = true;
for (i = 0; i < len; ++i) {
result = execute(sequence.charAt(i));
}
return result; // only last one matters
}
}
| Java |
/*
* Copyright (C) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import java.util.HashMap;
import java.util.Set;
import java.util.Map.Entry;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.os.AsyncTask;
import android.provider.BaseColumns;
import android.util.Log;
/**
* Stores new words temporarily until they are promoted to the user dictionary
* for longevity. Words in the auto dictionary are used to determine if it's ok
* to accept a word that's not in the main or user dictionary. Using a new word
* repeatedly will promote it to the user dictionary.
*/
public class AutoDictionary extends ExpandableDictionary {
// Weight added to a user picking a new word from the suggestion strip
static final int FREQUENCY_FOR_PICKED = 3;
// Weight added to a user typing a new word that doesn't get corrected (or is reverted)
static final int FREQUENCY_FOR_TYPED = 1;
// A word that is frequently typed and gets promoted to the user dictionary, uses this
// frequency.
static final int FREQUENCY_FOR_AUTO_ADD = 250;
// If the user touches a typed word 2 times or more, it will become valid.
private static final int VALIDITY_THRESHOLD = 2 * FREQUENCY_FOR_PICKED;
// If the user touches a typed word 4 times or more, it will be added to the user dict.
private static final int PROMOTION_THRESHOLD = 4 * FREQUENCY_FOR_PICKED;
private LatinIME mIme;
// Locale for which this auto dictionary is storing words
private String mLocale;
private HashMap<String,Integer> mPendingWrites = new HashMap<String,Integer>();
private final Object mPendingWritesLock = new Object();
private static final String DATABASE_NAME = "auto_dict.db";
private static final int DATABASE_VERSION = 1;
// These are the columns in the dictionary
// TODO: Consume less space by using a unique id for locale instead of the whole
// 2-5 character string.
private static final String COLUMN_ID = BaseColumns._ID;
private static final String COLUMN_WORD = "word";
private static final String COLUMN_FREQUENCY = "freq";
private static final String COLUMN_LOCALE = "locale";
/** Sort by descending order of frequency. */
public static final String DEFAULT_SORT_ORDER = COLUMN_FREQUENCY + " DESC";
/** Name of the words table in the auto_dict.db */
private static final String AUTODICT_TABLE_NAME = "words";
private static HashMap<String, String> sDictProjectionMap;
static {
sDictProjectionMap = new HashMap<String, String>();
sDictProjectionMap.put(COLUMN_ID, COLUMN_ID);
sDictProjectionMap.put(COLUMN_WORD, COLUMN_WORD);
sDictProjectionMap.put(COLUMN_FREQUENCY, COLUMN_FREQUENCY);
sDictProjectionMap.put(COLUMN_LOCALE, COLUMN_LOCALE);
}
private static DatabaseHelper sOpenHelper = null;
public AutoDictionary(Context context, LatinIME ime, String locale, int dicTypeId) {
super(context, dicTypeId);
mIme = ime;
mLocale = locale;
if (sOpenHelper == null) {
sOpenHelper = new DatabaseHelper(getContext());
}
if (mLocale != null && mLocale.length() > 1) {
loadDictionary();
}
}
@Override
public boolean isValidWord(CharSequence word) {
final int frequency = getWordFrequency(word);
return frequency >= VALIDITY_THRESHOLD;
}
@Override
public void close() {
flushPendingWrites();
// Don't close the database as locale changes will require it to be reopened anyway
// Also, the database is written to somewhat frequently, so it needs to be kept alive
// throughout the life of the process.
// mOpenHelper.close();
super.close();
}
@Override
public void loadDictionaryAsync() {
// Load the words that correspond to the current input locale
Cursor cursor = query(COLUMN_LOCALE + "=?", new String[] { mLocale });
try {
if (cursor.moveToFirst()) {
int wordIndex = cursor.getColumnIndex(COLUMN_WORD);
int frequencyIndex = cursor.getColumnIndex(COLUMN_FREQUENCY);
while (!cursor.isAfterLast()) {
String word = cursor.getString(wordIndex);
int frequency = cursor.getInt(frequencyIndex);
// Safeguard against adding really long words. Stack may overflow due
// to recursive lookup
if (word.length() < getMaxWordLength()) {
super.addWord(word, frequency);
}
cursor.moveToNext();
}
}
} finally {
cursor.close();
}
}
@Override
public void addWord(String word, int addFrequency) {
final int length = word.length();
// Don't add very short or very long words.
if (length < 2 || length > getMaxWordLength()) return;
if (mIme.getCurrentWord().isAutoCapitalized()) {
// Remove caps before adding
word = Character.toLowerCase(word.charAt(0)) + word.substring(1);
}
int freq = getWordFrequency(word);
freq = freq < 0 ? addFrequency : freq + addFrequency;
super.addWord(word, freq);
if (freq >= PROMOTION_THRESHOLD) {
mIme.promoteToUserDictionary(word, FREQUENCY_FOR_AUTO_ADD);
freq = 0;
}
synchronized (mPendingWritesLock) {
// Write a null frequency if it is to be deleted from the db
mPendingWrites.put(word, freq == 0 ? null : new Integer(freq));
}
}
/**
* Schedules a background thread to write any pending words to the database.
*/
public void flushPendingWrites() {
synchronized (mPendingWritesLock) {
// Nothing pending? Return
if (mPendingWrites.isEmpty()) return;
// Create a background thread to write the pending entries
new UpdateDbTask(getContext(), sOpenHelper, mPendingWrites, mLocale).execute();
// Create a new map for writing new entries into while the old one is written to db
mPendingWrites = new HashMap<String, Integer>();
}
}
/**
* This class helps open, create, and upgrade the database file.
*/
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + AUTODICT_TABLE_NAME + " ("
+ COLUMN_ID + " INTEGER PRIMARY KEY,"
+ COLUMN_WORD + " TEXT,"
+ COLUMN_FREQUENCY + " INTEGER,"
+ COLUMN_LOCALE + " TEXT"
+ ");");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w("AutoDictionary", "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + AUTODICT_TABLE_NAME);
onCreate(db);
}
}
private Cursor query(String selection, String[] selectionArgs) {
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(AUTODICT_TABLE_NAME);
qb.setProjectionMap(sDictProjectionMap);
// Get the database and run the query
SQLiteDatabase db = sOpenHelper.getReadableDatabase();
Cursor c = qb.query(db, null, selection, selectionArgs, null, null,
DEFAULT_SORT_ORDER);
return c;
}
/**
* Async task to write pending words to the database so that it stays in sync with
* the in-memory trie.
*/
private static class UpdateDbTask extends AsyncTask<Void, Void, Void> {
private final HashMap<String, Integer> mMap;
private final DatabaseHelper mDbHelper;
private final String mLocale;
public UpdateDbTask(Context context, DatabaseHelper openHelper,
HashMap<String, Integer> pendingWrites, String locale) {
mMap = pendingWrites;
mLocale = locale;
mDbHelper = openHelper;
}
@Override
protected Void doInBackground(Void... v) {
SQLiteDatabase db = mDbHelper.getWritableDatabase();
// Write all the entries to the db
Set<Entry<String,Integer>> mEntries = mMap.entrySet();
for (Entry<String,Integer> entry : mEntries) {
Integer freq = entry.getValue();
db.delete(AUTODICT_TABLE_NAME, COLUMN_WORD + "=? AND " + COLUMN_LOCALE + "=?",
new String[] { entry.getKey(), mLocale });
if (freq != null) {
db.insert(AUTODICT_TABLE_NAME, null,
getContentValues(entry.getKey(), freq, mLocale));
}
}
return null;
}
private ContentValues getContentValues(String word, int frequency, String locale) {
ContentValues values = new ContentValues(4);
values.put(COLUMN_WORD, word);
values.put(COLUMN_FREQUENCY, frequency);
values.put(COLUMN_LOCALE, locale);
return values;
}
}
}
| Java |
package org.pocketworkstation.pckeyboard;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.xmlpull.v1.XmlPullParserException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources;
import android.content.res.XmlResourceParser;
import android.util.Log;
public class PluginManager extends BroadcastReceiver {
private static String TAG = "PCKeyboard";
private static String HK_INTENT_DICT = "org.pocketworkstation.DICT";
private static String SOFTKEYBOARD_INTENT_DICT = "com.menny.android.anysoftkeyboard.DICTIONARY";
private LatinIME mIME;
// Apparently anysoftkeyboard doesn't use ISO 639-1 language codes for its locales?
// Add exceptions as needed.
private static Map<String, String> SOFTKEYBOARD_LANG_MAP = new HashMap<String, String>();
static {
SOFTKEYBOARD_LANG_MAP.put("dk", "da");
}
PluginManager(LatinIME ime) {
super();
mIME = ime;
}
private static Map<String, DictPluginSpec> mPluginDicts =
new HashMap<String, DictPluginSpec>();
static interface DictPluginSpec {
BinaryDictionary getDict(Context context);
}
static private abstract class DictPluginSpecBase
implements DictPluginSpec {
String mPackageName;
Resources getResources(Context context) {
PackageManager packageManager = context.getPackageManager();
Resources res = null;
try {
ApplicationInfo appInfo = packageManager.getApplicationInfo(mPackageName, 0);
res = packageManager.getResourcesForApplication(appInfo);
} catch (NameNotFoundException e) {
Log.i(TAG, "couldn't get resources");
}
return res;
}
abstract InputStream[] getStreams(Resources res);
public BinaryDictionary getDict(Context context) {
Resources res = getResources(context);
if (res == null) return null;
InputStream[] dicts = getStreams(res);
if (dicts == null) return null;
BinaryDictionary dict = new BinaryDictionary(
context, dicts, Suggest.DIC_MAIN);
if (dict.getSize() == 0) return null;
//Log.i(TAG, "dict size=" + dict.getSize());
return dict;
}
}
static private class DictPluginSpecHK
extends DictPluginSpecBase {
int[] mRawIds;
public DictPluginSpecHK(String pkg, int[] ids) {
mPackageName = pkg;
mRawIds = ids;
}
@Override
InputStream[] getStreams(Resources res) {
if (mRawIds == null || mRawIds.length == 0) return null;
InputStream[] streams = new InputStream[mRawIds.length];
for (int i = 0; i < mRawIds.length; ++i) {
streams[i] = res.openRawResource(mRawIds[i]);
}
return streams;
}
}
static private class DictPluginSpecSoftKeyboard
extends DictPluginSpecBase {
String mAssetName;
public DictPluginSpecSoftKeyboard(String pkg, String asset) {
mPackageName = pkg;
mAssetName = asset;
}
@Override
InputStream[] getStreams(Resources res) {
if (mAssetName == null) return null;
try {
InputStream in = res.getAssets().open(mAssetName);
return new InputStream[] {in};
} catch (IOException e) {
Log.e(TAG, "Dictionary asset loading failure");
return null;
}
}
}
@Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "Package information changed, updating dictionaries.");
getPluginDictionaries(context);
Log.i(TAG, "Finished updating dictionaries.");
mIME.toggleLanguage(true, true);
}
static void getSoftKeyboardDictionaries(PackageManager packageManager) {
Intent dictIntent = new Intent(SOFTKEYBOARD_INTENT_DICT);
List<ResolveInfo> dictPacks = packageManager.queryBroadcastReceivers(
dictIntent, PackageManager.GET_RECEIVERS);
for (ResolveInfo ri : dictPacks) {
ApplicationInfo appInfo = ri.activityInfo.applicationInfo;
String pkgName = appInfo.packageName;
boolean success = false;
try {
Resources res = packageManager.getResourcesForApplication(appInfo);
//Log.i(TAG, "Found dictionary plugin package: " + pkgName);
int dictId = res.getIdentifier("dictionaries", "xml", pkgName);
if (dictId == 0) continue;
XmlResourceParser xrp = res.getXml(dictId);
String assetName = null;
String lang = null;
try {
int current = xrp.getEventType();
while (current != XmlResourceParser.END_DOCUMENT) {
if (current == XmlResourceParser.START_TAG) {
String tag = xrp.getName();
if (tag != null) {
if (tag.equals("Dictionary")) {
lang = xrp.getAttributeValue(null, "locale");
String convLang = SOFTKEYBOARD_LANG_MAP.get(lang);
if (convLang != null) lang = convLang;
String type = xrp.getAttributeValue(null, "type");
if (type == null || type.equals("raw") || type.equals("binary")) {
assetName = xrp.getAttributeValue(null, "dictionaryAssertName"); // sic
} else {
Log.w(TAG, "Unsupported AnySoftKeyboard dict type " + type);
}
//Log.i(TAG, "asset=" + assetName + " lang=" + lang);
}
}
}
xrp.next();
current = xrp.getEventType();
}
} catch (XmlPullParserException e) {
Log.e(TAG, "Dictionary XML parsing failure");
} catch (IOException e) {
Log.e(TAG, "Dictionary XML IOException");
}
if (assetName == null || lang == null) continue;
DictPluginSpec spec = new DictPluginSpecSoftKeyboard(pkgName, assetName);
mPluginDicts.put(lang, spec);
Log.i(TAG, "Found plugin dictionary: lang=" + lang + ", pkg=" + pkgName);
success = true;
} catch (NameNotFoundException e) {
Log.i(TAG, "bad");
} finally {
if (!success) {
Log.i(TAG, "failed to load plugin dictionary spec from " + pkgName);
}
}
}
}
static void getHKDictionaries(PackageManager packageManager) {
Intent dictIntent = new Intent(HK_INTENT_DICT);
List<ResolveInfo> dictPacks = packageManager.queryIntentActivities(dictIntent, 0);
for (ResolveInfo ri : dictPacks) {
ApplicationInfo appInfo = ri.activityInfo.applicationInfo;
String pkgName = appInfo.packageName;
boolean success = false;
try {
Resources res = packageManager.getResourcesForApplication(appInfo);
//Log.i(TAG, "Found dictionary plugin package: " + pkgName);
int langId = res.getIdentifier("dict_language", "string", pkgName);
if (langId == 0) continue;
String lang = res.getString(langId);
int[] rawIds = null;
// Try single-file version first
int rawId = res.getIdentifier("main", "raw", pkgName);
if (rawId != 0) {
rawIds = new int[] { rawId };
} else {
// try multi-part version
int parts = 0;
List<Integer> ids = new ArrayList<Integer>();
while (true) {
int id = res.getIdentifier("main" + parts, "raw", pkgName);
if (id == 0) break;
ids.add(id);
++parts;
}
if (parts == 0) continue; // no parts found
rawIds = new int[parts];
for (int i = 0; i < parts; ++i) rawIds[i] = ids.get(i);
}
DictPluginSpec spec = new DictPluginSpecHK(pkgName, rawIds);
mPluginDicts.put(lang, spec);
Log.i(TAG, "Found plugin dictionary: lang=" + lang + ", pkg=" + pkgName);
success = true;
} catch (NameNotFoundException e) {
Log.i(TAG, "bad");
} finally {
if (!success) {
Log.i(TAG, "failed to load plugin dictionary spec from " + pkgName);
}
}
}
}
static void getPluginDictionaries(Context context) {
mPluginDicts.clear();
PackageManager packageManager = context.getPackageManager();
getSoftKeyboardDictionaries(packageManager);
getHKDictionaries(packageManager);
}
static BinaryDictionary getDictionary(Context context, String lang) {
//Log.i(TAG, "Looking for plugin dictionary for lang=" + lang);
DictPluginSpec spec = mPluginDicts.get(lang);
if (spec == null) spec = mPluginDicts.get(lang.substring(0, 2));
if (spec == null) {
//Log.i(TAG, "No plugin found.");
return null;
}
BinaryDictionary dict = spec.getDict(context);
Log.i(TAG, "Found plugin dictionary for " + lang + (dict == null ? " is null" : ", size=" + dict.getSize()));
return dict;
}
}
| Java |
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
/**
* Abstract base class for a dictionary that can do a fuzzy search for words based on a set of key
* strokes.
*/
abstract public class Dictionary {
/**
* Whether or not to replicate the typed word in the suggested list, even if it's valid.
*/
protected static final boolean INCLUDE_TYPED_WORD_IF_VALID = false;
/**
* The weight to give to a word if it's length is the same as the number of typed characters.
*/
protected static final int FULL_WORD_FREQ_MULTIPLIER = 2;
public static enum DataType {
UNIGRAM, BIGRAM
}
/**
* Interface to be implemented by classes requesting words to be fetched from the dictionary.
* @see #getWords(WordComposer, WordCallback)
*/
public interface WordCallback {
/**
* Adds a word to a list of suggestions. The word is expected to be ordered based on
* the provided frequency.
* @param word the character array containing the word
* @param wordOffset starting offset of the word in the character array
* @param wordLength length of valid characters in the character array
* @param frequency the frequency of occurence. This is normalized between 1 and 255, but
* can exceed those limits
* @param dicTypeId of the dictionary where word was from
* @param dataType tells type of this data
* @return true if the word was added, false if no more words are required
*/
boolean addWord(char[] word, int wordOffset, int wordLength, int frequency, int dicTypeId,
DataType dataType);
}
/**
* Searches for words in the dictionary that match the characters in the composer. Matched
* words are added through the callback object.
* @param composer the key sequence to match
* @param callback the callback object to send matched words to as possible candidates
* @param nextLettersFrequencies array of frequencies of next letters that could follow the
* word so far. For instance, "bracke" can be followed by "t", so array['t'] will have
* a non-zero value on returning from this method.
* Pass in null if you don't want the dictionary to look up next letters.
* @see WordCallback#addWord(char[], int, int)
*/
abstract public void getWords(final WordComposer composer, final WordCallback callback,
int[] nextLettersFrequencies);
/**
* Searches for pairs in the bigram dictionary that matches the previous word and all the
* possible words following are added through the callback object.
* @param composer the key sequence to match
* @param callback the callback object to send possible word following previous word
* @param nextLettersFrequencies array of frequencies of next letters that could follow the
* word so far. For instance, "bracke" can be followed by "t", so array['t'] will have
* a non-zero value on returning from this method.
* Pass in null if you don't want the dictionary to look up next letters.
*/
public void getBigrams(final WordComposer composer, final CharSequence previousWord,
final WordCallback callback, int[] nextLettersFrequencies) {
// empty base implementation
}
/**
* Checks if the given word occurs in the dictionary
* @param word the word to search for. The search should be case-insensitive.
* @return true if the word exists, false otherwise
*/
abstract public boolean isValidWord(CharSequence word);
/**
* Compares the contents of the character array with the typed word and returns true if they
* are the same.
* @param word the array of characters that make up the word
* @param length the number of valid characters in the character array
* @param typedWord the word to compare with
* @return true if they are the same, false otherwise.
*/
protected boolean same(final char[] word, final int length, final CharSequence typedWord) {
if (typedWord.length() != length) {
return false;
}
for (int i = 0; i < length; i++) {
if (word[i] != typedWord.charAt(i)) {
return false;
}
}
return true;
}
/**
* Override to clean up any resources.
*/
public void close() {
}
}
| Java |
//import drasys.or.nonlinear.*;
import gaiatools.numeric.function.Function;
/*
* Utility class for passing around functions
*
* implements the drasys "FunctionI" interface to enable Simpsons method
* outsource.
*/
public abstract class FunctionI extends Function {
public double value(double var) {
return 0;
}
}
| Java |
import java.util.StringTokenizer;
/**
* Adapted for heliosphere display
* this one for showing flux as a skymap
*/
public class HelioFluxViewer {
public static double AU = 1.49598* Math.pow(10,11); //meters
public HelioFluxViewer (String filename) {
file f = new file(filename);
//int num2 = 101;
double[] xArray = new double[60]; // x is theta
double[] yArray = new double[361]; // y is phi
// set up x and y axes for reading file
for (int i=0; i<xArray.length; i+=1) {
xArray[i]=(double)i+60.0;
}
for (int i=0; i<yArray.length; i+=1) {
yArray[i]=(double)i;
}
double[] zArray = new double[xArray.length*yArray.length];
for (int i=0; i<zArray.length; i++) zArray[i]=0.0;
f.initRead();
String line = ""; //f.readLine(); // garbage - header
int index = 0;
String garbage = "";
while ((line=f.readLine())!=null) {
double x=0;
double y=0;
double num=0;
StringTokenizer st = new StringTokenizer(line);
try {
garbage = st.nextToken();
x = Double.parseDouble(st.nextToken());
y = Double.parseDouble(st.nextToken());
//if (numS.equals("Infinity")) numS="0.001";
num = Double.parseDouble(st.nextToken());
//if (num==0.0) num = 0.001;
//num = num+1.0;
//num = Math.log(num);
}
catch (Exception e) {e.printStackTrace();}
zArray[index]=num;
//System.out.println(index + " " + zArray[index]);
index++;
}
System.out.println("index: " + index + " zArray.length: " + zArray.length);
// get min and max of zarray
double minz = 1000.0;
double maxz = 0.0;
for (int j=0; j<zArray.length; j++) {
if (zArray[j]>maxz) maxz=zArray[j];
if (zArray[j]<minz) minz=zArray[j];
}
System.out.println("minz: "+minz+" maxz: "+maxz);
/* int index = 0;
for (int i=0; i<x.length; i++) {
x[i]=(tpTimes[i]-GOODS)/24.0/60.0/60.0;
for (int j=0; j<y.length; j++) {
y[j]=tpHist[i].label[j];
if (tpHist[i].data[j]==0) z[index]=0.0;
else {
z[index]=tpHist[i].data[j];
//o("nonzero z: " + z[index]);
}
index++;
}
}*/
JColorGraph jcg = new JColorGraph(xArray,yArray,zArray,true);
jcg.fileName = filename;
String unitString = "Counts";
//if (histType == "Flux") unitString = "Diff. Flux (1/cm^2/s/sr/keV)";
//if (histType == "Distribution Function") unitString = "Dist. Function (s^3/km^6)";
//if (histType == "Log Distribution Function") unitString = "log Dist. Function (s^3/km^6)";
jcg.setLabels("Heliosphere Simulation","UniBern 2008",unitString);
jcg.run();
jcg.showIt();
}
public static final void main(String[] args) {
HelioFluxViewer m = new HelioFluxViewer (args[0]);
}
}
| Java |
/**
* this routine calculates the distribution function (6D)
* however based on 5D inputs as there is symmetry about inflow axis
*
* NOTE: parameters of distribution must be given in coordinates
* relative to inflow direction for this routine
* Damby & Camm 1957, Mostly from Judge & Wu 1979
*
* Most of the math of the calcuation is in this method!
*
* r = dist. from sun
* theta = angle from inflow
*
*
*/
public double computeReferenceCoords(
double r, double theta, double vr, double vt, double vPsi) {
// we need to make sure that vt is within an appropriate range
// this amounts to assuming no non-hyperbolic trajectories
if (Math.abs(vt) < vtLimit(vr,r)) return 0;
else {
Q = Math.sqrt((1-mu)*G*Ms/r);
//System.out.println(""+(vr*vr+vt*vt-2*Q*Q));
V0 = Math.sqrt(vr*vr + vt*vt - 2*Q*Q);
//System.out.println("computed easy numbers "+Q+" "+V0);
F1 = 2*Vb*V0/(Vtemp*Vtemp) * Math.cos(theta)*(V0 - vr)*(V0 - vr)/(V0*(V0-vr)+Q*Q) -
((Vb*Vb)+(V0*V0)+2*V0*Vb*Math.cos(theta))/(Vtemp*Vtemp);
F2 = 2*V0*Vb*vt/(Vtemp*Vtemp) * Math.sin(theta)*(V0-vr)/ (vr*(V0-vr) + (Q*Q));
//System.out.println("computed F1 & F2 "+F1+" "+F2);
return sp.compute(r,theta,vr,vt)*
N * test1 * Math.exp(F1 + F2*Math.sin(vPsi));
}
}
/**
* This routine does the analytic integration over psi (V psi)
* using the appropriate modified Bessel funciton.
*
* This routine takes coordinates in the reference frame
* Useful for computing density quicker.
*/
public double computeReference2D(double r, double theta, double vr, double vt) {
if (Math.abs(vt) < vtLimit(vr,r)) return 0;
else {
Q = Math.sqrt((1-mu)*G*Ms/r);
V0 = Math.sqrt(vr*vr + vt*vt - 2*Q*Q);
F1 = 2*Vb*V0/(Vtemp*Vtemp) * Math.cos(theta)*(V0 - vr)*(V0 - vr) / (V0*(V0-vr)+Q*Q) -
((Vb*Vb)+(V0*V0)+2*V0*Vb*Math.cos(theta))/(Vtemp*Vtemp);
F2 = 2*V0*Vb/(Vtemp*Vtemp) * Math.sin(theta)*(V0-vr)*vt/ (V0*(V0-vr) + (Q*Q));
return sp.compute(r,theta,vr,vt) * N * test1 *
Math.exp(F1)*Bessel.i0(F2);
}
}
/**
* This tells what the limit on tangential velocity is, based on r and radial velocity
* (returns an absolute value that vt must be greater than)
*/
public double vtLimit(double vr, double r) {
double QQ = Math.sqrt((1-mu)*G*Ms/r);
double t211 = 0;
if ((t211 = 2*QQ*QQ - vr*vr)<0) return 0;
else return Math.sqrt(t211) + 0.01; // this is in m/s so we're OK with this factor
}
/**
* This takes parameters in spherical (heliospheric) coordinates
*
* Does appropriate transformation and calculates computeReferenceCoords(args)
*/
/*public double compute(double r, double theta, double phi,
double vmag, double vtheta, double vphi) {
hpr = new HelioVector(HelioVector.SPHERICAL, r, phi, theta);
hpv = new HelioVector(HelioVector.SPHERICAL, vmag, vphi, vtheta);
//hpin = new HelioVector(HelioVector.Spherical, 1, phi0, theta0); // length doesn't matter here
return computeReferenceCoords(r, hpr.angleToInflow(phi0,theta0),
hpv.cylCoordRad(hpr), hpv.cylCoordTan(hpr), hpv.cylCoordPhi(hpr,hpin));
}*/
/**
* This takes parameters in spherical (heliospheric) coordinates
*
* Does appropriate transformation and calculates computeRefernce2D()
*/
/*public double compute2D(double r, double theta, double phi,
double vmag, double vtheta) {
hpr = new HelioVector(HelioVector.SPHERICAL, r, phi, theta);
hpv = new HelioVector(HelioVector.SPHERICAL, vmag, 0, vtheta);
//hpin = new HelioVector(HelioVector.Spherical, 1, phi0, theta0); // length doesn't matter here
return computeReference2D(r, hpr.angleToInflow(phi0,theta0),
hpv.cylCoordRad(hpr), hpv.cylCoordTan(hpr));
}*/
/**
* This takes coords in a more general frame, as in compute() above
* Returns a 3D function in velocity space, with args. vr, vtheta, vphi
*
*/
public FunctionIII getVelocityDistribution(final double r, final double theta, final double phi) {
return new FunctionIII () {
public double function3(double x, double y, double z) {
return dist(r,theta,phi,x,y,z);
}
};
}
/**
* This takes coords in a more general frame, as in compute() above
* Returns a 2D function in velocity space, with args. vr, vtheta
* (we have analytically integrated the Vpsi coordinate over all angles)
*/
public FunctionII get2DVelocityDistribution(final double r, final double theta, final double phi) {
return new FunctionII () {
public double function2(double x, double y) {
return computeReference2D(r,theta,x,y);
}
};
}
/**
* This takes coords relative to inflow, as in computeRefernceCoords above
* Returns a 3D function in velocity space, with args. vr, vtheta, vphi
*
*/
public FunctionIII getReferenceVelocityDistribution(final double r, final double theta) {
return new FunctionIII () {
public double function3(double x, double y, double z) {
return computeReferenceCoords(r,theta,x,y,z);
}
};
}
/**
* This takes coords in the reference frame.
* Returns a 2D function in velocity space, with args. vr, vtheta.
* The function returned is the analytic integration of all psi (Vpsi)
*/
public FunctionII get2DReferenceVelocityDistribution(final double r, final double theta) {
return new FunctionII () {
public double function2(double x, double y) {
return computeReference2D(r,theta,x,y);
}
};
}
/**
* This returns the density at a point in the heliosphere by doing
* a numerical 3D integration in all velocity space
* See MultipleIntegration.java for details
* (default is at .001 accuracy)
*/
public double density(double r, double theta, double phi) {
MultipleIntegration mi = new MultipleIntegration();
// old fashioned way
double [] lims = new double[6];
lims[0]=-3*Math.pow(10,5);
lims[1]=3*Math.pow(10,5); // m/s
lims[2]=-3*Math.pow(10,5);
lims[3]=3*Math.pow(10,5);
lims[4]=-3*Math.pow(10,5);
lims[5]=3*Math.pow(10,5);
// do the integral over + and then - velocity space to avoid the zero
/*double [] lims = new double[6];
lims[0]=-3*Math.pow(10,5);
lims[1]=0; // m/s
lims[2]=-3*Math.pow(10,5);
lims[3]=0;
lims[4]=-3*Math.pow(10,5);
lims[5]=0;
double [] lims2 = new double[6];
lims2[0]=0;
lims2[1]=3*Math.pow(10,5);
lims2[2]=0;
lims2[3]=3*Math.pow(10,5);
lims2[4]=0;
lims2[5]=3*Math.pow(10,5);*/
return mi.integrate(getVelocityDistribution(r,theta, phi) , lims);
// + mi.integrate(getVelocityDistribution(r,theta, phi) ,lims2);
// the integration routine will give us stats on the operation.
}
/**
* This returns the density at a point in the heliosphere by doing
* a numerical 2D integration, plus the
* analytic integratoin of the PSI coordinate with modified bessel function
* See MultipleIntegration.java for details
* (default is at .001 accuracy)
*/
public double density2D (double r, double theta, double phi) {
MultipleIntegration mi = new MultipleIntegration();
double [] lims = new double[4];
lims[0]=-3*Math.pow(10,7);
lims[1]=3*Math.pow(10,7);
lims[2]=-3*Math.pow(10,7);
lims[3]=3*Math.pow(10,7);
return mi.integrate(get2DReferenceVelocityDistribution(r,theta),lims);
// the integration routine will give us stats on the operation.
}
| Java |
/**
* A "hot" neutral helium model of the LISM
* (gaussian)
*/
public class SimpleHeLISM extends InterstellarMedium {
public static double K = 1.380622 * Math.pow(10,-23); //1.380622E-23 kg/m/s/s/K
public static double Mhe = 4*1.6726231 * Math.pow(10,-27); // 4 * 1.6726231 x 10-24 gm
private double temp, vb, n, vtemp, d;
private double phi0, theta0; // direction of bulk flow - used when converting to GSE
private double norm;
private double factor;
/**
* Default parameters for default constructor
*
*/
public SimpleHeLISM() {
this(28000.0, 0.0, 0.0, 2000.0, 1.5E-7);
}
/**
* Construct an interstellar neutral helium gaussian distribution
*parameters:
* bulk velocity of VLISM
* phi0, phi angle of bulk inflow
* theta0, theta angle of bulk inflow
* temperature, T(VLISM)
* density (VLISM)
* radiationToGravityRation (mu)
* ionization at 1AU (beta0)
*/
public SimpleHeLISM (double bulkVelocity, double phi0, double theta0,
double temperature, double density) {
vb = bulkVelocity;
this.phi0 = phi0;
this.theta0 = theta0;
temp = temperature;
d = density;
factor = -Mhe/2/K/temp;
//average velocity due to heat
vtemp = Math.sqrt(-1/factor);
// don't want to compute this every time...
norm = d*Math.pow(vtemp*Math.sqrt(Math.PI),-3);
/*
// DEBUG HERE
file f = new file("test_dist.txt");
f.initWrite(false);
double minRange = -100000;
double maxRange = 100000;
int steps = 100;
double delta = (maxRange-minRange)/steps;
for (int i=0; i<steps; i++) {
f.write((minRange+i*delta)+"\t"+heliumDist((minRange+i*delta),0,0)+"\t");
f.write(heliumDist(0,(minRange+i*delta),0)+"\t");
f.write(heliumDist(0,0,(minRange+i*delta))+"\n");
}
f.closeWrite();
*/
}
/**
* Returns the phase space density of neutral helium at this velocity
*/
public double heliumDist(double vx, double vy, double vz) {
double r = Math.sqrt((vx-vb)*(vx-vb) + vy*vy + vz*vz);
return norm*Math.exp(factor*r*r);
}
/**
* For testing
*/
public static final void main(String[] args) {
SimpleHeLISM shl = new SimpleHeLISM(27000,0,0,8000,1);
}
}
/*
double temp = 2000;
double density = 1;
double vbulk = 27000;
double norm = Math.sqrt((4*MP/2/PI/KB/temp)*(4*MP/2/PI/KB/temp)*(4*MP/2/PI/KB/temp));
return norm*Math.exp(-4*MP*((v1-vbulk)*(v1-vbulk)+v2*v2+v3*v3)/2/KB/temp);
*/
| Java |
//import drasys.or.nonlinear.*;
//import gaiatools.numeric.function.Function;
import flanagan.integration.*;
/*
* Utility class for passing around functions
*
* implements the drasys "FunctionI" interface to enable Simpsons method
* outsource.
*/
public abstract class FunctionI extends Function implements IntegralFunction{
public double function(double x) {
return 0;
}
public double value(double var) {
return function(var);
}
public String toString() {
return "a string";
}
public double ddif(int x, double y) {
return 0.0;
}
public double value(double[] x) {
return 0.0;
}
}
| Java |
/**
*
* Use this to calculate the v dist. of int. helium using
* the assumption of isotropic adiabatic cooling
*
*/
public class SemiModel {
public double AU = 1.49598* Math.pow(10,11); //meters
public double NaN = Double.NaN;
public double MAX = Double.MAX_VALUE;
public double U = 440*1000;
public double N0 = Math.pow(10,-6);
public double GAMMA = 3.0/2.0; // energy dependence in eflux ?? - inverse gamma in derivation..
static double beta = 3*Math.pow(10,-8);
static double PI = Math.PI;
public Legendre l;
public int degree = 20;
public double mu_i = 1.0;
public double D = 0.00001;
public double VSW = 400000.0;
public static double v_infinity = 27500.0; //m/s
public static double G = 6.673 * Math.pow(10,-11); // m^3/s^2/kg
public static double Ms = 1.98892 * Math.pow(10,30); // kg
public MultipleIntegration mi;
public double instr_normalization;
public int counter=0;
public SemiModel() {
//mu_i = 0.985; // cos(10 degrees)
//retry with perp
mu_i = 0.1;
l = new Legendre();
mi = new MultipleIntegration();
//for (double v = 0; v<VSW*1.1; v+= VSW/100) {
// System.out.println("v: "+ v + " f: "+ f(v));
//}
FunctionI integrand = new FunctionI () {
public double function(double mu) {
return instr_function(mu);
}
};
instr_normalization = mi.integrate(integrand, -1, 1, 1000);
System.out.println("norm: " + instr_normalization);
System.out.println("predict: " + Math.sqrt(1.0/2.0/Math.PI/13.2/Math.PI*180.0));
}
public double f(double v, double mu) {
//D = d;
//GAMMA = gamma;
double tbr=0.0;
for (int i=0; i<degree; i++) {
tbr += Math.pow(v/VSW,1-GAMMA)*(2.0*i+1)/2.0*l.p(i,mu_i)*l.p(i,mu)*Math.exp(-i*(i+1.0)*D*AU/VSW*(1.0-Math.pow(v/VSW,GAMMA)));
}
tbr*=N(AU*Math.pow(v/VSW,GAMMA));
tbr*=(instr_function(Math.acos(mu))+instr_normalization)/2;
return tbr;
}
/**
* now including instrument function - april 06 - from Aelig thesis
*
*/
public double f(double v) {
final double v_ = v;
FunctionI integrand = new FunctionI () {
public double function(double mu) {
return f(v_,mu);
}
};
double integral = mi.integrate(integrand, -1.0, -0.866, 1000);
return integral;
}
public double f(double norm, double dd, double gamm, double v) {
counter++;
D = dd;
GAMMA = gamm;
return norm*v*f(v*VSW);
}
public double f(double norm, double dd, double v) {
counter++;
D=dd;
return norm*v*f(v*VSW);
}
/**
* From Aelig thesis.. angular calibration..
*/
public double instr_function(double mu) {
double sigma = 13.2*Math.PI/180.0;
double factorAlph = Math.exp(-mu*mu/2.0/sigma/sigma);
return factorAlph; //(factorAlph+1.0d)/2.0d;
}
/**
* The model of interstellar neutral density..
*
* based on cold model, due upwind..
* see Moebius SW&CR homework set #4!
*/
private double N(double r) {
return N0*Math.exp(-beta*AU*AU*Math.sqrt(v_infinity*v_infinity+2.0*G*Ms/r)/G/Ms);
//return N0*Math.exp(-2*beta*AU*AU/r/v_infinity);
}
public static final void main(String[] args) {
SemiModel sm = new SemiModel();
double[] test = new double[20];
double[] test1 = new double[20];
double[] test2 = new double[20];
double[] test3 = new double[20];
double[] test4 = new double[20];
double[] test5 = new double[20];
double[] test6 = new double[20];
double[] dd = {0.0,0.0,0.0,0.0,0.0,0.0}; //4.38e-6,4.6e-6,4.0e-6,3.1e-6,2.6e-6,1.9e-6};
double ddtemp = 4.0e-6;
double[] nn = {1.0,1.0,1.0,1.0,1.0,1.0}; //3.01e12,2.1e11,2.2e11,2.6e11,3.2e11,5.5e11};
double nntemp = 2e11;
double[] gamma = {0.8d, 1.0d, 1.3d, 1.4d, 1.5d, 2.0d};
file f = new file("semi_out_test.dat");
f.initWrite(false);
int index = 0;
for (double w=0.0; w<=1.0; w+=0.02) {
index=0;
f.write(w+"\t");
while (index<6) {
f.write(sm.f(nn[index],dd[index],gamma[index],w)+"\t");
index++;
}
f.write("\n");
}
f.closeWrite();
}
}
| Java |
import java.util.StringTokenizer;
/**
* Adapted for heliosphere display
*
*/
public class MCAJ_image {
public static double AU = 1.49598* Math.pow(10,11); //meters
public MCAJ_image(String filename) {
file f = new file(filename);
int num2 = 101;
double[] xArray = new double[num2];
double[] yArray = new double[num2];
int in = 0;
for (double pos = -5.0; pos<5.0; pos+=10.0/((double)num2)) {
xArray[in]=pos;
yArray[in]=pos;
in++;
System.out.println("pos: " + pos + " next in: " + in);
}
double[] zArray = new double[num2*num2];
for (int i=0; i<zArray.length; i++) zArray[i]=0;
f.initRead();
String line = f.readLine(); // garbage - header
int index = 0;
while ((line=f.readLine())!=null) {
double x=0;
double y=0;
double num=0;
StringTokenizer st = new StringTokenizer(line);
try {
x = Double.parseDouble(st.nextToken());
y = Double.parseDouble(st.nextToken());
String numS = st.nextToken();
//if (numS.equals("Infinity")) numS="0.001";
num = Double.parseDouble(numS);
if (num==0.0) num = 0.001;
//num = num+1.0;
//num = Math.log(num);
}
catch (Exception e) {e.printStackTrace();}
zArray[index]=num;
index++;
}
System.out.println("index: " + index + " zArray.length: " + zArray.length);
// get min and max of zarray
double minz = 1000.0;
double maxz = 0.0;
for (int j=0; j<zArray.length; j++) {
if (zArray[j]>maxz) maxz=zArray[j];
if (zArray[j]<minz) minz=zArray[j];
}
System.out.println("minz: "+minz+" maxz: "+maxz);
/* int index = 0;
for (int i=0; i<x.length; i++) {
x[i]=(tpTimes[i]-GOODS)/24.0/60.0/60.0;
for (int j=0; j<y.length; j++) {
y[j]=tpHist[i].label[j];
if (tpHist[i].data[j]==0) z[index]=0.0;
else {
z[index]=tpHist[i].data[j];
//o("nonzero z: " + z[index]);
}
index++;
}
}*/
JColorGraph jcg = new JColorGraph(xArray,yArray,zArray,true);
String unitString = "Density";
//if (histType == "Flux") unitString = "Diff. Flux (1/cm^2/s/sr/keV)";
//if (histType == "Distribution Function") unitString = "Dist. Function (s^3/km^6)";
//if (histType == "Log Distribution Function") unitString = "log Dist. Function (s^3/km^6)";
jcg.setLabels("Heliosphere Simulation","UniBern 2008",unitString);
jcg.run();
jcg.showIt();
}
public static final void main(String[] args) {
MCAJ_image m = new MCAJ_image(args[0]);
}
}
| Java |
import java.util.Date;
import java.lang.Math;
public class NTest {
public static void main(String[] args) {
Date d1 = new Date();
//NeutralDistribution nd = new NeutralDistribution( 12, 123, 142);
double AU = 15 * 10^13; // m
SimpleNeutralDistribution snd = new SimpleNeutralDistribution(
25000, 0, 0, 10000, 7*Math.pow(10,-6), 0, 6.8*Math.pow(10,-8));
double q = snd.N(AU, 135*Math.PI/180, 25000);
System.out.println(q+"");
/*double[] array;
array = new double[100000];
for (int i = 1; i<100000; i++) {
array[i] = i;
// double test = nd.distributionFunction(123123, .21, 100+i, 421, .13);
}*/
Date d2 = new Date();
System.out.println(d2.getTime() - d1.getTime()+"");
}
}
| Java |
import SimpleInput;
import SimpleOutput;
public class primeSieve {
// This program implements the Sieve of Eratosthenes
public static void main (String args []) {
// declare basic objects
SimpleInput in = new SimpleInput();
SimpleOutput out = new SimpleOutput();
int M; // size of sieve
int i, number; // indices
// Determine size of sieve
out.println ("Use of the Sieve of Eratosthenes to compute primes");
out.println ("Enter how large an integer to process: ");
M = in.readInt();
// set up sieve
boolean [] crossedOut = new boolean [M+1];
// use size M+1 for elemens 0 through M
for (i = 0; i<= M; i++) // i++ is an abbreviation for i = i + 1
crossedOut[i] = false;
// follow cross-out process
for (number = 2; number < M; number++)
{if (!crossedOut[number])
{ // cross out multiples of number
i = 2*number;
while (i <= M)
{ crossedOut[i] = true;
i = i + number;
}
}
}
// print list of primes
out.println ("The following prime numbers have been found");
int numberOnLine = 0;
for (i = 2; i <= M; i++)
{if (!crossedOut[i])
{
out.print(i + "\t"); // add tab after each number
numberOnLine++;
if (numberOnLine == 8)
{
out.println(); // start a new line every 8 numbers
numberOnLine = 0;
}
}
}
out.println();
}
}
| Java |
import java.util.Date;
import java.util.Random;
public class MCThread extends Thread {
public boolean finished = false;
private double[] limits;
private int np;
private final FunctionIII f;
public double tbr;
private Random r;
private double w1,w2,w3;
public MCThread(FunctionIII funk, double[] lims, int num) {
limits = lims;
w1 = limits[1]-limits[0];
w2 = limits[3]-limits[2];
w3 = limits[5]-limits[4];
np = num;
f = funk; // do you feel it
tbr = 0;
r = new Random();
}
/**
* Just call the function a certain number of times and add the results together
* this is the dartboard
*/
public void run() {
tbr = 0.0;
double xpoint,ypoint,zpoint;
// System.out.println("widths: " + w1 + " " + w2 + " " + w3);
for (int i=0; i<np; i++) {
// select random point
xpoint = r.nextDouble()*w1 + limits[0];
ypoint = r.nextDouble()*w2 + limits[2];
zpoint = r.nextDouble()*w3 + limits[4];
tbr += f.function3(xpoint,ypoint,zpoint);
}
finished = true;
}
/**
* For testing - use GVLISM
*/
public static final void main(String[] args) {
MultipleIntegration mi = new MultipleIntegration();
final GaussianVLISM gvli = new GaussianVLISM(new HelioVector(HelioVector.CARTESIAN,
-27000.0,0.0,0.0), 100.0, 6000.0);
System.out.println("Created GVLISM" );
FunctionIII distZw = new FunctionIII () {
public double function3(double r, double p, double t) {
HelioVector hv = new HelioVector(HelioVector.SPHERICAL,r,p,t);
return gvli.heliumDist(hv)*r*r*Math.sin(t);
}
};
double[] limitsZw = {0.0,100000.0,0.0,2*Math.PI,0,Math.PI};
Date d1 = new Date();
double ans = mi.mcIntegrate(distZw, limitsZw,5000000);
Date d2 = new Date();
o("5000000 answer: " + ans + " Time: " + (d2.getTime() - d1.getTime()));
d1 = new Date();
ans = mi.mcIntegrate(distZw, limitsZw,5000000,1);
d2 = new Date();
o("5000000,1 answer: " + ans + " Time: " + (d2.getTime() - d1.getTime()));
d1 = new Date();
ans = mi.mcIntegrate(distZw, limitsZw,5000000,2);
d2 = new Date();
o("5000000,2 answer: " + ans + " Time: " + (d2.getTime() - d1.getTime()));
d1 = new Date();
ans = mi.mcIntegrate(distZw, limitsZw,5000000,3);
d2 = new Date();
o("5000000,3 answer: " + ans + " Time: " + (d2.getTime() - d1.getTime()));
System.out.println("answer in spherical coords = " + ans );
}
public static void o(String s) {
System.out.println(s);
}
} | Java |
import java.util.StringTokenizer;
public class IbexFitter {
public CurveFitter cf;
public IBEXLO_09fit ifit;
public IbexFitter() {
file f = new file("first_pass.txt");
int numLines = 926;
numLines=numLines/3;
f.initRead();
double[] x = new double[numLines];
double[] y = new double[numLines];
String line = "";
for (int i=0; i<numLines; i++) {
line = f.readLine();
StringTokenizer st = new StringTokenizer(line);
x[i]=Double.parseDouble(st.nextToken());
//x[i]-=1.0; // IMPORTANT _ SHIFT BY 1.0 TO MOVE TO HELIOCENTRIC FRAME!!
y[i]=Double.parseDouble(st.nextToken());
//System.out.println("row: " + i + " x: " + x[i] + " y: " + y[i]);
line = f.readLine();
line = f.readLine();
}
f.closeRead();
// loop through parameters here
// standard params:
double lamda = 74.7;
double v = 26000.0;
int res = 2;
double lamdaWidth = 15;
double vWidth = 10000;
double lamdaMin = 65.0;
double vMin=21000.0;
double lamdaDelta = lamdaWidth/res;
double vDelta = vWidth/res;
lamda = lamdaMin;
v = vMin;
file outF = new file("testOut.txt");
outF.initWrite(false);
for (int i=0; i<res; i++) {
for (int j=0; j<res; j++) {
System.out.println("starting doFit routine with i=" + i + " j= " + j);
cf = new CurveFitter(x,y,lamda,v);
cf.doFit(CurveFitter.IBEX1);
outF.write(lamda+"\t"+v+"\t");
outF.write(cf.minimum_pub+"\t");
outF.write(cf.bestParams[0]+"\n");
// get values of y and z at minimum
//double[] param = min.getParamValues();
//bestParams = param;
v+=vDelta;
}
lamda+=lamdaDelta;
}
outF.closeWrite();
}
public static final void main(String[] args) {
IbexFitter theMain = new IbexFitter();
}
} | Java |
import java.util.StringTokenizer;
public class TwoDPlot {
public CurveFitter cf;
public TwoDPlot() {
file f = new file("second_pass_ascii.txt");
f.initRead();
double[] x = new double[30];
double[] y = new double[30];
double[] z = new double[900];
for (int i=0; i<x.length; i++) x[i]=Double.parseDouble(f.readLine());
for (int i=0; i<y.length; i++) y[i]=Double.parseDouble(f.readLine());
for (int i=0; i<z.length; i++) z[i]=Double.parseDouble(f.readLine());
JColorGraph jcg = new JColorGraph(x,y,z);
String unitString = "log (sum square model error)";
jcg.setLabels("IBEX-LO","2010",unitString);
jcg.run();
jcg.showIt();
}
public static boolean contains(double[] set, double test) {
for (int i=0; i<set.length; i++) {
if (set[i]==test) return true;
}
return false;
}
public static void o(String s) {
System.out.println(s);
}
public static final void main(String[] args) {
TwoDPlot theMain = new TwoDPlot();
}
} | Java |
import java.util.StringTokenizer;
/**
* Simulating response at IBEX_LO with this class
*
* Create interstellar medium and perform integration
*
*/
public class IBEXLO_09fit {
public int mcN = 100000; // number of iterations per 3D integral
public String outFileName = "lo_fit_09.txt";
public static final double EV = 1.60218 * Math.pow(10, -19);
public static double MP = 1.672621*Math.pow(10.0,-27.0);
public static double AU = 1.49598* Math.pow(10,11); //meters
public static double EARTHSPEED = AU*2.0*3.14/365.0/24.0/3600.0;
// define angles and energies of the instrument here
// H mode (standard) energy bins in eV
public double[] minEnergies = {8.8, 17.6, 35.8, 74.2, 153.5, 330.6, 663.3, 1298.6};
public double[] maxEnergies = {23.2, 46.4, 94.3, 195.8, 404.6, 871.5, 1748.7, 3423.5};
public double[] minSpeedsHe, maxSpeedsHe, minSpeedsO, maxSpeedsO;
// Interstellar mode energies
// { spring min, spring max, fall min, fall max }
public double[] heEnergies = { 73.7, 194.3, 4.4, 11.6 };
public double[] oEnergies = {293.7, 774.3, 18.15, 47.9 };
public double[] heSpeeds;
public double[] oSpeeds;
// O mode efficiencies
// public double heSpringEff = 1.0*Math.pow(10,-7); // this was the original.. now going to adjust to match data including sputtering etc.
public double heSpringEff = 1.0*Math.pow(10,-7)/7.8; // nominal efficiency to "roughly" match data..
public double heFallEff = 1.6*Math.pow(10,-6);
public double oSpringEff = 0.004;
public double oFallEff = 0.001;
// angular acceptance - assume rectangular windows..
// these are half widths, e.g. +- for acceptance
public double spinWidth = 4.0*Math.PI/180.0;
public double hrWidth = 3.5*Math.PI/180.0;
public double lrWidth = 10.0*Math.PI/180.0;
public double eightDays = 8.0*24.0*60.0*60.0;
public double oneHour = 3600.0;
public double upWind = 74.0 * 3.14 / 180.0;
public double downWind = 254.0 * 3.14 / 180.0;
public double startPerp = 180*3.14/180; // SPRING
public double endPerp = 240*3.14/180; // SPRING
//public double startPerp = 260.0*3.14/180.0; // FALL
//public double endPerp = 340.0*3.14/180.0; // FALL
public double he_ion_rate = 6.00*Math.pow(10,-8);
public GaussianVLISM gv1;
// temporarily make them very small
//public double spinWidth = 0.5*Math.PI/180.0;
//public double hrWidth = 0.5*Math.PI/180.0;
//public double lrWidth = 0.5*Math.PI/180.0;
public double activeArea = 100.0/100.0/100.0; // 100 cm^2 in square meters now!!
public file outF;
public MultipleIntegration mi;
public NeutralDistribution ndHe;
public double look_offset=Math.PI;
public double currentLongitude, currentSpeed, currentDens, currentTemp;
public HelioVector bulkHE;
/**
*
*
*
*/
public IBEXLO_09fit() {
// calculate speed ranges with v = sqrt(2E/m)
heSpeeds = new double[heEnergies.length];
oSpeeds = new double[oEnergies.length];
o("calculating speed range");
for (int i=0; i<4; i++) {
heSpeeds[i]=Math.sqrt(2.0*heEnergies[i]/4.0/MP*EV);
oSpeeds[i]=Math.sqrt(2.0*oEnergies[i]/16.0/MP*EV);
System.out.println(heEnergies[i] +" = " + heSpeeds[i] + " , " + oEnergies[i] + " = " + oSpeeds[i]);
}
minSpeedsHe = new double[8];
maxSpeedsHe = new double[8];
minSpeedsO = new double[8];
maxSpeedsO = new double[8];
for (int i=0; i<8; i++) {
minSpeedsHe[i]=Math.sqrt(2.0*minEnergies[i]/4.0/MP*EV);
maxSpeedsHe[i]=Math.sqrt(2.0*maxEnergies[i]/4.0/MP*EV);
minSpeedsO[i]=Math.sqrt(2.0*minEnergies[i]/16.0/MP*EV);
maxSpeedsO[i]=Math.sqrt(2.0*maxEnergies[i]/16.0/MP*EV);
System.out.println(minSpeedsHe[i] +" = " + maxSpeedsHe[i] + " , " + minSpeedsO[i] + " = " + maxSpeedsO[i]);
}
System.out.println(minSpeedsHe[0] + "\t" + maxSpeedsHe[0] +"\t" + heSpeeds[2] + "\t" + heSpeeds[3]);
// BUILD INTERSTERLLAR MEDIUM - helium and oxygen here, primary and secondary oxygen..
//
bulkHE = new HelioVector(HelioVector.SPHERICAL, 26000.0, (74.68)*Math.PI/180.0, 95.5*Math.PI/180.0);
//HelioVector bulkO1 = new HelioVector(HelioVector.SPHERICAL,26000.0, (74+180)*Math.PI/180.0, 95.5*Math.PI/180);
GaussianVLISM gv1 = new GaussianVLISM(bulkHE,0.015*100.0*100.0*100.0,6000.0);
//KappaVLISM gv3 = new KappaVLISM(bulkO1, 0.00005*100*100*100, 6300, 1.6);
ndHe = new NeutralDistribution(gv1, 0.0, he_ion_rate); // mu is 0.0 for he
ndHe.debug=false;
currentLongitude = 74.68;
currentSpeed = 26000.0;
currentDens = 0.015;
currentTemp = 6000.0;
// DONE CREATING MEDIUM
o("earthspeed: " + EARTHSPEED);
mi = new MultipleIntegration();
o("done creating IBEXLO_09 object");
// DONE SETUP
//-
//-
// now lets run the test, see how this is doing
/*
// moving curve fitting routine here for exhaustive and to make scan plots
file ouf = new file("scanResults1.txt");
file f = new file("cleaned_ibex_data.txt");
int numLines = 413;
f.initRead();
double[] x = new double[numLines];
double[] y = new double[numLines];
String line = "";
for (int i=0; i<numLines; i++) {
line = f.readLine();
StringTokenizer st = new StringTokenizer(line);
x[i]=Double.parseDouble(st.nextToken());
//x[i]-=1.0; // IMPORTANT _ SHIFT BY 1.0 TO MOVE TO HELIOCENTRIC FRAME!!
y[i]=Double.parseDouble(st.nextToken());
//System.out.println("row: " + i + " x: " + x[i] + " y: " + y[i]);
}
f.closeRead();
// first scan: V vs Long.
// for (int i=0; i<
*/
// LOAD THE REAL DATA
/* file df = new file("second_pass.txt");
int numLines2 = 918;
df.initRead();
double[] xD = new double[numLines2];
double[] yD = new double[numLines2];
String line = "";
for (int i=0; i<numLines2; i++) {
line = df.readLine();
StringTokenizer st = new StringTokenizer(line);
xD[i]=Double.parseDouble(st.nextToken());
//x[i]-=1.0; // IMPORTANT _ SHIFT BY 1.0 TO MOVE TO HELIOCENTRIC FRAME!!
yD[i]=Double.parseDouble(st.nextToken());
System.out.println("row: " + i + " x: " + xD[i] + " y: " + yD[i]);
//line = f.readLine();
//line = f.readLine();
}
df.closeRead();
// END LOADING REAL DATA
*/
// MAKE SPIN PHASE SIMULATION
file spFile = new file("spin_phase_sim.txt");
spFile.initWrite();
for (int tt = 0; tt<360; tt++) {
// tt is the theta angle
double ans = getRate(40.0, tt*Math.PI/360.0);
spFile. write(tt+"\t"+ans+"\n");
}
spFile.closeWrite();
/*
// MAKE SIMULATION FROM REAL DATA.. STEP WITH TIME AND PARAMS FOR MAKING 2D PARAM PLOT
// loop through parameters here
// standard params:
double lamda = 74.7;
//double temp = 6000.0;
double v = 26000.0;
int res = 30;
double lamdaWidth = 20;
//double tWidth = 10000;
double vWidth = 10000;
double lamdaMin = 65.0;
//double tMin = 1000.0;
double vMin=21000.0;
double lamdaDelta = lamdaWidth/res;
//double tDelta = tWidth/res;
double vDelta = vWidth/res;
lamda = lamdaMin;
//temp=tMin;
v = vMin;
//file outF = new file("testVL_pass2_Out.txt");
//outF.initWrite(false);
for (int i=0; i<res; i++) {
v=vMin;
for (int j=0; j<res; j++) {
file outf = new file("fitP2_vl"+lamda+"_"+v+".txt");
outf.initWrite(false);
setParams(lamda,v,0.015,6000.0);
System.out.println(" now calc for: fitTTT_"+lamda+"_"+v+".txt");
double [] doyD = new double[110];
double [] rateD = new double[110];
in doyIndex = 0;
for (double doy=10.0 ; doy<65.0 ; doy+=0.5) {
outf.write(doy+"\t");
doyD[doyIndex]=doy;
doyIndex++;
//for (double off = 0.0 ; off<=3.0*Math.PI/2.0; off+=Math.PI/2.0) {
//look_offset=off;
look_offset=3.0*Math.PI/2.0;
double rr = getRate(doy);
System.out.println("trying: " + doy + " got "+rr);
outf.write(rr +"\t");
//}
//double rr = getRate(doy);
//System.out.println("trying: " + doy + " got "+rr);
outf.write("\n");
}
outf.closeWrite();
v+=vDelta;
}
//temp+=tDelta;
lamda+=lamdaDelta;
}
//outF.closeWrite();
*/
/*
for (int temptemp = 1000; temptemp<20000; temptemp+=2000) {
file outf = new file("fitB_"+temptemp+"_7468_26000.txt");
outf.initWrite(false);
setParams(74.68,26000,0.015,(double)temptemp);
for (double doy=10.0 ; doy<65.0 ; doy+=0.1) {
outf.write(doy+"\t");
//for (double off = 0.0 ; off<=3.0*Math.PI/2.0; off+=Math.PI/2.0) {
//look_offset=off;
look_offset=3.0*Math.PI/2.0;
double rr = getRate(doy);
System.out.println("trying: " + doy + " got "+rr);
outf.write(rr +"\t");
//}
//double rr = getRate(doy);
//System.out.println("trying: " + doy + " got "+rr);
outf.write("\n");
}
outf.closeWrite();
}
*/
}
// END CONSTRUCTOR
public void setParams(double longitude, double speed, double dens, double temp) {
currentLongitude = longitude;
currentSpeed = speed;
currentDens = dens;
currentTemp = temp;
// BUILD INTERSTERLLAR MEDIUM - helium and oxygen here, primary and secondary oxygen..
//
bulkHE = new HelioVector(HelioVector.SPHERICAL, speed, longitude*Math.PI/180.0, 95.5*Math.PI/180.0);
//HelioVector bulkO1 = new HelioVector(HelioVector.SPHERICAL,26000.0, (74+180)*Math.PI/180.0, 95.5*Math.PI/180);
GaussianVLISM gv1 = new GaussianVLISM(bulkHE,dens*100.0*100.0*100.0,temp);
//KappaVLISM gv3 = new KappaVLISM(bulkO1, 0.00005*100*100*100, 6300, 1.6);
ndHe = new NeutralDistribution(gv1, 0.0, he_ion_rate); // mu is 0.0 for he
ndHe.debug=false;
// DONE CREATING MEDIUM
}
public void setParams(double dens) {
currentDens = dens;
// BUILD INTERSTERLLAR MEDIUM - helium and oxygen here, primary and secondary oxygen..
//
//HelioVector bulkHE = new HelioVector(HelioVector.SPHERICAL, currentSpeed, currentLongitude*Math.PI/180.0, 95.5*Math.PI/180.0);
//HelioVector bulkO1 = new HelioVector(HelioVector.SPHERICAL,26000.0, (74+180)*Math.PI/180.0, 95.5*Math.PI/180);
GaussianVLISM gv1 = new GaussianVLISM(bulkHE,dens*100.0*100.0*100.0,currentTemp);
//KappaVLISM gv3 = new KappaVLISM(bulkO1, 0.00005*100*100*100, 6300, 1.6);
ndHe = new NeutralDistribution(gv1, 0.0, he_ion_rate); // mu is 0.0 for he
ndHe.debug=false;
// DONE CREATING MEDIUM
}
public void setParams(double dens, double temp) {
currentDens = dens;
currentTemp = temp;
// BUILD INTERSTERLLAR MEDIUM - helium and oxygen here, primary and secondary oxygen..
//
//HelioVector bulkHE = new HelioVector(HelioVector.SPHERICAL, currentSpeed, currentLongitude*Math.PI/180.0, 95.5*Math.PI/180.0);
//HelioVector bulkO1 = new HelioVector(HelioVector.SPHERICAL,26000.0, (74+180)*Math.PI/180.0, 95.5*Math.PI/180);
GaussianVLISM gv1 = new GaussianVLISM(bulkHE,dens*100.0*100.0*100.0,temp);
//KappaVLISM gv3 = new KappaVLISM(bulkO1, 0.00005*100*100*100, 6300, 1.6);
ndHe = new NeutralDistribution(gv1, 0.0, he_ion_rate); // mu is 0.0 for he
ndHe.debug=false;
// DONE CREATING MEDIUM
}
public void setParamsN(double dens, double ion) {
currentDens = dens;
currentTemp = temp;
// BUILD INTERSTERLLAR MEDIUM - helium and oxygen here, primary and secondary oxygen..
//
//HelioVector bulkHE = new HelioVector(HelioVector.SPHERICAL, currentSpeed, currentLongitude*Math.PI/180.0, 95.5*Math.PI/180.0);
//HelioVector bulkO1 = new HelioVector(HelioVector.SPHERICAL,26000.0, (74+180)*Math.PI/180.0, 95.5*Math.PI/180);
GaussianVLISM gv1 = new GaussianVLISM(bulkHE,dens*100.0*100.0*100.0,temp);
//KappaVLISM gv3 = new KappaVLISM(bulkO1, 0.00005*100*100*100, 6300, 1.6);
ndHe = new NeutralDistribution(gv1, 0.0, he_ion_rate); // mu is 0.0 for he
ndHe.debug=false;
// DONE CREATING MEDIUM
}
public double getRate(double dens, double doy) {
if ((currentDens!=dens)) {
System.out.println("new params: " + dens);
setParams(dens);
}
return getRate(doy);
}
public double getRate(double dens, double temp, double doy) {
if ((currentDens!=dens)|(currentTemp!=temp)) {
System.out.println("new params: " + dens + " " + temp);
setParams(dens,temp);
}
return getRate(doy);
}
public double getRate(double longitude, double speed, double dens, double temp, double doy) {
if ((currentLongitude!=longitude)|(currentSpeed!=speed)|(currentDens!=dens)|(currentTemp!=temp)) {
System.out.println("new params: " + longitude + " " + speed + " " + dens + " " + temp);
setParams(longitude,speed,dens,temp);
}
return getRate(doy);
}
/* use this to set the look direction in latitude */
double midThe = Math.PI/2.0;
/**
* Use this one to set the look direction in spin phase and then get the rate
*
*/
public double getRate(double doy, double theta) {
midThe = theta;
getRate(doy);
}
/**
* We want to call this from an optimization routine..
*
*/
public double getRate(double doy) {
// spacecraft position .. assume at earth at doy
//double pos = ((doy-80.0)/365.0);
double pos = (doy-265.0)*(360.0/365.0)*Math.PI/180.0;// - Math.PI;
// set look direction
double midPhi = 0.0;
midThe = Math.PI/2.0;
double appogee = 0;
// SET LOOK DIRECTION
// THIS SET IS FOR FIRST PASS
/*if (doy>10 && doy<15.5) {
//orbit 13
appogee = 13.1;
}
else if (doy>15.5 && doy<24.1) {
//orbit 14
appogee = 20.5;
}
else if (doy>24.1 && doy<32.0) {
//orbit 15
appogee = 28.1;
}
else if (doy>32.0 && doy<39.7) {
//orbit 16
appogee = 35.8;
}
else if (doy>39.7 && doy<47.5) {
//orbit 17
appogee = 43.2;
}
else if (doy>47.5 && doy<55.2) {
//orbit 18
appogee = 51.3;
}
else if (doy>55.2 && doy<62.6) {
//orbit 19
appogee = 58.8;
}
else if (doy>62.6 && doy<70.2) {
//orbit 20
appogee = 66.4;
}*/
// SECOND PASS
if (doy>10.5 && doy<18.0) {
//orbit 13
appogee = 14.0;
}
else if (doy>18.0 && doy<25.6) {
//orbit 14
appogee = 21.6;
}
else if (doy>25.6 && doy<33.3) {
//orbit 15
appogee = 29.25;
}
else if (doy>33.3 && doy<40.85) {
//orbit 16
appogee = 36.8;
}
else if (doy>40.85 && doy<48.85) {
//orbit 17
appogee = 44.6;
}
else if (doy>48.85 && doy<56.4) {
//orbit 18
appogee = 52.4;
}
else if (doy>56.4 && doy<64.0) {
//orbit 19
appogee = 60.0;
}
else if (doy>64.0 && doy<71.6) {
//orbit 20
appogee = 67.6;
}
//orbit 21 - apogee= 73.9
//orbit 22 - apogee = 81.8
else {
appogee=doy;
}
//doy = doy-183.0;
//appogee = appogee-183.0;
double he_ans_lr;
midPhi = (appogee-3.0-265.0)*360.0/365.0*Math.PI/180.0 + look_offset;
final double lookPhi = midPhi;
// centered at look diretion.. convert doy+10 (dec 21-jan1) to angle
//midPhi = (appogee+3.0-80.0)*360.0/365.0*Math.PI/180.0 + Math.PI/2;
//midPhi = midPhi;
// here's the now position
final HelioVector posVec = new HelioVector(HelioVector.SPHERICAL, 1*AU, pos, Math.PI/2.0);
final HelioVector scVelVec = new HelioVector(HelioVector.SPHERICAL, EARTHSPEED, pos+Math.PI/2.0, Math.PI/2.0);
// placeholder for zero
//final HelioVector scVelVec = new HelioVector(HelioVector.SPHERICAL, 0.0, pos+Math.PI/2.0, Math.PI/2.0);
FunctionIII he_func = new FunctionIII() { // helium neutral distribution
public double function3(double v, double p, double t) {
double tbr = activeArea*ndHe.dist(posVec, new HelioVector(HelioVector.SPHERICAL,v,p,t).sum(scVelVec) )*v*v*Math.sin(t)*v; // extra v for flux
tbr *= angleResponse(lookPhi,p);
// that is the integrand of our v-space integration
return tbr;
}
};
// set limits for integration - spring only here
//double[] he_lr_lims = { minSpeedsHe[0], maxSpeedsHe[0], midPhi-lrWidth, midPhi+lrWidth, midThe-lrWidth-spinWidth, midThe+lrWidth+spinWidth };
// old limits for including all spin..
double[] he_lr_lims = { minSpeedsHe[1], maxSpeedsHe[7], midPhi-lrWidth, midPhi+lrWidth, 3.0*Math.PI/8.0, 5.0*Math.PI/8.0 };
// new limits for including just a single point in spin phase
double[] he_lr_lims = { minSpeedsHe[1], maxSpeedsHe[7], midPhi-lrWidth, midPhi+lrWidth, midThe-lrWidth, midThe+lrWidth };
he_lr_lims[0]=minSpeedsHe[3]; he_lr_lims[1]=maxSpeedsHe[5]; //, midPhi-lrWidth, midPhi+lrWidth, midThe-lrWidth-spinWidth, midThe+lrWidth+spinWidth };
//PERFORM INTEGRATION
he_ans_lr = 12.0*oneHour *1.0/8.0 *1.0 * mi.mcIntegrate(he_func, he_lr_lims, mcN);
he_ans_lr*=heSpringEff;
return he_ans_lr;
}
public double sigma=6.1;
public double angleResponse(double centerA, double checkA) {
double cA = centerA*180.0/Math.PI;
double chA = checkA*180.0/Math.PI;
double tbr = Math.exp(-(cA-chA)*(cA-chA)/sigma/sigma);
return tbr;
}
public static final void main(String[] args) {
IBEXLO_09fit il = new IBEXLO_09fit();
}
public static void o(String s) {
System.out.println(s);
}
/*
* This is to load a given model from a file and give a proper normalization to match the ibex data
* for using a one parameter (normalization) fit.
*/
public class FitData {
public StringTokenizer st;
public double[] days;
public double[] rates;
public Vector daysV;
public Vector ratesV;
public FitData(String filename) {
daysV = new Vector();
ratesV = new Vector();
file f = new file(filename);
f.initRead();
String line = "";
while ((line=f.readLine())!=null) {
st = new StringTokenizer(line);
daysV.add(st.nextToken());
ratesV.add(st.nextToken());
}
// time to fix the arrays
days = new double[daysV.size()];
rates = new double[daysV.size()];
for (int i=0; i<days.length; i++) {
days[i]=Double.parseDouble((String)daysV.elementAt(i));
rates[i]=Double.parseDouble((String)ratesV.elementAt(i));
}
}
// we are going to interpolate here
public double getRate(double day) {
for (int i=0; i<days.length; i++) {
if (day<days[i]) { // this is where we want to be
return (rates[i]+rates[i+1])/2;
}
}
return 0;
}
}
}
/*
We need to keep track of Earth's Vernal Equinox
and use J2000 Ecliptic Coordinates!!!
March
2009 20 11:44
2010 20 17:32
2011 20 23:21
2012 20 05:14
2013 20 11:02
2014 20 16:57
2015 20 22:45
2016 20 04:30
2017 20 10:28
This gives the location of the current epoch zero ecliptic longitude..
However
/*
/*
Earth peri and aphelion
perihelion aphelion
2007 January 3 20:00 July 7 00:00
2008 January 3 00:00 July 4 08:00
2009 January 4 15:00 July 4 02:00
2010 January 3 00:00 July 6 12:00
2011 January 3 19:00 July 4 15:00
2012 January 5 01:00 July 5 04:00
2013 January 2 05:00 July 5 15:00
2014 January 4 12:00 July 4 00:00
2015 January 4 07:00 July 6 20:00
2016 January 2 23:00 July 4 16:00
2017 January 4 14:00 July 3 20:00
2018 January 3 06:00 July 6 17:00
2019 January 3 05:00 July 4 22:00
2020 January 5 08:00 July 4 12:00
*/ | Java |
import java.lang.Math;
import java.util.Date;
import gaiatools.numeric.integration.Simpson;
//import drasys.or.nonlinear.*; // our friend mr. simpson resides here
/**
* This class should take care of doing multi-dimensional numeric integrations.
* This will be slow!!
*
* Actually not half bad...
*
*
* Lukas Saul
* UNH Physics
* May, 2001
*
* Updated Aug. 2003 - only works with 2D integrals for now...
*
* Updated Aug. 2004 - 3D integrals OK! Did that really take 1 year??
*
* About 2.1 seconds to integrate e^(-x^2-y^2-z^2) !!
*/
public class MultipleIntegration {
private double result;
private Simpson s; // tool to do integrations
/**
* for testing - increments at every 1D integration performed
*/
public long counter, counter2;
/**
* Constructor just sets up the 1D integration routine for running
* after which all integrations may be called.
*/
public MultipleIntegration() {
counter = 0;
counter2 = 0;
result = 0.0;
s=new Simpson();
s.setErrMax(0.001);
// s.setMaxIterations(15);
}
/**
* sets counter to zero
*/
public void reset() {
counter = 0;
}
public void reset2() {
counter2 = 0;
}
/**
* Set accuracy of integration
*/
public void setEpsilon(double d) {
s.setErrMax(d);
}
/**
* Here's the goods, for 3D integrations.
*
* Limits are in order as folows: zlow, zhigh, ylow, yhigh, xlow, xhigh
*
*/
public double integrate(final FunctionIII f, final double[] limits) {
reset();
System.out.println("Called 3D integrator");
System.out.println("Integrating from: \n"+limits[0]+" "+limits[1]+
"\n"+limits[2]+" "+limits[3]+"\n"+limits[4]+" "+limits[5]);
double[] nextLims = new double[4];
for (int i=0; i<4; i++) {
nextLims[i] = limits[i+2];
}
final double[] nextLimits = nextLims;
FunctionI funcII = new FunctionI () {
public double function(double x) {
return integrate(f.getFunctionII(2,x), nextLimits);
}
};
try {
s.setInterval(limits[0],limits[1]);
result=s.getResult(funcII);
//result = integrate(funcII, limits[0], limits[1]);
return result;
// each call to funcII by the integrator does a double integration
}
catch(Exception e) {
e.printStackTrace();
return 0.0;
}
}
/**
* Here's the goods, for 2D integrations
*/
public double integrate(final FunctionII f, final double[] limits) {
//System.out.println("called 2D integrator");
//System.out.println("Integrating from: \n"+limits[0]+" "+limits[1]+
// "\n"+limits[2]+" "+limits[3]);
//reset2();
//if (limits.length!=4) return null;
//System.out.println("called 2D integrator");
FunctionI f1 = new FunctionI() {
public double function(double x) {
return integrate(f.getFunction(1,x),limits[2],limits[3]);
}
};
try{
s.setInterval(limits[0],limits[1]);
result=s.getResult(f1);
//result = integrate(f1, limits[0], limits[1]);
//System.out.println("in2d - result: " + result + " " + counter);
return result;
// each call to f1 by the intgrator does an integration
}
catch (Exception e) {
e.printStackTrace();
return 0.0;
}
}
/**
* Here's the simple goods, for 1D integrations
* courtesy of our friends at drasys.or.nonlinear
*/
public double integrate(final FunctionI f, double lowLimit, double highLimit) {
//System.out.println("Called 1D integrator");
try {
counter2++;
counter++;
if (counter%10000==1) System.out.println("Counter: " + counter);
s.setInterval(lowLimit,highLimit);
return s.getResult(f);
//return s.getResult(f,lowLimit,highLimit);
}
catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* Just for testing only here!!!
*
* seems to work - may 3, 2001
*
* lots more testing for limits of 3d , polar vs. cartesian - Oct. 2004
*/
public static final void main(String[] args) {
MultipleIntegration mi = new MultipleIntegration();
// some functions to integrate!!
FunctionI testf3 = new FunctionI() {
public double value(double x) {
return Math.exp(-x*x);
}
};
FunctionI testf4 = new FunctionI() {
public double value(double x) {
return x*x*x;
}
};
FunctionIII testf = new FunctionIII () {
public double function3(double x, double y, double z) {
return (Math.exp(-(x*x+y*y+z*z)));
}
};
FunctionIII testlims = new FunctionIII () {
public double function3(double x, double y, double z) {
return (x*y*y*z*z*z);
}
};
FunctionIII testfs = new FunctionIII () {
public double function3(double r, double p, double t) {
return (r*r*Math.sin(t)*Math.exp(-(r*r)));
}
};
FunctionII testf2a = new FunctionII () {
public double function2(double x, double y) {
return (Math.exp(-(x*x+y*y)));
}
};
FunctionII testf2b = new FunctionII () {
public double function2(double r, double t) {
return r*Math.exp(-(r*r));
}
};
FunctionII testf2 = testf.getFunctionII(0,0.0);
// these should be the same!! compare z=0 in above.. test here...
System.out.println("test2val: " + testf2.function2(0.1,0.2));
System.out.println("test2aval: " + testf2a.function2(0.1,0.2));
Date d5 = new Date();
double test3 = mi.integrate(testf4,-0.0,2.0);
double test4 = mi.integrate(testf3,-100.0,100.0);
Date d6 = new Date();
System.out.println("Answer x^3 0->2: " + test3);
System.out.println("Answer e^-x^2: " + test4);
System.out.println("answer^2: " + test4*test4);
System.out.println("took: " + (d6.getTime()-d5.getTime()));
System.out.println("1D integrations: " + mi.counter);
double[] lims2 = new double[4];
lims2[0]=-100.0;
lims2[1]=100.0;
lims2[2]=-100.0;
lims2[3]=100.0;
Date d3 = new Date();
double test2 = mi.integrate(testf2,lims2);
Date d4 = new Date();
System.out.println("Answer frm 2d testf2: " + test2);
System.out.println("took: " + (d4.getTime()-d3.getTime()));
System.out.println("1D integrations: " + mi.counter);
d3 = new Date();
test2 = mi.integrate(testf2a,lims2);
d4 = new Date();
System.out.println("Answer frm 2d testf2a: " + test2);
System.out.println("took: " + (d4.getTime()-d3.getTime()));
System.out.println("1D integrations: " + mi.counter);
System.out.println("trying polar 2d now");
lims2 = new double[4];
lims2[0]=0;
lims2[1]=2*Math.PI;
lims2[2]=0;
lims2[3]=10;
d3 = new Date();
double ttest = mi.integrate(testf2b,lims2);
d4 = new Date();
System.out.println("2d polar Answer: " + ttest);
System.out.println("took: " + (d4.getTime()-d3.getTime()));
System.out.println("1D integrations: " + mi.counter);
System.out.println("trying 3d now... ");
// basic limit test here,
double[] lims = new double[6];
lims[0]=0.0;
lims[1]=3.00;
lims[2]=0.0;
lims[3]=1.0;
lims[4]=0.0;
lims[5]=2.0;
Date d1 = new Date();
double test = mi.integrate(testlims,lims);
Date d2 = new Date();
System.out.println("Answer: " + test);
System.out.println("took: " + (d2.getTime()-d1.getTime()));
System.out.println("1D integrations: " + mi.counter);
System.out.println("answer: " + 8*81/2/3/4);
lims = new double[6];
lims[0]=-10.0;
lims[1]=10.00;
lims[2]=-10.0;
lims[3]=10.0;
lims[4]=-10.0;
lims[5]=10.0;
d1 = new Date();
test = mi.integrate(testf,lims);
d2 = new Date();
System.out.println("Answer: " + test);
System.out.println("took: " + (d2.getTime()-d1.getTime()));
System.out.println("1D integrations: " + mi.counter);
System.out.println("test^2/3: " + Math.pow(test,2.0/3.0));
System.out.println("trying 3d now... ");
// 3d Function integration working in spherical coords??
lims = new double[6];
lims[0]=0;
lims[1]=Math.PI;
lims[2]=0;
lims[3]=2*Math.PI;
lims[4]=0;
lims[5]=10.0;
d1 = new Date();
test = mi.integrate(testfs,lims);
d2 = new Date();
System.out.println("Answer: " + test);
System.out.println("took: " + (d2.getTime()-d1.getTime()));
System.out.println("1D integrations: " + mi.counter);
System.out.println("test^2/3: " + Math.pow(test,2.0/3.0));
}
} | Java |
//import cern.jet.math.Bessel;
import java.lang.Math;
import java.util.Date;
import drasys.or.nonlinear.*;
public class IntegralTest {
public static void main(String[] args) {
Simpsons s = new Simpsons();
MyF myF = new MyF();
Integration i = new Integration();
i.setMaxError(.001);
//s.setEpsilon(.001);
try {
Date d1 = new Date();
//System.out.println(""+s.getEpsilon());
System.out.println("Simp: "+s.integrate(myF,0.0,Math.PI));
Date d2 = new Date();
System.out.println("" + (d2.getTime() - d1.getTime()));
}
catch(Exception e) {}
i.setFunction(myF);
i.setStartDivision(4);
Date d3 = new Date();
System.out.println("MyGuy: "+i.integrate(0.0,Math.PI)+"");
Date d4 = new Date();
System.out.println("" + (d4.getTime() - d3.getTime()));
/*try {
s.setEpsilon(.000001);
System.out.println(""+s.getEpsilon());
System.out.println(""+s.integrate(myF,1,10));
}
catch(Exception e) {}try {
s.setEpsilon(.5);
System.out.println(""+s.getEpsilon());
System.out.println(""+s.integrate(myF,1,10));
}
catch(Exception e) {}try {
s.setEpsilon(.001);
System.out.println(""+s.getEpsilon());
System.out.println(""+s.integrate(myF,1,10));
}
catch(Exception e) {}try {
s.setEpsilon(.9);
System.out.println(""+s.getEpsilon());
System.out.println(""+s.integrate(myF,1,10));
}
catch(Exception e) {}*/
}
}
class MyF extends Function {
public double function(double x) {
return Math.sin(x);
}
}
| Java |
import java.util.Date;
/**
* The usual "hot model" here.. only with one species for now
*
*/
public class GaussianVLISM extends InterstellarMedium {
public HelioVector vBulk;
public double temp, density;
public static double KB = 1.3807*Math.pow(10,-23);
public static double MP = 1.672621*Math.pow(10,-27);
private double Mover2KbT, norm, temp1,temp2,temp3;
public static double NaN = Double.NaN;
/**
* Construct a gaussian VLISM
*/
public GaussianVLISM(HelioVector _vBulk, double _density, double _temp) {
vBulk = _vBulk;
temp = _temp;
density = _density;
//System.out.println("created gaussian vlism with ro: " + density + " temp: " + temp + " bulk: " + vBulk.getR());
// normalization for maxwellian distribution
// trying power of 1/2 to see what the difference is
norm = density*Math.pow(4.0*MP/2.0/Math.PI/KB/temp,3.0/2.0);
//norm = density*Math.sqrt(4.0*MP/2.0/Math.PI/KB/temp);
// argument of exponential requires this factor
Mover2KbT = 4.0*MP/2.0/KB/temp;
}
/**
*
* Pass in a heliovector if you feel like it.. slower?
* probably not..
*/
public double heliumDist(HelioVector v) {
return dist(v.getX(), v.getY(), v.getZ());
}
public double heliumDist(double v1, double v2, double v3) {
return dist(v1,v2,v3);
}
/**
* default - pass in 3 doubles
*/
public double dist(double v1, double v2, double v3) {
if (v1==NaN | v2==NaN | v3==NaN) return 0.0;
temp1 = v1-vBulk.getX(); temp2 = v2-vBulk.getY(); temp3 = v3-vBulk.getZ();
temp1 = temp1*temp1+temp2*temp2+temp3*temp3;
return norm*Math.exp(-Mover2KbT*temp1);
}
public double dist(HelioVector hv) {
return dist(hv.getX(), hv.getY(), hv.getZ());
}
public double protonDist(double v1, double v2, double v3) {
return 0;
}
public double hydrogenDist(double v1, double v2, double v3) {
return 0;
}
public double deuteriumDist(double v1, double v2, double v3) {
return 0;
}
public double electronDist(double v1, double v2, double v3) {
return 0;
}
public double alphaDist(double v1, double v2, double v3) {
return 0;
}
// etcetera...+
/**
* Finally well tested, Aug. 2004
*
* redoing testing w/ monte carlo integration - test MultipleIntegration here now 12/2010
*/
public static final void main(String[] args) {
final GaussianVLISM gvli = new GaussianVLISM(new HelioVector(HelioVector.CARTESIAN,
-27000.0,0.0,0.0), 100.0, 6000.0);
System.out.println("Created GVLISM" );
/*
int res = 100;
file f = new file ("gauss_samp.txt");
f.initWrite(false);
for (double v = -40000; v<10000; v+= 50000/res) {
double dens = gvli.heliumDist(v,0,0);
f.write(v+"\t"+dens+"\n");
}
f.closeWrite();
*/
//System.out.println("Maxwellian VLISM created, norm = " + norm);
MultipleIntegration mi = new MultipleIntegration();
//mi.setEpsilon(0.001);
FunctionIII dist = new FunctionIII () {
public double function3(double x, double y, double z) {
return gvli.heliumDist(x, y, z);
}
};
System.out.println("Test dist: " + dist.function3(20000,0,0));
//double[] limits = new double[6];
//limits[0]=mi.MINUS_INFINITY; limits[1]=mi.PLUS_INFINITY;
//limits[2]=mi.MINUS_INFINITY; limits[3]=mi.PLUS_INFINITY;
//limits[4]=mi.MINUS_INFINITY; limits[5]=mi.PLUS_INFINITY;
double[] limits2 = new double[6];
limits2[0]=-100000.0; limits2[1]=100000.0;
limits2[2]=-100000.0; limits2[3]=100000.0;
limits2[4]=-100000.0; limits2[5]=100000.0;
//double z = mi.integrate(dist,limits2,1000);
//o(" plain integration: " + z);
double z2 = mi.mcIntegrate(dist,limits2,100000);
o(" mc at 100000: " + z2);
double z3 = mi.mcIntegrate(dist,limits2,1000000);
o(" mc at 1000000: " + z3);
//System.out.println("answer: plain, mc1, mc2 = " + z+ " "+ z2 + " " + z3);
FunctionIII distZw = new FunctionIII () {
public double function3(double r, double p, double t) {
HelioVector hv = new HelioVector(HelioVector.SPHERICAL,r,p,t);
return gvli.heliumDist(hv)*r*r*Math.sin(t);
}
};
double[] limitsZw = {0.0,100000.0,0.0,2*Math.PI,0,Math.PI};
double ans = mi.mcIntegrate(distZw, limitsZw,1000000);
System.out.println("answer in spherical coords = " + ans );
}
public static void o(String s) {
System.out.println(s);
}
}
| Java |
/** This is a wrapper for some static functions I wrote
*
*/
public class LukeMath {
// recursively computes legendre polynomial of order n, argument x
public static double compute(int n,double x) {
if (n == 0) return 1;
else if (n == 1) return x;
return ( (2*n-1)*x*compute(n-1,x) - (n-1)*compute(n-2,x) ) / n;
}
}
// Guess we don't need this stuff...
/*public static long factorial(int m) {
if (m==1) return 1;
else return m*factorial(m-1);
}
}*/// L
/*C*** LEGENDRE POLYNOM P(X) OF ORDER N
C*** EXPLICIT EXPRESSION
POLLEG=0.
NEND=N/2
DO M=0,NEND
N2M2=N*2-M*2
NM2=N-M*2
NM=N-M
TERM=X**NM2*(-1.)**M
TERM=TERM/NFAK(M)*NFAK(N2M2)
TERM=TERM/NFAK(NM)/NFAK(NM2)
POLLEG=POLLEG+TERM
END DO
POLLEG=POLLEG/2**N
RETURN
END
C*/
// I love fortran! | Java |
public class MakeTanAngle135Array {
public static void main(String[] args) {
VIonBulk vib;
file myFile;
double AU = 1.5* Math.pow(10,11);
myFile = new file("135array.txt");
myFile.initWrite(false);
for (int v0=20000; v0<40000; v0=v0+1000) {
vib = new VIonBulk(AU, 28000, 135*3.14159/180);
double ourAngle = Math.atan(vib.Vr()/vib.Vperp());
myFile.write(v0+" "+ourAngle+System.getProperty("line.separator"));
}
myFile.closeWrite();
}
}
| Java |
/**
* A basic power law in ENERGY
*
*/
public class PowerLawVLISM extends InterstellarMedium {
public HelioVector vBulk;
public double power, density, lim1, lim2, norm, ee;
public static double NaN = Double.NaN;
public static double MP = 1.672621*Math.pow(10,-27);
public static double EV = 6.24150965*Math.pow(10,18);
/**
* Construct a power law VLISM
*/
public PowerLawVLISM(HelioVector _vBulk, double _density, double _power, double _ll, double _hh) {
vBulk = _vBulk;
power = _power;
density = _density;
lim1 = _ll;
lim2 = _hh;
// calculate normalization
norm = density/4/Math.PI/ (Math.pow(lim2,power+3.0)- Math.pow(lim1,power+3.0))*(power+3.0);
norm=norm;
System.out.println("norm: " + norm);
}
/**
*
* Pass in a heliovector if you feel like it.. slower?
* probably not..
*/
public double heliumDist(HelioVector v) {
return dist(v.getX(), v.getY(), v.getZ());
}
public double heliumDist(double v1, double v2, double v3) {
return dist(v1,v2,v3);
}
/**
* default - pass in 3 doubles
*/
public double dist(double v1, double v2, double v3) {
if (v1==NaN | v2==NaN | v3==NaN) return 0.0;
// calculate energy
double vv1 = v1-vBulk.getX();
double vv2 = v2-vBulk.getY();
double vv3 = v3-vBulk.getZ();
double vv = Math.sqrt(vv1*vv1+vv2*vv2+vv3*vv3);
// ee = 4*MP/2*(vv1*vv1+vv2*vv2+vv3*vv3)*EV;
// System.out.println("ee: " + ee);
if (vv>lim1 && vv<lim2) return norm*Math.pow(vv,power);
else return 0.0;
}
/**
* default - pass in 1 energy
*/
//public double dist(double energy) {
// if (v1==NaN | v2==NaN | v3==NaN) return 0.0;
// calculate energy
//double vv1 = v1-vBulk.getX();
//double vv2 = v2-vBulk.getY();
//double vv3 = v3-vBulk.getZ();
//ee = 4*MP/2*(vv1*vv1+vv2*vv2+vv3*vv3)*EV;
// System.out.println("ee: " + ee);
// ee=energy;
// if (ee>lim1 && ee<lim2) return norm*Math.pow(ee,power);
// else return 0.0;
//}
public double protonDist(double v1, double v2, double v3) {
return 0;
}
public double hydrogenDist(double v1, double v2, double v3) {
return 0;
}
public double deuteriumDist(double v1, double v2, double v3) {
return 0;
}
public double electronDist(double v1, double v2, double v3) {
return 0;
}
public double alphaDist(double v1, double v2, double v3) {
return 0;
}
// etcetera...+
/**
*
*/
public static final void main(String[] args) {
final PowerLawVLISM gvli = new PowerLawVLISM(new HelioVector(HelioVector.CARTESIAN,
-20000.0,0.0,0.0), 1.0, -4.0, 1000.0, 300000.0);
System.out.println("Created PLVLISM" );
//System.out.println("Maxwellian VLISM created, norm = " + norm);
MultipleIntegration mi = new MultipleIntegration();
//mi.setEpsilon(0.001);
FunctionIII dist = new FunctionIII () {
public double function3(double x, double y, double z) {
return gvli.heliumDist(x, y, z);
}
};
System.out.println("Test dist: " + dist.function3(20000,0,0));
double[] limits = new double[6];
limits[0]=mi.MINUS_INFINITY; limits[1]=mi.PLUS_INFINITY;
limits[2]=mi.MINUS_INFINITY; limits[3]=mi.PLUS_INFINITY;
limits[4]=mi.MINUS_INFINITY; limits[5]=mi.PLUS_INFINITY;
double[] limits2 = new double[6];
limits2[0]=-100000.0; limits2[1]=100000.0;
limits2[2]=-100000.0; limits2[3]=100000.0;
limits2[4]=-100000.0; limits2[5]=100000.0;
//double z = mi.mcIntegrate(dist,limits,128 );
double z2 = mi.mcIntegrate(dist,limits2,1000000);
System.out.println("Integral should equal density= " + z2);
}
}
| Java |
import java.lang.Math;
import java.util.Date;
//Put your own function here and intgrate it
// Lukas Saul - Warsaw 2000
// lets use someone elses, shall we?
// nah, they all suck. I'll write my own
public class Integration {
private int startDivision = 5;
private long maxDivision = 100000;
private int maxTime = 60;
private boolean checkTime = false;
private double maxError = .1;
private double averageValue;
private Function f;
//private int splitSize;
private double f1, f2, f3, f4, f5, f6, f7;
private Date d1, d2, d3;
private double ll,ul,last;
public void setStartDivision(int s) { startDivision = s; }
public int getStartDivision() {return startDivision; }
public void setMaxDivision(long m) {maxDivision = m; }
public long getMaxDivision() {return maxDivision;}
public void setMaxTime(int mt) {maxTime = mt;}
public int getMaxTime() {return maxTime; }
public void setCheckTime(boolean ct) {checkTime = ct; }
public boolean getCheckTime() {return checkTime; }
public void setMaxError(double me) { if (me<1 & me>0) maxError = me; }
public double getMaxError() {return maxError;}
public void setFunction(Function fi) {f=fi;}
//public void setSplitSize (int ss) {splitSize = ss;}
//public int getSplitSize () {return splitSize; }
private double IntegrateSimple(double lowerLimit, double upperLimit) {
if (lowerLimit==ll & upperLimit == ul) return last;
else {
ll = lowerLimit; ul=upperLimit;
f1 = f.function(lowerLimit); f2 = f.function(upperLimit);
last = (upperLimit - lowerLimit) * (f1 + .5*(f2-f1)); // trapezoidal area
return last;
}
}
public double integrate (double lowerLimit, double upperLimit) {
if (checkTime) d1 = new Date();
f3 = 0;
f4 = (upperLimit - lowerLimit)/startDivision; // f4 = divisionSize
for (int i = 0; i< startDivision; i++) {
f3 += recurse(lowerLimit+(i*f4), lowerLimit+((i+1)*f4), startDivision);
}
return f3;
}
private double recurse (double lower, double upper, long depth) {
if (checkTime) {
d2 = new Date();
if ((d2.getTime() - d1.getTime())/1000 > maxTime) {
return IntegrateSimple(lower, upper);
}
}
if (depth >= maxDivision) return IntegrateSimple(lower, upper);
f5 = IntegrateSimple(lower, lower + (upper-lower)/2);
f5 += IntegrateSimple(lower+ (upper-lower)/2, upper);
f6 = IntegrateSimple(lower, upper);
// if the difference between these two intgrals is within error, return the better
if (Math.abs(1-f6/f5) < maxError) return f5;
// if not divide up the two and recurse
else return recurse(lower, lower + (upper-lower)/2, depth*2) +
recurse(lower+ (upper-lower)/2, upper, depth*2);
}
}
| Java |
import cern.jet.math.Bessel;
import java.lang.Math;
import java.util.Date;
import drasys.or.nonlinear.*;
/** This class computes the pickup distribution as a function of
* vr, vt, ( and r, theta)
*/
public class 2DVelocityDistribution {
// constants not correct yet
public static double Ms = 2 * Math.pow(10,30);
public static double G = 6.67 * Math.pow(10,-11);
public static double AU = 1.5* Math.pow(10,11);
public static double K = 1.380622 * Math.pow(10,-23); //1.380622E-23 kg/m/s/s/K
public static double Mhe = 4*1.6726231 * Math.pow(10,-27); // 4 * 1.6726231 x 10-24 gm
public double Q, F1, F2, Temp, Vb, N, Vtemp, V0, mu, r, theta, betaPlus, betaMinus;
public double phi0, theta0; // direction of bulk flow - used when converting to GSE
//public Trapezoidal s;
public Integration s;
public NeutralDistribution nd; // this is our neutral helium distribution
public SurvivalProbability sp; // % of neutral ions still left at r,v
public 2DVelocityDistribution(double bulkVelocity, double phi0, double theta0,
double temperature, double density,
double radiationToGravityRatio, double lossRate1AU) {
// the constructor just sets up the parameters
Temp = temperature;
Vb = bulkVelocity;
this.phi0 = phi0;
this.theta0 = theta0;
N = density;
mu = radiationToGravityRatio;
betaMinus = lossRate1AU;
Vtemp = Math.sqrt(2*K*Temp/Mhe); //average velocity due to heat
sp = new SurvivalProbability(betaMinus);
nd = new NeutralDistribution(Vb, phi0, theta0,
Temp, N, mu);
}
public double N(double r, double theta, double vr, double vt) {
V0 = Math.sqrt(vr*vr + vt*vt - 2*Q*Q);
F1 = 2*Vb*vr/(Vtemp*Vtemp) *
Math.cos(theta)*(V0 - vr)*(V0 - vr) / (V0*(V0-vr)+Q*Q) -
((Vb*Vb)+(V0*V0)+2*V0*Vb*Math.cos(theta))/(Vtemp*Vtemp);
F2 = 2*V0*Vb/(Vtemp*Vtemp) * Math.sin(theta)*(V0-vr)*vt/ (V0*(V0-vr) + (Q*Q));
return sp.compute(r,theta,vt,vr) * N*Math.pow((Math.sqrt(Math.PI)*Vtemp),-3) *
Math.exp(F1)*Bessel.i0(F2);
}
// this function returns N(r,theta, vt)
public double N(double r, double theta, double vt) {
this.r=r; this.theta=theta;
Q = Math.sqrt((1-mu)*G*Ms/r);
Nvr nvr = new Nvr(vt);
//s = new Trapezoidal(); s.setMaxIterations(15); s.setEpsilon(1000000);
s=new Integration();
s.setFunction(nvr);
s.setMaxError(.01);
try {
return s.integrate( -100000, 100000);
}catch(Exception e) {
e.printStackTrace();
return 0;
}
}
class Nvr implements FunctionI, Function {
// this is the function we integrate over vr
public double vt;
public Nvr(double vt_) {
System.out.println("nvr constructor");
vt = vt_;
// System.out.println("set vt");
}
public double function(double vr) {
// System.out.println("Trying nvr.function vr= " + vr);
V0 = Math.sqrt(vr*vr + vt*vt - 2*Q*Q);
F1 = 2*Vb*vr/(Vtemp*Vtemp) * Math.cos(theta)*(V0 - vr)*(V0 - vr) / (V0*(V0-vr)+Q*Q) -
((Vb*Vb)+(V0*V0)+2*V0*Vb*Math.cos(theta))/(Vtemp*Vtemp);
F2 = 2*V0*Vb/(Vtemp*Vtemp) * Math.sin(theta)*(V0-vr)*vt/ (V0*(V0-vr) + (Q*Q));
return sp.compute(r,theta,vt,vr)*N*Math.pow((Math.sqrt(Math.PI)*Vtemp),-3) *
Math.exp(F1)*Bessel.i0(F2);
// here we integrate over L(r,v)*N(r,v) with L = survival probability.
// this could be all put into this routine but I leave it out for other
// factors to be added in later
}
}
} | Java |
import java.util.StringTokenizer;
import java.util.Vector;
/*
* This is to load a given model from a file and give a proper normalization to match the ibex data
* for using a one parameter (normalization) fit.
*/
public class FitData {
public StringTokenizer st;
public double[] days;
public double[] rates;
public Vector daysV;
public Vector ratesV;
public FitData(double[] qdays, double[] qrates) {
days = qdays;
rates = qrates;
}
public FitData(String filename) {
daysV = new Vector();
ratesV = new Vector();
file f = new file(filename);
f.initRead();
String line = "";
while ((line=f.readLine())!=null) {
st = new StringTokenizer(line);
daysV.add(st.nextToken());
ratesV.add(st.nextToken());
}
// time to fix the arrays
days = new double[daysV.size()];
rates = new double[daysV.size()];
for (int i=0; i<days.length; i++) {
days[i]=Double.parseDouble((String)daysV.elementAt(i));
rates[i]=Double.parseDouble((String)ratesV.elementAt(i));
}
}
// we are going to interpolate here
public double getRate(double day) {
for (int i=0; i<days.length; i++) {
if (day<days[i]) { // this is where we want to be
return (rates[i]+rates[i+1])/2;
}
}
return 0;
}
} | Java |
/*
* Interface MinimisationFunction
*
* This interface provides the abstract method for the function to be
* minimised by the methods in the class, Minimisation
*
* WRITTEN BY: Dr Michael Thomas Flanagan
*
* DATE: April 2003
* MODIFIED: April 2004
*
* DOCUMENTATION:
* See Michael Thomas Flanagan's Java library on-line web page:
* Minimisation.html
*
* Copyright (c) April 2004
*
* PERMISSION TO COPY:
* Permission to use, copy and modify this software and its documentation for
* NON-COMMERCIAL purposes is granted, without fee, provided that an acknowledgement
* to the author, Michael Thomas Flanagan at www.ee.ucl.ac.uk/~mflanaga, appears in all copies.
*
* Dr Michael Thomas Flanagan makes no representations about the suitability
* or fitness of the software for any or for a particular purpose.
* Michael Thomas Flanagan shall not be liable for any damages suffered
* as a result of using, modifying or distributing this software or its derivatives.
*
****************************************************************************************/
// Interface for Minimisation class
// Calculates value of function to be minimised
public interface MinimisationFunction{
double function(double[]param);
} | Java |
import gov.noaa.pmel.sgt.swing.JPlotLayout;
import gov.noaa.pmel.sgt.swing.JClassTree;
import gov.noaa.pmel.sgt.swing.prop.GridAttributeDialog;
import gov.noaa.pmel.sgt.JPane;
import gov.noaa.pmel.sgt.GridAttribute;
import gov.noaa.pmel.sgt.ContourLevels;
import gov.noaa.pmel.sgt.CartesianRenderer;
import gov.noaa.pmel.sgt.CartesianGraph;
import gov.noaa.pmel.sgt.GridCartesianRenderer;
import gov.noaa.pmel.sgt.IndexedColorMap;
import gov.noaa.pmel.sgt.ColorMap;
import gov.noaa.pmel.sgt.LinearTransform;
import gov.noaa.pmel.sgt.dm.SGTData;
import gov.noaa.pmel.util.GeoDate;
import gov.noaa.pmel.util.TimeRange;
import gov.noaa.pmel.util.Range2D;
import gov.noaa.pmel.util.Dimension2D;
import gov.noaa.pmel.util.Rectangle2D;
import gov.noaa.pmel.util.Point2D;
import gov.noaa.pmel.util.IllegalTimeValue;
import gov.noaa.pmel.sgt.dm.SimpleGrid;
import gov.noaa.pmel.sgt.dm.*;
import gov.noaa.pmel.sgt.SGLabel;
import java.awt.event.*;
import java.awt.print.*;
import java.awt.image.*;
//import net.jmge.gif.*;
import java.awt.*;
import javax.swing.*;
import java.io.*;
import javax.imageio.*;
/**
* Let's use this to take a look at 3D data with color...
*
* Put new code in makeGraph() routine
*
* Added to:
* @author Donald Denbo
* @version $Revision: 1.8 $, $Date: 2001/02/05 23:28:46 $
* @since 2.0
*
* Lukas Saul summer 2002
*/
public class JColorGraph extends PrintableDialog implements ActionListener{
public JPlotLayout rpl_;
public JPane gridKeyPane;
private GridAttribute gridAttr_;
JButton edit_;
JButton space_ = null;
JButton tree_;
JButton print_;
JButton save_;
JButton color_;
JPanel main;
Range2D datar;
ContourLevels clevels;
ColorMap cmap;
SGTData newData;
public String fileName ="test";
public String xLabel1, xLabel2, yLabel1, yLabel2;
// defaults
private String unitString = "log sqare error";
private String label1 = "University of Bern";
private String label2 = "Neutralizer";
public double[] xValues;
public double[] yValues;
public double[] zValues;
public float xMax, xMin, yMax, yMin, zMax, zMin;
public float cMin, cMax, cDelta;
public boolean b_color;
public JColorGraph() {
b_color = true;
}
public JColorGraph(double[] x, double[] y, double[] z) {
this(x,y,z,true);
}
public JColorGraph(double[] x, double[] y, double[] z, boolean b) {
b_color = b;
xValues=x;
yValues=y;
zValues=z;
// assume here we are going to have input the data already
xMax = (float)xValues[0]; xMin = (float)xValues[0];
yMax = (float)yValues[0]; yMin = (float)yValues[0];
zMax = (float)zValues[0]; zMin = (float)zValues[0];
//o("xMin: " + xMin);
for (int i=0; i<xValues.length; i++) {
if (xValues[i]<xMin) xMin = (float)xValues[i];
if (xValues[i]>xMax) xMax = (float)xValues[i];
}
for (int i=0; i<yValues.length; i++) {
if (yValues[i]<yMin) yMin = (float)yValues[i];
if (yValues[i]>yMax) yMax = (float)yValues[i];
}
for (int i=0; i<zValues.length; i++) {
if (zValues[i]<zMin) zMin = (float)zValues[i];
if (zValues[i]>zMax) zMax = (float)zValues[i];
}
o("xmin: " + xMin);
o("xmax: " + xMax);
o("ymin: " + yMin);
o("ymax: " + yMax);
cMin = zMin; cMax = zMax; cDelta = (zMax-zMin)/2;
datar = new Range2D(zMin, zMax, cDelta);
clevels = ContourLevels.getDefault(datar);
gridAttr_ = new GridAttribute(clevels);
if (b_color == true) cmap = createColorMap(datar);
else cmap = createMonochromeMap(datar);
gridAttr_.setColorMap(cmap);
gridAttr_.setStyle(GridAttribute.RASTER_CONTOUR);
}
private JPanel makeButtonPanel(boolean mark) {
JPanel button = new JPanel();
button.setLayout(new FlowLayout());
tree_ = new JButton("Tree View");
//MyAction myAction = new MyAction();
tree_.addActionListener(this);
button.add(tree_);
edit_ = new JButton("Edit GridAttribute");
edit_.addActionListener(this);
button.add(edit_);
print_= new JButton("Print");
print_.addActionListener(this);
button.add(print_);
save_= new JButton("Save");
save_.addActionListener(this);
button.add(save_);
color_= new JButton("Colors...");
color_.addActionListener(this);
button.add(color_);
// Optionally leave the "mark" button out of the button panel
if(mark) {
space_ = new JButton("Add Mark");
space_.addActionListener(this);
button.add(space_);
}
return button;
}
/**
* more hacking here
*/
public void showIt() {
frame.setVisible(true);
try {
Thread.sleep(3000);
BufferedImage ii = getImage();
//String s = JOptionPane.showInputDialog("enter file name");
ImageIO.write(ii,"png",new File(fileName+".png"));
//System.exit(0);
}
catch (Exception e) {
e.printStackTrace();
}
}
private JFrame frame = null;
public void run() {
/*
* Create a new JFrame to contain the demo.
*/
frame = new JFrame("Grid Demo");
main = new JPanel();
main.setLayout(new BorderLayout());
frame.setSize(600,500);
frame.getContentPane().setLayout(new BorderLayout());
/*
* Listen for windowClosing events and dispose of JFrame
*/
frame.addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent event) {
JFrame fr = (JFrame)event.getSource();
fr.setVisible(false);
}
public void windowOpened(java.awt.event.WindowEvent event) {
rpl_.getKeyPane().draw();
}
});
/*
* Create button panel with "mark" button
*/
JPanel button = makeButtonPanel(true);
/*
* Create JPlotLayout and turn batching on. With batching on the
* plot will not be updated as components are modified or added to
* the plot tree.
*/
rpl_ = makeGraph();
rpl_.setBatch(true);
/*
* Layout the plot, key, and buttons.
*/
main.add(rpl_, BorderLayout.CENTER);
gridKeyPane = rpl_.getKeyPane();
gridKeyPane.setSize(new Dimension(600,100));
rpl_.setKeyLayerSizeP(new Dimension2D(6.0, 1.0));
rpl_.setKeyBoundsP(new Rectangle2D.Double(0.0, 1.0, 6.0, 1.0));
main.add(gridKeyPane, BorderLayout.SOUTH);
frame.getContentPane().add(main, BorderLayout.CENTER);
frame.getContentPane().add(button, BorderLayout.SOUTH);
frame.pack();
// frame.setVisible(true);
/*
* Turn batching off. JPlotLayout will redraw if it has been
* modified since batching was turned on.
*/
rpl_.setBatch(false);
}
void edit_actionPerformed(java.awt.event.ActionEvent e) {
/*
* Create a GridAttributeDialog and set the renderer.
*/
GridAttributeDialog gad = new GridAttributeDialog();
gad.setJPane(rpl_);
CartesianRenderer rend = ((CartesianGraph)rpl_.getFirstLayer().getGraph()).getRenderer();
gad.setGridCartesianRenderer((GridCartesianRenderer)rend);
// gad.setGridAttribute(gridAttr_);
gad.setVisible(true);
}
void tree_actionPerformed(java.awt.event.ActionEvent e) {
/*
* Create a JClassTree for the JPlotLayout objects
*/
JClassTree ct = new JClassTree();
ct.setModal(false);
ct.setJPane(rpl_);
ct.show();
}
/**
* This example uses a pre-created "Layout" for raster time
* series to simplify the construction of a plot. The
* JPlotLayout can plot a single grid with
* a ColorKey, time series with a LineKey, point collection with a
* PointCollectionKey, and general X-Y plots with a
* LineKey. JPlotLayout supports zooming, object selection, and
* object editing.
*/
private JPlotLayout makeGraph() {
o("inside makeGraph");
//SimpleGrid sg;
SimpleGrid sg;
//TestData td;
JPlotLayout rpl;
//Range2D xr = new Range2D(190.0f, 250.0f, 1.0f);
//Range2D yr = new Range2D(0.0f, 45.0f, 1.0f);
//td = new TestData(TestData.XY_GRID, xr, yr,
// TestData.SINE_RAMP, 12.0f, 30.f, 5.0f);
//newData = td.getSGTData();
sg = new SimpleGrid(zValues, xValues, yValues, "Quantar");
sg.setXMetaData(new SGTMetaData(xLabel1, xLabel2));
sg.setYMetaData(new SGTMetaData(yLabel1, yLabel2));
//sg.setXMetaData(new SGTMetaData("Interstellar He Wind Temperature", "deg K"));
//sg.setYMetaData(new SGTMetaData("Interstellar He Bulk Speed", "km/s"));
sg.setZMetaData(new SGTMetaData(unitString, ""));
// newData.setKeyTitle(new SGLabel("a","test",new Point2D.Double(0.0,0.0)) );
// newData.setTimeArray(GeoDate[] tloc)
// newData.setTimeEdges(GeoDate[] edge);
sg.setTitle("tttest");
// newData.setXEdges(double[] edge);
// newData.setYEdges(double[] edge);
newData = sg;
//newData = sg.copy();
//Create the layout without a Logo image and with the
//ColorKey on a separate Pane object.
rpl = new JPlotLayout(true, false, false, "test layout", null, true);
rpl.setEditClasses(false);
//Create a GridAttribute for CONTOUR style.
//datar = new Range2D(zMin, zMax, (zMax-zMin)/6);
//clevels = ContourLevels.getDefault(datar);
//gridAttr_ = new GridAttribute(clevels);
//Create a ColorMap and change the style to RASTER_CONTOUR.
//ColorMap cmap = createColorMap(datar);
//gridAttr_.setColorMap(cmap);
//gridAttr_.setStyle(GridAttribute.RASTER_CONTOUR);
//Add the grid to the layout and give a label for
//the ColorKey.
//rpl.addData(newData, gridAttr_, "Diff. EFlux (1/cm^2/s/sr)");
rpl.addData(newData, gridAttr_, unitString);
// rpl.addData(newData);
/*
* Change the layout's three title lines.
*/
rpl.setTitles(label1,label2,"");
/*
* Resize the graph and place in the "Center" of the frame.
*/
rpl.setSize(new Dimension(600, 400));
/*
* Resize the key Pane, both the device size and the physical
* size. Set the size of the key in physical units and place
* the key pane at the "South" of the frame.
*/
rpl.setKeyLayerSizeP(new Dimension2D(6.0, 1.02));
rpl.setKeyBoundsP(new Rectangle2D.Double(0.01, 1.01, 5.98, 1.0));
return rpl;
}
private ColorMap createColorMap(Range2D datar) {
int[] red =
{ 255, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 7, 23, 39, 55, 71, 87,103,
119,135,151,167,183,199,215,231,
247,255,255,255,255,255,255,255,
255,255,255,255,255,255,255,255,
255,246,228,211,193,175,158,140};
int[] green =
{ 255, 0, 0, 0, 0, 0, 0, 0,
0, 11, 27, 43, 59, 75, 91,107,
123,139,155,171,187,203,219,235,
251,255,255,255,255,255,255,255,
255,255,255,255,255,255,255,255,
255,247,231,215,199,183,167,151,
135,119,103, 87, 71, 55, 39, 23,
7, 0, 0, 0, 0, 0, 0, 0};
int[] blue =
{ 255,143,159,175,191,207,223,239,
255,255,255,255,255,255,255,255,
255,255,255,255,255,255,255,255,
255,247,231,215,199,183,167,151,
135,119,103, 87, 71, 55, 39, 23,
7, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0};
IndexedColorMap cmap = new IndexedColorMap(red, green, blue);
cmap.setTransform(new LinearTransform(0.0, (double)red.length,
datar.start, datar.end));
return cmap;
}
/**
* here's a simpler map...
*/
private ColorMap createMonochromeMap(Range2D datar) {
int[] red = new int[200];
int[] green = new int [200];
int[] blue = new int [200];
red[0]=255; //red[1]=255;
green[0]=255; ///green[1]=255;
blue[0]=255; //lue[1]=255;
for (int i=1; i<red.length; i++) {
red[i]=230-i;
green[i]=230-i;
blue[i]=230-i;
}
IndexedColorMap cmap = new IndexedColorMap(red, green, blue);
cmap.setTransform(new LinearTransform(0.0, (double)red.length,
datar.start, datar.end));
return cmap;
}
public void actionPerformed(java.awt.event.ActionEvent event) {
Object source = event.getActionCommand();
Object obj = event.getSource();
if(obj == edit_)
edit_actionPerformed(event);
else if(obj == space_) {
System.out.println(" <<Mark>>");
}
else if(obj == tree_)
tree_actionPerformed(event);
else if(obj == save_) {
try {
BufferedImage ii = getImage();
String s = JOptionPane.showInputDialog("enter file name");
ImageIO.write(ii,"png",new File(s+".png"));
//File outputFile = new File("gifOutput_" +1+".gif");
//FileOutputStream fos = new FileOutputStream(outputFile);
//o("starting to write animated gif...");
////writeAnimatedGIF(ii,"CTOF He+", true, 3.0, fos);
//writeNormalGIF(ii, "MFI PSD", -1, false, fos);
//fos.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
else if (obj == print_) {
System.out.println("Trying to print...");
//setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintable(this);
if (job.printDialog()) {
try {
o("printing...");
job.print();
o("done...");
}
catch (Exception ex) {
ex.printStackTrace();
}
}
}
//setCursor(Cursor.getDefaultCursor());
else if (obj == color_) {
try {
System.out.println("changing color scale");
rpl_.setVisible(false);
rpl_.clear();
cMin = Float.parseFloat(
JOptionPane.showInputDialog(this,"Min. Color Value: ",cMin+""));
cMax = Float.parseFloat(
JOptionPane.showInputDialog(this,"Max. Color Value: ",cMax+""));
cDelta = Float.parseFloat(
JOptionPane.showInputDialog(this,"Delta. Color Value: ",cDelta+""));
rpl_.addData(newData, gridAttr_, "EFlux");
rpl_.setVisible(true);
}
catch (Exception e) {e.printStackTrace();}
}
}
private static void o(String s) {
System.out.println(s);
}
/*private void writeNormalGIF(Image img,
String annotation,
int transparent_index, // pass -1 for none
boolean interlaced,
OutputStream out) throws IOException {
Gif89Encoder gifenc = new Gif89Encoder(img);
gifenc.setComments(annotation);
gifenc.setTransparentIndex(transparent_index);
gifenc.getFrameAt(0).setInterlaced(interlaced);
gifenc.encode(out);
}*/
/**
* Use this to set the labels that will appear on the graph when you call "run()".
*
* This first is the big title, second subtitle, third units on color scale (z axis)
*/
public void setLabels(String l1, String l2, String l3) {
unitString = l3;
label1 = l1;
label2 = l2;
}
public void setXAxisLabels(String l1, String l2) {
xLabel1 = l1;
xLabel2 = l2;
}
public void setYAxisLabels(String l1, String l2) {
yLabel1 = l1;
yLabel2 = l2;
}
public BufferedImage getImage() {
//Image ii = rpl_.getIconImage();
//if (ii==null) {
// System.out.println ("lpl ain't got no image");
//}
//else {
//ImageIcon i = new ImageIcon(ii);
// return ii;
//}
try {
//show();
//setDefaultSizes();
//rpl.setAutoRange(false,false);
//rpl.setRange(new Domain(new Range2D(1.3, 4.0), new Range2D(0.0, 35000.0)));
rpl_.draw();
//show();
Robot r = new Robot();
Point p = main.getLocationOnScreen();
Dimension d = new Dimension(main.getSize());
//d.setSize( d.getWidth()+d.getWidth()/2,
// d.getHeight()+d.getHeight()/2 );
Rectangle rect = new Rectangle(p,d);
//BufferedImage bi = r.createScreenCapture(rect);
//ImageIcon i = new ImageIcon(r.createScreenCapture(rect));
return r.createScreenCapture(rect);
//setVisible(false);
//return i.getImage();
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
// some code from original below
/*
public static void main(String[] args) {
// Create the demo as an application
JColorGraph gd = new JColorGraph();
// Create a new JFrame to contain the demo.
//
JFrame frame = new JFrame("Grid Demo");
JPanel main = new JPanel();
main.setLayout(new BorderLayout());
frame.setSize(600,500);
frame.getContentPane().setLayout(new BorderLayout());
// Listen for windowClosing events and dispose of JFrame
frame.addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent event) {
JFrame fr = (JFrame)event.getSource();
fr.setVisible(false);
fr.dispose();
System.exit(0);
}
public void windowOpened(java.awt.event.WindowEvent event) {
rpl_.getKeyPane().draw();
}
});
//Create button panel with "mark" button
JPanel button = gd.makeButtonPanel(true);
// Create JPlotLayout and turn batching on. With batching on the
// plot will not be updated as components are modified or added to
// the plot tree.
rpl_ = gd.makeGraph();
rpl_.setBatch(true);
// Layout the plot, key, and buttons.
main.add(rpl_, BorderLayout.CENTER);
JPane gridKeyPane = rpl_.getKeyPane();
gridKeyPane.setSize(new Dimension(600,100));
rpl_.setKeyLayerSizeP(new Dimension2D(6.0, 1.0));
rpl_.setKeyBoundsP(new Rectangle2D.Double(0.0, 1.0, 6.0, 1.0));
main.add(gridKeyPane, BorderLayout.SOUTH);
frame.getContentPane().add(main, BorderLayout.CENTER);
frame.getContentPane().add(button, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
// Turn batching off. JPlotLayout will redraw if it has been
// modified since batching was turned on.
rpl_.setBatch(false);
}
*/
/* class MyAction implements java.awt.event.ActionListener {
public void actionPerformed(java.awt.event.ActionEvent event) {
Object source = event.getActionCommand();
Object obj = event.getSource();
if(obj == edit_)
edit_actionPerformed(event);
else if(obj == space_) {
System.out.println(" <<Mark>>");
}
else if(obj == tree_)
tree_actionPerformed(event);
else if (source == "Print") {
System.out.println("Trying to print...");
//setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintable(this);
if (job.printDialog()) {
try {
job.print();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
}
//setCursor(Cursor.getDefaultCursor());
}
}*/
/*
public void init() {
// Create the demo in the JApplet environment.
getContentPane().setLayout(new BorderLayout(0,0));
setBackground(java.awt.Color.white);
setSize(600,550);
JPanel main = new JPanel();
rpl_ = makeGraph();
JPanel button = makeButtonPanel(false);
rpl_.setBatch(true);
main.add(rpl_, BorderLayout.CENTER);
JPane gridKeyPane = rpl_.getKeyPane();
gridKeyPane.setSize(new Dimension(600,100));
main.add(gridKeyPane, BorderLayout.SOUTH);
getContentPane().add(main, "Center");
getContentPane().add(button, "South");
rpl_.setBatch(false);
}
*/ | Java |
import cern.jet.math.Bessel;
import java.lang.Math;
import java.util.Date;
import drasys.or.nonlinear.*;
public class BofTheta {
public static double Ms = 2 * Math.pow(10,30);
public static double G = 667 * Math.pow(10,-13);
public static double AU = 15* Math.pow(10,12);
private double r, v0;
private Simpsons s;
private EquationSolution es;
public BofTheta(double r, double v0) {
this.r = r; this.v0 = v0;
System.out.println("r= " + r);
s = new Simpsons(); s.setEpsilon(.001);
es = new EquationSolution(); es.setAccuracy(1); es.setMaxIterations(100);
System.out.println(es.getAccuracy() + " is accurate?");
System.out.println("r= " + r);
System.out.println(es.getMaxIterations()+"");
}
class DThetaDr implements FunctionI {
private double b = 0;
public DThetaDr(double b) {
this.b = b;
}
public double function(double rV) {
//System.out.println("Called function- "+b+ " " + r + " " +rV);
return v0*b/(rV*rV)*Math.sqrt(2*Ms*G/rV - v0*v0*b*b/(rV*rV) + v0*v0);
}
}
class ThetaOfB implements FunctionI {
public double function(double b) {
//System.out.println("Calling ThetaOfB");
DThetaDr dthDr = new DThetaDr(b);
//System.out.println("trying integral..." + dthDr.b);
try {
double q = s.integrate(dthDr, 1000*AU, r);
System.out.println("Theta= " + q);
return q;
}catch (Exception e) {
e.printStackTrace();
return 0;
}
}
}
public double calculate(double theta) {
ThetaOfB tob = new ThetaOfB();
try {
double bLimit = Math.sqrt(2*Ms*G*r/(v0*v0) + r*r);
return es.solve(tob, -bLimit, bLimit, theta);
}catch (Exception e) {
e.printStackTrace();
return 0;
}
}
}
| Java |
/*
* Class MaximisationExample
*
* An example of the use of the class Maximisation
* and the interface MaximisationFunction
*
* Finds the maximum of the function
* z = a + x^2 + 3y^4
* where a is constant
* (an easily solved function has been chosen
* for clarity and easy checking)
*
* WRITTEN BY: Michael Thomas Flanagan
*
* DATE: 29 December 2005
*
* PERMISSION TO COPY:
* Permission to use, copy and modify this software and its documentation
* for NON-COMMERCIAL purposes and without fee is hereby granted provided
* that an acknowledgement to the author, Michael Thomas Flanagan, and the
* disclaimer below, appears in all copies.
*
* The author makes no representations or warranties about the suitability
* or fitness of the software for any or for a particular purpose.
* The author shall not be liable for any damages suffered as a result of
* using, modifying or distributing this software or its derivatives.
*
**********************************************************/
import flanagan.math.*;
// Class to evaluate the function z = a + -(x-1)^2 - 3(y+1)^4
// where a is fixed and the values of x and y
// (x[0] and x[1] in this method) are the
// current values in the maximisation method.
class MaximFunct implements MaximisationFunction{
private double a = 0.0D;
// evaluation function
public double function(double[] x){
double z = a - (x[0]-1.0D)*(x[0]-1.0D) - 3.0D*Math.pow((x[1]+1.0D), 4);
return z;
}
// Method to set a
public void setA(double a){
this.a = a;
}
}
// Class to demonstrate maximisation method, Maximisation nelderMead
public class MaximisationExample{
public static void main(String[] args){
//Create instance of Maximisation
Maximisation max = new Maximisation();
// Create instace of class holding function to be maximised
MaximFunct funct = new MaximFunct();
// Set value of the constant a to 5
funct.setA(5.0D);
// initial estimates
double[] start = {1.0D, 3.0D};
// initial step sizes
double[] step = {0.2D, 0.6D};
// convergence tolerance
double ftol = 1e-15;
// Nelder and Mead maximisation procedure
max.nelderMead(funct, start, step, ftol);
// get the maximum value
double maximum = max.getMaximum();
// get values of y and z at maximum
double[] param = max.getParamValues();
// Print results to a text file
max.print("MaximExampleOutput.txt");
// Output the results to screen
System.out.println("Maximum = " + max.getMaximum());
System.out.println("Value of x at the maximum = " + param[0]);
System.out.println("Value of y at the maximum = " + param[1]);
}
}
| Java |
import java.util.StringTokenizer;
import java.util.Random;
public class Benford {
public file inFile, outFile;
public int[][] digitTallies;
public double[] factors = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0}; // last one placeholder
public int skipLines, dataColumn;
public StringTokenizer st;
public Random r;
public Benford(String[] args) {
r=new Random();
try {
skipLines = Integer.parseInt(args[1]);
dataColumn = Integer.parseInt(args[2]);
digitTallies = new int[10][factors.length];
o("datacolumn: " + dataColumn + " skiplines: " + skipLines );
// set all digit tallies to zero
for (int i=0; i<factors.length; i++) {
for (int j=0; j<10; j++) {
digitTallies[j][i]=0;
}
}
inFile = new file(args[0]);
inFile.initRead();
String line = "";
for (int i=0; i<skipLines; i++) line=inFile.readLine();
o("made it here 2");
while ((line=inFile.readLine())!=null) {
String numString = "";
st = new StringTokenizer(line);
for (int j=0; j<dataColumn; j++) {
numString = st.nextToken();
}
//o("numstring: " + numString);
for (int i=0; i<factors.length; i++) {
double theNumber = Double.parseDouble(numString);
if (theNumber!=0.0) {
//o("thenumber " + theNumber);
if (i==factors.length-1) factors[9]=1+r.nextInt(9);
theNumber = theNumber*factors[i];
int theDigit = getDigit(theNumber);
digitTallies[theDigit][i]++;
}
}
}
o("made it here 3");
// we have the tallies -- lets generate a nice data file
outFile = new file("benford_results.txt");
outFile.initWrite(false);
for (int j=0; j<10; j++) {
line = "";
for (int i=0; i<factors.length; i++) {
line += digitTallies[j][i]+"\t";
}
outFile.write(line+"\n");
}
outFile.closeWrite();
// done?
}
catch (Exception e) {
o("Format: java Benford filename.ext numLinesToSkip dataColumn_start_with_1");
e.printStackTrace();
}
}
public int getDigit(double d) {
while (d<=1.0) d*=10.0;
while (d>=10.0) d/=10.0;
return (int)(Math.floor(d));
}
public static final void main(String[] args) {
Benford b = new Benford(args);
}
public static void o(String s) {
System.out.println(s);
}
} | Java |
/*
* Class Fmath
*
* USAGE: Mathematical class that supplements java.lang.Math and contains:
* the main physical constants
* trigonemetric functions absent from java.lang.Math
* some useful additional mathematical functions
* some conversion functions
*
* WRITTEN BY: Dr Michael Thomas Flanagan
*
* DATE: June 2002
* AMENDED: 6 January 2006, 12 April 2006, 5 May 2006, 28 July 2006, 27 December 2006,
* 29 March 2007, 29 April 2007
*
* DOCUMENTATION:
* See Michael Thomas Flanagan's Java library on-line web pages:
* http://www.ee.ucl.ac.uk/~mflanaga/java/
* http://www.ee.ucl.ac.uk/~mflanaga/java/Fmath.html
*
* Copyright (c) june 2002, April 2007
*
* PERMISSION TO COPY:
* Permission to use, copy and modify this software and its documentation for
* NON-COMMERCIAL purposes is granted, without fee, provided that an acknowledgement
* to the author, Michael Thomas Flanagan at www.ee.ucl.ac.uk/~mflanaga, appears in all copies.
*
* Dr Michael Thomas Flanagan makes no representations about the suitability
* or fitness of the software for any or for a particular purpose.
* Michael Thomas Flanagan shall not be liable for any damages suffered
* as a result of using, modifying or distributing this software or its derivatives.
*
***************************************************************************************/
import java.util.Vector;
public class Fmath{
// PHYSICAL CONSTANTS
public static final double N_AVAGADRO = 6.0221419947e23; /* mol^-1 */
public static final double K_BOLTZMANN = 1.380650324e-23; /* J K^-1 */
public static final double H_PLANCK = 6.6260687652e-34; /* J s */
public static final double H_PLANCK_RED = H_PLANCK/(2*Math.PI); /* J s */
public static final double C_LIGHT = 2.99792458e8; /* m s^-1 */
public static final double R_GAS = 8.31447215; /* J K^-1 mol^-1 */
public static final double F_FARADAY = 9.6485341539e4; /* C mol^-1 */
public static final double T_ABS = -273.15; /* Celsius */
public static final double Q_ELECTRON = -1.60217646263e-19; /* C */
public static final double M_ELECTRON = 9.1093818872e-31; /* kg */
public static final double M_PROTON = 1.6726215813e-27; /* kg */
public static final double M_NEUTRON = 1.6749271613e-27; /* kg */
public static final double EPSILON_0 = 8.854187817e-12; /* F m^-1 */
public static final double MU_0 = Math.PI*4e-7; /* H m^-1 (N A^-2) */
// MATHEMATICAL CONSTANTS
public static final double EULER_CONSTANT_GAMMA = 0.5772156649015627;
public static final double PI = Math.PI; /* 3.141592653589793D */
public static final double E = Math.E; /* 2.718281828459045D */
// METHODS
// LOGARITHMS
// Log to base 10 of a double number
public static double log10(double a){
return Math.log(a)/Math.log(10.0D);
}
// Log to base 10 of a float number
public static float log10(float a){
return (float) (Math.log((double)a)/Math.log(10.0D));
}
// Base 10 antilog of a double
public static double antilog10(double x){
return Math.pow(10.0D, x);
}
// Base 10 antilog of a float
public static float antilog10(float x){
return (float)Math.pow(10.0D, (double)x);
}
// Log to base e of a double number
public static double log(double a){
return Math.log(a);
}
// Log to base e of a float number
public static float log(float a){
return (float)Math.log((double)a);
}
// Base e antilog of a double
public static double antilog(double x){
return Math.exp(x);
}
// Base e antilog of a float
public static float antilog(float x){
return (float)Math.exp((double)x);
}
// Log to base 2 of a double number
public static double log2(double a){
return Math.log(a)/Math.log(2.0D);
}
// Log to base 2 of a float number
public static float log2(float a){
return (float) (Math.log((double)a)/Math.log(2.0D));
}
// Base 2 antilog of a double
public static double antilog2(double x){
return Math.pow(2.0D, x);
}
// Base 2 antilog of a float
public static float antilog2(float x){
return (float)Math.pow(2.0D, (double)x);
}
// Log to base b of a double number and double base
public static double log10(double a, double b){
return Math.log(a)/Math.log(b);
}
// Log to base b of a double number and int base
public static double log10(double a, int b){
return Math.log(a)/Math.log((double)b);
}
// Log to base b of a float number and flaot base
public static float log10(float a, float b){
return (float) (Math.log((double)a)/Math.log((double)b));
}
// Log to base b of a float number and int base
public static float log10(float a, int b){
return (float) (Math.log((double)a)/Math.log((double)b));
}
// Square of a double number
public static double square(double a){
return a*a;
}
// Square of a float number
public static float square(float a){
return a*a;
}
// Square of an int number
public static int square(int a){
return a*a;
}
// factorial of n
// argument and return are integer, therefore limited to 0<=n<=12
// see below for long and double arguments
public static int factorial(int n){
if(n<0)throw new IllegalArgumentException("n must be a positive integer");
if(n>12)throw new IllegalArgumentException("n must less than 13 to avoid integer overflow\nTry long or double argument");
int f = 1;
for(int i=2; i<=n; i++)f*=i;
return f;
}
// factorial of n
// argument and return are long, therefore limited to 0<=n<=20
// see below for double argument
public static long factorial(long n){
if(n<0)throw new IllegalArgumentException("n must be a positive integer");
if(n>20)throw new IllegalArgumentException("n must less than 21 to avoid long integer overflow\nTry double argument");
long f = 1;
long iCount = 2L;
while(iCount<=n){
f*=iCount;
iCount += 1L;
}
return f;
}
// factorial of n
// Argument is of type double but must be, numerically, an integer
// factorial returned as double but is, numerically, should be an integer
// numerical rounding may makes this an approximation after n = 21
public static double factorial(double n){
if(n<0 || (n-Math.floor(n))!=0)throw new IllegalArgumentException("\nn must be a positive integer\nIs a Gamma funtion [Fmath.gamma(x)] more appropriate?");
double f = 1.0D;
double iCount = 2.0D;
while(iCount<=n){
f*=iCount;
iCount += 1.0D;
}
return f;
}
// log to base e of the factorial of n
// log[e](factorial) returned as double
// numerical rounding may makes this an approximation
public static double logFactorial(int n){
if(n<0 || (n-(int)n)!=0)throw new IllegalArgumentException("\nn must be a positive integer\nIs a Gamma funtion [Fmath.gamma(x)] more appropriate?");
double f = 0.0D;
for(int i=2; i<=n; i++)f+=Math.log(i);
return f;
}
// log to base e of the factorial of n
// Argument is of type double but must be, numerically, an integer
// log[e](factorial) returned as double
// numerical rounding may makes this an approximation
public static double logFactorial(long n){
if(n<0 || (n-Math.floor(n))!=0)throw new IllegalArgumentException("\nn must be a positive integer\nIs a Gamma funtion [Fmath.gamma(x)] more appropriate?");
double f = 0.0D;
long iCount = 2L;
while(iCount<=n){
f+=Math.log(iCount);
iCount += 1L;
}
return f;
}
// log to base e of the factorial of n
// Argument is of type double but must be, numerically, an integer
// log[e](factorial) returned as double
// numerical rounding may makes this an approximation
public static double logFactorial(double n){
if(n<0 || (n-Math.floor(n))!=0)throw new IllegalArgumentException("\nn must be a positive integer\nIs a Gamma funtion [Fmath.gamma(x)] more appropriate?");
double f = 0.0D;
double iCount = 2.0D;
while(iCount<=n){
f+=Math.log(iCount);
iCount += 1.0D;
}
return f;
}
// Maximum of a 1D array of doubles, aa
public static double maximum(double[] aa){
int n = aa.length;
double aamax=aa[0];
for(int i=1; i<n; i++){
if(aa[i]>aamax)aamax=aa[i];
}
return aamax;
}
// Maximum of a 1D array of floats, aa
public static float maximum(float[] aa){
int n = aa.length;
float aamax=aa[0];
for(int i=1; i<n; i++){
if(aa[i]>aamax)aamax=aa[i];
}
return aamax;
}
// Maximum of a 1D array of ints, aa
public static int maximum(int[] aa){
int n = aa.length;
int aamax=aa[0];
for(int i=1; i<n; i++){
if(aa[i]>aamax)aamax=aa[i];
}
return aamax;
}
// Maximum of a 1D array of longs, aa
public static long maximum(long[] aa){
long n = aa.length;
long aamax=aa[0];
for(int i=1; i<n; i++){
if(aa[i]>aamax)aamax=aa[i];
}
return aamax;
}
// Minimum of a 1D array of doubles, aa
public static double minimum(double[] aa){
int n = aa.length;
double aamin=aa[0];
for(int i=1; i<n; i++){
if(aa[i]<aamin)aamin=aa[i];
}
return aamin;
}
// Minimum of a 1D array of floats, aa
public static float minimum(float[] aa){
int n = aa.length;
float aamin=aa[0];
for(int i=1; i<n; i++){
if(aa[i]<aamin)aamin=aa[i];
}
return aamin;
}
// Minimum of a 1D array of ints, aa
public static int minimum(int[] aa){
int n = aa.length;
int aamin=aa[0];
for(int i=1; i<n; i++){
if(aa[i]<aamin)aamin=aa[i];
}
return aamin;
}
// Minimum of a 1D array of longs, aa
public static long minimum(long[] aa){
long n = aa.length;
long aamin=aa[0];
for(int i=1; i<n; i++){
if(aa[i]<aamin)aamin=aa[i];
}
return aamin;
}
// Reverse the order of the elements of a 1D array of doubles, aa
public static double[] reverseArray(double[] aa){
int n = aa.length;
double[] bb = new double[n];
for(int i=0; i<n; i++){
bb[i] = aa[n-1-i];
}
return bb;
}
// Reverse the order of the elements of a 1D array of floats, aa
public static float[] reverseArray(float[] aa){
int n = aa.length;
float[] bb = new float[n];
for(int i=0; i<n; i++){
bb[i] = aa[n-1-i];
}
return bb;
}
// Reverse the order of the elements of a 1D array of ints, aa
public static int[] reverseArray(int[] aa){
int n = aa.length;
int[] bb = new int[n];
for(int i=0; i<n; i++){
bb[i] = aa[n-1-i];
}
return bb;
}
// Reverse the order of the elements of a 1D array of longs, aa
public static long[] reverseArray(long[] aa){
int n = aa.length;
long[] bb = new long[n];
for(int i=0; i<n; i++){
bb[i] = aa[n-1-i];
}
return bb;
}
// Reverse the order of the elements of a 1D array of char, aa
public static char[] reverseArray(char[] aa){
int n = aa.length;
char[] bb = new char[n];
for(int i=0; i<n; i++){
bb[i] = aa[n-1-i];
}
return bb;
}
// return absolute values of an array of doubles
public static double[] arrayAbs(double[] aa){
int n = aa.length;
double[] bb = new double[n];
for(int i=0; i<n; i++){
bb[i] = Math.abs(aa[i]);
}
return bb;
}
// return absolute values of an array of floats
public static float[] arrayAbs(float[] aa){
int n = aa.length;
float[] bb = new float[n];
for(int i=0; i<n; i++){
bb[i] = Math.abs(aa[i]);
}
return bb;
}
// return absolute values of an array of long
public static long[] arrayAbs(long[] aa){
int n = aa.length;
long[] bb = new long[n];
for(int i=0; i<n; i++){
bb[i] = Math.abs(aa[i]);
}
return bb;
}
// return absolute values of an array of int
public static int[] arrayAbs(int[] aa){
int n = aa.length;
int[] bb = new int[n];
for(int i=0; i<n; i++){
bb[i] = Math.abs(aa[i]);
}
return bb;
}
// multiple all elements by a constant double[] by double -> double[]
public static double[] arrayMultByConstant(double[] aa, double constant){
int n = aa.length;
double[] bb = new double[n];
for(int i=0; i<n; i++){
bb[i] = aa[i]*constant;
}
return bb;
}
// multiple all elements by a constant int[] by double -> double[]
public static double[] arrayMultByConstant(int[] aa, double constant){
int n = aa.length;
double[] bb = new double[n];
for(int i=0; i<n; i++){
bb[i] = (double)aa[i]*constant;
}
return bb;
}
// multiple all elements by a constant double[] by int -> double[]
public static double[] arrayMultByConstant(double[] aa, int constant){
int n = aa.length;
double[] bb = new double[n];
for(int i=0; i<n; i++){
bb[i] = aa[i]*(double)constant;
}
return bb;
}
// multiple all elements by a constant int[] by int -> double[]
public static double[] arrayMultByConstant(int[] aa, int constant){
int n = aa.length;
double[] bb = new double[n];
for(int i=0; i<n; i++){
bb[i] = (double)(aa[i]*constant);
}
return bb;
}
// finds the value of nearest element value in array to the argument value
public static double nearestElementValue(double[] array, double value){
double diff = Math.abs(array[0] - value);
double nearest = array[0];
for(int i=1; i<array.length; i++){
if(Math.abs(array[i] - value)<diff){
diff = Math.abs(array[i] - value);
nearest = array[i];
}
}
return nearest;
}
// finds the index of nearest element value in array to the argument value
public static int nearestElementIndex(double[] array, double value){
double diff = Math.abs(array[0] - value);
int nearest = 0;
for(int i=1; i<array.length; i++){
if(Math.abs(array[i] - value)<diff){
diff = Math.abs(array[i] - value);
nearest = i;
}
}
return nearest;
}
// finds the value of nearest lower element value in array to the argument value
public static double nearestLowerElementValue(double[] array, double value){
double diff0 = 0.0D;
double diff1 = 0.0D;
double nearest = 0.0D;
int ii = 0;
boolean test = true;
double min = array[0];
while(test){
if(array[ii]<min)min = array[ii];
if((value - array[ii])>=0.0D){
diff0 = value - array[ii];
nearest = array[ii];
test = false;
}
else{
ii++;
if(ii>array.length-1){
nearest = min;
diff0 = min - value;
test = false;
}
}
}
for(int i=0; i<array.length; i++){
diff1 = value - array[i];
if(diff1>=0.0D && diff1<diff0 ){
diff0 = diff1;
nearest = array[i];
}
}
return nearest;
}
// finds the index of nearest lower element value in array to the argument value
public static int nearestLowerElementIndex(double[] array, double value){
double diff0 = 0.0D;
double diff1 = 0.0D;
int nearest = 0;
int ii = 0;
boolean test = true;
double min = array[0];
int minI = 0;
while(test){
if(array[ii]<min){
min = array[ii];
minI = ii;
}
if((value - array[ii])>=0.0D){
diff0 = value - array[ii];
nearest = ii;
test = false;
}
else{
ii++;
if(ii>array.length-1){
nearest = minI;
diff0 = min - value;
test = false;
}
}
}
for(int i=0; i<array.length; i++){
diff1 = value - array[i];
if(diff1>=0.0D && diff1<diff0 ){
diff0 = diff1;
nearest = i;
}
}
return nearest;
}
// finds the value of nearest higher element value in array to the argument value
public static double nearestHigherElementValue(double[] array, double value){
double diff0 = 0.0D;
double diff1 = 0.0D;
double nearest = 0.0D;
int ii = 0;
boolean test = true;
double max = array[0];
while(test){
if(array[ii]>max)max = array[ii];
if((array[ii] - value )>=0.0D){
diff0 = value - array[ii];
nearest = array[ii];
test = false;
}
else{
ii++;
if(ii>array.length-1){
nearest = max;
diff0 = value - max;
test = false;
}
}
}
for(int i=0; i<array.length; i++){
diff1 = array[i]- value;
if(diff1>=0.0D && diff1<diff0 ){
diff0 = diff1;
nearest = array[i];
}
}
return nearest;
}
// finds the index of nearest higher element value in array to the argument value
public static int nearestHigherElementIndex(double[] array, double value){
double diff0 = 0.0D;
double diff1 = 0.0D;
int nearest = 0;
int ii = 0;
boolean test = true;
double max = array[0];
int maxI = 0;
while(test){
if(array[ii]>max){
max = array[ii];
maxI = ii;
}
if((array[ii] - value )>=0.0D){
diff0 = value - array[ii];
nearest = ii;
test = false;
}
else{
ii++;
if(ii>array.length-1){
nearest = maxI;
diff0 = value - max;
test = false;
}
}
}
for(int i=0; i<array.length; i++){
diff1 = array[i]- value;
if(diff1>=0.0D && diff1<diff0 ){
diff0 = diff1;
nearest = i;
}
}
return nearest;
}
// finds the value of nearest element value in array to the argument value
public static int nearestElementValue(int[] array, int value){
int diff = (int) Math.abs(array[0] - value);
int nearest = array[0];
for(int i=1; i<array.length; i++){
if((int) Math.abs(array[i] - value)<diff){
diff = (int)Math.abs(array[i] - value);
nearest = array[i];
}
}
return nearest;
}
// finds the index of nearest element value in array to the argument value
public static int nearestElementIndex(int[] array, int value){
int diff = (int) Math.abs(array[0] - value);
int nearest = 0;
for(int i=1; i<array.length; i++){
if((int) Math.abs(array[i] - value)<diff){
diff = (int)Math.abs(array[i] - value);
nearest = i;
}
}
return nearest;
}
// finds the value of nearest lower element value in array to the argument value
public static int nearestLowerElementValue(int[] array, int value){
int diff0 = 0;
int diff1 = 0;
int nearest = 0;
int ii = 0;
boolean test = true;
int min = array[0];
while(test){
if(array[ii]<min)min = array[ii];
if((value - array[ii])>=0){
diff0 = value - array[ii];
nearest = array[ii];
test = false;
}
else{
ii++;
if(ii>array.length-1){
nearest = min;
diff0 = min - value;
test = false;
}
}
}
for(int i=0; i<array.length; i++){
diff1 = value - array[i];
if(diff1>=0 && diff1<diff0 ){
diff0 = diff1;
nearest = array[i];
}
}
return nearest;
}
// finds the index of nearest lower element value in array to the argument value
public static int nearestLowerElementIndex(int[] array, int value){
int diff0 = 0;
int diff1 = 0;
int nearest = 0;
int ii = 0;
boolean test = true;
int min = array[0];
int minI = 0;
while(test){
if(array[ii]<min){
min = array[ii];
minI = ii;
}
if((value - array[ii])>=0){
diff0 = value - array[ii];
nearest = ii;
test = false;
}
else{
ii++;
if(ii>array.length-1){
nearest = minI;
diff0 = min - value;
test = false;
}
}
}
for(int i=0; i<array.length; i++){
diff1 = value - array[i];
if(diff1>=0 && diff1<diff0 ){
diff0 = diff1;
nearest = i;
}
}
return nearest;
}
// finds the value of nearest higher element value in array to the argument value
public static int nearestHigherElementValue(int[] array, int value){
int diff0 = 0;
int diff1 = 0;
int nearest = 0;
int ii = 0;
boolean test = true;
int max = array[0];
while(test){
if(array[ii]>max)max = array[ii];
if((array[ii] - value )>=0){
diff0 = value - array[ii];
nearest = array[ii];
test = false;
}
else{
ii++;
if(ii>array.length-1){
nearest = max;
diff0 = value - max;
test = false;
}
}
}
for(int i=0; i<array.length; i++){
diff1 = array[i]- value;
if(diff1>=0 && diff1<diff0 ){
diff0 = diff1;
nearest = array[i];
}
}
return nearest;
}
// finds the index of nearest higher element value in array to the argument value
public static int nearestHigherElementIndex(int[] array, int value){
int diff0 = 0;
int diff1 = 0;
int nearest = 0;
int ii = 0;
boolean test = true;
int max = array[0];
int maxI = 0;
while(test){
if(array[ii]>max){
max = array[ii];
maxI = ii;
}
if((array[ii] - value )>=0){
diff0 = value - array[ii];
nearest = ii;
test = false;
}
else{
ii++;
if(ii>array.length-1){
nearest = maxI;
diff0 = value - max;
test = false;
}
}
}
for(int i=0; i<array.length; i++){
diff1 = array[i]- value;
if(diff1>=0 && diff1<diff0 ){
diff0 = diff1;
nearest = i;
}
}
return nearest;
}
// Sum of all array elements - double array
public static double arraySum(double[]array){
double sum = 0.0D;
for(double i:array)sum += i;
return sum;
}
// Sum of all array elements - float array
public static float arraySum(float[]array){
float sum = 0.0F;
for(float i:array)sum += i;
return sum;
}
// Sum of all array elements - int array
public static int arraySum(int[]array){
int sum = 0;
for(int i:array)sum += i;
return sum;
}
// Sum of all array elements - long array
public static long arraySum(long[]array){
long sum = 0L;
for(long i:array)sum += i;
return sum;
}
// Product of all array elements - double array
public static double arrayProduct(double[]array){
double product = 1.0D;
for(double i:array)product *= i;
return product;
}
// Product of all array elements - float array
public static float arrayProduct(float[]array){
float product = 1.0F;
for(float i:array)product *= i;
return product;
}
// Product of all array elements - int array
public static int arrayProduct(int[]array){
int product = 1;
for(int i:array)product *= i;
return product;
}
// Product of all array elements - long array
public static long arrayProduct(long[]array){
long product = 1L;
for(long i:array)product *= i;
return product;
}
// Concatenate two double arrays
public static double[] concatenate(double[] aa, double[] bb){
int aLen = aa.length;
int bLen = bb.length;
int cLen = aLen + bLen;
double[] cc = new double[cLen];
for(int i=0; i<aLen; i++)cc[i] = aa[i];
for(int i=0; i<bLen; i++)cc[i+aLen] = bb[i];
return cc;
}
// Concatenate two float arrays
public static float[] concatenate(float[] aa, float[] bb){
int aLen = aa.length;
int bLen = bb.length;
int cLen = aLen + bLen;
float[] cc = new float[cLen];
for(int i=0; i<aLen; i++)cc[i] = aa[i];
for(int i=0; i<bLen; i++)cc[i+aLen] = bb[i];
return cc;
}
// Concatenate two int arrays
public static int[] concatenate(int[] aa, int[] bb){
int aLen = aa.length;
int bLen = bb.length;
int cLen = aLen + bLen;
int[] cc = new int[cLen];
for(int i=0; i<aLen; i++)cc[i] = aa[i];
for(int i=0; i<bLen; i++)cc[i+aLen] = bb[i];
return cc;
}
// Concatenate two long arrays
public static long[] concatenate(long[] aa, long[] bb){
int aLen = aa.length;
int bLen = bb.length;
int cLen = aLen + bLen;
long[] cc = new long[cLen];
for(int i=0; i<aLen; i++)cc[i] = aa[i];
for(int i=0; i<bLen; i++)cc[i+aLen] = bb[i];
return cc;
}
// recast an array of float as doubles
public static double[] floatTOdouble(float[] aa){
int n = aa.length;
double[] bb = new double[n];
for(int i=0; i<n; i++){
bb[i] = (double)aa[i];
}
return bb;
}
// recast an array of int as double
public static double[] intTOdouble(int[] aa){
int n = aa.length;
double[] bb = new double[n];
for(int i=0; i<n; i++){
bb[i] = (double)aa[i];
}
return bb;
}
// recast an array of int as float
public static float[] intTOfloat(int[] aa){
int n = aa.length;
float[] bb = new float[n];
for(int i=0; i<n; i++){
bb[i] = (float)aa[i];
}
return bb;
}
// recast an array of int as long
public static long[] intTOlong(int[] aa){
int n = aa.length;
long[] bb = new long[n];
for(int i=0; i<n; i++){
bb[i] = (long)aa[i];
}
return bb;
}
// recast an array of long as double
// BEWARE POSSIBLE LOSS OF PRECISION
public static double[] longTOdouble(long[] aa){
int n = aa.length;
double[] bb = new double[n];
for(int i=0; i<n; i++){
bb[i] = (double)aa[i];
}
return bb;
}
// recast an array of long as float
// BEWARE POSSIBLE LOSS OF PRECISION
public static float[] longTOfloat(long[] aa){
int n = aa.length;
float[] bb = new float[n];
for(int i=0; i<n; i++){
bb[i] = (float)aa[i];
}
return bb;
}
// recast an array of short as double
public static double[] shortTOdouble(short[] aa){
int n = aa.length;
double[] bb = new double[n];
for(int i=0; i<n; i++){
bb[i] = (double)aa[i];
}
return bb;
}
// recast an array of short as float
public static float[] shortTOfloat(short[] aa){
int n = aa.length;
float[] bb = new float[n];
for(int i=0; i<n; i++){
bb[i] = (float)aa[i];
}
return bb;
}
// recast an array of short as long
public static long[] shortTOlong(short[] aa){
int n = aa.length;
long[] bb = new long[n];
for(int i=0; i<n; i++){
bb[i] = (long)aa[i];
}
return bb;
}
// recast an array of short as int
public static int[] shortTOint(short[] aa){
int n = aa.length;
int[] bb = new int[n];
for(int i=0; i<n; i++){
bb[i] = (int)aa[i];
}
return bb;
}
// recast an array of byte as double
public static double[] byteTOdouble(byte[] aa){
int n = aa.length;
double[] bb = new double[n];
for(int i=0; i<n; i++){
bb[i] = (int)aa[i];
}
return bb;
}
// recast an array of byte as float
public static float[] byteTOfloat(byte[] aa){
int n = aa.length;
float[] bb = new float[n];
for(int i=0; i<n; i++){
bb[i] = (float)aa[i];
}
return bb;
}
// recast an array of byte as long
public static long[] byteTOlong(byte[] aa){
int n = aa.length;
long[] bb = new long[n];
for(int i=0; i<n; i++){
bb[i] = (long)aa[i];
}
return bb;
}
// recast an array of byte as int
public static int[] byteTOint(byte[] aa){
int n = aa.length;
int[] bb = new int[n];
for(int i=0; i<n; i++){
bb[i] = (int)aa[i];
}
return bb;
}
// recast an array of byte as short
public static short[] byteTOshort(byte[] aa){
int n = aa.length;
short[] bb = new short[n];
for(int i=0; i<n; i++){
bb[i] = (short)aa[i];
}
return bb;
}
// recast an array of double as int
// BEWARE OF LOSS OF PRECISION
public static int[] doubleTOint(double[] aa){
int n = aa.length;
int[] bb = new int[n];
for(int i=0; i<n; i++){
bb[i] = (int)aa[i];
}
return bb;
}
// print an array of doubles to screen
// No line returns except at the end
public static void print(double[] aa){
for(int i=0; i<aa.length; i++){
System.out.print(aa[i]+" ");
}
System.out.println();
}
// print an array of doubles to screen
// with line returns
public static void println(double[] aa){
for(int i=0; i<aa.length; i++){
System.out.println(aa[i]+" ");
}
}
// print an array of floats to screen
// No line returns except at the end
public static void print(float[] aa){
for(int i=0; i<aa.length; i++){
System.out.print(aa[i]+" ");
}
System.out.println();
}
// print an array of floats to screen
// with line returns
public static void println(float[] aa){
for(int i=0; i<aa.length; i++){
System.out.println(aa[i]+" ");
}
}
// print an array of ints to screen
// No line returns except at the end
public static void print(int[] aa){
for(int i=0; i<aa.length; i++){
System.out.print(aa[i]+" ");
}
System.out.println();
}
// print an array of ints to screen
// with line returns
public static void println(int[] aa){
for(int i=0; i<aa.length; i++){
System.out.println(aa[i]+" ");
}
}
// print an array of longs to screen
// No line returns except at the end
public static void print(long[] aa){
for(int i=0; i<aa.length; i++){
System.out.print(aa[i]+" ");
}
System.out.println();
}
// print an array of longs to screen
// with line returns
public static void println(long[] aa){
for(int i=0; i<aa.length; i++){
System.out.println(aa[i]+" ");
}
}
// print an array of char to screen
// No line returns except at the end
public static void print(char[] aa){
for(int i=0; i<aa.length; i++){
System.out.print(aa[i]+" ");
}
System.out.println();
}
// print an array of char to screen
// with line returns
public static void println(char[] aa){
for(int i=0; i<aa.length; i++){
System.out.println(aa[i]+" ");
}
}
// print an array of String to screen
// No line returns except at the end
public static void print(String[] aa){
for(int i=0; i<aa.length; i++){
System.out.print(aa[i]+" ");
}
System.out.println();
}
// print an array of Strings to screen
// with line returns
public static void println(String[] aa){
for(int i=0; i<aa.length; i++){
System.out.println(aa[i]+" ");
}
}
// sort elements in an array of doubles into ascending order
// using selection sort method
// returns Vector containing the original array, the sorted array
// and an array of the indices of the sorted array
public static Vector<Object> selectSortVector(double[] aa){
int index = 0;
int lastIndex = -1;
int n = aa.length;
double holdb = 0.0D;
int holdi = 0;
double[] bb = new double[n];
int[] indices = new int[n];
for(int i=0; i<n; i++){
bb[i]=aa[i];
indices[i]=i;
}
while(lastIndex != n-1){
index = lastIndex+1;
for(int i=lastIndex+2; i<n; i++){
if(bb[i]<bb[index]){
index=i;
}
}
lastIndex++;
holdb=bb[index];
bb[index]=bb[lastIndex];
bb[lastIndex]=holdb;
holdi=indices[index];
indices[index]=indices[lastIndex];
indices[lastIndex]=holdi;
}
Vector<Object> vec = new Vector<Object>();
vec.addElement(aa);
vec.addElement(bb);
vec.addElement(indices);
return vec;
}
// sort elements in an array of doubles into ascending order
// using selection sort method
public static double[] selectionSort(double[] aa){
int index = 0;
int lastIndex = -1;
int n = aa.length;
double hold = 0.0D;
double[] bb = new double[n];
for(int i=0; i<n; i++){
bb[i]=aa[i];
}
while(lastIndex != n-1){
index = lastIndex+1;
for(int i=lastIndex+2; i<n; i++){
if(bb[i]<bb[index]){
index=i;
}
}
lastIndex++;
hold=bb[index];
bb[index]=bb[lastIndex];
bb[lastIndex]=hold;
}
return bb;
}
// sort elements in an array of floats into ascending order
// using selection sort method
public static float[] selectionSort(float[] aa){
int index = 0;
int lastIndex = -1;
int n = aa.length;
float hold = 0.0F;
float[] bb = new float[n];
for(int i=0; i<n; i++){
bb[i]=aa[i];
}
while(lastIndex != n-1){
index = lastIndex+1;
for(int i=lastIndex+2; i<n; i++){
if(bb[i]<bb[index]){
index=i;
}
}
lastIndex++;
hold=bb[index];
bb[index]=bb[lastIndex];
bb[lastIndex]=hold;
}
return bb;
}
// sort elements in an array of ints into ascending order
// using selection sort method
public static int[] selectionSort(int[] aa){
int index = 0;
int lastIndex = -1;
int n = aa.length;
int hold = 0;
int[] bb = new int[n];
for(int i=0; i<n; i++){
bb[i]=aa[i];
}
while(lastIndex != n-1){
index = lastIndex+1;
for(int i=lastIndex+2; i<n; i++){
if(bb[i]<bb[index]){
index=i;
}
}
lastIndex++;
hold=bb[index];
bb[index]=bb[lastIndex];
bb[lastIndex]=hold;
}
return bb;
}
// sort elements in an array of longs into ascending order
// using selection sort method
public static long[] selectionSort(long[] aa){
int index = 0;
int lastIndex = -1;
int n = aa.length;
long hold = 0L;
long[] bb = new long[n];
for(int i=0; i<n; i++){
bb[i]=aa[i];
}
while(lastIndex != n-1){
index = lastIndex+1;
for(int i=lastIndex+2; i<n; i++){
if(bb[i]<bb[index]){
index=i;
}
}
lastIndex++;
hold=bb[index];
bb[index]=bb[lastIndex];
bb[lastIndex]=hold;
}
return bb;
}
// sort elements in an array of doubles into ascending order
// using selection sort method
// returns Vector containing the original array, the sorted array
// and an array of the indices of the sorted array
public static void selectionSort(double[] aa, double[] bb, int[] indices){
int index = 0;
int lastIndex = -1;
int n = aa.length;
double holdb = 0.0D;
int holdi = 0;
for(int i=0; i<n; i++){
bb[i]=aa[i];
indices[i]=i;
}
while(lastIndex != n-1){
index = lastIndex+1;
for(int i=lastIndex+2; i<n; i++){
if(bb[i]<bb[index]){
index=i;
}
}
lastIndex++;
holdb=bb[index];
bb[index]=bb[lastIndex];
bb[lastIndex]=holdb;
holdi=indices[index];
indices[index]=indices[lastIndex];
indices[lastIndex]=holdi;
}
}
// sort the elements of an array into ascending order with matching switches in an array of the length
// using selection sort method
// array determining the order is the first argument
// matching array is the second argument
// sorted arrays returned as third and fourth arguments resopectively
public static void selectionSort(double[] aa, double[] bb, double[] cc, double[] dd){
int index = 0;
int lastIndex = -1;
int n = aa.length;
int m = bb.length;
if(n!=m)throw new IllegalArgumentException("First argument array, aa, (length = " + n + ") and the second argument array, bb, (length = " + m + ") should be the same length");
int nn = cc.length;
if(nn<n)throw new IllegalArgumentException("The third argument array, cc, (length = " + nn + ") should be at least as long as the first argument array, aa, (length = " + n + ")");
int mm = dd.length;
if(mm<m)throw new IllegalArgumentException("The fourth argument array, dd, (length = " + mm + ") should be at least as long as the second argument array, bb, (length = " + m + ")");
double holdx = 0.0D;
double holdy = 0.0D;
for(int i=0; i<n; i++){
cc[i]=aa[i];
dd[i]=bb[i];
}
while(lastIndex != n-1){
index = lastIndex+1;
for(int i=lastIndex+2; i<n; i++){
if(cc[i]<cc[index]){
index=i;
}
}
lastIndex++;
holdx=cc[index];
cc[index]=cc[lastIndex];
cc[lastIndex]=holdx;
holdy=dd[index];
dd[index]=dd[lastIndex];
dd[lastIndex]=holdy;
}
}
public static void selectionSort(float[] aa, float[] bb, float[] cc, float[] dd){
int index = 0;
int lastIndex = -1;
int n = aa.length;
int m = bb.length;
if(n!=m)throw new IllegalArgumentException("First argument array, aa, (length = " + n + ") and the second argument array, bb, (length = " + m + ") should be the same length");
int nn = cc.length;
if(nn<n)throw new IllegalArgumentException("The third argument array, cc, (length = " + nn + ") should be at least as long as the first argument array, aa, (length = " + n + ")");
int mm = dd.length;
if(mm<m)throw new IllegalArgumentException("The fourth argument array, dd, (length = " + mm + ") should be at least as long as the second argument array, bb, (length = " + m + ")");
float holdx = 0.0F;
float holdy = 0.0F;
for(int i=0; i<n; i++){
cc[i]=aa[i];
dd[i]=bb[i];
}
while(lastIndex != n-1){
index = lastIndex+1;
for(int i=lastIndex+2; i<n; i++){
if(cc[i]<cc[index]){
index=i;
}
}
lastIndex++;
holdx=cc[index];
cc[index]=cc[lastIndex];
cc[lastIndex]=holdx;
holdy=dd[index];
dd[index]=dd[lastIndex];
dd[lastIndex]=holdy;
}
}
public static void selectionSort(long[] aa, long[] bb, long[] cc, long[] dd){
int index = 0;
int lastIndex = -1;
int n = aa.length;
int m = bb.length;
if(n!=m)throw new IllegalArgumentException("First argument array, aa, (length = " + n + ") and the second argument array, bb, (length = " + m + ") should be the same length");
int nn = cc.length;
if(nn<n)throw new IllegalArgumentException("The third argument array, cc, (length = " + nn + ") should be at least as long as the first argument array, aa, (length = " + n + ")");
int mm = dd.length;
if(mm<m)throw new IllegalArgumentException("The fourth argument array, dd, (length = " + mm + ") should be at least as long as the second argument array, bb, (length = " + m + ")");
long holdx = 0L;
long holdy = 0L;
for(int i=0; i<n; i++){
cc[i]=aa[i];
dd[i]=bb[i];
}
while(lastIndex != n-1){
index = lastIndex+1;
for(int i=lastIndex+2; i<n; i++){
if(cc[i]<cc[index]){
index=i;
}
}
lastIndex++;
holdx=cc[index];
cc[index]=cc[lastIndex];
cc[lastIndex]=holdx;
holdy=dd[index];
dd[index]=dd[lastIndex];
dd[lastIndex]=holdy;
}
}
public static void selectionSort(int[] aa, int[] bb, int[] cc, int[] dd){
int index = 0;
int lastIndex = -1;
int n = aa.length;
int m = bb.length;
if(n!=m)throw new IllegalArgumentException("First argument array, aa, (length = " + n + ") and the second argument array, bb, (length = " + m + ") should be the same length");
int nn = cc.length;
if(nn<n)throw new IllegalArgumentException("The third argument array, cc, (length = " + nn + ") should be at least as long as the first argument array, aa, (length = " + n + ")");
int mm = dd.length;
if(mm<m)throw new IllegalArgumentException("The fourth argument array, dd, (length = " + mm + ") should be at least as long as the second argument array, bb, (length = " + m + ")");
int holdx = 0;
int holdy = 0;
for(int i=0; i<n; i++){
cc[i]=aa[i];
dd[i]=bb[i];
}
while(lastIndex != n-1){
index = lastIndex+1;
for(int i=lastIndex+2; i<n; i++){
if(cc[i]<cc[index]){
index=i;
}
}
lastIndex++;
holdx=cc[index];
cc[index]=cc[lastIndex];
cc[lastIndex]=holdx;
holdy=dd[index];
dd[index]=dd[lastIndex];
dd[lastIndex]=holdy;
}
}
public static void selectionSort(double[] aa, long[] bb, double[] cc, long[] dd){
int index = 0;
int lastIndex = -1;
int n = aa.length;
int m = bb.length;
if(n!=m)throw new IllegalArgumentException("First argument array, aa, (length = " + n + ") and the second argument array, bb, (length = " + m + ") should be the same length");
int nn = cc.length;
if(nn<n)throw new IllegalArgumentException("The third argument array, cc, (length = " + nn + ") should be at least as long as the first argument array, aa, (length = " + n + ")");
int mm = dd.length;
if(mm<m)throw new IllegalArgumentException("The fourth argument array, dd, (length = " + mm + ") should be at least as long as the second argument array, bb, (length = " + m + ")");
double holdx = 0.0D;
long holdy = 0L;
for(int i=0; i<n; i++){
cc[i]=aa[i];
dd[i]=bb[i];
}
while(lastIndex != n-1){
index = lastIndex+1;
for(int i=lastIndex+2; i<n; i++){
if(cc[i]<cc[index]){
index=i;
}
}
lastIndex++;
holdx=cc[index];
cc[index]=cc[lastIndex];
cc[lastIndex]=holdx;
holdy=dd[index];
dd[index]=dd[lastIndex];
dd[lastIndex]=holdy;
}
}
public static void selectionSort(long[] aa, double[] bb, long[] cc, double[] dd){
int index = 0;
int lastIndex = -1;
int n = aa.length;
int m = bb.length;
if(n!=m)throw new IllegalArgumentException("First argument array, aa, (length = " + n + ") and the second argument array, bb, (length = " + m + ") should be the same length");
int nn = cc.length;
if(nn<n)throw new IllegalArgumentException("The third argument array, cc, (length = " + nn + ") should be at least as long as the first argument array, aa, (length = " + n + ")");
int mm = dd.length;
if(mm<m)throw new IllegalArgumentException("The fourth argument array, dd, (length = " + mm + ") should be at least as long as the second argument array, bb, (length = " + m + ")");
long holdx = 0L;
double holdy = 0.0D;
for(int i=0; i<n; i++){
cc[i]=aa[i];
dd[i]=bb[i];
}
while(lastIndex != n-1){
index = lastIndex+1;
for(int i=lastIndex+2; i<n; i++){
if(cc[i]<cc[index]){
index=i;
}
}
lastIndex++;
holdx=cc[index];
cc[index]=cc[lastIndex];
cc[lastIndex]=holdx;
holdy=dd[index];
dd[index]=dd[lastIndex];
dd[lastIndex]=holdy;
}
}
public static void selectionSort(double[] aa, int[] bb, double[] cc, int[] dd){
int index = 0;
int lastIndex = -1;
int n = aa.length;
int m = bb.length;
if(n!=m)throw new IllegalArgumentException("First argument array, aa, (length = " + n + ") and the second argument array, bb, (length = " + m + ") should be the same length");
int nn = cc.length;
if(nn<n)throw new IllegalArgumentException("The third argument array, cc, (length = " + nn + ") should be at least as long as the first argument array, aa, (length = " + n + ")");
int mm = dd.length;
if(mm<m)throw new IllegalArgumentException("The fourth argument array, dd, (length = " + mm + ") should be at least as long as the second argument array, bb, (length = " + m + ")");
double holdx = 0.0D;
int holdy = 0;
for(int i=0; i<n; i++){
cc[i]=aa[i];
dd[i]=bb[i];
}
while(lastIndex != n-1){
index = lastIndex+1;
for(int i=lastIndex+2; i<n; i++){
if(cc[i]<cc[index]){
index=i;
}
}
lastIndex++;
holdx=cc[index];
cc[index]=cc[lastIndex];
cc[lastIndex]=holdx;
holdy=dd[index];
dd[index]=dd[lastIndex];
dd[lastIndex]=holdy;
}
}
public static void selectionSort(int[] aa, double[] bb, int[] cc, double[] dd){
int index = 0;
int lastIndex = -1;
int n = aa.length;
int m = bb.length;
if(n!=m)throw new IllegalArgumentException("First argument array, aa, (length = " + n + ") and the second argument array, bb, (length = " + m + ") should be the same length");
int nn = cc.length;
if(nn<n)throw new IllegalArgumentException("The third argument array, cc, (length = " + nn + ") should be at least as long as the first argument array, aa, (length = " + n + ")");
int mm = dd.length;
if(mm<m)throw new IllegalArgumentException("The fourth argument array, dd, (length = " + mm + ") should be at least as long as the second argument array, bb, (length = " + m + ")");
int holdx = 0;
double holdy = 0.0D;
for(int i=0; i<n; i++){
cc[i]=aa[i];
dd[i]=bb[i];
}
while(lastIndex != n-1){
index = lastIndex+1;
for(int i=lastIndex+2; i<n; i++){
if(cc[i]<cc[index]){
index=i;
}
}
lastIndex++;
holdx=cc[index];
cc[index]=cc[lastIndex];
cc[lastIndex]=holdx;
holdy=dd[index];
dd[index]=dd[lastIndex];
dd[lastIndex]=holdy;
}
}
public static void selectionSort(long[] aa, int[] bb, long[] cc, int[] dd){
int index = 0;
int lastIndex = -1;
int n = aa.length;
int m = bb.length;
if(n!=m)throw new IllegalArgumentException("First argument array, aa, (length = " + n + ") and the second argument array, bb, (length = " + m + ") should be the same length");
int nn = cc.length;
if(nn<n)throw new IllegalArgumentException("The third argument array, cc, (length = " + nn + ") should be at least as long as the first argument array, aa, (length = " + n + ")");
int mm = dd.length;
if(mm<m)throw new IllegalArgumentException("The fourth argument array, dd, (length = " + mm + ") should be at least as long as the second argument array, bb, (length = " + m + ")");
long holdx = 0L;
int holdy = 0;
for(int i=0; i<n; i++){
cc[i]=aa[i];
dd[i]=bb[i];
}
while(lastIndex != n-1){
index = lastIndex+1;
for(int i=lastIndex+2; i<n; i++){
if(cc[i]<cc[index]){
index=i;
}
}
lastIndex++;
holdx=cc[index];
cc[index]=cc[lastIndex];
cc[lastIndex]=holdx;
holdy=dd[index];
dd[index]=dd[lastIndex];
dd[lastIndex]=holdy;
}
}
public static void selectionSort(int[] aa, long[] bb, int[] cc, long[] dd){
int index = 0;
int lastIndex = -1;
int n = aa.length;
int m = bb.length;
if(n!=m)throw new IllegalArgumentException("First argument array, aa, (length = " + n + ") and the second argument array, bb, (length = " + m + ") should be the same length");
int nn = cc.length;
if(nn<n)throw new IllegalArgumentException("The third argument array, cc, (length = " + nn + ") should be at least as long as the first argument array, aa, (length = " + n + ")");
int mm = dd.length;
if(mm<m)throw new IllegalArgumentException("The fourth argument array, dd, (length = " + mm + ") should be at least as long as the second argument array, bb, (length = " + m + ")");
int holdx = 0;
long holdy = 0L;
for(int i=0; i<n; i++){
cc[i]=aa[i];
dd[i]=bb[i];
}
while(lastIndex != n-1){
index = lastIndex+1;
for(int i=lastIndex+2; i<n; i++){
if(cc[i]<cc[index]){
index=i;
}
}
lastIndex++;
holdx=cc[index];
cc[index]=cc[lastIndex];
cc[lastIndex]=holdx;
holdy=dd[index];
dd[index]=dd[lastIndex];
dd[lastIndex]=holdy;
}
}
// sort elements in an array of doubles (first argument) into ascending order
// using selection sort method
// returns the sorted array as second argument
// and an array of the indices of the sorted array as the third argument
public static void selectSort(double[] aa, double[] bb, int[] indices){
int index = 0;
int lastIndex = -1;
int n = aa.length;
int m = bb.length;
if(m<n)throw new IllegalArgumentException("The second argument array, bb, (length = " + m + ") should be at least as long as the first argument array, aa, (length = " + n + ")");
int k = indices.length;
if(m<n)throw new IllegalArgumentException("The third argument array, indices, (length = " + k + ") should be at least as long as the first argument array, aa, (length = " + n + ")");
double holdb = 0.0D;
int holdi = 0;
for(int i=0; i<n; i++){
bb[i]=aa[i];
indices[i]=i;
}
while(lastIndex != n-1){
index = lastIndex+1;
for(int i=lastIndex+2; i<n; i++){
if(bb[i]<bb[index]){
index=i;
}
}
lastIndex++;
holdb=bb[index];
bb[index]=bb[lastIndex];
bb[lastIndex]=holdb;
holdi=indices[index];
indices[index]=indices[lastIndex];
indices[lastIndex]=holdi;
}
}
/* returns -1 if x < 0 else returns 1 */
// double version
public static double sign(double x){
if (x<0.0){
return -1.0;
}
else{
return 1.0;
}
}
/* returns -1 if x < 0 else returns 1 */
// float version
public static float sign(float x){
if (x<0.0F){
return -1.0F;
}
else{
return 1.0F;
}
}
/* returns -1 if x < 0 else returns 1 */
// int version
public static int sign(int x){
if (x<0){
return -1;
}
else{
return 1;
}
}
/* returns -1 if x < 0 else returns 1 */
// long version
public static long sign(long x){
if (x<0){
return -1;
}
else{
return 1;
}
}
// UNIT CONVERSIONS
// Converts radians to degrees
public static double radToDeg(double rad){
return rad*180.0D/Math.PI;
}
// Converts degrees to radians
public static double degToRad(double deg){
return deg*Math.PI/180.0D;
}
// Converts electron volts(eV) to corresponding wavelength in nm
public static double evToNm(double ev){
return 1e+9*C_LIGHT/(-ev*Q_ELECTRON/H_PLANCK);
}
// Converts wavelength in nm to matching energy in eV
public static double nmToEv(double nm)
{
return C_LIGHT/(-nm*1e-9)*H_PLANCK/Q_ELECTRON;
}
// Converts moles per litre to percentage weight by volume
public static double molarToPercentWeightByVol(double molar, double molWeight){
return molar*molWeight/10.0D;
}
// Converts percentage weight by volume to moles per litre
public static double percentWeightByVolToMolar(double perCent, double molWeight){
return perCent*10.0D/molWeight;
}
// Converts Celsius to Kelvin
public static double celsiusToKelvin(double cels){
return cels-T_ABS;
}
// Converts Kelvin to Celsius
public static double kelvinToCelsius(double kelv){
return kelv+T_ABS;
}
// Converts Celsius to Fahrenheit
public static double celsiusToFahren(double cels){
return cels*(9.0/5.0)+32.0;
}
// Converts Fahrenheit to Celsius
public static double fahrenToCelsius(double fahr){
return (fahr-32.0)*5.0/9.0;
}
// Converts calories to Joules
public static double calorieToJoule(double cal){
return cal*4.1868;
}
// Converts Joules to calories
public static double jouleToCalorie(double joule){
return joule*0.23884;
}
// Converts grams to ounces
public static double gramToOunce(double gm){
return gm/28.3459;
}
// Converts ounces to grams
public static double ounceToGram(double oz){
return oz*28.3459;
}
// Converts kilograms to pounds
public static double kgToPound(double kg){
return kg/0.4536;
}
// Converts pounds to kilograms
public static double poundToKg(double pds){
return pds*0.4536;
}
// Converts kilograms to tons
public static double kgToTon(double kg){
return kg/1016.05;
}
// Converts tons to kilograms
public static double tonToKg(double tons){
return tons*1016.05;
}
// Converts millimetres to inches
public static double millimetreToInch(double mm){
return mm/25.4;
}
// Converts inches to millimetres
public static double inchToMillimetre(double in){
return in*25.4;
}
// Converts feet to metres
public static double footToMetre(double ft){
return ft*0.3048;
}
// Converts metres to feet
public static double metreToFoot(double metre){
return metre/0.3048;
}
// Converts yards to metres
public static double yardToMetre(double yd){
return yd*0.9144;
}
// Converts metres to yards
public static double metreToYard(double metre){
return metre/0.9144;
}
// Converts miles to kilometres
public static double mileToKm(double mile){
return mile*1.6093;
}
// Converts kilometres to miles
public static double kmToMile(double km){
return km/1.6093;
}
// Converts UK gallons to litres
public static double gallonToLitre(double gall){
return gall*4.546;
}
// Converts litres to UK gallons
public static double litreToGallon(double litre){
return litre/4.546;
}
// Converts UK quarts to litres
public static double quartToLitre(double quart){
return quart*1.137;
}
// Converts litres to UK quarts
public static double litreToQuart(double litre){
return litre/1.137;
}
// Converts UK pints to litres
public static double pintToLitre(double pint){
return pint*0.568;
}
// Converts litres to UK pints
public static double litreToPint(double litre){
return litre/0.568;
}
// Converts UK gallons per mile to litres per kilometre
public static double gallonPerMileToLitrePerKm(double gallPmile){
return gallPmile*2.825;
}
// Converts litres per kilometre to UK gallons per mile
public static double litrePerKmToGallonPerMile(double litrePkm){
return litrePkm/2.825;
}
// Converts miles per UK gallons to kilometres per litre
public static double milePerGallonToKmPerLitre(double milePgall){
return milePgall*0.354;
}
// Converts kilometres per litre to miles per UK gallons
public static double kmPerLitreToMilePerGallon(double kmPlitre){
return kmPlitre/0.354;
}
// Converts UK fluid ounce to American fluid ounce
public static double fluidOunceUKtoUS(double flOzUK){
return flOzUK*0.961;
}
// Converts American fluid ounce to UK fluid ounce
public static double fluidOunceUStoUK(double flOzUS){
return flOzUS*1.041;
}
// Converts UK pint to American liquid pint
public static double pintUKtoUS(double pintUK){
return pintUK*1.201;
}
// Converts American liquid pint to UK pint
public static double pintUStoUK(double pintUS){
return pintUS*0.833;
}
// Converts UK quart to American liquid quart
public static double quartUKtoUS(double quartUK){
return quartUK*1.201;
}
// Converts American liquid quart to UK quart
public static double quartUStoUK(double quartUS){
return quartUS*0.833;
}
// Converts UK gallon to American gallon
public static double gallonUKtoUS(double gallonUK){
return gallonUK*1.201;
}
// Converts American gallon to UK gallon
public static double gallonUStoUK(double gallonUS){
return gallonUS*0.833;
}
// Converts UK pint to American cup
public static double pintUKtoCupUS(double pintUK){
return pintUK/0.417;
}
// Converts American cup to UK pint
public static double cupUStoPintUK(double cupUS){
return cupUS*0.417;
}
// Calculates body mass index (BMI) from height (m) and weight (kg)
public static double calcBMImetric(double height, double weight){
return weight/(height*height);
}
// Calculates body mass index (BMI) from height (ft) and weight (lbs)
public static double calcBMIimperial(double height, double weight){
height = Fmath.footToMetre(height);
weight = Fmath.poundToKg(weight);
return weight/(height*height);
}
// Calculates weight (kg) to give a specified BMI for a given height (m)
public static double calcWeightFromBMImetric(double bmi, double height){
return bmi*height*height;
}
// Calculates weight (lbs) to give a specified BMI for a given height (ft)
public static double calcWeightFromBMIimperial(double bmi, double height){
height = Fmath.footToMetre(height);
double weight = bmi*height*height;
weight = Fmath.kgToPound(weight);
return weight;
}
// ADDITIONAL TRIGONOMETRIC FUNCTIONS
// Returns the length of the hypotenuse of a and b
// i.e. sqrt(a*a+b*b) [without unecessary overflow or underflow]
// double version
public static double hypot(double aa, double bb){
double amod=Math.abs(aa);
double bmod=Math.abs(bb);
double cc = 0.0D, ratio = 0.0D;
if(amod==0.0){
cc=bmod;
}
else{
if(bmod==0.0){
cc=amod;
}
else{
if(amod>=bmod){
ratio=bmod/amod;
cc=amod*Math.sqrt(1.0 + ratio*ratio);
}
else{
ratio=amod/bmod;
cc=bmod*Math.sqrt(1.0 + ratio*ratio);
}
}
}
return cc;
}
// Returns the length of the hypotenuse of a and b
// i.e. sqrt(a*a+b*b) [without unecessary overflow or underflow]
// float version
public static float hypot(float aa, float bb){
return (float) hypot((double) aa, (double) bb);
}
// Angle (in radians) subtended at coordinate C
// given x, y coordinates of all apices, A, B and C, of a triangle
public static double angle(double xAtA, double yAtA, double xAtB, double yAtB, double xAtC, double yAtC){
double ccos = Fmath.cos(xAtA, yAtA, xAtB, yAtB, xAtC, yAtC);
return Math.acos(ccos);
}
// Angle (in radians) between sides sideA and sideB given all side lengths of a triangle
public static double angle(double sideAC, double sideBC, double sideAB){
double ccos = Fmath.cos(sideAC, sideBC, sideAB);
return Math.acos(ccos);
}
// Sine of angle subtended at coordinate C
// given x, y coordinates of all apices, A, B and C, of a triangle
public static double sin(double xAtA, double yAtA, double xAtB, double yAtB, double xAtC, double yAtC){
double angle = Fmath.angle(xAtA, yAtA, xAtB, yAtB, xAtC, yAtC);
return Math.sin(angle);
}
// Sine of angle between sides sideA and sideB given all side lengths of a triangle
public static double sin(double sideAC, double sideBC, double sideAB){
double angle = Fmath.angle(sideAC, sideBC, sideAB);
return Math.sin(angle);
}
// Sine given angle in radians
// for completion - returns Math.sin(arg)
public static double sin(double arg){
return Math.sin(arg);
}
// Inverse sine
// Fmath.asin Checks limits - Java Math.asin returns NaN if without limits
public static double asin(double a){
if(a<-1.0D && a>1.0D) throw new IllegalArgumentException("Fmath.asin argument (" + a + ") must be >= -1.0 and <= 1.0");
return Math.asin(a);
}
// Cosine of angle subtended at coordinate C
// given x, y coordinates of all apices, A, B and C, of a triangle
public static double cos(double xAtA, double yAtA, double xAtB, double yAtB, double xAtC, double yAtC){
double sideAC = Fmath.hypot(xAtA - xAtC, yAtA - yAtC);
double sideBC = Fmath.hypot(xAtB - xAtC, yAtB - yAtC);
double sideAB = Fmath.hypot(xAtA - xAtB, yAtA - yAtB);
return Fmath.cos(sideAC, sideBC, sideAB);
}
// Cosine of angle between sides sideA and sideB given all side lengths of a triangle
public static double cos(double sideAC, double sideBC, double sideAB){
return 0.5D*(sideAC/sideBC + sideBC/sideAC - (sideAB/sideAC)*(sideAB/sideBC));
}
// Cosine given angle in radians
// for completion - returns Java Math.cos(arg)
public static double cos(double arg){
return Math.cos(arg);
}
// Inverse cosine
// Fmath.asin Checks limits - Java Math.asin returns NaN if without limits
public static double acos(double a){
if(a<-1.0D || a>1.0D) throw new IllegalArgumentException("Fmath.acos argument (" + a + ") must be >= -1.0 and <= 1.0");
return Math.acos(a);
}
// Tangent of angle subtended at coordinate C
// given x, y coordinates of all apices, A, B and C, of a triangle
public static double tan(double xAtA, double yAtA, double xAtB, double yAtB, double xAtC, double yAtC){
double angle = Fmath.angle(xAtA, yAtA, xAtB, yAtB, xAtC, yAtC);
return Math.tan(angle);
}
// Tangent of angle between sides sideA and sideB given all side lengths of a triangle
public static double tan(double sideAC, double sideBC, double sideAB){
double angle = Fmath.angle(sideAC, sideBC, sideAB);
return Math.tan(angle);
}
// Tangent given angle in radians
// for completion - returns Math.tan(arg)
public static double tan(double arg){
return Math.tan(arg);
}
// Inverse tangent
// for completion - returns Math.atan(arg)
public static double atan(double a){
return Math.atan(a);
}
// Inverse tangent - ratio numerator and denominator provided
// for completion - returns Math.atan2(arg)
public static double atan2(double a, double b){
return Math.atan2(a, b);
}
// Cotangent
public static double cot(double a){
return 1.0D/Math.tan(a);
}
// Inverse cotangent
public static double acot(double a){
return Math.atan(1.0D/a);
}
// Inverse cotangent - ratio numerator and denominator provided
public static double acot2(double a, double b){
return Math.atan2(b, a);
}
// Secant
public static double sec(double a){
return 1.0/Math.cos(a);
}
// Inverse secant
public static double asec(double a){
if(a<1.0D && a>-1.0D) throw new IllegalArgumentException("asec argument (" + a + ") must be >= 1 or <= -1");
return Math.acos(1.0/a);
}
// Cosecant
public static double csc(double a){
return 1.0D/Math.sin(a);
}
// Inverse cosecant
public static double acsc(double a){
if(a<1.0D && a>-1.0D) throw new IllegalArgumentException("acsc argument (" + a + ") must be >= 1 or <= -1");
return Math.asin(1.0/a);
}
// Exsecant
public static double exsec(double a){
return (1.0/Math.cos(a)-1.0D);
}
// Inverse exsecant
public static double aexsec(double a){
if(a<0.0D && a>-2.0D) throw new IllegalArgumentException("aexsec argument (" + a + ") must be >= 0.0 and <= -2");
return Math.asin(1.0D/(1.0D + a));
}
// Versine
public static double vers(double a){
return (1.0D - Math.cos(a));
}
// Inverse versine
public static double avers(double a){
if(a<0.0D && a>2.0D) throw new IllegalArgumentException("avers argument (" + a + ") must be <= 2 and >= 0");
return Math.acos(1.0D - a);
}
// Coversine
public static double covers(double a){
return (1.0D - Math.sin(a));
}
// Inverse coversine
public static double acovers(double a){
if(a<0.0D && a>2.0D) throw new IllegalArgumentException("acovers argument (" + a + ") must be <= 2 and >= 0");
return Math.asin(1.0D - a);
}
// Haversine
public static double hav(double a){
return 0.5D*Fmath.vers(a);
}
// Inverse haversine
public static double ahav(double a){
if(a<0.0D && a>1.0D) throw new IllegalArgumentException("ahav argument (" + a + ") must be >= 0 and <= 1");
return 0.5D*Fmath.vers(a);
}
// Sinc
public static double sinc(double a){
if(Math.abs(a)<1e-40){
return 1.0D;
}
else{
return Math.sin(a)/a;
}
}
//Hyperbolic sine of a double number
public static double sinh(double a){
return 0.5D*(Math.exp(a)-Math.exp(-a));
}
// Inverse hyperbolic sine of a double number
public static double asinh(double a){
double sgn = 1.0D;
if(a<0.0D){
sgn = -1.0D;
a = -a;
}
return sgn*Math.log(a+Math.sqrt(a*a+1.0D));
}
//Hyperbolic cosine of a double number
public static double cosh(double a){
return 0.5D*(Math.exp(a)+Math.exp(-a));
}
// Inverse hyperbolic cosine of a double number
public static double acosh(double a){
if(a<1.0D) throw new IllegalArgumentException("acosh real number argument (" + a + ") must be >= 1");
return Math.log(a+Math.sqrt(a*a-1.0D));
}
//Hyperbolic tangent of a double number
public static double tanh(double a){
return sinh(a)/cosh(a);
}
// Inverse hyperbolic tangent of a double number
public static double atanh(double a){
double sgn = 1.0D;
if(a<0.0D){
sgn = -1.0D;
a = -a;
}
if(a>1.0D) throw new IllegalArgumentException("atanh real number argument (" + sgn*a + ") must be >= -1 and <= 1");
return 0.5D*sgn*(Math.log(1.0D + a)-Math.log(1.0D - a));
}
//Hyperbolic cotangent of a double number
public static double coth(double a){
return 1.0D/tanh(a);
}
// Inverse hyperbolic cotangent of a double number
public static double acoth(double a){
double sgn = 1.0D;
if(a<0.0D){
sgn = -1.0D;
a = -a;
}
if(a<1.0D) throw new IllegalArgumentException("acoth real number argument (" + sgn*a + ") must be <= -1 or >= 1");
return 0.5D*sgn*(Math.log(1.0D + a)-Math.log(a - 1.0D));
}
//Hyperbolic secant of a double number
public static double sech(double a){
return 1.0D/cosh(a);
}
// Inverse hyperbolic secant of a double number
public static double asech(double a){
if(a>1.0D || a<0.0D) throw new IllegalArgumentException("asech real number argument (" + a + ") must be >= 0 and <= 1");
return 0.5D*(Math.log(1.0D/a + Math.sqrt(1.0D/(a*a) - 1.0D)));
}
//Hyperbolic cosecant of a double number
public static double csch(double a){
return 1.0D/sinh(a);
}
// Inverse hyperbolic cosecant of a double number
public static double acsch(double a){
double sgn = 1.0D;
if(a<0.0D){
sgn = -1.0D;
a = -a;
}
return 0.5D*sgn*(Math.log(1.0/a + Math.sqrt(1.0D/(a*a) + 1.0D)));
}
// MANTISSA ROUNDING (TRUNCATING)
// returns a value of xDouble truncated to trunc decimal places
public static double truncate(double xDouble, int trunc){
double xTruncated = xDouble;
if(!Fmath.isNaN(xDouble)){
if(!Fmath.isPlusInfinity(xDouble)){
if(!Fmath.isMinusInfinity(xDouble)){
if(xDouble!=0.0D){
String xString = ((new Double(xDouble)).toString()).trim();
xTruncated = Double.parseDouble(truncateProcedure(xString, trunc));
}
}
}
}
return xTruncated;
}
// returns a value of xFloat truncated to trunc decimal places
public static float truncate(float xFloat, int trunc){
float xTruncated = xFloat;
if(!Fmath.isNaN(xFloat)){
if(!Fmath.isPlusInfinity(xFloat)){
if(!Fmath.isMinusInfinity(xFloat)){
if(xFloat!=0.0D){
String xString = ((new Float(xFloat)).toString()).trim();
xTruncated = Float.parseFloat(truncateProcedure(xString, trunc));
}
}
}
}
return xTruncated;
}
// private method for truncating a float or double expressed as a String
private static String truncateProcedure(String xValue, int trunc){
String xTruncated = xValue;
String xWorking = xValue;
String exponent = " ";
String first = "+";
int expPos = xValue.indexOf('E');
int dotPos = xValue.indexOf('.');
int minPos = xValue.indexOf('-');
if(minPos!=-1){
if(minPos==0){
xWorking = xWorking.substring(1);
first = "-";
dotPos--;
expPos--;
}
}
if(expPos>-1){
exponent = xWorking.substring(expPos);
xWorking = xWorking.substring(0,expPos);
}
String xPreDot = null;
String xPostDot = "0";
String xDiscarded = null;
String tempString = null;
double tempDouble = 0.0D;
if(dotPos>-1){
xPreDot = xWorking.substring(0,dotPos);
xPostDot = xWorking.substring(dotPos+1);
int xLength = xPostDot.length();
if(trunc<xLength){
xDiscarded = xPostDot.substring(trunc);
tempString = xDiscarded.substring(0,1) + ".";
if(xDiscarded.length()>1){
tempString += xDiscarded.substring(1);
}
else{
tempString += "0";
}
tempDouble = Math.round(Double.parseDouble(tempString));
if(trunc>0){
if(tempDouble>=5.0){
int[] xArray = new int[trunc+1];
xArray[0] = 0;
for(int i=0; i<trunc; i++){
xArray[i+1] = Integer.parseInt(xPostDot.substring(i,i+1));
}
boolean test = true;
int iCounter = trunc;
while(test){
xArray[iCounter] += 1;
if(iCounter>0){
if(xArray[iCounter]<10){
test = false;
}
else{
xArray[iCounter]=0;
iCounter--;
}
}
else{
test = false;
}
}
int preInt = Integer.parseInt(xPreDot);
preInt += xArray[0];
xPreDot = (new Integer(preInt)).toString();
tempString = "";
for(int i=1; i<=trunc; i++){
tempString += (new Integer(xArray[i])).toString();
}
xPostDot = tempString;
}
else{
xPostDot = xPostDot.substring(0, trunc);
}
}
else{
if(tempDouble>=5.0){
int preInt = Integer.parseInt(xPreDot);
preInt++;
xPreDot = (new Integer(preInt)).toString();
}
xPostDot = "0";
}
}
xTruncated = first + xPreDot.trim() + "." + xPostDot.trim() + exponent;
}
return xTruncated.trim();
}
// Returns true if x is infinite, i.e. is equal to either plus or minus infinity
// x is double
public static boolean isInfinity(double x){
boolean test=false;
if(x==Double.POSITIVE_INFINITY || x==Double.NEGATIVE_INFINITY)test=true;
return test;
}
// Returns true if x is infinite, i.e. is equal to either plus or minus infinity
// x is float
public static boolean isInfinity(float x){
boolean test=false;
if(x==Float.POSITIVE_INFINITY || x==Float.NEGATIVE_INFINITY)test=true;
return test;
}
// Returns true if x is plus infinity
// x is double
public static boolean isPlusInfinity(double x){
boolean test=false;
if(x==Double.POSITIVE_INFINITY)test=true;
return test;
}
// Returns true if x is plus infinity
// x is float
public static boolean isPlusInfinity(float x){
boolean test=false;
if(x==Float.POSITIVE_INFINITY)test=true;
return test;
}
// Returns true if x is minus infinity
// x is double
public static boolean isMinusInfinity(double x){
boolean test=false;
if(x==Double.NEGATIVE_INFINITY)test=true;
return test;
}
// Returns true if x is minus infinity
// x is float
public static boolean isMinusInfinity(float x){
boolean test=false;
if(x==Float.NEGATIVE_INFINITY)test=true;
return test;
}
// Returns true if x is 'Not a Number' (NaN)
// x is double
public static boolean isNaN(double x){
boolean test=false;
if(x!=x)test=true;
return test;
}
// Returns true if x is 'Not a Number' (NaN)
// x is float
public static boolean isNaN(float x){
boolean test=false;
if(x!=x)test=true;
return test;
}
// Returns true if x equals y
// x and y are double
// x may be float within range, PLUS_INFINITY, NEGATIVE_INFINITY, or NaN
// NB!! This method treats two NaNs as equal
public static boolean isEqual(double x, double y){
boolean test=false;
if(Fmath.isNaN(x)){
if(Fmath.isNaN(y))test=true;
}
else{
if(Fmath.isPlusInfinity(x)){
if(Fmath.isPlusInfinity(y))test=true;
}
else{
if(Fmath.isMinusInfinity(x)){
if(Fmath.isMinusInfinity(y))test=true;
}
else{
if(x==y)test=true;
}
}
}
return test;
}
// Returns true if x equals y
// x and y are float
// x may be float within range, PLUS_INFINITY, NEGATIVE_INFINITY, or NaN
// NB!! This method treats two NaNs as equal
public static boolean isEqual(float x, float y){
boolean test=false;
if(Fmath.isNaN(x)){
if(Fmath.isNaN(y))test=true;
}
else{
if(Fmath.isPlusInfinity(x)){
if(Fmath.isPlusInfinity(y))test=true;
}
else{
if(Fmath.isMinusInfinity(x)){
if(Fmath.isMinusInfinity(y))test=true;
}
else{
if(x==y)test=true;
}
}
}
return test;
}
// Returns true if x equals y
// x and y are int
public static boolean isEqual(int x, int y){
boolean test=false;
if(x==y)test=true;
return test;
}
// Returns true if x equals y
// x and y are char
public static boolean isEqual(char x, char y){
boolean test=false;
if(x==y)test=true;
return test;
}
// Returns true if x equals y
// x and y are Strings
public static boolean isEqual(String x, String y){
boolean test=false;
if(x.equals(y))test=true;
return test;
}
// Returns true if x is an even number, false if x is an odd number
// x is int
public static boolean isEven(int x){
boolean test=false;
if(x%2 == 0.0D)test=true;
return test;
}
// Returns 0 if x == y
// Returns -1 if x < y
// Returns 1 if x > y
// x and y are double
public static int compare(double x, double y){
Double X = new Double(x);
Double Y = new Double(y);
return X.compareTo(Y);
}
// Returns 0 if x == y
// Returns -1 if x < y
// Returns 1 if x > y
// x and y are int
public static int compare(int x, int y){
Integer X = new Integer(x);
Integer Y = new Integer(y);
return X.compareTo(Y);
}
// Returns 0 if x == y
// Returns -1 if x < y
// Returns 1 if x > y
// x and y are long
public static int compare(long x, long y){
Long X = new Long(x);
Long Y = new Long(y);
return X.compareTo(Y);
}
// Returns 0 if x == y
// Returns -1 if x < y
// Returns 1 if x > y
// x and y are float
public static int compare(float x, float y){
Float X = new Float(x);
Float Y = new Float(y);
return X.compareTo(Y);
}
// Returns 0 if x == y
// Returns -1 if x < y
// Returns 1 if x > y
// x and y are short
public static int compare(byte x, byte y){
Byte X = new Byte(x);
Byte Y = new Byte(y);
return X.compareTo(Y);
}
// Returns 0 if x == y
// Returns -1 if x < y
// Returns 1 if x > y
// x and y are short
public static int compare(short x, short y){
Short X = new Short(x);
Short Y = new Short(y);
return X.compareTo(Y);
}
// Returns true if x is an even number, false if x is an odd number
// x is float but must hold an integer value
public static boolean isEven(float x){
double y=Math.floor(x);
if(((double)x - y)!= 0.0D)throw new IllegalArgumentException("the argument is not an integer");
boolean test=false;
y=Math.floor(x/2.0F);
if(((double)(x/2.0F)-y) == 0.0D)test=true;
return test;
}
// Returns true if x is an even number, false if x is an odd number
// x is double but must hold an integer value
public static boolean isEven(double x){
double y=Math.floor(x);
if((x - y)!= 0.0D)throw new IllegalArgumentException("the argument is not an integer");
boolean test=false;
y=Math.floor(x/2.0F);
if((x/2.0D-y) == 0.0D)test=true;
return test;
}
// Returns true if x is an odd number, false if x is an even number
// x is int
public static boolean isOdd(int x){
boolean test=true;
if(x%2 == 0.0D)test=false;
return test;
}
// Returns true if x is an odd number, false if x is an even number
// x is float but must hold an integer value
public static boolean isOdd(float x){
double y=Math.floor(x);
if(((double)x - y)!= 0.0D)throw new IllegalArgumentException("the argument is not an integer");
boolean test=true;
y=Math.floor(x/2.0F);
if(((double)(x/2.0F)-y) == 0.0D)test=false;
return test;
}
// Returns true if x is an odd number, false if x is an even number
// x is double but must hold an integer value
public static boolean isOdd(double x){
double y=Math.floor(x);
if((x - y)!= 0.0D)throw new IllegalArgumentException("the argument is not an integer");
boolean test=true;
y=Math.floor(x/2.0F);
if((x/2.0D-y) == 0.0D)test=false;
return test;
}
// Returns true if year (argument) is a leap year
public static boolean leapYear(int year){
boolean test = false;
if(year%4 != 0){
test = false;
}
else{
if(year%400 == 0){
test=true;
}
else{
if(year%100 == 0){
test=false;
}
else{
test=true;
}
}
}
return test;
}
// Returns milliseconds since 0 hours 0 minutes 0 seconds on 1 Jan 1970
public static long dateToJavaMilliS(int year, int month, int day, int hour, int min, int sec){
long[] monthDays = {0L, 31L, 28L, 31L, 30L, 31L, 30L, 31L, 31L, 30L, 31L, 30L, 31L};
long ms = 0L;
long yearDiff = 0L;
int yearTest = year-1;
while(yearTest>=1970){
yearDiff += 365;
if(Fmath.leapYear(yearTest))yearDiff++;
yearTest--;
}
yearDiff *= 24L*60L*60L*1000L;
long monthDiff = 0L;
int monthTest = month -1;
while(monthTest>0){
monthDiff += monthDays[monthTest];
if(Fmath.leapYear(year))monthDiff++;
monthTest--;
}
monthDiff *= 24L*60L*60L*1000L;
ms = yearDiff + monthDiff + day*24L*60L*60L*1000L + hour*60L*60L*1000L + min*60L*1000L + sec*1000L;
return ms;
}
}
| Java |
import java.util.StringTokenizer;
public class ParamPlotter {
public ParamPlotter() {
file f = new file("lVSv_6000_86p5_200k.txt");
double[] x = new double[30];
double[] y = new double[30];
double[] z = new double[900];
// we are going to set the x and y graph params by hand here..
// easier than reading from a file because we created the x and y with code previously
// get the params from IBEXWind.java :
double res = 30;
/*
double lamdaWidth = 20;
double vWidth = 8000;
double lamdaMin = 65.0;
//double tMin = 1000.0;
double vMin=22000.0;
double lamdaDelta = lamdaWidth/res;
double vDelta = vWidth/res;
*/
/*
double tempWidth = 7000;
double vWidth = 10000;
double tempMin = 1000.0;
//double tMin = 1000.0;
double vMin=20000.0;
double tempDelta = tempWidth/res;
double vDelta = vWidth/res;
*/
double lamdaWidth = 20.0;
double vWidth = 12000;
double lamdaMin = 65.0;
//double tMin = 1000.0;
double vMin=20000.0;
double lamdaDelta = lamdaWidth/res;
double vDelta = vWidth/res;
double lamda = lamdaMin;
//temp=tMin;
double v = vMin;
for (int i=0; i<30; i++) {
x[i]=lamdaMin + i*lamdaDelta;
y[i]=vMin + i*vDelta;
}
String line = "";
f.initRead();
int zIndex = 0;
while ((line=f.readLine())!=null) {
StringTokenizer st = new StringTokenizer(line);
String garb = st.nextToken();
garb = st.nextToken();
try {
z[zIndex]=Math.log(Double.parseDouble(st.nextToken()));
}
catch (Exception e) {
e.printStackTrace();
}
zIndex++;
}
System.out.println("going to throw up a plot now ");
JColorGraph jcg;
//jcg = new JColorGraph(x,y,z,false);
jcg = new JColorGraph(x,y,z);
String unitString = "log sum of squares difference";
jcg.setLabels("IBEX-LO","2010",unitString);
jcg.setXAxisLabels("Interstellar He Longitude", "deg");
jcg.setYAxisLabels("Interstellar He Temperature", "deg K");
// sg.setXMetaData(new SGTMetaData("Interstellar He Wind Longitude", "deg"));
// sg.setYMetaData(new SGTMetaData("Interstellar He Wind Temperature", "deg K"));
jcg.run();
jcg.showIt();
}
public static final void main(String[] args) {
ParamPlotter pp = new ParamPlotter();
}
} | Java |
import java.lang.Math;
import java.util.Date;
import java.util.Random;
import flanagan.integration.*;
//import drasys.or.nonlinear.*; // our friend mr. simpson resides here
/**
* This class should take care of doing multi-dimensional numeric integrations.
* This will be slow!!
*
* Actually not half bad...
*
*
* Lukas Saul
* UNH Physics
* May, 2001
*
* Updated Aug. 2003 - only works with 2D integrals for now...
*
* Updated Aug. 2004 - 3D integrals OK! Did that really take 1 year??
*
* About 2.1 seconds to integrate e^(-x^2-y^2-z^2) !!
*
* Testing in jan 2008 again..
*
* 16 points seems to work well enough for 4 digit precision of 3D gaussian integral in < 20ms
*/
public class MultipleIntegration {
public static double PLUS_INFINITY = Double.POSITIVE_INFINITY;
public static double MINUS_INFINITY = Double.NEGATIVE_INFINITY;
private double result;
public int npoints=128;
public int lastNP = 0;
public double smartMin = 0.0000000001;
Random r;
/**
* for testing - increments at every 1D integration performed
*/
public long counter, counter2;
/**
* Constructor just sets up the 1D integration routine for running
* after which all integrations may be called.
*/
public MultipleIntegration() {
r=new Random();
r.setSeed((new Date()).getTime());
counter = 0;
counter2 = 0;
result = 0.0;
}
/**
* sets counter to zero
*/
public void reset() {
counter = 0;
}
public void reset2() {
counter2 = 0;
}
/**
* Set accuracy of integration
*/
public void setEpsilon(double d) {
//s.setErrMax(d);
}
/**
* Deal with infinit limits here and call Flanagan gaussian quadrature for numeric integration
*
*/
public double gaussQuad(final FunctionI fI, final double min_l, final double max_l, final int np) {
try{ // if inifinite limits, replace arg x by x/1-x and integrate -1 to 1
if (min_l!=MINUS_INFINITY && max_l!=PLUS_INFINITY)
return Integration.gaussQuad(fI, min_l, max_l, np);
else if (min_l==MINUS_INFINITY && max_l==PLUS_INFINITY) {
// lets try recursion instead...
return
gaussQuad(fI, min_l, -10000.0, np/4) +
gaussQuad(fI, -10000.0, 0.0, np/4) +
gaussQuad(fI, 0.0, 10000.0, np/4) +
gaussQuad(fI, 10000.0, max_l, np/4);
/*FunctionI newFI = new FunctionI () {
public double function(double x) {
return (fI.function((1.0-x)/x)+fI.function((-1.0+x)/x))/x/x;
}
};
return Integration.gaussQuad(newFI,0.0,1.0,np);
*/
}
else if (min_l==MINUS_INFINITY) {
FunctionI newFI = new FunctionI () {
public double function(double x) {
return fI.function(max_l-(1.0-x)/x)/x/x;
}
};
return Integration.gaussQuad(newFI,0.0,1.0,np);
}
else if (max_l==PLUS_INFINITY) {
FunctionI newFI = new FunctionI () {
public double function(double x) {
return fI.function(min_l+(1.0-x)/x)/x/x;
}
};
return Integration.gaussQuad(newFI,0.0,1.0,np);
}
}
catch (Exception e) {
e.printStackTrace();
return 0.0;
}
return 0.0;
}
/**
* Here's the goods, for 3D integrations.
*
* Limits are in order as folows: zlow, zhigh, ylow, yhigh, xlow, xhigh
*
*/
public double integrate(final FunctionIII f, final double[] limits, final int np) {
reset();
// System.out.println("Called 3D integrator");
// System.out.println("Integrating from: \n"+limits[0]+" "+limits[1]+
// "\n"+limits[2]+" "+limits[3]+"\n"+limits[4]+" "+limits[5]);
double[] nextLims = new double[4];
for (int i=0; i<4; i++) {
nextLims[i] = limits[i+2];
}
final double[] nextLimits = nextLims;
FunctionI funcII = new FunctionI () {
public double function(double x) {
return integrate(f.getFunctionII(2,x), nextLimits, np);
}
};
result = gaussQuad(funcII,limits[0],limits[1],np);
return result;
}
/**
* Here's the goods, for 2D integrations
*/
public double integrate(final FunctionII f, final double[] limits, final int np) {
FunctionI f1 = new FunctionI() {
public double function(double x) {
return integrate(f.getFunction(1,x),limits[2],limits[3], np);
}
};
result = gaussQuad(f1, limits[0], limits[1], np);
return result;
// each call to f1 by the intgrator does an integration
}
/**
* Here's the simple goods, for 1D integrations
* courtesy of our friends at drasys.or.nonlinear
*/
public double integrate(final FunctionI f, double lowLimit, double highLimit, int np) {
//System.out.println("Called 1D integrator");
counter2++;
counter++;
//if (counter%10000==1) System.out.println("Counter: " + counter);
//s.setInterval(lowLimit,highLimit);
//return s.getResult(f);
return gaussQuad(f,lowLimit,highLimit,np);
//return
}
/**
* Monte-Carlo 1D Integration (not a good idea but for test)
*/
public double mcIntegrate(final FunctionI f, double lowLimit, double highLimit, int np) {
if (lowLimit == MINUS_INFINITY && highLimit == PLUS_INFINITY) {
FunctionI newFI = new FunctionI () {
public double function(double x) {
return (f.function((1.0-x)/x)+f.function((-1.0+x)/x))/x/x;
}
};
return mcIntegrate(newFI, 0.0, 1.0, np);
}
else {
r.setSeed((new Date()).getTime());
double tbr = 0.0;
for (int i=0; i<np; i++) {
// select random point
double point = r.nextGaussian()*(highLimit-lowLimit) + lowLimit;
tbr += f.function(point);
}
tbr*=(highLimit-lowLimit);
tbr/=np;
return tbr;
}
}
/**
* Monte-Carlo 2D Integration (not a good idea but for test)
*/
public double mcIntegrate(final FunctionII f, double[] limits, int np) {
r.setSeed((new Date()).getTime());
double w1 = limits[1]-limits[0];
double w2 = limits[3]-limits[2];
double tbr = 0.0;
double xpoint,ypoint;
System.out.println("widths: " + w1 + " " + w2);
for (int i=0; i<np; i++) {
// select random point
xpoint = r.nextDouble()*w1 + limits[0];
ypoint = r.nextDouble()*w2 + limits[2];
tbr += f.function2(xpoint,ypoint);
}
tbr*=w1*w2;
tbr=tbr/(double)np;
return tbr;
}
/**
* Monte carlo 3D integral
*/
public double mcIntegrate(final FunctionIII f, double[] limits, int np) {
if (limits[0] == MINUS_INFINITY && limits[1] == PLUS_INFINITY &&
limits[2] == MINUS_INFINITY && limits[3] == PLUS_INFINITY &&
limits[4] == MINUS_INFINITY && limits[5] == PLUS_INFINITY) {
System.out.println("doing infinite MC");
FunctionIII newFI = new FunctionIII () {
public double function(double x,double y, double z) {
double xp = (1.0-x)/x;
double yp = (1.0-y)/y;
double zp = (1.0-z)/z;
return (f.function3(xp,yp,zp)+f.function3(-xp,yp,zp)+
f.function3(xp,-yp,zp)+f.function3(-xp,-yp,zp)+
f.function3(xp,yp,-zp)+f.function3(-xp,yp,-zp)+
f.function3(xp,-yp,-zp)+f.function3(-xp,-yp,-zp))/x/x/y/y/z/z;
}
};
double [] newLims = {0.0,1.0, 0.0,1.0, 0.0,1.0};
return mcIntegrate(newFI, newLims, np);
}
else {
double w1 = limits[1]-limits[0];
double w2 = limits[3]-limits[2];
double w3 = limits[5]-limits[4];
double tbr = 0.0;
double xpoint,ypoint,zpoint;
// System.out.println("widths: " + w1 + " " + w2 + " " + w3);
for (int i=0; i<np; i++) {
// select random point
xpoint = r.nextDouble()*w1 + limits[0];
ypoint = r.nextDouble()*w2 + limits[2];
zpoint = r.nextDouble()*w3 + limits[4];
tbr += f.function3(xpoint,ypoint,zpoint);
}
tbr*=w1*w2*w3;
tbr=tbr/(double)np;
return tbr;
}
}
/**
* Monte carlo 3D integral - this time with a certain number of threads
*/
public double mcIntegrate(final FunctionIII f, double[] limits, int np, int threads) {
double tbr = 0.0; // this is the total tbr, not the to be returned for a single thread
// set up the threads
int numPerThread = np/threads;
MCThread theMCs[] = new MCThread[threads];
for (int i=0; i<threads; i++) theMCs[i]=new MCThread(f, limits, numPerThread);
System.out.println("doing numPerThread: " + numPerThread);
// start them all
for (int i=0; i<threads; i++) theMCs[i].start();
// wait for them to finish
boolean allDone = false;
while (!allDone) {
boolean tempDone = true;
for (int i=0; i<threads; i++) {
if (!theMCs[i].finished) {
try { Thread.sleep(1000);} catch (Exception e) { e.printStackTrace(); }
tempDone = false;
}
}
if (tempDone) allDone=true;
}
// add their results
for (int i=0; i<threads; i++) tbr+= theMCs[i].tbr;
double w1 = limits[1]-limits[0];
double w2 = limits[3]-limits[2];
double w3 = limits[5]-limits[4];
tbr*=w1*w2*w3;
tbr=tbr/(double)np;
return tbr;
}
/**
* Make a smart estimate at the proper number of iterations to perform
*
*/
public double mcIntegrateS(final FunctionIII f, double[] limits, int max_np) {
int currentNP=100;
double result1 = 0;
double result2 = 1;
while(Math.abs(result2-result1)>Math.abs(0.05*result2) && currentNP<max_np) {
//System.out.println("trying np: " + currentNP);
result1=mcIntegrate(f,limits,currentNP);
currentNP*=2;
result2=mcIntegrate(f,limits,currentNP);
}
lastNP = currentNP;
return result2;
}
/**
* Monte carlo 3D integral - take 3, implement smart functionality inside integration routine
* without losing any time here!!
*/
public double mcIntegrateSS(final FunctionIII f, double[] limits, int maxNp) {
currentNP = 100;
tbr = 0.0; // running total!
tbrLast = 100.0;
tbrNew = 0.0;
numDone = 0;
w1 = limits[1]-limits[0];
w2 = limits[3]-limits[2];
w3 = limits[5]-limits[4];
while (Math.abs(tbrLast-tbrNew)>Math.abs(acc*tbrLast) & numDone<maxNp & Math.abs(tbrLast)>smartMin) {
tbrNew = tbrLast;
for (int i=numDone; i<currentNP; i++) {
// select random point
xpoint = r.nextDouble()*w1 + limits[0];
ypoint = r.nextDouble()*w2 + limits[2];
zpoint = r.nextDouble()*w3 + limits[4];
tbr += f.function3(xpoint,ypoint,zpoint);
numDone++;
}
tbrLast = tbr;
tbrLast*=w1*w2*w3;
tbrLast=tbrLast/(double)numDone;
currentNP = currentNP*2;
}
lastNP = numDone;
return tbrLast;
}
// VARIABLES FOR ABOVE ROUTINE HERE:
int currentNP = 100;
double acc=0.01;
double tbr = 0.0; // running total!
double tbrLast = 100.0;
double tbrNew = 0.0;
int numDone = 0;
double xpoint,ypoint,zpoint;
double w1, w2, w3;
/**
* Just for testing only here!!!
*
* seems to work - may 3, 2001
*
* lots more testing for limits of 3d , polar vs. cartesian - Oct. 2004
*/
public static final void main(String[] args) {
MultipleIntegration mi = new MultipleIntegration();
// some functions to integrate!!
FunctionI testf1 = new FunctionI() {
public double function(double x) {
return Math.exp(-(x+20.0)*(x+20.0));
}
};
FunctionIII testf3 = new FunctionIII () {
public double function3(double x, double y, double z) {
return (Math.exp(-(x*x+y*y+z*z)));
}
};
FunctionIII testf4 = new FunctionIII () {
public double function3(double r, double p, double t) {
return r*r*Math.sin(t);
}
};
System.out.println("f1 gauss: "+mi.integrate(testf1,MINUS_INFINITY,PLUS_INFINITY,10000));
System.out.println("f1 gauss mc: "+mi.mcIntegrate(testf1,MINUS_INFINITY,PLUS_INFINITY,1000000));
System.out.println("sqrt pi: "+ Math.sqrt(Math.PI));
//System.out.println(""+mi.integrate(testf1,MINUS_INFINITY,0.0,512));
//System.out.println(""+mi.integrate(testf1,-100.0,0.0,512));
double[] lims = {MINUS_INFINITY, PLUS_INFINITY, MINUS_INFINITY, PLUS_INFINITY, MINUS_INFINITY, PLUS_INFINITY};
double[] lims2 = {-10.0,10.0,-10.0,10.0,-10.0,10.0};
double test3 = mi.integrate(testf3,lims2,64);
double test32 = mi.mcIntegrate(testf3,lims,1000000);
double test323 = mi.mcIntegrate(testf3,lims2,1000000);
System.out.println("test3 reg to 10: " + test3);
System.out.println("test3 mc: " + test32);
System.out.println("test3 mc to 10: " + test323);
System.out.println("pi to 3/2: "+ Math.pow(Math.PI,3.0/2.0));
System.out.println("new test");
double[] newLims = {0.0,2.0,0.0,2*Math.PI,0.0,Math.PI};
double newAns = mi.mcIntegrate(testf4,newLims,10000000);
System.out.println("answer new: " + newAns);
System.out.println("sphere volume " + (4.0/3.0*Math.PI*8.0));
double newAns2 = mi.mcIntegrateS(testf4,newLims,10000000);
System.out.println("answer new again: "+newAns2);
double newAns3 = mi.mcIntegrateSS(testf4,newLims,10000000);
System.out.println("answer new again SS: "+newAns3);
System.out.println("lastNP: " + mi.lastNP);
/*
// FOR TESTING 3D INTEGRALS
file f = new file("int_test.txt");
f.initWrite(false);
for (int i=1; i<256; i*=2) {
//System.out.println("lim: " + i);
Date d1 = new Date();
double test1 = mi.integrate(testf1, -100,100,i);
Date d2 = new Date();
//System.out.println("1D integrations: " + mi.counter);
double[] lims = {MINUS_INFINITY, PLUS_INFINITY, MINUS_INFINITY, PLUS_INFINITY, MINUS_INFINITY, PLUS_INFINITY};
double test3 = mi.integrate(testf3,lims,i);
Date d3 = new Date();
//System.out.println("3D integrations: " + mi.counter);
//System.out.println("Answer single gauss: " + test1);
//System.out.println("Answer trip gauss: " + test3);
//System.out.println("took: " + (d2.getTime()-d1.getTime()));
//System.out.println("took 3: " + (d3.getTime()-d2.getTime()));
f.write(i+"\t"+test3+"\t"+(d3.getTime()-d2.getTime()) + "\n");
}
f.closeWrite();
*/
/*
double[] lims2 = new double[4];
lims2[0]=-100.0;
lims2[1]=100.0;
lims2[2]=-100.0;
lims2[3]=100.0;
Date d3 = new Date();
double test2 = mi.integrate(testf2,lims2);
Date d4 = new Date();
System.out.println("Answer frm 2d testf2: " + test2);
System.out.println("took: " + (d4.getTime()-d3.getTime()));
System.out.println("1D integrations: " + mi.counter);
d3 = new Date();
test2 = mi.integrate(testf2a,lims2);
d4 = new Date();
System.out.println("Answer frm 2d testf2a: " + test2);
System.out.println("took: " + (d4.getTime()-d3.getTime()));
System.out.println("1D integrations: " + mi.counter);
System.out.println("trying polar 2d now");
lims2 = new double[4];
lims2[0]=0;
lims2[1]=2*Math.PI;
lims2[2]=0;
lims2[3]=10;
d3 = new Date();
double ttest = mi.integrate(testf2b,lims2);
d4 = new Date();
System.out.println("2d polar Answer: " + ttest);
System.out.println("took: " + (d4.getTime()-d3.getTime()));
System.out.println("1D integrations: " + mi.counter);
System.out.println("trying 3d now... ");
// basic limit test here,
double[] lims = new double[6];
lims[0]=0.0;
lims[1]=3.00;
lims[2]=0.0;
lims[3]=1.0;
lims[4]=0.0;
lims[5]=2.0;
Date d1 = new Date();
double test = mi.integrate(testlims,lims);
Date d2 = new Date();
System.out.println("Answer: " + test);
System.out.println("took: " + (d2.getTime()-d1.getTime()));
System.out.println("1D integrations: " + mi.counter);
System.out.println("answer: " + 8*81/2/3/4);
lims = new double[6];
lims[0]=-10.0;
lims[1]=10.00;
lims[2]=-10.0;
lims[3]=10.0;
lims[4]=-10.0;
lims[5]=10.0;
d1 = new Date();
test = mi.integrate(testf,lims);
d2 = new Date();
System.out.println("Answer: " + test);
System.out.println("took: " + (d2.getTime()-d1.getTime()));
System.out.println("1D integrations: " + mi.counter);
System.out.println("test^2/3: " + Math.pow(test,2.0/3.0));
System.out.println("trying 3d now... ");
// 3d Function integration working in spherical coords??
lims = new double[6];
lims[0]=0;
lims[1]=Math.PI;
lims[2]=0;
lims[3]=2*Math.PI;
lims[4]=0;
lims[5]=10.0;
d1 = new Date();
test = mi.integrate(testfs,lims);
d2 = new Date();
System.out.println("Answer: " + test);
System.out.println("took: " + (d2.getTime()-d1.getTime()));
System.out.println("1D integrations: " + mi.counter);
System.out.println("test^2/3: " + Math.pow(test,2.0/3.0));
*/
}
} | Java |
public class MyDouble {
public double value;
public MyDouble(double d) {
value=d;
}
} | Java |
import java.lang.Math;
import java.util.Date;
/**
* Lukas Saul - March 27, 2001
* Taken from C routine Four1, from Numerical Recipes
*/
public class JFFT {
public double[] dOutReal;
public double[] dOutImaginary;
private double[] dInReal;
//private long nn;
//private int iSign;
//private double wr, wi, wpr, wpi, wtemp, theta;
// for testing here...
public static void main(String[] args) {
double[] testData = new double[10000];
for (int m=0; m<testData.length; m++) {
testData[m]=m*m+2*m+3; // random function
}
JFFT j = new JFFT(testData);
//for (int q=0; q<testData.length; q++) {
// System.out.println(j.dOutReal[q] + " " + j.dOutImaginary[q]);
//}
}
public JFFT(double[] _dIn) {
Date d1 = new Date();
dInReal = _dIn;
int size = dInReal.length;
System.out.println(size);
// what if dIn.length is not a power of 2?
int test=1;
int i = 0;
while (test != 0) {
i++;
test = size >> i; // divide by 2^i (binary shift)
//System.out.println("test = " + test);
}
i=i-1;
System.out.println("final i = " + i);
int dif = size - (int)Math.pow(2,i);
System.out.println("dif = " + dif);
if (dif > 0) { // In this case we need to pad the array with zeroes
double[] dIn2 = new double[(int)Math.pow(2.0,i+1)]; //this could be faster
//copy by hand
for (int k=0; k<dInReal.length; k++) {
dIn2[k]=dInReal[k];
}
for (int j=dInReal.length; j<dIn2.length; j++) {
dIn2[j]=0;
}
// the new data:
dInReal = dIn2;
System.out.println("new size " + dInReal.length);
}
Date d2 = new Date();
System.out.println("setup took: " + (d2.getTime() - d1.getTime()) );
// Set up our discrete complex array
double[] ourData = new double[dInReal.length*2];
for (int j=0; j<dInReal.length; j++) {
ourData[2*j] = dInReal[j];
ourData[2*j+1] = 0; // set imaginary part to zero
}
// Ok, let's do the FFT on the ourData array:
four1(ourData, dInReal.length, 1);
dOutReal = new double[dInReal.length];
dOutImaginary = new double[dInReal.length];
for (int j=0; j<dInReal.length; j++) {
dOutReal[j] = ourData[2*j];
dOutImaginary[j] = ourData[2*j+1];
}
Date d3 = new Date();
System.out.println("fft took: " + (d3.getTime() - d1.getTime()) );
}
public void four1(double[] data, int nn, int isign) {
System.out.println("computing fft with args: " + data.length + " " + nn);
long n, mmax, m, j, istep, i;
double wtemp, wr, wpr, wpi, wi, theta;
float tempr, tempi;
n = nn/2;
System.out.println("compare " + n + " " + nn + " " + nn/2);
j=1;
for (i=1; i<n; i+=2) {
if (j>i) {
swap(data[(int)j], data[(int)i]);
swap(data[(int)j+1], data[(int)i+1]);
}
m=n/2;
while (m >= 2 && j>m) {
j -= m;
m=m/2;
}
j += m;
}
// Here begins Danielson-Lanczos section of routine
mmax=2;
while (n > mmax) {
istep = mmax << 1;
theta = isign*(6.28318530717959/mmax);
wtemp = Math.sin(0.5*theta);
wpr = -2.0*wtemp*wtemp;
wpi = Math.sin(theta);
wr=1.0;
wi=0.0;
for (m=1; m<mmax; m+=2) {
for (i=m; i<=n; i+=istep) {
j=i+mmax;
tempr = (float)(wr*data[(int)j] -
wi*data[(int)j+1]);
tempi = (float)(wr*data[(int)j+1] - wi*data[(int)j]);
data[(int)j] = data[(int)i] - tempr;
data[(int)j+1] = data[(int)i+1] - tempi;
data[(int)i] += tempr;
data[(int)i+1] += tempi;
}
wr = (wtemp=wr)*wpr - wi*wpi + wr;
wi = wi*wpr + wtemp*wpi + wi;
}
mmax = istep;
}
}
private void swap(double a, double b) {
double temp = a;
a=b;
b=temp;
}
} | Java |
/**
* A basic power law in ENERGY
*
*/
public class PowerLawVLISM extends InterstellarMedium {
public HelioVector vBulk;
public double power, density, lim1, lim2, norm, ee;
public static double NaN = Double.NaN;
public static double MP = 1.672621*Math.pow(10,-27);
public static double EV = 6.24150965*Math.pow(10,18);
/**
* Construct a power law VLISM
*/
public PowerLawVLISM(HelioVector _vBulk, double _density, double _power, double _ll, double _hh) {
vBulk = _vBulk;
power = _power;
density = _density;
lim1 = _ll;
lim2 = _hh;
// calculate normalization
norm = density/4/Math.PI/ (Math.pow(lim2,power+3.0)- Math.pow(lim1,power+3.0))*(power+3.0);
norm=norm;
System.out.println("norm: " + norm);
}
/**
*
* Pass in a heliovector if you feel like it.. slower?
* probably not..
*/
public double heliumDist(HelioVector v) {
return dist(v.getX(), v.getY(), v.getZ());
}
public double heliumDist(double v1, double v2, double v3) {
return dist(v1,v2,v3);
}
/**
* default - pass in 3 doubles
*/
public double dist(double v1, double v2, double v3) {
if (v1==NaN | v2==NaN | v3==NaN) return 0.0;
// calculate energy
double vv1 = v1-vBulk.getX();
double vv2 = v2-vBulk.getY();
double vv3 = v3-vBulk.getZ();
double vv = Math.sqrt(vv1*vv1+vv2*vv2+vv3*vv3);
// ee = 4*MP/2*(vv1*vv1+vv2*vv2+vv3*vv3)*EV;
// System.out.println("ee: " + ee);
if (vv>lim1 && vv<lim2) return norm*Math.pow(vv,power);
else return 0.0;
}
/**
* default - pass in 1 energy
*/
//public double dist(double energy) {
// if (v1==NaN | v2==NaN | v3==NaN) return 0.0;
// calculate energy
//double vv1 = v1-vBulk.getX();
//double vv2 = v2-vBulk.getY();
//double vv3 = v3-vBulk.getZ();
//ee = 4*MP/2*(vv1*vv1+vv2*vv2+vv3*vv3)*EV;
// System.out.println("ee: " + ee);
// ee=energy;
// if (ee>lim1 && ee<lim2) return norm*Math.pow(ee,power);
// else return 0.0;
//}
public double protonDist(double v1, double v2, double v3) {
return 0;
}
public double hydrogenDist(double v1, double v2, double v3) {
return 0;
}
public double deuteriumDist(double v1, double v2, double v3) {
return 0;
}
public double electronDist(double v1, double v2, double v3) {
return 0;
}
public double alphaDist(double v1, double v2, double v3) {
return 0;
}
// etcetera...+
/**
*
*/
public static final void main(String[] args) {
final PowerLawVLISM gvli = new PowerLawVLISM(new HelioVector(HelioVector.CARTESIAN,
-20000.0,0.0,0.0), 1.0, -4.0, 1000.0, 300000.0);
System.out.println("Created PLVLISM" );
//System.out.println("Maxwellian VLISM created, norm = " + norm);
MultipleIntegration mi = new MultipleIntegration();
//mi.setEpsilon(0.001);
FunctionIII dist = new FunctionIII () {
public double function3(double x, double y, double z) {
return gvli.heliumDist(x, y, z);
}
};
System.out.println("Test dist: " + dist.function3(20000,0,0));
double[] limits = new double[6];
limits[0]=mi.MINUS_INFINITY; limits[1]=mi.PLUS_INFINITY;
limits[2]=mi.MINUS_INFINITY; limits[3]=mi.PLUS_INFINITY;
limits[4]=mi.MINUS_INFINITY; limits[5]=mi.PLUS_INFINITY;
double[] limits2 = new double[6];
limits2[0]=-100000.0; limits2[1]=100000.0;
limits2[2]=-100000.0; limits2[3]=100000.0;
limits2[4]=-100000.0; limits2[5]=100000.0;
//double z = mi.mcIntegrate(dist,limits,128 );
double z2 = mi.mcIntegrate(dist,limits2,1000000);
System.out.println("Integral should equal density= " + z2);
}
}
| Java |
/**
* Utility class for passing around 2D functions
*
* Use this to get a 1D function by fixing one of the variables..
* the index to fix is passed in ( 0 or 1 )
*/
public abstract class FunctionII {
/**
* Override this for the function needed!!
*
*/
public double function2(double x, double y) {
return 0;
}
/**
*
* This returns a one dimensional function, given one of the values fixed
*
*/
protected final Function getFunction(final int index, final double value) {
if (index == 0) return new Function() {
public double function(double x) {
return function2(value,x);
}
};
else if (index == 1) return new Function() {
public double function(double x) {
return function2(x,value);
}
};
else {
System.out.println("index out of range in FunctionII.getFunction");
return null;
}
}
}
| Java |
/**
* Simulating response at IBEX_LO with this class
*
* Create interstellar medium and perform integration
*
*/
public class IBEXLO {
public int mcN = 20000; // number of iterations per 3D integral
public String outFileName = "ibex_lo_out17.txt";
String dir = "SPRING";
//String dir = "FALL";
public static final double EV = 1.60218 * Math.pow(10, -19);
public static double MP = 1.672621*Math.pow(10.0,-27.0);
public static double AU = 1.49598* Math.pow(10,11); //meters
public static double EARTHSPEED = AU*2.0*3.14/365.0/24.0/3600.0;
// define angles and energies of the instrument here
// H mode (standard) energy bins in eV
public double[] minEnergies = {8.8, 17.6, 35.8, 74.2, 153.5, 330.6, 663.3, 1298.6};
public double[] maxEnergies = {23.2, 46.4, 94.3, 195.8, 404.6, 871.5, 1748.7, 3423.5};
public double[] minSpeedsHe, maxSpeedsHe, minSpeedsO, maxSpeedsO;
// Interstellar mode energies
// { spring min, spring max, fall min, fall max }
public double[] heEnergies = { 73.7, 194.3, 4.4, 11.6 };
public double[] oEnergies = {293.7, 774.3, 18.15, 47.9 };
public double[] heSpeeds;
public double[] oSpeeds;
// O mode efficiencies
public double heSpringEff = 1.0*Math.pow(10,-7);
public double heFallEff = 1.6*Math.pow(10,-6);
public double oSpringEff = 0.004;
public double oFallEff = 0.001;
// angular acceptance - assume rectangular windows..
// these are half widths, e.g. +- for acceptance
public double spinWidth = 4.0*Math.PI/180.0;
public double hrWidth = 3.5*Math.PI/180.0;
public double lrWidth = 7.0*Math.PI/180.0;
public double eightDays = 8.0*24.0*60.0*60.0;
public double oneHour = 3600.0;
public double upWind = 74.0 * 3.14 / 180.0;
public double downWind = 254.0 * 3.14 / 180.0;
public double startPerp = 180*3.14/180; // SPRING
public double endPerp = 240*3.14/180; // SPRING
//public double startPerp = 260.0*3.14/180.0; // FALL
//public double endPerp = 340.0*3.14/180.0; // FALL
public double he_ion_rate = 1.0*Math.pow(10,-7);
public double o_ion_rate = 8.0*Math.pow(10,-7);
// temporarily make them very small
//public double spinWidth = 0.5*Math.PI/180.0;
//public double hrWidth = 0.5*Math.PI/180.0;
//public double lrWidth = 0.5*Math.PI/180.0;
public double activeArea = 100.0/100.0/100.0; // in square meters now!!
public file outF;
public MultipleIntegration mi;
/*
8.8 23.2
17.6 46.4
35.75 94.25
74.25 195.75
153.45 404.55
330.55 871.45
663.3 1748.7
1298.55 3423.45
he_S 73.7 194.3
he_F 4.4 11.6
o_S 293.7 774.3
o_F 18.15 47.85
*/
/**
*
*
*
*/
public IBEXLO() {
if (dir.equals("SPRING")) {
startPerp = 175*3.14/180;
endPerp = 235*3.14/180;
}
else if (dir.equals("FALL")) {
startPerp = 290.0*3.14/180.0; // FALL
endPerp = 360.0*3.14/180.0; // FALL
}
o("earthspeed: " + EARTHSPEED);
mi = new MultipleIntegration();
// set up output file
outF = new file(outFileName);
outF.initWrite(false);
// calculate speed ranges with v = sqrt(2E/m)
heSpeeds = new double[heEnergies.length];
oSpeeds = new double[oEnergies.length];
o("calculating speed range");
for (int i=0; i<4; i++) {
heSpeeds[i]=Math.sqrt(2.0*heEnergies[i]/4.0/MP*EV);
oSpeeds[i]=Math.sqrt(2.0*oEnergies[i]/16.0/MP*EV);
System.out.println(heEnergies[i] +" = " + heSpeeds[i] + " , " + oEnergies[i] + " = " + oSpeeds[i]);
}
minSpeedsHe = new double[8];
maxSpeedsHe = new double[8];
minSpeedsO = new double[8];
maxSpeedsO = new double[8];
for (int i=0; i<8; i++) {
minSpeedsHe[i]=Math.sqrt(2.0*minEnergies[i]/4.0/MP*EV);
maxSpeedsHe[i]=Math.sqrt(2.0*maxEnergies[i]/4.0/MP*EV);
minSpeedsO[i]=Math.sqrt(2.0*minEnergies[i]/16.0/MP*EV);
maxSpeedsO[i]=Math.sqrt(2.0*maxEnergies[i]/16.0/MP*EV);
System.out.println(minSpeedsHe[i] +" = " + maxSpeedsHe[i] + " , " + minSpeedsO[i] + " = " + maxSpeedsO[i]);
}
System.out.println(minSpeedsHe[0] + "\t" + maxSpeedsHe[0] +"\t" + heSpeeds[2] + "\t" + heSpeeds[3]);
// BUILD INTERSTERLLAR MEDIUM - helium and oxygen here, primary and secondary oxygen..
//
HelioVector bulkHE = new HelioVector(HelioVector.SPHERICAL,26000.0, (74+180)*Math.PI/180.0, 95.5*Math.PI/180);
HelioVector bulkO1 = new HelioVector(HelioVector.SPHERICAL,26000.0, (74+180)*Math.PI/180.0, 95.5*Math.PI/180);
HelioVector bulkO2 = new HelioVector(HelioVector.SPHERICAL,21000.0, (74+180)*Math.PI/180.0, 95.5*Math.PI/180);
// implement test 1 - a vector coming in along x axis
//HelioVector bulkHE = new HelioVector(HelioVector.SPHERICAL,26000.0, Math.PI, Math.PI/2.0);
//HelioVector bulkO1 = new HelioVector(HelioVector.SPHERICAL,25000.0, Math.PI, Math.PI/2.0);
//HelioVector bulkO2 = new HelioVector(HelioVector.SPHERICAL,21000.0, Math.PI, Math.PI/2.0);
// standard hot helium
GaussianVLISM gv1 = new GaussianVLISM(bulkHE,0.015*100*100*100,6300.0);
GaussianOxVLISM gv2 = new GaussianOxVLISM(bulkO1, bulkO2, 0.00005*100*100*100, 1000.0, 90000.0, 0.0); // last is fraction in 2ndry
final NeutralDistribution ndHe = new NeutralDistribution(gv1, 0.0, he_ion_rate);
final NeutralDistribution ndO = new NeutralDistribution(gv2, 0.0, o_ion_rate);
ndHe.debug=false;
ndO.debug=false;
// DONE CREATING MEDIUM
// PASSAGE SIMULATION - IN ECLIPTIC - SPRING or FALL - use String dir = "FALL" or "SPRING" to set all pointing params properly
//double initPos = Math.PI/2;
//double finalPos = 1.5*Math.PI;
double initPos = startPerp;
double finalPos = endPerp;
double step = 8.0*360.0/365.0*3.14/180.0; // these are orbit adjusts - every eight days
double step2 = step/8.0/2.0; // here wet take smaller integration timest than an orbit.. current: 12 hours
//determine entrance velocity vector and integration range
double midPhi = initPos-Math.PI/2.0;
double midThe = Math.PI/2.0;
for (double pos = initPos; pos<finalPos; pos+= step) {
// inner loop moves pos2
for (double pos2 = pos; pos2<pos+step; pos2+= step2) {
// here's the now position
final HelioVector posVec = new HelioVector(HelioVector.SPHERICAL, 1*AU, pos2, Math.PI/2.0);
final HelioVector scVelVec = new HelioVector(HelioVector.SPHERICAL, EARTHSPEED, pos2+Math.PI/2.0, Math.PI/2.0);
FunctionIII he_func = new FunctionIII() { // helium neutral distribution
public double function3(double v, double p, double t) {
double tbr = activeArea*ndHe.dist(posVec, new HelioVector(HelioVector.SPHERICAL,v,p,t).difference(scVelVec) )*v*v*Math.sin(t)*v; // extra v for flux
// that is the integrand of our v-space integration
return tbr;
}
};
FunctionIII o_func = new FunctionIII() { // oxygen neutral distribution
public double function3(double v, double p, double t) {
double tbr = activeArea*ndO.dist(posVec, new HelioVector(HelioVector.SPHERICAL,v,p,t).difference(scVelVec) )*v*v*Math.sin(t)*v; // extra v for flux
// that is the integrand of our v-space integration
return tbr;
}
};
// set look direction and limits -
if (dir.equals("FALL"))
midPhi = pos-Math.PI/2+(4.0*3.1416/180.0); // change look direction at downwind point
else if (dir.equals("SPRING"))
midPhi = pos+Math.PI/2+(4.0*3.1416/180.0); // change look direction at downwind point
// now step through the spin - out of ecliptic
double theta_step = 6.0*Math.PI/180.0;
for (double pos3 = Math.PI/2.0 - 3.0*theta_step; pos3<= (Math.PI/2.0 + 4.0*theta_step); pos3 += theta_step) {
midThe = pos3;
//int hrmn
//if (pos>downWind) {
// midPhi = pos + Math.PI/2.0;
// set limits for integration, fall is first here..
//if (dir.equals("FALL")) {
double[] he_hr_lims = { heSpeeds[2], heSpeeds[3], midPhi-lrWidth, midPhi+lrWidth, midThe-lrWidth-spinWidth, midThe+lrWidth+spinWidth };
double[] he_lr_lims = { minSpeedsHe[0], maxSpeedsHe[0], midPhi-lrWidth, midPhi+lrWidth, midThe-lrWidth-spinWidth, midThe+lrWidth+spinWidth };
double[] o_hr_lims = { oSpeeds[2], oSpeeds[3], midPhi-hrWidth, midPhi+hrWidth, midThe-hrWidth-spinWidth, midThe+hrWidth+spinWidth };
double[] o_lr_lims = { minSpeedsO[1], maxSpeedsO[1], midPhi-lrWidth, midPhi+lrWidth, midThe-lrWidth-spinWidth, midThe+lrWidth+spinWidth };
//}
if (dir.equals("SPRING")) {
he_hr_lims[0]=heSpeeds[0]; he_hr_lims[1]=heSpeeds[1]; //, midPhi-hrWidth, midPhi+hrWidth, midThe-hrWidth-spinWidth, midThe+hrWidth+spinWidth };
he_lr_lims[0]=minSpeedsHe[3]; he_lr_lims[1]=maxSpeedsHe[3]; //, midPhi-lrWidth, midPhi+lrWidth, midThe-lrWidth-spinWidth, midThe+lrWidth+spinWidth };
o_hr_lims[0]=oSpeeds[0]; o_hr_lims[1]=oSpeeds[1]; //, midPhi-hrWidth, midPhi+hrWidth, midThe-hrWidth-spinWidth, midThe+hrWidth+spinWidth };
o_lr_lims[0]=minSpeedsO[5]; o_lr_lims[1]=maxSpeedsO[5]; //, midPhi-lrWidth, midPhi+lrWidth, midThe-lrWidth-spinWidth, midThe+lrWidth+spinWidth };
}
// time * spin_duty * energy_duty * area_factor
double o_ans_hr = 12.0*oneHour *0.017 *7.0/8.0 *0.25 * mi.mcIntegrate(o_func, o_hr_lims, mcN);
double o_ans_lr = 12.0*oneHour *0.017 *1.0/8.0 *1.0 * mi.mcIntegrate(o_func, o_lr_lims, mcN);
//double he_ans_hr = 12.0*oneHour *0.017 *1.0/8.0 *1.0 * mi.mcIntegrate(he_func, he_hr_lims, mcN);
double he_ans_lr = 12.0*oneHour *0.017 *1.0/8.0 *1.0 * mi.mcIntegrate(he_func, he_lr_lims, mcN);
if (dir.equals("SPRING")) {
o_ans_hr*=oSpringEff;
o_ans_lr*=oSpringEff;
//he_ans_hr*=heSpringEff;
he_ans_lr*=heSpringEff;
}
else if (dir.equals("FALL")) {
o_ans_hr*=oFallEff;
o_ans_lr*=oFallEff;
//he_ans_hr*=heFallEff;
he_ans_lr*=heFallEff;
}
// double doy = (pos2*180.0/3.14)*365.0/360.0;
outF.write(pos2*180.0/3.14 + "\t" + pos3 + "\t" + o_ans_hr + "\t" + o_ans_lr +"\t" + he_ans_lr + "\n");
o("pos: " + pos2 +"\t"+ "the: " + pos3*180.0/3.14 + "\t" + o_ans_hr + "\t" + o_ans_lr + "\t" + he_ans_lr);
}
}
}
outF.closeWrite();
//double[] limits = {heSpeeds[0], heSpeeds[1], midPhi-hrWidth, midPhi+hrWidth, midThe-hrWidth-spinWidth, midThe+hrWidth+spinWidth};
// THIS TEST is moving the look angle with the Earth at the supposed proper position.
//double step = Math.abs((finalPos-initPos)/11.0);
/* initPos = 0.0;
finalPos = 2.0*Math.PI;
step = Math.abs((finalPos-initPos)/60.0);
for (double pos = initPos; pos<finalPos; pos+= step) {
// here's the now position
final HelioVector posVec = new HelioVector(HelioVector.SPHERICAL, 100*AU, 0.0*Math.PI, Math.PI/2.0);
midPhi = pos;
midThe = Math.PI/2.0;
double[] limits = { 30000.0, 300000.0, midPhi-hrWidth, midPhi+hrWidth, midThe-hrWidth-spinWidth, midThe+hrWidth+spinWidth };
o("doing pos: " + pos);
FunctionIII f3 = new FunctionIII() {
public double function3(double v, double p, double t) {
double tbr = ndH.dist(posVec, new HelioVector(HelioVector.SPHERICAL,v,p,t))*v*v*Math.sin(t); // extra v for flux
// that is the integrand of our v-space integration
return tbr;
}
};
outF.write(pos + "\t" + mi.mcIntegrate(f3, limits, 10000) + "\n");
}
outF.closeWrite();
*/
// 8 days, break to 12 hr
}
public static final void main(String[] args) {
IBEXLO il = new IBEXLO();
}
public static void o(String s) {
System.out.println(s);
}
}
| Java |
/**
*
*
*/
public abstract class Distribution {
} | Java |
import gov.noaa.pmel.sgt.swing.JPlotLayout;
import gov.noaa.pmel.sgt.swing.JClassTree;
import gov.noaa.pmel.sgt.swing.prop.GridAttributeDialog;
import gov.noaa.pmel.sgt.JPane;
import gov.noaa.pmel.sgt.GridAttribute;
import gov.noaa.pmel.sgt.ContourLevels;
import gov.noaa.pmel.sgt.CartesianRenderer;
import gov.noaa.pmel.sgt.CartesianGraph;
import gov.noaa.pmel.sgt.GridCartesianRenderer;
import gov.noaa.pmel.sgt.IndexedColorMap;
import gov.noaa.pmel.sgt.ColorMap;
import gov.noaa.pmel.sgt.LinearTransform;
import gov.noaa.pmel.sgt.dm.SGTData;
import gov.noaa.pmel.util.GeoDate;
import gov.noaa.pmel.util.TimeRange;
import gov.noaa.pmel.util.Range2D;
import gov.noaa.pmel.util.Dimension2D;
import gov.noaa.pmel.util.Rectangle2D;
import gov.noaa.pmel.util.Point2D;
import gov.noaa.pmel.util.IllegalTimeValue;
import gov.noaa.pmel.sgt.dm.SimpleGrid;
import gov.noaa.pmel.sgt.dm.*;
import gov.noaa.pmel.sgt.SGLabel;
import java.awt.event.*;
import java.awt.print.*;
import java.awt.image.*;
import net.jmge.gif.*;
import java.awt.*;
import javax.swing.*;
import java.io.*;
import javax.imageio.*;
/**
* Let's use this to take a look at 3D data with color...
*
* Put new code in makeGraph() routine
*
* Added to:
* @author Donald Denbo
* @version $Revision: 1.8 $, $Date: 2001/02/05 23:28:46 $
* @since 2.0
*
* Lukas Saul summer 2002
*/
public class JColorGraph extends PrintableDialog implements ActionListener{
public JPlotLayout rpl_;
public JPane gridKeyPane;
private GridAttribute gridAttr_;
JButton edit_;
JButton space_ = null;
JButton tree_;
JButton print_;
JButton save_;
JButton color_;
JPanel main;
Range2D datar;
ContourLevels clevels;
ColorMap cmap;
SGTData newData;
// defaults
private String unitString = "Diff. EFlux (1/cm^2/s/sr)";
private String label1 = "SOHO CTOF HE+";
private String label2 = "1996";
public double[] xValues;
public double[] yValues;
public double[] zValues;
public float xMax, xMin, yMax, yMin, zMax, zMin;
public float cMin, cMax, cDelta;
public boolean b_color;
public JColorGraph() {
b_color = true;
}
public JColorGraph(double[] x, double[] y, double[] z) {
this(x,y,z,true);
}
public JColorGraph(double[] x, double[] y, double[] z, boolean b) {
b_color = b;
xValues=x;
yValues=y;
zValues=z;
// assume here we are going to have input the data already
xMax = (float)xValues[0]; xMin = (float)xValues[0];
yMax = (float)yValues[0]; yMin = (float)yValues[0];
zMax = (float)zValues[0]; zMin = (float)zValues[0];
o("xMin: " + xMin);
for (int i=0; i<xValues.length; i++) {
if (xValues[i]<xMin) xMin = (float)xValues[i];
if (xValues[i]>xMax) xMax = (float)xValues[i];
}
for (int i=0; i<yValues.length; i++) {
if (yValues[i]<yMin) yMin = (float)yValues[i];
if (yValues[i]>yMax) yMax = (float)yValues[i];
}
for (int i=0; i<zValues.length; i++) {
if (zValues[i]<zMin) zMin = (float)zValues[i];
if (zValues[i]>zMax) zMax = (float)zValues[i];
}
o("xmin: " + xMin);
o("xmax: " + xMax);
cMin = zMin; cMax = zMax; cDelta = (zMax-zMin)/6;
datar = new Range2D(zMin, zMax, cDelta);
clevels = ContourLevels.getDefault(datar);
gridAttr_ = new GridAttribute(clevels);
if (b_color == true) cmap = createColorMap(datar);
else cmap = createMonochromeMap(datar);
gridAttr_.setColorMap(cmap);
gridAttr_.setStyle(GridAttribute.RASTER_CONTOUR);
}
private JPanel makeButtonPanel(boolean mark) {
JPanel button = new JPanel();
button.setLayout(new FlowLayout());
tree_ = new JButton("Tree View");
//MyAction myAction = new MyAction();
tree_.addActionListener(this);
button.add(tree_);
edit_ = new JButton("Edit GridAttribute");
edit_.addActionListener(this);
button.add(edit_);
print_= new JButton("Print");
print_.addActionListener(this);
button.add(print_);
save_= new JButton("Save");
save_.addActionListener(this);
button.add(save_);
color_= new JButton("Colors...");
color_.addActionListener(this);
button.add(color_);
// Optionally leave the "mark" button out of the button panel
if(mark) {
space_ = new JButton("Add Mark");
space_.addActionListener(this);
button.add(space_);
}
return button;
}
/**
* more hacking here
*/
public void showIt() {
frame.setVisible(true);
}
private JFrame frame = null;
public void run() {
/*
* Create a new JFrame to contain the demo.
*/
frame = new JFrame("Grid Demo");
main = new JPanel();
main.setLayout(new BorderLayout());
frame.setSize(600,500);
frame.getContentPane().setLayout(new BorderLayout());
/*
* Listen for windowClosing events and dispose of JFrame
*/
frame.addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent event) {
JFrame fr = (JFrame)event.getSource();
fr.setVisible(false);
}
public void windowOpened(java.awt.event.WindowEvent event) {
rpl_.getKeyPane().draw();
}
});
/*
* Create button panel with "mark" button
*/
JPanel button = makeButtonPanel(true);
/*
* Create JPlotLayout and turn batching on. With batching on the
* plot will not be updated as components are modified or added to
* the plot tree.
*/
rpl_ = makeGraph();
rpl_.setBatch(true);
/*
* Layout the plot, key, and buttons.
*/
main.add(rpl_, BorderLayout.CENTER);
gridKeyPane = rpl_.getKeyPane();
gridKeyPane.setSize(new Dimension(600,100));
rpl_.setKeyLayerSizeP(new Dimension2D(6.0, 1.0));
rpl_.setKeyBoundsP(new Rectangle2D.Double(0.0, 1.0, 6.0, 1.0));
main.add(gridKeyPane, BorderLayout.SOUTH);
frame.getContentPane().add(main, BorderLayout.CENTER);
frame.getContentPane().add(button, BorderLayout.SOUTH);
frame.pack();
// frame.setVisible(true);
/*
* Turn batching off. JPlotLayout will redraw if it has been
* modified since batching was turned on.
*/
rpl_.setBatch(false);
}
void edit_actionPerformed(java.awt.event.ActionEvent e) {
/*
* Create a GridAttributeDialog and set the renderer.
*/
GridAttributeDialog gad = new GridAttributeDialog();
gad.setJPane(rpl_);
CartesianRenderer rend = ((CartesianGraph)rpl_.getFirstLayer().getGraph()).getRenderer();
gad.setGridCartesianRenderer((GridCartesianRenderer)rend);
// gad.setGridAttribute(gridAttr_);
gad.setVisible(true);
}
void tree_actionPerformed(java.awt.event.ActionEvent e) {
/*
* Create a JClassTree for the JPlotLayout objects
*/
JClassTree ct = new JClassTree();
ct.setModal(false);
ct.setJPane(rpl_);
ct.show();
}
/**
* This example uses a pre-created "Layout" for raster time
* series to simplify the construction of a plot. The
* JPlotLayout can plot a single grid with
* a ColorKey, time series with a LineKey, point collection with a
* PointCollectionKey, and general X-Y plots with a
* LineKey. JPlotLayout supports zooming, object selection, and
* object editing.
*/
private JPlotLayout makeGraph() {
o("inside makeGraph");
//SimpleGrid sg;
SimpleGrid sg;
//TestData td;
JPlotLayout rpl;
//Range2D xr = new Range2D(190.0f, 250.0f, 1.0f);
//Range2D yr = new Range2D(0.0f, 45.0f, 1.0f);
//td = new TestData(TestData.XY_GRID, xr, yr,
// TestData.SINE_RAMP, 12.0f, 30.f, 5.0f);
//newData = td.getSGTData();
sg = new SimpleGrid(zValues, xValues, yValues, "Title");
sg.setXMetaData(new SGTMetaData("Helio Longitude", "deg"));
sg.setYMetaData(new SGTMetaData("Ecliptic Latitude", "deg"));
sg.setZMetaData(new SGTMetaData(unitString, ""));
// newData.setKeyTitle(new SGLabel("a","test",new Point2D.Double(0.0,0.0)) );
// newData.setTimeArray(GeoDate[] tloc)
// newData.setTimeEdges(GeoDate[] edge);
sg.setTitle("tttest");
// newData.setXEdges(double[] edge);
// newData.setYEdges(double[] edge);
newData = sg;
//newData = sg.copy();
//Create the layout without a Logo image and with the
//ColorKey on a separate Pane object.
rpl = new JPlotLayout(true, false, false, "test layout", null, true);
rpl.setEditClasses(false);
//Create a GridAttribute for CONTOUR style.
//datar = new Range2D(zMin, zMax, (zMax-zMin)/6);
//clevels = ContourLevels.getDefault(datar);
//gridAttr_ = new GridAttribute(clevels);
//Create a ColorMap and change the style to RASTER_CONTOUR.
//ColorMap cmap = createColorMap(datar);
//gridAttr_.setColorMap(cmap);
//gridAttr_.setStyle(GridAttribute.RASTER_CONTOUR);
//Add the grid to the layout and give a label for
//the ColorKey.
//rpl.addData(newData, gridAttr_, "Diff. EFlux (1/cm^2/s/sr)");
rpl.addData(newData, gridAttr_, unitString);
// rpl.addData(newData);
/*
* Change the layout's three title lines.
*/
rpl.setTitles(label1,label2,"");
/*
* Resize the graph and place in the "Center" of the frame.
*/
rpl.setSize(new Dimension(600, 400));
/*
* Resize the key Pane, both the device size and the physical
* size. Set the size of the key in physical units and place
* the key pane at the "South" of the frame.
*/
rpl.setKeyLayerSizeP(new Dimension2D(6.0, 1.02));
rpl.setKeyBoundsP(new Rectangle2D.Double(0.01, 1.01, 5.98, 1.0));
return rpl;
}
private ColorMap createColorMap(Range2D datar) {
int[] red =
{ 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 7, 23, 39, 55, 71, 87,103,
119,135,151,167,183,199,215,231,
247,255,255,255,255,255,255,255,
255,255,255,255,255,255,255,255,
255,246,228,211,193,175,158,140};
int[] green =
{ 0, 0, 0, 0, 0, 0, 0, 0,
0, 11, 27, 43, 59, 75, 91,107,
123,139,155,171,187,203,219,235,
251,255,255,255,255,255,255,255,
255,255,255,255,255,255,255,255,
255,247,231,215,199,183,167,151,
135,119,103, 87, 71, 55, 39, 23,
7, 0, 0, 0, 0, 0, 0, 0};
int[] blue =
{ 255,143,159,175,191,207,223,239,
255,255,255,255,255,255,255,255,
255,255,255,255,255,255,255,255,
255,247,231,215,199,183,167,151,
135,119,103, 87, 71, 55, 39, 23,
7, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0};
IndexedColorMap cmap = new IndexedColorMap(red, green, blue);
cmap.setTransform(new LinearTransform(0.0, (double)red.length,
datar.start, datar.end));
return cmap;
}
/**
* here's a simpler map...
*/
private ColorMap createMonochromeMap(Range2D datar) {
int[] red = new int[200];
int[] green = new int [200];
int[] blue = new int [200];
red[0]=255; //red[1]=255;
green[0]=255; ///green[1]=255;
blue[0]=255; //lue[1]=255;
for (int i=1; i<red.length; i++) {
red[i]=230-i;
green[i]=230-i;
blue[i]=230-i;
}
IndexedColorMap cmap = new IndexedColorMap(red, green, blue);
cmap.setTransform(new LinearTransform(0.0, (double)red.length,
datar.start, datar.end));
return cmap;
}
public void actionPerformed(java.awt.event.ActionEvent event) {
Object source = event.getActionCommand();
Object obj = event.getSource();
if(obj == edit_)
edit_actionPerformed(event);
else if(obj == space_) {
System.out.println(" <<Mark>>");
}
else if(obj == tree_)
tree_actionPerformed(event);
else if(obj == save_) {
try {
BufferedImage ii = getImage();
String s = JOptionPane.showInputDialog("enter file name");
ImageIO.write(ii,"png",new File(s+".png"));
//File outputFile = new File("gifOutput_" +1+".gif");
//FileOutputStream fos = new FileOutputStream(outputFile);
//o("starting to write animated gif...");
////writeAnimatedGIF(ii,"CTOF He+", true, 3.0, fos);
//writeNormalGIF(ii, "MFI PSD", -1, false, fos);
//fos.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
else if (obj == print_) {
System.out.println("Trying to print...");
//setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintable(this);
if (job.printDialog()) {
try {
o("printing...");
job.print();
o("done...");
}
catch (Exception ex) {
ex.printStackTrace();
}
}
}
//setCursor(Cursor.getDefaultCursor());
else if (obj == color_) {
try {
System.out.println("changing color scale");
rpl_.setVisible(false);
rpl_.clear();
cMin = Float.parseFloat(
JOptionPane.showInputDialog(this,"Min. Color Value: ",cMin+""));
cMax = Float.parseFloat(
JOptionPane.showInputDialog(this,"Max. Color Value: ",cMax+""));
cDelta = Float.parseFloat(
JOptionPane.showInputDialog(this,"Delta. Color Value: ",cDelta+""));
rpl_.addData(newData, gridAttr_, "EFlux");
rpl_.setVisible(true);
}
catch (Exception e) {e.printStackTrace();}
}
}
private static void o(String s) {
System.out.println(s);
}
private void writeNormalGIF(Image img,
String annotation,
int transparent_index, // pass -1 for none
boolean interlaced,
OutputStream out) throws IOException {
Gif89Encoder gifenc = new Gif89Encoder(img);
gifenc.setComments(annotation);
gifenc.setTransparentIndex(transparent_index);
gifenc.getFrameAt(0).setInterlaced(interlaced);
gifenc.encode(out);
}
/**
* Use this to set the labels that will appear on the graph when you call "run()".
*
* This first is the big title, second subtitle, third units on color scale (z axis)
*/
public void setLabels(String l1, String l2, String l3) {
unitString = l3;
label1 = l1;
label2 = l2;
}
public BufferedImage getImage() {
//Image ii = rpl_.getIconImage();
//if (ii==null) {
// System.out.println ("lpl ain't got no image");
//}
//else {
//ImageIcon i = new ImageIcon(ii);
// return ii;
//}
try {
//show();
//setDefaultSizes();
//rpl.setAutoRange(false,false);
//rpl.setRange(new Domain(new Range2D(1.3, 4.0), new Range2D(0.0, 35000.0)));
rpl_.draw();
//show();
Robot r = new Robot();
Point p = main.getLocationOnScreen();
Dimension d = new Dimension(main.getSize());
//d.setSize( d.getWidth()+d.getWidth()/2,
// d.getHeight()+d.getHeight()/2 );
Rectangle rect = new Rectangle(p,d);
//BufferedImage bi = r.createScreenCapture(rect);
//ImageIcon i = new ImageIcon(r.createScreenCapture(rect));
return r.createScreenCapture(rect);
//setVisible(false);
//return i.getImage();
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
// some code from original below
/*
public static void main(String[] args) {
// Create the demo as an application
JColorGraph gd = new JColorGraph();
// Create a new JFrame to contain the demo.
//
JFrame frame = new JFrame("Grid Demo");
JPanel main = new JPanel();
main.setLayout(new BorderLayout());
frame.setSize(600,500);
frame.getContentPane().setLayout(new BorderLayout());
// Listen for windowClosing events and dispose of JFrame
frame.addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent event) {
JFrame fr = (JFrame)event.getSource();
fr.setVisible(false);
fr.dispose();
System.exit(0);
}
public void windowOpened(java.awt.event.WindowEvent event) {
rpl_.getKeyPane().draw();
}
});
//Create button panel with "mark" button
JPanel button = gd.makeButtonPanel(true);
// Create JPlotLayout and turn batching on. With batching on the
// plot will not be updated as components are modified or added to
// the plot tree.
rpl_ = gd.makeGraph();
rpl_.setBatch(true);
// Layout the plot, key, and buttons.
main.add(rpl_, BorderLayout.CENTER);
JPane gridKeyPane = rpl_.getKeyPane();
gridKeyPane.setSize(new Dimension(600,100));
rpl_.setKeyLayerSizeP(new Dimension2D(6.0, 1.0));
rpl_.setKeyBoundsP(new Rectangle2D.Double(0.0, 1.0, 6.0, 1.0));
main.add(gridKeyPane, BorderLayout.SOUTH);
frame.getContentPane().add(main, BorderLayout.CENTER);
frame.getContentPane().add(button, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
// Turn batching off. JPlotLayout will redraw if it has been
// modified since batching was turned on.
rpl_.setBatch(false);
}
*/
/* class MyAction implements java.awt.event.ActionListener {
public void actionPerformed(java.awt.event.ActionEvent event) {
Object source = event.getActionCommand();
Object obj = event.getSource();
if(obj == edit_)
edit_actionPerformed(event);
else if(obj == space_) {
System.out.println(" <<Mark>>");
}
else if(obj == tree_)
tree_actionPerformed(event);
else if (source == "Print") {
System.out.println("Trying to print...");
//setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintable(this);
if (job.printDialog()) {
try {
job.print();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
}
//setCursor(Cursor.getDefaultCursor());
}
}*/
/*
public void init() {
// Create the demo in the JApplet environment.
getContentPane().setLayout(new BorderLayout(0,0));
setBackground(java.awt.Color.white);
setSize(600,550);
JPanel main = new JPanel();
rpl_ = makeGraph();
JPanel button = makeButtonPanel(false);
rpl_.setBatch(true);
main.add(rpl_, BorderLayout.CENTER);
JPane gridKeyPane = rpl_.getKeyPane();
gridKeyPane.setSize(new Dimension(600,100));
main.add(gridKeyPane, BorderLayout.SOUTH);
getContentPane().add(main, "Center");
getContentPane().add(button, "South");
rpl_.setBatch(false);
}
*/ | Java |
import java.util.*;
//import cern.jet.math.Bessel;
//import com.imsl.math.Complex;
/**
* This calculates the velocity distribution of neutral atoms in the heliosphere.
* (according to the hot model or interstellar neutral dist. of choice)
*
* Also computes losses to ionization!
*
* Uses an input distribution class to determine LISM f.
*
* Lukas Saul - Warsaw 2000
*
* Winter 2001 or so - got rid of Wu & Judge code
* Last Modified - October 2002 - moved lism distribution to separate class
* reviving - April 2004
*/
public class NeutralDistribution {
public static double Ms = 1.98892 * Math.pow(10,30); // kg
public static double G = 6.673 * Math.pow(10,-11);
public static double AU = 1.49598* Math.pow(10,11); //meters
public static double NaN = Double.NaN;
private double mu, beta, Gmod;
// this gives our original neutral distribution in LISM
private InterstellarMedium im;
// these variables are for getHPInfinity
private double rdot, rdoti, thetadot, L, ptheta, pthetai, thc, vdif;
private double e, a, phi, shift;
private HelioVector hpr, hpv, hpn, hpox, hpoy, hpvi, hpdif, hpThetaHat, answer;
public boolean goingIn;
// other objects and primitives
private InterstellarMedium vlism;
private double test2;
private HelioVector tempHV, thetaHat;
private double testX, testY, arg;
/**
* Parameters:
* InterstellarMedium (starting point)
* radiationToGravityRatio (mu)
* SurvivalProbability (ionization rate calculatore)
*
*/
public NeutralDistribution(InterstellarMedium im, double radiationToGravityRatio, double beta0) {
mu = radiationToGravityRatio;
beta = beta0;
//sp = new SurvivalProbability(beta, mu);
vlism = im;
Gmod = G*(1-mu);
// initialize them now. We don't want to build java objects during calculations.
hpr = new HelioVector();
hpv = new HelioVector();
hpn = new HelioVector();
hpox = new HelioVector();
hpoy = new HelioVector();
hpvi = new HelioVector();
hpdif = new HelioVector();
hpThetaHat = new HelioVector();
answer = new HelioVector();
tempHV = new HelioVector();
thetaHat = new HelioVector();
goingIn=false;
}
/**
* Calculate the full distribution. This time perform all transformations
* explicitly, instead of reading them from a paper (WU and JUDGE).
* Coordinates are expected in Heliospheric coordinates (phi=0,theta=0 = direct upwind)
*
* Uses HelioVector.java to assist in geometry calculations
*
* we are being careful now not to create "new" variables (instances) to save time
* especially our vectors (HelioVectors)
*/
public double dist(double r, double theta, double phi, double vx, double vy, double vz) {
//o("Calling dist: "+r+" "+theta+" "+phi+" "+vx+" "+vy+" "+vz);
// first make some reference vectors to help simplify geometry
hpr.setCoords(HelioVector.SPHERICAL, r, theta, phi);
// take the reverse of the velocity to help keep it straight
hpv.setCoords(HelioVector.CARTESIAN, vx, vy, vz);
hpvi = getHPInfinity(hpr, hpv); // here's the hard part - this call also sets thetaDif
// the angle swept out by the particle from -inf to now
if (hpvi==null) return 0;
// then calculate the v0 - vinf
//hpdif.setCoords(hpInflow);
//HelioVector.difference(hpdif, hpvi);
//o("hpdif: "+hpdif);
// we need to multiply by the survival probability here...
// then do the gaussian with survival probability
double answer = vlism.heliumDist(hpvi.getX(),hpvi.getY(),hpvi.getZ());
//o(""+answer);
return answer;
}
/**
* Use this to compute the original velocity vector at infinity,
* given a velocity and position at a current time.
*
* // note velocity vector is reversed, represents origin to point at t=-infinity
*
* Use static heliovector methods to avoid the dreaded "new Object()"...
*
*/
private HelioVector getHPInfinity(HelioVector hpr, HelioVector hpv) {
double r = hpr.getR();
// - define orbital plane
// orbital plane is all vectors r with: r dot hpn = 0
// i.e. hpn = n^hat (normal vector to orbital plane)
hpn.setCoords(hpr);
HelioVector.crossProduct(hpn, hpv); // defines orbital plane
if (hpn.getR()==0) {return null;} // problems with div. by zero if we are at the origin
else HelioVector.normalize(hpn);
// are we coming into the sun or going away?
// we need to know this for the geometry;
goingIn = false;
if (hpr.dotProduct(hpv)<0) goingIn = true;
// We are going to set up coordinates in the orbital plane..
// unit vectors in this system are hpox and hpoy
// choose hpox so the particle is on the -x axis
// such that hpox*hpn=0 (dot product)
//hpox.setCoords(HelioVector.CARTESIAN, hpn.getY(), -hpn.getX(), 0);
hpox.setCoords(HelioVector.CARTESIAN, -hpr.getX()/r, -hpr.getY()/r, -hpr.getZ()/r);
HelioVector.normalize(hpox);
// this is the y axis in orbital plane
hpoy.setCoords(hpn);
HelioVector.crossProduct(hpoy, hpox); // hopy (Y) = hpn(Z) cross hpox (X)
o("hpoy size: " + hopy.getR());
HelioVector.normalize(hpoy);
o("hopy size: " + hopy.getR());
// we want the ++ quadrant to be where the particle came from, i.e.dtheta/dt positive
/*testY = hpr.dotProduct(hpoy);
testX = hpr.dotProduct(hpox);
if (goingIn && (testY<0)) {
HelioVector.invert(hpoy); //o("we have inverted hpoy 1...");
}
else if (!goingIn && (testY>0)) {
HelioVector.invert(hpoy); //o("we have inverted hpoy 2...");
}
if (goingIn && (testX<0)) {
HelioVector.invert(hpox); //o("we have inverted hpox 1...");
}
else if (!goingIn &&(testY>0)) {
HelioVector.invert(hpoy); //o("we have inverted hpox 2...");
}*/
// test so far
o("hpr: " + hpr.o());
o("hpv: " + hpv.o());
o("hpox: " + hpox.o());
o("hpoy: " + hpoy.o());
o("hpr dot hpox: " + hpr.dotProduct(hpox));
// ok, we have defined the orbital plane !
// now lets put the given coordinates into this plane
// they are: r, ptheta, rdot, thetadot
// Now we know ptheta, the orbital plane theta component
//ptheta = hpr.getAngle(hpox);
//if (!goingIn) ptheta = -ptheta + 2*Math.PI;
ptheta = Math.PI;
// we want rDot. This is the component of traj. parallel to our position
//
rdot = -hpv.dotProduct(hpr)/r;
// one way to get thetadot:
//
// thetadot = v_ cross r_ / r^2 ????
//
// using a temp variable to avoid "new Object()..."
//
//tempHV.setCoords(hpv);
//HelioVector.crossProduct(tempHV,hpr);
//thetadot = tempHV.getR()/r/r;
// yet a fucking nother way to get thetadot
//
// is from v = rdot rhat + r thetadot thetahat...
//
// thetadot thetahat = (v_ - rdot rhat) / r
//
// but we need the thetaHat to get the sign right
// thetaHat is just (0,-1) in our plane
// because we are sitting on the minus X axis
// thats how we chose hpox
//
thetaHat.setCoords(hpoy);
thetaHat.invert(); //we have thetahat
tempHV.setCoords(hpv);
HelioVector.product(tempHV,1.0/r);
HelioVector.difference(tempHV,hpr.product(rdot/r));
thetadot = tempHV.getR()/r;
// but what is the sign?
if (hpv.dotProduct(thetaHat),0) thetadot = -thetadot;
// test so far
o("Coords in orbital plane - r: " + hpr.getR());
o("ptheta: " + ptheta);
o("thetadot: " + thetadot);
o("rdot: " + rdot);
// NOW WE CAN DO THE KEPLERIAN MATH
// let's calculate the orbit now, in terms of eccentricity e
// ,semi-major axis a, and rdoti (total energy = 1/2(rdoti^2))
//
// the orbit equation is a conic section
// r(theta) = a(1-e^2) / [ 1 + e cos (theta - theta0) ]
//
// thanks Bernoulli..
L=r*r*thetadot; // ok - we know our angular momentum (/Mhe)
// NOW use the ENERGY conservation to compute
// rdoti - the velocity at infinity
//
//if ((test2=rdot*rdot - L*L/r/r + 2*Gmod*Ms/r) < 0) {
test2=hpv.dotProduct(hpv)-2*Gmod*Ms/r;
o("E= " + test2);
if (test2 < 0) {
o("discarding elipticals...");
// System.out.println("discarding elipticals");
return null;
}
o("E dif: " + ( (rdot*rdot + L*L/r/r - 2*Gmod*Ms/r) - test2 ));
rdoti=-Math.sqrt(test2);
o("rdoti: " + rdoti);
a = -Gmod*Ms/rdoti/rdoti;
// e = Math.sqrt(1+L*L*rdoti*rdoti/Gmod/Gmod/Ms/Ms);
e = Math.sqrt(1-L*L/a/Gmod/Ms);
if (e<=1) {
System.out.println("I thought we threw out ellipticals already??");
return null;
}
double maxPhi = Math.acos(1/e);
o("maxPhi: " + maxPhi);
o("e= " + e + " a= " + a);
// that pretty much defines the orbit, we need to find the angular shift
// to match with our coordinate system
arg = a*(1-e*e)/e/r - 1/e;
o("arg: " + arg);
if (arg<-1 | arg>1) {
o("problems here 9a8nv3");
//return null;
}
phi = Math.acos(arg)-maxPhi;
if (goingIn) { // we are in the +y half, ptheta<180
shift = ptheta-(Math.PI-phi);
pthetai = (Math.PI-maxPhi)+shift;
}
else {
shift = (Math.PI-phi)-(2*Math.PI-ptheta);
pthetai = (Math.PI-maxPhi)+shift;
}
o("phi: " + phi + " pthetai" + pthetai);
// now we know vinf in it's entirety. The vector, in original coordinates:
double vinfxo = rdoti*Math.cos(pthetai);
double vinfyo = rdoti*Math.sin(pthetai);
// put together our answer from the coords in the orbital plane
// and the orbital plane unit vectors
answer.setCoords(hpox);
HelioVector.product(answer,vinfxo);
//HelioVector.sum(answer,hpoy.product(vinfyo));
HelioVector.product(hpoy,vinfyo);
HelioVector.sum(answer,hpoy);
// that's a vector going away from the sun. Invert it
HelioVector.invert(answer);
return answer;
}
/**
* for testing only
*/
public static final void main(String[] args) {
/*parameters:
*/
Date dt3 = new Date();
NeutralDistribution nd = new NeutralDistribution(new GaussianVLISM(new HelioVector(),0.0,0.0),0.0,0.0);
Date dt4 = new Date();
o("constructor took: "+(dt4.getTime()-dt3.getTime()));
// test getHPInfinity
//HelioVector tttt = new HelioVector();
Date dt1 = new Date();
HelioVector r1 = new HelioVector(HelioVector.CARTESIAN, 0.01,AU, 0.01);
HelioVector v1 = new HelioVector(HelioVector.CARTESIAN, 0.01, 0.01, -50000);
o("Trying r = AUy, v = -50000x");
HelioVector tttt = nd.getHPInfinity(r1,v1);
o("goingIN: "+ nd.goingIn);
o(tttt+"");
double einit= 0.5*v1.dotProduct(v1) - Ms*nd.Gmod/Math.sqrt(r1.dotProduct(r1));
double efinal= 0.5*tttt.dotProduct(tttt);
o("energy difference = " + Math.abs(efinal-einit));
o("\n\n\n");
r1 = new HelioVector(HelioVector.CARTESIAN, AU,0.01,0.01);
v1 = new HelioVector(HelioVector.CARTESIAN, 0.01,-50000, 0.01);
o("Trying x axis, -50000y");
tttt = nd.getHPInfinity(r1,v1);
o("goingIN: "+ nd.goingIn);
o(tttt+"");
einit= 0.5*v1.dotProduct(v1) - Ms*nd.Gmod/Math.sqrt(r1.dotProduct(r1));
efinal= 0.5*tttt.dotProduct(tttt);
o("energy difference = " + Math.abs(efinal-einit));
o("\n\n\n");
r1 = new HelioVector(HelioVector.CARTESIAN, 0.01,0.01,AU);
v1 = new HelioVector(HelioVector.CARTESIAN, 0.01, 0.01, -50000);
o("Trying z axis, -50000z");
tttt = nd.getHPInfinity(r1,v1);
o("goingIN: "+ nd.goingIn);
o(tttt+"");
einit= 0.5*v1.dotProduct(v1) - Ms*nd.Gmod/Math.sqrt(r1.dotProduct(r1));
efinal= 0.5*tttt.dotProduct(tttt);
o("energy difference = " + Math.abs(efinal-einit));
o("\n\n\n");
r1 = new HelioVector(HelioVector.CARTESIAN, AU,0.01,0.01);
v1 = new HelioVector(HelioVector.CARTESIAN, 50000, 0.01, 0.01);
o("Trying x axis, 50000x");
tttt = nd.getHPInfinity(r1,v1);
o("goingIN: "+ nd.goingIn);
o(tttt+"");
einit= 0.5*v1.dotProduct(v1) - Ms*nd.Gmod/Math.sqrt(r1.dotProduct(r1));
efinal= 0.5*tttt.dotProduct(tttt);
o("energy difference = " + Math.abs(efinal-einit));
o("\n\n\n");
r1 = new HelioVector(HelioVector.CARTESIAN, 0.01,0.01,AU);
v1 = new HelioVector(HelioVector.CARTESIAN, 0.01, 0.01, 50000);
o("Trying z axis, 50000z");
tttt = nd.getHPInfinity(r1,v1);
o("goingIN: "+ nd.goingIn);
o(tttt+"");
einit= 0.5*v1.dotProduct(v1) - Ms*nd.Gmod/Math.sqrt(r1.dotProduct(r1));
efinal= 0.5*tttt.dotProduct(tttt);
o("energy difference = " + Math.abs(efinal-einit));
o("\n\n\n");
r1 = new HelioVector(HelioVector.CARTESIAN, 0.01,AU,0.01);
v1 = new HelioVector(HelioVector.CARTESIAN, 0.01, 50000, 0.01);
o("Trying y axis, 50000y");
tttt = nd.getHPInfinity(r1,v1);
o("goingIN: "+ nd.goingIn);
o(tttt+"");
einit= 0.5*v1.dotProduct(v1) - Ms*nd.Gmod/Math.sqrt(r1.dotProduct(r1));
efinal= 0.5*tttt.dotProduct(tttt);
o("energy difference = " + Math.abs(efinal-einit));
o("\n\n\n");
//OK, that's 6 easy tests to see whats happening.
// to be really sure lets give her 3 more interesting cases and
r1 = new HelioVector(HelioVector.CARTESIAN, 0.01,0.01,AU);
v1 = new HelioVector(HelioVector.CARTESIAN, 0.01, 0.01, 0.01);
o("Trying z axis, 0v");
tttt = nd.getHPInfinity(r1,v1);
o("goingIN: "+ nd.goingIn);
o(tttt+"");
einit= 0.5*v1.dotProduct(v1) - Ms*nd.Gmod/Math.sqrt(r1.dotProduct(r1));
efinal= 0.5*tttt.dotProduct(tttt);
o("energy difference = " + Math.abs(efinal-einit));
o("\n\n\n");
r1 = new HelioVector(HelioVector.CARTESIAN, 0.01,0.01,AU);
v1 = new HelioVector(HelioVector.CARTESIAN, 50000, 0.01, 0.01);
o("Trying z axis, 50000x");
tttt = nd.getHPInfinity(r1,v1);
o("goingIN: "+ nd.goingIn);
o(tttt+"");
einit= 0.5*v1.dotProduct(v1) - Ms*nd.Gmod/Math.sqrt(r1.dotProduct(r1));
efinal= 0.5*tttt.dotProduct(tttt);
o("energy difference = " + Math.abs(efinal-einit));
o("\n\n\n");
r1 = new HelioVector(HelioVector.CARTESIAN, 0.01,0.01,AU);
v1 = new HelioVector(HelioVector.CARTESIAN, -50000, 0.01, 0.01);
o("Trying z axis, -50000x");
tttt = nd.getHPInfinity(r1,v1);
o("goingIN: "+ nd.goingIn);
o(tttt+"");
einit= 0.5*v1.dotProduct(v1) - Ms*nd.Gmod/Math.sqrt(r1.dotProduct(r1));
efinal= 0.5*tttt.dotProduct(tttt);
o("energy difference = " + Math.abs(efinal-einit));
o("\n\n\n");
Date dt2 = new Date();
System.out.println("9 took: "+(dt2.getTime()-dt1.getTime()));
// hello
/*
Date d0= new Date();
o("r on z axis, v on -x");
double d = nd.dist(1*AU,0,.001,0,0,0);
o(d+"\n\n\n\n\nr on x axis, v on -x");
double e = nd.dist(100*AU,0,Math.PI/2, 0,0,.001);
double f = nd.dist(100*AU,0,.001, 0,0,.001);
Date d1 = new Date();
o(e+"\n"+f+"\n3 dists took: " + (d1.getTime()-d0.getTime()) );
double dd = nd.density(AU,0,0);
o(dd+"");
Date d2 = new Date();
o((d2.getTime()-d1.getTime()));
*/
}
private static void o(String s) {
System.out.println(s);
}
} | Java |
import java.util.Date;
public class LegendreTest {
public static void main(String[] args) {
Date d1 = new Date();
System.out.println(Legendre.compute(3,3));
Date d2 = new Date();
System.out.println(d2.getTime() - d1.getTime());
Legendre l = new Legendre();
file f = new file("deltadata6.txt");
f.initWrite(false);
//double cdels[] = new double[100];
//Arrays.fill(cdels,0.0);
for (double j=-1.0; j<1.0; j+=+0.04) {
double delt=0.0;
for (int i=0; i<50; i++) {
delt += (2*i+1)/2*l.p(i,j)*l.p(i,0.0);
}
//System.out.println("testing");
System.out.println(j+"\t"+delt);
f.write(j+"\t"+delt+"\n");
}
f.closeWrite();
System.exit(0);
}
}
| Java |
import java.util.StringTokenizer;
public class TwoDPlot {
public CurveFitter cf;
public TwoDPlot() {
file f = new file("sp_param_65_74_6_5.txt");
f.initRead();
double[] x = new double[30];
double[] y = new double[30];
double[] z = new double[900];
for (int i=0; i<x.length; i++) x[i]=Double.parseDouble(f.readLine());
for (int i=0; i<y.length; i++) y[i]=Double.parseDouble(f.readLine());
for (int i=0; i<z.length; i++) {
String ss = f.readLine();
System.out.println(ss);
z[i]=Double.parseDouble(ss);
//z[i]=Math.log(z[i]);
}
// modify z
//for (int i=0; i<z.length; i++) z[i]=z[i]-840000.0;
JColorGraph jcg = new JColorGraph(x,y,z);
String unitString = "log (sum square model error)";
jcg.setLabels("IBEX-LO","2010",unitString);
jcg.run();
jcg.showIt();
}
public static boolean contains(double[] set, double test) {
for (int i=0; i<set.length; i++) {
if (set[i]==test) return true;
}
return false;
}
public static void o(String s) {
System.out.println(s);
}
public static final void main(String[] args) {
TwoDPlot theMain = new TwoDPlot();
}
} | Java |
//import cern.jet.math.Bessel;
import java.lang.Math;
import java.util.Date;
public class YadavaIntegral {
public YadavaIntegral() {
MultipleIntegration mi = new MultipleIntegration();
double[] lims2 = new double[4];
lims2[0]=0.0;
lims2[1]=Math.PI;
lims2[2]=0.0;
lims2[3]=Math.PI;
FunctionII yadavaEnergyLoss = new FunctionII () {
double R = 2.8E-15;
public double function2(double b, double theta) {
return Math.sin(theta) * (1-R*Math.sin(theta)/b) / b / Math.exp(R*Math.sin(theta)/b);
}
};
double test2 = mi.integrate(yadavaEnergyLoss,lims2);
System.out.println(test2+"");
}
public static void main(String[] args) {
YadavaIntegral yi = new YadavaIntegral();
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.